branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>package com.connexity.demo.controller; import com.connexity.demo.model.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping(path = "/api") public class MessageController { private Map<String, Integer> visitCounter = new HashMap<>(); @RequestMapping(path = "/message") @ResponseBody public Message getMessage(@RequestParam(name = "name")String name) { Message message = new Message(); message.setMessage("Hello, " + name + "!"); message.setDate(LocalDate.now()); visitCounter.computeIfAbsent(name, n -> 0); visitCounter.compute(name, (key, value) -> value + 1); message.setVisits(visitCounter.get(name)); return message; } } <file_sep>package com.connexity.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Locale; @Controller public class ReactController { @Autowired protected ViewResolver viewResolver; private static final String reactTemplate = "react/index.html"; @RequestMapping(value = "/", method= RequestMethod.GET, produces="text/html") public void reactView(HttpServletRequest request, HttpServletResponse response) { renderReactHtml(request,response); } private void renderReactHtml(HttpServletRequest request, HttpServletResponse response) { try { View view = viewResolver.resolveViewName(reactTemplate, Locale.US); view.render(new HashMap<>(), request, response); } catch (Exception e) { throw new RuntimeException(e); } } } <file_sep>package com.connexity.demo.model; import java.time.LocalDate; public class Message { private String message; private LocalDate date; private Integer visits; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } public Integer getVisits() { return visits; } public void setVisits(Integer visits) { this.visits = visits; } } <file_sep>package com.connexity.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration(exclude={BatchAutoConfiguration.class }) @ComponentScan(basePackages={ "com.connexity.demo" // If you have a library that configures via spring annotations, // add it to this list }) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
cca5a84edce259e9020563e933e043427bd3a733
[ "Java" ]
4
Java
nmockovciak/cs130-skeleton
f7e7718caa86c69d087836d953cb5a8ec3eb9af3
02c1b868a8f0d7b46c091f00f0d2d1b4473af3a5
refs/heads/master
<repo_name>a815278055/vue<file_sep>/src/main/java/com/itheima/servlet/XxxController.java package com.itheima.servlet; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/user") public class XxxController { @RequestMapping("/test") public ModelAndView test(ModelAndView modelAndView){ modelAndView.addObject("str","你好,vue"); modelAndView.setViewName("hello.html"); return modelAndView; } }
b036dd36a359926f004dcc1e8a9f17277dcd3a5d
[ "Java" ]
1
Java
a815278055/vue
b8453132e646b0cb0f418193ae4dde41e6009c96
99608e8ac7556790456bd2bf88d85c9fc336d0fc
refs/heads/main
<repo_name>yuhsuan18/Question-Answering-System<file_sep>/main.py import io import random import string import warnings import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import warnings warnings.filterwarnings('ignore') import requests import json import re import time # Downloading and installing NLTK #pip install nltk # for downloading packages #nltk.download('popular', quiet=True) #nltk.download('punkt') #nltk.download('wordnet') import nltk from nltk.stem import WordNetLemmatizer # Collect keywords intent_dict = {'1':'weather','2':'food','3':'traffic','4':'greetings'} weather_dict = ['weather','sunny','windy','rainy','rain','snow','fogggy','forecast','cold','warm','cool','hot','temp','temperature'] food_dict = ['restaurant','food','breakfast','lunch','dinner','eat','brunch','meal','coffee','fika','cafe','wine','dine','hungry','starve','go','date','romantic','book','table','service'] transport_dict = ['bus','tram','transport','wait','Vagnhallen Majorna','Centralstationen','next','time'] GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey","hej", "hej hej hej") GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "what's up","hej", "hej hej hej"] # ### Functions for weather def getweather(city): request = "http://api.openweathermap.org/data/2.5/forecast?q=" + city + "&units=metric&cnt=40&appid=d910cdfca2b02ed3e3922ac6e61e1463" response = requests.get(request) def jprint(obj): text = json.dumps(obj,sort_keys=True,indent=4) with open("output.json","w") as outfile: outfile.write(text) jprint(response.json()) f = open ('output.json', "r") data = json.loads(f.read()) with open('forecast.txt','w') as fp: for line in data['list']: fp.write(line['dt_txt']) fp.write('\n') for w in line['main'].items(): fp.writelines(str(w)) fp.write('\n') for words in line['weather']: fp.writelines(str(words)) fp.write('\n') fp.write('\n') def datetoweather(date,time='12:00'): date_string = '2021' + '-' + date[0:2] + '-' + date[2:4] time_string = time + ':00' return tuple([date_string,time_string]) # e.g. (2021-03-08 ,15:00:00) def process_weather(user_response,responseidx): word_dict ={} with open('forecast.txt','r') as fp: for k in range(40): key = fp.readline() key = key.replace('\n','') key = tuple(key.split()) words_list = [] for i in range(10): line = fp.readline() line = line.replace('\n','') words_list.append(line) fp.readline() word_dict[key] = words_list response_list = user_response.lower().split() if key in word_dict.keys(): if 'highest' in response_list or 'max' in response_list: respon = word_dict[responseidx][7] respon = re.sub('[,\(\)\']','',respon) print("BOBO: ",respon + " deg. Celcius") elif 'lowest' in response_list or 'min' in response_list: respon = word_dict[responseidx][8] respon = re.sub('[,\(\)\']','',respon) print("BOBO: ",respon + " deg. Celcius") elif 'temperature' in response_list or 'temp' in response_list or 'hot' in response_list or 'cold' in response_list: respon = word_dict[responseidx][0] respon = re.sub('[,\(\)\']','',respon) print("BOBO: ",respon + " deg. Celcius") elif 'rain' in response_list: respon = word_dict[responseidx][2] respon = re.sub('[,\(\)\']','',respon) print("BOBO: ",respon + " %") # ### Functions for traffic def process_traffic(user_response): tram_list = [] with open('traffic.txt','r') as fp: for i in range(10): fp.readline() tram_no = fp.readline() tram_no = tram_no.replace('\n','') departure = fp.readline() departure = departure.replace('\n','') hour = departure.split()[1][5:7] minute = departure.split()[1][8:10] duration = fp.readline() duration = duration.replace('\n','') duration = duration.split()[2] tram_list.append((tram_no,hour,minute,duration)) fp.readline() # print(tram_list) t = time.localtime() current_time = time.strftime("%H:%M", t) current_hr = current_time[:2] current_minute = current_time[3:] for item in tram_list: count = 0 if current_hr > item[1]: continue elif current_hr < item[1]: count +=1 print("next tram/bus: ", item[0]) print("next departure time: ",item[1]+':'+item[2]) elif current_hr == item[1] and current_minute > item[2]: continue else: count +=1 print("next tram/bus: ", item[0]) print("next departure time: ",item[1]+':'+item[2]) if count == 0: print("sorry! No tram or bus") # ### General functions def process_intent(sentence): intent = -1 sentence = sentence.lower() translation = sentence.maketrans(string.punctuation,string.punctuation,string.punctuation) # remove punctuation sentence = sentence.translate(translation) for word in sentence.split(): if word in weather_dict: intent = 1 elif word in food_dict: intent = 2 elif word in transport_dict: intent = 3 elif word in GREETING_RESPONSES: intent = 4 return int(intent) #Reading in the corpus def read_corpus(intent): if intent == 1: f=open('forecast.txt','r',errors = 'ignore',encoding='utf-8') raw=f.read() raw = raw.lower()# converts to lowercase elif intent == 2: f=open('restaurant_eng.txt','r',errors = 'ignore',encoding='utf-8') raw=f.read() raw = raw.lower()# converts to lowercase elif intent == 3: f=open('traffic.txt','r',errors = 'ignore',encoding='utf-8') raw=f.read() raw = raw.lower()# converts to lowercase else: print(" Sorry!! services are not support right now") #Tokenisation sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences word_tokens = nltk.word_tokenize(raw)# converts to list of words return sent_tokens, word_tokens # Preprocessing #WordNet is a semantically-oriented dictionary of English included in NLTK def LemTokens(tokens): lemmer = nltk.stem.WordNetLemmatizer() return [lemmer.lemmatize(token) for token in tokens] def LemNormalize(text): remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation) return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict))) #Keyword matching def greeting(sentence): for word in sentence.split(): if word.lower() in GREETING_INPUTS: return random.choice(GREETING_RESPONSES) def response(user_response, intent): robo_response='' if (intent == 1): # weather city = input("BOBO: which city do you want to know? ") getweather(city) date = input("BOBO: which date? (MMDD) ") time = input("BOBO: what time? (06:00 / 12:00 / 18:00) ") responseidx = datetoweather(date,time) process_weather(user_response,responseidx) return robo_response elif (intent == 2): # food pass elif (intent == 3): # traffic process_traffic(user_response) return robo_response else: # greeting pass sent_tokens, word_tokens = read_corpus(intent) sent_tokens.append(user_response) TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english') tfidf = TfidfVec.fit_transform(sent_tokens) vals = cosine_similarity(tfidf[-1], tfidf) idx=vals.argsort()[0][-2] flat = vals.flatten() flat.sort() req_tfidf = flat[-2] if(req_tfidf==0): robo_response=robo_response+"I am sorry! I don't understand you. Can you give more details ?" return robo_response else: robo_response = robo_response+sent_tokens[idx] return robo_response def get_response(user_response): flag = True intent = process_intent(user_response) if intent == -1: print("We are sorry, it's not support now !") return if intent == 4: print("BOBO: "+ greeting(user_response)) else: print("BOBO: My name is Bobo. I will answer your queries. If you want to exit, type Bye!\n") print("BOBO: Welcome to ",intent_dict[str(intent)], "Section") while(flag==True): user_response=user_response.lower() if(user_response!='bye'): if(user_response =='thanks' or user_response =='thank you' or user_response == 'tack'): flag=False print("BOBO: You are welcome..") else: if intent != 4: print(response(user_response, intent)) else: flag=False print("BOBO: Bye! take care..") return user_response = input("BOBO: type bye to exit or type something to carry on\n ") if user_response =='bye': print("BOBO: see u next time !! ") break intent = process_intent(user_response) if intent == -1: print("BOBO: We are sorry, it's not support now !\n") return if intent == 4: print("BOBO: "+ greeting(user_response)) def main(): user_response = input("Hej hej, what do you want to know?\n") get_response(user_response) # In[ ]: if __name__ == "__main__": main() <file_sep>/README.md # Digital Assistant Implement a digital assistant for querying weather, transportation and food information. It will understand what the users are saying and direct them to get useful information. * weather: Data from OpenWeather (https://openweathermap.org/) * traffic: Data from Västtrafik (https://www.vasttrafik.se/en/travel-planning/travel-planner/) * food: restaurants recommendations from Göteborgs-Posten (https://www.gp.se/livsstil/tv%C3%A5-dagar/restauranger-i-g%C3%B6teborg-gp-listar-%C3%A5rets-39-recensioner-1.22061629)
036096884cdf3fc95f2b53357203dda9f0f2c405
[ "Markdown", "Python" ]
2
Python
yuhsuan18/Question-Answering-System
da958cf7acb26c9e7c018bff0801124a7385ab0a
094630d1798523f0285be51d6f48d8219ce21a66
refs/heads/master
<file_sep>(function ($) { //insert to JQ fn $.fn.interactiveMap = function (options) { //stałe var constant = {}; //wartości domyślne po inicjalizacji nadpisanie z options var defaults = { lang: { latitude: null, longitude: null, zoom: null, partners: null, poligons: null }, ajax: { loadPartners: null } }; defaults = $.extend(defaults, options); var vars = {}; var partnersFromDB = defaults.lang.partners; var events = { loadPartners: function (partners_array) { $.ajaxSetup({ beforeSend: function (xhr, type) { if (!type.crossDomain) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')); } }, }); $.ajax({ url: defaults.ajax.loadPartners, type: 'post', data: { partners: partners_array }, success: function (data) { switch (data.success) { case 'AJAX_OK': //Clear $('.partner-wrapper').empty(); $('.partners-container').removeClass('middle'); $('.map-container').removeClass('middle'); $('.partner-wrapper').hide(); if (data.no_results === true) { $('.partners-container').addClass('middle'); $('.map-container').addClass('middle'); } else { if ($('body').width() < 1250) { if ($(".partners-container").length) { $('html, body').animate({ scrollTop: $(".partners-container").offset().top - 100 }, 500); } } } //Paste results $('.partner-wrapper').html(data.html); $('.partner-wrapper').fadeIn(); break; default: console.log('default-action') } }, error: function (request, textStatus, errorThrown) { console.log('errror'); } }); } }; //funkcje używane w pluginie var functions = { /** * Init */ initializeMap: function () { var latitude = defaults.lang.latitude; var longitude = defaults.lang.longitude; var stylez = [ { featureType: "all", elementType: "all", stylers: [ { saturation: -100 } ] } ]; function initialize() { var myLatlng = new google.maps.LatLng(latitude, longitude); var map = new google.maps.Map(document.getElementById("map-canvas"), { zoom: defaults.lang.zoom, center: myLatlng, styles: [ { "featureType": "administrative.country", "elementType": "geometry.fill", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative.country", "elementType": "geometry.stroke", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative.country", "elementType": "labels.text", "stylers": [ { "visibility": "off" } ] } ] }); var canvas = $('#map-canvas').height(); if (canvas == 400) { map.setZoom(5); } //Obiekty partnerów które beda zaznaczone na mapie var partner_id = {}; var partner_localization = []; for (i = 0; i < partnersFromDB.length; i++) { partner_localization[i] = new google.maps.LatLng( Number(partnersFromDB[i].latitude), Number(partnersFromDB[i].longitude) ); partner_id[i] = new Array(); partner_id[i].push(partnersFromDB[i].id); } //Muszą być w tej samej kolejności co w area.json (tablica przechowywująca koordynaty województw) var provinces = []; provinces['0'] = 'dolnoslaskie'; provinces['1'] = 'kieleckie'; provinces['2'] = 'kujawsko_pomorskie'; provinces['3'] = 'lodzkie'; provinces['4'] = 'lubelskie'; provinces['5'] = 'lubuskie'; provinces['6'] = 'malopolskie'; provinces['7'] = 'mazowieckie'; provinces['8'] = 'opolskie'; provinces['9'] = 'podkarpackie'; provinces['10'] = 'podlaskie'; provinces['11'] = 'pomorskie'; provinces['12'] = 'slaskie'; provinces['13'] = 'warminsko_mazurskie'; provinces['14'] = 'wielkopolskie'; provinces['15'] = 'zachodnio_pomorskie'; var polygon = JSON.parse(defaults.lang.poligons); var polgyon_map = polygon.features; var i; var j; var provinces_with_polygons = []; var province_polygon = []; var polygon_arr = []; //funkcja która stwierdza czy polygon zawiera punkt !hard shit google.maps.Polygon.prototype.Contains = function (point) { var crossings = 0, path = this.getPath(); // for each edge for (var i = 0; i < path.getLength(); i++) { var a = path.getAt(i), j = i + 1; if (j >= path.getLength()) { j = 0; } var b = path.getAt(j); if (rayCrossesSegment(point, a, b)) { crossings++; } } // // odd number of crossings? return (crossings % 2 == 1); function rayCrossesSegment(point, a, b) { var px = point.lng(), py = point.lat(), ax = a.lng(), ay = a.lat(), bx = b.lng(), by = b.lat(); if (ay > by) { ax = b.lng(); ay = b.lat(); bx = a.lng(); by = a.lat(); } // alter longitude to cater for 180 degree crossings if (px < 0) { px += 360; } if (ax < 0) { ax += 360; } if (bx < 0) { bx += 360; } if (py == ay || py == by) py += 0.00000001; if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false; if (px < Math.min(ax, bx)) return true; var red = (ax != bx) ? ((by - ay) / (bx - ax)) : Infinity; var blue = (ax != px) ? ((py - ay) / (px - ax)) : Infinity; return (blue >= red); } } //Zliczanie propertiesów partnera function countProperties(obj) { var count = 0; for (var property in obj) { if (Object.prototype.hasOwnProperty.call(obj, property)) { count++; } } return count; } var markers = []; // Sets the map on all markers in the array. function setMapOnAll(map) { for (var i = 0; i < markers.length; i++) { markers[i].setMap(map); } markers = []; } // Removes the markers from the map, but keeps them in the array. function clearMarkers() { setMapOnAll(null); } var index_final = []; var final = []; //partner_elements - to są już rozmieszczeni na mapie partnerzy na danych województwach var partner_elements = {}; //Przelatujemy po każdym województwie i ustawiamy mu parametry provinces.forEach(function (province_name, province_index) { //Nadajemy każdemu województwowi granice - polygony provinces_with_polygons[province_name] = []; for (j = 0; j < polgyon_map[province_index].geometry.coordinates[0][0].length; j++) { provinces_with_polygons[province_name].push( new google.maps.LatLng( polgyon_map[province_index].geometry.coordinates[0][0][j][1], polgyon_map[province_index].geometry.coordinates[0][0][j][0] ) ); } //Ustalenie wyglądu wszystkich województw province_polygon[province_name] = new google.maps.Polygon({ paths: provinces_with_polygons[province_name], strokeColor: '#000', strokeOpacity: 0.8, strokeWeight: 1, fillColor: '#fff', fillOpacity: 0.6 }); //Wsadzanie wszystkich polygonów do jednej tablicy polygon_arr.push(province_polygon[province_name]); //Ustawienie mapy na każdym województwie province_polygon[province_name].setMap(map); //Ustalenie położenia danego partnera partner_elements[province_index] = new Array(); for (j = 0; j < countProperties(partner_id); j++) { if (polygon_arr[province_index].Contains(partner_localization[j])) { partner_elements[province_index].push(partner_localization[j]); partner_elements[province_index].push(partner_id[j]); } } //Dodanie koloru na hover-in google.maps.event.addListener(polygon_arr[province_index], 'mouseover', function (event) { this.setOptions( { fillOpacity: 0.6, fillColor: '#ccc'}, ); }); //Dodanie koloru na hover-out google.maps.event.addListener(polygon_arr[province_index], 'mouseout', function (event) { this.setOptions( { fillOpacity: 0.6, fillColor: '#fff'}, ); }); //Dodanie hovera tam gdzie jest jakiś partner var index_partner = Number(polygon_arr.indexOf(polygon_arr[province_index])); for (j = 0; j < partner_elements[index_partner].length; j++) { polygon_arr[province_index].setOptions( { fillOpacity: 0.6, fillColor: '#e8412c'}, ); google.maps.event.addListener(polygon_arr[province_index], 'mouseout', function (event) { this.setOptions( { fillOpacity: 0.6, fillColor: '#e8412c'}, ); }); google.maps.event.addListener(polygon_arr[province_index], 'mouseover', function (event) { this.setOptions( { fillOpacity: 0.8, fillColor: '#e8412c'}, ); }); } //Dodanie eventu na click danego województwa google.maps.event.addListener(province_polygon[province_name], 'click', function (event) { clearMarkers(); for (i = 0; i < partner_elements[province_index].length; i++) { //Aby dla każdego elementu ustalony był marker dla nieparzystych, if ((i % 2) == 0) { var partner_type = null; //Pobranie typu partnera partnersFromDB.forEach(function (partner, partner_index) { //Inkrementacja iteracji aby wyciągnąć id danego partnera if (partner.id == partner_elements[province_index][Number(i + 1)][0]) { partner_type = partner.partner_type; } }); //Ustawienie innych kolorow w zależności od typu partnera // TO DO przerobić jak będzie baza tych typów lub pobierać z langa if (partner_type == null || !partner_type) { var icon = { url: "/gfx/map_marker_blue.png", // url w razie wu scaledSize: new google.maps.Size(35, 35) // scaled size }; } else { var icon = { url: "/gfx/map_marker_blue.png", // w razie wu scaledSize: new google.maps.Size(50, 50) // scaled size }; } //ustawienie markera var marker = new google.maps.Marker({ position: partner_elements[province_index][i], animation: google.maps.Animation.DROP, map: map, icon: icon // label: { // fontFamily: 'Font Awesome 5 Free', // text: '<i class="fa fa-map-marker" aria-hidden="true"></i>' // } }); markers.push(marker); } else { index_final.push(partner_elements[province_index][i]); } } for (i = 0; i < countProperties(partnersFromDB); i++) { for (j = 0; j < index_final.length; j++) { if (partnersFromDB[i].id == index_final[j]) { final.push(partnersFromDB[i]); } } } //AJAX załadowanie danych obok mapki events.loadPartners(final); //Reset po kliknięciu innego województwa index_final = []; final = []; }); }); } ; if (typeof ($("#map-canvas").attr("id")) != "undefined") initialize(); }, init: function () { functions.initializeMap(); } }; //funkcje używane w pluginie var public_functions = {}; //elementy pobrane var $this = this; //PLUGIN functions.init(); //PLUGIN - END return public_functions; }; })(jQuery);<file_sep> (function ($) { //insert to JQ fn $.fn.add_users = function (options) { //stałe var constant = {}; //wartości domyślne po inicjalizacji nadpisanie z options var defaults = { lang: { users: null }, ajax: { deleteRow: null } }; defaults = $.extend(defaults, options); var vars = {}; var events = { deleteRow: function (row) { $.ajaxSetup({ beforeSend: function (xhr, type) { if (!type.crossDomain) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')); } }, }); $.ajax({ url: defaults.ajax.deleteRow, type: 'post', data: { row: row.attr('data-id') }, success: function (data) { switch (data.success) { case 'AJAX_OK': row.parents("tr").remove(); break; default: console.log('default-action') } }, error: function (request, textStatus, errorThrown) { console.log('errror'); } }); } }; //funkcje używane w pluginie var functions = { initMapUser: function () { var latitude = defaults.lang.latitude; var longitude = defaults.lang.longitude; var stylez = [ { featureType: "all", elementType: "all", stylers: [ { saturation: -100 } ] } ]; var myLatlng = new google.maps.LatLng(latitude, longitude); var map = new google.maps.Map(document.getElementById("map-canvas"), { zoom: defaults.lang.zoom, center: myLatlng, styles: [ { "featureType": "administrative.country", "elementType": "geometry.fill", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative.country", "elementType": "geometry.stroke", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative.country", "elementType": "labels.text", "stylers": [ { "visibility": "off" } ] } ] }); var canvas = $('#map-canvas').height(); if (canvas == 400) { map.setZoom(5); } google.maps.event.addListener(map, "click", function (e) { //lat and lng is available in e object let lat = e.latLng.lat(); let lng = e.latLng.lng(); $('input[name="lat"]').val(lat); $('input[name="lng"]').val(lng); }); }, init: function () { $('.add-form').on('click', function () { let length = $('.inputs').length; if (!length) { $('#form').append($html); functions.initMapUser(); } else { alert('You can only add/edit one user at once'); } }); $('.edit').on('click', function () { let length = $('.inputs').length; if (!length) { let lng = $('[name="record"]:checked').length if (lng <= 1) { $("table tbody").find('input[name="record"]').each(function () { if ($(this).is(":checked")) { let id = $(this).attr('data-id') $('#form').append($htmlEdit); $('#user').attr('action', '/editUser'); functions.initMapUser(); $.each(defaults.lang.users, function (key, value) { if (value.id == id) { $('input[name="city"]').val(value.city); $('input[name="desc"]').val(value.desc); $('input[name="lat"]').val(value.latitude); $('input[name="lng"]').val(value.longitude); $('input[name="name"]').val(value.name); $('input[name="surrname"]').val(value.surrname); $('input[name="phone"]').val(value.phone); $('input[name="street"]').val(value.street); } }); $('input[name="id"]').val($(this).attr('data-id')); return false;// break } }); } else { alert('You can only add/edit one user at once'); } } else { alert('You can only add/edit one user at once'); } }); $(".delete-row").click(function () { $("table tbody").find('input[name="record"]').each(function () { if ($(this).is(":checked")) { events.deleteRow($(this)); } }); }); } }; //funkcje używane w pluginie var public_functions = {}; //elementy pobrane var $this = this; //PLUGIN functions.init(); //PLUGIN - END return public_functions; }; })(jQuery);<file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; /** * Description of MainController * * @author pirog */ class InteractiveMap { private $google_key; public function __construct() { $this->google_key = '' ; } public function defaultAction(){ } public function loadPartners(Request $request){ $partners = ''; $partners = $request->partners; $view = \View::make('partners',['partners' => $partners])->render(); $html = (string)$view; return response()->json([ 'success'=>'AJAX_OK', 'html' => $html ]); } } ?><file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; /** * Description of MainController * * @author pirog */ class MainController { public function __construct() { } //put your code here private function save(Request $request) { $name = $request->input('name'); $surname = $request->input('surrname'); $desc = $request->input('desc'); $phone = $request->input('phone'); $city = $request->input('city'); $street = $request->input('street'); $lat = $request->input('lat'); $lng = $request->input('lng'); $data = array( 'name' => $name, 'surrname' => $surname, 'desc' => $desc, 'phone' => $phone, 'city' => $city, 'street' => $street, 'latitude' => $lat, 'longitude' => $lng ); \DB::table('users')->insert($data); return Redirect('/'); } private function update(Request $request) { $name = $request->input('name'); $surname = $request->input('surrname'); $desc = $request->input('desc'); $phone = $request->input('phone'); $city = $request->input('city'); $street = $request->input('street'); $lat = $request->input('lat'); $lng = $request->input('lng'); $id = $request->input('id'); var_dump($id); $data = array( 'name' => $name, 'surrname' => $surname, 'desc' => $desc, 'phone' => $phone, 'city' => $city, 'street' => $street, 'latitude' => $lat, 'longitude' => $lng ); \DB::table('users') ->where('id',$id) ->update($data); return Redirect('/'); } public function addUser(Request $request) { $rules = array( 'name' => 'required', 'surrname' => 'required', 'desc' => 'required', 'lat' => 'required', 'phone' => 'required', 'lng' => 'required', 'city' => 'required', 'street' => 'required' ); $validator = Validator::make($request->all(), $rules); if ($validator->fails()) { return Redirect('/') ->withErrors($validator); } else { return $this->save($request); } } public function editUser(Request $request) { $rules = array( 'name' => 'required', 'surrname' => 'required', 'desc' => 'required', 'lat' => 'required', 'phone' => 'required', 'lng' => 'required', 'city' => 'required', 'street' => 'required' ); $validator = Validator::make($request->all(), $rules); if ($validator->fails()) { return Redirect('/') ->withErrors($validator); } else { return $this->update($request); } } public function deleteRow(Request $request){ $id = ''; $id = (int)$request->row; //$user = new User; $user = User::find($id); if($user->delete()){ return response()->json([ 'success'=>'AJAX_OK', ]); } else{ return response()->json([ 'success'=>'ERROR', ]); } return response()->json([ 'success'=>'AJAX_OK', ]); } } ?><file_sep><?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 () { $users = DB::table('users')->get(); return view('users',['users' => $users ]); }); Route::get('/map', function(){ $users = DB::table('users')->get(); $partnersJSON = json_encode($users); $path = storage_path() . "/json/area.json"; // ie: /var/www/laravel/app/storage/json/filename.json $json = json_encode(file_get_contents($path), true); return view('interactive_map',[ 'users' => $partnersJSON, 'poligons' => $json ]); }); Route::post('/map/post', 'InteractiveMap@loadPartners'); Route::post('/addUser', 'MainController@addUser'); Route::post('/editUser', 'MainController@editUser'); Route::post('/delete' ,'MainController@deleteRow');
16cd2afc5eb0407c3891067e8c0b5b075f1c21a8
[ "JavaScript", "PHP" ]
5
JavaScript
pirogpiotr1/interactive-map
da893fd50867fc72c3401f072b6bd96dcf2b3b1c
dae27f637e7418e9517806118057384fb47cf0dd
refs/heads/master
<repo_name>santippe/genericJSDemo<file_sep>/sqlite.js //import express from 'express'; const sqlite3 = require('sqlite3'); //import db from 'sqlite'; //import Promise from 'bluebird'; const express = require('express'); const port = process.env.PORT || 3000; let app = express(); let db = new sqlite3.Database(':memory:'); db.exec("CREATE TABLE [Post]( ID INTEGER DEFAULT 0)"); console.log('Query started..'); let lastTimeout; app.get('/posts', async (req, res, next) => { clearTimeout(lastTimeout); try { //const posts = await db.all('SELECT * FROM Post LIMIT 10'); let smt=db.prepare("SELECT * FROM POST LIMIT 10 :p1"); smt.bind() res.send(posts); console.log('Query done'); } catch (err) { //next(err); } lastTimeout = exitFromServer(); }); app.listen(port,()=>{ lastTimeout = exitFromServer(); }); function exitFromServer(){ return setTimeout(()=>{ console.log('process terminated'); process.exit() },30000); }
9f1ecad76c3ea3cd697cd15ef659affd1452e134
[ "JavaScript" ]
1
JavaScript
santippe/genericJSDemo
29efcb7c307d1ca441057da0557c1aa41feb8ea9
500e0eebfc11a3cb03fcfe5dfcc4f2ec3065ccd8
refs/heads/master
<repo_name>NCTU-PCCA/NCTU_Fox<file_sep>/codebook/Graph/Flow/dinic.cpp (a) Bounded Maxflow Construction: 1. add two node ss, tt 2. add_edge(ss, tt, INF) 3. for each edge u -> v with capacity [l, r]: add_edge(u, tt, l) add_edge(ss, v, l) add_edge(u, v, r-l) 4. see (b), check if it is possible. 5. answer is maxflow(ss, tt) + maxflow(s, t) ------------------------------------------------------- (b) Bounded Possible Flow: 1. same construction method as (a) 2. run maxflow(ss, tt) 3. for every edge connected with ss or tt: rule: check if their rest flow is exactly 0 4. answer is possible if every edge do satisfy the rule; 5. otherwise, it is NOT possible. ------------------------------------------------------- (c) Bounded Minimum Flow: 1. same construction method as (a) 2. answer is maxflow(ss, tt) ------------------------------------------------------- (d) Bounded Minimum Cost Flow: * the concept is somewhat like bounded possible flow. 1. same construction method as (a) 2. answer is maxflow(ss, tt) + (∑ l * cost for every edge) ------------------------------------------------------- (e) Minimum Cut: 1. run maxflow(s, t) 2. run cut(s) 3. ss[i] = 1: node i is at the same side with s. ------------------------------------------------------- const long long INF = 1LL<<60; struct Dinic { //O(VVE), with minimum cut static const int MAXN = 5003; struct Edge{ int u, v; long long cap, rest; }; int n, m, s, t, d[MAXN], cur[MAXN]; vector<Edge> edges; vector<int> G[MAXN]; void init(){ edges.clear(); for ( int i = 0 ; i < n ; i++ ) G[i].clear(); n = 0; } // min cut start bool side[MAXN]; void cut(int u) { side[u] = 1; for ( int i : G[u] ) { if ( !side[ edges[i].v ] && edges[i].rest ) cut(edges[i].v); } } // min cut end int add_node(){ return n++; } void add_edge(int u, int v, long long cap){ edges.push_back( {u, v, cap, cap} ); edges.push_back( {v, u, 0, 0LL} ); m = edges.size(); G[u].push_back(m-2); G[v].push_back(m-1); } bool bfs(){ fill(d,d+n,-1); queue<int> que; que.push(s); d[s]=0; while (!que.empty()){ int u = que.front(); que.pop(); for (int ei : G[u]){ Edge &e = edges[ei]; if (d[e.v] < 0 && e.rest > 0){ d[e.v] = d[u] + 1; que.push(e.v); } } } return d[t] >= 0; } long long dfs(int u, long long a){ if ( u == t || a == 0 ) return a; long long flow = 0, f; for ( int &i=cur[u]; i < (int)G[u].size() ; i++ ) { Edge &e = edges[ G[u][i] ]; if ( d[u] + 1 != d[e.v] ) continue; f = dfs(e.v, min(a, e.rest) ); if ( f > 0 ) { e.rest -= f; edges[ G[u][i]^1 ].rest += f; flow += f; a -= f; if ( a == 0 )break; } } return flow; } long long maxflow(int _s, int _t){ s = _s, t = _t; long long flow = 0, mf; while ( bfs() ){ fill(cur,cur+n,0); while ( (mf = dfs(s, INF)) ) flow += mf; } return flow; } } dinic; <file_sep>/contest/PTC1803/pE.cpp #include<set> #include<vector> #include<algorithm> #include<cstdio> #include<cmath> using namespace std; struct event{ bool is_start; int ind; double pos; bool operator<(const event& rhs) const{ if (pos != rhs.pos) return pos < rhs.pos; return !is_start; } }; struct data{ double xl, yl, xr, yr; double lenPerx, yPerx; int c; } a[300005]; int n, r; double col[10004]; vector<event> ev; struct comp{ bool operator()(int lhs, int rhs)const{ if (a[lhs].xl < a[rhs].xl){ double tmp = a[lhs].yl + (a[rhs].xl - a[lhs].xl) * a[lhs].yPerx; return tmp > a[rhs].yl; } else { double tmp = a[rhs].yl + (a[lhs].xl - a[rhs].xl) * a[rhs].yPerx; return tmp < a[lhs].yl; } } }; set<int,comp> s; void solve(){ double last_pos; for (auto& x : ev){ if (s.size()){ int ind = *s.begin(); col[a[ind].c] += (x.pos - last_pos) * a[ind].lenPerx; last_pos = x.pos; } else last_pos = a[x.ind].xl; if (x.is_start) s.insert(x.ind); else s.erase(x.ind); } } int main (){ int t; scanf("%d", &t); while (t--){ scanf("%d%d", &n,&r); fill(col, col+10004, 0); ev.clear(); s.clear(); for (int i=0;i<n;i++){ scanf("%lf%lf%lf%lf%d", &a[i].xl, &a[i].yl, &a[i].xr, &a[i].yr, &a[i].c); if (a[i].xl == a[i].xr){ n--; i--; continue; } a[i].c --; if (a[i].xl > a[i].xr){ swap(a[i].xl, a[i].xr); swap(a[i].yl, a[i].yr); } double xx = a[i].xl - a[i].xr; double yy = a[i].yl - a[i].yr; a[i].lenPerx = sqrt(xx*xx + yy*yy) / abs(xx); a[i].yPerx = yy / xx; ev.push_back({true,i,a[i].xl}); ev.push_back({false,i,a[i].xr}); } sort(ev.begin(), ev.end()); solve(); sort(col, col+r); printf("%.2f %.2f %.2f\n", col[0], col[(r+1)/2-1], col[r-1]); } } <file_sep>/contest/ITSA2018/p7.cpp #include<bits/stdc++.h> using namespace std; char buf[100]; long long k; string s; vector<pair<int,string> > v; void init(){ s = ""; v.clear(); scanf("%s", buf); scanf("%lld", &k); k--; stringstream ss; ss << buf; for (int i=0;;i++){ int c = ss.get(); if (c < 0) break; if (c >= 'a' && c <= 'z'){ s.push_back(c); } else if (c == '*'){ s.push_back('.'); v.push_back({i,string("aeiou")}); } else { string tmp; getline(ss, tmp, ']'); sort(tmp.begin(),tmp.end()); s.push_back('.'); v.push_back({i,move(tmp)}); } } } void solve(){ reverse(v.begin(), v.end()); for (auto & x : v){ long long m = x.second.size(); s[x.first] = x.second[k%m]; k /= m; } if (k) cout << "*\n"; else cout << s << '\n'; } int main (){ cin.tie(0); int T; cin >> T; for (int ncase=1; ncase<=T; ncase++){ init(); solve(); } } <file_sep>/codebook/String/PalindromicTree.cpp // remember init() !!! // remember make_fail() !!! // insert s need 1 base !!! // notice MLE const int sigma = 62; const int MAXC = 1000006; inline int idx(char c){ if ('a'<= c && c <= 'z')return c-'a'; if ('A'<= c && c <= 'Z')return c-'A'+26; if ('0'<= c && c <= '9')return c-'0'+52; } struct PalindromicTree{ struct Node{ Node *next[sigma], *fail; int len, cnt; // for dp Node(){ memset(next,0,sizeof(next)); fail=0; len = cnt = 0; } } buf[MAXC], *bufp, *even, *odd; void init(){ bufp = buf; even = new (bufp++) Node(); odd = new (bufp++) Node(); even->fail = odd; odd->len = -1; } void insert(char *s){ Node* ptr = even; for (int i=1; s[i]; i++){ ptr = extend(ptr,s+i); } } Node* extend(Node *o, char *ptr){ int c = idx(*ptr); while ( *ptr != *(ptr-1-o->len) )o=o->fail; Node *&np = o->next[c]; if (!np){ np = new (bufp++) Node(); np->len = o->len+2; Node *f = o->fail; if (f){ while ( *ptr != *(ptr-1-f->len) )f=f->fail; np->fail = f->next[c]; } else { np->fail = even; } np->cnt = np->fail->cnt; } np->cnt++; return np; } } PAM; <file_sep>/contest/PTC1803/pD.cpp #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int dp[1010][1010][3]; char a[1010]; char b[1010]; int alen,blen; // 0 first is empty // 1 second is empty // 2 using both void init(){ fill((int*)dp,(int*)dp+1010*1010*3,0); scanf("%s%s",a,b); alen=strlen(a); blen=strlen(b); } int match(int i,int j){ if(a[i]==b[j])return 2; return -3; } void solve(){ dp[0][0][2]=match(0,0); for(int i = 1 ; i < alen ; i ++){ dp[i][0][2]=match(i,0); } for(int i = 1 ; i < blen ; i ++){ dp[0][i][2]=match(0,i); } for(int i = 1 ; i < alen ; i ++){ for(int j = 1 ; j < blen ; j ++){ dp[i][j][2]=dp[i-1][j-1][2]+match(i,j); dp[i][j][2]=max(dp[i][j-1][0]+match(i,j),dp[i][j][2]); dp[i][j][2]=max(dp[i-1][j][1]+match(i,j),dp[i][j][2]); dp[i][j][0]=dp[i-1][j-1][2]-3; dp[i][j][0]=max(dp[i][j-1][0]-1,dp[i][j][0]); dp[i][j][0]=max(dp[i-1][j][1]-3,dp[i][j][0]); dp[i][j][1]=dp[i-1][j-1][2]-3; dp[i][j][1]=max(dp[i][j-1][0]-3,dp[i][j][1]); dp[i][j][1]=max(dp[i-1][j][1]-1,dp[i][j][1]); } } } int main (){ int T; scanf("%d",&T); while(T--){ init(); solve(); int ans=0; for(int i = 0 ; i < alen ; i ++){ ans=max(dp[i][blen-1][0],ans); ans=max(dp[i][blen-1][2],ans); } for(int i = 0 ; i < blen ; i ++){ ans=max(dp[alen-1][i][1],ans); ans=max(dp[alen-1][i][2],ans); } printf("%d\n",ans); } } <file_sep>/codebook/Graph/LCA.cpp //lv紀錄深度 //father[多少冪次][誰] //已經建好每個人的父親是誰 (father[0][i]已經建好) //已經建好深度 (lv[i]已經建好) void makePP(){ for(int i = 1; i < 20; i++){ for(int j = 2; j <= n; j++){ father[i][j]=father[i-1][ father[i-1][j] ]; } } } int find(int a, int b){ if(lv[a] < lv[b]) swap(a,b); int need = lv[a] - lv[b]; for(int i = 0; need!=0; i++){ if(need&1) a=father[i][a]; need >>= 1; } for(int i = 19 ;i >= 0 ;i--){ if(father[i][a] != father[i][b]){ a=father[i][a]; b=father[i][b]; } } return a!=b?father[0][a] : a; } <file_sep>/codebook/Graph/Min_mean_cycle.cpp // from BCW /* minimum mean cycle */ const int MAXE = 1805; const int MAXN = 35; const double inf = 1029384756; const double eps = 1e-6; struct Edge { int v,u; double c; }; int n,m,prv[MAXN][MAXN], prve[MAXN][MAXN], vst[MAXN]; Edge e[MAXE]; vector<int> edgeID, cycle, rho; double d[MAXN][MAXN]; inline void bellman_ford() { for(int i=0; i<n; i++) d[0][i]=0; for(int i=0; i<n; i++) { fill(d[i+1], d[i+1]+n, inf); for(int j=0; j<m; j++) { int v = e[j].v, u = e[j].u; if(d[i][v]<inf && d[i+1][u]>d[i][v]+e[j].c) { d[i+1][u] = d[i][v]+e[j].c; prv[i+1][u] = v; prve[i+1][u] = j; } } } } double karp_mmc() { // returns inf if no cycle, mmc otherwise double mmc=inf; int st = -1; bellman_ford(); for(int i=0; i<n; i++) { double avg=-inf; for(int k=0; k<n; k++) { if(d[n][i]<inf-eps) avg=max(avg,(d[n][i]-d[k][i])/(n-k)); else avg=max(avg,inf); } if (avg < mmc) tie(mmc, st) = tie(avg, i); } for(int i=0; i<n; i++) vst[i] = 0; edgeID.clear(); cycle.clear(); rho.clear(); for (int i=n; !vst[st]; st=prv[i--][st]) { vst[st]++; edgeID.PB(prve[i][st]); rho.PB(st); } while (vst[st] != 2) { int v = rho.back(); rho.pop_back(); cycle.PB(v); vst[v]++; } reverse(ALL(edgeID)); edgeID.resize(SZ(cycle)); return mmc; }<file_sep>/contest/PTC1804/pB.cpp #include <bits/stdc++.h> using namespace std; const int MAXM = 6003; int n, m; int E[MAXM][3], d[MAXM]; bool relax(){ bool re=0; for (int i=0; i<n+m; i++){ int u = E[i][0]; int v = E[i][1]; int w = E[i][2]; if (d[u] > d[v]+w ){ d[u] = d[v] + w; re=1; } } return re; } int main(){ int T; cin >> T; while (T--){ scanf("%d %d", &n, &m); for (int i=0; i<m; i++){ int u, v, w; scanf("%d %d %d", &u, &v, &w); E[i][0]=u; E[i][1]=v; E[i][2]=w; } for (int i=0; i<MAXM; i++) d[i]=1<<29; d[0]=0; for (int i=1; i<=n; i++){ E[i-1+m][0] = 0; E[i-1+m][1] = i; E[i-1+m][2] = 0; } for (int i=0; i<=n; i++){ relax(); } if ( relax() ) puts("No"); else puts("Yes"); } } <file_sep>/contest/PTC1804/pA.cpp #include <bits/stdc++.h> using namespace std; int gcd(int a, int b){ if (b==0)return a; return gcd(b,a%b); } struct vec{ long long x,y; vec operator-(const vec& r)const{ return {x-r.x,y-r.y}; } bool operator<(const vec& r)const{ if(x!=r.x)return x<r.x; return y<r.y; } }; vec vecgcdx(vec a, vec b){ if(a.x<b.x)swap(a,b); if(b.x==0)return b; auto d = a.x/b.x; b.x*=d; b.y*=d; a = a -b; return a; } vec vecgcdy(vec a, vec b){ if(a.y<0){ a.x*=-1; a.y*=-1; } if(b.y<0){ b.x*=-1; b.y*=-1; } if(a.y<b.y)swap(a,b); if(b.y==0)return b; auto d = a.y/b.y; b.x*=d; b.y*=d; a = a -b; if(a.x<0){ a.x*=-1; a.y*=-1; } return a; } set<vec> s; vector<vec> v; double dis(vec x){ return sqrt(x.x*x.x+x.y*x.y); } void grob(){ queue<pair<int,int>> q; for(int i = 0 ; i < (int)v.size() ; i ++){ for(int j = i+1 ; j < (int)v.size() ; j ++){ q.push({i,j}); } } while(q.size()){ auto now = q.front(); q.pop(); int i = now.first; int j = now.second; if(v[i].x!=0||v[j].x!=0){ auto tmp = vecgcdx(v[i],v[j]); if(s.count(tmp)==0&&dis(tmp)<dis(v[i])&&dis(tmp)<dis(v[j])){ s.insert(tmp); for(int ii = 0 ; ii < (int)v.size() ; ii ++){ q.push({ii,(int)v.size()}); } v.push_back(tmp); } } if(v[i].y!=0||v[j].y!=0){ auto tmp = vecgcdy(v[i],v[j]); if(s.count(tmp)==0&&dis(tmp)<dis(v[i])&&dis(tmp)<dis(v[j])){ s.insert(tmp); for(int ii = 0 ; ii < (int)v.size() ; ii ++){ q.push({ii,(int)v.size()}); } v.push_back(tmp); } } } } int main(){ int T; cin >> T; while (T--){ s.clear(); v.clear(); long long x,y; scanf("%lld%lld",&x,&y); if(x<0){x*=-1;y*=-1;} v.push_back({x,y}); s.insert({x,y}); scanf("%lld%lld",&x,&y); if(x<0){x*=-1;y*=-1;} v.push_back({x,y}); s.insert({x,y}); grob(); double ans = sqrt(double(x*x+y*y)); for(const auto ve:v){ if(ve.x==0&&ve.y==0)continue; ans= min(ans,sqrt(double(ve.x*ve.x+ve.y*ve.y))); } printf("%.2f\n",ans); } } <file_sep>/contest/WorldFinals2019/43WorldFinalsWorkstation-Team63/Desktop/AC/H.cpp #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; const int MAXN = 500005; const int LG = 20; int n, K; int par[MAXN][LG]; bool on_cyc[MAXN]; int cycl[MAXN], cycid[MAXN], cyczo[MAXN]; int din[MAXN]; vector<int> G[MAXN]; void init(){ cin >> n >> K; for (int i=1; i<=n; i++){ int v; cin >> v; par[i][0] = v; din[v]++; G[v].push_back(i); } for (int h=1; h<LG; h++){ for (int i=1; i<=n; i++){ par[i][h] = par[ par[i][h-1] ][h-1]; } } } void find_trees(){ fill(on_cyc+1, on_cyc+1+n, 1); queue<int> que; for (int i=1; i<=n; i++) if ( din[i]==0 ){ que.push(i); } while (que.size()){ int u = que.front(); que.pop(); on_cyc[u] = 0; int v = par[u][0]; din[v]--; if ( din[v]==0 ) que.push(v); } } void build_cycl(){ fill( cycl+1, cycl+1+n, -1); fill( cycid+1, cycid+1+n, -1); for (int i=1; i<=n; i++){ int w = par[i][19]; if ( cycl[w]!=-1 ) continue; int len = 1; int v = par[w][0]; int it = 0; cycid[w] = it++; cyczo[w] = w; while ( v!=w ) { cycid[v] = it++; cyczo[v] = w; len++; v = par[v][0]; } cycl[w] = len; v = par[w][0]; while( v!=w ){ cycl[v] = len; v = par[v][0]; } } } int subS[MAXN]; void solve(){ for (int pi=1; pi<=n; pi++){ int k = K; int w = pi; if ( !on_cyc[w] ){ subS[w]++; for (int i=LG-1; i>=0; i--){ if ( on_cyc[ par[w][i] ] ) continue; if ( (1<<i) > k ) continue; k -= (1<<i); w = par[w][i]; } if ( k==0 && !on_cyc[ par[w][0] ] ){ subS[ par[w][0] ]--; } if ( k>0 ){ k--; w = par[w][0]; } } if ( !on_cyc[w] ) continue; int cl = cycl[w]; int ci = cycid[w]; if ( k>=cl ) subS[ cyczo[w] ]++; else { if ( ci+k >= cl ){ // split subS[w]++; w = cyczo[w]; k -= cl - ci; } subS[w]++; k++; for (int i=LG-1; i>=0; i--){ if ( (1<<i) <= k ){ w = par[w][i]; k -= (1<<i); } } if ( cycid[w]!=0 ) subS[w]--; } } } bool vis[MAXN]; void dfs(int u){ if ( vis[u] ) return; vis[u] = 1; for (int v:G[u]){ dfs(v); subS[u] += subS[v]; } } void parsum(){ for (int i=1; i<=n; i++){ if (!on_cyc[i]) { dfs(i); } else { if ( cycid[i]==0 ){ int v = par[i][0]; int sum = subS[i]; while ( v!=i ){ sum += subS[v]; subS[v] = sum; v = par[v][0]; } } } } } int main(){ cin.tie(0); cin.sync_with_stdio(0); init(); find_trees(); build_cycl(); solve(); parsum(); for (int i=1; i<=n; i++){ cout << subS[i] << '\n'; } } <file_sep>/codebook/DataStructure/Treap_Lin.cpp #include <bits/stdc++.h> using namespace std; const int INF = 1<<30; int ran(){ static unsigned x = 20190223; return x = 0xdefaced*x+1; } struct Treap{ Treap *l,*r; int num,m,sz,tag,ra,ad; Treap(int a){ l=r=0; num=m=a; sz=1; tag=ad=0; ra = ran(); } }; int size(Treap *a){ return a ? a->sz : 0; } int min(Treap *a){ return a ? a->m+a->ad : INF; } void push(Treap *a){ if(!a) return; if(a->tag){ swap(a->l,a->r); if(a->l)a->l->tag ^= 1; if(a->r)a->r->tag ^= 1; a->tag=0; } if(a->l)a->l->ad += a->ad; if(a->r)a->r->ad += a->ad; a->num += a->ad; a->m += a->ad; a->ad = 0; } void pull(Treap *a){ if(!a) return; a->sz=1+size(a->l)+size(a->r); a->m = min({ a->num, min(a->l), min(a->r) }); } Treap* merge(Treap *a, Treap *b){ if(!a || !b) return a ? a : b; if(a->ra > b->ra){ push(a); a->r = merge(a->r,b); pull(a); return a; }else{ push(b); b->l = merge(a,b->l); pull(b); return b; } } void split (Treap *o, Treap *&a, Treap *&b, int k){ if(!k) a=0, b=o; else if(size(o)==k) a=o, b=0; else{ push(o); if(k <= size(o->l)){ b = o; split(o->l, a, b->l,k); pull(b); }else{ a = o; split(o->r, a->r, b, k-size(o->l)-1); pull(a); } } } int main(){ Treap *head=0, *ta, *tb, *tc, *td; int a, b, c, n; scanf("%d",&n); for(int i=0; i<n; i++){ int t; scanf("%d",&t); head = merge(head,new Treap(t)); } int Q; scanf("%d",&Q); char ss[50]; while(Q--){ scanf("%s",ss); if(strcmp(ss,"ADD")==0){ scanf("%d%d%d",&a,&b,&c); split(head,tb,tc,b); split(tb,ta,tb,a-1); tb -> ad += c; head = merge(ta, merge(tb, tc)); }else if(strcmp(ss,"REVERSE")==0){ scanf("%d%d",&a,&b); split(head,tb,tc,b); split(tb,ta,tb,a-1); tb -> tag ^= 1; head = merge(ta, merge(tb, tc)); }else if(strcmp(ss,"REVOLVE")==0){ scanf("%d%d%d",&a,&b,&c); split(head,tb,tc,b); split(tb,ta,tb,a-1); int szz = size(tb); c %= szz; split(tb,tb,td,szz-c); tb=merge(td,tb); head = merge(ta, merge(tb, tc)); }else if(strcmp(ss,"INSERT")==0){ scanf("%d%d",&a,&b); split(head,ta,tc,a); tb = new Treap(b); head = merge(ta, merge(tb, tc)); }else if(strcmp(ss,"DELETE")==0){ scanf("%d",&a); split(head,ta,tc,a-1); split(tc,tb,tc,1); delete tb; head = merge(ta,tc); }else if(strcmp(ss,"MIN")==0){ scanf("%d%d",&a,&b); split(head,tb,tc,b); split(tb,ta,tb,a-1); printf("%d\n",min(tb)); head = merge(ta, merge(tb, tc)); } } } <file_sep>/codebook/Math/NTT.cpp // Remember coefficient are mod P // {n, 2^n, p, a, root} Note: p = a*2^n+1 // {16, 65536, 65537, 1, 3} // {20, 1048576, 7340033, 7, 3} template < LL P, LL root, int MAXN > // (must be 2^k) struct NTT { static LL bigmod(LL a, LL b) { LL res = 1; for (LL bs = a; b; b >>= 1, bs = (bs * bs) % P) if (b & 1) res = (res * bs) % P; return res; } static LL inv(LL a, LL b) { if (a == 1) return 1; return (((LL)(a - inv(b % a, a)) * b + 1) / a) % b; } LL omega[MAXN + 1]; NTT() { omega[0] = 1; LL r = bigmod(root, (P - 1) / MAXN); for (int i = 1; i <= MAXN; i++) omega[i] = (omega[i - 1] * r) % P; } // n must be 2^k void tran(int n, LL a[], bool inv_ntt = false) { int basic = MAXN / n, theta = basic; for (int m = n; m >= 2; m >>= 1) { int mh = m >> 1; for (int i = 0; i < mh; i++) { LL w = omega[i * theta % MAXN]; for (int j = i; j < n; j += m) { int k = j + mh; LL x = a[j] - a[k]; if (x < 0) x += P; a[j] += a[k]; if (a[j] > P) a[j] -= P; a[k] = (w * x) % P; } } theta = (theta * 2) % MAXN; } int i = 0; for (int j = 1; j < n - 1; j++) { for (int k = n >> 1; k > (i ^= k); k >>= 1); if (j < i) swap(a[i], a[j]); } if (inv_ntt) { LL ni = inv(n, P); reverse(a + 1, a + n); for (i = 0; i < n; i++) a[i] = (a[i] * ni) % P; } } }; const LL P=2013265921, root=31; const int MAXN=4194304; // MAXN 的因數也可以跑 NTT<P, root, MAXN> ntt; <file_sep>/contest/ITSA2018/p5.cpp #include<bits/stdc++.h> using namespace std; const int MAXN = 50; int n; long long a[MAXN]; void init(){ cin >> n; for (int i=0; i<n; i++){ cin >> a[i]; } long long ans=0; long long b = 1; for (int i=n-1; i>=0; i--){ ans += a[i] * b; b*=2LL; } cout << ans << '\n'; } void solve(){ } int main (){ int T; cin >> T; for (int ncase=1; ncase<=T; ncase++){ init(); solve(); } } <file_sep>/contest/ITSA2018/p6.cpp #include<bits/stdc++.h> using namespace std; const int MOD = 1e9+7; const int MAXN = 1e6+6; int d[MAXN], dp[MAXN]; int n, k; void build(){ d[0] = 1; int sum=1; for (int i=1; i<MAXN; i++){ d[i] = sum; sum = (sum+d[i])%MOD; } } void init(){ cin >> n >> k; dp[0] = 1; int sum = 1; for (int i=1; i<=n; i++){ dp[i] = sum; if (i>=k) dp[i] = (dp[i] + (long long)d[k]*dp[i-k]%MOD -dp[i-k])%MOD; if ( dp[i]<0 ) dp[i]+=MOD; sum = ( dp[i] + sum ) % MOD; } } void solve(){ cout << dp[n] << '\n'; } int main (){ build(); int T; cin >> T; for (int ncase=1; ncase<=T; ncase++){ init(); solve(); } } <file_sep>/codebook/Other/count_spanning_tree.cpp 新的方法介绍 下面我们介绍一种新的方法——Matrix-Tree定理(Kirchhoff矩阵-树定理)。 Matrix-Tree定理是解决生成树计数问题最有力的武器之一。它首先于1847年被Kirchhoff证明。在介绍定理之前,我们首先明确几个概念: 1、G的度数矩阵D[G]是一个n*n的矩阵,并且满足:当i≠j时,dij=0;当i=j时,dij等于vi的度数。 2、G的邻接矩阵A[G]也是一个n*n的矩阵, 并且满足:如果vi、vj之间有边直接相连,则aij=1,否则为0。 我们定义G的Kirchhoff矩阵(也称为拉普拉斯算子)C[G]为C[G]=D[G]-A[G], 则Matrix-Tree定理可以描述为:G的所有不同的生成树的个数等于其Kirchhoff矩阵C[G]任何一个n-1阶主子式的行列式的绝对值。 所谓n-1阶主子式,就是对于r(1≤r≤n),将C[G]的第r行、第r列同时去掉后得到的新矩阵,用Cr[G]表示。 生成树计数 算法步骤: 1、 构建拉普拉斯矩阵 Matrix[i][j] = degree(i) , i==j -1,i-j有边 0,其他情况 2、 去掉第r行,第r列(r任意) 3、 计算矩阵的行列式 /* *********************************************** MYID : <NAME> LANG : G++ PROG : Count_Spaning_Tree_From_Kuangbin ************************************************ */ #include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> using namespace std; const double eps = 1e-8; const int MAXN = 110; int sgn(double x) { if(fabs(x) < eps)return 0; if(x < 0)return -1; else return 1; } double b[MAXN][MAXN]; double det(double a[][MAXN],int n) { int i, j, k, sign = 0; double ret = 1; for(i = 0;i < n;i++) for(j = 0;j < n;j++) b[i][j] = a[i][j]; for(i = 0;i < n;i++) { if(sgn(b[i][i]) == 0) { for(j = i + 1; j < n;j++) if(sgn(b[j][i]) != 0) break; if(j == n)return 0; for(k = i;k < n;k++) swap(b[i][k],b[j][k]); sign++; } ret *= b[i][i]; for(k = i + 1;k < n;k++) b[i][k]/=b[i][i]; for(j = i+1;j < n;j++) for(k = i+1;k < n;k++) b[j][k] -= b[j][i]*b[i][k]; } if(sign & 1)ret = -ret; return ret; } double a[MAXN][MAXN]; int g[MAXN][MAXN]; int main() { int T; int n,m; int u,v; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); memset(g,0,sizeof(g)); while(m--) { scanf("%d%d",&u,&v); u--;v--; g[u][v] = g[v][u] = 1; } memset(a,0,sizeof(a)); for(int i = 0;i < n;i++) for(int j = 0;j < n;j++) if(i != j && g[i][j]) { a[i][i]++; a[i][j] = -1; } double ans = det(a,n-1); printf("%.0lf\n",ans); } return 0; }<file_sep>/contest/PTC1809/pE.cpp #include <bits/stdc++.h> using namespace std; #define pushS(x) sa[--bkt[s[x]]] = x #define pushL(x) sa[bkt[s[x]]++] = x #define induce_sort(v){\ fill_n(sa,n,0);\ copy_n(_bkt,A,bkt);\ for(i=n1-1;~i;--i)pushS(v[i]);\ copy_n(_bkt,A-1,bkt+1);\ for(i=0;i<n;++i)if(sa[i]&&!t[sa[i]-1])pushL(sa[i]-1);\ copy_n(_bkt,A,bkt);\ for(i=n-1;~i;--i)if(sa[i]&&t[sa[i]-1])pushS(sa[i]-1);\ } template<typename T> void sais(const T s,int n,int *sa,int *_bkt,int *p,bool *t,int A){ int *rnk=p+n,*s1=p+n/2,*bkt=_bkt+A; int n1=0,i,j,x=t[n-1]=1,y=rnk[0]=-1,cnt=-1; for(i=n-2;~i;--i)t[i]=(s[i]==s[i+1]?t[i+1]:s[i]<s[i+1]); for(i=1;i<n;++i)rnk[i]=t[i]&&!t[i-1]?(p[n1]=i,n1++):-1; fill_n(_bkt,A,0); for(i=0;i<n;++i)++_bkt[s[i]]; for(i=1;i<A;++i)_bkt[i]+=_bkt[i-1]; induce_sort(p); for(i=0;i<n;++i)if(~(x=rnk[sa[i]])) j=y<0||memcmp(s+p[x],s+p[y],(p[x+1]-p[x])*sizeof(s[0])) ,s1[y=x]=cnt+=j; if(cnt+1<n1)sais(s1,n1,sa,bkt,rnk,t+n,cnt+1); else for(i=0;i<n1;++i)sa[s1[i]]=i; for(i=0;i<n1;++i)s1[i]=p[sa[i]]; induce_sort(s1); } const int MAXN=200005,MAXA='z'+1; int sa[MAXN],bkt[MAXN+MAXA],p[MAXN*2]; bool t[MAXN*2]; const int MAX = MAXN; int ct[MAX], he[MAX], rk[MAX]; int tsa[MAX], tp[MAX][2]; void suffix_array(char *ip){ int len = strlen(ip); int alp = 256; memset(ct, 0, sizeof(ct)); for(int i=0;i<len;i++) ct[ip[i]+1]++; for(int i=1;i<alp;i++) ct[i]+=ct[i-1]; for(int i=0;i<len;i++) rk[i]=ct[ip[i]]; for(int i=1;i<len;i*=2){ for(int j=0;j<len;j++){ if(j+i>=len) tp[j][1]=0; else tp[j][1]=rk[j+i]+1; tp[j][0]=rk[j]; } memset(ct, 0, sizeof(ct)); for(int j=0;j<len;j++) ct[tp[j][1]+1]++; for(int j=1;j<len+2;j++) ct[j]+=ct[j-1]; for(int j=0;j<len;j++) tsa[ct[tp[j][1]]++]=j; memset(ct, 0, sizeof(ct)); for(int j=0;j<len;j++) ct[tp[j][0]+1]++; for(int j=1;j<len+1;j++) ct[j]+=ct[j-1]; for(int j=0;j<len;j++) sa[ct[tp[tsa[j]][0]]++]=tsa[j]; rk[sa[0]]=0; for(int j=1;j<len;j++){ if( tp[sa[j]][0] == tp[sa[j-1]][0] && tp[sa[j]][1] == tp[sa[j-1]][1] ) rk[sa[j]] = rk[sa[j-1]]; else rk[sa[j]] = j; } } for(int i=0,h=0;i<len;i++){ if(rk[i]==0) h=0; else{ int j=sa[rk[i]-1]; h=max(0,h-1); for(;ip[i+h]==ip[j+h];h++); } he[rk[i]]=h; } } char s[MAXN]; int main(){ int T; cin >> T; while (T--){ scanf("%s",s); suffix_array(s); int n = strlen(s); for (int i=0; i<n; i++) cout << sa[i] << ' '; cout << '\n'; sais(s,n,sa,bkt,p,t,MAXA); for (int i=0; i<n; i++) cout << sa[i] << ' '; cout << '\n'; } } <file_sep>/contest/WorldFinals2019/43WorldFinalsWorkstation-Team63/Desktop/AC/E.cpp #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; const int MAXN = 500005; int n, m; vector<int> G[MAXN]; int deg[MAXN]; void init(){ cin >> n >> m; for (int i=0; i<m; i++){ int u, v; cin >> u >> v; G[u].push_back(v); G[v].push_back(u); deg[u]++; deg[v]++; } } bool black[MAXN]; bool vis[MAXN]; vector<int> S; void dfs_comp(int u){ if ( vis[u] ) return; vis[u] = 1; S.push_back(u); for (int v:G[u]){ dfs_comp(v); } } vector< pair<int,int> > ans; void other(){ queue<int> que; for (int u:S) if ( deg[u]==1 ) { que.push(u); } while (que.size()){ int u = que.front(); que.pop(); black[u] = 1; for (int v:G[u]){ deg[v]--; if (deg[v]==1){ que.push(v); } } } for (int u:S){ for (int v:G[u]){ if ( black[u] && !black[v] ){ ans.push_back( {v,u} ); } } } } void isTree(){ for (int u:S){ if (deg[u]==1){ ans.push_back( {u,G[u][0]} ); } } } void solve(){ for (int i=1; i<=n; i++) if (!vis[i]) { S.clear(); dfs_comp(i); int sum = 0; for (int x:S) sum += deg[x]; if ( sum+2 == (int)S.size()*2 ){ // is tree isTree(); } else { // other case other(); } } } int main(){ cin.tie(0); cin.sync_with_stdio(0); init(); solve(); cout << ans.size() << '\n'; sort(ans.begin(),ans.end()); for (auto p: ans){ cout << p.first << ' ' << p.second << '\n'; } } <file_sep>/codebook/Math/pollardRho.cpp // from PEC // does not work when n is prime Int f(Int x, Int mod){ return add(mul(x, x, mod), 1, mod); } Int pollard_rho(Int n) { if ( !(n & 1) ) return 2; while (true) { Int y = 2, x = rand()%(n-1) + 1, res = 1; for ( int sz = 2 ; res == 1 ; sz *= 2 ) { for ( int i = 0 ; i < sz && res <= 1 ; i++) { x = f(x, n); res = __gcd(abs(x-y), n); } y = x; } if ( res != 0 && res != n ) return res; } }<file_sep>/contest/PTC1804/pD.cpp #include<bits/stdc++.h> using namespace std; int n; int x[100004], y[100004]; pair<int,int> p[100004]; int ox; int oy; int gcd(int a, int b){ if (b==0) return a; return gcd(b,a%b); } int ABS(int z){return max(z,-z);} void f(pair<int,int>& z){ z.first -= ox; z.second -= oy; if (!z.first && !z.second) return; int g = gcd( ABS(z.first), ABS(z.second) ); z.first /= g; z.second /= g; } bool check1(){ for (int i=0;i<n;i++) if (!p[i].first && !p[i].second) return true; return false; } int m=0; pair<int,int> q[100004]; typedef pair<int,int> pii; bool cmp(const pii &a, const pii &b){ return atan2(a.second,a.first) < atan2(b.second,b.first); } long long cross(const pii &a, const pii &b){ return (long long)a.first*b.second - (long long)a.second*b.first; } bool check2(){ m=0; for (int i=0; i<n; i++){ if ( p[i].first==0 && p[i].second==0 )continue; q[m++] = p[i]; } sort(q,q+m,cmp); if (m==1) return 1; for (int l=0, r=1, cnt=1; l<m; l++,cnt--){ while ( l!=r && q[r]==q[l] ) r=(r+1)%m, cnt++; while ( cross(q[l],q[r]) > 0 ) r=(r+1)%m, cnt++; if (2*cnt>n) return 0; } return 1; } int main (){ int T; scanf("%d", &T); while (T--){ scanf("%d", &n); for (int i=0;i<n;i++){ int xi, yi; scanf("%d%d", &xi,&yi); p[i] = {xi,yi}; x[i] = xi; y[i] = yi; } sort(x, x+n); sort(y, y+n); ox = x[n/2]; oy = y[n/2]; for_each (p, p+n, f); if (check1() && check2()) printf("%d %d\n", ox, oy); else printf("0\n"); } } <file_sep>/codebook/Other/DigitCounting.cpp int dfs(int pos, int state1, int state2 ....., bool limit, bool zero) { if ( pos == -1 ) return 是否符合條件; int &ret = dp[pos][state1][state2][....]; if ( ret != -1 && !limit ) return ret; int ans = 0; int upper = limit ? digit[pos] : 9; for ( int i = 0 ; i <= upper ; i++ ) { ans += dfs(pos - 1, new_state1, new_state2, limit & ( i == upper), ( i == 0) && zero); } if ( !limit ) ret = ans; return ans; } int solve(int n) { int it = 0; for ( ; n ; n /= 10 ) digit[it++] = n % 10; return dfs(it - 1, 0, 0, 1, 1); } <file_sep>/codebook/Math/LinearPrime.cpp const int MAXP = 100; //max prime vector<int> P; // primes void build_prime(){ static bitset<MAXP> ok; int np=0; for (int i=2; i<MAXP; i++){ if (ok[i]==0)P.push_back(i), np++; for (int j=0; j<np && i*P[j]<MAXP; j++){ ok[ i*P[j] ] = 1; if ( i%P[j]==0 )break; } } } <file_sep>/codebook/makefile codebook.pdf: codebook.tex content.tex xelatex codebook.tex xelatex codebook.tex rm codebook.aux codebook.log codebook.toc -f clean: rm codebook.pdf -f <file_sep>/codebook/Math/FFT.cpp // use llround() to avoid EPS typedef double Double; const Double PI = acos(-1); // STL complex may TLE typedef complex<Double> Complex; #define x real() #define y imag() template<typename Iter> // Complex* void BitReverse(Iter a, int n){ for (int i=1, j=0; i<n; i++){ for (int k = n>>1; k>(j^=k); k>>=1); if (i<j) swap(a[i],a[j]); } } template<typename Iter> // Complex* void FFT(Iter a, int n, int rev=1){ // rev = 1 or -1 assert( (n&(-n)) == n ); // n is power of 2 BitReverse(a,n); Iter A = a; for (int s=1; (1<<s)<=n; s++){ int m = (1<<s); Complex wm( cos(2*PI*rev/m), sin(2*PI*rev/m) ); for (int k=0; k<n; k+=m){ Complex w(1,0); for (int j=0; j<(m>>1); j++){ Complex t = w * A[k+j+(m>>1)]; Complex u = A[k+j]; A[k+j] = u+t; A[k+j+(m>>1)] = u-t; w = w*wm; } } } if (rev==-1){ for (int i=0; i<n; i++){ A[i] /= n; } } } <file_sep>/contest/PTC1808/pB.cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 52; const long long mod = 1e9+7; int n, m; char G[MAXN][MAXN]; int straw[MAXN][MAXN]; int tot; long long dp[2][MAXN][MAXN][MAXN*MAXN]; auto *now = dp[0]; auto *pre = dp[1]; void init(){ cin >> n >> m; for (int i=n; i>=1; i--){ scanf("%s", G[i]+1 ); } tot=0; for(int i = 1 ; i <= n ; i ++){ for(int j = 1 ; j <= m ; j ++){ straw[i][j]=straw[i][j-1]; if(G[i][j]=='#'){ straw[i][j]++; tot++; } } } } inline int a(int x,int y){ if(G[x][y]=='#')return 1; return 0; } void clear(long long (*ptr)[MAXN][MAXN*MAXN]){ for(int j = 0 ; j <= m ; j ++){ for(int k = 0 ; k <= tot ; k ++){ for(int l = 0 ; l <= n*m/2 ; l ++){ ptr[j][k][l]=0; } } } } void solve(){ clear(pre); clear(now); for(int j = 0 ; j <= m ; j ++){ now[j][straw[1][j]][j]=1; } for(int i = 2 ; i <= n ; i ++){ swap(pre,now); clear(now); for(int j = 0 ; j <= m ; j ++){ for(int k = straw[i][j] ; k <= tot ; k ++){ for(int l = j ; l <= n*m/2 ; l ++){ now[j][k][l]=pre[j][k-straw[i][j]][l-j]; if(l&&j){ now[j][k][l]+=now[j-1][k-a(i,j)][l-1]; now[j][k][l]%=mod; } } } } } long long ans=0; for(int j = 0 ; j <= m ; j ++){ ans+=now[j][tot][n*m/2]; ans%=mod; } printf("%lld\n",ans); } int main(){ int T; cin >> T; while (T--){ init(); if(tot%2==1)puts("0"); else { tot/=2; solve(); } } } <file_sep>/codebook/Graph/Flow/SW-mincut.cpp // all pair min cut // global min cut struct SW{ // O(V^3) static const int MXN = 514; int n,vst[MXN],del[MXN]; int edge[MXN][MXN],wei[MXN]; void init(int _n){ n = _n; FZ(edge); FZ(del); } void addEdge(int u, int v, int w){ edge[u][v] += w; edge[v][u] += w; } void search(int &s, int &t){ FZ(vst); FZ(wei); s = t = -1; while (true){ int mx=-1, cur=0; for (int i=0; i<n; i++) if (!del[i] && !vst[i] && mx<wei[i]) cur = i, mx = wei[i]; if (mx == -1) break; vst[cur] = 1; s = t; t = cur; for (int i=0; i<n; i++) if (!vst[i] && !del[i]) wei[i] += edge[cur][i]; } } int solve(){ int res = 2147483647; for (int i=0,x,y; i<n-1; i++){ search(x,y); res = min(res,wei[y]); del[y] = 1; for (int j=0; j<n; j++) edge[x][j] = (edge[j][x] += edge[y][j]); } return res; } }graph; <file_sep>/contest/ITSA2018/p13.cpp #include<bits/stdc++.h> using namespace std; void init(){ } void solve(){ } int main (){ int T; cin >> T; for (int ncase=1; ncase<=T; ncase++){ init(); solve(); } } <file_sep>/contest/TOPC2018/pE.cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 512; int n, a[MAXN]; bitset<MAXN> f[MAXN][MAXN]; int dp[2][MAXN][MAXN]; int posj, posk; auto pre = dp[0], now = dp[1]; void init(){ cin >> n; assert(1<=n && n <= 511); for (int i=1; i<=n; i++){ cin >> a[i]; assert(a[i]>=0 && a[i]<=511); } } int build_dp(){ pre = dp[0]; now = dp[1]; for (int j=0; j<MAXN; j++) for (int k=0; k<MAXN; k++) f[0][j][k] = 0; for (int j=0; j<MAXN; j++) for (int k=0; k<MAXN; k++) pre[j][k] = -1, now[j][k] = -1; f[0][0][0] = 1; for (int i=1; i<=n; i++){ for (int j=0; j<MAXN; j++) for (int k=0; k<MAXN; k++) f[i][j][k] = 0; for (int j=0; j<MAXN; j++) for (int k=0; k<MAXN; k++) now[j][k] = -1; for (int j=0; j<512; j++){ for (int k=0; k<512; k++){ if ( f[i-1][j][k] ){ f[i][ j^a[i] ][k] = 1; f[i][j][ k|a[i] ] = 1; } if ( f[i-1][j][k] ){ now[j][k] = max( now[j][k], a[i] ); } if ( pre[j][k]!=-1 ){ now[j^a[i]][k] = max( now[j^a[i]][k], pre[j][k] ); now[j][k|a[i]] = max( now[j][k|a[i]], pre[j][k] ); } } } swap(pre,now); } swap(pre,now); int ans = -1; for (int j=0; j<MAXN; j++) for (int k=0; k<MAXN; k++){ if ( now[j][k]!=-1 ){ if ( ans < j+k+now[j][k] ){ ans = j+k+now[j][k]; posj = j; posk = k; } } } return ans; } vector<int> A, B, C; void recover_f(int I, int J, int K){ if (I<=0) return; /* if ( f[i-1][j][k] ){ f[i][ j^a[i] ][k] = 1; f[i][j][ k|a[i] ] = 1; } */ int i = I; for (int j=0; j<512; j++){ for (int k=0; k<512; k++){ if ( f[i-1][j][k] && (j^a[i])==J && k==K ){ A.push_back(a[i]); recover_f(i-1,j,k); return; } if ( f[i-1][j][k] && j==J && (k|a[i])==K ){ B.push_back(a[i]); recover_f(i-1,j,k); return; } } } } int main(){ init(); cout << build_dp() << '\n'; for (int i=1; i<=n; i++){ if ( now[posj][posk] == a[i] ){ swap(a[i],a[n]); C.push_back(a[n]); n--; break; } } int pre_posj = posj; int pre_posk = posk; build_dp(); recover_f(n,pre_posj,pre_posk); if(A.size()+B.size()+C.size()!=n+1){ while(1); } cout << A.size(); for (int x:A) cout << ' ' << x; cout << '\n'; cout << B.size(); for (int x:B) cout << ' ' << x; cout << '\n'; cout << C.size(); for (int x:C) cout << ' ' << x; cout << '\n'; } <file_sep>/codebook/Other/Dp1D1D.cpp #include<bits/stdc++.h> int t, n, L; int p; char s[MAXN][35]; ll sum[MAXN] = {0}; long double dp[MAXN] = {0}; int prevd[MAXN] = {0}; long double pw(long double a, int n) { if ( n == 1 ) return a; long double b = pw(a, n/2); if ( n & 1 ) return b*b*a; else return b*b; } long double f(int i, int j) { // cout << (sum[i] - sum[j]+i-j-1-L) << endl; return pw(abs(sum[i] - sum[j]+i-j-1-L), p) + dp[j]; } struct INV { int L, R, pos; }; INV stk[MAXN*10]; int top = 1, bot = 1; void update(int i) { while ( top > bot && i < stk[top].L && f(stk[top].L, i) < f(stk[top].L, stk[top].pos) ) { stk[top - 1].R = stk[top].R; top--; } int lo = stk[top].L, hi = stk[top].R, mid, pos = stk[top].pos; //if ( i >= lo ) lo = i + 1; while ( lo != hi ) { mid = lo + (hi - lo) / 2; if ( f(mid, i) < f(mid, pos) ) hi = mid; else lo = mid + 1; } if ( hi < stk[top].R ) { stk[top + 1] = (INV) { hi, stk[top].R, i }; stk[top++].R = hi; } } int main() { cin >> t; while ( t-- ) { cin >> n >> L >> p; dp[0] = sum[0] = 0; for ( int i = 1 ; i <= n ; i++ ) { cin >> s[i]; sum[i] = sum[i-1] + strlen(s[i]); dp[i] = numeric_limits<long double>::max(); } stk[top] = (INV) {1, n + 1, 0}; for ( int i = 1 ; i <= n ; i++ ) { if ( i >= stk[bot].R ) bot++; dp[i] = f(i, stk[bot].pos); update(i); // cout << (ll) f(i, stk[bot].pos) << endl; } if ( dp[n] > 1e18 ) { cout << "Too hard to arrange" << endl; } else { vector<PI> as; cout << (ll)dp[n] << endl; } } return 0; } <file_sep>/codebook/String/suffix_array.cpp /*he[i]保存了在後綴數組中相鄰兩個後綴的最長公共前綴長度 *sa[i]表示的是字典序排名為i的後綴是誰(字典序越小的排名越靠前) *rk[i]表示的是後綴我所對應的排名是多少 */ const int MAX = 1020304; int ct[MAX], he[MAX], rk[MAX]; int sa[MAX], tsa[MAX], tp[MAX][2]; void suffix_array(char *ip){ int len = strlen(ip); int alp = 256; memset(ct, 0, sizeof(ct)); for(int i=0;i<len;i++) ct[ip[i]+1]++; for(int i=1;i<alp;i++) ct[i]+=ct[i-1]; for(int i=0;i<len;i++) rk[i]=ct[ip[i]]; for(int i=1;i<len;i*=2){ for(int j=0;j<len;j++){ if(j+i>=len) tp[j][1]=0; else tp[j][1]=rk[j+i]+1; tp[j][0]=rk[j]; } memset(ct, 0, sizeof(ct)); for(int j=0;j<len;j++) ct[tp[j][1]+1]++; for(int j=1;j<len+2;j++) ct[j]+=ct[j-1]; for(int j=0;j<len;j++) tsa[ct[tp[j][1]]++]=j; memset(ct, 0, sizeof(ct)); for(int j=0;j<len;j++) ct[tp[j][0]+1]++; for(int j=1;j<len+1;j++) ct[j]+=ct[j-1]; for(int j=0;j<len;j++) sa[ct[tp[tsa[j]][0]]++]=tsa[j]; rk[sa[0]]=0; for(int j=1;j<len;j++){ if( tp[sa[j]][0] == tp[sa[j-1]][0] && tp[sa[j]][1] == tp[sa[j-1]][1] ) rk[sa[j]] = rk[sa[j-1]]; else rk[sa[j]] = j; } } for(int i=0,h=0;i<len;i++){ if(rk[i]==0) h=0; else{ int j=sa[rk[i]-1]; h=max(0,h-1); for(;ip[i+h]==ip[j+h];h++); } he[rk[i]]=h; } } <file_sep>/contest/TOPC2018/pC.cpp #include <bits/stdc++.h> using namespace std; struct Point{ double x, y; bool operator < (const Point &b) const { return atan2(y,x) < atan2(b.y,b.x); } Point operator + (const Point &b) const { return {x+b.x,y+b.y}; } Point operator - (const Point &b) const { return {x-b.x,y-b.y}; } double operator * (const Point &b) const { return x*b.x + y*b.y; } double operator % (const Point &b) const { return x*b.y - y*b.x; } }; Point f(Point line, Point p){ double r = sqrt(p.x*p.x + p.y*p.y); double t = 2*atan2(line.y,line.x) - atan2(p.y,p.x); return {r*cos(t),r*sin(t)}; } const int MAXN = 10000; int n; Point p[MAXN], tar; void init(){ cin >> n; cin >> tar.x >> tar.y; for (int i=0; i<n; i++) cin >> p[i].x >> p[i].y; sort(p,p+n); Point a = f(p[0],tar); Point b = f(p[n-1],tar); Point v = a-b; double len = sqrt(v.x*v.x + v.y*v.y); printf("%.10f\n",len); } void solve(){ } int main(){ int T; cin >> T; while (T--){ init(); solve(); } } <file_sep>/contest/TTCPC2018/pI.cpp #include <bits/stdc++.h> using namespace std; char name[100]; array<int,9> numw,numb,numt; int cntw,cntb,cntt; int ee,ss,ww,nn,rc,gf,wb; void init(){ fill(numw.begin(),numw.end(),0); fill(numb.begin(),numb.end(),0); fill(numt.begin(),numt.end(),0); ee=0,ss=0,ww=0,nn=0,rc=0,gf=0,wb=0; cntw=0,cntb=0,cntt=0; scanf("%s",name); for(int i = 0 ; i < 17 ; i ++){ string tmp; cin >> tmp; if(tmp[0]>='0'&&tmp[0]<='9'){ int num=tmp[0]-'1'; if(tmp[1]=='W'){ cntw++; numw[num]++; } else if(tmp[1]=='B'){ cntb++; numb[num]++; } else{ cntt++; numt[num]++; } } else if(tmp=="EE"){ ee++; } else if(tmp=="SS"){ ss++; } else if(tmp=="WW"){ ww++; } else if(tmp=="NN"){ nn++; } else if(tmp=="RC"){ rc++; } else if(tmp=="GF"){ gf++; } else{ wb++; } } } void check32(){ int cnt[3]={0}; cnt[ee%3]++; cnt[ss%3]++; cnt[ww%3]++; cnt[nn%3]++; cnt[rc%3]++; cnt[gf%3]++; cnt[wb%3]++; cnt[cntw%3]++; cnt[cntb%3]++; cnt[cntt%3]++; //printf("!!! %d %d %d\n",cnt[0],cnt[1],cnt[2]); if(cnt[0]!=9)throw 0; if(cnt[2]!=1)throw 0; } bool realcheck(array<int,9> a){ int minv=10; for(int i = 0 ; i < 9 ; i ++){ if(a[i]!=0){ minv=i; break; } } if(minv==10)return true; if(a[minv]>=3){ a[minv]-=3; if(realcheck(a))return true; a[minv]+=3; } if(minv<=6&&a[minv+1]>=1&&a[minv+2]>=1){ a[minv]--; a[minv+1]--; a[minv+2]--; if(realcheck(a))return true; a[minv]++; a[minv+1]++; a[minv+2]++; } return false; } void check(array<int,9> a,int total){ if(total%3==2){ for(int i = 0 ; i < 9 ; i ++){ if(a[i]>=2){ a[i]-=2; if(realcheck(a))return; a[i]+=2; } } throw 0; } else{ if(!realcheck(a))throw 0; } } int main(){ int T; scanf("%d",&T); while(T--){ init(); bool ok=true; try{ check32(); check(numb,cntb); check(numt,cntt); check(numw,cntw); } catch(...){ ok=false; } if(ok)printf("%s can yell out Mahjong!\n",name); else printf("Nothing happened.\n"); } } /* 2 Capoo 1W 1W 1W 2W 2W 4W 4W 4W 3T 4T 5T 7T 8T 9T GF GF GF DogDog 1B 2B 2B 2B 3B 3B 3B 4B 4B 1T 1T 1T 1T WW WW WB WB */ <file_sep>/contest/PTC1803/README.md # PTC (2018/03/14) ## result ![result](./result.png) <file_sep>/codebook/String/AC.cpp // remember make_fail() !!! // notice MLE const int sigma = 62; const int MAXC = 200005; inline int idx(char c){ if ('A'<= c && c <= 'Z')return c-'A'; if ('a'<= c && c <= 'z')return c-'a' + 26; if ('0'<= c && c <= '9')return c-'0' + 52; assert(false); } struct ACautomaton{ struct Node{ Node *next[sigma], *fail; int cnt; // dp Node() : next{}, fail{}, cnt{}{} } buf[MAXC], *bufp, *ori, *root; void init(){ bufp = buf; ori = new (bufp++) Node(); root = new (bufp++) Node(); } void insert(char *s){ Node *ptr = root; for (int i=0; s[i]; i++){ int c = idx(s[i]); if (!ptr->next[c]) ptr->next[c] = new (bufp++) Node(); ptr = ptr->next[c]; } ptr->cnt=1; } Node* trans(Node *o, int c){ if (o->next[c]) return o->next[c]; return o->next[c] = trans(o->fail, c); } void make_fail(){ static queue<Node*> que; for (int i=0; i<sigma; i++) ori->next[i] = root; root->fail = ori; que.push(root); while ( que.size() ){ Node *u = que.front(); que.pop(); for (int i=0; i<sigma; i++){ if (!u->next[i])continue; u->next[i]->fail = trans(u->fail,i); que.push(u->next[i]); } u->cnt += u->fail->cnt; } } } ac; <file_sep>/contest/2018_NCTU_Annual/pH.cpp #include <bits/stdc++.h> using namespace std; const long long INF = ( (1LL)<<60 ); bitset<250001> S; int sum=0; long long dd=0; long long cal(long long a, long long b){ long long ans = a*a + b*b - dd - a*b*2; if (ans<0) ans = -ans; return ans/2; } int main(){ S[0] = 1; int n; cin >> n; for (int i=0, hi; i<n; i++){ cin >> hi; S |= (S<<hi); sum += hi; dd += hi*hi; } long long ans = INF; for (int i=0; i<=sum; i++){ if ( S[i] ){ ans = min( ans, cal(i,sum-i) ); } } cout << ans << '\n'; } <file_sep>/contest/2018_NCTU_Annual/pB.cpp #include <bits/stdc++.h> using namespace std; int n; int la, ra; int lb, rb; int lc, rc; int dp[31][130][130][50]; int main(){ dp[0][0][0][0] = 1; scanf("%d", &n); scanf("%d %d", &la, &ra); scanf("%d %d", &lb, &rb); scanf("%d %d", &lc, &rc); for (int i=1; i<=n; i++){ int x, y, z; scanf("%d %d %d", &x, &y, &z); for (int a=0; a<=ra; a++)for (int b=0; b<=rb; b++)for (int c=0; c<=rc; c++){ dp[i][a][b][c] = dp[i-1][a][b][c]; } for (int a=x; a<=ra; a++)for (int b=y; b<=rb; b++)for (int c=z; c<=rc; c++){ dp[i][a][b][c] += dp[i-1][a-x][b-y][c-z]; } } long long ans = 0; for (int a=la; a<=ra; a++)for (int b=lb; b<=rb; b++)for (int c=lc; c<=rc; c++){ ans += dp[n][a][b][c]; } cout << ans << '\n'; } <file_sep>/codebook/Basic/vimrc/.script #!/bin/bash CF="-std=c++11 -fsanitize=undefined -D FOX" WF="-Wall -Wextra -Wshadow -pedantic" PN=$(echo $2 | sed 's/\..*$//') cpp(){ g++ $1.cpp $CF $WF -o $1 && run ./$1 } py(){ run "python $1.py" } addin(){ read -p "case name: " CASE && gedit $PN\_$CASE.in } run(){ for i in "$PN"_*.in do echo "======== $i ========" bash -c "$1" < $i done } echo "=========================v" "$1" "$2" echo "=========================^" <file_sep>/codebook/Math/theorem.cpp /* Lucas's Theorem For non-negative integer n,m and prime P, C(m,n) mod P = C(m/M,n/M) * C(m%M,n%M) mod P = mult_i ( C(m_i,n_i) ) where m_i is the i-th digit of m in base P. ------------------------------------------------------- Kirchhoff's theorem A_{ii} = deg(i), A_{ij} = (i,j) \in E ? -1 : 0 Deleting any one row, one column, and cal the det(A) ------------------------------------------------------- Nth Catalan recursive function: C_0 = 1, C_{n+1} = C_n * 2(2n + 1)/(n+2) ------------------------------------------------------- Mobius Formula u(n) = 1 , if n = 1 (-1)^m , 若 n 無平方數因數,且 n = p1*p2*p3*...*pk 0 , 若 n 有大於 1 的平方數因數 - Property 1. (積性函數) u(a)u(b) = u(ab) 2. ∑_{d|n} u(d) = [n == 1] ------------------------------------------------------- Mobius Inversion Formula if f(n) = ∑_{d|n} g(d) then g(n) = ∑_{d|n} u(n/d)f(d) = ∑_{d|n} u(d)f(n/d) - Application the number/power of gcd(i, j) = k - Trick 分塊, O(sqrt(n)) ------------------------------------------------------- Chinese Remainder Theorem (m_i 兩兩互質) x = a_1 (mod m_1) x = a_2 (mod m_2) .... x = a_i (mod m_i) construct a solution: Let M = m_1 * m_2 * m_3 * ... * m_n Let M_i = M / m_i t_i = 1 / M_i t_i * M_i = 1 (mod m_i) solution x = a_1 * t_1 * M_1 + a_2 * t_2 * M_2 + ... + a_n * t_n * M_n + k * M = k*M + ∑ a_i * t_i * M_i, k is positive integer. under mod M, there is one solution x = ∑ a_i * t_i * M_i ------------------------------------------------------- Burnside's lemma |G| * |X/G| = sum( |X^g| ) where g in G 總方法數: 每一種旋轉下不動點的個數總和 除以 旋轉的方法數 */ <file_sep>/contest/TTCPC2018/README.md # TTCPC 臺清交程式設計競賽 (2018/04/29) ![problem set](https://drive.google.com/file/d/1l0dsWJ_D6Gu9tiA3UhfWCf3YespIrJRI/view) ![test data](https://drive.google.com/drive/folders/1PcqqKifn_UQoHo2yxTvWfpTDOOijInKL) ## result ![result](./photo1.jpg) ![result](./sb.jpg) ![result](./mapping.jpg) ![result](./result.jpg) ![result](./photo2.jpg) <file_sep>/contest/ITSA2018/p3.cpp #include<bits/stdc++.h> using namespace std; void init(){ char s[100]; scanf("%s",s); int n = strlen(s); while(1){ bool found=false; for(int i = 0 ; i < n-1 ; i ++){ if(s[i]<s[i+1]){ s[i]++; found=true; for(int j = i+1 ; j < n ; j ++){ s[j]='0'; } break; } } if(!found)break; } printf("%s\n",s); } void solve(){ } int main (){ int T; cin >> T; for (int ncase=1; ncase<=T; ncase++){ init(); solve(); } } <file_sep>/contest/TTCPC2018/pH.cpp #include <bits/stdc++.h> using namespace std; using LL = long long; LL al, be, ga; LL l1, l2, l3; array<LL,4> f, g, h; void makel(LL l){ l1 = l; l2 = l*l; l3 = l*l*l; } void makef(){ f = {-l1, 1,0,0}; for (int i=0;i<4;i++)f[i] *= 6*ga; } void makeg(){ g = {l2-l1, -2*l1+1,1,0}; for (int i=0;i<4;i++)g[i] *= 3*be; } void makeh(){ h = {-2*l3+3*l2-l1, 6*l2-6*l1+1, -6*l1+3, 2}; for (int i=0;i<4;i++)h[i] *= al; } void make(LL l){ makel(l); makef(); makeg(); makeh(); } LL ff(LL x){ LL ret=0; LL now = 1; for (int i=0;i<4;i++){ ret += f[i] * now; now *= x; } return ret; } LL gg(LL x){ LL ret=0; LL now = 1; for (int i=0;i<4;i++){ ret += g[i] * now; now *= x; } return ret; } LL hh(LL x){ LL ret=0; LL now = 1; for (int i=0;i<4;i++){ ret += h[i] * now; now *= x; } return ret; } array<LL,4> bitl, bitr; void makebit(LL l, LL r){ make(l); for (int i=0;i<4;i++){ bitl[i] = f[i] + g[i] + h[i]; bitr[i] = -bitl[i]; } bitr[0] += ff(r) - ff(l) + gg(r) - gg(l) + hh(r) - hh(l); } const int MAXN = 100005; void add(long long bit[], int pos, long long val){ while (pos<MAXN){ bit[pos] += val; pos += pos&(-pos); } } long long query(long long bit[], int pos){ long long re=0; while (pos>0){ re += bit[pos]; pos -= pos&(-pos); } return re; } long long bit[4][MAXN]; void add(int l, int r){ makebit(l,r);/* printf("bitl: "); for (int i=0; i<4; i++) printf("%lld ", bitl[i]); puts(""); printf("bitr: "); for (int i=0; i<4; i++) printf("%lld ", bitr[i]); puts(""); printf("f: "); for (int i=0; i<4; i++) printf("%lld ", f[i]); puts(""); printf("g: "); for (int i=0; i<4; i++) printf("%lld ", g[i]); puts(""); printf("h: "); for (int i=0; i<4; i++) printf("%lld ", h[i]); puts(""); add(bit[0],l-1,bitl[0]); add(bit[0],r,bitr[0]);*/ for (int i=0; i<4; i++){ add(bit[i],l,bitl[i]); add(bit[i],r,bitr[i]); } } long long query(long long x){ long long re=0; re += query(bit[0],x); re += x*query(bit[1],x); re += x*x*query(bit[2],x); re += x*x*x*query(bit[3],x); return re; } long long query(int l, int r){ return query(r-1) - query(l-1); } int n; void init(){ memset(bit,0,sizeof(bit)); cin >> n; cin >> al >> be >> ga; for (int i=1, ai; i<=n; i++){ scanf("%d", &ai); add(bit[0],i,(long long)ai*6); } } int main(){ int T; cin >> T; while (T--){ init(); int m; cin >> m; for (int i=0; i<m; i++){ printf("BIT: "); for (int i=1; i<=n; i++)printf("%lld ", (query(i)-query(i-1))/6 ); puts(""); int cmd, l, r; scanf("%d %d %d", &cmd, &l, &r); r++; if (cmd==1){ add(l,r); } else { long long ans = query(l,r); const int MOD = 1e9+7; ans = (ans/6)%MOD; printf("%lld\n",ans); } } } } /* 1 3 1 2 3 17 239 999 4 2 1 3 1 2 3 2 2 3 2 1 2 */ <file_sep>/contest/2018_NCTU_Annual/pG.cpp #pragma GCC optimize("O3") #include <bits/stdc++.h> using namespace std; void build_KMP(int n, char *s, int *f){ // 1 base f[0]=-1, f[1]=0; for (int i=2; i<=n; i++){ int w = f[i-1]; while ( w>=0 && s[w+1] != s[i]) w = f[w]; f[i] = w+1; } } const int MAXN = 1000006; int n, k; int f[MAXN]; char s[MAXN]; int tag[MAXN]; set<int> v[MAXN]; bool ok[MAXN]; bool check(int len){ fill(ok,ok+n+1,0); ok[len] = true; for (int i=len+1; i<=n; i++){ if ( ok[ f[i] ] ){ ok[i] = 1; } } int cnt = 1; for (int i=len+len; i<=n; i++){ if ( ok[i]){ cnt++; i+=len-1; } } return cnt >=k ; } int main(){ scanf("%d%s", &k, s+1); n = strlen(s+1); build_KMP(n,s,f); vector<int> temp; for (int w=n; w>0; w = f[w]){ temp.push_back(w); } reverse(temp.begin(),temp.end()); int l=0, r=(int)temp.size()-1; while (l!=r){ int mid = (l+r)>>1; if ( !check(temp[mid]) ) r=mid; else l=mid+1; } if(r>0 && check(r)){ cout << temp[r-1] << '\n'; } else { cout << "-1" << '\n'; } } <file_sep>/codebook/Math/ax+by=gcd.cpp pair<int,int> extgcd(int a, int b){ if (b==0) return {1,0}; int k = a/b; pair<int,int> p = extgcd(b,a-k*b); return { p.second, p.first - k*p.second }; } <file_sep>/contest/2018_NCTU_Annual/README.md # 交大校內年度賽 (2018/09/04) - [Online Judge](https://oj.nctu.me/groups/17/bulletins/) ## result ![result](./result.png) ![p1](./p1.jpg) <file_sep>/codebook/Graph/Flow/Gomory_Hu.cpp Construct of Gomory Hu Tree 1. make sure the whole graph is clear 2. set node 0 as root, also be the parent of other nodes. 3. for every node i > 0, we run maxflow from i to parent[i] 4. hense we know the weight between i and parent[i] 5. for each node j > i, if j is at the same side with i, make the parent of j as i ------------------------------------------------------- int e[MAXN][MAXN]; int p[MAXN]; Dinic D; // original graph void gomory_hu() { fill(p, p+n, 0); fill(e[0], e[n], INF); for ( int s = 1 ; s < n ; s++ ) { int t = p[s]; Dinic F = D; int tmp = F.max_flow(s, t); for ( int i = 1 ; i < s ; i++ ) e[s][i] = e[i][s] = min(tmp, e[t][i]); for ( int i = s+1 ; i <= n ; i++ ) if ( p[i] == t && F.side[i] ) p[i] = s; } }<file_sep>/contest/ITSA2018/README.md # ITSA 桂冠賽 (2018/05/19) - [website](http://172.16.31.10/ITSAcontest/ITSA2018/) ## result ![result](./result.png) ![p1](./p1.jpg) ![p](./p.jpg) <file_sep>/codebook/Graph/Flow/Karzanov.cpp const long long INF = 1LL<<60; struct Karzanov{ // O(V*V*V) static const int MAXN = 5003; struct Edge{ int v, w; long long u, f; // cap, flow }; int n, m ,s, t, d[MAXN]; vector<Edge> edges; vector<int> G[MAXN]; int topo[MAXN], order[MAXN], topon; long long ex[MAXN]; int cur[MAXN]; bool forzon[MAXN]; vector< pair<int,long long> > sta[MAXN]; // ei, f Karzanov() { init(); } void init( int _n = MAXN ){ n = _n, m=0; edges.clear(); for (int i=0; i<n; i++) G[i].clear(); } void add_edge(int v, int w, long long u){ edges.push_back( {v,w,u,0} ); edges.push_back( {w,v,0,0} ); m = edges.size(); G[v].push_back(m-2); G[w].push_back(m-1); } long long max_flow(int _s, int _t){ s=_s, t=_t; long long flow=0; while (bfs()) flow += blocking_flow(); return flow; } private: bool bfs(){ fill(topo,topo+n,-1); topon=0; fill(order,order+n,-1); fill(d,d+n,-1); queue<int> que; que.push(s); d[s]=0; while ( !que.empty() ){ int v = que.front(); que.pop(); order[v] = topon; topo[topon++] = v; for (int ei:G[v]){ Edge &e = edges[ei]; if ( d[e.w]<0 && e.f<e.u ){ d[e.w] = d[v]+1; que.push(e.w); } } } return d[t]>=0; } void modify(int ei, long long df){ Edge &e = edges[ei]; ex[ e.v ] -= df; ex[ e.w ] += df; e.f += df; edges[ei^1].f -= df; } void push_step(){ for (int i=0; i<topon; i++){ int v = topo[i]; for (int &j=cur[v]; j<(int)G[v].size(); j++){ if (ex[v]==0)break; Edge &e = edges[ G[v][j] ]; if ( forzon[e.w] || e.u==e.f || order[v]>=order[e.w] )continue; long long delta = min(ex[v],e.u-e.f); modify( G[v][j], delta ); sta[ e.w ].push_back( {G[v][j],delta}); if (e.f<e.u)break; } } } bool balancing_step(){ for (int i=topon-1; i>0 ;i--) if (ex[ topo[i] ]>0){ int w = topo[i]; while (ex[w]>0){ int ei = sta[w].back().first; long long delta = min( sta[w].back().second, ex[w] ); modify( ei, -delta); sta[w].pop_back(); } forzon[w]=1; return 1; } return 0; } long long blocking_flow(){ fill(ex,ex+n,0); fill(cur,cur+n,0); fill(forzon,forzon+n,0); for (int i=0; i<n; i++) sta[i].clear(); long long flow = 0; ex[s] = INF; for (int i=0; i<n; i++){ push_step(); flow += ex[t]; ex[t]=0; if ( !balancing_step() )break; } return flow; } } karzanov; <file_sep>/codebook/Graph/Dijkstra.cpp struct Edge{ int v; long long len; bool operator < (const Edge &b)const { return len>b.len; } }; const long long INF = 1LL<<60; void Dijkstra(int n, vector<Edge> G[], long long d[], int s, int t=-1){ static priority_queue<Edge> pq; while ( pq.size() )pq.pop(); for (int i=1; i<=n; i++)d[i]=INF; d[s]=0; pq.push( {s,d[s]} ); while ( pq.size() ){ auto x = pq.top(); pq.pop(); int u = x.v; if (d[u]<x.len)continue; if (u==t)return; for (auto &e:G[u]){ if (d[e.v] > d[u]+e.len){ d[e.v] = d[u]+e.len; pq.push( {e.v,d[e.v]} ); } } } } <file_sep>/contest/2018_NCTU_Annual/pD.cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 202; const int INF = 1<<29; int n, a[MAXN][MAXN], d[MAXN][MAXN]; void init(){ scanf("%d", &n); for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ scanf("%d", &a[i][j]); } } for (int i=0; i<2*n; i++){ for (int j=0; j<2*n; j++){ d[i][j] = INF; if (i%2!=j%2){ if ( a[i/2][j/2] !=-1 ) d[i][j] = a[i/2][j/2]; } } } } void solve(){ for (int k=0; k<2*n; k++){ for (int i=0; i<2*n; i++){ for (int j=0; j<2*n; j++){ d[i][j] = min( d[i][j], d[i][k]+d[k][j] ); } } } } void output(){ for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ a[i][j] = d[i*2][j*2+1]; } } for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ if (a[i][j]==INF)a[i][j]=-1; printf("%d ",a[i][j]); } puts(""); } } int main(){ init(); solve(); output(); } <file_sep>/codebook/Graph/MaximumClique.cpp const int MAXN = 105; int best; int n; int num[MAXN]; int path[MAXN]; int G[MAXN][MAXN]; bool dfs( int *adj, int total, int cnt ){ int t[MAXN]; if (total == 0){ if( best < cnt ){ best = cnt; return true; } return false; } for(int i = 0; i < total; i++){ if( cnt+(total-i) <= best ) return false; if( cnt+num[adj[i]] <= best ) return false; int k=0; for(int j=i+1; j<total; j++) if(G[ adj[i] ][ adj[j] ]) t[k++] = adj[j]; if (dfs(t, k, cnt+1)) return true; } return false; } int MaximumClique(){ int adj[MAXN]; if (n <= 0) return 0; best = 0; for(int i = n-1; i >= 0; i--){ int k=0; for(int j = i+1; j < n; j++) if (g[i][j]) adj[k++] = j; dfs( adj, k, 1 ); num[i] = best; } return best; } <file_sep>/contest/WorldFinals2019/43WorldFinalsWorkstation-Team63/Desktop/AC/D.cpp #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; using pci = pair<char,int>; using pii = pair<int,int>; const int MAXN = 1000004; int n; map<int,vector<pci>> m; void init(){ char buf[20]; cin >> n; for (int i=0; i<n; i++) { cin >> buf; int v = atoi(buf+1); m[v].push_back({buf[0],i+1}); } } int ans[MAXN]; vector<pii> cal(const vector<pci>& v) { vector<pii> ret; vector<int> s(v.size()); for (int i=0; i<(int)v.size(); i++) { if (v[i].first == 's') s[i]++; else s[i]--; } partial_sum(s.begin(), s.end(), s.begin()); if (s.back()) return ret; auto it = min_element(s.begin(), s.end()); while (it != s.end()) { int i = it-s.begin(); if (i==(int)v.size()-1) { int a = v[i].second+1; ret.push_back({a, n+1}); int b = v[0].second+1; ret.push_back({1, b}); } else { int a = v[i].second+1; int b = v[i+1].second+1; ret.push_back({a,b}); } it = find(it+1, s.end(), *it); } return ret; } void solve(){ for (auto& p : m) { //cout << "type: " << p.first << endl; for (auto& q : cal(p.second)) { //cout << q.first << ' ' << q.second << endl; ans[ q.first ] ++; ans[ q.second ] --; } } partial_sum(ans+1, ans+n+1, ans+1); auto it = max_element(ans+1, ans+n+1); cout << it-ans << ' ' << *it << '\n'; } int main(){ cin.tie(0); cin.sync_with_stdio(0); init(); solve(); } <file_sep>/codebook/Math/FWHT.cpp // FWHT template const int MAXN = 1<<20; void FWHT(int a[], int l=0, int r=MAXN-1){ if (l==r)return; int mid = (l+r)>>1+1, n = r-l+1; FWHT(a,l,mid-1); FWHT(a,mid,r); for (int i=0; i<(n>>1); i++){ int a1=a[l+i], a2=a[mid+i]; a[l+i] = a1+a2; a[mid+i] = a1-a2; } } <file_sep>/codebook/String/BWT.cpp string BWT(string); // by suffix array string iBWT(string &s, int start=0){ int n = (int) s.size(); string ret(n,' '); vector<int> next(n,0), box[256]; for (int i=0; i<n; i++) // bucket sort box[ (int)s[i] ].push_back(i); for (int i=0, j=0; i<256; i++) for (int x:box[i]) next[j++] = x; for (int i=0, p=start; i<n; i++) ret[i] = s[ p=next[p] ]; return ret; } <file_sep>/contest/TTCPC2018/pA.cpp #include <bits/stdc++.h> using namespace std; const int MOD = 1e9+7; struct Mat{ vector< vector<int> > A; Mat(){ A.resize( 4, vector<int>(4,0) ); for (int i=0; i<4; i++) A[i][i]=1; } Mat operator * (const Mat &b) const{ Mat re; for (int i=0; i<4; i++){ for (int j=0; j<4; j++){ re.A[i][j]=0; for (int k=0; k<4; k++){ re.A[i][j] += (long long)A[i][k] * b.A[k][j] %MOD; re.A[i][j] %= MOD; } } } return re; } }; Mat pow(Mat A, long long n){ Mat re; while (n>0){ if (n&1) re = re*A; A = A*A; n>>=1; } return re; } long long n; int a1, a2, b1, w, x, y, z; int a[10], b[10]; Mat TM; void init(){ scanf("%lld %d %d %d %d %d %d %d", &n, &a1, &a2, &b1, &w, &x, &y, &z); TM = Mat(); TM.A[0][0]=0, TM.A[0][1]=x, TM.A[0][2]=w; TM.A[1][0]=1, TM.A[1][1]=0, TM.A[1][2]=0; TM.A[2][0]=y, TM.A[2][1]=0, TM.A[2][2]=z; TM.A[3][0]=y, TM.A[3][1]=x, TM.A[3][2]=(w+z)%MOD; a[1] = a1; a[2] = a2; b[1] = b1; b[2] = ( (long long)y*a[1]%MOD + (long long)z*b[1]%MOD ) %MOD; for (int i=3; i<10; i++){ a[i] = (w*b[i-1] + x*a[i-2])%MOD; b[i] = (y*a[i-1] + z*b[i-1])%MOD; } for (int i=1; i<10; i++){ //printf("%d %d\n", a[i], b[i]); } if (n==1){ cout << (a[1]+b[1])%MOD << '\n'; } else { Mat M = pow(TM,n-2); int S = ((long long)a[1]+a[2]+b[1]+b[2])%MOD; long long ans = (long long)M.A[3][0]*a[2]%MOD + (long long)M.A[3][1]*a[1]%MOD + (long long)M.A[3][2]*b[2]%MOD + (long long)M.A[3][3]*S%MOD; ans %= MOD; cout << ans << '\n'; } } int main(){ int T; cin >> T; while (T--){ init(); } } <file_sep>/contest/PTC1809/pB.old.cpp #include<bits/stdc++.h> using namespace std; const int MAXN = 5000004; int n; bool eve[MAXN]; vector<int> ad[MAXN]; int par[MAXN]; int deg[MAXN]; int fa[MAXN]; int find(int x){ if (fa[x]==x) return x; return fa[x] = find(fa[x]); } bool ok; void massert(bool b){ if (b) return; cout << "what the fuck\n"; exit(0); } void init(){ ok=1; scanf("%d", &n); for (int i=0; i<n; i++){ eve[i] = false; ad[i].clear(); par[i] = deg[i] = 0; } int m; scanf("%d", &m); while (m--){ int x; scanf("%d", &x); eve[x] = true; } for (int i=0; i<n; i++) fa[i] = i; for (int i=0; i<n-1; i++){ int u, v; scanf("%d%d", &u, &v); massert( 0<=u && u<n ); massert( 0<=v && v<n ); ad[u].push_back(v); ad[v].push_back(u); u = find(u); v = find(v); if(u==v)ok=0; else fa[u] = v; } } void solve(){ massert(ok); if (!ok){ puts("-1"); return; } vector<int> a; queue<int> que; que.push(0); fill(par,par+n,0); while (que.size()){ int u = que.front(); que.pop(); a.push_back(u); for (int v:ad[u]) if ( v!=par[u] ){ par[v] = u; que.push(v); } } for (int i=0; i<n; i++) deg[i] = ad[i].size()%2; int ans = n-1; for (int i=n-1; i>0; i--){ int u = a[i]; if ( deg[u] == eve[u] ){ deg[u]^=1; deg[ par[u] ]^=1; ans--; } } if ( deg[0] == eve[0] || n>50000) puts("-1"); else cout << ans << '\n'; } int main (){ int T; scanf("%d", &T); massert(0<=T); while (T--){ init(); solve(); } } <file_sep>/codebook/Geometry/Intersection_of_two_lines.cpp Point interPnt(Point p1, Point p2, Point q1, Point q2, bool &res){ Double f1 = cross(p2, q1, p1); Double f2 = -cross(p2, q2, p1); Double f = (f1 + f2); if(fabs(f) < EPS) { res = false; return {}; } res = true; return (f2 / f) * q1 + (f1 / f) * q2; } <file_sep>/contest/PTC1808/pC.cpp #include <bits/stdc++.h> using namespace std; int ds[10004]; int boss(int x){ if (x==ds[x]) return x; return ds[x] = boss(ds[x]); } struct yee{ int u, v, w; bool operator<(const yee& y)const{ return w > y.w; } }; int n, m; priority_queue<yee> pq1, pq2; void init(){ for (int i=0;i<10004;i++){ ds[i] = i; } cin >>n >>m; for (int i=0;i<n;i++){ int x; cin >>x; pq1.push({i, n, x}); } for (int i=0;i<m;i++){ int u, v, x; cin >>u >>v >>x; pq1.push({u, v, x}); pq2.push({u, v, x}); } } void solve(){ long long ans1 = 0, ans2 = 0; while (!pq1.empty()){ auto x = pq1.top(); pq1.pop(); int ub = boss(x.u); int vb = boss(x.v); if (ub != vb){ ds[ub] = vb; ans1 += x.w; } } for (int i=0;i<10004;i++){ ds[i] = i; } while (!pq2.empty()){ auto x = pq2.top(); pq2.pop(); int ub = boss(x.u); int vb = boss(x.v); if (ub != vb){ ds[ub] = vb; ans2 += x.w; } } cout <<min(ans1, ans2) <<'\n'; } int main(){ cin.tie(0); int T; cin >>T; while (T--){ init(); solve(); } } <file_sep>/contest/PTC1808/README.md # PTC (2018/08/15) ## result ![result](./result.png) <file_sep>/contest/TTCPC2018/pF.cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 102; int n, a[MAXN], dp[MAXN]; int din[MAXN]; vector<int> G[MAXN]; void init(){ scanf("%d",&n); for (int i=0, u; i<n; i++){ scanf("%d", &u); scanf("%d", &a[u]); int k; scanf("%d", &k); for (int j=0, v; j<k; j++){ scanf("%d", &v); G[v].push_back(u); din[u]++; } } } int main(){ init(); queue<int> que; for (int i=0; i<n; i++){ if (din[i]==0) que.push(i); } int ans=0; while (que.size()){ int u = que.front(); que.pop(); dp[u] += a[u]; ans = max(ans, dp[u]); for (int v:G[u]){ dp[v] = max(dp[v], dp[u]); din[v]--; if (din[v]==0) que.push(v); } } cout << ans <<'\n'; } /* 5 0 199 4 1 2 3 4 1 935 0 2 879 2 1 3 3 522 0 4 146 2 1 3 */ <file_sep>/contest/2018_NCTU_Annual/pC.cpp #include <bits/stdc++.h> using namespace std; string a[3]; bool comp(const string& l, const string& r){ if (l.size()!=r.size()) return l.size() > r.size(); return l < r; } bool check(){ const string& l = a[1]; const string& r = a[2]; size_t p = 0; for (char x : r){ while (p < l.size() && l[p] != x) p++; if (p == l.size()) return false; p++; } return true; } int main(){ cin.tie(0); cin.sync_with_stdio(0); for (int i=0; i<3; i++) cin >>a[i]; //for (int i=0; i<3; i++) cout <<a[i] <<'\n';; sort(a, a+3, comp); if (a[0] != a[1]){ cout <<a[0].size() <<'\n'; } else if (!check()){ cout <<a[2].size() <<'\n'; } else cout <<0 <<'\n'; } <file_sep>/codebook/Graph/MinimumSteinerTree.cpp // Minimum Steiner Tree // O(V 3^T + V^2 2^T) struct SteinerTree{ #define V 33 #define T 8 #define INF 1023456789 int n , dst[V][V] , dp[1 << T][V] , tdst[V]; void init( int _n ){ n = _n; for( int i = 0 ; i < n ; i ++ ){ for( int j = 0 ; j < n ; j ++ ) dst[ i ][ j ] = INF; dst[ i ][ i ] = 0; } } void add_edge( int ui , int vi , int wi ){ dst[ ui ][ vi ] = min( dst[ ui ][ vi ] , wi ); dst[ vi ][ ui ] = min( dst[ vi ][ ui ] , wi ); } void shortest_path(){ for( int k = 0 ; k < n ; k ++ ) for( int i = 0 ; i < n ; i ++ ) for( int j = 0 ; j < n ; j ++ ) dst[ i ][ j ] = min( dst[ i ][ j ], dst[ i ][ k ] + dst[ k ][ j ] ); } int solve( const vector<int>& ter ){ int t = (int)ter.size(); for( int i = 0 ; i < ( 1 << t ) ; i ++ ) for( int j = 0 ; j < n ; j ++ ) dp[ i ][ j ] = INF; for( int i = 0 ; i < n ; i ++ ) dp[ 0 ][ i ] = 0; for( int msk = 1 ; msk < ( 1 << t ) ; msk ++ ){ if( msk == ( msk & (-msk) ) ){ int who = __lg( msk ); for( int i = 0 ; i < n ; i ++ ) dp[ msk ][ i ] = dst[ ter[ who ] ][ i ]; continue; } for( int i = 0 ; i < n ; i ++ ) for( int submsk = ( msk - 1 ) & msk ; submsk ; submsk = ( submsk - 1 ) & msk ) dp[ msk ][ i ] = min( dp[ msk ][ i ], dp[ submsk ][ i ] + dp[ msk ^ submsk ][ i ] ); for( int i = 0 ; i < n ; i ++ ){ tdst[ i ] = INF; for( int j = 0 ; j < n ; j ++ ) tdst[ i ] = min( tdst[ i ], dp[ msk ][ j ] + dst[ j ][ i ] ); } for( int i = 0 ; i < n ; i ++ ) dp[ msk ][ i ] = tdst[ i ]; } int ans = INF; for( int i = 0 ; i < n ; i ++ ) ans = min( ans , dp[ ( 1 << t ) - 1 ][ i ] ); return ans; } } solver; <file_sep>/contest/TOPC2018/pF.cpp #include <bits/stdc++.h> using namespace std; int n, cnt[10]; string s; void init(){ fill(cnt,cnt+10,0); cin >> s; n = s.size(); for (char c:s){ cnt[ c-'0' ]++; } } int half(){ for (int i=0; i<10; i++){ if ( cnt[i]+cnt[i] >=n ){ return i; } } return -1; } void solve(){ vector<bool> pre(n), suf(n); { int mx=0; fill(cnt,cnt+10,0); for (int i=0; i<n; i++){ int c = s[i]-'0'; mx = max( mx, ++cnt[c] ); if (mx+mx>i+1)pre[i]=0; else pre[i]=1; } } { int mx = 0; fill(cnt,cnt+10,0); for (int i=n-1; i>=0; i--){ int c = s[i]-'0'; mx = max( mx, ++cnt[c] ); if ( mx+mx > n-i ) suf[i] = 0; else suf[i]=1; } } char c = '9'+1; for (int i=0; i<n; i+=2){ bool ok = 1; if (i>0 && !pre[i-1]) ok=0; if (i<n-1 && !suf[i+1]) ok=0; if (ok) c = min(c,s[i]); } cout << c << '\n'; } int main(){ cin.sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--){ init(); int d = half(); if ( d==-1 ){ if (n%2==0){ cout << "0\n"; } else { solve(); } } else { int len = cnt[d] - (n-cnt[d]); if (d==0 || len==0) cout << 0 << '\n'; else { for (int x=0; x<len; x++){ cout << d; } cout << '\n'; } } } } <file_sep>/codebook/Basic/T.cpp #pragma GCC optimize("Ofast") #include <bits/stdc++.h> #include <sys/time.h> #include <sys/resource.h> using namespace std; void setstack(){ // Set soft limit and hard limit to max const rlimit tmp {RLIM_INFINITY,RLIM_INFINITY}; setrlimit(RLIMIT_STACK,&tmp); } int main(){ #define name "" #ifndef FOX freopen(name".in","r",stdin); freopen(name".out","w",stdout); #endif static_assert(strlen(name)); ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); } <file_sep>/contest/PTC1809/pD.cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 1003; const int MAXM = 10004; const double INF = 1e16; struct Edge{ int v, u; double c; }; int n, m; Edge e[MAXM]; double d[MAXN][MAXN]; void init(){ scanf("%d %d", &n, &m); for (int i=0; i<m; i++){ int u, v, c; scanf("%d %d %d", &u, &v, &c); u--, v--; e[i].v = u; e[i].u = v; e[i].c = c; } } void BF(){ for (int i=0; i<n; i++) d[0][i] = 0; for (int i=0; i<n; i++){ fill(d[i+1],d[i+1]+n,INF); for (int j=0; j<m; j++){ int v = e[j].v, u = e[j].u; if (d[i][v] < INF && d[i+1][u] > d[i][v] + e[j].c){ d[i+1][u] = d[i][v] + e[j].c; } } } } void mmc(){ double mmc = INF; BF(); for (int i=0; i<n; i++){ double avg = -INF; for (int k=0; k<n; k++){ if (d[n][i]<INF) avg = max(avg,(d[n][i]-d[k][i])/(n-k)); else avg = max(avg,INF); } mmc = min(mmc,avg); } printf("%.12f\n",mmc); } int main(){ int T; cin >> T; while (T--){ init(); mmc(); } } <file_sep>/contest/PTC1803/pA.cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 100005; int n; long long d, a[MAXN]; bool check(int k){ priority_queue<long long,vector<long long>,greater<long long>> pq; for (int i=0; i<k; i++) pq.push(0); long long mx=0; for (int i=0; i<n; i++){ long long u = pq.top(); pq.pop(); u += a[i]; pq.push(u); mx = max(mx,u); } return mx <= d; } int main(){ scanf("%d %lld", &n, &d); for (int i=0; i<n; i++) scanf("%lld", a+i); int l=1, r=n; while (l!=r){ int mid = (l+r)>>1; if ( check(mid) ) r=mid; else l=mid+1; } if ( check(n)==0 ) puts("-1"); else printf("%d\n",r); } <file_sep>/contest/2018_NCTU_Annual/pJ.cpp #include <bits/stdc++.h> using namespace std; using Double = double; const Double EPS = 1e-9; struct Point{ Double x, y; bool operator < (const Point &b) const { if ( fabs( x-b.x ) > EPS ) return x < b.x; if ( fabs( y-b.y ) > EPS ) return y < b.y; return false; } Point operator -(const Point& b) const{ return Point{x-b.x, y-b.y}; } Double operator % (const Point &b) const { return x*b.y - y*b.x; } }; Double abs2( Point p ){ return p.x * p.x + p.y * p.y; } Point circumcentre(const Point& p0, const Point& p1, const Point& p2){ Point a = p1 - p0; Point b = p2 - p0; Double c1 = abs2(a) * 0.5; Double c2 = abs2(b) * 0.5; Double d = a % b; Double x = p0.x + ( c1*b.y - c2*a.y ) / d; Double y = p0.y + ( c2*a.x - c1*b.x ) / d; return {x,y}; } bool online(const Point &a, const Point &b, const Point &c){ return fabs( (c-a)%(b-a) ) < EPS; } int n; Point p[400]; int main(){ scanf("%d", &n); if (n==1 || n==2){ printf("%d\n", n); return 0; } for (int i=0; i<n; i++){ int x, y; scanf("%d%d", &x, &y); p[i] = {(Double)x,(Double)y}; } random_shuffle(p,p+n); int k = min(n,50); int mx = 2; for (int i=0; i<k; i++){ for (int j=i+1; j<k; j++){ map< Point, int > cnt; for (int k=0; k<n; k++) if(k!=i && k!=j && !online(p[i], p[j], p[k])){ Point o = circumcentre(p[i],p[j],p[k]); auto &dp = cnt[o]; dp++; mx = max(mx,dp+2); } } } if ( mx >= (n+1)/2 ) cout << mx << '\n'; else cout << "i don't know\n"; } <file_sep>/contest/WorldFinals2019/43WorldFinalsWorkstation-Team63/Desktop/AC/A.cpp #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; using pii = pair<int,int>; const int INF = 1e8; const int MAXN = 500005; tuple<int,int,int> a[2][MAXN]; int n; void init(){ cin >> n; for (int j=0; j<2; j++){ for (int i=0; i<n; i++) cin >> get<0>(a[j][i]); for (int i=0; i<n; i++) cin >> get<1>(a[j][i]); for (int i=0; i<n; i++) get<2>(a[j][i]) = i; } sort( a[0], a[0] + n); sort( a[1], a[1] + n); } void imp() { cout << "impossible" << endl; exit(0); } vector<int> ans[2]; void solve(){ set< pii > L, R; int ptrL=0, ptrR=0; while ( ptrL<n || ptrR<n ){ if ( L.empty() ){ int pric = get<0>(a[0][ptrL]); while ( ptrL<n && get<0>(a[0][ptrL])== pric ){ L.insert( {get<1>(a[0][ptrL]), get<2>(a[0][ptrL])+1} ); ptrL++; } } if ( R.empty() ){ int pric = get<0>(a[1][ptrR]); while ( ptrR<n && get<0>(a[1][ptrR]) == pric ){ R.insert( {get<1>(a[1][ptrR]), get<2>(a[1][ptrR])+1} ); ptrR++; } } assert( !L.empty() && !R.empty() ); if ( L.size() < R.size() ){ // pop_small(L,R,0,1); for (pii p : L) { auto it = R.lower_bound({ p.first, -1 }); if (it == R.begin()) imp(); it--; ans[0].push_back(p.second); ans[1].push_back(it->second); R.erase(it); } L.clear(); } else { // pop_small(R,L,1,0); for (pii p : R) { auto it = L.upper_bound({ p.first, INF }); if (it == L.end()) imp(); ans[0].push_back(it->second); ans[1].push_back(p.second); L.erase(it); } R.clear(); } } } int main(){ cin.tie(0); cin.sync_with_stdio(0); init(); solve(); assert((int)ans[0].size() == n); assert((int)ans[1].size() == n); for (int i=0; i<n; i++) cout << ans[0][i] << ' '; cout << endl; for (int i=0; i<n; i++) cout << ans[1][i] << ' '; cout << endl; } <file_sep>/contest/TOPC2018/README.md # TOPC (2018/09/15) - [Website](http://icpc2018.ntu.edu.tw/) - [problems](./TOPC2018.pdf) ## result ![result](./result_top10.png) ![result](./result.png) <file_sep>/contest/ITSA2018/p1.cpp #include<bits/stdc++.h> using namespace std; set< pair<int,pair<int,int>> > S; int mabs(int x){ if (x<0)return -x; return x; } void build(){ for (int x=-100; x<=100; x++){ for (int y=x; y<=100; y++){ int a = x+y; int b = mabs(x-y); int p = x*y; int c; if (p<0){ p*=-1; if (p%100==50) c=p/100; else if (p%100>50) c = p/100+1; else c = p/100; c*=-1; } else { if (p%100>=50) c=p/100+1; else c=p/100; } S.insert( {a,{b,c}} ); } } } void solve(){ int a, b, c; scanf("%d%d%d", &a,&b,&c); int ans=0; ans += S.count( {a,{b,c}} ); ans += S.count( {a,{c,b}} ); ans += S.count( {b,{a,c}} ); ans += S.count( {b,{c,a}} ); ans += S.count( {c,{a,b}} ); ans += S.count( {c,{b,a}} ); puts(ans ? "Yes" : "No"); } int main (){ build(); int T; cin >> T; for (int ncase=1; ncase<=T; ncase++){ solve(); } } <file_sep>/contest/PTC1808/pD.cpp #include <bits/stdc++.h> using namespace std; const long long MOD = 1e9+7; struct Mat{ long long a, b, c, d; Mat operator * (const Mat &B) const { Mat re; re.a = ( (a*B.a)%MOD + (b*B.c)%MOD )%MOD; re.b = ( (a*B.b)%MOD + (b*B.d)%MOD )%MOD; re.c = ( (c*B.a)%MOD + (d*B.c)%MOD )%MOD; re.d = ( (c*B.b)%MOD + (d*B.d)%MOD )%MOD; return re; } }; Mat pow(Mat a, int n){ Mat re = {1,0,0,1}; while (n>0){ if (n&1) re = re * a; a = a*a; n>>=1; } return re; } pair<int,int> f(int n){ Mat T = pow( {1,1,1,0}, n ); return { (T.c+T.d)%MOD, T.c }; } long long pow(long long a, long long n, long long mod){ long long re = 1; while (n>0){ if (n&1) re = re * a % mod; a = a*a %mod; n/=2; } return re; } long long inv(long long x){ x %= MOD; return pow(x,MOD-2,MOD); } long long nor(long long x){ x %= MOD; if (x<0) x+=MOD; return x; } bool check(int n, long long tar, long long u, long long v){ if (n==0) return tar == u; if (n==1) return tar == u+v; v += u; for (int i=2; i<=n; i++){ v += u; u = v - u; if ( v>tar ) return 0; } return tar == v; } int n, x, m, y, k; int main(){ int T; cin >> T; while (T--){ cin >> n >> x >> m >> y >> k; pair<int,int> p1 = f(n); long long a1 = p1.first; long long b1 = p1.second; //printf("%lld %lld\n",a1,b1); pair<int,int> p2 = f(m); long long a2 = p2.first; long long b2 = p2.second; //printf("%lld %lld\n",a2,b2); if ( a2*b1 == a1*b2 ){ puts("Impossible"); continue; } long long v = (a2*x-a1*y)%MOD * inv(a2*b1-a1*b2) %MOD; long long u = (x-b1*v)%MOD * inv(a1) %MOD; v = nor(v); u = nor(u); if ( !check(n,x,u,v) || !check(m,y,u,v) ){ puts("Impossible"); continue; } pair<int,int> p = f(k); long long ans = (p.first*u%MOD + p.second*v%MOD)%MOD; cout << ans << '\n'; } } <file_sep>/contest/WorldFinals2019/43WorldFinalsWorkstation-Team63/workspace/CLionProject/CMakeLists.txt cmake_minimum_required(VERSION 3.12) project(CLionProject) set(CMAKE_CXX_STANDARD 14) add_executable(CLionProject main.cpp)<file_sep>/codebook/Other/Parser.cpp using LL = long long; const int MAXLEVEL = 2; // binary operators const vector<char> Ops[MAXLEVEL] = { {'+', '-'}, // level 0 {'*', '/'} // level 1 }; // unary operators const vector<pair<char,int>> Op1s = { {'-', 0} // operator negative works on level 0 }; struct Node{ ~Node(){ delete L; delete R; } enum { op, op1, num } type; LL val; Node *L, *R; } *root; char getOp1(int LEVEL, istream& is){ is >>ws; for (auto& x : Op1s){ auto& op = x.first; auto& lev = x.second; if (LEVEL == lev && is.peek() == op) return is.get(); } return 0; } template <int LEVEL> void parse(Node*& x, istream& is){ char op1 = getOp1(LEVEL, is); parse<LEVEL+1>(x, is); if (op1) x = new Node{Node::op1, op1, x, nullptr}; auto& ops = Ops[LEVEL]; while (is>>ws && count(ops.begin(), ops.end(), is.peek())){ x = new Node{Node::op, is.get(), x, nullptr}; parse<LEVEL+1>(x->R, is); } } template <> void parse<MAXLEVEL>(Node*& x, istream& is){ char op1 = getOp1(MAXLEVEL, is); is>>ws; if (is.peek()>='0' && is.peek()<='9'){ LL t; is >>t; x = new Node{Node::num, t, nullptr, nullptr}; } else if (is.peek() == '('){ is.get(); parse<0>(x, is); is>>ws; if (is.get()!=')') throw 0; } else throw 0; if (op1) x = new Node{Node::op1, op1, x, nullptr}; } // throw when error occur !!!!! void build(istream& is){ parse<0>(root, is); if ((is>>ws).peek() != EOF) throw 0; } <file_sep>/contest/PTC1808/pE.cpp #include <bits/stdc++.h> using namespace std; const long long INF = 1e18; const int MAXN = 50004; int n, k; long long a[MAXN], S[MAXN]; long long dp[MAXN]; int pos[MAXN]; void init(){ scanf("%d %d", &n, &k); for (int i=1; i<=n; i++){ scanf("%lld", &a[i]); } sort(a+1,a+1+n); for (int i=1; i<=n; i++){ S[i] = S[i-1]+a[i]; } } long long cost(int l, int r){ int mid = (l+r)/2; return (S[r]-S[mid]) - (r-mid)*a[mid] + (mid-l+1)*a[mid] - (S[mid]-S[l-1]); } void solve(){ dp[0] = 0, pos[0] = 0; for (int i=1; i<k; i++) dp[i] = INF; dp[k] = cost(1,k), pos[k] = 0; for (int i=k+1; i<=n; i++){ dp[i] = dp[i-k] + cost(i-k+1,i), pos[i] = i-k; for (int j=pos[i-1]; j<i-k; j++){ long long v = dp[j] + cost(j+1,i); if ( v < dp[i] ){ pos[i] = j; dp[i] = v; } } } cout << dp[n] << '\n'; } int main(){ int T; cin >> T; while (T--){ init(); solve(); //for (int i=1; i<=n; i++) printf("%lld ", a[i]); puts(""); //for (int i=1; i<=n; i++) printf("%lld ", dp[i]); puts(""); } } <file_sep>/README.md # NCTU_Fox NCTU_Fox, an team for ACM ICPC of National Chiao Tung University. ![p1](https://raw.githubusercontent.com/NCTU-PCCA/NCTU_Fox/master/contest/TTCPC2018/photo2.jpg) # Member - [陳昇暉(ss1h2a3tw)](https://www.facebook.com/ss1h2a3tw) - [莊昕宸(harryoooooooooo)](https://www.facebook.com/harryoooooooooo) - [吳宗達(cthbst)](https://www.facebook.com/cthbst) # Award (2018-2019) - **2019 ACM-ICPC Wrold Final 21st Place** - [ICPC 台北站](https://icpc.baylor.edu/regionals/finder/Taipei-2018) Rank: 4, Third Place, World Final 晉級順位 2 - [ICPC 首爾站](https://icpc.baylor.edu/regionals/finder/Seoul-2018) Rank: 12, Eighth Place - [NCPC](https://ncpc.ntnu.edu.tw/ncpc2018/) Rank: 13, 佳作 - 交大年度賽 Rank: 1 - [TOPC](https://icpc.baylor.edu/regionals/finder/hua-lien-online-2017) Rank: 3, Second Place - [ITSA 桂冠賽](http://algorithm.csie.ncku.edu.tw/ITSAcontest/ITSA2018/) Rank: 8, 佳作 - [臺清交程式設計競賽](https://www.facebook.com/nthu.cssa/posts/1690192604405429) Rank: 3, 銅牌獎 <file_sep>/contest/WorldFinals2019/43WorldFinalsWorkstation-Team63/Desktop/AC/G.cpp #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; const int sigma = 26; const int MAXC = 1000006; inline int idx(char c){ return c - 'A'; } // remember make_fail()!!!! @@ ssh // notice MLE const int MAXN = 1000006; int ans[MAXN]; struct AC{ struct Node{ Node *next[sigma], *fail; Node() : next{}, fail{}, cnt{} {} int cnt; } buf[MAXC], *bufp, *ori, *root; vector<Node*> BFSord; void init(){ bufp = buf; ori = new (bufp++) Node(); root = new (bufp++) Node(); } Node* insert(char *s){ Node *ptr = root; for (int i=0; s[i]; i++){ int c = idx(s[i]); if (!ptr->next[c]) ptr->next[c] = new (bufp++) Node(); ptr = ptr->next[c]; } return ptr; } Node* trans(Node *o, int c){ if ( o->next[c] ) return o->next[c]; return o->next[c] = trans(o->fail,c); } void make_fail(){ queue<Node*> que; for (int i=0; i<sigma; i++) ori->next[i] = root; root->fail = ori; que.push(root); while ( que.size() ){ Node *u = que.front(); que.pop(); BFSord.push_back(u); for (int i=0; i<sigma; i++){ if (!u->next[i])continue; u->next[i]->fail = trans(u->fail,i); que.push(u->next[i]); } } } void collectFail(){ reverse(BFSord.begin(), BFSord.end()); for (auto u:BFSord){ u->fail->cnt += u->cnt; } } } ac; int n, m; pair<char,int> in[MAXN]; AC::Node *w[MAXN], *qid[MAXN]; char s[MAXN]; void init(){ cin >> n >> m; for (int i=1; i<=n; i++){ cin >> in[i].first >> in[i].second; } ac.init(); for (int i=0; i<m; i++){ cin >> s; int l = strlen(s); reverse(s,s+l); qid[i] = ac.insert(s); } } void solve(){ ac.make_fail(); w[1] = ac.trans( ac.root, idx(in[1].first) ); for (int i=2; i<=n; i++){ auto pre = w[ in[i].second ]; w[i] = ac.trans( pre, idx(in[i].first) ); } for (int i=1; i<=n; i++){ w[i]->cnt++; } ac.collectFail(); for (int i=0; i<m; i++){ cout << qid[i]->cnt << '\n'; } } int main(){ cin.tie(0); cin.sync_with_stdio(0); init(); solve(); } <file_sep>/codebook/Graph/Matching/Hungarian.cpp // Maximum Cardinality Bipartite Matching // Worst case O(nm) struct Graph{ static const int MAXN = 5003; vector<int> G[MAXN]; int n, match[MAXN], vis[MAXN]; void init(int _n){ n = _n; for (int i=0; i<n; i++) G[i].clear(); } bool dfs(int u){ for (int v:G[u]){ if (vis[v]) continue; vis[v]=true; if (match[v]==-1 || dfs(match[v])){ match[v] = u; match[u] = v; return true; } } return false; } int solve(){ int res = 0; memset(match,-1,sizeof(match)); for (int i=0; i<n; i++){ if (match[i]==-1){ memset(vis,0,sizeof(vis)); if ( dfs(i) ) res++; } } return res; } } graph; <file_sep>/contest/ITSA2018/p8.cpp #include<bits/stdc++.h> using namespace std; const int MAXN = 100005; struct str{ int x, y, z; bool operator < (const str &b) const { if (x!=b.x) return x<b.x; if (y!=b.y) return y>b.y; return z<b.z; } }a[MAXN]; int n; long long bit[MAXN]; long long pre[MAXN]; long long suf[MAXN]; void init(){ vector<int> xs, ys; scanf("%d", &n); for (int i=0; i<n; i++){ int x, y, z; scanf("%d %d %d", &x, &y, &z); xs.push_back(x); ys.push_back(y); a[i] = {x,y,z}; } sort(xs.begin(),xs.end()); sort(ys.begin(),ys.end()); xs.resize( unique(xs.begin(),xs.end()) - xs.begin() ); ys.resize( unique(ys.begin(),ys.end()) - ys.begin() ); for (int i=0; i<n; i++){ a[i].x = lower_bound(xs.begin(),xs.end(),a[i].x)-xs.begin()+1; a[i].y = lower_bound(ys.begin(),ys.end(),a[i].y)-ys.begin()+1; } sort(a,a+n); //for (int i=0; i<n; i++) printf("%d %d %d\n", a[i].x, a[i].y, a[i].z); } void build_pre(){ memset(bit,0,sizeof(bit)); for (int i=0; i<n; i++){ // query(a[i].y,n) max // trans ( 1,n+1-a[i].y ) int w = n+1 - a[i].y; long long best = 0; while (w>0){ best = max(best,bit[w]); w -= w&-w; } pre[i] = best + a[i].z; // update(a[i].y,pre[i]) w = n+1 - a[i].y; while (w<MAXN){ bit[w] = max(bit[w],pre[i]); w += w&-w; } } //for (int i=0; i<n; i++) printf("%lld ", pre[i]); puts(""); } void build_suf(){ memset(bit,0,sizeof(bit)); for (int i=n-1; i>=0; i--){ // query(1,a[i].y) max int w = a[i].y; long long best = 0; while (w>0){ best = max(best,bit[w]); w -= w&-w; } suf[i] = best + a[i].z; // update(a[i].y,suf[i]) w = a[i].y; while (w<MAXN){ bit[w] = max(bit[w],suf[i]); w += w&-w; } } //for (int i=0; i<n; i++) printf("%lld ", suf[i]); puts(""); } void solve(){ build_pre(); build_suf(); for (int i=1; i<n; i++) pre[i] = max(pre[i],pre[i-1]); for (int i=n-2; i>=0; i--) suf[i] = max(suf[i],suf[i+1]); long long ans = 0; for (int i=1; i<n-1; i++){ ans = max(ans, pre[i]+suf[i+1] ); } for (int i=0; i<n; i++){ ans = max(ans,pre[i]); ans = max(ans,suf[i]); } cout << ans << '\n'; } int main (){ int T; cin >> T; for (int ncase=1; ncase<=T; ncase++){ init(); solve(); } } <file_sep>/codebook/String/Z-value.cpp z[0] = 0; for ( int bst = 0, i = 1; i < len ; i++ ) { if ( z[bst] + bst <= i ) z[i] = 0; else z[i] = min(z[i - bst], z[bst] + bst - i); while ( str[i + z[i]] == str[z[i]] ) z[i]++; if ( i + z[i] > bst + z[bst] ) bst = i; } // 回文版 void Zpal(const char *s, int len, int *z) { // Only odd palindrome len is considered // z[i] means that the longest odd palindrom centered at // i is [i-z[i] .. i+z[i]] z[0] = 0; for (int b=0, i=1; i<len; i++) { if (z[b]+b >= i) z[i] = min(z[2*b-i], b+z[b]-i); else z[i] = 0; while (i+z[i]+1 < len && i-z[i]-1 >= 0 && s[i+z[i]+1] == s[i-z[i]-1]) z[i] ++; if (z[i]+i > z[b]+b) b = i; } } <file_sep>/codebook/DataStructure/ext_heap.cpp #include <bits/extc++.h> typedef __gnu_pbds::priority_queue<int> heap_t; heap_t a,b; int main() { a.clear(); b.clear(); a.push(1); a.push(3); b.push(2); b.push(4); assert(a.top() == 3); assert(b.top() == 4); // merge two heap a.join(b); assert(a.top() == 4); assert(b.empty()); return 0; }<file_sep>/contest/TOPC2018/pD.cpp #include<bits/stdc++.h> using namespace std; const int MAXN = 500004; int scr[MAXN]; int cnt[MAXN]; bool vis[MAXN], _vis[MAXN]; vector<int> G[MAXN]; int RG[MAXN]; int n, m, s; int S[26]; vector<int> scores, sides; const int ii[] = {0, 1, 0,-1}; const int jj[] = {1, 0,-1, 0}; inline int dir(char c){ switch(c){ case 'u': return 3; break; case 'd': return 1; break; case 'r': return 0; break; case 'l': return 2; break; default: assert(false); } } void dfs(int now){ cnt[now] = 0; vis[now] = true; for (int x : G[now])if(!vis[x]){ scr[x] = scr[now]; dfs(x); cnt[now] += cnt[x]; } cnt[now] ++; } void find_loop(int now){ while (true){ _vis[now] = true; int next = RG[now]; if (_vis[next]){ scr[now] = 0; dfs(now); for (int i=next; i!=now; i=RG[i]) cnt[i] = cnt[now]; return; } now = next; } } void init(){ static char buf[MAXN]; scanf("%d%d%d", &n, &m, &s); for (int i=0; i<s; i++){ scanf("%d", S+i); } scores.clear(); sides.clear(); for (int i=0; i<n*m; i++){ G[i].clear(); vis[i] = _vis[i] = false; } for (int i=0; i<n; i++){ scanf("%s", buf); for (int j=0; j<m; j++){ int now = i*m + j; if (buf[j] >= 'A' && buf[j] <= 'Z'){ RG[now] = -2; scr[now] = S[buf[j]-'A']; scores.push_back(now); } else { int d = dir(buf[j]); int ni = i+ii[d]; int nj = j+jj[d]; if (ni>=0 && ni<n && nj>=0 && nj<m){ RG[now] = ni*m + nj; G[ni*m + nj].push_back(now); } else { RG[now] = -1; scr[now] = 0; sides.push_back(now); } } } } for (int x : scores) dfs(x); for (int x : sides ) dfs(x); for (int i=0; i<n*m; i++) if(!vis[i]) find_loop(i); } void solve(){ long long ans = 0; for (int i=0; i<n; i++){ for (int j=0; j<m; j++) if(RG[i*m+j] >= -1){ for (int k=0; k<4; k++){ int ni = i+ii[k]; int nj = j+jj[k]; if (ni>=0 && ni<n && nj>=0 && nj<m && scr[ni*m+nj]>scr[i*m+j]){ ans = max(ans, (long long)(scr[ni*m+nj] - scr[i*m+j]) * cnt[i*m+j] ); } } } } for (int x : scores) ans += (long long)cnt[x] * scr[x]; printf("%lld\n", ans); } int main (){ int T; scanf("%d", &T); while (T--){ init(); solve(); } } <file_sep>/contest/2018_NCTU_Annual/pA.cpp #include <bits/stdc++.h> using namespace std; const int INF = 1e9+7; int main(){ int ans = 1; map<int,int> CC; int n; cin >> n; if ( n>1) ans = 2; if ( n==2 ){ int a ,b; cin >> a >> b; if (a==0 && b!=0 ) cout << 1 << '\n'; else cout << 2 << '\n'; return 0; } int cnt_zero=0; for (int i=0, last=INF, cnt=0; i<n; i++){ int ai = 0; scanf("%d", &ai); CC[ai]++; if (ai==0) cnt_zero++; ans = max( ans, CC[ai] ); } if (n==2 && n-cnt_zero==1 ) ans=1; cout << ans << '\n'; } <file_sep>/contest/ITSA2018/p4.cpp #include<bits/stdc++.h> using namespace std; vector<bool> vis; string s; set<long long> ss; void init(){ vis.resize(s.size()); ss.clear(); fill(vis.begin(), vis.end(), false); } void dfs(int dep){ if (dep == (int)vis.size()){ string t; long long c= 0 ; int cnt=0; for (size_t i=0; i<s.size(); i++) if (vis[i]){ c = 10 * c + s[i]-'0'; cnt++; } if (cnt==0)return; ss.insert(c); return; } vis[dep] = true; dfs(dep+1); vis[dep] = false; dfs(dep+1); } void solve(){ dfs(0); cout << ss.size() << '\n'; } int main (){ cin.tie(0); while (cin >> s){ init(); solve(); } } <file_sep>/contest/PTC1809/pC.cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 10000+777; char a[MAXN]; char b[MAXN]; int alen; int blen; int dp[2][MAXN]; int *pre = dp[0]; int *now = dp[1]; void init(){ scanf("%s%s",a,b); alen=strlen(a); blen=strlen(b); for(int i = 0 ; i <= blen ; i ++){ pre[i]=i; now[i]=0; } } void solve(){ for(int i = 0 ; i < alen ; i ++){ pre[0]=i; now[0]=i+1; for(int j = 0 ; j < blen ; j ++){ now[j+1]=min({now[j],pre[j],pre[j+1]})+1; if(a[i]==b[j]){ now[j+1]= min( now[j+1], pre[j]); } } swap(pre,now); } printf("%d\n",pre[blen]); } int main(){ int T; scanf("%d",&T); while(T--){ init(); solve(); } } <file_sep>/codebook/Other/ManhattanMST.cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 100005; const int OFFSET = 2000; // y-x may < 0, offset it, if y-x too large, please write a unique function const int INF = 0xFFFFFFF; int n; int x[MAXN], y[MAXN], p[MAXN]; typedef pair<int, int> pii; pii bit[MAXN]; // [ val, pos ] struct P { int x, y, id; bool operator<(const P&b ) const { if ( x == b.x ) return y > b.y; else return x > b.x; } }; vector<P> op; struct E { int x, y, cost; bool operator<(const E&b ) const { return cost < b.cost; } }; vector<E> edges; int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); } void update(int i, int v, int p) { while ( i ) { if ( bit[i].first > v ) bit[i] = {v, p}; i -= i & (-i); } } pii query(int i) { pii res = {INF, INF}; while ( i < MAXN ) { if ( bit[i].first < res.first ) res = {bit[i].first, bit[i].second}; i += i & (-i); } return res; } void input() { cin >> n; for ( int i = 0 ; i < n ; i++ ) cin >> x[i] >> y[i], op.push_back((P) {x[i], y[i], i}); } void mst() { for ( int i = 0 ; i < MAXN ; i++ ) p[i] = i; int res = 0; sort(edges.begin(), edges.end()); for ( auto e : edges ) { int x = find(e.x), y = find(e.y); if ( x != y ) { p[x] = y; res += e.cost; } } cout << res << endl; } void construct() { sort(op.begin(), op.end()); for ( int i = 0 ; i < n ; i++ ) { pii q = query(op[i].y - op[i].x + OFFSET); update(op[i].y - op[i].x + OFFSET, op[i].x + op[i].y, op[i].id); if ( q.first == INF ) continue; edges.push_back((E) {op[i].id, q.second, abs(x[op[i].id]-x[q.second]) + abs(y[op[i].id]-y[q.second]) }); } } void solve() { // [45 ~ 90 deg] for ( int i = 0 ; i < MAXN ; i++ ) bit[i] = {INF, INF}; construct(); // [0 ~ 45 deg] for ( int i = 0 ; i < MAXN ; i++ ) bit[i] = {INF, INF}; for ( int i = 0 ; i < n ; i++ ) swap(op[i].x, op[i].y); construct(); for ( int i = 0 ; i < n ; i++ ) swap(op[i].x, op[i].y); // [-90 ~ -45 deg] for ( int i = 0 ; i < MAXN ; i++ ) bit[i] = {INF, INF}; for ( int i = 0 ; i < n ; i++ ) op[i].y *= -1; construct(); // [-45 ~ 0 deg] for ( int i = 0 ; i < MAXN ; i++ ) bit[i] = {INF, INF}; for ( int i = 0 ; i < n ; i++ ) swap(op[i].x, op[i].y); construct(); // mst mst(); } int main () { input(); solve(); return 0; } <file_sep>/contest/WorldFinals2019/43WorldFinalsWorkstation-Team63/Desktop/AC/C.cpp #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; void init(){ } void solve(){ } int main(){ cin.tie(0); cin.sync_with_stdio(0); init(); solve(); } <file_sep>/contest/2018_NCTU_Annual/pF.cpp #include <bits/stdc++.h> using namespace std; const long long INF = 1ll << 60; const int MAXN = 1e5+4; struct Dinic{ struct Edge{ int u, v; long long cap, rest; }; int n, m, s, t, d[MAXN], cur[MAXN]; vector<Edge> edges; vector<int> G[MAXN]; void init(){ edges.clear(); for (int i=0;i<MAXN;i++) G[i].clear(); } void add_edge(int u, int v, long long cap){ edges.push_back({u, v, cap, cap}); edges.push_back({v, u, 0, 0ll}); m = edges.size(); G[u].push_back(m-2); G[v].push_back(m-1); } bool bfs(){ memset(d, -1, sizeof(d)); queue<int> que; que.push(s); d[s] = 0; while (!que.empty()){ int u = que.front(); que.pop(); for (int ei : G[u]){ Edge &e = edges[ei]; if (d[e.v] < 0 && e.rest > 0){ d[e.v] = d[u] + 1; que.push(e.v); } } } return d[t] >= 0; } long long dfs(int u, long long a){ if (u == t || a == 0) return a; long long flow = 0, f; for (int &i = cur[u]; i<(int)G[u].size(); i++){ Edge &e = edges[ G[u][i] ]; if (d[u] + 1 != d[e.v]) continue; f = dfs(e.v, min(a, e.rest)); if (f > 0){ e.rest -= f; edges[ G[u][i]^1 ].rest += f; flow += f; a -= f; if (a == 0) break; } } return flow; } long long maxflow(int _s, int _t){ this->s = _s; this->t = _t; long long flow = 0, mf; while ( bfs() ){ memset(cur, 0, sizeof(cur)); while((mf=dfs(s,INF))) flow += mf; } return flow; } }dinic; const int s = 1e5, t = 1e5+1; int n, m; int c[MAXN]; vector<int> ad[MAXN]; vector< pair<int,int> > edges; bool vis[MAXN]; bool tag[MAXN]; void dfs(int now, bool _t){ tag[now] = _t; vis[now] = true; for (int x : ad[now]) if (!vis[x]) dfs(x, !_t); } int main(){ scanf("%d%d", &n, &m); for (int i=0;i<n;i++) scanf("%d", c+i); for (int i=0; i<m; i++){ int u, v; scanf("%d%d", &u, &v); u --; v --; ad[u].push_back(v); ad[v].push_back(u); edges.push_back({u,v}); } for (int i=0; i<n; i++) if(!vis[i]) dfs(i, 0); for (auto e:edges){ int u = e.first, v = e.second; if ( tag[u] ) swap(u,v); dinic.add_edge(u, v, 1); } for (int i=0; i<n; i++){ if (tag[i]){ // to sink dinic.add_edge(i, t, c[i]); } else { // from source dinic.add_edge(s, i, c[i]); } } cout <<m-dinic.maxflow(s, t) <<'\n'; } <file_sep>/contest/TOPC2018/pH.cpp #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; int pop[1<<14]; int n, P, a[1<<14], cnt[1<<14], sum[1<<14]; int dp[1<<14]; int mU; inline int trans(int U, int S){ return pop[U^S]; } void init(){ cin >> P >> n; memset(a,0,sizeof(int)*(1<<P)); memset(cnt,0,sizeof(int)*(1<<P)); memset(sum,0,sizeof(int)*(1<<P)); char s[20]; for (int i=0; i<n; i++){ scanf("%s", s); int ai=0; for (int j=0; j<P; j++){ ai += (s[j]-'0') * (1<<j); } a[ai]++; } mU = 0; for (int S=(1<<P)-1; S>=0; S--){ if ( a[S] ) mU |= S; } for (int U=mU; U>=0; U=(U-1)&mU){ for (int S=U; S>=0; S=(S-1)&U){ cnt[U] += a[S]; sum[U] += a[S] * trans(U,S); if (S==0) break; } if (U==0)break; } } void solve(){ const int INF = 1e9+7; dp[0] = 0; for (int U=1; U<(1<<P); U++) if ((U&mU)==U){ dp[U] = INF; for (int S=U; S>=0; S=(S-1)&U){ int tmp = dp[S]; tmp += sum[U] - sum[S] - trans(U,S) * (cnt[S]); dp[U] = min(dp[U],tmp); if (S==0)break; } } cout << dp[ mU ] << '\n'; } int main(){ for (int i=(1<<14)-1; i>=0; i--){ pop[i] = __builtin_popcount(i); } int T; cin >> T; while (T--){ init(); solve(); } } <file_sep>/codebook/Geometry/Intersection_of_two_circle.cpp vector<Point> interCircle(Point o1, Double r1, Point o2, Double r2) { Double d2 = abs2(o1 - o2); Double d = sqrt(d2); Point u = (o1+o2)*0.5 + (o1-o2)*(r2*r2-r1*r1)/(2.0*d2); if (abs((r1+r2)*(r1+r2) - d2) < 1e-6) return {u}; if (d < fabs(r1-r2) || r1+r2 < d) return {}; Double A = sqrt((r1+r2+d) * (r1-r2+d) * (r1+r2-d) * (-r1+r2+d)); Point v = Point{o1.y-o2.y, -o1.x+o2.x} * A / (2.0*d2); return {u+v, u-v}; } <file_sep>/contest/PTC1804/README.md # PTC (2018/04/11) ## result ![result](./result.png) <file_sep>/contest/2018_NCTU_Annual/pE.cpp #include <bits/stdc++.h> using namespace std; using pii = pair<int,int>; const int MAXN = 100005; int n, m; pair<int,int> tt[MAXN], s[MAXN]; bool cmp(pii a, pii b){ return (double) a.first/a.second > (double)b.first/b.second; } int main(){ scanf("%d", &n); for (int i=0; i<n; i++){ scanf("%d", &tt[i].second); } for (int i=0; i<n; i++){ scanf("%d", &tt[i].first); } for (int i=0; i<n; i++){ if ( tt[i].first !=0 && tt[i].second!=0 ){ s[ m++ ] = tt[i]; } } sort(s,s+m,cmp); long long ans = 0, sum=0; for (int i=0; i<m; i++){ ans += sum * s[i].first; sum += s[i].second; } cout << ans << '\n'; } <file_sep>/codebook/DataStructure/SparseTable.h const int MAXN = 200005; const int lgN = 20; struct SP{ //sparse table int Sp[MAXN][lgN]; function<int(int,int)> opt; void build(int n, int *a){ // 0 base for (int i=0 ;i<n; i++) Sp[i][0]=a[i]; for (int h=1; h<lgN; h++){ int len = 1<<(h-1), i=0; for (; i+len<n; i++) Sp[i][h] = opt( Sp[i][h-1] , Sp[i+len][h-1] ); for (; i<n; i++) Sp[i][h] = Sp[i][h-1]; } } int query(int l, int r){ int h = __lg(r-l+1); int len = 1<<h; return opt( Sp[l][h] , Sp[r-len+1][h] ); } }; <file_sep>/codebook/Math/Karatsuba.cpp // N is power of 2 template<typename Iter> void DC(int N, Iter tmp, Iter A, Iter B, Iter res){ fill(res,res+2*N,0); if (N<=32){ for (int i=0; i<N; i++){ for (int j=0; j<N; j++){ res[i+j] += A[i]*B[j]; } } return; } int n = N/2; auto a = A+n, b = A; auto c = B+n, d = B; DC(n,tmp+N,a,c,res+2*N); for (int i=0; i<N; i++){ res[i+N] += res[2*N+i]; res[i+n] -= res[2*N+i]; } DC(n,tmp+N,b,d,res+2*N); for (int i=0; i<N; i++){ res[i] += res[2*N+i]; res[i+n] -= res[2*N+i]; } auto x = tmp; auto y = tmp+n; for (int i=0; i<n; i++) x[i] = a[i]+b[i]; for (int i=0; i<n; i++) y[i] = c[i]+d[i]; DC(n,tmp+N,x,y,res+2*N); for (int i=0; i<N; i++){ res[i+n] += res[2*N+i]; } } // DC(1<<16,tmp.begin(),A.begin(),B.begin(),res.begin()); <file_sep>/codebook/Other/java.java import java.util.*; import java.math.*; import java.io.*; public class java{ static class Comp implements Comparator<Integer>{ public int compare(Integer lhs, Integer rhs){ return lhs - rhs; } } static class Yee implements Comparable<Yee>{ public int compareTo(Yee y){ return 0; } } static class Reader{ private BufferedReader br; private StringTokenizer st; public Reader(){ br = new BufferedReader(new InputStreamReader(System.in)); } boolean hasNext() throws IOException{ String s; while (st == null || !st.hasMoreElements()){ if ((s = br.readLine())==null) return false; st = new StringTokenizer(s); } return true; } String next() throws IOException{ while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next()); }// Long.parseLong, Double.parseDouble, br.readLine } public static void main(String args[])throws IOException{ Reader cin = new Reader(); //Scanner cin = new Scanner(System.in); PrintWriter cout = new PrintWriter(System.out); //Scanner cin = new Scanner(new File("t.in")); //PrintWriter cout = new PrintWriter(new File("t.out")); // ***** cout.close() or cout.flush() is needed ***** // 2D array: int[][] a = new int[10][10]; // input, EOF, Graph int n = cin.nextInt(); // nextFloat, nextLine, next ArrayList<ArrayList<Integer>> G = new ArrayList<>(); for (int i=0; i<n; i++) G.add(new ArrayList<>()); while (cin.hasNext()){ // EOF int u = cin.nextInt(), v = cin.nextInt(); G.get(u).add(v); } // Math: E, PI, min, max, random(double 0~1), sin... // Collections(List a): swap(a,i,j), sort(a[,comp]), min(a), binarySearch(a,val[,comp]) // set Set<Integer> set = new TreeSet<>(); set.add(87); set.remove(87); if (!set.contains(87)) cout.println("no 87"); // map Map<String, Integer> map = new HashMap<>(); map.put("0", 1); map.put("2", 3); for ( Map.Entry<String,Integer> i : map.entrySet() ) cout.println(i.getKey() + " " + i.getValue() + " wry"); cout.println( map.get("1") ); // Big Number: TEN ONE ZERO, modInverse isProbablePrime modInverse modPow // add subtract multiply divide remainder, and or xor not shiftLeft shiftRight // queue: add, peek(==null), poll PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder()); Queue<Integer> q = new ArrayDeque<Integer>(); // stack: push, empty, pop Stack<Integer> s = new Stack<Integer>(); cout.close(); } } <file_sep>/contest/TTCPC2018/pE.cpp #include <bits/stdc++.h> using namespace std; char getc(){ static const int bufsize = 1<<16; static char B[bufsize], *S=B, *T=B; return (S==T&&(T=(S=B)+fread(B,1,bufsize,stdin),S==T)?0:*S++); } void input(int &a){ scanf("%d",&a); return; a=0; register char p; while ( (p=getc())<'-' ) if (p==0 || p==EOF) return; a=p^'0'; while ( (p=getc()) >= '0' ) a = a*10 + (p^'0'); } const int MAXN = 100005; const int LG = 18; int d[MAXN]; int h[MAXN]; int par[MAXN][LG]; int dp[MAXN][LG]; int n, m; int vis[MAXN]; vector<int> G[MAXN]; void init(){ input(n); for (int i=1, u, v; i<n; i++){ input(u); input(v); G[u].push_back(v); G[v].push_back(u); } for (int i=1; i<=n; i++) input(d[i]); memset(vis,0,sizeof(vis)); queue<int> que; que.push(1); vis[1]=1; par[1][0]=1; while ( que.size() ){ int u = que.front(); que.pop(); dp[u][0] = d[u]; for (int i=1; i<LG; i++){ par[u][i] = par[ par[u][i-1] ][i-1]; dp[u][i] = max(dp[u][i-1], dp[ par[u][i-1] ][i-1] ); } for (int v:G[u]){ if ( vis[v] ) continue; par[v][0]=u; h[v] = h[u]+1; vis[v]=1; que.push(v); } } } int main(){ //freopen("pE.in","r",stdin); int T; input(T); while (T--){ init(); for (int i=1; i<=n; i++) G[i].clear(); input(m); while (m--){ int u, v; input(u); input(v); int ans=(-1e9)-10; if (h[u]<h[v]) swap(u,v); // h[u] >= h[v] int dh = h[u]-h[v]; for (int i=LG-1; i>=0; i--){ if ( dh < (1<<i) )continue; dh -= (1<<i); ans = max( ans, dp[u][i] ); u = par[u][i]; } for (int i=LG-1; i>=0; i--){ if ( par[u][i] == par[v][i] ) continue; ans = max( ans, dp[u][i]); ans = max( ans, dp[v][i]); u = par[u][i]; v = par[v][i]; } if (u!=v) ans = max(ans, d[ par[u][0] ] ); ans = max(ans, d[ u ] ); ans = max(ans, d[ v ] ); printf("%d\n",ans); } } } /* 1 12 1 2 2 3 3 4 3 5 2 6 6 7 7 8 6 9 6 10 10 11 11 12 10 4 6 6 6 5 4 5 4 4 5 10 5 1 12 3 9 7 11 8 9 2 2 */ <file_sep>/contest/PTC1808/pA.cpp #include <bits/stdc++.h> using namespace std; int n; int cnt[105]; double cal(int a, int b, int c){ int i = cnt[a]; int j = cnt[b]-cnt[a]; int k = cnt[c]-cnt[b]; int l = n-cnt[c]; double sum=0; sum += fabs( n/4.0 - i ); sum += fabs( n/4.0 - j ); sum += fabs( n/4.0 - k ); sum += fabs( n/4.0 - l ); return sum; } int main(){ cin >> n; for (int i=0; i<n; i++){ int ai; scanf("%d", &ai); cnt[ai]++; } for (int i=1; i<105; i++) cnt[i] += cnt[i-1]; int a, b, c; double ans = 1e9; for (int i=0; i<=100; i++){ for (int j=i+1; j<=100; j++){ for (int k=j+1; k<100; k++){ double d = cal(i,j,k); if (d<ans){ ans = d; a=i; b=j; c=k; } } } } printf("%d %d %d\n", a, b, c); } <file_sep>/codebook/Math/Random.cpp inline int ran(){ static int x = 20167122; return x = (x * 0xdefaced + 1) & INT_MAX; } <file_sep>/contest/TOPC2018/pA.cpp #include <bits/stdc++.h> using namespace std; int main(){ cin.sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--){ string s; cin >> s; for (auto &c:s) { if ( 'A' <= c && c <= 'Z' ) c += 'z'-'Z'; } bool done=0; for (char c:s){ if (c=='n'){ puts("No"); done=1; break; } } for (int i=0; i<s.size() && !done; i++){ if ( i+1<s.size() ){ if ( s[i]=='a' && s[i+1]=='c' ){ puts("Yes"); done=1; break; } } if ( i+2<s.size() ){ if ( s[i]=='y' && s[i+1]=='e' && s[i+2]=='s'){ puts("Yes"); done=1; break; } } } if (!done) puts("Unknown"); } } <file_sep>/contest/2018_NCTU_Annual/pK.cpp #include <bits/stdc++.h> using namespace std; using LL = long long; inline LL myabs(LL x){ return max(x, -x); } LL ans = 1ll<<60; void solve(size_t idx, const vector<LL>& a, const vector<LL>& b){ LL x = a[idx]; size_t p = 0; for (size_t i=0; i<a.size(); i++) if(i != idx){ while (p+1 < b.size() && myabs(b[p+1]-x-a[i]) <= myabs(b[p]-x-a[i])) p++; ans = min(ans, myabs(b[p] - x - a[i])); } } int main(){ vector<LL> a; vector<LL> b; int n; scanf("%d", &n); for (int i=0; i<n; i++){ LL x; scanf("%lld", &x); if (x<0) b.push_back(-x); else a.push_back(x); } sort(a.begin(), a.end()); sort(b.begin(), b.end()); if (!a.size()){ cout <<b[0]+b[1]+b[2] <<'\n'; return 0; } if (!b.size()){ cout <<a[0]+a[1]+a[2] <<'\n'; return 0; } for (size_t i=0; i<a.size(); i++) solve(i, a, b); for (size_t i=0; i<b.size(); i++) solve(i, b, a); cout <<ans <<'\n'; } <file_sep>/codebook/Geometry/2Dpoint.cpp typedef double Double; struct Point { Double x,y; bool operator < (const Point &b)const{ //return tie(x,y) < tie(b.x,b.y); //return atan2(y,x) < atan2(b.y,b.x); assert(0 && "choose compare"); } Point operator + (const Point &b)const{ return {x+b.x,y+b.y}; } Point operator - (const Point &b)const{ return {x-b.x,y-b.y}; } Point operator * (const Double &d)const{ return {d*x,d*y}; } Point operator / (const Double &d)const{ return {x/d,y/d}; } Double operator * (const Point &b)const{ return x*b.x + y*b.y; } Double operator % (const Point &b)const{ return x*b.y - y*b.x; } friend Double abs2(const Point &p){ return p.x*p.x + p.y*p.y; } friend Double abs(const Point &p){ return sqrt( abs2(p) ); } }; typedef Point Vector; struct Line{ Point P; Vector v; bool operator < (const Line &b)const{ return atan2(v.y,v.x) < atan2(b.v.y,b.v.x); } }; <file_sep>/contest/WorldFinals2019/43WorldFinalsWorkstation-Team63/Desktop/AC/B.cpp #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; using LL = long double; struct Point{ long double x, y; Point operator - (const Point &b){ return {x-b.x, y-b.y}; } }; const int MAXN = 10004; const LL INF = 1e18; // enough or not? int n, H; LL alpha, beta; Point p[MAXN]; LL dp[MAXN]; void init(){ cin >> n >> H >> alpha >> beta; for (int i=1; i<=n; i++){ cin >> p[i].x >> p[i].y; } } inline LL Sqr(LL x){ return x*x; } inline LL dis(const Point &a, const Point &b){ return Sqr(a.x-b.x) + Sqr(a.y-b.x); } bool ok1(int l, int r){ LL d = (p[r].x - p[l].x) / 2; Point o{ p[l].x+d, H-d }; d = Sqr(d); for (int i=l; i<=r; i++){ if ( p[i].y > o.y && dis(p[i],o) > d ){ return false; } } return true; } inline LL w(int l, int r){ return alpha * (H - p[r].y) + beta * Sqr(p[r].x - p[l].x); } void solve1(){ dp[1] = alpha * ( H - p[1].y ); for (int i=2; i<=n; i++){ dp[i] = INF; for (int j=1; j<i; j++){ if ( ok1(j,i) ){ dp[i] = min( dp[i], dp[j] + w(j,i)); } } } if ( dp[n]==INF ) cout << "impossible" << endl; else cout << dp[n] << '\n'; } void solve(){ dp[1] = alpha * ( H - p[1].y ); for (int i=2; i<=n; i++){ dp[i] = INF; Point o {p[i].x, (long double)H}; LL gl = p[i].x - (H-p[i].y)*2, gr = p[i].x; for (int j=i-1; j>=1; j--){ Point v = p[j] - o; LL x = v.x; LL y = v.y; LL r[2] = { -(x+y), sqrtl(2*x*y) }; r[0] -= r[1]; r[1] = r[0] + 2*r[1]; LL lb = p[i].x - r[1] * 2; LL rb = p[i].x - r[0] * 2; if ( v.y < -r[0] ){ rb = p[i].x; } gl = max(gl,lb); gr = min(gr,rb); if ( gl<= p[j].x && p[j].x <=gr ){ dp[i] = min( dp[i], dp[j] + w(j,i)); } } } if ( dp[n]==INF ) cout << "impossible" << endl; else cout << (long long) roundl( dp[n] ) << '\n'; } int main(){ cin.tie(0); cin.sync_with_stdio(0); init(); solve(); } <file_sep>/contest/TOPC2018/genE.py print(511) for _ in range(511): print(511,end=' ') <file_sep>/codebook/String/smallest_rotation.cpp string mcp(string s){ int n = s.length(); s += s; int i=0, j=1; while (i<n && j<n){ int k = 0; while (k < n && s[i+k] == s[j+k]) k++; if (s[i+k] <= s[j+k]) j += k+1; else i += k+1; if (i == j) j++; } int ans = i < n ? i : j; return s.substr(ans, n); } Contact GitHub API Training Shop Blog About <file_sep>/codebook/Graph/planar.cpp //skydog #include <iostream> #include <cstdio> #include <cstdlib> #include <iomanip> #include <vector> #include <cstring> #include <string> #include <queue> #include <deque> #include <stack> #include <map> #include <set> #include <utility> #include <list> #include <cmath> #include <algorithm> #include <cassert> #include <bitset> #include <complex> #include <climits> #include <functional> using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<ll, ll> l4; #define mp make_pair #define pb push_back #define debug(x) cerr << #x << " = " << x << " " const int N=400+1; struct Planar { int n,m,hash[N],fa[N],deep[N],low[N],ecp[N]; vector<int> g[N],son[N]; set< pair<int,int> > SDlist[N],proots[N]; int nxt[N][2],back[N],rev[N]; deque<int> q; void dfs(int u) { hash[u]=1; q.pb(u); ecp[u]=low[u]=deep[u]; int v; for (int i = 0; i < g[u].size(); ++i) if(!hash[v=g[u][i]]) { fa[v]=u; deep[v]=deep[u]+1; dfs(v); low[u]=min(low[u],low[v]); SDlist[u].insert(mp(low[v],v)); } else ecp[u]=min(ecp[u],deep[v]); low[u]=min(low[u],ecp[u]); } int visited[N]; void addtree(int u,int t1,int v,int t2) { nxt[u][t1]=v; nxt[v][t2]=u; } void findnxt(int u,int v,int& u1,int& v1) { u1=nxt[u][v^1]; if(nxt[u1][0]==u) v1=0; else v1=1; } void walkup(int u,int v) { back[v]=u; int v1=v,v2=v,u1=1,u2=0,z; for (;;) { if(hash[v1]==u || hash[v2]==u) break; hash[v1]=u;hash[v2]=u; z=max(v1,v2); if(z>n) { int p=fa[z-n]; if(p!=u) { proots[p].insert(mp(-low[z-n], z)); v1=p,v2=p,u1=0,u2=1; } else break; } else { findnxt(v1,u1,v1,u1); findnxt(v2,u2,v2,u2); } } } int topstack; pair<int,int> stack[N]; int outer(int u,int v) { return ecp[v]<deep[u] || (SDlist[v].size() && SDlist[v].begin()->first<deep[u]); } int inside(int u,int v) { return proots[v].size()>0 || back[v]==u; } int active(int u,int v) { return inside(u,v) || outer(u,v); } void push(int a,int b) { stack[++topstack]=mp(a,b); } void mergestack() { int v1,t1,v2,t2,s,s1; v1=stack[topstack].first;t1=stack[topstack].second; topstack--; v2=stack[topstack].first;t2=stack[topstack].second; topstack--; s=nxt[v1][t1^1]; s1=(nxt[s][1]==v1); nxt[s][s1]=v2; nxt[v2][t2]=s; SDlist[v2].erase( make_pair(low[v1-n],v1-n) ); proots[v2].erase( make_pair(-low[v1-n],v1) ); } void findnxtActive(int u,int t,int& v,int& w1,int S) { findnxt(u,t,v,w1); while(u!=v && !active(S,v)) findnxt(v,w1,v,w1); } void walkdown(int S,int u) { topstack=0; int t1,v=S,w1,x2,y2,x1,y1,p; for(t1=0;t1<2;++t1) { findnxt(S,t1^1,v,w1); while(v!=S) { if(back[v]==u) { while(topstack>0) mergestack(); addtree(S,t1,v,w1); back[v]=0; } if(proots[v].size()) { push(v,w1); p=proots[v].begin()->second; findnxtActive(p,1,x1,y1,u); findnxtActive(p,0,x2,y2,u); if(active(u,x1) && !outer(u,x1)) v=x1,w1=y1; else if(active(u,x2) && !outer(u,x2)) v=x2,w1=y2; else if(inside(u,x1) || back[x1]==u) v=x1,w1=y1; else v=x2,w1=y2; push(p,v==x2); } else if(v>n || ( ecp[v]>=deep[u] && !outer(u,v) )) findnxt(v,w1,v,w1); else if(v<=n && outer(u,v) && !topstack) { addtree(S,t1,v,w1); break; } else break; } } } int work(int u) { int v; for (int i = 0; i < g[u].size(); ++i) if(fa[v=g[u][i]]==u) { son[u].push_back(n+v); proots[n+v].clear(); addtree(n+v,1,v,0); addtree(n+v,0,v,1); } for (int i = 0; i < g[u].size(); ++i) if(deep[v=g[u][i]]>deep[u]+1) walkup(u,v); topstack=0; for (int i = 0; i < son[u].size(); ++i) walkdown(son[u][i], u); for (int i = 0; i < g[u].size(); ++i) if(deep[v=g[u][i]]>deep[u]+1 && back[v]) return 0; return 1; } void init(int _n) { n = _n; m = 0; for(int i=1;i<=2*n;++i) { g[i].clear(); SDlist[i].clear(); son[i].clear(); proots[i].clear(); nxt[i][0]=nxt[i][1]=0; fa[i]=0; hash[i]=0;low[i]=ecp[i]=deep[i]=back[i]=0; q.clear(); } } void add(int u, int v) { ++m; g[u].pb(v); g[v].pb(u); } bool check_planar() { if(m>3*n-5) return false; // memset(hash,0,sizeof hash); for(int i=1;i<=n;++i) if(!hash[i]) { deep[i]=1; dfs(i); } memset(hash,0,sizeof hash); //memset(hash, 0, (2*n+1)*sizeof(hash[0])); // originally only looks at last n element assert(q.size() == n); while (!q.empty()) { if (!work(q.back())) return false; q.pop_back(); } return true; } } base, _new; vector<ii> edges; int n, m; inline void build(int n, Planar &_new) { _new.init(n); for (auto e : edges) _new.add(e.first, e.second); } void end() { puts("-1"); exit(0); } bool vis[N]; const int maxp = 5; int path[maxp], tp=0; void dfs(int cur) { vis[cur] = true; path[tp++] = cur; if (tp == maxp) { auto it = lower_bound(base.g[cur].begin(), base.g[cur].end(), path[0]); if ( it != base.g[cur].end() && *it == path[0]) { //a cycle int x = n+1; for (int i = 0; i < 5; ++i) edges.pb(mp(x, path[i])); build(x, _new); if (_new.check_planar()) { for (int i = 0; i < maxp; ++i) printf("%d%c", path[i], i==maxp-1?'\n':' '); exit(0); } for (int i = 0; i < 5; ++i) edges.pop_back(); } } else { for (auto e : base.g[cur]) if (!vis[e]) dfs(e); } vis[cur] = false; --tp; } int main() { scanf("%d %d", &n, &m); if (n <= 4) { assert(false); puts("0"); return 0; } for (int i = 0; i < m; ++i) { int u, v; scanf("%d %d", &u, &v); edges.pb(mp(u, v)); } build(n, base); if (!base.check_planar()) end(); for (int i = 1; i <= n; ++i) sort(base.g[i].begin(), base.g[i].end()); for (int i = 1; i <= n; ++i) dfs(i); end(); } <file_sep>/codebook/Graph/Dijkstra.py from heapq import * INF = 2*10**10000 t = input() for pp in range(t): n, m = map(int, raw_input().split()) g, d, q = [[] for _ in range(n+1)], [0] + [INF] * n, [(0, 0)] #for i in range(1, m): # a[i], b[i], c[i], l[i], o[i] = map(int, input().split()) for _ in range(m): u, v, c, l, o = map(int, raw_input().split()) g[u] += [(o, v, c, l)] while q: u = heappop(q)[1] for e in g[u]: k = d[u] / e[2] if k < 0: k = 0 else: k = k * e[3] t, v = d[u] + e[0] + k, e[1] if t < d[v]: d[v] = t heappush(q, (d[v], v)) print(d[n]) <file_sep>/codebook/DataStructure/Treap.cpp #include<bits/stdc++.h> using namespace std; template<class T,unsigned seed>class treap{ public: struct node{ T data; int size; node *l,*r; node(T d){ size=1; data=d; l=r=NULL; } inline void up(){ size=1; if(l)size+=l->size; if(r)size+=r->size; } inline void down(){ } }*root; inline int size(node *p){return p?p->size:0;} inline bool ran(node *a,node *b){ static unsigned x=seed; x=0xdefaced*x+1; unsigned all=size(a)+size(b); return (x%all+all)%all<size(a); } void clear(node *&p){ if(p)clear(p->l),clear(p->r),delete p,p=NULL; } ~treap(){clear(root);} void split(node *o,node *&a,node *&b,int k){ if(!k)a=NULL,b=o; else if(size(o)==k)a=o,b=NULL; else{ o->down(); if(k<=size(o->l)){ b=o; split(o->l,a,b->l,k); b->up(); }else{ a=o; split(o->r,a->r,b,k-size(o->l)-1); a->up(); } } } void merge(node *&o,node *a,node *b){ if(!a||!b)o=a?a:b; else{ if(ran(a,b)){ a->down(); o=a; merge(o->r,a->r,b); }else{ b->down(); o=b; merge(o->l,a,b->l); } o->up(); } } void build(node *&p,int l,int r,T *s){ if(l>r)return; int mid=(l+r)>>1; p=new node(s[mid]); build(p->l,l,mid-1,s); build(p->r,mid+1,r,s); p->up(); } inline int rank(T data){ node *p=root; int cnt=0; while(p){ if(data<=p->data)p=p->l; else cnt+=size(p->l)+1,p=p->r; } return cnt; } inline void insert(node *&p,T data,int k){ node *a,*b,*now; split(p,a,b,k); now=new node(data); merge(a,a,now); merge(p,a,b); } }; treap<int ,20141223>bst; int n,m,a,b; int main(){ //當成二分查找樹用 while(~scanf("%d",&a))bst.insert(bst.root,a,bst.rank(a)); while(~scanf("%d",&a))printf("%d\n",bst.rank(a)); bst.clear(bst.root); return 0; } <file_sep>/codebook/Geometry/circumcentre.cpp #include "2Dpoint.cpp" Point circumcentre(Point &p0, Point &p1, Point &p2){ Point a = p1-p0; Point b = p2-p0; Double c1 = abs2(a)*0.5; Double c2 = abs2(b)*0.5; Double d = a % b; Double x = p0.x + ( c1*b.y - c2*a.y ) / d; Double y = p0.y + ( c2*a.x - c1*b.x ) / d; return {x,y}; } <file_sep>/contest/2018_NCTU_Annual/pI.cpp #include <bits/stdc++.h> using namespace std; const long long MOD = 1e9+7; const int MAXN = 100005; int n; long long a[MAXN]; int root; vector<int> G[MAXN]; long long S_b[MAXN], CA_b[MAXN], CL_b[MAXN], SZ_b[MAXN]; long long S[MAXN], CA[MAXN], CL[MAXN], SZ[MAXN]; long long nor(long long x){ x%=MOD; if (x<0) x+=MOD; return x; } void init(){ scanf("%d", &n); for (int i=1; i<=n; i++) scanf("%lld", &a[i]); for (int i=1; i<n; i++){ int u, v; scanf("%d %d", &u, &v); G[u].push_back(v); G[v].push_back(u); } root = rand()%n+1; } void dfs_1(int u, int fa){ CL_b[u] = 1; SZ_b[u] = 1; CA_b[u] = a[u]; S_b[u] = 0; for (int v:G[u]) if (v!=fa) { dfs_1(v,u); CL_b[u] = nor( CL_b[u] + CL_b[v] + SZ_b[v] ); SZ_b[u] += SZ_b[v]; CA_b[u] = nor( CA_b[u] + CA_b[v] + a[u] * SZ_b[v] ); S_b[u] = nor( S_b[u] + S_b[v] + CA_b[v] + a[u]*CL_b[v] ); } } void dfs(int u, int fa){ for (int v:G[u]) if (v!=fa) { SZ[v] = n - SZ_b[v] + 1; CL[v] = nor( (CL[u] + SZ[u]) + (CL_b[u] -1 - CL_b[v] - SZ_b[v]) ); dfs(v,u); } } int main(){ init(); root=1; dfs_1(root,root); SZ[root] = 1; CL[root] = 1; CA[root] = a[u]; S[root] = 0; dfs(root,root); for (int i=1; i<=n; i++){ printf("%lld ", S_b[i]); } long long ans = 0; for (int i=1; i<=n; i++){ } cout << ans << '\n'; } <file_sep>/codebook/Graph/Matching/Kuhn_Munkres.cpp const int MAXN = 400 + 10; const long long INF64 = 0x3f3f3f3f3f3f3f3fll; int nl, nr; int pre[MAXN]; long long slack[MAXN]; long long W[MAXN][MAXN]; long long lx[MAXN], ly[MAXN]; int mx[MAXN], my[MAXN]; bool vx[MAXN], vy[MAXN]; void augment(int u) { if(!u) return; augment(mx[pre[u]]); mx[pre[u]] = u; my[u] = pre[u]; } void match(int x) { queue<int> que; que.push(x); while(1) { while(!que.empty()) { x = que.front(); que.pop(); vx[x] = 1; for (int i=1; i<=nr; i++) { if(vy[i]) continue; long long t = lx[x] + ly[i] - W[x][i]; if(t > 0) { if(slack[i] >= t) slack[i] = t, pre[i] = x; continue; } pre[i] = x; if(!my[i]) { augment(i); return; } vy[i] = 1; que.push(my[i]); } } long long t = INF64; for (int i=1; i<=nr; i++) if(!vy[i]) t = min(t, slack[i]); for (int i=1; i<=nl; i++) if(vx[i]) lx[i] -= t; for (int i=1; i<=nr; i++) { if(vy[i]) ly[i] += t; else slack[i] -= t; } for (int i=1; i<=nr; i++) { if(vy[i] || slack[i]) continue; if(!my[i]) { augment(i); return; } vy[i] = 1; que.push(my[i]); } } } int main() { int m; cin >> nl >> nr >> m; nr = max(nl, nr); while(m--) { int u, v; long long w; cin >> u >> v >> w; W[u][v] = w; lx[u] = max(lx[u], w); } for (int i=1; i<=nl; i++) { for (int x=1; x<=nl; x++) vx[x] = 0; for (int y=1; y<=nr; y++) vy[y] = 0, slack[y] = INF64; match(i); } long long ans = 0; for (int i=1; i<=nl; i++) ans += W[i][mx[i]]; cout << ans << '\n'; for (int i=1; i<=nl; i++) { if (i > 1) cout << ' '; cout << (W[i][mx[i]] ? mx[i] : 0); } cout << '\n'; } <file_sep>/codebook/Other/CppRandom.cpp void init(){ std::random_device rd; std::default_random_engine gen( rd() ); std::uniform_int_distribution <unsigned long long> dis(0,ULLONG_MAX); for (int i=0; i<MAXN; i++){ h[i] = dis(gen); } } <file_sep>/contest/PTC1803/pB.cpp #include <bits/stdc++.h> using namespace std; const int MOD = 1e9+7; const int MAXN = 100005; int n, a[MAXN]; vector<int> as; int bit[MAXN]; void add(int pos, int val){ while (pos<=n){ bit[pos] = (bit[pos]+val)%MOD; pos += (pos&(-pos)); } } int sum(int pos){ int re=0; while (pos>0){ re = (bit[pos]+re)%MOD; pos -= (pos&(-pos)); } return re; } void build(int a[], int dp[]){ memset(bit,0,sizeof(bit)); for (int i=0; i<n; i++){ dp[i]=0; dp[i] = ( dp[i] + sum(a[i]-1) )%MOD; add( a[i], (dp[i]+1)%MOD ); } } void init(){ as.clear(); scanf("%d", &n); for (int i=0; i<n; i++) scanf("%d", a+i); for (int i=0; i<n; i++) as.push_back(a[i]); sort(as.begin(),as.end()); for (int i=0; i<n; i++){ a[i] = lower_bound(as.begin(),as.end(),a[i])-as.begin()+1; } } int f[MAXN], g[MAXN]; void solve(){ build(a,f); reverse(a,a+n); build(a,g); reverse(g,g+n); int ans=0; for (int i=0; i<n; i++){ ans = (ans + (long long)f[i]*g[i]%MOD)%MOD; } printf("%d\n",ans); } int main(){ int T; cin >> T; while (T--){ init(); solve(); } } <file_sep>/codebook/Math/inverse.cpp const int MAXN = 1000006; int inv[MAXN]; void invTable(int bound, int p){ inv[1] = 1; for (int i=2; i<bound; i++){ inv[i] = (long long)inv[p%i] * (p-p/i) %p; } } int inv(int b, int p){ if (b==1) return 1; return (long long)inv(p%b,p) * (p-p/b) %p; } <file_sep>/codebook/Geometry/3D_ConvexHull.cpp // return the faces with pt indexes int flag[MXN][MXN]; struct Point{ ld x,y,z; Point operator - (const Point &b) const { return (Point){x-b.x,y-b.y,z-b.z}; } Point operator * (const ld &b) const { return (Point){x*b,y*b,z*b}; } ld len() const { return sqrtl(x*x+y*y+z*z); } ld dot(const Point &a) const { return x*a.x+y*a.y+z*a.z; } Point operator * (const Point &b) const { return (Point){y*b.z-b.y*z,z*b.x-b.z*x,x*b.y-b.x*y}; } }; Point ver(Point a, Point b, Point c) { return (b - a) * (c - a); } vector<Face> convex_hull_3D(const vector<Point> pt) { int n = SZ(pt); REP(i,n) REP(j,n) flag[i][j] = 0; vector<Face> now; now.push_back((Face){0,1,2}); now.push_back((Face){2,1,0}); int ftop = 0; for (int i=3; i<n; i++){ ftop++; vector<Face> next; REP(j, SZ(now)) { Face& f=now[j]; ld d=(pt[i]-pt[f.a]).dot(ver(pt[f.a], pt[f.b], pt[f.c])); if (d <= 0) next.push_back(f); int ff = 0; if (d > 0) ff=ftop; else if (d < 0) ff=-ftop; flag[f.a][f.b] = flag[f.b][f.c] = flag[f.c][f.a] = ff; } REP(j, SZ(now)) { Face& f=now[j]; if (flag[f.a][f.b] > 0 and flag[f.a][f.b] != flag[f.b][f.a]) next.push_back((Face){f.a,f.b,i}); if (flag[f.b][f.c] > 0 and flag[f.b][f.c] != flag[f.c][f.b]) next.push_back((Face){f.b,f.c,i}); if (flag[f.c][f.a] > 0 and flag[f.c][f.a] != flag[f.a][f.c]) next.push_back((Face){f.c,f.a,i}); } now=next; } return now; } <file_sep>/codebook/Other/IO_optimization.cpp #include <stdio.h> char getc(){ static const int bufsize = 1<<16; static char B[bufsize], *S=B, *T=B; return (S==T&&(T=(S=B)+fread(B,1,bufsize,stdin),S==T)?0:*S++); } template <class T> bool input(T& a){ a=(T)0; register char p; while ((p = getc()) < '-') if (p==0 || p==EOF) return false; if (p == '-') while ((p = getc()) >= '0') a = a*10 - (p^'0'); else { a = p ^ '0'; while ((p = getc()) >= '0') a = a*10 + (p^'0'); } return true; } template <class T, class... U> bool input(T& a, U&... b){ if (!input(a)) return false; return input(b...); } <file_sep>/codebook/Geometry/ConvexHull.cpp #include "2Dpoint.cpp" // retunr H, 第一個點會在 H 出現兩次 void ConvexHull(vector<Point> &P, vector<Point> &H){ int n = P.size(), m=0; sort(P.begin(),P.end()); H.clear(); for (int i=0; i<n; i++){ while (m>=2 && (P[i]-H[m-2]) % (H[m-1]-H[m-2]) <0)H.pop_back(), m--; H.push_back(P[i]), m++; } for (int i=n-2; i>=0; i--){ while (m>=2 && (P[i]-H[m-2]) % (H[m-1]-H[m-2]) <0)H.pop_back(), m--; H.push_back(P[i]), m++; } } <file_sep>/codebook/DataStructure/2D_RangeTree.cpp // remember sort x !!!!! typedef int T; const int LGN = 20; const int MAXN = 100005; struct Point{ T x, y; friend bool operator < (Point a, Point b){ return tie(a.x,a.y) < tie(b.x,b.y); } }; struct TREE{ Point pt; int toleft; }tree[LGN][MAXN]; struct SEG{ T mx, Mx; int sz; TREE *st; }seg[MAXN*4]; vector<Point> P; void build(int l, int r, int o, int deep){ seg[o].mx = P[l].x; seg[o].Mx = P[r].x; seg[o].sz = r-l+1;; if(l == r){ tree[deep][r].pt = P[r]; tree[deep][r].toleft = 0; seg[o].st = &tree[deep][r]; return; } int mid = (l+r)>>1; build(l,mid,o+o,deep+1); build(mid+1,r,o+o+1,deep+1); TREE *ptr = &tree[deep][l]; TREE *pl = &tree[deep+1][l], *nl = &tree[deep+1][mid+1]; TREE *pr = &tree[deep+1][mid+1], *nr = &tree[deep+1][r+1]; int cnt = 0; while(pl != nl && pr != nr) { *(ptr) = pl->pt.y <= pr->pt.y ? cnt++, *(pl++): *(pr++); ptr -> toleft = cnt; ptr++; } while(pl != nl) *(ptr) = *(pl++), ptr -> toleft = ++cnt, ptr++; while(pr != nr) *(ptr) = *(pr++), ptr -> toleft = cnt, ptr++; } int main(){ int n; cin >> n; for(int i = 0 ;i < n; i++){ T x,y; cin >> x >> y; P.push_back((Point){x,y}); } sort(P.begin(),P.end()); build(0,n-1,1,0); } <file_sep>/codebook/Other/Mo_algorithm.cpp int l = 0, r = 0, nowAns = 0, BLOCK_SIZE, n, m; int ans[]; struct QUE{ int l, r, id; friend bool operator < (QUE a, QUE b){ if(a.l / BLOCK_SIZE != b.l / BLOCK_SIZE) return a.l / BLOCK_SIZE < b.l / BLOCK_SIZE; return a.r < b.r; } }querys[]; inline void move(int pos, int sign) { // update nowAns } void solve() { BLOCK_SIZE = int(ceil(pow(n, 0.5))); sort(querys, querys + m); for (int i = 0; i < m; ++i) { const QUE &q = querys[i]; while (l > q.l) move(--l, 1); while (r < q.r) move(r++, 1); while (l < q.l) move(l++, -1); while (r > q.r) move(--r, -1); ans[q.id] = nowAns; } } <file_sep>/codebook/Other/python.py #!/usr/bin/env python3 # import import math from math import * import math as M from math import sqrt # input n = int( input() ) a = [ int(x) for x in input().split() ] # EOF while True: try: solve() except: break; # output print( x, sep=' ') print( ''.join( str(x)+' ' for x in a ) ) print( '{:5d}'.format(x) ) # sort a.sort() sorted(a) # list a = [ x for x in range(n) ] a.append(x) # Basic operator a, b = 10, 20 a/b # 0.5 a//b # 0 a%b # 10 a**b # 10^20 # if, else if, else if a==0: print('zero') elif a>0: print('postive') else: print('negative') # loop while a==b and b==c: for i in LIST: # stack # C++ stack = [3,4,5] stack.append(6) # push() stack.pop() # pop() stack[-1] # top() len(stack) # size() O(1) # queue # C++ from collections import deque queue = deque([3,4,5]) queue.append(6) # push() queue.popleft() # pop() queue[0] # front() len(queue) # size() O(1) # random from random import * randrange(L,R,step) # [L,R) L+k*step randint(L,R) # int from [L,R] choice(list) # pick 1 item from list choices(list,k) # pick k item shuffle(list) Uniform(L,R) # float from [L,R] # Decimal from fractions import Fraction from decimal import Decimal, getcontext getcontext().prec = 250 # set precision itwo = Decimal(0.5) two = Decimal(2) N = 200 def angle(cosT): """given cos(theta) in decimal return theta""" for i in range(N): cosT = ((cosT + 1) / two) ** itwo sinT = (1 - cosT * cosT) ** itwo return sinT * (2 ** N) pi = angle(Decimal(-1)) # file IO r = open("filename.in") a = r.read() # read whole content into one string w = open("filename.out", "w") w.write('123\n') # IO redirection import sys sys.stdin = open('filename.in') sys.stdout = open('filename.out', 'w') <file_sep>/codebook/Graph/Tarjan.cpp 割點 點 u 為割點 if and only if 滿足 1. or 2. 1. u 爲樹根,且 u 有多於一個子樹。 2. u 不爲樹根,且滿足存在 (u,v) 爲樹枝邊 (或稱父子邊,即 u 爲 v 在搜索樹中的父親),使得 DFN(u) <= Low(v)。 ------------------------------------------------------- 橋 一條無向邊 (u,v) 是橋 if and only if (u,v) 爲樹枝邊,且滿足 DFN(u) < Low(v)。 // 0 base struct TarjanSCC{ static const int MAXN = 1000006; int n, dfn[MAXN], low[MAXN], scc[MAXN], scn, count; vector<int> G[MAXN]; stack<int> stk; bool ins[MAXN]; void tarjan(int u){ dfn[u] = low[u] = ++count; stk.push(u); ins[u] = true; for(auto v:G[u]){ if(!dfn[v]){ tarjan(v); low[u] = min(low[u], low[v]); }else if(ins[v]){ low[u] = min(low[u], dfn[v]); } } if(dfn[u] == low[u]){ int v; do { v = stk.top(); stk.pop(); scc[v] = scn; ins[v] = false; } while(v != u); scn++; } } void getSCC(){ memset(dfn,0,sizeof(dfn)); memset(low,0,sizeof(low)); memset(ins,0,sizeof(ins)); memset(scc,0,sizeof(scc)); count = scn = 0; for(int i = 0 ; i < n ; i++ ){ if(!dfn[i]) tarjan(i); } } }SCC; <file_sep>/codebook/README.md # Codebook of team NCTU_Fox - [latest version PDF](https://drive.google.com/open?id=1BE3YoEIVL1873pOpBCTAezFNkn0LsXfo) ## Build ```bash make ``` ## Environment - xelatex ```bash sudo apt-get -y install texlive \ texlive-full \ gedit-latex-plugin \ texlive-fonts-recommended \ latex-beamer \ texpower \ texlive-pictures \ texlive-latex-extra \ texpower-examples \ imagemagick ``` - English font: Consolas ```bash cd ~/Desktop/ wget https://github.com/kakkoyun/linux.files/raw/master/fonts/Consolas.ttf sudo mkdir -p /usr/share/fonts/consolas sudo mv Consolas.ttf /usr/share/fonts/consolas/ sudo chmod 644 /usr/share/fonts/consolas/Consolas.ttf cd /usr/share/fonts/consolas sudo mkfontscale && sudo mkfontdir && sudo fc-cache -fv ``` - Chinese font: [思源黑體](https://www.beforafter.org/blog/source-han-sans-font) ```bash cd ~/Desktop/ wget https://noto-website.storage.googleapis.com/pkgs/NotoSansCJKtc-hinted.zip sudo unzip NotoSansCJKtc-hinted.zip -d /usr/share/fonts/Noto\ Sans\ CJK\ TC/ cd /usr/share/fonts/Noto\ Sans\ CJK\ TC/ sudo chmod 644 *.otf sudo mkfontscale && sudo mkfontdir && sudo fc-cache -fv ``` <file_sep>/contest/PTC1803/pC.cpp #include <bits/stdc++.h> using namespace std; int n, k; const int N = 5004; const long long MOD = 1e9+7; long long dp[N][N]; void build(){ dp[0][0] = 1; for (int i=1; i<N; i++){ for (int j=1; j<N; j++){ dp[i][j] = (dp[i][j-1]*i%MOD + dp[i-1][j-1]*(j+1-i)%MOD)%MOD; } } for (int i=1; i<N; i++){ for (int j=1; j<N; j++){ dp[i][j] = (dp[i][j] + dp[i-1][j])%MOD; } } } int main (){ build(); while (scanf("%d", &n) != EOF){ int q; scanf("%d", &q); while (q--){ scanf("%d", &k); printf("%lld ", dp[ min(k,n) ][n]); } printf("\n"); } } <file_sep>/codebook/Graph/SchreierSims.cpp // time: O(n^2 lg^3 |G| + t n lg |G|) // mem : O(n^2 lg |G| + tn) // t : number of generator namespace SchreierSimsAlgorithm{ typedef vector<int> Permu; Permu inv( const Permu& p ){ Permu ret( p.size() ); for( int i = 0; i < int(p.size()); i ++ ) ret[ p[ i ] ] = i; return ret; } Permu operator*( const Permu& a, const Permu& b ){ Permu ret( a.size() ); for( int i = 0 ; i < (int)a.size(); i ++ ) ret[ i ] = b[ a[ i ] ]; return ret; } typedef vector<Permu> Bucket; typedef vector<int> Table; typedef pair<int,int> pii; int n, m; vector<Bucket> bkts, bktsInv; vector<Table> lookup; int fastFilter( const Permu &g, bool addToG = 1 ){ n = bkts.size(); Permu p; for( int i = 0 ; i < n ; i ++ ){ int res = lookup[ i ][ p[ i ] ]; if( res == -1 ){ if( addToG ){ bkts[ i ].push_back( p ); bktsInv[ i ].push_back( inv( p ) ); lookup[ i ][ p[i] ] = (int)bkts[i].size()-1; } return i; } p = p * bktsInv[i][res]; } return -1; } long long calcTotalSize(){ long long ret = 1; for( int i = 0 ; i < n ; i ++ ) ret *= bkts[i].size(); return ret; } bool inGroup( const Permu &g ){ return fastFilter( g, false ) == -1; } void solve( const Bucket &gen, int _n ){ n = _n, m = gen.size(); // m perm[0..n-1]s {//clear all bkts.clear(); bktsInv.clear(); lookup.clear(); } for(int i = 0 ; i < n ; i ++ ){ lookup[i].resize(n); fill(lookup[i].begin(), lookup[i].end(), -1); } Permu id( n ); for(int i = 0 ; i < n ; i ++ ) id[i] = i; for(int i = 0 ; i < n ; i ++ ){ bkts[i].push_back(id); bktsInv[i].push_back(id); lookup[i][i] = 0; } for(int i = 0 ; i < m ; i ++) fastFilter( gen[i] ); queue< pair<pii,pii> > toUpd; for(int i = 0; i < n; i ++) for(int j = i; j < n; j ++) for(int k = 0; k < (int)bkts[i].size(); k ++) for(int l = 0; l < (int)bkts[j].size(); l ++) toUpd.push( {pii(i,k), pii(j,l)} ); while( !toUpd.empty() ){ pii a = toUpd.front().first; pii b = toUpd.front().second; toUpd.pop(); int res = fastFilter(bkts[a.first][a.second] * bkts[b.first][b.second]); if(res == -1) continue; pii newPair(res, (int)bkts[res].size() - 1); for(int i = 0; i < n; i ++) for(int j = 0; j < (int)bkts[i].size(); ++j){ if(i <= res) toUpd.push(make_pair(pii(i , j), newPair)); if(res <= i) toUpd.push(make_pair(newPair, pii(i, j))); } } } } <file_sep>/codebook/Math/Miller-Rabin.cpp typedef long long LL; inline LL bin_mul(LL a, LL n,const LL& MOD){ LL re=0; while (n>0){ if (n&1) re += a; a += a; if (a>=MOD) a-=MOD; n>>=1; } return re%MOD; } inline LL bin_pow(LL a, LL n,const LL& MOD){ LL re=1; while (n>0){ if (n&1) re = bin_mul(re,a,MOD); a = bin_mul(a,a,MOD); n>>=1; } return re; } bool is_prime(LL n){ //static LL sprp[3] = { 2LL, 7LL, 61LL}; static LL sprp[7] = { 2LL, 325LL, 9375LL, 28178LL, 450775LL, 9780504LL, 1795265022LL }; if (n==1 || (n&1)==0 ) return n==2; int u=n-1, t=0; while ( (u&1)==0 ) u>>=1, t++; for (int i=0; i<3; i++){ LL x = bin_pow( sprp[i]%n, u, n); if (x==0 || x==1 || x==n-1)continue; for (int j=1; j<t; j++){ x=x*x%n; if (x==1 || x==n-1)break; } if (x==n-1)continue; return 0; } return 1; } <file_sep>/contest/TTCPC2018/pB.cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 1000006; int n; long long w[MAXN], h[MAXN]; long long psum[MAXN]; int dp[MAXN]; int solve(int L, int R){ // [l,r] psum[L-1]=0; for (int i=L; i<=R; i++) psum[i] = psum[i-1] + w[i]; vector< pair<int,int> > que; // x, dp dp[L]=1; que.push_back( {L,dp[L]} ); for (int i=L+1; i<=R; i++){ if (psum[i-1]<=h[i]){ dp[i]=1; } else if ( w[i-1]>h[i] ){ dp[i]=dp[i-1]+1; } else { int l=L, r=i-1; while (l!=r){ int mid=(l+r)/2; if ( psum[i-1]-psum[mid-1] <= h[i] )r=mid; else l=mid+1; } l--; dp[i] = dp[l]+1; int idx = que.size()-1; while ( idx>0 && que[idx].first>=l ) idx--; if ( que[idx].first<l ) idx++; dp[i] = min( dp[i], que[idx].second+1); } while ( que.size() && que.back().second >= dp[i] ) que.pop_back(); que.push_back( {i,dp[i]} ); } if (R==n && w[R]==n) return 0; if (R==n || w[R]==n) return dp[R]; return dp[R]*2; } int main(){ cin >> n; for (int i=1; i<=n; i++) scanf("%lld %lld", &w[i], &h[i]); w[0]=-1; int cnt_seg=0; int last=1; for (int i=2; i<=n; i++){ if ( w[i] != w[i-1]+1 ){ cnt_seg += solve(last,i-1); last=i; } } cnt_seg += solve(last,n); cout << cnt_seg << '\n'; } /* 3 1 5 3 4 2 2 4 2 5 3 5 4 5 1 5 3 1 0 2 0 3 0 */ <file_sep>/codebook/Geometry/Smallest_Circle.cpp #include "circumcentre.cpp" pair<Point,Double> SmallestCircle(int n, Point _p[]){ Point *p = new Point[n]; memcpy(p,_p,sizeof(Point)*n); random_shuffle(p,p+n); Double r2=0; Point cen; for (int i=0; i<n; i++){ if ( abs2(cen-p[i]) <= r2)continue; cen = p[i], r2=0; for (int j=0; j<i; j++){ if ( abs2(cen-p[j]) <= r2)continue; cen = (p[i]+p[j])*0.5; r2 = abs2(cen-p[i]); for (int k=0; k<j; k++){ if ( abs2(cen-p[k]) <= r2)continue; cen = circumcentre(p[i],p[j],p[k]); r2 = abs2(cen-p[k]); } } } delete[] p; return {cen,r2}; } // auto res = SmallestCircle(,); <file_sep>/codebook/Graph/Flow/Min_Cost_Max_Flow.cpp // long long version typedef pair<long long, long long> pll; struct CostFlow { static const int MAXN = 350; static const long long INF = 1LL<<60; struct Edge { int to, r; long long rest, c; }; int n, pre[MAXN], preL[MAXN]; bool inq[MAXN]; long long dis[MAXN], fl, cost; vector<Edge> G[MAXN]; void init() { for ( int i = 0 ; i < MAXN ; i++) G[i].clear(); } void add_edge(int u, int v, long long rest, long long c) { G[u].push_back({v, (int)G[v].size(), rest, c}); G[v].push_back({u, (int)G[u].size()-1, 0, -c}); } pll flow(int s, int t) { fl = cost = 0; while (true) { fill(dis, dis+MAXN, INF); fill(inq, inq+MAXN, 0); dis[s] = 0; queue<int> que; que.push(s); while ( !que.empty() ) { int u = que.front(); que.pop(); inq[u] = 0; for ( int i = 0 ; i < (int)G[u].size() ; i++) { int v = G[u][i].to; long long w = G[u][i].c; if ( G[u][i].rest > 0 && dis[v] > dis[u] + w) { pre[v] = u; preL[v] = i; dis[v] = dis[u] + w; if (!inq[v]) { inq[v] = 1; que.push(v); } } } } if (dis[t] == INF) break; long long tf = INF; for (int v = t, u, l ; v != s ; v = u ) { u = pre[v]; l = preL[v]; tf = min(tf, G[u][l].rest); } for (int v = t, u, l ; v != s ; v = u ) { u = pre[v]; l = preL[v]; G[u][l].rest -= tf; G[v][G[u][l].r].rest += tf; } cost += tf * dis[t]; fl += tf; } return {fl, cost}; } } flow; <file_sep>/contest/ITSA2018/p2.cpp #include<bits/stdc++.h> using namespace std; string ins; vector<string> cmds; void init(){ cmds.clear(); getline(cin,ins); stringstream ss (ins); string s; while ( ss>>s )cmds.push_back(s); } long long dfs(){ string cmd = cmds.back(); cmds.pop_back(); if ( cmd[0]=='+' ){ long long y = dfs(); long long x = dfs(); return x+y; } else if ( cmd[0]=='-' ){ long long y = dfs(); long long x = dfs(); return x-y; } else if ( cmd[0]=='*' ){ long long y = dfs(); long long x = dfs(); return x*y; } else { long long x = stoi(cmd); return x; } } void solve(){ cout << dfs() << '\n'; } int main (){ int T; cin >> T; getline(cin,ins); for (int ncase=1; ncase<=T; ncase++){ init(); solve(); } } <file_sep>/contest/2018_NCTU_Annual/pL.cpp #include <bits/stdc++.h> using namespace std; int main(){ cin.tie(0); cin.sync_with_stdio(0); int T; cin >>T; while(T--){ long long a, b, c, d, e ,f ,g, h, i; cin >>a>>b>>c>>d>>e>>f>>g>>h>>i; cout << a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h <<' '; cout << a*e*i + b*f*g + c*d*h + c*e*g + b*d*i + a*f*h <<'\n'; } } <file_sep>/contest/PTC1809/pA.py sum = 0 while True: try: x = int(input()) if x==0: print(sum) sum=0 else: sum += x except: break; <file_sep>/contest/PTC1804/pC.cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 1000006; int n; vector<int> G[MAXN]; int h[MAXN]; int pre[MAXN]; void dfs(int u){ h[u]=0; for (int v:G[u]){ if (h[v]==-1) dfs(v); h[u] = max(h[u],h[v]+1); } } void dp(int u){ for (int i=0, mx=1; i<G[u].size(); i++){ int v = G[u][i]; pre[v] = max(pre[v],mx); mx = max(mx,h[v]+2); } for (int i=G[u].size()-1, mx=1; i>=0; i--){ int v = G[u][i]; pre[v] = max(pre[v],mx); mx = max(mx,h[v]+2); } for (int v:G[u]){ pre[v] = max(pre[v],pre[u]+1); dp(v); } } int main(){ int T; cin >> T; while (T--){ scanf("%d", &n); for (int i=1; i<n; i++){ int u, v; scanf("%d %d", &u, &v); G[u].push_back(v); } fill(h+1,h+1+n,-1); memset(pre,-1,sizeof(pre)); long long H=0; for (int i=1; i<=n; i++){ if (h[i]==-1) dfs(i); H += h[i]; } int root = max_element(h+1,h+1+n)-h; pre[root]=0; dp(root); long long R=0; for (int i=1; i<=n; i++){ R += max( h[i], pre[i]); } printf("%lld %lld\n",H,R); for (int i=1; i<=n; i++) G[i].clear(); } } <file_sep>/contest/PTC1809/README.md # PTC (2018/09/12) ## result ![result](./result.png)
13ec27cad87882a822790c7d23c7618410134ec0
[ "CMake", "Markdown", "Makefile", "Java", "Python", "C", "C++", "Shell" ]
129
C++
NCTU-PCCA/NCTU_Fox
f23aeb0df327feeb46634ff38dd0bb0c2505e21b
4423bcfdf452d101d1aeb6d52fa054f1e6bd2dae
refs/heads/master
<file_sep>package br.com.upperfinanceiro.RN; import br.com.upperfinanceiro.DAO.CategoriaDAO; import br.com.upperfinanceiro.model.Categoria; import br.com.upperfinanceiro.model.Usuario; import br.com.upperfinanceiro.util.DAOFactory; import java.util.List; public class CategoriaRN { private CategoriaDAO categoriaDAO; public CategoriaRN() { this.categoriaDAO = DAOFactory.criarCategoriaDAO(); } public List<Categoria> listar(Usuario usuario) { return this.categoriaDAO.listar(usuario); } public Categoria salvar(Categoria categoria) { Categoria pai = categoria.getPai(); //Verifica se a categoria tem um pai. if(pai == null) { String msg = "A Categoria "+ categoria.getDescricao() + " deve ter um pai definido!"; throw new IllegalArgumentException(msg); } // boolean mudouFator = pai.getFator() != categoria.getFator(); categoria.setFator(pai.getFator()); categoria = this.categoriaDAO.salvar(categoria); //Verifica se mudou de categoria (no caso de RECEITA para DESPESA). Muda só o fator da categoria atual. //Só entra no processo se for true. if (mudouFator) { //Carrega toda a estrutura, pois o objeto não vem com os 'filhos' carregados. categoria = this.carregar(categoria.getCodigo()); //Aplica a categoria e pega o fator da mesma. this.replicarFator(categoria, categoria.getFator()); } return categoria; } //Método para repassar a mudança de fator para todas as categorias da hierarquia abaixo da categoria alterada. private void replicarFator(Categoria categoria, int fator) { if(categoria.getFilhos() != null) { for (Categoria filho : categoria.getFilhos()) { filho.setFator(fator); this.categoriaDAO.salvar(filho); this.replicarFator(filho, fator); } } } public void excluir(Categoria categoria) { this.categoriaDAO.excluir(categoria); } //Realiza a exclusão por usuário. public void excluir(Usuario usuario) { List<Categoria> lista = this.listar(usuario); for (Categoria categoria : lista) { this.categoriaDAO.excluir(categoria); } } public Categoria carregar(Integer categoria) { return this.categoriaDAO.carregar(categoria); } public void salvarEstruturaPadrao(Usuario usuario) { Categoria despesas = new Categoria(null, usuario, "DESPESAS", -1); despesas = this.categoriaDAO.salvar(despesas); this.categoriaDAO.salvar(new Categoria(despesas, usuario, "Moradia", -1)); this.categoriaDAO.salvar(new Categoria(despesas, usuario, "Alimentação", -1)); this.categoriaDAO.salvar(new Categoria(despesas, usuario, "Roupas", -1)); this.categoriaDAO.salvar(new Categoria(despesas, usuario, "Transporte", -1)); this.categoriaDAO.salvar(new Categoria(despesas, usuario, "Cuidados Pessoais", -1)); this.categoriaDAO.salvar(new Categoria(despesas, usuario, "Educação", -1)); this.categoriaDAO.salvar(new Categoria(despesas, usuario, "Saúde", -1)); this.categoriaDAO.salvar(new Categoria(despesas, usuario, "Lazer", -1)); this.categoriaDAO.salvar(new Categoria(despesas, usuario, "Pagamentos", -1)); this.categoriaDAO.salvar(new Categoria(despesas, usuario, "Outros", -1)); Categoria receitas = new Categoria(null, usuario, "RECEITAS", 1); receitas = this.categoriaDAO.salvar(receitas); this.categoriaDAO.salvar(new Categoria(receitas, usuario, "Salário", 1)); this.categoriaDAO.salvar(new Categoria(receitas, usuario, "Extras", 1)); this.categoriaDAO.salvar(new Categoria(receitas, usuario, "Investimentos", 1)); this.categoriaDAO.salvar(new Categoria(receitas, usuario, "Prêmio", 1)); this.categoriaDAO.salvar(new Categoria(receitas, usuario, "Presente", 1)); this.categoriaDAO.salvar(new Categoria(receitas, usuario, "Outros", 1)); } } <file_sep>package br.com.upperfinanceiro.RN; import br.com.upperfinanceiro.DAO.UsuarioDAO; import br.com.upperfinanceiro.model.Usuario; import br.com.upperfinanceiro.util.DAOFactory; import java.util.List; public class UsuarioRN { private UsuarioDAO usuarioDAO; public UsuarioRN() { //Instância da propriedade DAO no construtor. this.usuarioDAO = DAOFactory.criarUsuarioDAO(); } public Usuario carregar(Integer codigo) { return this.usuarioDAO.carregar(codigo); } public Usuario buscarPorLogin(String login) { return this.usuarioDAO.buscarPorLogin(login); } public void salvar(Usuario usuario) { Integer codigo = usuario.getCodigo(); if(codigo == null || codigo == 0) { usuario.getPermissao().add("ROLE_USUARIO"); this.usuarioDAO.salvar(usuario); //Quando o usuário for registrado no sistema, já é criado a estrutura padrão de Categorias para ele. CategoriaRN categoriaRN = new CategoriaRN(); categoriaRN.salvarEstruturaPadrao(usuario); } else { this.usuarioDAO.atualizar(usuario); } } public void excluir(Usuario usuario) { CategoriaRN categoriaRN = new CategoriaRN(); //Quando o usuário for excluído, exclui as categorias que ele tinha também. categoriaRN.excluir(usuario); this.usuarioDAO.excluir(usuario); } public List<Usuario> listar() { return this.usuarioDAO.listar(); } } <file_sep># UPPER FINANCEIRO Sistema [Upper Gerenciador Financeiro Pessoal](http://www.upperfinanceiro.com.br). ###Notas * Versão 0.0.1 Betta em produção 18/03/2016. ---- &copy; 2016, [Todos os Direitos Reservados). Brasil. <file_sep>package br.com.upperfinanceiro.web; import br.com.upperfinanceiro.RN.LancamentoRN; import br.com.upperfinanceiro.model.Conta; import br.com.upperfinanceiro.model.Lancamento; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; @ManagedBean public class PrincipalBean { private List<Lancamento> listaAtehoje; private List<Lancamento> listaFuturos; @ManagedProperty(value = "#{contextoBean}") private ContextoBean contextoBean; public List<Lancamento> getListaAtehoje() { if (this.listaAtehoje == null) { Conta conta = this.contextoBean.getContaAtiva(); Calendar hoje = new GregorianCalendar(); LancamentoRN lancamentoRN = new LancamentoRN(); this.listaAtehoje = lancamentoRN.listar(conta, null, hoje.getTime()); } return this.listaAtehoje; } public List<Lancamento> getListaFuturos() { if (this.listaFuturos == null) { Conta conta = this.contextoBean.getContaAtiva(); Calendar amanha = new GregorianCalendar(); amanha.add(Calendar.DAY_OF_MONTH, 1); LancamentoRN lancamentoRN = new LancamentoRN(); this.listaFuturos = lancamentoRN.listar(conta, amanha.getTime(), null); } return listaFuturos; } public ContextoBean getContextoBean() { return contextoBean; } public void setContextoBean(ContextoBean contextoBean) { this.contextoBean = contextoBean; } } <file_sep>package br.com.upperfinanceiro.web; import br.com.upperfinanceiro.RN.ContaRN; import br.com.upperfinanceiro.model.Conta; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; @ManagedBean @RequestScoped public class ContaBean { private Conta selecionada = new Conta(); private List<Conta> lista = null; @ManagedProperty(value = "#{contextoBean}") private ContextoBean contextoBean; public String salvar() { //Atribui a conta o usuário que está logado, pois toda conta relaciona com um usuário. this.selecionada.setUsuario(this.contextoBean.getUsuarioLogado()); ContaRN contaRN = new ContaRN(); Conta conta = new Conta(); //Mensagem de Salvamento! FacesContext context = FacesContext.getCurrentInstance(); contaRN.salvar(this.selecionada); //mensagem estava dando problema na dialog //context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso!!", "Conta inserida!")); //"limpar" o formulário quando ele for recarregado. this.selecionada = new Conta(); //forçar a recarga da lista. this.lista = null; return null; } public String excluir() { ContaRN contaRN = new ContaRN(); //Obtém a conta selecionada e faz a exclusão. contaRN.excluir(this.selecionada); //"limpar" o formulário quando ele for recarregado. this.selecionada = new Conta(); //forçar a recarga da lista. this.lista = null; return null; } public String tornarFavorita() { ContaRN contaRN = new ContaRN(); contaRN.tornarFavorita(this.selecionada); this.selecionada = new Conta(); return null; } public Conta getSelecionada() { return selecionada; } public void setSelecionada(Conta selecionada) { this.selecionada = selecionada; } public List<Conta> getLista() { if (this.lista == null) { ContaRN contaRN = new ContaRN(); //Obtém uma instância do usuário conectado para consultar as suas contas. this.lista = contaRN.listar(this.contextoBean.getUsuarioLogado()); } return this.lista; } public ContextoBean getContextoBean() { return contextoBean; } public void setContextoBean(ContextoBean contextoBean) { this.contextoBean = contextoBean; } } <file_sep>package br.com.upperfinanceiro.DAO; import br.com.upperfinanceiro.model.Categoria; import br.com.upperfinanceiro.model.Usuario; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; public class CategoriaDAOHibernate implements CategoriaDAO { private Session session; public void setSession(Session session) { this.session = session; } @Override public Categoria salvar(Categoria categoria) { //Salvar a entidade categoria. O merge faz a 'fusão' da instância da categoria, uma vez que o Hibernate não permite 2 instância do mesmo obj. Categoria merged = (Categoria) this.session.merge(categoria); //Força a sincronização dos objetos em memória com o bd. this.session.flush(); //Remove da memória do Hibernate todos os objetos carregados. this.session.clear(); return merged; } @Override public void excluir(Categoria categoria) { //Como pode ocorrer a exclusão em cascata, temos que carregar todos pais filhos e netos para que se for preciso sejam excluídos. //Dessa forma todos os filhos e netos estarão carregados e a exclusão em cascata funcionará categoria = (Categoria) this.carregar(categoria.getCodigo()); this.session.delete(categoria); this.session.flush(); this.session.clear(); } @Override public Categoria carregar(Integer categoria) { return (Categoria) this.session.get(Categoria.class, categoria); } @SuppressWarnings("unchecked") @Override public List<Categoria> listar(Usuario usuario) { //Somente os primeiros níveis de categoria será carregado. Os demais será feito pelo relacionamento OneToMany dos filhos. String hql = "select c from Categoria c where c.pai is null and c.usuario = :usuario"; Query query = this.session.createQuery(hql); query.setInteger("usuario", usuario.getCodigo()); List<Categoria> lista = query.list(); return lista; } } <file_sep>package br.com.upperfinanceiro.model; import java.io.Serializable; import java.util.Date; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; @Entity public class Conta implements Serializable { @Id @GeneratedValue private Integer conta; /*Usuário é a chave estrangeira (muitas contas para um usuário). ManyToOne e JoinColumn carregará todos os dados do usuário quando a conta do mesmo for carregada. OnDelete exclui todas as contas do usuário se ele for excluído.*/ @ManyToOne @OnDelete(action = OnDeleteAction.CASCADE) @JoinColumn(nullable = false) private Usuario usuario; private String descricao; //Campo não pode ser nulo nem alterado posteriormente. @Column( nullable = false, updatable = false) private Date cadastro; private float saldoInicial; private boolean favorita; public Integer getConta() { return conta; } public void setConta(Integer conta) { this.conta = conta; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public Date getCadastro() { return cadastro; } public void setCadastro(Date cadastro) { this.cadastro = cadastro; } public float getSaldoInicial() { return saldoInicial; } public void setSaldoInicial(float saldoInicial) { this.saldoInicial = saldoInicial; } public boolean isFavorita() { return favorita; } public void setFavorita(boolean favorita) { this.favorita = favorita; } @Override public int hashCode() { int hash = 5; hash = 67 * hash + Objects.hashCode(this.conta); hash = 67 * hash + Objects.hashCode(this.usuario); hash = 67 * hash + Objects.hashCode(this.descricao); hash = 67 * hash + Objects.hashCode(this.cadastro); hash = 67 * hash + Float.floatToIntBits(this.saldoInicial); hash = 67 * hash + (this.favorita ? 1 : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Conta other = (Conta) obj; if (!Objects.equals(this.conta, other.conta)) { return false; } if (!Objects.equals(this.usuario, other.usuario)) { return false; } if (!Objects.equals(this.descricao, other.descricao)) { return false; } if (!Objects.equals(this.cadastro, other.cadastro)) { return false; } if (Float.floatToIntBits(this.saldoInicial) != Float.floatToIntBits(other.saldoInicial)) { return false; } if (this.favorita != other.favorita) { return false; } return true; } } <file_sep>package br.com.upperfinanceiro.web; import br.com.upperfinanceiro.RN.ContaRN; import br.com.upperfinanceiro.RN.UsuarioRN; import br.com.upperfinanceiro.model.Conta; import br.com.upperfinanceiro.model.Usuario; import java.io.Serializable; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.event.ValueChangeEvent; @ManagedBean @SessionScoped public class ContextoBean implements Serializable { //gerar serialVersionUID private int codigoContaAtiva = 0; //Obtém o login do usuário remoto e executa a carga desse usuário usando o método da classe UsuarioRN. public Usuario getUsuarioLogado() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext external = context.getExternalContext(); String login = external.getRemoteUser(); if (login != null) { UsuarioRN usuarioRN = new UsuarioRN(); return usuarioRN.buscarPorLogin(login); } return null; } //Fornece a conta ativa no momento. public Conta getContaAtiva() { Conta contaAtiva = null; //Se não tiver conta ativa, obtém a conta favorita do usuário logado, ou a primeira cadastrada. if (this.codigoContaAtiva == 0) { contaAtiva = this.getContaAtivaPadrao(); } else { ContaRN contaRN = new ContaRN(); contaAtiva = contaRN.carregar(this.codigoContaAtiva); } if (contaAtiva != null) { this.codigoContaAtiva = contaAtiva.getConta(); return contaAtiva; } return null; } //Lógica para determinar qual será a conta padrão. private Conta getContaAtivaPadrao() { ContaRN contaRN = new ContaRN(); Conta contaAtiva = null; //Pega o usuário logado. Usuario usuario = this.getUsuarioLogado(); //Seta pra contaAtiva a conta favorita. contaAtiva = contaRN.buscarFavorita(usuario); //Se o usuário não tive nenhuma conta ativa, ele coloca por padrão a primeira. if (contaAtiva == null) { List<Conta> contas = contaRN.listar(usuario); if (contas != null && contas.size() > 0) { //Seta a primeira conta da lista como padrão. contaAtiva = contas.get(0); } } return contaAtiva; } //Método para exibir os itens do comboBox public void changeContaAtiva(ValueChangeEvent event) { this.codigoContaAtiva = (Integer) event.getNewValue(); } } <file_sep>package br.com.upperfinanceiro.RN; import br.com.upperfinanceiro.DAO.ContaDAO; import br.com.upperfinanceiro.model.Conta; import br.com.upperfinanceiro.model.Usuario; import br.com.upperfinanceiro.util.DAOFactory; import java.util.Date; import java.util.List; public class ContaRN { private ContaDAO contaDAO; public ContaRN() { this.contaDAO = DAOFactory.criarContaDAO(); } //Lista de todas as contas de um determinado uauário. public List<Conta> listar(Usuario usuario) { return this.contaDAO.listar(usuario); } public Conta carregar(Integer conta) { return this.contaDAO.carregar(conta); } public void salvar(Conta conta) { //define a data atual para data de cadastro conta.setCadastro(new Date()); this.contaDAO.salvar(conta); } public void excluir(Conta conta) { this.contaDAO.excluir(conta); } //Busca a conta bancária que ficará imediatamente ativa no sistema. public Conta buscarFavorita(Usuario usuario) { return this.contaDAO.buscarFavorita(usuario); } //Registrar uma determinada conta como favorita, somente uma. public void tornarFavorita(Conta contaFavorita) { //Obtém a conta favorita atual Conta conta = this.buscarFavorita(contaFavorita.getUsuario()); if (conta != null) { //Seta a conta favorita atual como false e salva. conta.setFavorita(false); this.contaDAO.salvar(conta); } //Marca a conta recebida no parâmetro (que será a nova favorita) como true e salva. contaFavorita.setFavorita(true); this.contaDAO.salvar(conta); } } <file_sep>package br.com.upperfinanceiro.model; import java.io.Serializable; import java.util.List; import java.util.Objects; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ForeignKey; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import org.hibernate.annotations.OrderBy; @Entity public class Categoria implements Serializable { @Id @GeneratedValue private Integer codigo; @ManyToOne //Atributo name refere ao nome da coluna da tabela e o 2º name refere ao nome da fk. @JoinColumn(name = "categoria_pai", nullable = true, foreignKey = @ForeignKey(name = "fk_categoria_categoria")) private Categoria pai; @ManyToOne @JoinColumn(name = "usuario", foreignKey = @ForeignKey(name = "fk_categoria_usuario")) @OnDelete(action = OnDeleteAction.CASCADE) private Usuario usuario; private String descricao; private int fator; //Carregar a lista de categorias filhas. EAGER faz a carga imediata no momento da consulta. REMOVE excluirá os filhos caso a categoria pai for excluída. @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.REMOVE) //Carregar todas as categorias cujo o campo 'name' seja igual o cod. da categoria atual. @JoinColumn(name = "categoria_pai", updatable = false) //Especifica a ordenação para os filhos. @OrderBy(clause = "descricao asc") private List<Categoria> filhos; public Categoria() { } //Construtor completo para criar as categorias padrão do sistema. public Categoria(Categoria pai, Usuario usuario, String descricao, int fator) { this.pai = pai; this.usuario = usuario; this.descricao = descricao; this.fator = fator; } public Integer getCodigo() { return codigo; } public void setCodigo(Integer codigo) { this.codigo = codigo; } public Categoria getPai() { return pai; } public void setPai(Categoria pai) { this.pai = pai; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public int getFator() { return fator; } public void setFator(int fator) { this.fator = fator; } public List<Categoria> getFilhos() { return filhos; } public void setFilhos(List<Categoria> filhos) { this.filhos = filhos; } @Override public int hashCode() { int hash = 7; hash = 53 * hash + Objects.hashCode(this.codigo); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Categoria other = (Categoria) obj; if (!Objects.equals(this.codigo, other.codigo)) { return false; } return true; } } <file_sep>package br.com.upperfinanceiro.util; import br.com.upperfinanceiro.DAO.CategoriaDAO; import br.com.upperfinanceiro.DAO.CategoriaDAOHibernate; import br.com.upperfinanceiro.DAO.ChequeDAO; import br.com.upperfinanceiro.DAO.ChequeDAOHibernate; import br.com.upperfinanceiro.DAO.ContaDAO; import br.com.upperfinanceiro.DAO.ContaDAOHibernate; import br.com.upperfinanceiro.DAO.LancamentoDAO; import br.com.upperfinanceiro.DAO.LancamentoDAOHibernate; import br.com.upperfinanceiro.DAO.UsuarioDAO; import br.com.upperfinanceiro.DAO.UsuarioDAOHibernate; //Classe construtora de DAOs. Único ponto onde as classes DAOs devem ser instanciadas public class DAOFactory { public static UsuarioDAO criarUsuarioDAO() { UsuarioDAOHibernate usuarioDAOH = new UsuarioDAOHibernate(); usuarioDAOH.setSession(HibernateUtil.getSessionFactory().getCurrentSession()); return usuarioDAOH; } public static ContaDAO criarContaDAO() { ContaDAOHibernate contaDAOH = new ContaDAOHibernate(); contaDAOH.setSession(HibernateUtil.getSessionFactory().getCurrentSession()); return contaDAOH; } public static CategoriaDAO criarCategoriaDAO() { CategoriaDAOHibernate categoriaDAOH = new CategoriaDAOHibernate(); categoriaDAOH.setSession(HibernateUtil.getSessionFactory().getCurrentSession()); return categoriaDAOH; } public static LancamentoDAO criarLancamentoDAO() { LancamentoDAOHibernate lancamentoDAOH = new LancamentoDAOHibernate(); lancamentoDAOH.setSession(HibernateUtil.getSessionFactory().getCurrentSession()); return lancamentoDAOH; } public static ChequeDAO criarChequeDAO() { ChequeDAOHibernate chequeDAO = new ChequeDAOHibernate(); chequeDAO.setSession(HibernateUtil.getSessionFactory().getCurrentSession()); return chequeDAO; } } <file_sep>package br.com.upperfinanceiro.model; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; //Indica que a classe é um objeto e não precisa de um identificador próprio @Embeddable public class ChequeId implements Serializable { private static final long serialVersionUID = 1L; //Essa tag indica que essa propriedade é obrigatória @Basic @Column(name = "cheque", nullable = false) private Integer cheque; @Basic(optional = false) @Column(name = "conta", nullable = false) private Integer conta; /*Construtor vazio é obrigatório quando se cria um construtor que recebe parametros, pois quando criamos um construtor com parametros o padrão deixa de existir*/ public ChequeId() { } //Construtor para facilitar a criação de uma instancia da classe public ChequeId(Integer cheque, Integer conta) { this.cheque = cheque; this.conta = conta; } public Integer getCheque() { return cheque; } public void setCheque(Integer cheque) { this.cheque = cheque; } public Integer getConta() { return conta; } public void setConta(Integer conta) { this.conta = conta; } } <file_sep>package br.com.upperfinanceiro.util; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; //Configura o tipo de requisição web que a classe Filter vai interceptar @WebFilter(urlPatterns = {"*.jsf"}) public class ConexaoHibernateFilter implements Filter { private SessionFactory sf; //Método é executado quando o aplicativo é colocado no ar. public void init(FilterConfig config) throws ServletException { //Criação do sessionFactory, que cria todas as sessões do Hibernate a cada requisição. this.sf = HibernateUtil.getSessionFactory(); } //Método onde toda requisição web pode ser interceptada public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException { Session currentSession = this.sf.getCurrentSession(); Transaction transaction = null; try { //Iniciando uma transação de banco de dados. transaction = currentSession.beginTransaction(); //Processamento é passado adiante, para a execução normal. Se não executar essa linha a requisição não será lançada. chain.doFilter(servletRequest, servletResponse); //Conclui a transação do banco dando commit nos dados. transaction.commit(); //Se a sessão estiver aberta fecha a sessão. if (currentSession.isOpen()) { currentSession.close(); } } catch (Throwable ex) { //Se qualquer erro for lançado no processamento o catch trata o(s) erro(s) e da um rollback na transação. try { if(transaction.isActive()) { transaction.rollback(); } } catch (Throwable t) { t.printStackTrace(); } throw new ServletException(ex); } } //É executado quando o aplicativo web é desativado ou o Tomcat é retirado do ar. public void destroy(){} }
5e4af1f27636f95a2c6a7ff842613ef5d6f7bc99
[ "Markdown", "Java" ]
13
Java
luishmnascimento/upperfinanceiro
88441fa0cbbf2fc0769e2d4a085bbf0076e1c544
e2fd016b459b9df58927ca8b61f20a8a0d790996
refs/heads/main
<file_sep>// // CategoryDetailTableViewController.swift // Tasty-Recipe // // Created by user196689 on 7/7/21. // import UIKit class CategoryDetailTableViewController: UITableViewController { var recipes : [Recipe] = [] let manager = Manager() @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var categoryTitle: UINavigationItem! override func viewDidLoad() { super.viewDidLoad() let recipeCell = UINib.init(nibName: "RecipeCell", bundle: nil) self.tableView.register(recipeCell, forCellReuseIdentifier: "RecipeCell") self.clearsSelectionOnViewWillAppear = true } override func viewDidAppear(_ animated: Bool) { // fetch category choice from category table view let categoryChoice = UserDefaults.standard.string(forKey: "categoryChoice")! self.categoryTitle.title = categoryChoice // find recipes by category from firebase manager.loadRecipeByCategory(category: categoryChoice ){ recipesCategoryArray in self.recipes = recipesCategoryArray if(self.recipes.count != 0){ self.backgroundView.frame = CGRect(x: 0, y: 0, width: 0, height: 0) // delete background view } self.tableView.reloadData() } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return recipes.count } func openRecipe(index: Int){ UserDefaults.standard.set(self.recipes[index].name, forKey: "name") UserDefaults.standard.set(self.recipes[index].id, forKey: "recipeId") UserDefaults.standard.set(self.recipes[index].timeInMinutes, forKey: "timeInMinutes") UserDefaults.standard.set(self.recipes[index].serving, forKey: "serving") UserDefaults.standard.set(self.recipes[index].image, forKey: "image") UserDefaults.standard.set(self.recipes[index].category, forKey: "category") UserDefaults.standard.set(self.recipes[index].ingredients, forKey: "ingredients") UserDefaults.standard.set(self.recipes[index].instructions, forKey: "instructions") UserDefaults.standard.set(self.recipes[index].levelOfCooking, forKey: "levelOfCooking") } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 260 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { openRecipe(index: indexPath.section) navigationController?.navigationBar.backgroundColor = .white // go to recipe detail view controller self.performSegue(withIdentifier: "RecipeDetailSegueC", sender: self) self.modalPresentationStyle = .fullScreen } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeCell", for: indexPath) as! RecipeCell cell.setUpCell(recipe: self.recipes[indexPath.section]) return cell } } <file_sep>// // LoginSignUpViewController.swift // Tasty-Recipe // // Created by user196689 on 6/29/21. // import UIKit class LoginSignUpViewController: UIViewController { //UI view properties @IBOutlet weak var dontHaveAccountLabel: CustomLabel! @IBOutlet weak var loginButton: CustomButton! @IBOutlet weak var signupButton: CustomButton! @IBOutlet weak var TastyLabel: CustomLabel! //first loading func override func viewDidLoad() { super.viewDidLoad() setUpProperties() } func setUpProperties(){ signupButton.makeCustomWhiteButton() TastyLabel.setSpacing(space: 1.75) } //hides the status bar override var prefersStatusBarHidden: Bool { return true } } <file_sep># Tasty-Recipe Tasty App is an app for exchanging recipes and sharing recipes between cooks. The application was build as part of a final project for IOS course. The application is written in Swift (using storyboard), and uses FireStore and Storage for real time database. In this app you can upload, and watch all recipes and search for them by category and name. Also, you can add you favorite recipe in your recipes favorites. ## ScreenShots ### Main Page <img src="https://user-images.githubusercontent.com/57193219/126903498-07918999-b03f-4db3-aba4-8723e0b4ba47.png" width="350" height="700"> ## Login <img src="https://user-images.githubusercontent.com/57193219/126903499-df3f88fd-85be-46af-97eb-f79edca36864.png" width="350" height="700"> ## Sign Up <img src="https://user-images.githubusercontent.com/57193219/126903501-12662220-8022-4953-b5f6-d1f83236c5d3.png" width="350" height="700"> ## Home Page <img src="https://user-images.githubusercontent.com/57193219/126903513-dc954b4b-4042-4f9c-b133-effb36b86977.png" width="350" height="700"> ## Recipe Details <img src="https://user-images.githubusercontent.com/57193219/126903527-b8e01412-f9a4-43ad-babb-cff96c977635.png" width="350" height="700"> <img src="https://user-images.githubusercontent.com/57193219/126903530-ff75094b-e339-432c-8eb9-c68ad8dece62.png" width="350" height="700"> ## Categories <img src="https://user-images.githubusercontent.com/57193219/126903516-7c91435a-b78d-4f20-bffc-1d97c9c741f4.png" width="350" height="700"> ## Watch Recipes by category <img src="https://user-images.githubusercontent.com/57193219/126903517-bc48b276-bbbe-4956-93fc-72d4ba21e25c.png" width="350" height="700"> ## add new Recipe <img src="https://user-images.githubusercontent.com/57193219/126903521-336301de-8b2b-4ff2-8c84-bb36fae0c1b3.png" width="350" height="700"> ## favorites Page <img src="https://user-images.githubusercontent.com/57193219/126903523-02487995-e8df-4047-8869-2eaf47618b5e.png" width="350" height="700"> <file_sep>// // CustomNavigationController.swift // Tasty-Recipe // // Created by user196689 on 6/30/21. // import UIKit class CustomNavigationController: UINavigationController { //first loadng func override func viewDidLoad() { super.viewDidLoad() makeBarInvisable() } func makeBarInvisable(){ navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() navigationBar.isTranslucent = true } } <file_sep>// // FavoritesTableViewController.swift // Tasty-Recipe // // Created by user196689 on 6/30/21. // import UIKit import Firebase import FirebaseFirestore class FavoritesTableViewController: UITableViewController { @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var errorLabel: CustomLabel! var recipes : [Recipe] = [] let manager = Manager() var empty = "0" var remove = "0" override func viewDidLoad() { navigationController?.navigationBar.backgroundColor = .white super.viewDidLoad() // init recipe cell let recipeCell = UINib.init(nibName: "RecipeCell", bundle: nil) self.tableView.register(recipeCell, forCellReuseIdentifier: "RecipeCell") self.clearsSelectionOnViewWillAppear = true } override func viewDidAppear(_ animated: Bool) { manager.loadFavorites() { favoritesArray in self.recipes = favoritesArray if(self.recipes.count != 0){ self.backgroundView.frame = CGRect(x: 0, y: 0, width: 0, height: 0) } self.tableView.reloadData() } } // refresh the table view @IBAction func refreshTableTapped(_ sender: Any) { empty = UserDefaults.standard.string(forKey: "isEmpty")! remove = UserDefaults.standard.string(forKey: "remove")! if(empty == "1" && remove == "1"){// if there is only one recipe anf it is removed self.backgroundView.frame = CGRect(x: 0, y: 0, width: 414, height: 696) }else{ manager.loadFavorites() { favoritesArray in self.recipes = favoritesArray if(self.recipes.count != 0){ self.backgroundView.frame = CGRect(x: 0, y: 0, width: 0, height: 0) } self.tableView.reloadData() } } } /* func openRecipe(index: Int){ UserDefaults.standard.set(self.recipes[index].name, forKey: "name") UserDefaults.standard.set(self.recipes[index].timeInMinutes, forKey: "timeInMinutes") UserDefaults.standard.set(self.recipes[index].serving, forKey: "serving") UserDefaults.standard.set(self.recipes[index].image, forKey: "image") UserDefaults.standard.set(self.recipes[index].category, forKey: "category") UserDefaults.standard.set(self.recipes[index].ingredients, forKey: "ingredients") UserDefaults.standard.set(self.recipes[index].instructions, forKey: "instructions") UserDefaults.standard.set(self.recipes[index].levelOfCooking, forKey: "levelOfCooking") }*/ // MARK: - Table view data source } extension FavoritesTableViewController{ override func numberOfSections(in tableView: UITableView) -> Int { if(self.empty == "1" && self.remove == "1"){// if there is only one recipe anf it is removed recipes = [] } return recipes.count } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { /*navigationController?.navigationBar.backgroundColor = .white self.performSegue(withIdentifier: "RecipeDetailSegueF", sender: self) openRecipe(index: indexPath.section)*/ } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeCell", for: indexPath) as! RecipeCell cell.setUpCell(recipe: self.recipes[indexPath.section]) return cell } } <file_sep>// // AppIconSerice.swift // Tasty-Recipe // // Created by user196689 on 7/12/21. // import Foundation import UIKit class AppIconService{ let application = UIApplication.shared func changeAppIcon(){ application.setAlternateIconName("AppIcons") } } <file_sep>// // CustomTextField.swift // Tasty-Recipe // // Created by user196689 on 6/30/21. // import UIKit class CustomTextField: UITextField { //first loading func override init(frame: CGRect) { super.init(frame: frame) defaultSetUp() } //first required required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) defaultSetUp() } func defaultSetUp() { //textfields layer.borderColor = UIColor(red: 169/255, green: 169/255, blue: 169/255, alpha: 1).cgColor layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0) layer.borderWidth = 1 layer.cornerRadius = layer.frame.height/2 layer.masksToBounds = true } } <file_sep>// // CategoryTableViewController.swift // Tasty-Recipe // // Created by user196689 on 6/30/21. // import UIKit import Firebase class CategoryTableViewController: UITableViewController { let items = Constants.categories override func viewDidLoad() { super.viewDidLoad() self.tableView.reloadData() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let categoryCell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath) as! CategoryCell categoryCell.categoryLabel.text = items[indexPath.row] categoryCell.categoryLabel.font = categoryCell.categoryLabel.font.withSize(28) return categoryCell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 120 } // call out category tapped, to category detail table view override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { navigationController?.navigationBar.backgroundColor = .white UserDefaults.standard.setValue(items[indexPath.row], forKey: "categoryChoice") } } <file_sep>// // NetworkProcessor.swift // Tasty-Recipe // // Created by user196689 on 7/4/21. // import Foundation class NetworkProcessor{ lazy var configuraiton = URLSessionConfiguration.default lazy var session = URLSession(configuration: configuraiton) var url : URL? init(url : URL) { self.url = url } typealias JSONDownloader = ((Codable?)-> Void) typealias IMAGEDATADownloader = ((Data?, HTTPURLResponse?, Error?)-> Void) //Download Image Data func downloadImage(_ completion : @escaping IMAGEDATADownloader ){ guard let imageUrl = self.url else { return } let imageRequest = URLRequest(url: imageUrl) let imageDataTask = session.dataTask(with: imageRequest) { (imageData, imageResponse, imageError) in if imageError == nil { guard let response = imageResponse as? HTTPURLResponse else {return} switch response.statusCode { case 200: guard let data = imageData else {return} completion(data, nil, nil ) default: return } }else { print("Error downloading Image: \(imageError.debugDescription)") completion(nil, nil, imageError!) } } imageDataTask.resume() } } <file_sep>// // HomeTableViewController.swift // Tasty-Recipe // // Created by user196689 on 6/30/21. // import UIKit import Firebase import FirebaseFirestore class HomeTableViewController: UITableViewController, UISearchBarDelegate { @IBOutlet var table: UITableView! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var LogOutButton: UIBarButtonItem! @IBOutlet weak var SearchButton: UIBarButtonItem! @IBOutlet weak var errorLabel: CustomLabel! @IBOutlet weak var backgroundView: UIView! var recipes : [Recipe] = [] var currentRecipes: [Recipe] = [] let manager = Manager() static var recipeCollectionRef: CollectionReference! var names : [String] = [] override func viewDidLoad() { navigationController?.navigationBar.backgroundColor = .white super.viewDidLoad() // init recipe cell let recipeCell = UINib.init(nibName: "RecipeCell", bundle: nil) self.tableView.register(recipeCell, forCellReuseIdentifier: "RecipeCell") //set up search bar setUpSearchBar() alterLayout() self.clearsSelectionOnViewWillAppear = true } override func viewDidAppear(_ animated: Bool) { manager.loadData() { recipesArray in self.recipes = recipesArray if(self.recipes.count != 0){ self.backgroundView.frame = CGRect(x: 0, y: 0, width: 0, height: 0) } self.currentRecipes = self.recipes self.tableView.reloadData() for recipe in self.recipes{ self.names.append(recipe.name!) } } } private func alterLayout(){ table.tableHeaderView = UIView() table.estimatedSectionHeaderHeight = 50 navigationItem.titleView = searchBar searchBar.placeholder = "Search By Name" } private func setUpSearchBar(){ searchBar.delegate = self } // search for recipes and show them inthe table view func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard !searchText.isEmpty else{ currentRecipes = recipes table.reloadData() return } currentRecipes = recipes.filter({ recipe -> Bool in return recipe.name!.lowercased().contains(searchText.lowercased()) }) table.reloadData() } // log out from user @IBAction func LogOutButtonTapped(_ sender: Any) { UserDefaults.standard.set("", forKey: "id") let storyboard :UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let loginSignUpNC = storyboard.instantiateViewController(withIdentifier: "MainNavController") as! UINavigationController loginSignUpNC.modalPresentationStyle = .fullScreen self.present(loginSignUpNC, animated: true, completion: nil) let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return currentRecipes.count } func openRecipe(index: Int){ UserDefaults.standard.set(self.currentRecipes[index].name, forKey: "name") UserDefaults.standard.set(self.currentRecipes[index].id, forKey: "recipeId") UserDefaults.standard.set(self.currentRecipes[index].timeInMinutes, forKey: "timeInMinutes") UserDefaults.standard.set(self.currentRecipes[index].serving, forKey: "serving") UserDefaults.standard.set(self.currentRecipes[index].image, forKey: "image") UserDefaults.standard.set(self.currentRecipes[index].category, forKey: "category") UserDefaults.standard.set(self.currentRecipes[index].ingredients, forKey: "ingredients") UserDefaults.standard.set(self.currentRecipes[index].instructions, forKey: "instructions") UserDefaults.standard.set(self.currentRecipes[index].levelOfCooking, forKey: "levelOfCooking") } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 260 } // go to recipe detail view controller, with user defaults including recipe information override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { navigationController?.navigationBar.backgroundColor = .white self.performSegue(withIdentifier: "RecipeDetailH", sender: self) openRecipe(index: indexPath.section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // show recipe cell let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeCell", for: indexPath) as! RecipeCell cell.setUpCell(recipe: self.currentRecipes[indexPath.section]) return cell } // once tpped enter, hide keyboard func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { self.searchBar.endEditing(true) } } <file_sep>// // RecipeCell.swift // Tasty-Recipe // // Created by user196689 on 6/30/21. // import UIKit class RecipeCell: UITableViewCell { @IBOutlet weak var recipeNameLabel: UILabel! @IBOutlet weak var recipeImage: UIImageView! @IBOutlet weak var timetocookLabel: UILabel! @IBOutlet weak var levelOfCookingLabel: UILabel! @IBOutlet weak var servingLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() selectionStyle = .none } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setUpCell(recipe: Recipe){ loadImage(recipe: recipe) recipeNameLabel.text! = recipe.name! servingLabel.text! = String(recipe.serving!) + " people" timetocookLabel.text! = String(recipe.timeInMinutes!) + " min" levelOfCookingLabel.text! = recipe.levelOfCooking! } //show imageUI after converting the url image func loadImage(recipe: Recipe){ var downloadedImage = UIImage() guard let imageString = recipe.image else{return} guard let imageURL = URL(string: imageString) else {return} let imageProcessor = NetworkProcessor(url: imageURL) imageProcessor.downloadImage{ (data,response, error) in DispatchQueue.main.async { guard let imageData = data else {return} downloadedImage = UIImage(data: imageData)! self.recipeImage.image = downloadedImage } } } } <file_sep>// // LoginViewController.swift // Tasty-Recipe // // Created by user196689 on 6/30/21. // import UIKit import FirebaseAuth import FirebaseFirestore class LoginViewController: UIViewController , UITextFieldDelegate{ //UI view properties @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var paasswordTextField: UITextField! @IBOutlet weak var topConstraint: NSLayoutConstraint! @IBOutlet weak var loginButton: CustomButton! @IBOutlet weak var errorLabel: CustomLabel! let manager = Manager() //first load func override func viewDidLoad() { super.viewDidLoad() setUpProperties() } func setUpProperties(){ navigationController?.navigationBar.layer.frame.origin.y = 22 // hide error label errorLabel.alpha = 0 paasswordTextField.isSecureTextEntry = true } //pops current view controller @IBAction func backButtonTapped(_ sender: Any) { navigationController?.popViewController(animated: true) } //hides the status bar override var prefersStatusBarHidden: Bool { return true } // login button tapped @IBAction func LoginButtonTapped(_ sender: Any) { // validate text fields let error = validateFields() if (error != nil){ showError(error!) } //create clean version of the text fields let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) let password = paasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) //login to the firestore Auth.auth().signIn(withEmail: email, password: password) { result, error in if (error != nil){ self.showError(error!.localizedDescription) }else { self.transitionToTabBar() UserDefaults.standard.setValue(result!.user.uid, forKey: "id") } } } // go to main tabbar func transitionToTabBar(){ let tapbarController = storyboard?.instantiateViewController(identifier: Constants.Stroyboard.tapbar) view.window?.rootViewController = tapbarController } func showError(_ message:String) { errorLabel.text = message errorLabel.alpha = 1 } //validate te fields and check if the data is correct-> returns nil, else, returns nil. func validateFields() -> String?{ if( emailTextField.text?.trimmingCharacters(in: .whitespaces) == "" || paasswordTextField.text?.trimmingCharacters(in: .whitespaces) == ""){ return "Please fill in all fields" } return nil }} // textfield slides up extension LoginViewController { func textFieldDidBeginEditing(_ textField: UITextField) { topConstraint.constant = CGFloat(40) navigationController?.navigationBar.isHidden = true } func textFieldDidEndEditing(_ textField: UITextField) { topConstraint.constant = CGFloat(101) } // handle enter tapped func textFieldShouldReturn(_ textField: UITextField) -> Bool { navigationController?.navigationBar.isHidden = false switch textField { case self.emailTextField: self.paasswordTextField.becomeFirstResponder() default: self.paasswordTextField.resignFirstResponder() } textField.resignFirstResponder() return true } } <file_sep>// // CustomLabel.swift // Tasty-Recipe // // Created by user196689 on 6/29/21. // import UIKit class CustomLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) defaultSetUp() } //first required to load required init?(coder aDecoder: NSCoder ) { super.init(coder: aDecoder) defaultSetUp() } func defaultSetUp(){ //label spacing let labelSpace = 1 let labelAttributeString = NSMutableAttributedString(string: text!) labelAttributeString.addAttribute(NSAttributedString.Key.kern, value: labelSpace, range: NSMakeRange(0, labelAttributeString.length)) attributedText = labelAttributeString } //sets the spacing of text func setSpacing(space: CGFloat){ let labelAttributeString = NSMutableAttributedString(string: text!) labelAttributeString.addAttribute(NSAttributedString.Key.kern, value: space, range: NSMakeRange(0, labelAttributeString.length)) attributedText = labelAttributeString } } <file_sep>// // CustomColor.swift // Tasty-Recipe // // Created by user196689 on 6/29/21. // import Foundation import UIKit struct CustomColor { let orange: UIColor! init(withFrame: CGRect){ orange = UIColor(red: 255/255, green: 140/255, blue: 43/255, alpha: 1) } func getOrangeColor() -> UIColor { return orange } } <file_sep>// // RecipeIndregientsCell.swift // Tasty-Recipe // // Created by user196689 on 7/6/21. // import UIKit class RecipeIngredientsCell: UITableViewCell { @IBOutlet weak var IngredientsLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } func setUpCell(ingredients: String){ let setuptext = SetUpTextView() IngredientsLabel.attributedText = setuptext.setUpText(ingredients) IngredientsLabel.sizeToFit() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } <file_sep>// // Recipe.swift // Tasty-Recipe // // Created by user196689 on 7/4/21. // import Foundation struct Recipe{ var name: String? var id: String? var levelOfCooking: String? var category: String? var timeInMinutes: Int? var ingredients: String? var image:String? var instructions:String? var serving:Int? init(name: String,id: String, levelOfCooking: String, category: String,timeInMinutes: Int, ingredients: String, image:String,instructions:String,serving:Int){ self.name = name self.id = id self.levelOfCooking = levelOfCooking self.category = category self.timeInMinutes = timeInMinutes self.ingredients = ingredients self.image = image self.instructions = instructions self.serving = serving } init(){ } } <file_sep>// // SignUpViewController.swift // Tasty-Recipe // // Created by user196689 on 6/30/21. // import UIKit import FirebaseAuth import FirebaseFirestore class SignUpViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var topConstraint: NSLayoutConstraint! @IBOutlet weak var nameTextField: CustomTextField! @IBOutlet weak var emailTextField: CustomTextField! @IBOutlet weak var passwordTextField: CustomTextField! @IBOutlet weak var signUpButton: CustomButton! @IBOutlet weak var errorLabel: CustomLabel! //first loading func override func viewDidLoad() { super.viewDidLoad() errorLabel.alpha = 0 passwordTextField.isSecureTextEntry = true } //pops current view controller @IBAction func backButtonTapped(_ sender: Any) { navigationController?.popViewController(animated: true) } //hides the status bar override var prefersStatusBarHidden: Bool { return true } //validate te fields and check if the data is correct-> returns nil, else, returns nil. func validateFields() -> String?{ if(nameTextField.text?.trimmingCharacters(in: .whitespaces) == "" || emailTextField.text?.trimmingCharacters(in: .whitespaces) == "" || passwordTextField.text?.trimmingCharacters(in: .whitespaces) == ""){ return "Please fill in all fields" } return nil } @IBAction func signUpTapped(_ sender: Any) { //validate the fields let error = validateFields() if (error != nil){ showError(error!) }else { //validate the fields without white spaces let name = nameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) // create user Auth.auth().createUser(withEmail: email, password: <PASSWORD>) { result, err in //check for errors if (err != nil) { self.showError("Error Creating User") } else { let db = Firestore.firestore() db.collection("users").document(result!.user.uid).setData( ["id": result!.user.uid,"name":name,"uid": result!.user.uid, "favorites": []] ) UserDefaults.standard.setValue(result!.user.uid, forKey: "id") self.transitionToTabBar() } } } } // go to main tabbar func transitionToTabBar(){ let tapbarController = storyboard?.instantiateViewController(identifier: Constants.Stroyboard.tapbar) view.window?.rootViewController = tapbarController } func showError(_ message:String) { errorLabel.text = message errorLabel.alpha = 1 } } extension SignUpViewController { // wile typing, put view up func textFieldDidBeginEditing(_ textField: UITextField) { navigationController?.navigationBar.isHidden = true topConstraint.constant = CGFloat(10) } func textFieldDidEndEditing(_ textField: UITextField) { topConstraint.constant = CGFloat(100) } // after enter return view to normal func textFieldShouldReturn(_ textField: UITextField) -> Bool { navigationController?.navigationBar.isHidden = false self.switchBasedNextTextField(textField) topConstraint.constant = CGFloat(100) return true } // handle enter tapped private func switchBasedNextTextField(_ textField: UITextField) { switch textField { case self.nameTextField: self.emailTextField.becomeFirstResponder() case self.emailTextField: self.passwordTextField.becomeFirstResponder() default: self.passwordTextField.resignFirstResponder() } } } <file_sep>// // CategoryCell.swift // Tasty-Recipe // // Created by user196689 on 7/12/21. // import UIKit class CategoryCell: UITableViewCell { @IBOutlet weak var categoryLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } <file_sep>// // Manager.swift // Tasty-Recipe // // Created by user196689 on 7/7/21. // import Foundation import FirebaseFirestore import UIKit class Manager{ var recipeCollectionRef: CollectionReference! // add recipe to favorites fiels in user collection func loadRecipeToFavorites(recipe: Recipe){ let id = UserDefaults.standard.string(forKey: "id")! Firestore.firestore().collection("users").document(id).updateData(["favorites": FieldValue.arrayUnion([recipe.id!])]) } // check if the recipe in user favorites array func loadFavoriteStatus(recipe: Recipe,_ callback:@escaping ((Bool) -> Void)){ var flag: Bool = false let id = UserDefaults.standard.string(forKey: "id")! Firestore.firestore().collection("users").document(id).getDocument(){ snapshot, error in let array : [String] = snapshot!.get("favorites") as! [String] if(array.contains(recipe.id!)){ RunLoop.main.perform{ flag = true callback(flag) } }else{ RunLoop.main.perform{ flag = false callback(flag) } } } } // load favorites recipes from the user collection func loadFavorites(_ callback:@escaping (([Recipe]) -> Void)){ let id = UserDefaults.standard.string(forKey: "id")! var favoritesArray = [Recipe]() favoritesArray = [] Firestore.firestore().collection("users").document(id).getDocument(){ snapshot, error in let array : [String] = snapshot!.get("favorites") as! [String] for item in array{ Firestore.firestore().collection("recipes").document(item).getDocument{document,error in if(document == nil){ }else{ let name = document?.get("name") as! String let levelOfCooking = document?.get("levelOfCooking") as! String let category = document?.get("category") as! String let timeInMinutes = document?.get("timeInMinutes") as! Int let ingredients = document?.get("ingredients") as! String let image = document?.get("image") as! String let instructions = document?.get("instructions") as! String let serving = document?.get("serving") as! Int let recipeId = document?.get("id") as! String let recipe = Recipe(name: name,id: recipeId ,levelOfCooking: levelOfCooking, category: category, timeInMinutes: timeInMinutes, ingredients: ingredients, image: image, instructions: instructions, serving: serving) favoritesArray.append(recipe) } if(favoritesArray.count == 1){ UserDefaults.standard.set(1, forKey: "isEmpty") } else{ UserDefaults.standard.set(0, forKey: "isEmpty") } RunLoop.main.perform{ callback(favoritesArray) } } } } } // delete recipe id from favorites field in user collection func removeRecipeFromFavorites(recipe: Recipe){ let id = UserDefaults.standard.string(forKey: "id")! Firestore.firestore().collection("users").document(id).updateData(["favorites": FieldValue.arrayRemove([recipe.id!])]) { err in if let err = err { print("Error updating document: \(err)") } else { print("Document successfully updated") } } } // load recipe by given category func loadRecipeByCategory(category: String,_ callback:@escaping (([Recipe]) -> Void)) { var recipesCategoryArray = [Recipe]() recipeCollectionRef = Firestore.firestore().collection("recipes") recipeCollectionRef.whereField("category", isEqualTo: category ).getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { for document in querySnapshot!.documents { let recipe = self.loadRecipeFromDocument(document: document) recipesCategoryArray.append(recipe) if(recipesCategoryArray.count == querySnapshot!.count){ RunLoop.main.perform{ callback(recipesCategoryArray) } } } } } } // load each recipe information func loadRecipeFromDocument(document: QueryDocumentSnapshot) -> Recipe{ let name = document.get("name") as! String let levelOfCooking = document.get("levelOfCooking") as! String let category = document.get("category") as! String let timeInMinutes = document.get("timeInMinutes") as! Int let ingredients = document.get("ingredients") as! String let image = document.get("image") as! String let instructions = document.get("instructions") as! String let serving = document.get("serving") as! Int let recipeId = document.get("id") as! String let recipe = Recipe(name: name,id: recipeId ,levelOfCooking: levelOfCooking, category: category, timeInMinutes: timeInMinutes, ingredients: ingredients, image: image, instructions: instructions, serving: serving) return recipe } // load recipes from firebase from "recipes" collection func loadData(_ callback:@escaping (([Recipe]) -> Void)) { var recipesArray = [Recipe]() recipeCollectionRef = Firestore.firestore().collection("recipes") recipeCollectionRef.getDocuments { snapshot, error in if let err = error{ print("error fetching docs\(err)") } else{ guard let snap = snapshot else {return} for document in snapshot!.documents{ let recipe = self.loadRecipeFromDocument(document: document) recipesArray.append(recipe) if(recipesArray.count == snap.count){ RunLoop.main.perform{ callback(recipesArray) } } } } } } } <file_sep>// // RecipeInstructionsCell.swift // Tasty-Recipe // // Created by user196689 on 7/6/21. // import UIKit class RecipeInstructionsCell: UITableViewCell { @IBOutlet weak var instructionsLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } func setUpCell(instructions: String){ let setuptext = SetUpTextView() instructionsLabel.attributedText = setuptext.setUpText(instructions) instructionsLabel.sizeToFit() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } <file_sep>// // Constans.swift // Tasty-Recipe // // Created by user196689 on 7/3/21. // import Foundation struct Constants{ struct Stroyboard { static let loginViewController = "LoginVC" static let signupViewController = "SignUpVC" static let tapbar = "TapBarVC" } static let categories = ["APPETIZER","MAIN DISH", "DESSERT", "PASTA", "SOUP"] } <file_sep>// // RecipeDescriptionCell.swift // Tasty-Recipe // // Created by user196689 on 7/6/21. // import UIKit class RecipeDescriptionCell: UITableViewCell { var currentRecipe = Recipe() let manager = Manager() @IBOutlet weak var recipeImageDes: UIImageView! @IBOutlet weak var recipeLevelOfCookingDes: UILabel! @IBOutlet weak var recipeTimetoCookDes: UILabel! @IBOutlet weak var recipeServingDes: UILabel! @IBOutlet weak var heartButton: UIButton! override func awakeFromNib() { super.awakeFromNib() heartButton.imageEdgeInsets = UIEdgeInsets(top: 30,left: 30,bottom: 30,right: 30) heartButton.frame = CGRect(x: 0, y:0, width: 30, height: 30) } // heart button tapped @IBAction func handleMarkAsFavorite(_ sender: Any) { manager.loadFavoriteStatus(recipe: currentRecipe){ flag in self.manager.loadRecipeToFavorites(recipe: self.currentRecipe) if(!flag){ //paint red UserDefaults.standard.set(0, forKey: "remove") self.heartButton.setImage(UIImage(named: "ic_favorites_orange.png"), for: .normal) self.manager.loadRecipeToFavorites(recipe: self.currentRecipe) self.reloadInputViews() }else{ //paint gray self.heartButton.setImage(UIImage(named: "ic_favorites_grey.png"), for: .normal) //if recipes.count == 1, remove and put no recipes yet view UserDefaults.standard.set(1, forKey: "remove") self.manager.removeRecipeFromFavorites(recipe: self.currentRecipe) self.reloadInputViews() } } } func setUpCell(_ recipe:Recipe){ currentRecipe = recipe loadImage(recipe: recipe) self.recipeLevelOfCookingDes.text = recipe.levelOfCooking self.recipeServingDes.text = String(recipe.serving!) + " People" self.recipeTimetoCookDes.text = String(recipe.timeInMinutes!) + " min" //check if recipe is added to favorites manager.loadFavoriteStatus(recipe: currentRecipe) { flag in if(flag){ // the heart is orange self.heartButton.setImage(UIImage(named: "ic_favorites_orange.png"), for: .normal) }else{ // the heart is white self.heartButton.setImage(UIImage(named: "ic_favorites_grey.png"), for: .normal) } } } func loadImage(recipe: Recipe){ var downloadedImage = UIImage() guard let imageString = recipe.image else{return} guard let imageURL = URL(string: imageString) else {return} let imageProcessor = NetworkProcessor(url: imageURL) imageProcessor.downloadImage{ (data,response, error) in DispatchQueue.main.async { guard let imageData = data else {return} downloadedImage = UIImage(data: imageData)! self.recipeImageDes.image = downloadedImage } } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: true) } } <file_sep>// // RecipeDetailViewController.swift // Tasty-Recipe // // Created by user196689 on 7/6/21. // import UIKit class RecipeDetailViewController: UIViewController { var recipe : Recipe? var name = "" var image = "" var ingredients = "" var instructions = "" var levelOfCooking = "" var category = "" var serving = 0 var timeInMinutes = 0 var recipeId = "" let manager = Manager() var headers = ["Description", "Ingredients", "Instructions"] @IBOutlet weak var tbl: UITableView! override func viewDidLoad() { super.viewDidLoad() self.modalPresentationStyle = .fullScreen self.tabBarController?.tabBar.barTintColor = .white // fetch recipe information from open recipe func self.name = UserDefaults.standard.string(forKey: "name")! self.image = UserDefaults.standard.string(forKey: "image")! self.ingredients = UserDefaults.standard.string(forKey: "ingredients")! self.instructions = UserDefaults.standard.string(forKey: "instructions")! self.levelOfCooking = UserDefaults.standard.string(forKey: "levelOfCooking")! self.category = UserDefaults.standard.string(forKey: "category")! self.serving = UserDefaults.standard.integer(forKey: "serving") self.timeInMinutes = UserDefaults.standard.integer(forKey: "timeInMinutes") self.recipeId = UserDefaults.standard.string(forKey: "recipeId")! // create recipe recipe = Recipe(name: self.name, id: recipeId, levelOfCooking: self.levelOfCooking, category: self.category, timeInMinutes: self.timeInMinutes, ingredients: self.ingredients, image: self.image, instructions: self.instructions, serving: self.serving) //init cells tbl.register(UINib.init(nibName: "RecipeDescriptionCell", bundle: nil), forCellReuseIdentifier: "RecipeDescriptionCell") tbl.register(UINib.init(nibName: "RecipeIngredientsCell", bundle: nil), forCellReuseIdentifier: "RecipeIngredientsCell") tbl.register(UINib.init(nibName: "RecipeInstructionsCell", bundle: nil), forCellReuseIdentifier: "RecipeInstructionsCell") tbl.dataSource = self tbl.delegate = self } @IBAction func backButtonTapped(_ sender: Any) { navigationController?.popViewController(animated: true) } } extension RecipeDetailViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return headers.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 350 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() if (headers[indexPath.section].contains("Description")){ //invoke recipe description cell let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeDescriptionCell") as! RecipeDescriptionCell cell.setUpCell(recipe!) cell.selectionStyle = .none; return cell } if(headers[indexPath.section].contains("Ingredients")){ //invoke recipe ingredients cell let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeIngredientsCell") as! RecipeIngredientsCell cell.setUpCell(ingredients: (recipe?.ingredients!)!) cell.selectionStyle = .none; return cell } if(headers[indexPath.section].contains("Instructions")){ //invoke recipe instructions cell let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeInstructionsCell") as! RecipeInstructionsCell cell.setUpCell(instructions: (recipe?.instructions!)!) cell.selectionStyle = .none; return cell } return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50.0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: CGRect(x: 0, y: 0, width: tbl.frame.size.width, height: 50)) view.backgroundColor = UIColor(red: 255/255, green: 213/255, blue: 128/255, alpha: 1) let titleLabel = UILabel(frame: view.frame) titleLabel.textColor = .black titleLabel.textAlignment = .center //put recipe name in description header if(headers[section].contains("Description")){ titleLabel.text = recipe?.name }else{ titleLabel.text = headers[section] } view.addSubview(titleLabel) return view } } extension RecipeDetailViewController: UITableViewDelegate{ } <file_sep>// // setUpTextView.swift // Tasty-Recipe // // Created by user196689 on 7/25/21. // import Foundation import UIKit struct SetUpTextView{ init() { } // put spacing between lines func setUpText(_ line: String) -> NSMutableAttributedString{ let attributedString = NSMutableAttributedString(string: line) // *** Create instance of `NSMutableParagraphStyle` let paragraphStyle = NSMutableParagraphStyle() // *** set LineSpacing property in points *** paragraphStyle.lineSpacing = 5 // Whatever line spacing you want in points // *** Apply attribute to string *** attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length)) return attributedString } } <file_sep>// // NewRecipeTableViewController.swift // Tasty-Recipe // // Created by user196689 on 7/4/21. // import UIKit import Firebase class NewRecipeTableViewController: UITableViewController,UITextFieldDelegate, UITextViewDelegate { let db = Firebase.Firestore.firestore() let storage = Firebase.Storage.storage().reference() @IBOutlet weak var ingredientsTextView: UITextView! @IBOutlet weak var nameTextField: CustomTextField! @IBOutlet weak var servingTextField: CustomTextField! @IBOutlet weak var instructionsTextView: UITextView! @IBOutlet weak var timeInMinTextField: CustomTextField! @IBOutlet weak var newImageSelect: UIImageView! @IBOutlet weak var uploadImageButton: CustomButton! @IBOutlet weak var createNewRecipeButton: CustomButton! @IBOutlet weak var segmentedCategories: UISegmentedControl! @IBOutlet weak var segmentedLevelOfCooking: UISegmentedControl! @IBOutlet weak var errorLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() uploadImageButton.makeCustomWhiteButton() errorLabel.alpha = 0 //init default segmentes options self.segmentedLevelOfCooking.selectedSegmentIndex = 0 self.segmentedCategories.selectedSegmentIndex = 0 self.nameTextField.delegate = self self.ingredientsTextView.delegate = self self.servingTextField.delegate = self self.instructionsTextView.delegate = self self.timeInMinTextField.delegate = self defaultSetUpTextView(textview: instructionsTextView) defaultSetUpTextView(textview: ingredientsTextView) } // creates new recipe document after create tapped @IBAction func createNewRecipeTapped(_ sender: Any) { let error = fieldsAreFilled() if(error != nil){ errorLabel.text = error errorLabel.alpha = 1 }else{ // creates new recipe document let id = UUID().uuidString let name = nameTextField.text let categories = Constants.categories let category = categories[self.segmentedCategories.selectedSegmentIndex] let ingredients = ingredientsTextView.text let instructions = instructionsTextView.text let levels = ["EASY" ,"MIDDLE", "HARD"] let levelOfCooking = levels[self.segmentedLevelOfCooking.selectedSegmentIndex] let timeInMinutes = (timeInMinTextField.text! as NSString).integerValue let servingFor = (servingTextField.text! as NSString).integerValue // add convert image to url and saves in the recipe image field guard let image = newImageSelect.image?.pngData() else{ return} let ref = storage.child("recipes/\(id).png") ref.putData(image, metadata: nil){_, error in if(error == nil){ self.convertImageStorageToImageURL(id) {imageURL in self.errorLabel.alpha = 0 self.db.collection("recipes").document(id).setData( [ "id" : id, "name": name!, "category": category, "ingredients": ingredients!, "instructions": instructions!, "levelOfCooking": levelOfCooking, "timeInMinutes": timeInMinutes, "serving": servingFor, "image": imageURL ] ) self.nameTextField.text = "" self.segmentedCategories.selectedSegmentIndex = 0 self.ingredientsTextView.text = "" self.instructionsTextView.text = "" self.segmentedLevelOfCooking.selectedSegmentIndex = 0 self.timeInMinTextField.text = "" self.servingTextField.text = "" self.newImageSelect.image = UIImage(systemName: "plus.rectangle.on.folder") } self.errorLabel.alpha = 1 self.errorLabel.text = "Recipe Uploaded Sucessfully" }else{ print("error") } } } } @IBAction func uploadImageTapped(_ sender: Any) { let imagePicker = UIImagePickerController() imagePicker.sourceType = .photoLibrary imagePicker.delegate = self imagePicker.allowsEditing = true present(imagePicker, animated: true) } // check if all fields are filled func fieldsAreFilled() -> String? { if(nameTextField.text!.isEmpty){ return "Please enter recipe name" } if(ingredientsTextView.text!.isEmpty){ return "Please enter recipe ingredients" } if(instructionsTextView.text!.isEmpty){ return "Please enter recipe instructions" } if(servingTextField.text!.isEmpty){ return "Please enter recipe serving" } if(timeInMinTextField.text!.isEmpty){ return "Please enter recipe time in minutes" } return nil } func convertImageStorageToImageURL(_ imageId: String, _ callback:@escaping ((String) -> Void)) { var urlString = "" urlString = "" // add image to forebase storage storage.child("recipes/\(imageId).png").downloadURL { url, error in guard let url = url, error == nil else { return } urlString = url.absoluteString callback(urlString) } } // MARK: - Table view data source @IBAction func segmentedSectionTapped(_ sender: Any) { } override func numberOfSections(in tableView: UITableView) -> Int { return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.switchBasedNextTextField(textField) return true } private func switchBasedNextTextField(_ textField: UITextField) { // orginizing the next text field by clicking enter switch textField { case self.nameTextField: self.ingredientsTextView.becomeFirstResponder() case self.ingredientsTextView: self.instructionsTextView.becomeFirstResponder() case self.instructionsTextView: self.servingTextField.becomeFirstResponder() case self.servingTextField: self.timeInMinTextField.becomeFirstResponder() default: self.timeInMinTextField.resignFirstResponder() } } func defaultSetUpTextView(textview: UITextView) { //textfields textview.layer.borderColor = UIColor(red: 169/255, green: 169/255, blue: 169/255, alpha: 1).cgColor textview.layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0) textview.layer.borderWidth = 1 textview.layer.masksToBounds = true } } extension NewRecipeTableViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{ // after picking the image func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let imageR = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerEditedImage")] as? UIImage { newImageSelect.image = imageR } picker.dismiss(animated: true, completion: nil) } // on cancel clicked func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } }
3fe5e289ba622d96048c1403090b371d0553e5bf
[ "Swift", "Markdown" ]
25
Swift
shellyKrihali/Tasty-Recipe
1a029a772f0a49a1cf0eb7f0a889534f9fa372aa
3b7a19440f92485753cc97545b82ecd5b23f2cc0
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameScript : MonoBehaviour { [SerializeField] private RectTransform _backgroundCircle1, _backgroundCircle2; [SerializeField] private RectTransform _playerCircle; [SerializeField] private float _initTimer; [SerializeField] private float _initDistanceTimer; [SerializeField] private Text _scoreText2; [SerializeField] private float _bgMinSize; [SerializeField] private float _bgMaxSize; [SerializeField] private float _bgMinDistance; [SerializeField] private float _bgMaxDistance; [SerializeField] private float _bgMinSpeed; [SerializeField] private float _bgMaxSpeed; [SerializeField] private float _addAmount; [SerializeField] private GameObject _gameOverModal; [SerializeField] private Text _scoreText, _timerText; private float _survived; private bool _started, _gameOver; private float _timer; private float _newDistanceTimer; private float _imaginaryCircleRadius; private float _bgCircleDistance; private float _bgCurrCircleDistance; private float _bgCircleSpeed; private float _bgCurrCircleSpeed; private void Start() { _timer = _initTimer; _newDistanceTimer = _initDistanceTimer; _bgCurrCircleDistance = _bgCircleDistance = Random.Range(_bgMinDistance, _bgMaxDistance); _bgCurrCircleSpeed = _bgCircleSpeed = Random.Range(_bgMinSpeed, _bgMaxSpeed); } public void QuitGame () { Application.Quit(); } public void RestartGame() { SceneManager.LoadScene(0); } private void Update() { if (_gameOver) return; if (Input.GetKeyDown(KeyCode.Space)) { _playerCircle.sizeDelta += Vector2.one * _addAmount; _started = true; } if (!_started) return; if (_playerCircle.sizeDelta.x < _imaginaryCircleRadius - _bgCircleDistance / 2 || _playerCircle.sizeDelta.x > _imaginaryCircleRadius + _bgCircleDistance / 2) { _timer -= Time.deltaTime; } else { _survived += Time.deltaTime; } _timerText.text = _timer.ToString("N2"); _scoreText.text = _survived.ToString("N2"); _scoreText2.text = _survived.ToString("N2"); _newDistanceTimer -= Time.deltaTime; if (_newDistanceTimer <= 0) { _bgCurrCircleSpeed = Random.Range(_bgMinSpeed, _bgMaxSpeed); _bgCurrCircleDistance = Random.Range(_bgMinDistance, _bgMaxDistance); _newDistanceTimer = _initDistanceTimer; } _bgCircleDistance = Mathf.MoveTowards(_bgCircleDistance, _bgCurrCircleDistance, Time.deltaTime * 5f); _bgCircleSpeed = Mathf.MoveTowards(_bgCircleSpeed, _bgCurrCircleSpeed, Time.deltaTime * 5f); _backgroundCircle1.sizeDelta = Vector2.one * (_imaginaryCircleRadius - (_bgCircleDistance / 2)); _backgroundCircle2.sizeDelta = Vector2.one * (_imaginaryCircleRadius + (_bgCircleDistance / 2)); _playerCircle.sizeDelta -= Vector2.one * _bgMaxSpeed * 7f * Time.deltaTime; var sin = Mathf.Abs(Mathf.Sin(Time.time * Mathf.Deg2Rad * _bgCircleSpeed)); _imaginaryCircleRadius = Mathf.Lerp(_bgMinSize, _bgMaxSize, sin); if (_timer <= 0) { _gameOverModal.SetActive(true); _gameOver = true; } } }
6debe156dce1d4b13c2529a9af493f806e3dab83
[ "C#" ]
1
C#
FaizanDurrani/OneButtonThing
79301771e8c4995db60b8e0fd195bc0897997b41
f8fbba13b8644a320dcaedf3394de5e7da216290
refs/heads/master
<repo_name>akbarbudiman/ListBilangan<file_sep>/utama.js function ganjil() { var x = document.getElementById("thelimit"); if(x.value > 0){ var result = ""; for(i = 1 ; i <= x.value ; i = i + 2){ result = result + i + "\n"; } document.getElementById("result").innerHTML = result; } } function genap() { var x = document.getElementById("thelimit"); if(x.value > 0){ var result = ""; for(i = 2 ; i <= x.value ; i = i + 2){ result = result + i + "\n"; } document.getElementById("result").innerHTML = result; } } function prime() { var x = document.getElementById("thelimit"); if(x.value > 1){ var result = ""; for(i = 2 ; i <= x.value ; i++){ var isprime = true; for(j = 2 ; j <= Math.sqrt(i); j++){ if(i%j == 0){ isprime = false; break; } } if(isprime == true){ result = result + i + "\n"; } } document.getElementById("result").innerHTML = result; } } <file_sep>/README.md # ListBilangan Halaman yang memiliki fitur menampilkan bilangan-bilangan dari kategori yang dipilih hingga limit yang ditentukan
82d63fec9531b5d950e3a17316c9cd4f077b0290
[ "JavaScript", "Markdown" ]
2
JavaScript
akbarbudiman/ListBilangan
0318a7f779db721c97da54c0c7904a62f24c549a
f339197cbb54ca9ed5c28f4ea92a15975e0d4553
refs/heads/main
<file_sep>package br.edu.infnet.infra.vagas; import br.edu.infnet.domain.vagas.Vaga; import java.util.List; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @FeignClient(url = "http://localhost:8082/vagas", name="Vagas") public interface VagaService { @PostMapping Vaga publicarVaga(@RequestBody Vaga vaga); @GetMapping(path = {"/usuario/{idUsuario}"}) List<Vaga> listarPorIdUsuario(@PathVariable int idUsuario); @GetMapping(path = "/cargo/{pesquisa}") List<Vaga> pesquisarVagasPorCargo(@PathVariable String pesquisa); @GetMapping(path = "/cidade/{pesquisa}") List<Vaga> pesquisarVagasPorCidade(@PathVariable String pesquisa); } <file_sep>package br.edu.infnet.app.usuarios; import br.edu.infnet.domain.usuarios.Usuario; import br.edu.infnet.domain.vagas.Vaga; import br.edu.infnet.infra.usuarios.UsuarioService; import br.edu.infnet.infra.vagas.VagaService; import java.util.List; import javax.validation.Valid; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class UsuarioController { @Autowired private UsuarioService usuarioService; @Autowired private VagaService vagaService; @RequestMapping("/login") public ModelAndView logarNoSite(String email, String senha) { ModelAndView retorno = new ModelAndView("index"); if(StringUtils.isNoneBlank(email) && StringUtils.isNoneBlank(senha)) { Usuario usuario = usuarioService.obterPorEmail(email); if(usuario != null && senha.equals(usuario.getSenha())) { String destino = ""; switch(usuario.getTipo()) { case 'E': destino = "empresa/index"; try { List<Vaga> publicadas = vagaService.listarPorIdUsuario(usuario.getId()); retorno.addObject("publicadas", publicadas); } catch (Exception e) { } break; case 'C': destino = "candidato/index"; try { List<Vaga> publicadas = vagaService.listarVagas(); retorno.addObject("publicadas", publicadas); } catch (Exception e) { } break; } retorno.setViewName(destino); retorno.addObject("usuario", usuario); } else { retorno.addObject("erro", "Login inválido"); } } else { retorno.addObject("erro", "Os campos são obrigatórios"); } return retorno; } @RequestMapping("usuario/criarConta") public ModelAndView criarConta(@Valid Usuario usuario, BindingResult br) { ModelAndView retorno = new ModelAndView("usuario/manter"); if(br.hasErrors()) { retorno.addObject("erros", br.getFieldErrors()); } else { Usuario gravado = usuarioService.inserirUsuario(usuario); String destino = ""; switch(usuario.getTipo()) { case 'E': destino = "empresa/index"; break; case 'C': destino = "candidato/index"; break; } retorno.setViewName(destino); retorno.addObject("usuario", gravado); } return retorno; } // inserir Alterar dados } <file_sep>CREATE TABLE `usuarios` ( `id` int NOT NULL AUTO_INCREMENT, `nome` varchar(50) NOT NULL, `endereco` varchar(100) NOT NULL, `telefone` varchar(20) NOT NULL, `email` varchar(30) NOT NULL, `senha` varchar(32) NOT NULL, `cpf` varchar(11) NOT NULL, `razao_social` varchar(50) DEFAULT NULL, `cnpj` varchar(14) DEFAULT NULL, `tipo` char(1) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email_UNIQUE` (`email`), UNIQUE KEY `cpf_UNIQUE` (`cpf`), UNIQUE KEY `cnpj_UNIQUE` (`cnpj`) ) ENGINE=InnoDB CREATE TABLE `vagas` ( `id` int NOT NULL AUTO_INCREMENT, `id_usuario` int NOT NULL, `cargo` varchar(45) NOT NULL, `cidade` varchar(100) NOT NULL, `forma_contratacao` varchar(45) NOT NULL, PRIMARY KEY (`id`), KEY `fk_usuarios_idx` (`id_usuario`), CONSTRAINT `fk_usuarios` FOREIGN KEY (`id_usuario`) REFERENCES `usuarios` (`id`) ) ENGINE=InnoDB CREATE TABLE `criterios` ( `id` int NOT NULL AUTO_INCREMENT, `id_vaga` int NOT NULL, `descricao` varchar(45) NOT NULL, `perfil` int NOT NULL, `peso` int NOT NULL, PRIMARY KEY (`id`), KEY `fk_vaga_idx` (`id_vaga`), CONSTRAINT `fk_vaga` FOREIGN KEY (`id_vaga`) REFERENCES `vagas` (`id`) ) ENGINE=InnoDB<file_sep>spring.datasource.url=jdbc:mysql://localhost:3306/db_venturarh spring.datasource.username=root spring.datasource.password= server.port=8080 <file_sep># Ventura HR Projeto de Bloco: Desenvolvimento de Serviços em Nuvem com Java - Projeto Físico do Banco de Dados: - Usuarios - Vagas - Criterios - Definição da Arquitetura do Sistema (módulos e pacotes) - Usuário - inserirUsuario() - alterarUsuario() - excluirUsuario() - listarUsuarios() - obterPorId() - obterPorEmail() - Empresa - publicarVaga() - listarVagas() - listarPorIdUsuario() - pesquisarVagasPorCargo() - pesquisarVagasPorCidade() - Cliente - obterPorEmail() - publicarVaga() - listarPorIdUsuario() - pesquisarVagasPorCargo() - pesquisarVagasPorCidade() - WebApp - logarNoSite() - criarConta() - alterarConta() [pendente] - publicarVaga() [pendente] - pesquisarVaga() [pendente] <file_sep>package br.edu.infnet.app.vagas; import br.edu.infnet.domain.usuarios.Usuario; import br.edu.infnet.domain.vagas.Criterio; import br.edu.infnet.domain.vagas.Vaga; import br.edu.infnet.infra.vagas.VagaService; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class VagaController { @Autowired private VagaService vagaService; @RequestMapping("empresa/publicarVaga") // Validar a inserção dos critérios public ModelAndView publicarVaga(@Valid Vaga vaga, Usuario usuario, BindingResult br) { ModelAndView retorno = new ModelAndView("empresa/publicar"); List<Criterio> listaCriterio = vaga.getCriterioList(); if(br.hasErrors()) { retorno.addObject("erros", br.getFieldErrors()); } else { if(listaCriterio != null && !listaCriterio.isEmpty()) { listaCriterio.forEach(criterio -> { criterio.setVaga(vaga); }); Vaga gravada = vagaService.publicarVaga(vaga); String destino = "/"; vaga.setIdUsuario(usuario.getId()); retorno.setViewName(destino); retorno.addObject("vaga", gravada); } } return retorno; } }
bacf4b8f3d148063b79b55c783e13b7926acb953
[ "Markdown", "Java", "SQL", "INI" ]
6
Java
aespois/infnet-projeto-java
36f53191640b34519ed7e8ea51c6d30eac2fcac2
29581cd19179e85c77c894789454dd0c08cb0ece
refs/heads/master
<repo_name>markatskiddle/RS_Android<file_sep>/app/src/main/java/com/example/markprime/rs_android/scan/loginFragment/LoginFragment.java package com.example.markprime.rs_android.scan.loginFragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.*; import com.android.volley.VolleyError; import com.example.markprime.rs_android.R; import com.example.markprime.rs_android.scan.FragmentInteractionListener; import com.example.markprime.rs_android.scan.ScannerActivity; import com.example.markprime.rs_android.scan.networking.NetworkManager; import com.example.markprime.rs_android.scan.networking.VolleySingletonErrorListener; import com.example.markprime.rs_android.scan.networking.VolleySingletonListener; import com.example.markprime.rs_android.scan.networking.VolleySingletonTimeOutListener; import org.json.JSONObject; public class LoginFragment extends Fragment { private TextView txt_login_title, txt_login_by, txt_login_to_skiddle, txt_login_new_account, txt_login_pc_url, txt_forgotten_password, txt_error; private EditText et_email, et_password; private ImageView iv_rs_logo, iv_skiddle_logo; private Button btn_login; private LinearLayout ll_main, ll_logo_container, ll_by_skiddle, ll_title_container; private boolean emailTouched = false, passwordTouched = false; private Context context; SharedPreferences sharedPreferences; FragmentInteractionListener fragmentInteractionListener; public LoginFragment() { // Required empty public constructor } public static LoginFragment newInstance() { return new LoginFragment(); } @Override public void onAttach(Context context) { super.onAttach(context); fragmentInteractionListener = (FragmentInteractionListener) context; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // isNetworkAvailable(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_login, container, false); setupTextViews(view); setupButtons(view); setupEditTexts(view); setupImageViews(view); ll_main = view.findViewById(R.id.ll_main); ll_main.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { fragmentInteractionListener.dismissKeyboard(et_email); fragmentInteractionListener.dismissKeyboard(et_password); if (emailTouched) { if (!et_email.getText().toString().equals("") && !et_password.getText().toString().equals("")) { if (!isValidEmail(et_email.getText().toString())) { } else { } } else { } } if (passwordTouched) { if (et_password.getText().toString().length() < 8) { } else { } } return false; } }); et_email.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { emailTouched = true; return false; } }); et_password.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { passwordTouched = true; return false; } }); return view; } @Override public void onDestroyView() { super.onDestroyView(); fragmentInteractionListener.dismissKeyboard(et_email); fragmentInteractionListener.dismissKeyboard(et_password); } private void setupTextViews(View view) { txt_login_title = view.findViewById(R.id.txt_login_title); txt_login_by = view.findViewById(R.id.txt_login_by); txt_login_to_skiddle = view.findViewById(R.id.txt_login_to_skiddle); txt_login_new_account = view.findViewById(R.id.txt_login_new_account); txt_login_pc_url = view.findViewById(R.id.txt_login_pc_url); txt_forgotten_password = view.findViewById(R.id.txt_forgotten_password); txt_error = view.findViewById(R.id.txt_error); txt_forgotten_password.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://promotioncentre.co.uk/recover-password.php")); startActivity(intent); } }); } private void setupButtons(View view) { btn_login = view.findViewById(R.id.btn_login); btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragmentInteractionListener.dismissKeyboard(et_email); fragmentInteractionListener.dismissKeyboard(et_password); String URL = "https://www.skiddle.com/api/v1/promoter/authenticate/?api_key=5490be161354c5c440beff5bef88175a"; txt_error.setVisibility(View.INVISIBLE); if (validateFields()) { fragmentInteractionListener.showLoader(); NetworkManager.getInstance(getContext().getApplicationContext()).loginPostRequest(URL, new VolleySingletonListener<JSONObject>() { @Override public void onResult(JSONObject object) { // BaseActivity.printOut("Login Network Call", object); try { // saveUserDetails(object.getJSONObject("results")); loadScanner(); } catch (Exception e) { e.printStackTrace(); } try { switch (object.getInt("error")) { case 0: //There is no error, continue // saveUserDetails(object.getJSONObject("results")); break; case 1: //There was an error // BaseActivity.printOut("Login object", object.toString()); txt_error.setVisibility(View.VISIBLE); txt_error.setText(getActivity().getString(R.string.login_details_error)); break; } } catch (Exception e) { e.printStackTrace(); } } }, et_email.getText().toString(), et_password.getText().toString(), txt_error, getActivity(), new VolleySingletonErrorListener() { @Override public void onErrorResult(VolleyError object) { object.printStackTrace(); if (getActivity() != null) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { fragmentInteractionListener.dismissLoader(); } }); } } }, new VolleySingletonTimeOutListener() { @Override public void onTimeoutResult(Exception object) { object.printStackTrace(); if (getActivity() != null) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { fragmentInteractionListener.dismissLoader(); } }); } } }); } } }); } private void setupEditTexts(View view) { et_email = view.findViewById(R.id.et_email); et_password = view.findViewById(R.id.et_password); } private void setupImageViews(View view) { iv_rs_logo = view.findViewById(R.id.iv_rs_logo); iv_skiddle_logo = view.findViewById(R.id.iv_skiddle_logo); } // private void saveUserDetails(JSONObject object) throws Exception { // // // // SharedPreferences.Editor editor = sharedPreferences.edit(); // editor.putInt("PROMOTER_ID", object.getInt("promoterid")); // editor.putString("PACCESS_TOKEN", object.getString("paccess_token")); // // editor.putBoolean("LOGGED_IN", true); // editor.putBoolean("FIRST_LOAD", false); // editor.apply(); // } private void loadScanner(){ } private boolean validateFields() { if (!et_email.getText().toString().equals("") && !et_password.getText().toString().equals("")) { if (isValidEmail(et_email.getText().toString())) { if (et_password.getText().toString().length() > 7) { return true; } else { txt_error.setVisibility(View.VISIBLE); txt_error.setText(getActivity().getString(R.string.login_password_advice)); return false; } } else { txt_error.setVisibility(View.VISIBLE); txt_error.setText(getActivity().getString(R.string.login_email_advice)); return false; } } else { txt_error.setVisibility(View.VISIBLE); txt_error.setText(getActivity().getString(R.string.login_error_empty_fields)); return false; } } private boolean isValidEmail(String target) { if (TextUtils.isEmpty(target)) { return false; } else { return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } } private boolean isNetworkAvailable() { final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = connectivityManager.getActiveNetworkInfo(); return ni != null && ni.isConnected(); } }<file_sep>/app/src/main/java/com/example/markprime/rs_android/scan/eventsFragment/EventsFragment.java package com.example.markprime.rs_android.scan.eventsFragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.markprime.rs_android.R; import com.example.markprime.rs_android.scan.FragmentInteractionListener; import com.example.markprime.rs_android.scan.networking.NetworkManager; import com.example.markprime.rs_android.scan.networking.VolleySingletonListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.EventObject; import java.util.List; public class EventsFragment extends Fragment { private RecyclerView re_events; private Context context; private List<EventObject> eventList = new ArrayList<>(); private EventsAdapter eventsAdapter; private FragmentInteractionListener fragmentInteractionListener; public EventsFragment(){} public static EventsFragment newInstance() { EventsFragment fragment = new EventsFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_events, container, false); setUpRecyclerView(view); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(receiver, intentFilter); getEvents(); return view; } private void setUpRecyclerView(final View view) { re_events = view.findViewById(R.id.re_events); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); re_events.setLayoutManager(linearLayoutManager); setAdapter(); } private void getEvents() { NetworkManager.getInstance(context).GetRequest("https://www.skiddle.com/api/v1/events/search?api_key=008f1e6099ecc48e990e3776784d447b&platform=android&type=mobileapp&version=97&limit=40&offset=0&description=1&imagefilter=1&platform=android&order=date&radius=30&latitude=53.3994794&longitude=-2.524805&eventcode=4&aggs=genreids,eventcode", new VolleySingletonListener<JSONObject>() { @Override public void onResult(JSONObject object) { try { JSONArray jsonArray = object.getJSONArray("results"); for (int i = 0; i < jsonArray.length(); i++) { eventList.add(new EventObject(jsonArray.getJSONObject(i))); } } catch (JSONException e) { e.printStackTrace(); } setAdapter(); Log.d("RESPONSE", object.toString()); } }); } @Override public void onAttach(Context context) { super.onAttach(context); this.context = context; fragmentInteractionListener = (FragmentInteractionListener) context; } @Override public void onDetach() { super.onDetach(); } private void setAdapter() { eventsAdapter = new EventsAdapter(context, eventList); re_events.setAdapter(eventsAdapter); } // private EventsAdapterListener eventsAdapterListener = new EventsAdapterListener() { // @Override // public void eventClicked(EventObject eventObject) { // fragmentInteractionListener.openEventDetailsFragment(eventObject.getFullObject()); // } // }; private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo ni = connectivityManager.getActiveNetworkInfo(); if (ni != null && ni.isConnectedOrConnecting()) { if (re_events.getAdapter() == null) { getEvents() ;}else return; } } }; @Override public void eventClicked(EventObject eventObject) { } } <file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'io.fabric' apply plugin: 'com.google.gms.google-services' apply plugin: 'realm-android' apply plugin: 'com.android.application' buildscript { repositories { maven { url 'https://maven.fabric.io/public' } maven { url "http://jcenter.bintray.com" } maven { url "https://maven.google.com" } } dependencies { classpath 'io.fabric.tools:gradle:1.26.1' } } repositories { maven { url 'https://maven.fabric.io/public' } } android { compileSdkVersion 27 defaultConfig { applicationId "com.example.markprime.rs_android" minSdkVersion 23 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'com.android.support:support-v4:27.1.1' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.android.support:recyclerview-v7:27.1.1' implementation 'com.android.volley:volley:1.1.1' implementation 'org.greenrobot:eventbus:3.1.1' implementation 'com.google.code.gson:gson:2.8.5' implementation 'me.dm7.barcodescanner:zbar:1.9' implementation 'com.thoughtbot:expandablerecyclerview:1.3' implementation 'io.realm:android-adapters:2.1.0' implementation('com.crashlytics.sdk.android:answers:1.3.8@aar') { transitive = true } implementation('com.crashlytics.sdk.android:crashlytics:2.6.6@aar') { transitive = true } implementation 'com.bignerdranch.android:expandablerecyclerview:3.0.0-RC1' implementation 'com.google.firebase:firebase-core:16.0.4' implementation 'com.android.support:design:27.1.1' implementation('com.github.florent37:androidparallax:1.0.1@aar') { transitive = true } implementation 'com.squareup.picasso:picasso:2.71828' implementation 'com.github.siyamed:android-shape-imageview:0.9.3@aar' } <file_sep>/app/src/main/java/com/example/markprime/rs_android/scan/utils/AppController.java package com.example.markprime.rs_android.scan.utils; import android.app.Application; import com.example.markprime.rs_android.scan.networking.NetworkManager; public class AppController extends Application { @Override public void onCreate() { super.onCreate(); NetworkManager.getInstance(this); } } <file_sep>/app/src/main/java/com/example/markprime/rs_android/scan/networking/VolleySingletonListener.java package com.example.markprime.rs_android.scan.networking; public interface VolleySingletonListener<T> { void onResult(T object); }<file_sep>/app/src/main/java/com/example/markprime/rs_android/scan/FragmentInteractionListener.java package com.example.markprime.rs_android.scan; import android.widget.EditText; public interface FragmentInteractionListener { void showLoader(); void dismissLoader(); void setLoginFrag(); void dismissKeyboard(EditText editText); }
b360882c61a0f5e0d485480a67ec5fef04fe3ef2
[ "Java", "Gradle" ]
6
Java
markatskiddle/RS_Android
91a97cc259c96595e1d8d2bb56395aa91725a894
22cbf99dfe6066a25ee4fdec1989ec3b301ad0d2
refs/heads/devel
<file_sep>MAX_DISTANCE = 140. LANE_OFFSET = 1.8 <file_sep>#define COMMA_VERSION "0.5.8-release"
19f374acd1822aaa417648a867aaf3a910e97466
[ "C", "Python" ]
2
Python
priuscom/openpilot
36b25d11c7e6f8c6d6402f4340d991bef315de98
826c0fc3c7196f7c160905aa919bac9c68acc840
refs/heads/master
<repo_name>mohini14/GoogleKeep<file_sep>/GoogleKeep/Classes/Utils/Define.swift // // Define.swift // GoogleKeep // // Created by <NAME> on 27/07/17. // Copyright © 2017 <NAME> . All rights reserved. // import UIKit struct Define { struct ImageName { static let kSlideBarImage = "SlideBarButton.png" } struct IntegerConstants { static let kTwoConst = CGFloat(2) } struct ColorConstants { static let kNavigationBarColor = UIColor(red: 238/255, green: 186/255, blue: 44/255, alpha: 1) static let KBaseColor = UIColor(red: 109/255, green: 87/255, blue: 16/255, alpha:1) } struct CellIdentifireConstant { static let kMenuTableCellIdentifier = "MenuTableCell" static let kNoteCollectionCellIdentifier = "NoteCollectionCell" } struct XIBNames{ static let kNotesCollectionCellNIB = "NotesCollectionCell" static let kAddNewNoteViewNIB = "AddNewNoteView" } struct SegueIdentifiers { static let kMenuVCToHomeVC = "MenuVCToHOmeVC" } struct CoreDataEntitynames{ static let kNoteEntity = "Note" } struct NoteEntityAttributeNames { static let kNoteHeadingAttribute = "noteHeading" static let kNoteDescriptionAttribute = "noteDescription" static let kNoteDateAttribuet = "noteDate" } } <file_sep>/GoogleKeep/Classes/ViewControllers/HomeViewController.swift // // HomeViewController.swift // GoogleKeep // // Created by <NAME> on 27/07/17. // Copyright © 2017 <NAME> . All rights reserved. // import UIKit import CoreData let kViewShadowOpacity = CGFloat(0.5) let kViewShadowRadius = Int(1) let kViewShadowOffsetWidth = Int(-1) let kViewShadowOffsethieght = Int(1) let kviewShadowSize = CGFloat(5.0) //let kSubViewTopConstartintValue = CGFloat(64.0) class HomeViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ //MARK: IBOutlets @IBOutlet weak var notesCollectionView : UICollectionView! @IBOutlet weak var bottomView : UIView! //MARK: Private Oulets var notesArray : Array<Note>? var CellHieght : CGFloat? //MARK: View life cycle methods override func viewDidLoad() { super.viewDidLoad() initialVCSetup() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning(){ super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Private methods func initialVCSetup(){ title = "Keep" addToggleButton() InitialDeclarations() populateData() dropShadow(scale: true) addRefreshControlToCollectionView() } func populateData(){ self.notesArray = CoreData.fetchAllNotes() if (notesArray?.count)! > 0 { self.notesCollectionView.reloadData() } self.notesCollectionView.refreshControl?.endRefreshing() } func addToggleButton(){ Utility.setSliderBarPropertyWithVC(sender: self) } func dropShadow(scale: Bool = true) { self.bottomView.tintColor = Define.ColorConstants.KBaseColor self.bottomView.layer.masksToBounds = false self.bottomView.layer.shadowColor = UIColor.black.cgColor self.bottomView.layer.shadowOffset = CGSize.init(width: 5, height: 5) self.bottomView.layer.shadowOpacity = Float(kViewShadowOpacity) self.bottomView.layer.shadowRadius = 10 self.bottomView.layer.shadowPath = UIBezierPath(rect: self.bottomView.bounds).cgPath self.bottomView.layer.shouldRasterize = true } func InitialDeclarations(){ self.notesArray = Array() // register NIB let nib = UINib(nibName: Define.XIBNames.kNotesCollectionCellNIB, bundle: nil) self.notesCollectionView?.register(nib, forCellWithReuseIdentifier:Define.CellIdentifireConstant.kNoteCollectionCellIdentifier) } func addRefreshControlToCollectionView(){ self.notesCollectionView.refreshControl = UIRefreshControl() self.notesCollectionView.refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh") self.notesCollectionView.refreshControl?.addTarget(self, action: #selector(self.populateData), for: UIControlEvents.valueChanged) } //MARK: Collection view Data Source func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (self.notesArray?.count)! } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var cell : NotesCollectionCell! cell = collectionView.dequeueReusableCell(withReuseIdentifier: Define.CellIdentifireConstant.kNoteCollectionCellIdentifier, for: indexPath) as! NotesCollectionCell cell.setUpCellAttributes((self.notesArray?[indexPath.row])!, withCompletionHandler: { (height) in self.CellHieght = height } ) return cell } // //Use for size // func collectionView(_ collectionView: UICollectionView, // layout collectionViewLayout: UICollectionViewLayout, // sizeForItemAt indexPath: IndexPath) -> CGSize { //// if let cellHt = self.CellHieght //// { //// return CGSize(width: self.view.frame.size.width, height: cellHt + 20.0) //// } // return CGSize (width: self.view.frame.size.width , height: 150.0) // } // //MARK: Actions on VC @IBAction func addNewNoteButtonPressed(_ sender: Any) { let subView = Bundle.main.loadNibNamed(Define.XIBNames.kAddNewNoteViewNIB, owner: nil, options: nil)?.first as! AddNewNoteView let rect = CGRect(origin: CGPoint(x: 0,y :(self.navigationController?.navigationBar.frame.size.height)! + 10.0), size: CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height)) subView.frame = rect self.view.addSubview(subView) subView.onFetchingNewNote = { (newNote : Note) -> Void in if !((newNote.noteDescription?.isEmpty)!){ CoreData.saveANewNote(newNote) } } } } <file_sep>/GoogleKeep/Classes/TableCellParentClass/MenuTableViewCell.swift // // MenuTableViewCell.swift // GoogleKeep // // Created by <NAME> on 01/08/17. // Copyright © 2017 <NAME> . All rights reserved. // import UIKit class MenuTableViewCell: UITableViewCell { //MARK: IBOutlets @IBOutlet weak var menuName : UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } public func setCellProperties (_ labelString : String){ if (self.menuName != nil) { self.menuName.text = " " + labelString } } } <file_sep>/GoogleKeep/Classes/CoreData.swift // // CoreDate.swift // GoogleKeep // // Created by <NAME> on 02/08/17. // Copyright © 2017 <NAME> . All rights reserved. // import UIKit import CoreData class CoreData: NSObject { static var managedContext : NSManagedObjectContext? = nil class func getManagedObjectContext() { //1 guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } managedContext = appDelegate.persistentContainer.viewContext } //MARK: Note related methods class func saveANewNote(_ newNote : Note){ CoreData.getManagedObjectContext() let entity = NSEntityDescription.entity(forEntityName:Define.CoreDataEntitynames.kNoteEntity, in:managedContext!) let newNoteToSave = NSManagedObject(entity: entity!, insertInto: managedContext) //save values for entity attributes newNoteToSave.setValue(newNote.noteHeading , forKeyPath: Define.NoteEntityAttributeNames.kNoteHeadingAttribute) newNoteToSave.setValue(newNote.noteDescription , forKeyPath: Define.NoteEntityAttributeNames.kNoteDescriptionAttribute) newNoteToSave.setValue(newNote.noteDate , forKeyPath: Define.NoteEntityAttributeNames.kNoteDateAttribuet) // using try catch while saving do { try managedContext?.save() } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } } class func fetchAllNotes() -> Array<Note>?{ CoreData.getManagedObjectContext() var array = Array<Note>() let fetchRequest = NSFetchRequest<Note>(entityName:Define.CoreDataEntitynames.kNoteEntity) do { let fetchedResults = try managedContext!.fetch(fetchRequest) for item in fetchedResults { array.append(item) } return array } catch let error as NSError { // something went wrong, print the error. print(error.description) } return nil } } <file_sep>/GoogleKeep/Classes/ViewControllers/MenuViewController.swift // // MenuViewController.swift // GoogleKeep // // Created by <NAME> on 27/07/17. // Copyright © 2017 <NAME> . All rights reserved. // import UIKit enum MenuType : String{ case Notes = "Notes" case Reminder = "Reminders" } class MenuViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { //MARK: IBOutlets @IBOutlet weak var viewOverImageView : UIView! @IBOutlet weak var menuTableView : UITableView! // MARK:Private variables var menuArray : Array<String>? override func viewDidLoad(){ super.viewDidLoad() initialVCSetup() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Private methods func initialVCSetup(){ self.viewOverImageView.backgroundColor = UIColor.black.withAlphaComponent(0.6) self.menuArray = [MenuType.Notes.rawValue,MenuType.Reminder.rawValue] } //MARK: table view data source methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.menuArray?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : MenuTableViewCell! cell = tableView.dequeueReusableCell(withIdentifier: Define.CellIdentifireConstant.kMenuTableCellIdentifier, for:indexPath) as! MenuTableViewCell if cell == nil { cell = MenuTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier:Define.CellIdentifireConstant.kMenuTableCellIdentifier) } cell.setCellProperties((self.menuArray?[indexPath.row])!) return cell } //MARK: Menu table view Delegate methods func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let menuType = (self.menuArray?[indexPath.row])! var SegueName : String? switch menuType { case MenuType.Notes.rawValue: SegueName = Define.SegueIdentifiers.kMenuVCToHomeVC // case MenuType.Reminder.rawValue : // SegueName = " " default: SegueName = nil } if SegueName != nil{ self.performSegue(withIdentifier: SegueName!, sender: indexPath) } } } <file_sep>/GoogleKeep/Classes/CollectionCellParentClass/NotesCollectionCell.swift // // NotesCollectionCell.swift // GoogleKeep // // Created by <NAME> on 01/08/17. // Copyright © 2017 <NAME> . All rights reserved. // import UIKit import CoreData let extraPeddingRequired = CGFloat(40.0) class NotesCollectionCell: UICollectionViewCell { //MARK: IBOutlets @IBOutlet weak var NoteHeadingLabel : UILabel! @IBOutlet weak var NoteDescriptionLabel : UILabel! // mistake : change to small var onFetchingCellSize : ((CGFloat) -> Void?)? = nil //MARK: Over rided methods override func awakeFromNib() { super.awakeFromNib() } //MARK: Instance methods func setUpCellAttributes(_ noteDetails : Note, withCompletionHandler onFetchingCellSize:(CGFloat)-> Void ){ if self.NoteHeadingLabel != nil{ self.NoteHeadingLabel.text = noteDetails.noteHeading } if self.NoteDescriptionLabel != nil{ self.NoteDescriptionLabel.text = noteDetails.noteDescription } // let ht = self.setCellHieght(noteDetails) // if let onFetchingCellSize = self.onFetchingCellSize{ // onFetchingCellSize(ht) // } // self.setCellHieght(noteDetails) } //MARK: private methods private func setCellHieght(_ noteDetails : Note) { let ht = self.NoteDescriptionLabel.frame.size.height + self.NoteHeadingLabel.frame.size.height + extraPeddingRequired self.frame.size = CGSize(width : 414.0 , height: ht) } } <file_sep>/GoogleKeep/Classes/Utils/Utility.swift // // Utility.swift // GoogleKeep // // Created by <NAME> on 27/07/17. // Copyright © 2017 <NAME> . All rights reserved. // import UIKit class Utility: NSObject { //MARK:Alerts on Screen class func promptMessageOnScreen (_ message : String, viewContoller: UIViewController) -> () { let alert = UIAlertController(title: NSLocalizedString("ALert", comment: "") ,message: message , preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler:nil)) viewContoller.present(alert, animated:true, completion:nil) } //MARK: SWReveal helper methods class func setSliderBarPropertyWithVC (sender : UIViewController){ let revealViewController : SWRevealViewController! = sender.revealViewController() if revealViewController != nil { let slidBarButtonItem : UIBarButtonItem = UIBarButtonItem(image: UIImage(named:Define.ImageName.kSlideBarImage), landscapeImagePhone: nil, style: .plain, target: sender.revealViewController(), action: #selector(sender.revealViewController().revealToggle(_:))) sender.navigationItem.leftBarButtonItem = slidBarButtonItem sender.revealViewController().rearViewRevealWidth = (sender.view.frame.width / (2)) + 40; sender.view.addGestureRecognizer(sender.revealViewController().panGestureRecognizer()) } } //MARK: Date and time methods class func getCurrentDate() -> (Int,Int,Int){ let date = Date() let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day], from: date) let year = components.year let month = components.month let day = components.day let currentDate = (day!,month!,year!) return currentDate } } <file_sep>/GoogleKeep/Classes/AddNewNoteView.swift // // AddNewNoteView.swift // GoogleKeep // // Created by <NAME> on 02/08/17. // Copyright © 2017 <NAME> . All rights reserved. // import UIKit import CoreData class AddNewNoteView: UIView { //MARK: IBoutlets @IBOutlet weak var noteTitleTextField : UITextField! @IBOutlet weak var noteDescriptionTextView : UITextView! //MARK: variables var onFetchingNewNote : ((_ fetchedNote : Note) -> Void)? override func draw(_ rect: CGRect) { super.draw(rect) } //MARK: Private methods func initSettings(){ } func convertDateTupleToString() -> (String){ let dateTuple = Utility.getCurrentDate() let dateString : String = String(dateTuple.0) + "-" + String(dateTuple.1) + "-" + String(dateTuple.2) return dateString } //MARK: Actions on NIB @IBAction func saveNoteButtonPressed(_ sender: Any) { CoreData.getManagedObjectContext() let newNote = Note.init(entity: NSEntityDescription.entity(forEntityName: Define.CoreDataEntitynames.kNoteEntity , in:CoreData.managedContext!)!, insertInto: CoreData.managedContext) if !((self.noteDescriptionTextView?.text.isEmpty)!){ // get current date newNote.noteDate = self.convertDateTupleToString() newNote.noteHeading = self.noteTitleTextField.text newNote.noteDescription = self.noteDescriptionTextView.text if let onFetchingNewNote = onFetchingNewNote{ onFetchingNewNote(newNote) self.removeFromSuperview() } } else{ self.removeFromSuperview() } } @IBAction func cancelButtonPressed(_ sender: Any) { self.removeFromSuperview() } }
d551f92740bb3f1cda5967c2ee85f9feace1c50d
[ "Swift" ]
8
Swift
mohini14/GoogleKeep
29508ecea8f06daf9b68b058b0ed198d59b59cf3
1886782675bac0b8db4a3f69f6aec34b328f06ec
refs/heads/master
<repo_name>evancloutier/yahoo-fantasy-bot<file_sep>/utils/models/mongo.js var mongoose = require('mongoose'); var db = mongoose.connection; // initializing our database mongoose.connect('mongodb://localhost/fantasybot'); // error handler db.on('error', function(err) { console.log(err); }); // reconnect when closed db.on('disconnected', function() { connect(); }); db.once('open', function () { console.log("Success! Connected to the database!"); });<file_sep>/utils/models/user.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; let userSchema = new Schema({ // authentication specific data fb_id: String, yahoo_guid: String, oauth_token: String, oauth_token_secret: String, oauth_verifier: String, oauth_session_handle: String, creation_time: String, // yahoo specific data games: [{ game: [{ name: String, game_key: String, season: String, teams: [{ name: String, team_key: String, league_key: String }] }] }] }); let User = mongoose.model('User', userSchema); module.exports = User;<file_sep>/utils/authentication.js //importing modules const fs = require('fs'); const mongoose = require('mongoose'); const parser = require('xml2json'); const qs = require('querystring'); const request = require('request'); const yahoo = require('./yahoo'); const Mongo = require('./models/mongo'); const User = require('./models/user'); const consumerKey = process.env.CONSUMER_KEY; const consumerSecret = process.env.CONSUMER_SECRET; const redirectUri = process.env.REDIRECT_URI; exports.checkAuthentication = (fb_id) => { return new Promise((resolve, reject) => { User.findOne({ fb_id: fb_id }, (error, result) => { if (error) return reject(error); if (result) return resolve(true); else return resolve(false); }); }); } exports.checkVerifier = (fb_id) => { return new Promise((resolve, reject) => { User.findOne({ fb_id: fb_id }, (error, result) => { if (error) return reject(error); if (result) { if (result.oauth_verifier) return resolve(true); else return resolve(false); } }); }); } exports.updateVerifier = (token, verifier) => { return new Promise((resolve, reject) => { User.findOne({ oauth_token: token }, (error, result) => { if (error) return reject(error); if (result) { // located the token if (result.oauth_verifier == null) { // ensure that our verifier hasn't already been written const conditions = { oauth_token: token }; const update = { oauth_verifier: verifier }; const options = { multi: false }; User.update(conditions, update, options, (error, result) => { if (error) return reject(error); console.log("Successfully updated verifier"); return resolve(true); }); } } else { // couldn't find the token return resolve(false); } }) }); } exports.getAuthenticationUrl = (fb_id) => { return new Promise((resolve, reject) => { const url = "https://api.login.yahoo.com/oauth/v2/get_request_token"; const oauth = { callback: redirectUri, consumer_key: consumerKey, consumer_secret: consumerSecret }; request.post({ url: url, oauth: oauth }, (error, response, body) => { if (error) reject(error); const responseData = qs.parse(body); let user = new User({ fb_id: fb_id, yahoo_guid: null, oauth_token: responseData.oauth_token, oauth_token_secret: responseData.oauth_token_secret, oauth_verifier: null, oauth_session_handle: null, creation_time: null }); user.save((error, user) => { if (error) reject(error); console.log("User saved!"); }); const authenticationUrl = responseData.xoauth_request_auth_url; resolve(authenticationUrl); }); }); } exports.deleteUser = (fb_id) => { return new Promise((resolve, reject) => { User.findOneAndRemove({ fb_id: fb_id }, (error, result) => { if (error) return reject(error); return resolve(); }); }); } exports.getVerifier = (verifier) => { return new Promise((resolve, reject) => { let fbid = ""; User.findOne({ oauth_verifier: verifier }, (error, result) => { if (error) return reject(error); if (result) { fbid = result.fb_id; const url = "https://api.login.yahoo.com/oauth/v2/get_token"; const oauth = { consumer_key: consumerKey, consumer_secret: consumerSecret, token: result.oauth_token, token_secret: result.oauth_token_secret, verifier: result.oauth_verifier }; request.post({ url: url, oauth: oauth }, (error, response, body) => { if (error) return reject(error); const tokenData = qs.parse(body); const conditions = { oauth_verifier: verifier }; const update = { yahoo_guid: tokenData.xoauth_yahoo_guid, oauth_token: tokenData.oauth_token, oauth_token_secret: tokenData.oauth_token_secret, oauth_session_handle: tokenData.oauth_session_handle, creation_time: (Date.now() / 1000 / 60) }; const options = { mutli: false }; User.update(conditions, update, options, (error, result) => { if (error) return reject(error); else { console.log("Successfully updated OAuth credentials"); console.log(result); console.log("----------------"); return resolve(fbid); } }); }); } }); }); } exports.getUserDetails = (fb_id) => { return new Promise((resolve, reject) => { User.findOne({ fb_id: fb_id }, (error, result) => { if (error) return reject(error); const url = "http://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games/teams"; const oauth = { consumer_key: consumerKey, consumer_secret: consumerSecret, token: result.oauth_token, token_secret: result.oauth_token_secret, verifier: result.oauth_verifier }; request.get({ url: url, oauth: oauth }, (error, response, body) => { if (error) return reject(error); const parsedData = JSON.parse(parser.toJson(body)); const userDetails = parsedData.fantasy_content.users.user; let gamesArray = []; let gameArray = []; for (const userObject in userDetails) { if (userObject == "games") { const gameDetails = userDetails[userObject].game; const gameCount = userDetails[userObject].count; if (gameCount == 1) { let teamArray = []; const teamsDetail = gameDetails.teams; const sport = gameDetails.name; const season = gameDetails.season; const type = gameDetails.type; const isActive = yahoo.checkCurrentSeason(sport.toLowerCase(), season); if (!isEmpty(teamsDetail) && type == "full" && isActive) { const teamCount = teamsDetail.count; const teamDetails = teamsDetail.team; if (teamCount > 1) { for (const teamObject in teamDetails) { const splitKey = teamDetails[teamObject].team_key.split("."); const leagueKey = splitKey[0] + "." + splitKey[1] + "." + splitKey[2]; const team = { name: teamDetails[teamObject].name, team_key: teamDetails[teamObject].team_key, league_key: leagueKey }; teamArray.push(team); } } else { const splitKey = teamDetails.team_key.split("."); const leagueKey = splitKey[0] + "." + splitKey[1] + "." + splitKey[2]; const team = { name: teamDetails.name, team_key: teamDetails.team_key, league_key: leagueKey }; teamArray.push(team); } const game = { name: sport.toLowerCase(), game_key: gameDetails.game_key, season: season, teams: teamArray }; gameArray.push(game); } } else { for (const gameObject in gameDetails) { let teamArray = []; const teamsDetail = gameDetails[gameObject].teams; const sport = gameDetails[gameObject].name; const season = gameDetails[gameObject].season; const type = gameDetails[gameObject].type; const isActive = yahoo.checkCurrentSeason(sport.toLowerCase(), season); if (!isEmpty(teamsDetail) && type == "full" && isActive) { const teamCount = teamsDetail.count; const teamDetails = teamsDetail.team; if (teamCount > 1) { for (const teamObject in teamDetails) { const splitKey = teamDetails[teamObject].team_key.split("."); const leagueKey = splitKey[0] + "." + splitKey[1] + "." + splitKey[2]; const team = { name: teamDetails[teamObject].name, team_key: teamDetails[teamObject].team_key, league_key: leagueKey }; teamArray.push(team); } } else { const splitKey = teamDetails.team_key.split("."); const leagueKey = splitKey[0] + "." + splitKey[1] + "." + splitKey[2]; const team = { name: teamDetails.name, team_key: teamDetails.team_key, league_key: leagueKey }; teamArray.push(team); } const game = { name: sport.toLowerCase(), game_key: gameDetails[gameObject].game_key, season: gameDetails[gameObject].season, teams: teamArray }; gameArray.push(game); } } } } } const games = { game: gameArray }; gamesArray.push(games); console.log(gamesArray); console.log("----------------"); // updating our user in the database const conditions = { fb_id: fb_id }; const update = { games: gamesArray }; const options = { multi : false }; User.update(conditions, update, options, (error, result) => { if (error) return console.log(error); console.log("Successfully added user Yahoo! data"); return resolve(true); }); }); }); }); } exports.checkRefresh = (fb_id) => { return new Promise((resolve, reject) => { User.findOne({ fb_id: fb_id }, (error, result) => { if (error) return reject(error); if (result) { const difference = (Date.now() / 60000) - result.creation_time; if (difference > 59) { const url = "https://api.login.yahoo.com/oauth/v2/get_token"; const oauth = { consumer_key: consumerKey, consumer_secret: consumerSecret, token: result.oauth_token, token_secret: result.oauth_token_secret, session_handle: result.oauth_session_handle, signature_method: 'PLAINTEXT' }; request.post({ url: url, oauth: oauth }, (error, response, body) => { const refreshData = qs.parse(body); const conditions = { fb_id: fb_id }; const update = { oauth_token: refreshData.oauth_token, oauth_token_secret: refreshData.oauth_token_secret, oauth_session_handle: refreshData.oauth_session_handle, creation_time: (Date.now() / 60000) }; const options = { multi: false }; User.update(conditions, update, options, (error, result) => { if (error) return reject(error); console.log("Successfully refreshed token"); resolve(true); }); }); } else { console.log("Tokens still valid"); resolve(true); } } else { resolve(false); } }); }); } function isEmpty(object) { for (var property in object) { if (object.hasOwnProperty(property)) return false; } return true; } <file_sep>/utils/models/sportstats.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; let sportStatsSchema = new Schema({ baseball: [{ stat_id: String, stat_name: String, stat_abrv: String }], basketball: [{ stat_id: String, stat_name: String, stat_abrv: String }], football: [{ stat_id: String, stat_name: String, stat_abrv: String }], hockey: [{ stat_id: String, stat_name: String, stat_abrv: String }] }); let SportStats = mongoose.model('sportStats', sportStatsSchema); module.exports = SportStats;<file_sep>/app.js 'use strict'; // Dependencies and Parameters const bodyParser = require('body-parser'); const crypto = require('crypto'); const express = require('express'); const fetch = require('node-fetch'); const request = require('request'); const qs = require('querystring'); const Wit = require('node-wit').Wit; const log = require('node-wit').log; const yahoo = require('./utils/yahoo'); const Mongo = require('./utils/models/mongo'); const User = require('./utils/models/user'); const authentication = require('./utils/authentication'); const PORT = process.env.PORT || 8445; const consumerKey = process.env.CONSUMER_KEY; const consumerSecret = process.env.CONSUMER_SECRET; const redirectUri = process.env.REDIRECT_URI; const WIT_TOKEN = process.env.WIT_TOKEN; const FB_PAGE_ID = process.env.FB_PAGE_ID; const FB_PAGE_TOKEN = process.env.FB_PAGE_TOKEN; const FB_APP_SECRET = process.env.FB_APP_SECRET; const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN; // Messenger API Specific Code const fbMessage = (id, text) => { const body = JSON.stringify({ recipient: { id }, message: { text }, }); const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN); return fetch('https://graph.facebook.com/me/messages?' + qs, { method: 'POST', headers: {'Content-Type': 'application/json'}, body, }) .then(rsp => rsp.json()) .then(json => { if (json.error && json.error.message) { throw new Error(json.error.message); } return json; }); }; const sendErrorMessage = (id) => { const text = "Uh oh! It seems like something went wrong when I was processing your request. Please try again :)" const body = JSON.stringify({ recipient: { id }, message: { text }, }); const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN); return fetch('https://graph.facebook.com/me/messages?' + qs, { method: 'POST', headers: {'Content-Type': 'application/json'}, body, }) .then(rsp => rsp.json()) .then(json => { if (json.error && json.error.message) { throw new Error(json.error.message); } return json; }); }; const sendStandingsMessage = (userObject, standingsArray) => { return new Promise((resolve, reject) => { const text = "Anything else I can do for you?"; const message = "Here are the standings for your " + userObject.context.sport + " league: "; fbMessage(userObject.fbid, message).then(() => { for (const standingsString in standingsArray) { fbMessage(userObject.fbid, standingsArray[standingsString]).then(() => { if (standingsString == (standingsArray.length - 1)) { fbMessage(userObject.fbid, text).then(() => null); return resolve(); } }); } }).catch((err) => { console.log("Oops! An error occurred while forwarding the response to " + userObject.fbid + ": " + err.stack || err); sendErrorMessage(userObject.fbid); }); }); }; const sendMatchupMessage = (userObject, matchup) => { return new Promise((resolve, reject) => { const text = "Anything else I can do for you?"; const message = "Here is your " + userObject.context.sport + " matchup for this week: "; fbMessage(userObject.fbid, message).then(() => { fbMessage(userObject.fbid, matchup).then(() => { fbMessage(userObject.fbid, text).then(() => null); return resolve(); }); }).catch((err) => { console.log("Oops! An error occurred while forwarding the response to " + userObject.fbid + ": " + err.stack || err); sendErrorMessage(userObject.fbid); }); }); }; const sendPlayerMessage = (userObject, stats) => { return new Promise((resolve, reject) => { const text = "Anything else I can do for you?"; const message = "Here are " + userObject.context.player + "'s stats: "; fbMessage(userObject.fbid, message).then(() => { fbMessage(userObject.fbid, stats).then(() => { fbMessage(userObject.fbid, text).then(() => null); return resolve(); }); }).catch((err) => { console.log("Oops! An error occurred while forwarding the response to " + userObject.fbid + ": " + err.stack || err); sendErrorMessage(userObject.fbid); }); }); }; const sendLineupMessage = (userObject, lineup) => { return new Promise((resolve, reject) => { const text = "Anything else I can do for you?"; const message = "Here is your " + userObject.context.sport + " lineup! 🏆"; fbMessage(userObject.fbid, message).then(() => { if (userObject.context.sport == "baseball") { fbMessage(userObject.fbid, lineup.offense).then(() => { fbMessage(userObject.fbid, lineup.pitchers).then(() => { if (lineup.bench != "") { fbMessage(userObject.fbid, lineup.bench).then(() => { fbMessage(userObject.fbid, text); return resolve(); }); } else { fbMessage(userObject.fbid, text); return resolve(); } }); }).catch((err) => { console.log("Oops! An error occurred while forwarding the response to " + userObject.fbid + ": " + err.stack || err); sendErrorMessage(userObject.fbid); }); } else if (userObject.context.sport == "basketball") { fbMessage(userObject.fbid, lineup.offense).then(() => { if (lineup.bench != "") { fbMessage(userObject.fbid, lineup.bench).then(() => { fbMessage(userObject.fbid, text); return resolve(); }); } }); } else if (userObject.context.sport == "football") { fbMessage(userObject.fbid, lineup.offense).then(() => { if (lineup.bench != "") { fbMessage(userObject.fbid, lineup.bench).then(() => { fbMessage(userObject.fbid, text); return resolve(); }); } else { fbMessage(userObject.fbid, text); return resolve(); } }).catch((err) => { console.log("Oops! An error occurred while forwarding the response to " + userObject.fbid + ": " + err.stack || err); sendErrorMessage(userObject.fbid); }); } else if (userObject.context.sport == "hockey") { fbMessage(userObject.fbid, lineup.offense).then(() => { fbMessage(userObject.fbid, lineup.defense).then(() => { if (lineup.bench != "") { fbMessage(userObject.fbid, lineup.bench).then(() => { fbMessage(userObject.fbid, text); return resolve(); }); } else { fbMessage(userObject.fbid, text); return resolve(); } }); }).catch((err) => { console.log("Oops! An error occurred while forwarding the response to " + userObject.fbid + ": " + err.stack || err); sendErrorMessage(userObject.fbid); }); } }).catch((err) => { console.log("Oops! An error occurred while forwarding the response to " + userObject.fbid + ": " + err.stack || err); sendErrorMessage(userObject.fbid); }); }); }; // TO-DO: Handle case of 3+ buttons (i.e. "More..." button) const sendTeamsMessage = (id, object) => { let buttonArray = []; let payloadContext = ""; if (object.context.hasOwnProperty("lineup")) payloadContext = "lineup"; else if (object.context.hasOwnProperty("matchup")) payloadContext = "matchup"; else if (object.context.hasOwnProperty("standings")) payloadContext = "standings"; else if (object.context.hasOwnProperty("player")) payloadContext = "player"; const teams = object.result.teams; for (const team in teams) { const button = { type: "postback", title: teams[team], payload: payloadContext + ":" + object.context.sport + ":" + teams[team] }; buttonArray.push(button); } const body = JSON.stringify({ recipient: { id }, message: { attachment: { type: "template", payload: { template_type: "button", text: "For which team?", buttons: buttonArray } } } }); const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN); return fetch('https://graph.facebook.com/me/messages?' + qs, { method: 'POST', headers: {'Content-Type': 'application/json'}, body, }) .then(rsp => rsp.json()) .then(json => { if (json.error && json.error.message) { throw new Error(json.error.message); } return json; }); }; // Wit.ai Bot Specific Code const sessions = {}; const findOrCreateSession = (fbid) => { let sessionId; Object.keys(sessions).forEach(k => { if (sessions[k].fbid === fbid) { sessionId = k; } }); if (!sessionId) { sessionId = new Date().toISOString(); sessions[sessionId] = {fbid: fbid, context: {}}; } return sessionId; }; const firstEntityValue = (entities, entity) => { const val = entities && entities[entity] && Array.isArray(entities[entity]) && entities[entity].length > 0 && entities[entity][0].value ; if (!val) { return null; } return typeof val === 'object' ? val.value : val; }; const allEntityValues = (entities, entity) => { const val = entities && entities[entity] && Array.isArray(entities[entity]) && entities[entity].length > 0; if (!val) return null; let entityArray = []; let array = entities[entity]; for (const object in array) { entityArray.push(array[object].value); } return entityArray; }; // Wit.ai Bot Actions (The important stuff!) const actions = { send({sessionId}, {text}) { const recipientId = sessions[sessionId].fbid; if (recipientId) { return fbMessage(recipientId, text) .then(() => null) .catch((err) => { console.error("Oops! An error occurred while forwarding the response to" + recipientId + ":" + err.stack || err); sendErrorMessage(userObject.fbid); }); } else { console.error("Oops! Couldn't find user for session: " + sessionId); sendErrorMessage(userObject.fbid); return Promise.resolve(); } }, getAuthentication({ sessionId, context, entities }) { return new Promise((resolve, reject) => { const recipientId = sessions[sessionId].fbid; if (recipientId) { authentication.checkAuthentication(recipientId).then((result) => { if (result == true) { context.returningUser = true; } else { context.newUser = true; } if (isEmpty(entities)) { console.log("Entities not present"); } else { console.log("Entities present"); if (entities.hasOwnProperty("intent") && entities.hasOwnProperty("player")) { const player = allEntityValues(entities, "player"); const intent = allEntityValues(entities, "intent"); let playerObject = {}; if (player.length == 2 && intent.length == 2) { if (intent.indexOf("lineup") != -1 && intent.indexOf("bench") != -1) { playerObject = { firstPlayer: player[0] + ":" + intent[0], secondPlayer: player[1] + ":" + intent[1] }; context.player = playerObject; context.lineup = true; context.bench = true; } else { // TO-DO: Error handling for other intents } } else if (player.length == 2 && intent.length == 1) { // unlikely case if (intent.indexOf("lineup") != -1) { playerObject = { firstPlayer: player[0] + ":" + intent[0], secondPlayer: player[1], missing: "bench" }; context.player = playerObject; context.lineup = true; } else if (intent.indexOf("bench") != -1) { playerObject = { firstPlayer: player[0] + ":" + intent[0], secondPlayer: player[1], missing: "lineup" }; context.player = playerObject; context.bench = true; } } else if (player.length == 1 && intent.length == 2) { if (intent.indexOf("lineup") != -1 && intent.indexOf("bench") != -1) { playerObject = { firstPlayer: player[0] + ":" + intent[0], secondPlayer: ":" + intent[1], missing: "player" }; context.player = playerObject; context.lineup = true; context.bench = true; } else { sendErrorMessage(userObject.fbid); } } else if (player.length == 1 && intent.length == 1) { if (intent.indexOf("lineup") != -1) { playerObject = { firstPlayer: player[0] + ":" + intent[0], missing: "playerbench" }; context.player = playerObject; context.lineup = true; } else if (intent.indexOf("bench") != -1) { playerObject = { firstPlayer: player[0] + ":" + intent[0], missing: "playerlineup" }; context.player = playerObject; context.bench = true; } } else { sendErrorMessage(userObject.fbid); sessions[sessionId].context.done = true; const context = sessions[sessionId].context; actions.clearSession({ sessionId, context }); } if (entities.hasOwnProperty("sport")) { context.sport = firstEntityValue(entities, "sport"); } } else if (entities.hasOwnProperty("intent")) { console.log("Intent present"); if (firstEntityValue(entities, "intent") == "lineup") { console.log("Seeking lineup"); context.lineup = true; if (entities.hasOwnProperty("sport")) { console.log("Sport identified"); context.sport = firstEntityValue(entities, "sport"); } else { console.log("Sport not found"); } } else if (firstEntityValue(entities, "intent") == "standings") { console.log("Seeking standings"); context.standings = true; if (entities.hasOwnProperty("sport")) { console.log("Sport identified"); context.sport = firstEntityValue(entities, "sport"); } else { console.log("Sport not found"); } } else if (firstEntityValue(entities, "intent") == "playing") { console.log("Seeking matchup"); context.matchup = true; if (entities.hasOwnProperty("sport")) { console.log("Sport identified"); context.sport = firstEntityValue(entities, "sport"); } else { console.log("Sport not found"); } } else { // TO-DO: Add more functionality based on user intent } } else if (entities.hasOwnProperty("player")) { console.log("Player present"); context.player = firstEntityValue(entities, "player"); if (entities.hasOwnProperty("datetime")) { console.log("Date identified"); context.datetime = firstEntityValue(entities, "datetime"); } if (entities.hasOwnProperty("sport")) { console.log("Sport identified"); context.sport = firstEntityValue(entities, "sport"); } } else { console.log("Intent not present"); } } console.log(context); console.log("-----------"); return resolve(context); }); } else { console.error("Oops! Couldn't find user for session: " + sessionId); return Promise.resolve(); } }); }, getAuthenticationUrl({ sessionId, context, entities }) { // Getting the OAuth authentication URL and passing it to Wit via context return new Promise((resolve, reject) => { const recipientId = sessions[sessionId].fbid; if (recipientId) { authentication.getAuthenticationUrl(recipientId).then((result) => { context.newAuthentication = result; return resolve(context); }); } else { console.error("Oops! Couldn't find user for session: " + sessionId); } }); }, updateDoneContext({ sessionId, context }) { return new Promise((resolve, reject) => { if (!context.hasOwnProperty("done")) context.done = true; return resolve(context); }); }, clearSession({ sessionId, context }) { return new Promise((resolve, reject) => { if (context.hasOwnProperty("done")) { delete sessions[sessionId]; console.log("Session deleted"); } else { // TO-DO: More error checking console.log("Session not deleted"); } return Promise.resolve(); }); }, deleteUser({ sessionId, context }) { return new Promise((resolve, reject) => { const recipientId = sessions[sessionId].fbid; if (recipientId) { authentication.deleteUser(recipientId).then(() => { console.log("User successfully deleted"); sessions[sessionId].context.done = true; const context = sessions[sessionId].context; actions.clearSession({ sessionId, context }); }) } else { console.error("Oops! Couldn't find user for session: " + sessionId); } }); }, updateSportContext({ sessionId, context, entities }) { return new Promise((resolve, reject) => { console.log("Updating sport context..."); if (entities.hasOwnProperty("sport")) { console.log("Sport entity found"); context.sport = firstEntityValue(entities, "sport"); } else { console.log("Sport entity not found"); context.notSport = true; } console.log(context); return resolve(context); }); }, checkNumberOfLeagues({ sessionId, context }) { return new Promise((resolve, reject) => { const recipientId = sessions[sessionId].fbid; if (recipientId) { yahoo.getTeamCount(recipientId, context.sport).then((count) => { if (count > 1) { context.multipleLeagues = true; } else if (count == 1) { context.singleLeague = true; } else { context.noLeagues = true; context.done = true; } console.log(context); console.log("----------"); return resolve(context); }); } else { console.error("Oops! Couldn't find user for session:", sessionId); return Promise.resolve(); } }); }, sendLeagueMessage({ sessionId, context }) { return new Promise((resolve, reject) => { const recipientId = sessions[sessionId].fbid; if (recipientId) { yahoo.getTeams(recipientId, context.sport).then((result) => { const messageObject = { result, context }; sendTeamsMessage(recipientId, messageObject); context.didNotClick = true; return resolve(context); }); } else { console.error("Oops! Couldn't find user for session:", sessionId); return Promise.resolve(); } }); }, getLineup({ sessionId, context }) { return new Promise((resolve, reject) => { const recipientId = sessions[sessionId].fbid; if (recipientId) { const userObject = { fbid: recipientId, context }; yahoo.getLineup(userObject).then((result) => { sendLineupMessage(userObject, result).then(() => { context.done = true; return resolve(context); }); }); } else { console.error("Oops! Couldn't find user for session:", sessionId); return Promise.resolve(); } }); }, getStandings({ sessionId, context }) { return new Promise((resolve, reject) => { const recipientId = sessions[sessionId].fbid; if (recipientId) { const userObject = { fbid: recipientId, context }; yahoo.getStandings(userObject).then((result) => { sendStandingsMessage(userObject, result).then(() => { context.done = true; return resolve(context); }); }); } else { console.error("Oops! Couldn't find user for session:", sessionId); return Promise.resolve(); } }); }, getMatchup({ sessionId, context }) { return new Promise((resolve, reject) => { const recipientId = sessions[sessionId].fbid; if (recipientId) { const userObject = { fbid: recipientId, context }; console.log("Checking matchup..."); yahoo.getMatchup(userObject).then((result) => { if (result) { sendMatchupMessage(userObject, result); context.done = true; return resolve(context); } else { // TO-DO: Error checking for matchups } }); } else { console.error("Oops! Couldn't find user for session:", sessionId); return Promise.resolve(); } }); }, getPlayerStats({ sessionId, context }) { return new Promise((resolve, reject) => { const recipientId = sessions[sessionId].fbid; if (recipientId) { const userObject = { fbid: recipientId, context }; console.log("Checking player stats..."); yahoo.getPlayerStats(userObject).then((result) => { if (result) { sendPlayerMessage(userObject, result); context.done = true; return resolve(context); } else { // TO-DO: Error checking for stats } }); } else { console.error("Oops! Couldn't find user for session:", sessionId); return Promise.resolve(); } }); }, movePlayers({ sessionId, context }) { return new Promise((resolve, reject) => { const recipientId = sessions[sessionId].fbid; if (recipientId) { console.log(context); console.log("-----------------"); } else { console.error("Oops! Couldn't find user for session:", sessionId); return Promise.resolve(); } }); } }; // Wit Instance Creation const wit = new Wit({ accessToken: WIT_TOKEN, actions, logger: new log.Logger(log.INFO) }); // Webserver Creation and Handling const app = express(); app.use(({method, url}, rsp, next) => { rsp.on('finish', () => { console.log(`${rsp.statusCode} ${method} ${url}`); }); next(); }); app.use(bodyParser.json({ verify: verifyRequestSignature })); app.get('/', (req, res) => { res.send("Welcome to my website!"); }); // Webhook Setup app.get('/webhook', (req, res) => { if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === FB_VERIFY_TOKEN) { res.send(req.query['hub.challenge']); } else { res.sendStatus(400); } }); // OAuth Webhook app.get('/callback', (req, res) => { const oauthToken = res.req.res.socket.parser.incoming.query.oauth_token; const oauthVerifier = res.req.res.socket.parser.incoming.query.oauth_verifier; if (oauthToken != null && oauthVerifier != null) { authentication.updateVerifier(oauthToken, oauthVerifier).then((body) => { if (body == true) { res.redirect("https://www.m.me/fantasybot"); console.log("Preparing to update verifier..."); authentication.getVerifier(oauthVerifier).then((fbid) => { console.log("Preparing to get user details..."); authentication.getUserDetails(fbid).then((data) => { const sessionId = findOrCreateSession(fbid); const firstMessage = "You're all set up!"; const secondMessage = "Since you're new, here are some questions you can ask me.\n• Who is in my baseball lineup?\n• Who am I playing this week in basketball?\n• What are the standings in my hockey league?"; fbMessage(fbid, firstMessage).then(() => { fbMessage(fbid, secondMessage).then(() => { sessions[sessionId].context.done = true; const context = sessions[sessionId].context; actions.clearSession({ sessionId, context }); }); }); }); }); } }); } }); // Message Handler app.post('/webhook', (req, res) => { const data = req.body; if (data.object === 'page') { data.entry.forEach(entry => { entry.messaging.forEach(event => { if (event.message) { const sender = event.sender.id; const sessionId = findOrCreateSession(sender); const {text, attachments} = event.message; if (attachments) { fbMessage(sender, 'Sorry I can only process text messages for now.') .catch(console.error); } else if (text) { // Here is the meat and potatoes of the bot wit.runActions(sessionId, text, sessions[sessionId].context).then((context) => { console.log('Waiting for next user messages'); sessions[sessionId].context = context; }) .catch((err) => { console.error('Oops! Got an error from Wit: ', err.stack || err); }) } } else if (event.postback) { const sender = event.sender.id; const sessionId = findOrCreateSession(sender); const payload = event.postback.payload; const splitPayload = payload.split(":"); if (event.postback.payload == "resetSession") { sessions[sessionId].context.done = true; const context = sessions[sessionId].context; actions.clearSession({ sessionId, context }); } else if (event.postback.payload == "yahooLogout") { authentication.deleteUser(sender).then(() => { console.log("User successfully deleted"); sessions[sessionId].context.done = true; const context = sessions[sessionId].context; actions.clearSession({ sessionId, context }); }); } else { sessions[sessionId].context.multipleLeagues = true; sessions[sessionId].context.sport = splitPayload[1]; sessions[sessionId].context.team = splitPayload[2]; const userObject = { fbid: sender, context: sessions[sessionId].context }; if (splitPayload[0] == "lineup") { yahoo.getLineup(userObject).then((result) => { sendLineupMessage(userObject, result).then(() => { sessions[sessionId].context.done = true; const context = sessions[sessionId].context; actions.clearSession({ sessionId, context }); }); }); } else if (splitPayload[0] == "matchup") { yahoo.getMatchup(userObject).then((result) => { sendMatchupMessage(userObject, result).then(() => { sessions[sessionId].context.done = true; const context = sessions[sessionId].context; actions.clearSession({ sessionId, context }); }); }); } else if (splitPayload[0] == "standings") { yahoo.getStandings(userObject).then((result) => { sendStandingsMessage(userObject, result).then(() => { sessions[sessionId].context.done = true; const context = sessions[sessionId].context; actions.clearSession({ sessionId, context }); }); }); } else if (splitPayload[0] == "player") { yahoo.getPlayerStats(userObject).then((result) => { sendPlayerMessage(userObject, result).then(() => { sessions[sessionId].context.done = true; const context = sessions[sessionId].context; actions.clearSession({ sessionId, context }); }); }); } } } else { console.log('received event', JSON.stringify(event)); } }); }); } res.sendStatus(200); }); function verifyRequestSignature(req, res, buf) { var signature = req.headers["x-hub-signature"]; if (!signature) { console.error("Couldn't validate the signature."); } else { var elements = signature.split('='); var method = elements[0]; var signatureHash = elements[1]; var expectedHash = crypto.createHmac('sha1', FB_APP_SECRET) .update(buf) .digest('hex'); if (signatureHash != expectedHash) { throw new Error("Couldn't validate the request signature."); } } } const isEmpty = (object) => { for (var property in object) { if (object.hasOwnProperty(property)) return false; } return true; } app.listen(PORT); console.log("Server is listening on port " + PORT); <file_sep>/README.md # A Facebook Messenger Bot for Yahoo! Fantasy Sports Easily get updates and manage your Yahoo! Fantasy Sports teams via Facebook Messenger. There are a few simple actions you can do with it including checking your lineup, matchup, player stats, and league standings. Support for multiple leagues across an account is built in as well. In the future, I'm hoping to implement an autoset feature so that the bot will manage your lineup for you by moving players from the bench to the active roster.
cd8d5d91e7823c0f73617257ac498e7df542d201
[ "JavaScript", "Markdown" ]
6
JavaScript
evancloutier/yahoo-fantasy-bot
8ebd4b26e416ad78f0123e5de32007400d84f0ae
34a79bc11acfb92547cc7c585089f8757b18feec
refs/heads/master
<repo_name>sveta0112/fullstack-review<file_sep>/helpers/github.js const request = require('request'); const config = require('../config.js'); const db = require('../database/index.js'); let getReposByUsername = (user, callback) => { // TODO - Use the request module to request repos for a specific // user from the github API // The options object has been provided to help you out, // but you'll have to fill in the URL //console.log(`https://api.github.com/users/${user.term}/repos`); let options = { url: `https://api.github.com/users/${user.term}/repos`, headers: { 'User-Agent': 'request', 'Authorization': `token ${config.TOKEN}` } }; request.get(options , (err, gitBody) => { if(err){ throw err; }else{ //console.log(JSON.parse(gitBody.body.name)); for(var i = 0; i < JSON.parse(gitBody.body).length; i++){ db.save(JSON.parse(gitBody.body)[i].name, JSON.parse(gitBody.body)[i].html_url, JSON.parse(gitBody.body)[i].size); } // db.save(JSON.parse(gitBody.body)); callback(null, JSON.parse(gitBody.body)); } }); } module.exports.getReposByUsername = getReposByUsername;<file_sep>/server/index.js const express = require('express'); const bodyParser = require('body-parser'); var helpers = require('../helpers/github.js'); const db = require('../database/index.js'); let app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(express.static(__dirname + '/../client/dist')); app.post('/repos',(req, res) => { console.log(req.body); helpers.getReposByUsername(req.body, (err, result) =>{ if(err){ throw err; }else{ res.send(result); } }); // TODO - your code here! // This route should take the github username provided // and get the repo information from the github API, then // save the repo information in the database }); app.get('/repos', function (req, res) { // TODO - your code here! // This route should send back the top 25 repos db.find((err, result) => { if(err){ throw err; }else{ var final = result.map(val => val); console.log(final); res.send(final); } }); }); let port = 1128; app.listen(port, function() { console.log(`listening on port ${port}`); }); <file_sep>/client/src/components/RepoList.jsx import React from 'react'; const RepoList = (props) => ( <div> <h4> Repo List Component </h4> There are {props.repos.length} repos. <br/>&nbsp;&nbsp;&nbsp;{props.repos.map((item,index) => (<a key={index} href={item.html_url}><br/>{item.name}<br/>{item.html_url}<br/>&nbsp;&nbsp;&nbsp;&nbsp;<br/>{item.size}</a> ) )} </div> ) export default RepoList;
ea24f871b70f86336bab4dba63dcfb55555fca0f
[ "JavaScript" ]
3
JavaScript
sveta0112/fullstack-review
0cc518ae8d055df34277fcdd411d57235cb9ee50
5cf0634b09404bb92b13b526ecafeb8c07639849
refs/heads/master
<file_sep>package net.weirun.moduleproject.user.login; /** * 登录接口 * Created by JiangYongHao on 2016/7/6. */ public interface OnLoginListener { /** * 登录成功 * * @param data */ void onSuccess(String data); /** * 登录失败 */ void onFailed(String message); /** * 取消登录 * * @param data */ void onCancel(String data); } <file_sep>package net.weirun.gallerylibrary.widget; import android.content.Context; import android.content.res.TypedArray; import android.nfc.FormatException; import android.os.Handler; import android.os.Message; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; import com.bumptech.glide.Glide; import net.weirun.gallerylibrary.MyGalleryAdapter; import net.weirun.gallerylibrary.OnPagerItemClickListener; import net.weirun.gallerylibrary.R; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; /** * Created by JiangYongHao on 2016/7/6. */ public class GalleryPagerView extends RelativeLayout implements ViewPager.OnPageChangeListener { private static final String TAG = "GalleryPagerView"; private ViewPager mViewPager; private LinearLayout mPointLayout; private MyGalleryAdapter mAdapter; private Context mContext; private int timeCount; private OnPagerItemClickListener itemClickListener; /** * 是否自动切换 */ private boolean isAuto = true; /** * 轮播图的点 */ private int mPointId; private int mTimerPosition = 0; private int mViewPosition = 0; /** * 加载图片的位图:图片宽度 */ private int mImageWith; /** * 加载图片的高度: */ private int mImageHeight; /** * 轮播图的宽高比例 */ private float mImageProportion; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { mTimerPosition++; // Log.d(TAG, "handleMessage: -------------------------------------------" + timeCount); if (mTimerPosition == timeCount) { // Log.d(TAG, "handleMessage: = "); int index = mViewPager.getCurrentItem(); index = index % mGallery.size() + 1; mViewPager.setCurrentItem(index, true); mTimerPosition = 0; } } }; private Timer mTimer; private TimerTask mTimerTask = new TimerTask() { @Override public void run() { if (mGallery != null && mGallery.size() > 1 && isAuto) { handler.sendEmptyMessage(0); // Log.d(TAG, "run: ------------------------------------------"); } } }; private List<View> mGallery = new ArrayList<View>(); public GalleryPagerView(Context context) { super(context); init(context); } public GalleryPagerView(Context context, AttributeSet attrs) throws FormatException { super(context, attrs); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.GalleryPagerView); timeCount = array.getInteger(R.styleable.GalleryPagerView_gallery_switching_time, 5); mImageProportion = array.getFloat(R.styleable.GalleryPagerView_gallery_with_height_proportion, 0f); mPointId = array.getResourceId(R.styleable.GalleryPagerView_gallery_gallery_point, R.drawable.point_selector); isAuto = array.getBoolean(R.styleable.GalleryPagerView_gallery_is_auto_switch, true); if (timeCount <= 0) { throw new FormatException("轮播图切换时间不能小于0秒"); } if (mImageProportion < 0) { throw new FormatException("比例大小不能小于0"); } // Log.d(TAG, "GalleryPagerView: timeCount = " + timeCount); if (timeCount < 3) { timeCount = 3; } else if (timeCount > 30) { timeCount = 30; } // Log.d(TAG, "GalleryPagerView: timeCount = " + mPointId); init(context); } /** * 初始化 * * @param context */ private void init(Context context) { mContext = context; View view = inflate(context, R.layout.layout, this); mViewPager = (ViewPager) view.findViewById(R.id.main_view_pager); mPointLayout = (LinearLayout) view.findViewById(R.id.points); mViewPager.addOnPageChangeListener(this); } private int mCurrentPosition; private List<String> mGalleryPaths; /** * 设点点击监听 * * @param itemClickListener */ public void setOnItemClickListener(OnPagerItemClickListener itemClickListener) { this.itemClickListener = itemClickListener; } /** * 是否自动切换 * * @param isAuto */ public void setIsAutoSwitch(boolean isAuto) { this.isAuto = isAuto; } /** * 设置加载图片的宽高度 * * @param with * @param height */ public void setImageSize(int with, int height) { this.mImageHeight = height; this.mImageWith = with; } /** * 设置图片 * * @param galleryPaths */ public void setGallery(List<String> galleryPaths) { mGallery.removeAll(mGallery); if (mPointLayout.getChildCount() > 0) mPointLayout.removeAllViews(); mGalleryPaths = galleryPaths; if (galleryPaths != null && galleryPaths.size() > 0) { if (galleryPaths.size() > 1) { ImageView firstView = createImageView(galleryPaths.get(galleryPaths.size() - 1)); mGallery.add(firstView); for (String url : galleryPaths) { if (url != null) { ImageView imageView = createImageView(url); if (imageView != null) { mGallery.add(imageView); addPoint(); } } } ImageView lastView = createImageView(galleryPaths.get(0)); mGallery.add(lastView); mPointLayout.setVisibility(VISIBLE); mPointLayout.getChildAt(0).setSelected(true); mCurrentPosition = 1; initTimer(); } else if (galleryPaths.size() == 1) { ImageView imageView = createImageView(galleryPaths.get(0)); mPointLayout.setVisibility(GONE); if (imageView != null) { mGallery.add(imageView); } } } mAdapter = new MyGalleryAdapter(mGallery); mViewPager.setAdapter(mAdapter); if (mGallery.size() > 1) mViewPager.setCurrentItem(1); mViewPager.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // Toast.makeText(mContext, "" + mViewPager.getCurrentItem(), Toast.LENGTH_SHORT).show(); // Log.d(TAG, "onClick: -----mViewPager----"); } }); } /** * 初始化定时器 */ private void initTimer() { if (mTimer == null) { mTimer = new Timer(); mTimer.schedule(mTimerTask, 1000, 1000); } else { mTimerPosition = 0; } } /** * 添加点 */ private void addPoint() { ImageView pointView = new ImageView(mContext); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(20, 20); pointView.setPadding(3, 3, 3, 3); pointView.setLayoutParams(params); pointView.setImageResource(mPointId); pointView.setSelected(false); mPointLayout.addView(pointView); } private ImageView createImageView(String url) { if (url != null) { ImageView imageView = new ImageView(mContext); if (mImageHeight > 0 && mImageWith > 0) { Glide.with(mContext).load(url).centerCrop().override(mImageWith, mImageHeight).into(imageView); } else { Glide.with(mContext).load(url).centerCrop().into(imageView); } imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // Toast.makeText(mContext, "" + mViewPager.getCurrentItem(), Toast.LENGTH_SHORT).show(); Log.d(TAG, "onClick: -----mViewPager----"); if (itemClickListener != null) { itemClickListener.onPagerItemClick(mCurrentPosition); } } }); return imageView; } return null; } /** * 设置轮播图的宽高比例 * * @param scale */ public void setScale(float scale) throws Exception { if (scale <= 0) { throw new Exception("轮播图比例不能小于或者等于0"); } mImageProportion = scale; } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // Log.d(TAG, "onPageScrolled: -----------------------------" + position); } @Override public void onPageSelected(int position) { mViewPosition = position; if (position == 0) { position = mPointLayout.getChildCount() - 1; } else { position = (position - 1) % (mGallery.size() - 2); } if (position != mCurrentPosition) { mPointLayout.getChildAt(position).setSelected(true); mPointLayout.getChildAt(mCurrentPosition).setSelected(false); Log.d(TAG, "onPageSelected: position = " + position); Log.d(TAG, "onPageSelected: mCurrentPosition = " + mCurrentPosition); mCurrentPosition = position; } } @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager.SCROLL_STATE_IDLE) { mTimerPosition = 0; if (mGallery != null && mGallery.size() > 1) { if (mViewPosition < 1) { // mCurrentPosition = mGalleryPaths.size(); mViewPager.setCurrentItem(mGallery.size() - 2, false); } else if (mViewPosition > mGallery.size() - 2) { // mCurrentPosition = 0; mViewPager.setCurrentItem(1, false); } } Log.d(TAG, "onPageSelected: mCurrentPosition 后 = " + mCurrentPosition); Log.d(TAG, "============================================================= "); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.d(TAG, "onMeasure: mode = " + MeasureSpec.getMode(widthMeasureSpec)); Log.d(TAG, "onMeasure: mode = " + MeasureSpec.getMode(heightMeasureSpec)); Log.d(TAG, "onMeasure: size = " + MeasureSpec.getSize(widthMeasureSpec)); if (mImageProportion > 0) { int width = MeasureSpec.getSize(widthMeasureSpec); mImageWith = width; mImageHeight = (int) (width * mImageProportion); setViewHeight(mImageHeight); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } private void setViewHeight(int height) { ViewGroup.LayoutParams params = this.getLayoutParams(); params.width = ViewGroup.LayoutParams.MATCH_PARENT; params.height = height; this.setLayoutParams(params); } @Override protected void onDetachedFromWindow() { cancelTimer(); Log.d(TAG, "onDetachedFromWindow: "); super.onDetachedFromWindow(); } /** * 取消定时器 */ public void cancelTimer() { if (mTimer != null) { mTimerTask.cancel(); mTimer.cancel(); mTimer = null; } } } <file_sep># ModuleProject02 测试提交 无限自动轮播图小demo : <file_sep>package net.weirun.moduleproject.user.login; /** * Created by JiangYongHao on 2016/7/6. */ public interface LoginViewIF { /** * 提示信息 * * @param message */ void showToast(String message); /** * 获取登录信息 * * @param userName * @param passWord */ void getLoginMessage(String userName, String passWord); /** * 调转页面 */ void moveToIndex(); } <file_sep>package net.weirun.moduleproject.http; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.Toast; import com.yolanda.nohttp.Headers; import com.yolanda.nohttp.NoHttp; import com.yolanda.nohttp.RequestMethod; import com.yolanda.nohttp.download.DownloadListener; import com.yolanda.nohttp.download.DownloadQueue; import com.yolanda.nohttp.download.DownloadRequest; import com.yolanda.nohttp.rest.OnResponseListener; import com.yolanda.nohttp.rest.Request; import com.yolanda.nohttp.rest.RequestQueue; import com.yolanda.nohttp.rest.Response; import java.io.File; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Created by JiangYongHao on 2016/7/5. */ public class HttpUtil { private static HttpUtil httpUtil; private static RequestQueue requestQueue; private Context mContext; public static final int TIME_OUT = 10000; private net.weirun.moduleproject.http.OnResponseListener listener; private static DownloadQueue downloadQueue; private net.weirun.moduleproject.http.DownloadListener mDownloadListener; public static HttpUtil newInstance() { if (httpUtil == null) { httpUtil = new HttpUtil(); requestQueue = NoHttp.newRequestQueue(); downloadQueue = NoHttp.newDownloadQueue(); } return httpUtil; } /** * 当有文件上传的时候使用此方法 * * @param url 请求路径 * @param what 请求标志 * @param params 请求附加键值对 Map * @param listener 请求的监听 */ public void post(@NonNull String url, int what, Map<String, String> params, net.weirun.moduleproject.http.OnResponseListener listener) { this.listener = listener; Request<String> request = NoHttp.createStringRequest(url, RequestMethod.POST); setCancelSign(what, request); if (params != null) { request.add(params); } requestQueue.add(what, request, responseListener); } /** * 当有文件上传的时候使用此方法 * * @param url 请求路径 * @param what 请求标志 * @param params 请求附加键值对 Map * @param files 请求上传的文件的路径 * @param listener 请求的监听 */ public void post(@NonNull String url, int what, Map<String, String> params, Map<String, String> files, net.weirun.moduleproject.http.OnResponseListener listener) { this.listener = listener; Request<String> request = createRequest(url, RequestMethod.POST); setCancelSign(what, request); if (params != null) { request.add(params); } addFiles(files, request); requestQueue.add(what, request, responseListener); } /** * @param request * @param what * @param listener */ public void post(@NonNull Request<String> request, int what, net.weirun.moduleproject.http.OnResponseListener listener) { this.listener = listener; if (request != null) { request.setConnectTimeout(TIME_OUT); requestQueue.add(what, request, responseListener); } } /** * @param url 请求的路径Url * @param what 请求标志:可以用于取消连接 * @param listener 请求监听 */ public void get(@NonNull String url, int what, net.weirun.moduleproject.http.OnResponseListener listener) { this.listener = listener; // this.mContext = context; Request<String> request = NoHttp.createStringRequest(url, RequestMethod.GET); setCancelSign(what, request); requestQueue.add(what, request, responseListener); } /** * 根据路径 ,下载文件 * * @param what 下载标志:可用于取消下载 * @param url 下载文件的url * @param path 下载的文件的存放路径 * @param isDeleteOld 是否删除已有的文件(如果有) * @param listener 下载监听器 */ public void downloadFile(int what, @NonNull String url, @NonNull String path, boolean isDeleteOld, net.weirun.moduleproject.http.DownloadListener listener) { if (url != null) { this.mDownloadListener = listener; DownloadRequest downloadRequest = NoHttp.createDownloadRequest(url, path, isDeleteOld); setCancelSign(what, downloadRequest); downloadQueue.add(what, downloadRequest, downloadListener); } else { } } /** * 根据路径 ,下载文件 * * @param what 下载标志:可用于取消下载 * @param url 下载文件的url * @param path 下载的文件的存放路径 * @param fileName 下载的文件的自定义名称 * @param isRange 是否断点下载 * @param isDeleteOld 是否删除已有的文件(如果有) * @param listener 下载监听器 */ public void downloadFile(int what, @NonNull String url, @NonNull String path, String fileName, boolean isRange, boolean isDeleteOld, net.weirun.moduleproject.http.DownloadListener listener) { this.mDownloadListener = listener; DownloadRequest downloadRequest = NoHttp.createDownloadRequest(url, path, fileName, isRange, isDeleteOld); setCancelSign(what, downloadRequest); downloadQueue.add(what, downloadRequest, downloadListener); } /** * 穿件请求 */ private Request createRequest(@NonNull String url, @NonNull RequestMethod method) { return NoHttp.createStringRequest(url, method); } /** * 把文件添加到请求 * * @param files * @param request */ private void addFiles(Map<String, String> files, Request<String> request) { if (files != null) { Set<Map.Entry<String, String>> entries = files.entrySet(); // Iterator<Map.Entry<String, String>> it = entries.iterator(); for (Map.Entry<String, String> entry : entries) { if (entry != null) { String key = entry.getKey(); String value = entry.getValue(); if (value != null) { File file = new File(value); request.add(key, file); } } } } } /** * 设置请求的取消标志 * * @param what * @param request */ private void setCancelSign(int what, DownloadRequest request) { if (request != null) { request.setCancelSign(what); request.setConnectTimeout(TIME_OUT); } } /** * 设置请求的取消标志 * * @param what * @param request */ private void setCancelSign(int what, Request<String> request) { if (request != null) { request.setCancelSign(what); request.setConnectTimeout(TIME_OUT); } } /** * 取消数据请求 * * @param sign */ public void cancelBySign(int sign) { requestQueue.cancelBySign(sign); } /** * 取消下载请求 * * @param sign */ public void cancelDownloadBySign(int sign) { downloadQueue.cancelBySign(sign); } /** * 取消所有的数据请求请求 */ public void cancelAll() { requestQueue.cancelAll(); } /** * 取消所有的下载请求请求 */ public void cancelAllDownload() { requestQueue.cancelAll(); } /** * 取消所有的请求 */ public void cancelAllRequest() { requestQueue.cancelAll(); downloadQueue.cancelAll(); } private OnResponseListener responseListener = new OnResponseListener() { @Override public void onStart(int what) { if (listener != null) { listener.onStart(what); } } @Override public void onSucceed(int what, Response response) { if (listener != null) { listener.onSucceed(what, response.get().toString()); } } @Override public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) { if (mContext != null) Toast.makeText(mContext, "连接失败!", Toast.LENGTH_SHORT).show(); if (listener != null) onFailed(what, url, tag, exception, responseCode, networkMillis); } @Override public void onFinish(int what) { if (listener != null) { listener.onFinish(what); } } }; /** * 下载文件监听器 */ private DownloadListener downloadListener = new DownloadListener() { @Override public void onDownloadError(int what, Exception exception) { if (mDownloadListener != null) { mDownloadListener.onDownloadError(what, exception); } } @Override public void onStart(int what, boolean isResume, long rangeSize, Headers responseHeaders, long allCount) { if (mDownloadListener != null) { mDownloadListener.onStart(what, isResume, rangeSize, responseHeaders, allCount); } } @Override public void onProgress(int what, int progress, long fileCount) { if (mDownloadListener != null) { mDownloadListener.onProgress(what, progress, fileCount); } } @Override public void onFinish(int what, String filePath) { if (mDownloadListener != null) { mDownloadListener.onFinish(what, filePath); } } @Override public void onCancel(int what) { if (mDownloadListener != null) { mDownloadListener.onCancel(what); } } }; } <file_sep>package net.weirun.moduleproject.utils; import android.content.Context; import android.os.Handler; import android.os.Message; import android.widget.TextView; import java.util.Timer; import java.util.TimerTask; /** * Created by JiangYongHao on 2016/6/17. * <p/> * 定时器帮助类 */ public class TimerUtil { /** * 时间到了就执行 */ public interface OnTimeOutListener { /** * 时间到了就执行 */ void onTimeOut(int time, boolean isStop); } private OnTimeOutListener listener; /** * 定时的时间 单位m */ private int timeCount; /** * 当前的时间标志 m */ private int currentTime = 0; private boolean isAdd; private TextView timeTextView; private String mNormalText; private String mAppendText; private StringBuilder mBuilder = new StringBuilder(); public void setListener(OnTimeOutListener listener) { this.listener = listener; } /** * 启动 * * @param count */ public void startTimer(int count) { this.timeCount = count; isAdd = true; currentTime = count; startTimer(); } // /** // * 启动 // * // * @param count // */ // public void startTimer(int count, TextView textView) { // this.timeTextView = textView; // textView.setText("" + count); // this.timeCount = count; // isAdd = true; // currentTime = count; // startTimer(); // } /** * 启动定时器 * * @param count 时间 s :秒 * @param textView 需要显示的view * @param normal View 默认的显示字符串 * @param append 在时间后添加的字符串 */ public void startTimer(int count, TextView textView, String normal, String append) { this.timeTextView = textView; textView.setText("" + count); this.timeCount = count; isAdd = true; currentTime = count; this.mNormalText = normal; this.mAppendText = append; startTimer(); } /** * 停止计时器 */ public void stopTimer() { if (timer != null) { timer.cancel(); timerTask.cancel(); timer = null; } } /** * 启动定时器 */ private void startTimer() { if (timer == null) { timer = new Timer(); timer.schedule(timerTask, 0, 1000); } } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1001) { if (isAdd) { currentTime--; if (currentTime >= 0) { if (listener != null) { listener.onTimeOut(currentTime, false); } if (timeTextView != null) { mBuilder.delete(0, mBuilder.length()); mBuilder.append(currentTime); if (mAppendText != null) { mBuilder.append(mAppendText); } timeTextView.setText(mBuilder.toString()); } } else { if (listener != null) { listener.onTimeOut(currentTime, true); } if (timeTextView != null && mNormalText != null) { timeTextView.setText(mNormalText); } else if (timeTextView != null) { timeTextView.setText(""); } isAdd = false; currentTime = -1; } } } super.handleMessage(msg); } }; private Timer timer; private TimerTask timerTask = new TimerTask() { @Override public void run() { handler.sendEmptyMessage(1001); } }; } <file_sep>package net.weirun.moduleproject.constant; /** * Created by JiangYongHao on 2016/4/2. */ public class ShareFileKey { // 用户信息 /** * file name */ public static final String FILE_NAME = "ProjectFile"; public static final String KEY_IS_SPLASH_SHOW= "is_splash_show"; /** * SESSION */ public static final String USER_SESSION = "session_id"; /** * 是否登录 */ public static final String USER_IS_LOGIN = "isLogin"; /** * 用户名称 */ public static final String USER_NAME = "UserName"; /** * 用户昵称 */ public static final String USER_NICK_NAME = "nickname"; /** * 用户头像url */ public static final String USER_PORTRAIT = "userPortrait"; /** * 用户鲜花 */ public static final String USER_FLOWER = "flower"; /** * 用户已用空间 */ public static final String USER_SPACE_USE = "disk_space_use"; /** * 用户天然号 */ public static final String USER_ACCOUNT_NAME = "user_name_account"; /** * 用户天然号 */ public static final String USER_ID = "user_ID"; /** * 用户电话 */ public static final String USER_PHONE = "user_phone"; /** * 省份 */ public static final String KEY_ADDRESS_PROVINCE = "ADDRESS_PROVINCE"; /** * 城市 */ public static final String KEY_ADDRESS_CITY = "ADDRESS_CITY"; /** * 区 */ public static final String KEY_ADDRESS_DISTRICT = "ADDRESS_DISTRICT"; } <file_sep>package net.weirun.moduleproject.http; import com.yolanda.nohttp.rest.Response; /** * Created by JiangYongHao on 2016/7/5. */ public interface OnResponseListener { /** * 当请求开始. * * @param what the credit of the incoming request is used to distinguish between multiple requests. */ void onStart(int what); /** * 请求成功返回数据 * * @param what 所设置的请求码 * @param data 请求成功返回的数据 */ void onSucceed(int what,String data); /** * 当请求失败的时候执行此方法 * * @param what the credit of the incoming request is used to distinguish between multiple requests. * @param url url. * @param tag tag of request callback. * @param exception error types. Error types include the following:<p>{@link com.yolanda.nohttp.error.NetworkError} The network is not available, please check the network.</p> * <p>{@link com.yolanda.nohttp.error.TimeoutError} Connect to the server or a timeout occurred while reading data.</p> * <p>{@link com.yolanda.nohttp.error.UnKnownHostError} Is not found in the network of the target server.</p> * <p>{@link com.yolanda.nohttp.error.URLError} Download url is wrong.</p> * @param responseCode server response code. * @param networkMillis request process consumption time. */ void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis); /** * 当请求完成 * * @param what the credit of the incoming request is used to distinguish between multiple requests. */ void onFinish(int what); } <file_sep>package net.weirun.moduleproject; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.yolanda.nohttp.NoHttp; import com.yolanda.nohttp.RequestMethod; import com.yolanda.nohttp.rest.Request; import net.weirun.gallerylibrary.widget.GalleryPagerView; import net.weirun.moduleproject.utils.TimerUtil; import net.weirun.moduleproject.version.VersionUtils; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private List<String> galleryPaths = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); galleryPaths.add("http://img5.imgtn.bdimg.com/it/u=2340349138,2028497687&fm=21&gp=0.jpg"); galleryPaths.add("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1467865811&di=8ebb2dfecfcdd5edae59b037eee3601e&src=http://g.hiphotos.baidu.com/zhidao/pic/item/4034970a304e251f3ba0d299a186c9177f3e537f.jpg"); galleryPaths.add("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1467865811&di=55eb478c7703ed9821aad8c66afd3cb2&src=http://e.hiphotos.baidu.com/zhidao/pic/item/b219ebc4b74543a9ee2c5fc11c178a82b9011483.jpg"); galleryPaths.add("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1467865811&di=8ebb2dfecfcdd5edae59b037eee3601e&src=http://g.hiphotos.baidu.com/zhidao/pic/item/4034970a304e251f3ba0d299a186c9177f3e537f.jpg"); galleryPaths.add("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1467865811&di=55eb478c7703ed9821aad8c66afd3cb2&src=http://e.hiphotos.baidu.com/zhidao/pic/item/b219ebc4b74543a9ee2c5fc11c178a82b9011483.jpg"); galleryPaths.add("http://img3.imgtn.bdimg.com/it/u=332767035,3916081752&fm=21&gp=0.jpg"); GalleryPagerView pagerView = (GalleryPagerView) findViewById(R.id.nav_gallery); pagerView.setGallery(galleryPaths); VersionUtils versionUtils = new VersionUtils(); versionUtils.checkVersion(this); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); // drawer.setDrawerListener(toggle); drawer.addDrawerListener(toggle); toggle.syncState(); TextView textView = (TextView) findViewById(R.id.code); TimerUtil util = new TimerUtil(); util.setListener(new TimerUtil.OnTimeOutListener() { @Override public void onTimeOut(int time, boolean isStop) { } }); util.startTimer(60); util.startTimer(60, textView, "获取验证码", "秒后重新获取"); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.END)) { drawer.closeDrawer(GravityCompat.END); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.END); return true; } public void clickBT(View view) { Intent intent = new Intent(); intent.setClass(this, Main2Activity.class); startActivity(intent); } } <file_sep>package net.weirun.moduleproject.version; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.Log; import java.net.HttpURLConnection; /** * Created by JiangYongHao on 2016/7/8. */ public class VersionUtils { private static final String TAG = "VersionUtils"; public static final String URL = ""; public void checkVersion(Context context) { getCurrentVersion(context); } /** * 获取当前版本号 * * @param context */ private void getCurrentVersion(Context context) { PackageManager packageManager = context.getPackageManager(); try { PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0); Log.d(TAG, "getCurrentVersion: version = " + packageInfo.versionName); Log.d(TAG, "getCurrentVersion: version = " + packageInfo.versionCode); // return;packageInfo.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } // HttpURLConnection } } <file_sep>package net.weirun.moduleproject.user.login; /** * Created by JiangYongHao on 2016/7/6. */ public interface LoginModule { /** * 登录 */ void login(String userName,String passWord,String url,OnLoginListener loginListener); /** * 退出 */ void exit(); }
2b5d47fee81530c5502925f04d2471997b82fe5f
[ "Markdown", "Java" ]
11
Java
JiangYongHao/ModuleProject02
ac979b03abce8142388660311983a28f8e22df7e
fdd2da58c09c867118f6863112630ab423afd57a
refs/heads/master
<file_sep>from guizero import App, PushButton import socket import time import keyboard # ##SERVER # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object # host = "192.168.178.22" # Get local machine name # port = 8765 # Reserve a port for your service. # s.bind((host, port)) # Bind to the port # s.listen(1) # Now wait for client connection. # while True: # c, addr = s.accept() # Establish connection with client. # print ('Got connection from', addr) # data = c.recv(1024) # print(data) # c.send('Thank you for connecting'.encode()) # c.close() # Close the connection # method to set the key or combination for each button def map_key(keynumber): buttons[keynumber].bg = "red" time.sleep(0.01) #record event keymaps[keynumber] = keyboard.read_hotkey() print (keymaps[keynumber]) app = App(title="Keypad example", width=200, height=90, layout="grid") buttons = [ PushButton(app, command=map_key, args=[0], text="1", grid=[0,0]), PushButton(app, command=map_key, args=[1], text="2", grid=[1,0]), PushButton(app, command=map_key, args=[2], text="3", grid=[2,0]), PushButton(app, command=map_key, args=[3], text="4", grid=[3,0]), PushButton(app, command=map_key, args=[4], text="5", grid=[0,1]), PushButton(app, command=map_key, args=[5], text="6", grid=[1,1]), PushButton(app, command=map_key, args=[6], text="7", grid=[2,1]), PushButton(app, command=map_key, args=[7], text="8", grid=[3,1]) ] keymaps = [ "", #hotkey for key 1 etc "", "", "", "", "", "", "" ] app.display()<file_sep>import time from threading import Thread class keyboard: thread = Thread() keymap = ["" for x in range(8)] keymap[0] = "YEEET" print(keymap)<file_sep>import server import GUI import keyboard class Main: print("YEEEET")<file_sep>import threading import socket import time from threading import Thread class Server: thread = Thread() def __init__(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object host = "192.168.178.22" # Get local machine name port = 8765 # Reserve a port for your service. s.bind((host, port)) # Bind to the port s.listen(1) # Now wait for client connection. run_forever(self) #SERVER """keep the server up""" def run_forever(self): # runnning forever while True: c, addr = self.s.accept() # Establish connection with client. print ('Got connection from', addr) # show the client connection data = c.recv(1024) # get data sent from client print(data) c.send('Thank you for connecting'.encode()) # message the client c.close() # Close the connection<file_sep>from guizero import App, PushButton import time import keyboard # method to set the key or combination for each button def map_key(keynumber): buttons[keynumber].bg = "red" app = App(title="Keypad example", width=200, height=90, layout="grid") buttons = [ PushButton(app, command=map_key, args=[0], text="1", grid=[0,0]), PushButton(app, command=map_key, args=[1], text="2", grid=[1,0]), PushButton(app, command=map_key, args=[2], text="3", grid=[2,0]), PushButton(app, command=map_key, args=[3], text="4", grid=[3,0]), PushButton(app, command=map_key, args=[4], text="5", grid=[0,1]), PushButton(app, command=map_key, args=[5], text="6", grid=[1,1]), PushButton(app, command=map_key, args=[6], text="7", grid=[2,1]), PushButton(app, command=map_key, args=[7], text="8", grid=[3,1]) ] app.display()
d441aa6d426d3c0539aefc845e502cafca7fefee
[ "Python" ]
5
Python
Lillux-de/PiBoard
132e8c2e3d37a52804c7338712d90a0518646682
555c6cb4e34237bf8b244dc7934d1d81da074d38
refs/heads/master
<file_sep># Data Strucutures :pushpin: Description ## TODO :clipboard: - Stack - Queue - Graph ## DOING :writing_hand: - LinkedList ## DONE :heavy_check_mark: - Tree<file_sep>public class Tree { private Node root; private String name; public int height = 0; // Initialize the tree public Tree(Node root, String name) { this.root = root; this.name = name; } public Tree(Node root) { this.root = root; this.name = null; } public Tree() { this.root = null; this.name = null; } public void setRoot() { this.root = null; } public void removeChildren(Node parent) { // removing all children from a node parent.setChildren(null); } public void remove(Node node) { // to remove a nood we need to find its parent and then use the node class to remove // a specific child if (this.root == node) { this.root = null; } this.helpRemove(this.root, node); } private void helpRemove(Node parent, Node target) { if (parent.hasChildren()) { for (Node child: parent.getChildren()) { if (child.equals(target)) { parent.remove(child); } if (child.hasChildren()) { helpRemove(child, target); } } } } public void display(){ if (this.name != null) { System.out.println(this.name); } helpDisplay(this.root, 0); System.out.println(); } private void helpDisplay(Node node, int depth) { String formatting = ""; if (depth > 0) { formatting = "|__"; for (int i = 0; i < depth - 1; i++) { formatting = " " + formatting; } } System.out.println(formatting + node.toString()); if (node.hasChildren()) { for (Node child: node.getChildren()) { helpDisplay(child, depth + 1); } } } }
ece3fa68fb761c46094e05a10e8f329eb216a3c5
[ "Markdown", "Java" ]
2
Markdown
Sbu-05-exe/Java-Data-Structures
4ec4cdf4c65c698908ded8fa18fabcd910f730f6
792c8ca54c26813ce9c77d53daf7fbbab7318123
refs/heads/main
<repo_name>DiogaoDoBargalhao/WeatherPredictionForJena<file_sep>/ForecastingWeatherDiogoAlves.py """ Weather Forecasting problem for the Jena Dataset Comments are marked with a #. If running, please stop in each block and read the comments carefully! Each block ends in a space and the next begins with a comment sign. Dataset: https://www.kaggle.com/pankrzysiu/weather-archive-jena Description of the variables of the data: p (mbar) - Air pressure (SI: bar) T (degC) - Air Temperature (SI: Celsius) Tpot (K) - Air Temperature (SI: Kelvin (+273.42 K)) rh - relative humidity VPmax, VPact, VPdef - Vapor pressure (maximum, actual, definite(?)) sh - No idea! H2OC - Water concentration or humidity rho - Air density (SI - g/m**3) wv, maxwv - Wind velocity (average, maximum) (SI - m/s) wd - Wind direction (SI - Deg) """ # Imports, including packages for Regression and Data Visualization, error metrics import pandas as pd import numpy as np import matplotlib.pyplot as plt from pandas.plotting import lag_plot,autocorrelation_plot import seaborn as sn import statsmodels.api as sm from statsmodels.tsa.api import VAR from statsmodels.tsa.stattools import adfuller, grangercausalitytests import pickle from datetime import datetime from pmdarima import auto_arima from scipy.stats import pearsonr from tbats import TBATS from autots import AutoTS import matplotlib.dates as mdates # Reads the csv file from disk WeatherTimeSeries = pd.read_csv( r'HOMEDIRECTORY\jena_climate_2009_2016.csv', parse_dates=True, index_col=0) WeatherTimeSeries.index.name = 'Date/Time' WeatherTimeSeries.reset_index(inplace=True) WeatherSeriesDate = WeatherTimeSeries.iloc[:,0] WeatherSeriesDate = pd.to_datetime(WeatherSeriesDate) # Temperature as the Target: WeatherSeriesTarget = WeatherTimeSeries.iloc[:,2] # Getting explanatory variables to explain temperature Explanatory_Vars = WeatherTimeSeries.columns.tolist() Explanatory_Vars.remove('Date/Time') Explanatory_Vars.remove('T (degC)') WeatherSeriesExplanatory = WeatherTimeSeries.loc[:, Explanatory_Vars] Series = [WeatherSeriesTarget,WeatherSeriesExplanatory] WeatherSeries = pd.concat(Series,axis=1) # Basic descriptive statistics of Target, see whether there are outliers, Missing values, extreme values... WeatherSeriesTarget.describe() plt.plot(WeatherSeriesTarget) plt.title("Weather as Temperature Over Time") plt.xlabel('Date') plt.ylabel('Value') plt.show() plt.hist(WeatherSeriesTarget, bins=10) plt.show() # A boxplot: sn.boxplot(WeatherSeriesTarget,orient = "h",palette = "Set2") # Mean temp of around 10 degrees. # Describing explanatory variables individually: for column in WeatherSeriesExplanatory.columns: WeatherSeriesExplanatory[column].describe() figure = plt.figure plt.plot(WeatherSeriesExplanatory[column]) plt.title(column) plt.xlabel('Date') plt.ylabel('Value') plt.show() # Plots together for viewing convenience: fig, axes = plt.subplots(nrows=3, ncols=4, dpi=120, figsize=(10,6)) for i, ax in enumerate(axes.flatten()): data = WeatherSeriesExplanatory[WeatherSeriesExplanatory.columns[i]] ax.plot(data, color='blue', linewidth=1) # Decorations ax.set_title(WeatherSeriesExplanatory.columns[i]) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') ax.spines["top"].set_alpha(0) ax.tick_params(labelsize=6) plt.tight_layout(); # Most of the variables are seasonal as well, except the last 3. Except for these three, they co-evolve, apparently. # See how Target and explanatory variables co-evolve, first by plotting together, # then finding correlation, and scatterplots: for col in WeatherSeriesExplanatory.columns: figure = plt.figure ax = plt.gca() ax.scatter(WeatherSeriesExplanatory[col], WeatherSeriesTarget) ax.set_xlabel(col) ax.set_ylabel("Temperature") ax.set_title("Scatterplot {} and {}".format(col,"Temperature")) plt.legend() plt.show() # Views together: fig, axes = plt.subplots(nrows=3, ncols=4, dpi=120, figsize=(10,6)) for i, ax in enumerate(axes.flatten()): data = WeatherSeriesExplanatory[WeatherSeriesExplanatory.columns[i]] ax.scatter(data, WeatherSeriesTarget) # Decorations ax.set_title(WeatherSeriesExplanatory.columns[i]) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') ax.set_title("{} and {}".format(WeatherSeriesExplanatory.columns[i],"Target")) ax.tick_params(labelsize=6) plt.tight_layout(); # A simple Correlation Matrix to find the most correlated variables: corr = WeatherSeries.corr() sn.heatmap(corr, xticklabels=corr.columns.values, yticklabels=corr.columns.values) CorrVars = WeatherSeries.corr()["T (degC)"].sort_values(ascending = False).to_frame() CorrVars.index.name = 'Variable' CorrVars.reset_index(inplace=True) CorrVars = CorrVars.iloc[1:] # Finding most correlated variables: CorrVars.rename(columns = {'T (degC)':'Correlation'}, inplace = True) CorrVars = CorrVars.loc[abs(CorrVars['Correlation']) >= 0.5].iloc[:,0].to_dict() # Subsetting the Explanatory dataframe to these: Interesting_Explanatory = WeatherSeriesExplanatory[[col_name for col_name in CorrVars.values()]] # Note how all the variables except the last 3 are relevant. We could easily exclude them from analysis. # In other words, wind speed and wind direction have no effect on Temperature. # Air pressure seems to have a nonlinear relationship, whereas air density has a negative relationship with temperature. ## Repeating the heatmap only with these variables and Temperature: temp = [WeatherSeriesTarget,Interesting_Explanatory] temp = pd.concat(temp,axis=1) corr_2 = temp.corr() sn.heatmap(corr_2, xticklabels=corr_2.columns.values, yticklabels=corr_2.columns.values) # Plotting the most correlated time series together for Visual inspection: for column in Interesting_Explanatory.columns: fig, ax_left = plt.subplots() ax_right = ax_left.twinx() ax_left.plot(WeatherSeriesTarget, color='black') ax_right.plot(Interesting_Explanatory[column], color='red') ax.set_title("TimeSeries {} and {}".format("Temperature",column)) plt.show() # Lag plot and Autocorrelation Function of target: lag_plot(WeatherSeriesTarget) autocorrelation_plot(WeatherSeriesTarget) # Seasonal and trend decomposition of original series Decomp = sm.tsa.seasonal_decompose(WeatherSeriesTarget,freq = 365 * 24 * 6) fig = Decomp.plot() fig.set_figheight(8) fig.set_figwidth(15) plt.show() # Note absence of upward or downward trend of temperatures, as well as clear seasonal cycles at several levels (days, months, years) in humps! # Testing for stationarity of the series through the ADF test: def adf_test(ts, signif=0.05): dftest = adfuller(ts, autolag='AIC') adf = pd.Series(dftest[0:4], index=['Test Statistic','p-value','# Lags','# Observations']) for key,value in dftest[4].items(): adf['Critical Value (%s)'%key] = value print (adf) p = adf['p-value'] if p <= signif: print(f"Stationary") else: print(f"Non-Stationary") #apply adf test on the series (Stationarity) adf_test(WeatherSeriesTarget) # Doing ADF on each time series: for name, column in WeatherSeries.iteritems(): adf_test(column) print('\n',column.name) # The conclusion is that all series are I(0), i.e stationary, as wel could see from visual inspection! ## Choose a level of aggregation (if needed!) Can choose several and proceed: ## Note that there are several cycles within each time period, hourly, daily, etc. test_3 = [WeatherSeriesDate,WeatherSeriesTarget,WeatherSeriesExplanatory] Full_explanatory = pd.concat(test_3,axis=1) # Aggregating Time series by hour, day, week, and month, then choose a level: Full_explanatory['Date/Time'] = pd.to_datetime(Full_explanatory['Date/Time']) Hourly_Full_explanatory = Full_explanatory.resample('60T', on='Date/Time').mean() Hourly_Full_explanatory.index.name = 'Date/Time' Hourly_Full_explanatory.reset_index(inplace=True) Hourly_Full_explanatory['Date/Time'] = pd.to_datetime(Hourly_Full_explanatory['Date/Time']) Daily_Full_explanatory = Full_explanatory.resample('1440T', on='Date/Time').mean() Daily_Full_explanatory.index.name = 'Date/Time' Daily_Full_explanatory.reset_index(inplace=True) Daily_Full_explanatory['Date/Time'] = pd.to_datetime(Daily_Full_explanatory['Date/Time']) Weekly_Full_explanatory = Full_explanatory.resample('W', on='Date/Time').mean() Weekly_Full_explanatory.index.name = 'Date/Time' Weekly_Full_explanatory.reset_index(inplace=True) Weekly_Full_explanatory['Date/Time'] = pd.to_datetime(Weekly_Full_explanatory['Date/Time']) Monthly_Full_explanatory = Full_explanatory.resample('M', on='Date/Time').mean() Monthly_Full_explanatory.index.name = 'Date/Time' Monthly_Full_explanatory.reset_index(inplace=True) Monthly_Full_explanatory['Date/Time'] = pd.to_datetime(Monthly_Full_explanatory['Date/Time']) # I do not have computing power enough to calculate data hourly, can choose, WLOG, daily means: # Daily Mean temperature looks like a good aggregation level. Look at periodicity: res = sm.tsa.seasonal_decompose(Daily_Full_explanatory.iloc[:,1].dropna(),freq = 365) fig = res.plot() fig.set_figheight(8) fig.set_figwidth(15) plt.show() # There are still several seasonal cycles, monthly, and yearly at this level of aggregation. # The months can clearly be seen as humps on the seasonal graph over a year (around 12) # This block separates out data for training and testing: # Use 2016 as test data, noting there is a day of 2017 in the end of the test data (367 data points to predict from test)! Train_Beginning_index = 0 Train_end_index = len(Daily_Full_explanatory) - len(Daily_Full_explanatory[Daily_Full_explanatory['Date/Time'].dt.strftime('%Y.%m.%d').str.contains("2016")]) - 1 Test_Beginning_index = Train_end_index Test_end_index = len(Daily_Full_explanatory) Train_Time_Series = Daily_Full_explanatory.iloc[Train_Beginning_index:Train_end_index,:] Test_Time_Series = Daily_Full_explanatory.iloc[Test_Beginning_index:Test_end_index,:] # last year for testing # Testing several approaches on train data: # Approach 1: AutoML approach TBATS (see https://pypi.org/project/tbats/), uses only data from time series minus covariates Train_Target = Train_Time_Series.iloc[:,1] Test_Target = Test_Time_Series.iloc[:,1] # Fit the model for daily data considering cycle of months and years: TBATS_estimator = TBATS(seasonal_periods=(30,365)) # Month and Year seasonal Components # Note: this takes quite a bit! for convenience, I fitted the model, then saved (and loaded it) TBATS_Model = TBATS_estimator.fit(Train_Target) ############################################################################### # Pickle and unpickle object (some of these estimations can take some time!) with open('TBATS_Model.pickle', 'wb') as output: pickle.dump(TBATS_Model, output) with open('TBATS_Model.pickle', 'rb') as data: TBATS_Model = pickle.load(data) ############################################################################### # Forecast the fitted model for the remaining 367 days, i.e, length of test data: TBATS_forecast = TBATS_Model.forecast(steps=367) # # Approach 2: AutoML approach AutoTS (see https://pypi.org/project/AutoTS/) # Model declaration model = AutoTS( forecast_length=367, frequency='infer', prediction_interval=0.9, ensemble=None, model_list="superfast", transformer_list="fast", max_generations=25, num_validations=2, validation_method="backwards" ) # Declares the series time stamp as index (required by model) Train_Time_Series_AutoTS = Train_Time_Series.set_index('Date/Time') Test_Time_Series_AutoTS = Test_Time_Series.set_index('Date/Time') # This snippet takes some time. Fits the model in the Training dataset: AUTOTS_Model = model.fit(Train_Time_Series_AutoTS) ############################################################################### # Same pickling as before, to save time in future iterations of code: with open('AUTOTS_Model.pickle', 'wb') as output: pickle.dump(AUTOTS_Model, output) # Loading the datasets: with open('AUTOTS_Model.pickle', 'rb') as data: AUTOTS_Model = pickle.load(data) ############################################################################### # Use the trained model to forecast for the next 367 periods (again, length of test data, obviously) Autots_forecast = AUTOTS_Model.predict().forecast ## Approaches 3,4,5: SARIMA with (SARIMAX) and without exogenous regressors: use Automatic approach similar ## to GridSearch (auto_arima) to find optimal values. ## Consider only monthly seasonal cycles. Save time to get only low order AR and MA terms. # Model declaration and Grid Search. Takes quite a bit! Sarima_model_no_exog = auto_arima(Train_Target, start_p=0, start_q=0, max_p=2, max_q=2, start_P=0, start_Q=0, max_P=2, max_Q=2, m=30, seasonal=True, trace=True, d=0, D=0, error_action='warn', suppress_warnings=True, random_state = 8748, n_fits=5) SarimaX_model = auto_arima(Train_Target, start_p=0, start_q=0, max_p=2, max_q=2, start_P=0, start_Q=0, max_P=2, max_Q=2, m=30, seasonal=True, exogenous = Train_Time_Series.iloc[:,2:15] , trace=True, d=0, D=0, error_action='warn', suppress_warnings=True, random_state = 8748, n_fits=5) # Usual pickling and loading: ############################################################################### with open('SARIMA_no_EXOG.pickle', 'wb') as output: pickle.dump(Sarima_model_no_exog, output) with open('SARIMAX.pickle', 'wb') as output: pickle.dump(SarimaX_model, output) with open('SARIMA_no_EXOG.pickle', 'rb') as data: Sarima_model_no_exog = pickle.load(data) with open('SARIMAX.pickle', 'rb') as data: SarimaX_model = pickle.load(data) ############################################################################### # Using the 2 SARIMA models to perform predictions for the test set: Sarima_no_exog_forecast = Sarima_model_no_exog.predict(n_periods=367) # Considering the covariates from the test set (if we have those): SarimaX_forecast_test_Covariates = SarimaX_model.predict(n_periods=367, exogenous = Test_Time_Series.iloc[:,2:15].fillna(method = 'ffill')) # SARIMAX Results seem too good to be true (overfitting?) # Using the model to predict test data using covariates from the train data (obviously with same length): # Let us use the last year in the train data to predict new test: SarimaX_forecast_test_train_Covariates = SarimaX_model.predict(n_periods=len(Test_Time_Series), exogenous = Train_Time_Series.iloc[-367:,2:15].fillna(method = 'ffill')) # Note what we have done here. "Sarima_no_exog_forecast" is a model trained without exogenous regressors # and used to predict the test data. "SarimaX_forecast_test_Covariates" predicts the test data of temperature # using the exogenous regressors from test data. And "SarimaX_forecast_test_train_Covariates" does the same # but considering the last 367 observations from train data as exogenous regressors. # Approach 5: Vector Auto-Regressive (VAR), models all time series together. # Begin by computing the Granger causality between series, measuring how much one series is # Helpful in predicting another. maxlag=5 test = 'ssr_chi2test' def grangers_causation_matrix(data, variables, test='ssr_chi2test', verbose=False): df = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables) for c in df.columns: for r in df.index: test_result = grangercausalitytests(data[[r, c]], maxlag=maxlag, verbose=False) p_values = [round(test_result[i+1][0][test][1],4) for i in range(maxlag)] if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}') min_p_value = np.min(p_values) df.loc[r, c] = min_p_value df.columns = [var + '_x' for var in variables] df.index = [var + '_y' for var in variables] return df # Take into account that the complete time series is given by DailyFullExplanatory (lines 189-192) Granger_test_matrix = grangers_causation_matrix(Daily_Full_explanatory.iloc[:,1:15].dropna(), variables = Daily_Full_explanatory.iloc[:,1:15].columns) print(Granger_test_matrix.iloc[:1].to_string()) Granger_causality_vector = Granger_test_matrix.iloc[:1].T # The table above gives the p-values of the Granger test. If smaller than 0.05, # then they Granger-cause Temperature. # We keep only the variables that Granger-cause Prices and check them against previous: Granger_causes_Temperature = Granger_causality_vector[Granger_causality_vector.iloc[:,0] < 0.05] Granger_causes_Temperature.rename(columns = {'T (degC)_y':'Granger_Value_p-test'}, inplace = True) # Note that this matches the correlation and graphical analysis (all variables except # wv (m/s), max. wv (m/s) and wd (deg) Granger cause Temperature. We could exclude these 3. # Next step: Cointegration test. Since all series are I(0), this step can be waived, but will leave it here for completeness: # Cointegration test (Johansen): from statsmodels.tsa.vector_ar.vecm import coint_johansen def cointegration_test(df, alpha=0.05): """Perform Johanson's Cointegration Test and Report Summary""" out = coint_johansen(df,-1,5) d = {'0.90':0, '0.95':1, '0.99':2} traces = out.lr1 cvts = out.cvt[:, d[str(1-alpha)]] def adjust(val, length= 6): return str(val).ljust(length) # Summary print('Name :: Test Stat > C(95%) => Signif \n', '--'*20) for col, trace, cvt in zip(df.columns, traces, cvts): print(adjust(col), ':: ', adjust(round(trace,2), 9), ">", adjust(cvt, 8), ' => ' , trace > cvt) cointegration_test(Daily_Full_explanatory.iloc[:,1:15].dropna()) # There is no need to difference any pair of series, but I will leave it here # Fit a VAR on train and test data and derive quality measures: # Number of Observations and declaration of train and test chunks: nobs = 367 TimeSeries_train, TimeSeries_test = Train_Time_Series, Test_Time_Series # Find model order by fitting model for several delays and computing the AIC: model = VAR(np.asarray(TimeSeries_train.iloc[:,1:15])) for i in [1,2,3,4,5,6,7,8,9]: result = model.fit(i) print('Lag Order =', i) print('AIC : ', result.aic) print('BIC : ', result.bic) print('FPE : ', result.fpe) print('HQIC: ', result.hqic, '\n') # Results aren't that different, let's choose 5 as the VAR order # Train VAR with selected model order: model_fitted = model.fit(5) model_fitted.summary() # Checking for serial correlation of residuals using the Durbin-Watson statistic: from statsmodels.stats.stattools import durbin_watson out = durbin_watson(model_fitted.resid) for col, val in zip(TimeSeries_train.iloc[:,1:15].columns, out): print(col, ':', round(val, 2)) # The residuals distribution looks OK! # Fitting the model on the train dataset: lag_order = model_fitted.k_ar # Input data for forecasting forecast_input = TimeSeries_train.iloc[:,1:15].values[-lag_order:] # Forecast fc = model_fitted.forecast(y=forecast_input, steps=nobs) VAR_forecast = pd.DataFrame(fc, index=Daily_Full_explanatory.iloc[:,1:15].index[-nobs:], columns=Daily_Full_explanatory.iloc[:,1:15].columns) # Sanity check VAR_forecast # VAR_forecast has the same name structure as the other methods (method_forecast) # but returns a list of 14 time series, the temperature and all the predicted others # in a length of 367 observations. Thus, VAR models and predicts all series together! # Remove White spaces in predicted, real vectors: VAR_forecast.columns = VAR_forecast.columns.str.replace(' ', '') Daily_Full_explanatory.columns = Daily_Full_explanatory.columns.str.replace(' ', '') TimeSeries_train.columns = TimeSeries_train.columns.str.replace(' ', '') TimeSeries_test.columns = TimeSeries_test.columns.str.replace(' ', '') # PLot of forecasts vs actuals for the VAR (All time series) fig, axes = plt.subplots(nrows=int(len(Daily_Full_explanatory.iloc[:,1:15].columns)/2), ncols=2, dpi=150, figsize=(10,10)) for i, (col,ax) in enumerate(zip(Daily_Full_explanatory.iloc[:,1:15].columns, axes.flatten())): VAR_forecast[col].plot(legend=True, ax=ax).autoscale(axis='x',tight=True) TimeSeries_test.iloc[:,1:15][col][-nobs:].plot(legend=True, ax=ax); ax.set_title(col + ": Forecast vs Actuals") ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') ax.spines["top"].set_alpha(0) ax.tick_params(labelsize=6) plt.tight_layout(); # VAR cannot model seasonality, finds it safer to just forecast mean of the series # Seems to be the approach that minimizes the error metric. # Evaluate Accuracy of the models (only some explanatory variables, the others are easy enough!) # Uniform names: model_AUTOTS_prediction = Autots_forecast.iloc[:,0] dates = list(model_AUTOTS_prediction.index) plot_test = Test_Time_Series.iloc[:,1] plot_test.index = dates model_TBATS_prediction = pd.DataFrame(TBATS_forecast,index=dates) model_AUTOTS_prediction = Autots_forecast.iloc[:,0] model_SARIMA_prediction = pd.DataFrame(Sarima_no_exog_forecast,index=dates) model_SARIMAX_prediction = pd.DataFrame(SarimaX_forecast_test_Covariates,index=dates) model_SarimaX_forecast_test_train_Covariates = pd.DataFrame(SarimaX_forecast_test_train_Covariates,index=dates) model_VAR_prediction = VAR_forecast.iloc[:,0] model_VAR_prediction.index=dates # Pickle the objects for further study: temp_list = [plot_test,model_TBATS_prediction, model_AUTOTS_prediction,model_SARIMA_prediction, model_SARIMAX_prediction,model_SarimaX_forecast_test_train_Covariates,model_VAR_prediction] results = pd.concat(temp_list,axis=1) results.columns = ["Observed","TBATS_forecast","AUTOTS_forecast", "SARIMA_forecast","SARIMAX_forecast","SanityCheckSarimax","VAR_forecast"] # Note: results puts together in a dataframe the observed test data (year of 2016, daily) agains # the predictions of the methods as explained above. I called "SanityCheckSarimax" the method # of SarimaX that uses as exogenous regressors the last 367 values of the train data, as explained above. # Everything else is self-explanatory. ############################################################################### with open('results.pickle', 'wb') as output: pickle.dump(results, output) with open('results.pickle', 'rb') as data: results = pickle.load(data) ############################################################################### # Several measures of adjustment, both classical and time-series oriented def forecast_accuracy(forecast, actual): mae = np.mean(np.abs(forecast - actual)) # MAE rmse = np.mean((forecast - actual)**2)**.5 # RMSE # Treatment of series to use further methods: Join = pd.concat([forecast, actual], axis=1).dropna() EuclideanDist = np.linalg.norm(Join.iloc[:,0].values-Join.iloc[:,1].values) #Euclidean Distance CosineSimilarity = np.dot(Join.iloc[:,0], Join.iloc[:,1])/(np.linalg.norm(Join.iloc[:,0])*np.linalg.norm(Join.iloc[:,1])) Pearson = pearsonr(Join.iloc[:,0],Join.iloc[:,1])[0] return(mae,rmse, EuclideanDist, CosineSimilarity, Pearson) # Ensemble of quality measures to ascertain goodness of fit of each model. # We had fit each model, now let's see how they match up by evaluating their fit compared: forecast_results = [] for column in results.iloc[:,1:len(results)].columns: forecast_results.append(forecast_accuracy(results[column],results.iloc[:,0])) # This dataframe contrasts measures and methods: forecast_results = pd.DataFrame (forecast_results, columns=['MAE','RMSE','Euclidean','CosineSim.','Pearson']) forecast_results.index = ['TBATS','AUTOTS','SARIMA','SARIMAX','SARIMAX_2','VAR'] forecast_results.sort_values(by=['MAE','RMSE','Euclidean','CosineSim.','Pearson']) # The output of this step is a dataframe matching methods and quality measures that says how # well each method performed. Note we want to minimize MAE, RMSE, Euclidean, and maximize the other 2. # This points to the conclusions: VAR performed horribly, being the worse, followed by SARIMA; # The automated ML approaches are mid of the scale. SARIMAX is probably some overfitting phenomenon. # If one forgets that, then SARIMAX_2 is the winner. This method involves using the last n observations # of the available data as exogenous regressors for the forecast of the next n periods. # Let us plot the predicted values of each method vs test data to get a visual feel: plt.figure(figsize=(12, 6)) plt.subplot(1,2,1) plt.plot(results.iloc[:,1],'r', label='Forecast') plt.plot(results.iloc[:,0],'b',label='Actual') plt.xlabel('Day in 2016') plt.ylabel('Mean Temperature') plt.legend(loc='best') plt.title('Predictions of TBATS Model') plt.subplot(1,2,2) plt.plot(results.iloc[:,2],'r', label='Forecast') plt.plot(results.iloc[:,0],'b',label='Actual') plt.xlabel('Day in 2016') plt.ylabel('Mean Temperature') plt.legend(loc='best') plt.title('Prediction of AUTOTS') # The 2 automated methods replicate some seasonal cycles, but are not able to match the full # variation, especially in a monthly cycle. In this regard, TBATS is worse. # SARIMA vs SARIMAX, the latter probably overfit: plt.figure(figsize=(12, 6)) plt.subplot(1,2,1) plt.plot(results.iloc[:,3],'r', label='Forecast') plt.plot(results.iloc[:,0],'b',label='Actual') plt.xlabel('Day in 2016') plt.ylabel('Mean Temperature') plt.legend(loc='best') plt.title('Predictions of SARIMA Model') plt.subplot(1,2,2) plt.plot(results.iloc[:,4],'r', label='Forecast') plt.plot(results.iloc[:,0],'b',label='Actual') plt.xlabel('Day in 2016') plt.ylabel('Mean Temperature') plt.legend(loc='best') plt.title('Prediction of SARIMAX') # SARIMA is able to replicate the seasonal effect in the beginning, but then # simply predicts the mean value. SARIMAX is practically indistinguishable from the data. # SARIMAX (Approach 2) vs VAR: plt.figure(figsize=(12, 6)) plt.subplot(1,2,1) plt.plot(results.iloc[:,5],'r', label='Forecast') plt.plot(results.iloc[:,0],'b',label='Actual') plt.xlabel('Day in 2016') plt.ylabel('Mean Temperature') plt.legend(loc='best') plt.title('Predictions of SARIMA_SanityCheck Model') plt.subplot(1,2,2) plt.plot(results.iloc[:,6],'r', label='Forecast') plt.plot(results.iloc[:,0],'b',label='Actual') plt.xlabel('Day in 2016') plt.ylabel('Mean Temperature') plt.legend(loc='best') plt.title('Prediction of VAR') ######################## MODEL CHOICE ############################################################## # From the above, the logic is clear: we use the SARIMAX model with the last n periods for exogenous variables # to predict the following n periods. # Predict on an unseen time labeled data with chosen model (next 31 days) # Write SarimaX_model to get model order and declare it: SarimaX_model Predictive_model = sm.tsa.statespace.SARIMAX(Daily_Full_explanatory.iloc[:,1], order=(1, 0, 2), seasonal_order=(0, 0, 2, 30), exog = Daily_Full_explanatory.iloc[:,2:15].fillna(method = 'ffill'), enforce_stationarity=False, enforce_invertibility=False) # Fit the model declared to the entire dataset to perform predictions with: # Beware: takes a few minutes! results = Predictive_model.fit() # This is a results wrapper that can be used to get forecasts with using SARIMAX determined automatically: # Get forecasts for the unseen, out of sample 31 days by using the last 31 days of data, as outlined above: pred_uc = results.get_forecast(steps=31, exog=Daily_Full_explanatory.iloc[-31:,2:15].fillna(method = 'ffill')) Predicted_weather = pred_uc.predicted_mean datelist = pd.date_range(datetime(2017, 1, 1), periods=31).tolist() Predicted_weather.index = datelist # Pedicted_weather matches each day against mean temperature. # Let us plot this prediction: fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.plot(Predicted_weather) ax.xaxis.set_major_locator(mdates.DayLocator(interval=7)) # Let us see how the prediction looks agains the corresponding month of the previous 2 years: Weather_Jan_2016 = Daily_Full_explanatory[(Daily_Full_explanatory['Date/Time'].astype(str).str[:7] == '2016-01')].iloc[:,1] Weather_Jan_2015 = Daily_Full_explanatory[(Daily_Full_explanatory['Date/Time'].astype(str).str[:7] == '2015-01')].iloc[:,1] # Comparison of prediction vs Weather of January in 2016 and 2015: plt.figure(figsize=(12, 6)) plt.subplot(1,1,1) plt.plot(np.array(pred_uc.predicted_mean),'r', label='Forecast Jan 2017') plt.plot(np.array(Weather_Jan_2016),'b',label='Weather Jan2016') plt.plot(np.array(Weather_Jan_2015),'g',label='Weather Jan2015') plt.xlabel('Observation') plt.ylabel('Temperatures over January') plt.legend(loc='best') plt.title('Predictions and actual values January') # The model is able to replicate the initial high temperatures observed <file_sep>/README.md # WeatherPredictionForJena Python Code for predicting the weather in Jena one month ahead (can be used for any kind of weather forecast with covariates, includes Data Analysis) Must first get the Jena Weather dataset from Kaggle.
fbb18abc4284ae40d55c79309b8387d2e5f9e97a
[ "Markdown", "Python" ]
2
Python
DiogaoDoBargalhao/WeatherPredictionForJena
57e5c90c95c9e8ac27143648d461ecb9e732938f
c8f2d8979422d2c3f661f24d819216dffabeb847
refs/heads/master
<file_sep>#include <iostream> int modSuma(int numA, int numB, int mod){ int res = (numA + numB)%mod; return res; } int modResta(int numA, int numB,int mod){ int res = numA - numB; while (res < 0){ //Si es negativo se convirte en positivo res+=mod; } res%=mod; return res; } int modMult(int numA, int numB,int mod){ int res = (numA*numB)%mod; return res; } int main(){ int opcion; int numA; int numB; int mod; std::cout << "Elija una opcion:\n"; std::cout << "1. Sumar\n"; std::cout << "2. Restar\n"; std::cout << "3. Multiplicar\n"; std::cin >> opcion; std::cout << "Ingrese el primer numero: "; std::cin >> numA; std::cout << "Ingrese el segundo numero: "; std::cin >> numB; std::cout << "Ingrese el modulo: "; std::cin >> mod; if (opcion == 1){ std::cout << modSuma(numA, numB, mod) << std::endl; } if(opcion == 2){ std::cout << modResta(numA, numB, mod) << std::endl; } if(opcion == 3){ std::cout << modMult(numA, numB, mod) << std::endl; } return 0; } <file_sep>#include <iostream> #include <cstdlib> #include <time.h> using namespace std; template<typename T> void Mazo<T>::agregar(T carta) { cartas.push(carta); } template<typename T> T Mazo<T>::quitar() { T tmp = cartas.getBack(); cartas.pop(); return tmp; } template<typename T> void Mazo<T>::barajar(T *arr,int ncartas){ srand(time(NULL)); T tmp; int r; for(int i = 0; i < ncartas; i++) { r = rand()%ncartas; tmp = arr[i]; arr[i] = arr[r]; arr[r] = tmp; } for (int i = 0; i < ncartas; i++) { agregar(arr[i]); } } template<typename T> bool Mazo<T>::vacio() { return cartas.empty(); } <file_sep>#include "listade.h" ListaDE::ListaDE() { front = nullptr; back = nullptr; } ListaDE::~ListaDE() { while (!isEmpty()) { Nodo *n; n = front->next; delete front; front = n; } } bool ListaDE::isEmpty() { if (front == nullptr) return true; return false; } void ListaDE::pushFront(int v) { front = new Nodo(v, nullptr, front); if (back == nullptr) back = front; else front->next->prev = front; } void ListaDE::pushBack(int v) { if (back != nullptr) { back->next = new Nodo(v, back, nullptr); back = back->next; } else front = back = new Nodo(v, nullptr, nullptr); } int ListaDE::popFront() { int val = front->val; Nodo *tmp = front; if (front == back) { front = nullptr; back = nullptr; } else { front = front->next; front->prev = nullptr; } delete tmp; return val; } int ListaDE::popBack() { int val = back->val; if (front == back) { delete front; front = nullptr; back = nullptr; } else { Nodo *tmp = back->prev; delete back; back = tmp; back->next = nullptr; } return val; } int ListaDE::deleteNode(int n) { if (front != nullptr) { if (front == back and n == front->val) { delete front; front = back = nullptr; } else if (n == front->val) { Nodo *tmp = front; front = front->next; delete tmp; } else { Nodo *pred = front; Nodo *tmp = front->next; while(tmp != nullptr and !(tmp->val = n)) { pred = pred->next; tmp =tmp->next; } if (tmp != nullptr) { pred->next = tmp->next; if (tmp == back) back = pred; delete tmp; } } } } bool ListaDE::isInList(int n) { Nodo *tmp= front; while(tmp != nullptr and !(tmp->val == n )) { tmp = tmp->next; } if (tmp != nullptr) return true; return false; } <file_sep>#include "ListaEnlazada.h" ListaEnlazada::ListaEnlazada() { cabeza = nullptr; cola = nullptr; } void ListaEnlazada::agrCabeza(int num) { cabeza = new Nodo( num , cabeza ); if(cola == nullptr) { cola = cabeza; } } void ListaEnlazada::agrCola(int num) { if(cola != 0) { cola -> next = new Nodo(num); cola = cola -> next; } else { cola = new Nodo(num); cabeza = cola; } } int ListaEnlazada::boCabeza() { if(cabeza == nullptr and cola == nullptr) { cout << "lista vacia" << endl; return 0; } int cabezret = cabeza -> num; Nodo *tmp = cabeza; //para borrar la cabeza if(cabeza == cola) { cabeza = nullptr; cola = nullptr; } else { cabeza = cabeza -> next; } delete tmp; return cabezret; } int ListaEnlazada::boCola() { if(cabeza == nullptr and cola == nullptr) { cout << "lista vacia" << endl; return 0; } int colaret = cola -> num; if(cabeza == cola) { cabeza = nullptr; cola = nullptr; } else { Nodo *tmp; tmp = cabeza; while(tmp->next != cola) { tmp = tmp->next; } delete cola; cola = tmp; cola->next = nullptr; } return colaret; } void ListaEnlazada::boNodo(int n) { if(cabeza != nullptr) { if(cabeza == cola and n == cabeza->num) { delete cabeza; cabeza = nullptr; cola = nullptr; } else { if(n == cabeza->num) { Nodo *tmp = cabeza -> next; cabeza = cabeza -> next; delete tmp; } else { Nodo *prev, *tmp; prev = cabeza; tmp = cabeza -> next; while(tmp != 0 and !(tmp->num == n)) { prev = prev -> next; tmp = tmp -> next; } if(tmp != nullptr) { prev -> next = tmp -> next; if(tmp == cola) cola = prev; delete tmp; } } } } } bool ListaEnlazada::Vacia() { if(cabeza == nullptr) return true; return false; } bool ListaEnlazada::estaenLista(int n) const { Nodo *tmp; tmp = cabeza; while(tmp != nullptr and !(tmp -> num == n)) { tmp = tmp -> next; } if(tmp != nullptr) { return tmp; } } void FusionaryOrdenar(ListaEnlazada *lista1, ListaEnlazada *lista2) { if( ( lista1->getcabeza() == nullptr and lista1->getcola() == nullptr ) or ( lista2->getcabeza() == nullptr and lista2->getcola() == nullptr ) ) { cout << "una de tus listas esta vacia" << endl; return; } Nodo *tmp1, *tmp2; } ListaEnlazada::~ListaEnlazada() { Nodo *tmp; while(!Vacia()) { tmp = cabeza->next; delete cabeza; cabeza = tmp; } delete tmp; } <file_sep>#include<iostream> using namespace std; void fswap(int *A,int *B) { int temp; if(*A>*B) { temp=*A; *A=*B; *B=temp; } } int main() { int *a; int a1=8; a=&a1; int *b; int b1=2; b=&b1; fswap(a,b); cout<<*a<<" "<<*b<<endl; } <file_sep>#ifndef PILA_H #define PILA_H #include "nodo.h" class Pila { private: Nodo *back; public: Pila(); ~Pila(); bool empty(); void push(int v); void pop(); int getBack(); }; #endif // PILA_H <file_sep>#include <iostream> #include <cstdlib> #include <time.h> using namespace std; template<typename T> void Mazo<T>::agregar(T carta) { cartas.push(carta); } template<typename T> T Mazo<T>::quitar() { T tmp = cartas.getBack(); cartas.pop(); return tmp; } template<typename T> void Mazo<T>::barajar(T *arr,int ncartas){ srand(time(NULL)); T tmp; int r; for(int i = 0; i < ncartas; i++) { r = rand()%ncartas; tmp = arr[i]; arr[i] = arr[r]; arr[r] = tmp; } for (int i = 0; i < ncartas; i++) { agregar(arr[i]); } } template<typename T> bool Mazo<T>::vacio() { return cartas.empty(); } // void Barajar::swap(int &a, int &b){ // int tmp = a; // a = b; // b = tmp; // } // Pila<int> Barajar::operator()(int *arr, int cantidad,int veces ){ // srand (time(NULL)); // int r; // Pila<int> pila; // for(int i =0; i< veces; i++) { // for (int j = 0; j < cantidad; j++) { // r = rand()%cantidad; // swap(arr[j], arr[r]); // } // } // for (int i =0 ;i < cantidad; i++) { // cout << arr[i]<< endl;; // } // cout << "*******" << endl; // for (int i =0 ;i < cantidad; i++) { // pila.push(arr[i]); // } // return pila; // } <file_sep>#include <iostream> #include "listadec.h" using namespace std; int main() { ListaDEC lista; lista.pushBack(1); lista.pushBack(3); lista.pushBack(52); lista.pushBack(123); lista.pushBack(2); lista.pushBack(324); lista.pushBack(51); lista.pushBack(12); lista.pushBack(109); cout << lista.front->val << endl; cout << lista.back->val << endl; cout << lista.back->prev->val << endl; lista.popBack(); cout << lista.back->val << endl; lista.popBack(); cout << lista.back->val << endl; return 0; } <file_sep>#include <iostream> #include <stdlib.h> using namespace std; int divide(int *array, int inicio, int fin) { int izquierda; int derecha; int pivot; int temp; pivot = array[inicio]; izquierda = inicio; derecha = fin; while (izquierda < derecha) { while (array[derecha] > pivot) { derecha--; } while ((izquierda < derecha) and (array[izquierda] <= pivot)) { izquierda++; } if (izquierda < derecha) { temp = array[izquierda]; array[izquierda] = array[derecha]; array[derecha] = temp; } } temp = array[derecha]; array[derecha] = array[inicio]; array[inicio] = temp; return derecha; } void quicksort(int *array, int inicio, int fin) { int pivot; if (inicio < fin) { pivot = divide(array, inicio, fin); quicksort(array, inicio, pivot - 1); quicksort(array, pivot + 1, fin); } } int main() { int t= 10; int *lista; lista=new int[t]; for(int i=0;i<t;i++) lista[i]=rand()%100+1; quicksort(lista,0, t-1); for(int i=0;i<t;i++) cout<<lista[i]<<" "; return 0; } <file_sep>#include <iostream> #include "tres.h" using namespace std; //http://www.cplusplus.com/articles/4z18T05o/ void fun::obtener(int &x, int &y, int &z) { x = cola.front().getI(); y = cola.front().getJ(); z = cola.front().getK(); cola.pop(); } int tres::lim(int a) { cout <<"A: " << a << endl; if (a < 0) return (a + 3); else if (a > 3) return (a - 3); else return a; } tres::tres() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { tab[i][j][k] = '*'; } } } jugadas = 0; turno = 0; } void tres::printTabl() { for (int i = 2; i >= 0; i--) { for (int j = 0; j < 3; j++) { cout << " "; // para que se mire mejor if (j == 1) cout << i + 1 << " "; else cout << " "; for (int n = 0; n < 2 - j; n++) cout << " "; for (int k = 0; k < 3; k++) { cout << "/" << tab[i][j][k] ; } cout << "/" << endl; } cout << endl; } } void tres::printPart() { cout << " 1 2 3" << endl; for (int j = 0; j < 3; j++) { cout << " " << j + 1 << " "; for (int k = 0; k < 3; k++) { cout << tab[_i][j][k] << " "; } cout << endl; } cout << endl; } bool tres::libre(char c) { if (c == '*') return true; return false; } char tres::simb() { if (turno) return 'O'; else return 'X'; } void tres::lados(int i, int j, int k) { //1; -1; 0 if (0 <= _i + i and _i + i < 3 and 0 <= _j + j and _j + j < 3 and 0 <= _k + k and _k + k < 3) { if (tab[_i + i][_j + j][_k + k] == simb()) validos(i, j, k); } } bool tres::verificar() {// +1 ,-1 o 0 int m; int n; int p; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { if (!(i == 0 and j == 0 and k == 0)) { m = i; n = j; p = k; if (m > 1) m -= 3; if (n > 1) n -= 3; if (p > 1) p -= 3; lados(m, n, p); } } } } int i = 0; int j = 0; int k = 0;//PODRIA USAR LOS MISMOS DE ARRIBA while (!validos.empty()) { validos.obtener(i, j , k); i = lim(_i + i * 2); j = lim(_j + j * 2); k = lim(_k + k * 2); if (tab[i][j][k] == simb()) { tab[_i][_j][_k] = 'G'; tab[i][j][k] = 'G'; return true; } } return false; } void tres::jugar() { while (jugadas < 27) {//el tablero solo tiene 27 espacios, cuando se llenan, termina el juego en empate inicio: system("clear"); printTabl(); cout << "Jugadas: " << jugadas << " Juega: " << simb() << endl << "Ingresa la capa: "; cin >> _i; if (0 < _i and _i <= 3) { _i--; do { system("clear"); printPart(); cout << "Ingresa la columna y fila: "; cin >> _k; cin >> _j; if (_k == 0 or _j == 0) goto inicio; // AREGLAR ESTO } while (!(0 < _k and _k <= 3 and 0 < _j and _j <= 3) or !libre(tab[_i][--_j][--_k])); tab[_i][_j][_k] = simb(); if(jugadas > 3) { // no puedes ganar antes de las 4 jugadas, 'jugadas' empieza en 0 if (verificar()) { system("clear"); cout << "GANA " << simb() << endl; printTabl(); return; } } turno = !turno; jugadas++; } } system("clear"); cout << "EMPATE!" << endl; printTabl(); } <file_sep>#include "tres.h" int main() { tres tresEnRaya; tresEnRaya.jugar(); // hacer una clase/struct en el que pueda meter 3 números // la clase debe tener un init() en el cual restablecemos los valores de todo; }<file_sep>#include "uno.h" #include <iostream> using namespace std; Uno::Uno(int nJug) { jug = nJug; turno = 0; direccion = 1; int mazos = 2; if (nJug > 4) // Dos mazos si juegan 4 o menos jugadores mazos += (nJug - 4) / 2; // cada 2 jugadores aumento un mazo int nCartas = 52 * mazos; CartaUno *cartas = new CartaUno[nCartas]; // un mazo tiene 52 cartas char color[5] = {'g', 'r', 'y', 'b', 'n'};// Green, Red, Yellow, Blue, Ninguno char tipo[6] = {'n', 'r', 'b', '2', 'c', '4'}; // Numero, Reversa, Bloqueo, 2: +2, Cambiar-color, 4 +4 int nc = 0; // Quiero 52 cartas , no uso 4 ceros // primero hacer los sets de 12 cartas por color 48 // luego aumentarle las 4 cartas sin color : 2 de cambiar color y 2 de +4 for (int v = 0; v < mazos; v++) { for (int c = 0; c < 4; c++) {// cuatro colores for (int i = 0; i < 9; i++) { cartas[nc].num = i + 1; cartas[nc].color = color[c]; cartas[nc].tipo = tipo[0]; //tipo 0 = número nc++; } for (int t = 1; t < 4; t++) { //Genero: Reversa, Bloqueo y +2 cartas[nc].num = 0; cartas[nc].color = color[c]; cartas[nc].tipo = tipo[t]; nc++; } } for (int v = 0; v < 2; v++) { for (int t = 4; t < 6; t++) { //aqúi genero los 2 últimos tipos, 2 cartas por tipo cartas[nc].num = 0; cartas[nc].color = color[4]; cartas[nc].tipo = tipo[t]; nc++; } } } mazo.barajar(cartas, nCartas); delete[] cartas; manos = new Lista<CartaUno>[nJug]; } // void pushFront(T num); // void pushBack(T num); // void popFront(); // void popBack(); // void popN(int n); // bool empty(); // T getfront(); // T getback(); // T getN(int n); // int size(); void Uno::repartirCartas() { for (int j = 0; j < 7; j++) { for (int i = 0 ; i < jug; i++) { manos[i].pushBack(mazo.quitar()); } } } void Uno::sgtTurno() { if (direccion) { turno++; if (turno >= jug) turno -= jug; } else { turno--; if (turno < 0) turno += jug; } } void Uno::partida() { repartirCartas(); } int main() { Uno juego(4); cout << "holi" << endl; // CartaUno p; // CartaUno q; // p.color = 'c'; // p.num = 1; // p.tipo = 't'; // q.color = 'r'; // q.num = 2; // q.tipo = 'w'; // cout << p.color << p.num <<p.tipo << endl; // cout << q.color << q.num <<q.tipo << endl; // p = q; // cout << p.color << p.num <<p.tipo << endl; } <file_sep>#ifndef CIFRADOMOD_H #define CIFRADOMOD_H #include <fstream> #include <string> using namespace std; class cifradoMod { private: int clavPri; int clavPub; fstream input; fstream output; public: cifradoMod(int num); cifradoMod() {} void cifrar(string nombreIn, string nombreOut); void descifrar(string nombreIn, string nombreOut, int clavePublica); int getClavPub() { return clavPub; } }; #endif // CIFRADOMOD_H <file_sep>#include "ListaEnlazada.h" int main() { ListaEnlazada Milista; Milista.agrCabeza(1); Milista.agrCola(2); Milista.agrCola(3); Milista.agrCola(4); Milista.agrCola(5); Milista.boNodo(4); } <file_sep>#ifndef NODO_H #define NODO_H #include <iostream> using namespace std; class Nodo { public: int num; Nodo *next; Nodo(int n, Nodo *ptr = nullptr) { num = n; next = ptr; } }; #endif // NODO_H <file_sep>#include <iostream> #include <stack> #include <queue> #include <string> using namespace std; int strToInt(string &input, string oper) { int num = 0; int pos = 0; while( oper.find(input[pos]) == string::npos and input[pos]!='\0') // string::npos = no se encontró en la busqueda { num = num*10; num += input[pos] - '0'; pos++; } input.erase(0,pos); return num; } string infToRPN(string in, string oper) { stack<char> pila; string rpn; int findPos; while(!in.empty()) { findPos = oper.find(in[0]); if (findPos != string::npos) { if (oper[findPos] == '(') { pila.push('('); } else if (oper[findPos] == ')') { while(pila.top() != '(') { rpn.push_back(pila.top()); rpn.push_back('_'); pila.pop(); } pila.pop(); } else if (oper[findPos] == '*' or oper[findPos] == '/') { while(true) { if (pila.empty() or pila.top() == '+' or pila.top() == '-' or pila.top() == '(') { pila.push(oper[findPos]); break; } else { rpn.push_back(pila.top()); rpn.push_back('_'); pila.pop(); } } } else if (oper[findPos] == '+' or oper[findPos] == '-') { while(true) { if (pila.empty() or pila.top() == '(') { pila.push(oper[findPos]); break; } else { rpn.push_back(pila.top()); rpn.push_back('_'); pila.pop(); } } } in.erase(0,1); // borra el primer elemento del string } else { while(oper.find(in[0]) == string::npos and !in.empty()) { rpn.push_back(in[0]); in.erase(0,1); } rpn.push_back('_'); } } while (!pila.empty()) { rpn.push_back(pila.top()); rpn.push_back('_'); pila.pop(); } return rpn; } int calculadora(string in) { stack<int> pila; string oper("()+-*/"); string rpn = infToRPN(in, oper); int tmp; while(!rpn.empty()) { if(oper.find(rpn[0]) == string::npos) { pila.push(strToInt(rpn, oper+'_')); rpn.erase(0,1); // elimina '_' } else { tmp = pila.top(); pila.pop(); if(rpn[0] == '+') tmp = pila.top() + tmp; else if(rpn[0] == '-') tmp = pila.top() - tmp; else if(rpn[0] == '*') tmp = pila.top() * tmp; else if(rpn[0] == '/') tmp = pila.top() / tmp; pila.pop(); pila.push(tmp); rpn.erase(0,2); // elimina operador y '_' } } return pila.top(); } int main() { string operacion; cout << "Ingresa operacion(sin espacios): "; cin >> operacion; cout << calculadora(operacion) << endl; }<file_sep>#ifndef PILA_H #define PILA_H template<typename T> class Nodo { public: Nodo *prev; T val; Nodo(){ prev = nullptr;} Nodo(T i, Nodo *p) { val = i; prev = p;} }; template<typename T> class Pila { private: Nodo<T> *back; public: Pila(); ~Pila(); bool empty(); void push(T v); void pop(); T getBack(); }; #include "pila.cpp" #endif // PILA_H <file_sep>#include <iostream> #include <queue> using namespace std; int modResta(int numA, int numB,int mod){ int res = numA - numB; while (res < 0){ //Si es negativo se convirte en positivo res+=mod; } res%=mod; return res; } bool inverso(queue<int> &cocientes, int num, int modu, int &k) // num%modu { int residuo, tempn, r; if(num > modu) { tempn = num; num = modu; modu = tempn; } while(r != 0) { tempn = modu % num; cocientes.push(modu/num); modu = num % modu; residuo = num; //residuo es el anterior QU3 R1K0l1N0 num = tempn; r = num; //r es el ultimo residuo k++; } if(residuo == 1) { k -= 2; return true; } return false; } int euclides(queue <int> cocientes, int modu, int k) { if(k == 0) {return 0;} if(k == 1) {return 1;} int Pk; queue<int> tempcoci = cocientes; for(int i = 0; i < k-2 ; i++) { tempcoci.pop(); } Pk = modResta(euclides(cocientes,modu,k-2),euclides(cocientes,modu,k-1)*tempcoci.front(),modu); return Pk; } int main() { queue <int> cocientes ; int k = 0, i, x, y; cout<<"Ingresa los valores: "; cin >> x; cout << "Ingresa el segundo valor: "; cin >> y; cout << endl; if(inverso(cocientes,x,y,k) == true) { if(x > y){y = x;} i = k + 2; cout << euclides(cocientes,y,i) << endl; } else { cout << "No tiene inverso " << endl; } } <file_sep>#include <iostream> #include <queue> using namespace std; class invModular { private: int modResta(int numA, int numB, int mod); public: int euclidesEx(int numA, int numB); }; <file_sep>#ifndef NODO_H #define NODO_H class Nodo { public: Nodo *next; Nodo *prev; int val; Nodo(); Nodo(int i, Nodo *prev = nullptr, Nodo *next = nullptr); }; #endif // NODO_H <file_sep>#include "invModular.h" int main(){ invModular inverso; int num; int mod; int invMod; cout << "Ingrese un numero: "; cin >> num; cout << "Ingrese el modulo: "; cin >> mod; invMod = inverso.euclidesEx(num, mod); if (invMod) cout << "El inverso modular es: "<< invMod << endl; else cout << "No tiene inverso" << endl; return 0; } <file_sep>#include <iostream> #include "cifradoMod.h" using namespace std; int main() { int clavPri; int clavPub; int opcion; string input; string output; cout << "1.Cifrar \n2. Descifrar" << endl; cin >> opcion; if (opcion == 1) { cout << "Clave Privada: "; cin >> clavPri; cifradoMod cifrador(clavPri); cout << "Clave Publica: " << cifrador.getClavPub() << endl; cout << "Nombre de archivo a cifrar: "; cin >> input; cout << "Nombre del archivo output: "; cin >> output; cifrador.cifrar(input, output); } else { cout << "Clave: "; cin >> clavPub; cifradoMod cifrador; cout << "Nombre de archivo a descifrar: "; cin >> input; cout << "Nombre del archivo output: "; cin >> output; cifrador.descifrar(input, output, clavPub ); } return 0; } <file_sep>#include "invModular.h" int invModular::modResta(int numA, int numB,int mod){ int res = numA - numB; while (res < 0) res+=mod; res%=mod; return res; } int invModular::euclidesEx(int numA, int numB){ queue<int> cocientes; int residuo = -1; int resAnterior = 0; int pos; int mod = numB; int euExtA = 0; int euExtB = 1; for (pos = 0; residuo != 0; pos++){ //La variable "pos" ya es k+2, ya que la posición del residuo 0 es k+1 cocientes.push(numB/numA); //y el for da una vuelta más para comprobar y suma +1 a pos. resAnterior = residuo; residuo = numB % numA; numB = numA; numA = residuo; } if (resAnterior != 1) return 0; for (int i = 2; i <= pos; i++){ int tmp = modResta(euExtA, euExtB*cocientes.front(), mod); cocientes.pop(); euExtA = euExtB; euExtB = tmp; } return euExtB; } <file_sep>#include<iostream> #include"lista_circular.h" CList::~CList() { for(IntNode *p;!isEmpty();) { p = head->next; delete head; head = p; } } void CList::addToHead(int el) { head = new IntNode(el,head); if (tail == nullptr) tail = head; } void CList::addToTail(int el) { if (isEmpty()) { tail = new IntNode(el); tail->next = tail; } else { tail->next = new IntNode(el,tail->next); tail->next = head; } } int CList::deleteFromHead() { int el = head->info; IntNode *tmp = head; if (head == tail) head = tail = nullptr; else head = head->next; delete tmp; return el; } int CList::deleteFromTail() { int el = tail -> info; if (head == tail) { delete head; head = tail = nullptr; } else { IntNode *tmp; for(tmp = head; tmp->next != tail; tmp = tmp->next); delete tail; tail = tmp; tail->next = nullptr; } return el; } void CList::deleteNode(int el) { if (head != nullptr) if (head == tail and el == head ->info) { delete head; head = tail = nullptr; } else if (el == head->info) { IntNode *tmp = head->next; head = head->next; delete tmp; } else { IntNode *pred, *tmp; for (pred = head, tmp = head->next; tmp != nullptr and !(tmp->info == el); pred = pred->next,tmp = tmp->next ); if (tmp != nullptr) { pred->next = tmp->next; if (tmp == tail) tail = pred; delete tmp; } } } bool CList::isInList(int el) const { IntNode *tmp; for (tmp = head; tmp != nullptr and !(tmp->info == el); tmp = tmp->next); return tmp != nullptr; } <file_sep>#ifndef LISTADE_H #define LISTADE_H #include "nodo.h" class ListaDE { private: public: Nodo *front; Nodo *back; ListaDE(); ~ListaDE(); bool isEmpty(); void pushFront(int v); void pushBack(int v); int popFront(); int popBack(); int deleteNode (int n); bool isInList (int n); }; #endif // LISTADE_H <file_sep>#include<iostream> using namespace std; float convertir_minutos(float hora) { int hora_1 = hora; return hora_1*60 + (hora - hora_1)*100; } void convertir_horas(int minutos,bool formato) { float hora; float minutos_1 = (minutos%60); hora = minutos/60; if (formato==true) { if ( hora < 10 ) cout << "0"; cout << hora << ":"; if ( minutos_1 < 10) cout << "0"; cout << minutos_1; } if (formato==false) { if (hora > 12 and minutos_1 < 10) cout << hora-12 << ":" << "0" << minutos_1 << " pm"; if (hora > 12 and minutos_1 >= 10) cout << hora-12 << ":" << minutos_1 << " pm"; if (hora <= 12 and minutos_1 < 10) cout << hora << ":" << "0" << minutos_1 << " am"; if (hora <= 12 and minutos_1 >= 10) cout << hora << ":" << minutos_1 << " am"; } } void imprimir_horario(float minutos_entrada, float minutos_salida, float duracion_hora, bool formato_hora) { float minutos_total = minutos_salida - minutos_entrada; float total_horas = (float)(minutos_salida - minutos_entrada)/(float)(duracion_hora); float hora_1,hora_2; if (minutos_total<=0 or minutos_total<duracion_hora) cout<<"Horario no valido"<<endl; else { hora_1=minutos_entrada; for(int i=0;i<total_horas;i++) { hora_2= hora_1+duracion_hora; if (hora_2<=minutos_salida) { convertir_horas(hora_1,formato_hora); cout<<" - "; convertir_horas(hora_2,formato_hora); cout<<endl; } hora_1=hora_2; } } } int main() { //variables de entrada: float hora_inicio; float hora_fin; float duracion_hora; bool formato_hora; cout<<"Datos: "<<endl; cout<<"Inicio: ";cin>>hora_inicio; cout<<"Fin: ";cin>>hora_fin; cout<<"Duracion: ";cin>>duracion_hora; cout<<"Formato hora: (0=am/pm,1=normal)";cin>>formato_hora; float minutos_inicio = convertir_minutos(hora_inicio); float minutos_fin = convertir_minutos(hora_fin); imprimir_horario(minutos_inicio,minutos_fin,duracion_hora,formato_hora); } <file_sep>#include <iostream> #include "lista.h" using namespace std; int main() { Lista<int> hola; for(int i =0; i<10; i++){ hola.pushBack(i); } for(int i =0; i<10; i++){ cout <<hola.getN(i) << endl; } cout << "size:" << hola.size() << endl; hola.popN(5); for(int i =0; i<9; i++){ cout <<hola.getN(i) << endl; } cout << "size:" << hola.size() << endl; hola.popN(5); cout << "size:" << hola.size() << endl; hola.popN(5); cout << "size:" << hola.size() << endl; hola.popN(5); cout << "size:" << hola.size() << endl; hola.popN(5); cout << "size:" << hola.size() << endl; hola.popN(5); cout << "size:" << hola.size() << endl; hola.popBack(); cout << "size:" << hola.size() << endl; hola.popBack(); cout << "size:" << hola.size() << endl; hola.popBack(); cout << "size:" << hola.size() << endl; hola.popBack(); cout << "size:" << hola.size() << endl; hola.popBack(); cout << "size:" << hola.size() << endl; hola.popBack(); cout << "size:" << hola.size() << endl; hola.pushBack(1); cout << "size:" << hola.size() << endl; } <file_sep>#ifndef LISTAENLAZADA_H #define LISTAENLAZADA_H #include "Nodo.h" class ListaEnlazada { public: ListaEnlazada(); ~ListaEnlazada(); void agrCabeza(int num); void agrCola(int num); int boCabeza(); int boCola(); void boNodo(int n); bool estaenLista(int n) const; int Vacia(); private: Nodo *cabeza, *cola; }; #endif // LISTAENLAZADA_H <file_sep>#include <iostream> #include "pila.h" using namespace std; int main(int argc, char *argv[]) { Pila pila; cout << pila.empty() << endl; for (int i=0; i<10;i++) pila.push(i); cout << pila.empty() << endl; for (int i=0; i <10;i++){ cout <<pila.getBack() << endl; pila.pop(); } cout << pila.empty() << endl; return 0; } <file_sep>#ifndef NODO_H #define NODO_H #include <iostream> using namespace std; class Nodo { public: int num; Nodo *next; Nodo(int n, Nodo *ptr = nullptr) { num = n; next = ptr; } }; #endif // NODO_H <file_sep>#ifndef UNO_H #define UNO_H #include "pila/pila.h" #include "lista/lista.h" #include "mazo/mazo.h" struct CartaUno { char color; // G-R-B-Y-B int num; //1-9 char tipo; //Numero-Cancelar-Voltear-+2 .... SIN COLOR, +4 cambiar color 1 }; class Uno{ private: int jug; int turno; bool direccion; Mazo<CartaUno> mazo; Mazo<CartaUno> mesa; Lista<CartaUno> *manos; void cancelarTurno(); void aumentarCartas(int n); void cambiarSentido(); void repartirCartas(); void sgtTurno(); public: Uno(int nJug); void partida(); }; #endif //UNO_H //----------- //l COLOR l //l # l //l l //l T+4 l //l l //l l //----------<file_sep>#include "nodo.h" Nodo::Nodo() { next = nullptr; prev = nullptr; } Nodo::Nodo(int i, Nodo *p , Nodo *n ) { val = i; prev = p; next = n; } <file_sep>#include"ListaEnlazada.h" Nodo * combinar_listas(ListaEnlazada *L1,ListaEnlazada *L2) { Nodo *t1,*t2,*H; if(L1->cabeza==nullptr and L2->cabeza==nullptr) { cout<<"Las listas estan vacias"<<endl; } else { t1 = L1->cabeza; t2 = L2->cabeza; if (t1->num<t2->num) H = L1->cabeza; else H = L2->cabeza; Nodo *A = H; cout<<H->num<<endl; while(t1!=nullptr and t2!=nullptr) { //cout<<t1<<" "<<t2<<endl; if(t1==nullptr or t2==nullptr) return A; if(t1->num <= t2->num) { t1 = t1->next; H->next=t2; H = H->next; cout<<H->num<<endl; } //cout<<t1<<" "<<t2<<endl; if(t1==nullptr or t2==nullptr) return A; if(t2->num <= t1->num) { t2 = t2->next; H->next=t1; H=H->next; cout<<H->num<<endl; } //cout<<t1<<" "<<t2<<endl; if(t1==nullptr or t2==nullptr) return A; } } } int main() { ListaEnlazada *A; A = new ListaEnlazada; A->agrCabeza(12); A->agrCabeza(5); A->agrCabeza(1); cout<<"DIRECCIONES LISTA A: "<<endl; cout<<A->cabeza<<" "<<endl; cout<<A->cabeza->next<<endl; cout<<A->cabeza->next->next<<endl; ListaEnlazada *B; B = new ListaEnlazada; B->agrCabeza(19); B->agrCabeza(8); B->agrCabeza(2); cout<<"DIRECCIONES LISTA B: "<<endl; cout<<B->cabeza<<endl; cout<<B->cabeza->next<<endl; cout<<B->cabeza->next->next<<endl; Nodo *EZ = combinar_listas(A,B); cout<<"Nueva Lista: "<<endl; while (EZ!=nullptr) { cout<<"Direccion: "<<EZ<<" "<<EZ->num<<endl; EZ = EZ->next; } return 0; } <file_sep>#include "lista.h" template<typename T> Lista<T>::Lista() { front = nullptr; back = nullptr; } template<typename T> void Lista<T>::pushFront(T val) { front = new NodoL<T>( val , front ); if (back == nullptr) back = front; } template<typename T> void Lista<T>::pushBack(T val) { if (back != nullptr) { back -> next = new NodoL<T>(val); back = back -> next; } else { back = new NodoL<T>(val); front = back; } } template<typename T> void Lista<T>::popFront() { if (front == nullptr and back == nullptr) return; NodoL<T> *tmp = front; //para borrar la front if (front == back) { front = nullptr; back = nullptr; } else front = front -> next; delete tmp; } template<typename T> void Lista<T>::popBack() { if (front == nullptr and back == nullptr) return; if (front == back) { front = nullptr; back = nullptr; } else { NodoL<T> *tmp; tmp = front; while (tmp->next != back) tmp = tmp->next; delete back; back = tmp; back->next = nullptr; } } template<typename T> void Lista<T>::popN(int n) { if (front == nullptr) return; if (n == 0) { NodoL<T> *tmp = front->next; front = front->next; delete tmp; } else { NodoL<T> *prev = front; NodoL<T> *tmp = front -> next; while (tmp != nullptr and n > 1) { prev = prev->next; tmp = tmp->next; n--; } if (tmp != nullptr) { prev->next = tmp->next; if (tmp == back) back = prev; delete tmp; } } } template<typename T> T Lista<T>::getN(int n) { if (front == nullptr) throw;// como hacer que no retorne nada ?? if (n == 0) return front->val; else { NodoL<T> *tmp = front -> next; while (tmp != nullptr and n > 1) { tmp = tmp->next; n--; } if (tmp != nullptr) return tmp->val; else throw; // cómo hacer para me retorne nada:'( } } template<typename T> bool Lista<T>::empty() { if (front == nullptr) return true; return false; } template<typename T> int Lista<T>::size() { if (front == nullptr) return 0; else { int size = 1; NodoL<T> *tmp = front -> next; while (tmp != nullptr) { tmp = tmp->next; size++; } return size; } } template<typename T> Lista<T>::~Lista() { if (front != nullptr and back != nullptr){ NodoL<T> *tmp; while (!empty()) { tmp = front->next; delete front; front = tmp; } delete tmp; } } template<typename T> T Lista<T>::getback() { return back->val; } template<typename T> T Lista<T>::getfront() { return front->val; } <file_sep>#include "mazo.h" #include "../pila/pila.h" #include <iostream> using namespace std; class Naipes { public: char palo; int num; }; int main() { Mazo<int> cartas; int c[] = {1, 2, 3, 4, 5, 6}; cartas.barajar(c, 6); while (!cartas.vacio()) { cout << cartas.quitar() << endl; } cout << "-----" << endl; Mazo<Naipes> barajaNaipes; Naipes *cc = new Naipes[52]; char palo[] = {'E','C','T', 'D'}; for (int j = 0; j < 4; j++) { for (int i = 0; i < 13; i++) { cc[j*13+i].palo = palo[j]; cc[j*13+i].num = i+1; } } barajaNaipes.barajar(cc, 52); while (!barajaNaipes.vacio()) { Naipes tmp = barajaNaipes.quitar(); cout << tmp.palo<< " " << tmp.num<< endl; } delete[] cc; }<file_sep>#include <iostream> #include <vector> using namespace std; void josefo(int salto, int vivos, vector<int>& v) { int i = 0; salto -=1; while (v.size() > vivos) { i += salto; if (i >= v.size()) i = i % v.size(); v.erase(v.begin() + i); } } void josefo_SinSTL(int salto, int vivos, int *arr, int arrSize){ int i = 0; int cont = arrSize; int check; while(cont > vivos) { check = salto; while(check > 0){ if(i >= arrSize) i -= arrSize; if(arr[i] !=0) check--; i++; } arr[i-1] = 0; cont-- ; } } int main() { vector<int> v; int personas; int salto; cout << "# Personas: "; cin >> personas; cout << "Salto: "; cin >> salto; for (int i = 1; i <= personas; i++) { v.push_back(i); } josefo(salto, 2, v); for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; } cout << endl; //------------- int *array = new int[personas]; for (int i = 1; i <= personas; i++){ array[i-1] = i; } josefo_SinSTL(salto, 2, array, personas); for (int i = 0; i < personas; ++i){ if(array[i] != 0){ cout << array[i]<< " "; } } cout << endl; delete[] array; }<file_sep>#include "carta.h" CartaUno::CartaUno(int n, char c){ numero = n; color = c; } Cancelar::Cancelar(char c): CartaUno(0, c){ } Voltear::Voltear(char c): CartaUno(0, c){ } Aumentar::Aumentar(char c, int nC): CartaUno(0, c){ } <file_sep>#include "../pila/pila.h" #include <iostream> template<typename T> class Mazo{ private: Pila<T> cartas; public: void agregar(T carta); T quitar(); void barajar(T *arr, int ncartas); bool vacio(); //void barajar(T *arr,int ncartas, void(*fnc)(T, T)); //void barajar(T *arr, function<void(T, T)> &f);//recibir ptr a funcion; esa función va a ser el swap con random //recibe un array con las cartas }; #include "mazo.cpp"<file_sep>#include <queue> using namespace std; class xyz { private: int i; int j; int k; public: xyz(int a, int b, int c) { i = a; j = b; k = c;} int getI() {return i;} int getJ() {return j;} int getK() {return k;} }; class fun { private: queue<xyz> cola; public: void operator() (int i, int j, int k) { cola.push(xyz(i, j, k)); } void obtener(int &x, int &y, int &z); bool empty(){ cola.empty(); } }; class tres { private: char tab[3][3][4]; int _i; int _j; int _k; int jugadas; bool turno; fun validos; void printTabl(); void printPart(); bool libre(char c); bool verificar(); void lados(int i, int j, int k); char simb(); int lim(int a); public: tres(); void jugar(); };<file_sep>#ifndef CARTA_H #define CARTA_H class CartaUno{ protected: int num; char color; public: CartaUno(int n, char c); }; class Cancelar: public CartaUno{ public: Cancelar(char c); }; class Voltear: public CartaUno{ public: Voltear(char c); }; class Aumentar: public CartaUno{ private: int nCartas; public: Aumentar(char c, int nC); }; #endif //CARTA_H<file_sep>#ifndef LISTAENLAZADA_H #define LISTAENLAZADA_H template<typename T> class NodoL { public: NodoL *next; T val; NodoL(T n, NodoL *ptr = nullptr) { val = n; next = ptr; } }; template<typename T> class Lista { private: NodoL<T> *front; NodoL<T> *back; public: Lista(); ~Lista(); void pushFront(T num); void pushBack(T num); void popFront(); void popBack(); void popN(int n); bool empty(); T getfront(); T getback(); T getN(int n); int size(); }; #include "lista.cpp" #endif // LISTAENLAZADA_H <file_sep>#include <iostream> using namespace std; bool compara( char *a, char *b){ while(*a != '\0' ){ if (*a == *b){ a++; b++; } else return false; } return true; } int main(){ char a[]= "holaz"; char b[] = "hola"; cout << compara(a , b) << endl; } <file_sep>//#include "pila.h" template<typename T> Pila<T>::Pila() { back = nullptr; } template<typename T> Pila<T>::~Pila() { while (!empty()) { Nodo<T> *tmp; tmp = back->prev; delete back; back = tmp; } } template<typename T> bool Pila<T>::empty() { if (back == nullptr) return true; return false; } template<typename T> void Pila<T>::push(T v) { back = new Nodo<T>(v, back); } template<typename T> void Pila<T>::pop() { if (back->prev == nullptr) { delete back; back = nullptr; } else { Nodo<T> *tmp = back->prev; delete back; back = tmp; } } template<typename T> T Pila<T>::getBack() { return back->val; } <file_sep>#include "ListaEnlazada.h" int main() { ListaEnlazada Milista1; ListaEnlazada Milista2; for(int i = 0 ; i <= 8 ; i+=2) { Milista1.agrCola(i); } for(int i = 1 ; i <= 9 ; i+=2) { Milista2.agrCola(i); } cout << Milista1.estaenLista(4) << endl; } <file_sep>#include "pila.h" Pila::Pila() { back = nullptr; } Pila::~Pila() { while (!empty()) { Nodo *tmp; tmp = back->prev; delete back; back = tmp; } } bool Pila::empty() { if (back == nullptr) return true; return false; } void Pila::push(int v) { back = new Nodo(v, back); } void Pila::pop() { if (back->prev == nullptr) { delete back; back = nullptr; } else { Nodo *tmp = back->prev; delete back; back = tmp; } } int Pila::getBack() { return back->val; } <file_sep># Objetos y Abstracción de datos Tareas <file_sep>#include "listadec.h" ListaDEC::ListaDEC() { front = nullptr; back = nullptr; } ListaDEC::~ListaDEC() { while (!isEmpty()) { Nodo *n; n = front->next; delete front; front = n; } } bool ListaDEC::isEmpty() { if (front == nullptr) return true; return false; } void ListaDEC::pushFront(int v) { front = new Nodo(v, back, front); if (back == nullptr) back = front; else { front->next->prev = front; back->next = front; } } void ListaDEC::pushBack(int v) { if (back != nullptr) { back->next = new Nodo(v, back, front); back = back->next; front->prev = back; } else front = back = new Nodo(v, nullptr, nullptr); } int ListaDEC::popFront() { int val = front->val; Nodo *tmp = front; if (front == back) { front = nullptr; back = nullptr; } else { front = front->next; front->prev = back; back->next = front; } delete tmp; return val; } int ListaDEC::popBack() { int val = back->val; if (front == back) { delete front; front = nullptr; back = nullptr; } else { Nodo *tmp = back->prev; delete back; // no funciona back = tmp; back->next = front; front->prev = back; } return val; } int ListaDEC::deleteNode(int n) { if (front != nullptr) { if (front == back and n == front->val) { delete front; front = back = nullptr; } else if (n == front->val) { Nodo *tmp = front; front = front->next; delete tmp; front->prev = back; back->next = front; } else { Nodo *pred = front; Nodo *tmp = front->next; while (tmp != front and !(tmp->val = n)) { pred = pred->next; tmp = tmp->next; } if (tmp != front) { pred->next = tmp->next; if (tmp == back) back = pred; delete tmp;/// ? } } } } bool ListaDEC::isInList(int n) { Nodo *tmp = front; while (tmp != back and !(tmp->val == n )) { tmp = tmp->next; } if (tmp != back) if (tmp->val == n) return true; return false; } <file_sep>#include <iostream> #include <stdlib.h> using namespace std; void printLista(int *lista,int n) { for(int i=0;i<n;i++) cout<<lista[i]<<" "; cout<<endl; } void i_sort(int *lista,int n) { int j, temp; for (int i=0;i<n; i++) { j = i; while (j > 0 and lista[j] < lista[j-1]) { temp = lista[j]; lista[j] = lista[j-1]; lista[j-1] = temp; j--; } } } int main() { int n=7; int *lista; lista = new int [n]; for(int i=0;i<n;i++) lista[i]= rand()%20+1; printLista(lista,n); i_sort(lista,n); printLista(lista,n); delete lista; } <file_sep>#include <iostream> #include <stdlib.h> using namespace std; void swap(int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; } void bubbleSort(int *arr, int size) { bool isSorted = false; for (int i = 1; i < size and !isSorted; i++) { isSorted = true; for (int j = 0; j < size -i ; j++) { if(arr[j] > arr[j+1]) { isSorted = false; swap(arr[j], arr[j+1]); } } } } void cocktailSort(int *arr, int size) { bool isSorted = false; for (int i = 1; i < size and !isSorted; i++) { isSorted = true; for (int j = i-1; j < size -i ; j++) { if(arr[j] > arr[j+1]) { isSorted = false; swap(arr[j], arr[j+1]); } } isSorted = true; for (int j = size-i-1; j >i-1 ; j--) { if(arr[j] < arr[j-1]) { isSorted = false; swap(arr[j], arr[j-1]); } } } } void selectionSort(int *arr, int size) { int min; for (int i = 0; i < size ; i++) { min = i; for (int j = i+1; j < size; j++) { if (arr[j] < arr[min]) min = j; } swap(arr[i], arr[min]); } } void insertionSort() { } void quickSort() { } void printArr(int *arr, int size) { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } int main() { int size = 10; int *array; array = new int[size]; for(int i = 0; i < size; i++) array[i]= rand() % 100; printArr(array, size); //bubbleSort(array, size); //cocktailSort(array, size); selectionSort(array, size); printArr(array, size); }<file_sep>#include"lista_circular.cpp" using namespace std; int main() { CList *lista; lista = new CList; lista->addToHead(24); lista->addToTail(5); lista->addToTail(6); lista->addToTail(7); cout<<lista->head<<endl; cout<<lista->tail->next<<endl; cout<<lista->tail->next->info<<endl; //cout<<lista->deleteFromTail()<<endl; } <file_sep>#include <fstream> #include "invModular.h" #include "cifradoMod.h" cifradoMod::cifradoMod(int num) { clavPri = num; invModular inverso; clavPub = inverso.euclidesEx(clavPri, 256); while (clavPub == 0) { cout << "El numero ingresado no tiene inverso, ingresa otro: \n"; cin >> clavPri; clavPub = inverso.euclidesEx(clavPri, 256); } } void cifradoMod::cifrar(string nombreIn, string nombreOut) { char letra; //Abrir archivo y verifica que exista: input.open (nombreIn.c_str(), fstream::in | fstream::binary); //.c_str para que pueda leer el string output.open (nombreOut.c_str(), fstream::out); while (!input.is_open()) { cout << "No existe el archivo que quieres cifrar, ingresa otro: "; cin >> nombreIn; input.open (nombreIn.c_str(), fstream::in); } //Cifrar: while (input >> noskipws >> letra) { output.put((letra * clavPri) % 256); } input.close(); output.close(); } void cifradoMod::descifrar(string nombreIn, string nombreOut, int clavePublica) { char letra; //Abrir archivo y verifica que exista: input.open (nombreIn.c_str(), fstream::in | fstream::binary); //.c_str para que pueda leer el string output.open (nombreOut.c_str(), fstream::out); while (!input.is_open()) { cout << "No existe el archivo que quieres descifrar, ingresa otro: "; cin >> nombreIn; input.open (nombreIn.c_str(), fstream::in); } //Descifrar: while (input >> noskipws >> letra) { output.put((letra * clavePublica) % 256); } input.close(); output.close(); } <file_sep>#include <iostream> using namespace std; int resto(int &num, int dig) { int convertir; int divisor = 1; for(int it=1; it<dig; it++) { divisor = divisor*10; } convertir = num/divisor; num = num%divisor; return convertir; } void romanos(int num, int &dig) { if(dig == 4) { if(num == 3){ cout<<"MMM";} if(num == 2){ cout<<"MM";} if(num == 1){ cout<<"M";} dig--; return; } if(dig == 3) { if(num == 9){ cout<<"CM";} if(num == 8){ cout<<"DCCC";} if(num == 7){ cout<<"DCC";} if(num == 6){ cout<<"DC";} if(num == 5){ cout<<"D";} if(num == 4){ cout<<"CD";} if(num == 3){ cout<<"CCC";} if(num == 2){ cout<<"CC";} if(num == 1){ cout<<"C";} dig--; return; } if(dig == 2) { if(num == 9){ cout<<"XC";} if(num == 8){ cout<<"LXXX";} if(num == 7){ cout<<"LXX";} if(num == 6){ cout<<"LX";} if(num == 5){ cout<<"L";} if(num == 4){ cout<<"XL";} if(num == 3){ cout<<"XXX";} if(num == 2){ cout<<"XX";} if(num == 1){ cout<<"X";} dig--; return; } if(dig == 1) { if(num == 9){ cout<<"IX";} if(num == 8){ cout<<"VIII";} if(num == 7){ cout<<"VII";} if(num == 6){ cout<<"VI";} if(num == 5){ cout<<"V";} if(num == 4){ cout<<"IV";} if(num == 3){ cout<<"III";} if(num == 2){ cout<<"II";} if(num == 1){ cout<<"I";} dig--; return; } } int numerocifras(int num) { int digits; if(num/1000 >= 1) { digits = 4; return digits; } if(num/100 >= 1) { digits = 3; return digits; } if(num/10 >= 1) { digits = 2; return digits; } digits = 1; return digits; } int main() { int numero, digitos, convertir; cout<<"Ingrese el numero que desea convertir: "; cin>>numero; cout<<endl; digitos = numerocifras(numero); conversionaromanos(numero,digitos); } <file_sep>#ifndef INVMODULAR_H #define INVMODULAR_H #include <iostream> #include <queue> using namespace std; class invModular { private: int modResta(int numA, int numB, int mod); public: int euclidesEx(int numA, int numB); }; #endif // INVMODULAR_H
32118f373997f18da485f56ec576f4071491cc11
[ "Markdown", "C++" ]
53
C++
agublazer/OAD
d4b80dda8e3f929ae35a8e36a25d52c5ddff9e47
84fda3c88a5e5110544857c6ad99139786aa4c25
refs/heads/gh-pages
<file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "c7196b70cd6aba1c5b57942f9f8d9f89", "url": "/charter-amendment/index.html" }, { "revision": "3b08501ef83c3e13f3d5", "url": "/charter-amendment/static/css/2.ac1ab58b.chunk.css" }, { "revision": "a90fb2e5beb0270123f9", "url": "/charter-amendment/static/css/main.5ecd60fb.chunk.css" }, { "revision": "3b08501ef83c3e13f3d5", "url": "/charter-amendment/static/js/2.55e1b1df.chunk.js" }, { "revision": "348e18c767030a34e3e00df7559622cb", "url": "/charter-amendment/static/js/2.55e1b1df.chunk.js.LICENSE.txt" }, { "revision": "a90fb2e5beb0270123f9", "url": "/charter-amendment/static/js/main.76b9f1a3.chunk.js" }, { "revision": "d7e35b441272fffc5d9d", "url": "/charter-amendment/static/js/runtime-main.0398313d.js" } ]);
06323a233fabe445a2821070e9cb3b568dee19a6
[ "JavaScript" ]
1
JavaScript
lanemc/charter-amendment
b0920ae5b56f6aef300f339286106d445af46730
b251ae6ce5e66576b26129eeef5b867c48b18a5a
refs/heads/master
<repo_name>PasoSteve/peekapp<file_sep>/Imageupload/app/src/main/java/peek/imageupload/GridViewAdapter.java package peek.imageupload; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class GridViewAdapter extends BaseAdapter{ //Declare Variables private Activity activity; private String[] filepath; private String[] filename; //thumbnailwidth allows for quickly adjusting the grid width for testing optimal size private int thumbnailwidth = 300; private static LayoutInflater inflater = null; public GridViewAdapter(Activity a, String[] fpath, String[] fname){ activity = a; filepath = fpath; filename = fname; inflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount(){ return filepath.length; } public Object getItem(int postion) { return postion; } public long getItemId(int position){ return position; } public View getView(int position, View convertView, ViewGroup parent){ View vi = convertView; if (convertView == null) vi = inflater.inflate(R.layout.gridview_item, null); //Locate the TextView in received images TextView text = (TextView) vi.findViewById(R.id.text); //Locate the imageview in received images ImageView image = (ImageView) vi.findViewById(R.id.image); //set file name to the Textview followed by position text.setText(filename[position]); //Decode the filepath with bitmapfactory BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(filepath[position], bitmapOptions); double imageWidth = bitmapOptions.outWidth; double imageHeight = bitmapOptions.outHeight; //calculate aspect ratio so image doesnt scale weird double d_aspectratio = imageHeight/imageWidth; double d_height = thumbnailwidth * d_aspectratio; int height = (int) d_height; bitmapOptions.inJustDecodeBounds = false; //decode the image map with the new bounds Bitmap bmp = BitmapFactory.decodeFile(filepath[position]); Bitmap resized = Bitmap.createScaledBitmap(bmp, thumbnailwidth, height, true); //Bitmap bmp = BitmapFactory.decodeFile(filepath[position]); //Bitmap resized = Bitmap.createScaledBitmap(bmp, 400, 400, true); //set the decoded bitmapp to the imageview image.setImageBitmap(resized); return vi; } }
ad34c7d48ef54be953156d95b110605f2fb7bb5a
[ "Java" ]
1
Java
PasoSteve/peekapp
bf4bffa366c9707c4f8916e59acbaaea46f445a5
c7c9b26f2f32cece265c745af061711432854512
refs/heads/master
<repo_name>Mr-Lima/broland-api<file_sep>/README.md ### Just a project to help my friends mount and admin their minecraft server in AWS Pair with https://github.com/Mr-Lima/broland-web <file_sep>/src/api/server.js import express from 'express'; import initRestRoutes from './routes'; import { registerMiddleware, registerErrorHandler } from './middlewares'; const app = express(); registerMiddleware(app); initRestRoutes(app); registerErrorHandler(app); export default app; <file_sep>/src/services/helpers/utility.js import { validationResult } from 'express-validator'; import { UnprocessableEntity } from 'http-errors'; import logger from '../../config/logger'; /** * * * @export * @param {Error} err * @returns void */ export default function handleError(err) { logger.error(err.stack || err); } export function validateRequest(request, next) { const valErr = validationResult(request); if (!valErr.isEmpty()) next(new UnprocessableEntity(valErr.array())); } <file_sep>/src/api/middlewares/index.js import { json } from 'express'; import cors from 'cors'; import handleError from '../../services/helpers/utility'; /** * Init Express middleware * * @param {import('express').Router} router * @returns {void} */ export function registerMiddleware(router) { router.use(cors()); router.use(json()); } /** * Init Express error handler * * @param {import('express').Router} router * @var {Error} err * @returns {void} */ export function registerErrorHandler(router) { // eslint-disable-next-line no-unused-vars router.use((err, req, res, next) => { handleError(err); return res.status(err.statusCode || 500).json({ error: err.message || err, status: err.statusCode || 500, }); }); } <file_sep>/src/api/components/server/routes.js import { Router } from 'express'; import { validate, start, stop, status, toggle } from './controller'; /** * * * @export * @param {import('express').Router} router * @param {string} prefix */ export default function registerServerRoutes(router, prefix) { const serverRouter = new Router(); serverRouter.get('/status', status); serverRouter.post('/toggle', validate('toggleServer'), toggle); serverRouter.post('/start', validate('toggleServer'), start); serverRouter.post('/stop', validate('toggleServer'), stop); router.use(`${prefix}`, serverRouter); } <file_sep>/src/api/components/index.js import registerServerRoutes from './server/routes'; /** * Init Express api routes * * @param {import('express').Router} router * @param {string} prefix * @returns {void} */ export default function registerApiRoutes(router, prefix) { registerServerRoutes(router, `${prefix}/server`); } <file_sep>/src/index.js import { createServer } from 'http'; import { env } from './config/globals'; import logger from './config/logger'; import app from './api/server'; async function startServer() { try { logger.info('Starting server'); const server = createServer(app); app.get('/status', (req, res) => { res.status(200).end(); }); app.head('/status', (req, res) => { res.status(200).end(); }); // Useful if you're behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc) // It shows the real origin IP in the heroku or Cloudwatch logs app.enable('trust proxy'); server.listen(env.PORT); server.on('listening', () => { logger.info( `\n################################################ 🛡️ Server listening on port: ${env.PORT} in ${env.NODE_ENV} 🛡️ ################################################`, ); }); server.on('close', () => { logger.info('Server closed'); }); } catch (err) { logger.error(err.stack); } } startServer(); <file_sep>/src/api/components/server/controller.js import { body } from 'express-validator'; import { Unauthorized, UnprocessableEntity } from 'http-errors'; import { startInstance, stopInstance, getInstanceStatus, } from '../../../services/aws'; import { env } from '../../../config/globals'; import { validateRequest } from '../../../services/helpers/utility'; export function validate(method) { switch (method) { case 'toggleServer': return [ body('user', 'empty user').exists(), body('password', 'empty password').exists(), ]; default: return []; } } export async function status(req, res, next) { try { const result = await getInstanceStatus(env.EC2_INSTANCE); res.send(result); } catch (err) { next(err); } } export async function toggle(req, res, next) { validateRequest(req, next); if (req.body.user !== 'admin' || req.body.password !== '<PASSWORD>') next(new Unauthorized('Invalid credentials')); else { try { const statusResult = await getInstanceStatus(env.EC2_INSTANCE); if (statusResult.status === 'running') { const result = await stopInstance(env.EC2_INSTANCE); res.send(result); } else if (statusResult.status === 'stopped') { const result = await startInstance(env.EC2_INSTANCE); res.send(result); } else { throw new UnprocessableEntity( 'The server is doing something, try another time', ); } } catch (err) { next(err); } } } export async function start(req, res, next) { validateRequest(req, next); if (req.body.user !== 'admin' || req.body.password !== '<PASSWORD>') next(new Unauthorized('Invalid credentials')); else { try { const result = await startInstance(env.EC2_INSTANCE); res.send(result); } catch (err) { next(err); } } } export async function stop(req, res, next) { validateRequest(req, next); if (req.body.user !== 'admin' || req.body.password !== '<PASSWORD>') next(new Unauthorized('Invalid credentials')); else { try { const result = await stopInstance(env.EC2_INSTANCE); res.send(result); } catch (err) { next(err); } } } <file_sep>/src/api/routes.js import registerApiRoutes from './components'; /** * Init Express REST routes * * @param {import('express').Router} router * @returns {void} */ export default function initRestRoutes(router) { const prefix = ''; registerApiRoutes(router, prefix); }
ad2d255d3d03f76856a81945e4824a9811b782a5
[ "Markdown", "JavaScript" ]
9
Markdown
Mr-Lima/broland-api
41cf0c95915ce15007e4599547e4643c70a245a4
60fcd789863a00698b1f88d795af9717e2fb13e6
refs/heads/master
<repo_name>GhostKicker/fadeev_a_u<file_sep>/matrix/matrix.h #ifndef MATRIX_H #define MATRIX_H #include <cstddef> using namespace std; class Matrix { public: Matrix() = default; Matrix(const ptrdiff_t& nRow, const ptrdiff_t& nCol); Matrix(const Matrix& m); ~Matrix(); void swapWith(Matrix& m); ptrdiff_t& length(); ptrdiff_t& rowNum(); ptrdiff_t& colNum(); double& operator()(const ptrdiff_t i, const ptrdiff_t j); const double& operator()(const ptrdiff_t i, const ptrdiff_t j) const; bool operator==(const Matrix& rhs); bool operator!=(const Matrix& rhs); Matrix& operator=(const Matrix& obj); Matrix& operator+=(const Matrix& m); Matrix& operator-=(const Matrix& m); Matrix& operator*=(const Matrix& m); Matrix& operator*=(const double& rhs); //double& determinator(); //Matrix& pow(const Matrix& m, long long& power); //Matrix& inverse(); private: double** ppData_{ nullptr }; ptrdiff_t nRow_{ 0 }; ptrdiff_t nCol_{ 0 }; ptrdiff_t length_{ 0 }; }; Matrix operator+(const Matrix& lhs, const Matrix& rhs); Matrix operator-(const Matrix& lhs, const Matrix& rhs); Matrix operator*(const Matrix& lhs, const Matrix& rhs); Matrix operator*(const Matrix& lhs, const double& rhs); Matrix operator*(const double& lhs, const Matrix& rhs); #endif // !MATRIX_H <file_sep>/rational/rational_test.cpp #include "rational.h" #include <iostream> #include <sstream> using namespace std; bool testParse(const std::string str) { using namespace std; istringstream istrm(str); Rational z; istrm >> z; if (istrm.good()) { cout << "Read success: " << str << z << endl; } else { cout << "Read error : " << str << z << endl; } return istrm.good(); } int main() { using namespace std; Rational smth; smth.~Rational(); Rational a; Rational b; Rational c(3, 5); cout << "1/2 and 1/3" << endl; RationalBasicTest(cout, Rational(1, 2), Rational(1, 3)); cout << "1/2 and -2" << endl; RationalBasicTest(cout, Rational(1, 2), -2); cout << "-1 * " << c << " = " << -c << endl; //cout << "-2 and 1/3" << endl; //RationalBasicTest(cout, -2, Rational(1, 3)); testParse("3/ 5"); testParse("-3 :5"); testParse("-3 / 2"); cout << "Input first rational number" << endl; cin >> a; cout << a << endl; cout << "Input second rational number" << endl; cin >> b; cout << b << endl; Rational aa(a); Rational bb(b); cout << "nonnormalized a and b : " << aa << " " << bb << endl; aa.normalizeWith(bb); cout << "normalized a and b : " << aa << " " << bb << endl; RationalBasicTest(cout, a, b); int d; cin >> d; return 0; } <file_sep>/string_matrix/string_matrix.cpp #include "string_matrix.h" #include <stdexcept> String_Matrix::String_Matrix (const ptrdiff_t& l, const ptrdiff_t& w) { if (l < 0 || w < 0) { throw (std::invalid_argument("negative size")); } pArray_ = new std::string[l*w]; } String_Matrix::~String_Matrix() { delete[] pArray_; } String_Matrix::String_Matrix(const String_Matrix& m) { } String_Matrix& String_Matrix::operator=(const String_Matrix& m) { String_Matrix tmp(length_, weigth_); tmp.length_ = m.length_; tmp.weigth_ = m.weigth_; tmp.pArray_ = new std::string[tmp.length_*tmp.weigth_]; for (ptrdiff_t i = 0; i < *(tmp.pArray_)->size(); i++) { } }<file_sep>/priorityqueuel/priorityqueuel.cpp #include "priorityqueuel.h" #include <stdexcept> #include <sstream> #include <iostream> using namespace std; bool PriorityQueueL::isEmpty() const { return pHead_ == nullptr; } void PriorityQueueL::pop() { Node* pDel = pHead_; pHead_ = pHead_->pNext_; delete pDel; } const int& PriorityQueueL::top() const { if (isEmpty()) throw(runtime_error("stack is empty!")); return pHead_->data_; } void PriorityQueueL::push(const int& d) { if (!isEmpty()) { if (pHead_->data_ < d) { pHead_ = new Node(pHead_, d); } else { Node* pCycle = pHead_; while (pCycle->pNext_ != nullptr && pCycle->pNext_->data_ >= d) { pCycle = pCycle->pNext_; } Node* pTmp = pCycle->pNext_; pCycle->pNext_ = new Node(pTmp, d); } } else { pHead_ = new Node(nullptr, d); } } PriorityQueueL::~PriorityQueueL() { while (!isEmpty()) { pop(); } pHead_ = nullptr; } void PriorityQueueL::clear() { while (!isEmpty()) { pop(); } pHead_ = nullptr; } PriorityQueueL::PriorityQueueL(const PriorityQueueL& pql) { PriorityQueueL q; Node* current = pql.pHead_; if (!pql.isEmpty()) { q.push(current->data_); while (current->pNext_ != nullptr) { current = current->pNext_; q.push(current->data_); } } swap(this->pHead_, q.pHead_); } PriorityQueueL& PriorityQueueL::operator=(const PriorityQueueL& rhs) { //finally, done! if (rhs.isEmpty()) { clear(); } else { Node* pRhs = rhs.pHead_; if (this->isEmpty()) { pHead_ = new Node(nullptr, pRhs->data_); Node* pThis = this->pHead_; while (pRhs->pNext_ != nullptr) { pThis->pNext_ = new Node(nullptr, pRhs->pNext_->data_); pThis = pThis->pNext_; pRhs = pRhs->pNext_; } } else { Node* pThis = this->pHead_; pThis->data_ = pRhs->data_; while (pThis->pNext_ != nullptr && pRhs->pNext_ != nullptr) { pThis->pNext_->data_ = pRhs->pNext_->data_; pThis = pThis->pNext_; pRhs = pRhs->pNext_; } while (pRhs->pNext_ != nullptr) { pThis->pNext_ = new Node (nullptr, pRhs->pNext_->data_); pThis = pThis->pNext_; pRhs = pRhs->pNext_; } Node* tmp = pThis; pThis = pThis->pNext_; pRhs = pRhs->pNext_; tmp->pNext_ = nullptr; while (pThis != nullptr) { Node* tmp = pThis; pThis = pThis->pNext_; delete tmp; } } } return *this; }<file_sep>/stacka/stacka.h #ifndef STACKA_H #define STACKA_H #include <cstddef> class StackA { public: StackA() = default; StackA(const StackA& st); StackA(const ptrdiff_t& size); ~StackA(); StackA& operator=(const StackA& st); const ptrdiff_t& size(); const ptrdiff_t& capacity(); void push(const int& v); void pop(); int& top(); void clear(); void resize(const int& size); bool isEmpty(); private: int* pArray_ = nullptr; ptrdiff_t physSize_ = 0; ptrdiff_t logicSize_ = 0; }; #endif // !STACKA_H <file_sep>/complex/complex.cpp #include <iostream> #include <sstream> #include "complex.h" Complex operator+(const Complex& lhs, const double rhs) { return operator+(lhs, Complex(rhs)); }; Complex operator-(const Complex& lhs, const double rhs) { return operator-(lhs, Complex(rhs)); }; Complex operator*(const Complex& lhs, const double rhs) { return operator*(lhs, Complex(rhs)); }; Complex operator/(const Complex& lhs, const double rhs) { return operator/(lhs, Complex(rhs)); }; std::ostream& operator<<(std::ostream& ostrm, const Complex& rhs) { return rhs.writeTo(ostrm); } std::istream& operator>>(std::istream& istrm, Complex& rhs) { return rhs.readFrom(istrm); } bool testParse(const std::string& str) { using namespace std; istringstream istrm(str); Complex z; istrm >> z; if (istrm.good()) { cout << "Read success: " << str << z << endl; } else { cout << "Read error : " << str << z << endl; } return istrm.good(); } Complex::Complex(const double real) : Complex(real, 0.0) { } Complex::Complex(const double real, const double imagenary) : re(real) , im(imagenary) { } const double Eps{ 0.00001 }; bool Complex::operator==(const Complex& rhs) const { bool a = (abs(re - rhs.re) < Eps); bool b = (abs(im - rhs.im) < Eps); if (a && b) { return true; } else { return false; } }; bool Complex::operator!=(const Complex& rhs) const { return !operator==(rhs); } Complex& Complex::operator+=(const Complex& rhs) { re += rhs.re; im += rhs.im; return *this; } Complex& Complex::operator-=(const Complex& rhs) { re -= rhs.re; im -= rhs.im; return *this; } Complex operator+(const Complex& lhs, const Complex& rhs) { Complex sum(lhs); sum += rhs; return sum; } Complex operator-(const Complex& lhs, const Complex& rhs) { Complex dif(lhs); dif -= rhs; return dif; } Complex operator*(const Complex& lhs, const Complex& rhs) { Complex com(lhs); com *= rhs; return com; } Complex operator/(const Complex& lhs, const Complex& rhs) { Complex quo(lhs); quo /= rhs; return quo; } Complex& Complex::operator*=(const double rhs) { re *= rhs; im *= rhs; return *this; } Complex& Complex::operator/=(const double rhs) { re /= rhs; im /= rhs; return *this; } Complex& Complex::operator*=(const Complex& rhs) { re = (re * rhs.re - im * rhs.im); im = (re * rhs.im + im * rhs.re); return *this; } Complex& Complex::operator/=(const Complex& rhs) { re = (re * rhs.re + im * rhs.im) / (rhs.re * rhs.re + rhs.im * rhs.im); im = (im * rhs.re - re * rhs.im) / (rhs.re * rhs.re + rhs.im * rhs.im); return *this; } Complex& Complex::operator-() { re = -re; im = -im; return *this; } std::ostream& Complex::writeTo(std::ostream& ostrm) const { ostrm << leftBrace << re << separator << im << rightBrace; return ostrm; } std::istream& Complex::readFrom(std::istream& istrm) { char leftBrace(0); double real(0.0); char comma(0); double imaganary(0.0); char rightBrace(0); istrm >> leftBrace >> real >> comma >> imaganary >> rightBrace; if (istrm.good()) { if ((Complex::leftBrace == leftBrace) && (Complex::separator == comma) && (Complex::rightBrace == rightBrace)) { re = real; im = imaganary; } else { istrm.setstate(std::ios_base::failbit); } } return istrm; }<file_sep>/vec3d/vec3d_test.cpp #include <iostream> #include "vec3d.h" using namespace std; int main() { Vec3d v1(2.0, 4.0, 6.0); Vec3d v(3, 4, 5); Vec3d v7(3.0,-4.0,12.0); Vec3d v2 = v1; Vec3d v4(-2.0, 4.1, 5.1); Vec3d v5(-2.0, 4.100009, 5.1); Vec3d v6(-2.0, 4.10001, 5.1); Vec3d v8(2, 0, 0); Vec3d v9(0, 2, 0); cout << v4 << " == " << v5 << " <==> " << ((v4 == v5) ? "true" : "false") << endl; cout << v4 << " == " << v6 << " <==> " << ((v4 == v6) ? "true" : "false") << endl; cout << v4 << " != " << v6 << " <==> " << ((v4 != v6) ? "true" : "false") << endl; cout << v << " * " << 3.5 << " = " << v*3.5 << endl; cout << 3.5 << " * " << v << " = " << 3.5*v << endl; cout << v << " / " << -3.5 << " =" << v / (-3.5) << endl; v = v + v1; cout << "- " << v << " = " << (-v) << endl; cout << "Vector length of " << v7 << " is " << v7.length() << endl; cout << "Dot product of " << v1 << " and " << v7 << " is " << dotProduct(v1, v7) << endl; cout << "Cross product of " << v8 << " and " << v9 << " is " << crossProduct(v8, v9) << endl; return 0; }<file_sep>/array/array.h #ifndef ARRAY_H #define ARRAY_H #include <cstddef> using namespace std; class Array { //erase(i), push_back, pop_back public: Array(); Array(const Array& ar); Array(const int& size); ~Array(); void swapWith(Array& rhs); void resize(const ptrdiff_t& newCap); ptrdiff_t size() const; ptrdiff_t capacity() const; void insert(ptrdiff_t i, int data); void erase(ptrdiff_t i); void push_back(const int num); void pop_back(); int& operator[](const ptrdiff_t i); const int& operator[](const ptrdiff_t i) const; Array& operator=(const Array& obj); private: ptrdiff_t physSize_{ 0 }; ptrdiff_t logicSize_{ 0 }; int* pData_{ nullptr }; }; #endif // !ARRAY_H <file_sep>/stackl/stackl.cpp #include "stackl.h" #include <stdexcept> using namespace std; void StackL::push(const int& data) { pHead_ = new Node(pHead_, data); } int& StackL::top() { if (isEmpty()) throw(runtime_error("stack is empty!")); return pHead_->data_; } const int& StackL::top() const { if (isEmpty()) throw(runtime_error("stack is empty!")); return pHead_->data_; } void StackL::pop() { Node* pDel = pHead_; pHead_ = pHead_->pNext_; delete pDel; } bool StackL::isEmpty() const { return nullptr == pHead_; } StackL::~StackL() { while (!isEmpty()) { pop(); } } void StackL::clear() { while (!isEmpty()) { pop(); } } StackL::StackL(const StackL& st) { //wrong, will be rewritten pHead_ = nullptr; if (!st.isEmpty()) { pHead_ = new Node(nullptr, st.pHead_->data_); Node* current = pHead_; Node* currentst = st.pHead_; do { currentst = currentst->pNext_; current->pNext_ = new Node(nullptr, currentst->data_); current = current->pNext_; } while (!(nullptr == currentst->pNext_)); } } StackL& StackL::operator=(const StackL& obj) { if (this != &obj) { StackL tmpst(obj); Node* tmp = tmpst.pHead_; tmpst.pHead_ = pHead_; pHead_ = tmp; } return *this; }<file_sep>/stackl/stackl_test.cpp #include "stackl.h" #include <iostream> using namespace std; int main() { StackL stack; stack.push(3); cout << "top element: " << stack.top() << endl; cout << "stack is empty: " << (stack.isEmpty() ? "true" : "false") << endl; stack.pop(); cout << "stack is empty: " << (stack.isEmpty() ? "true" : "false") << endl; try { stack.top(); } catch (runtime_error e) { cout << "I tried to get top from empty stack but I couldn't" << endl; } stack.push(1); stack.push(2); cout << "top element: " << stack.top() << endl; stack.pop(); cout << "top element: " << stack.top() << endl; stack.push(3); StackL stack2(stack); cout << "top element of 2nd stack: " << stack2.top() << endl; stack2.pop(); cout << "top element of 2nd stack: " << stack2.top() << endl; stack2.pop(); try { stack2.top(); } catch (runtime_error e) { cout << "I tried to get top from empty stack but I couldn't" << endl; } StackL stack3; stack3 = stack; cout << "top element of 3rd stack: " << stack3.top() << endl; stack3.pop(); cout << "top element of 3rd stack: " << stack3.top() << endl; stack3.pop(); try { stack3.top(); } catch (runtime_error e) { cout << "I tried to get top from empty stack but I couldn't" << endl; } return 0; }<file_sep>/priorityqueuel/priorityqueuel.h #ifndef PRIORITYQUEUE_H #define PRIORITYQUEUE_H class PriorityQueueL { public: PriorityQueueL() = default; PriorityQueueL(const PriorityQueueL& pql); ~PriorityQueueL(); PriorityQueueL& operator=(const PriorityQueueL& rhs); void clear(); void push(const int& data); void pop(); const int& top() const; bool isEmpty() const; private: struct Node { Node* pNext_ = nullptr; int data_ = int(0); Node(Node* pNode, const int& d) :pNext_(pNode) ,data_(d) { } }; Node* pHead_ = nullptr; }; #endif // !PRIORITYQUEUE_H <file_sep>/queuea/queuea_test.cpp #include "queuea.h" #include <iostream> int main() { QueueA q; q.push(3); return 0; }<file_sep>/complex/complex.h #ifndef COMPLEX_H #define COMPLEX_H #include <iosfwd> #include <iostream> struct Complex { Complex() = default; Complex(const Complex& c) = default; ~Complex() = default; explicit Complex(const double real); Complex(const double real, const double imaginary); bool operator==(const Complex& rhs) const; bool operator!=(const Complex& rhs) const; Complex& operator+=(const Complex& rhs); Complex& operator+=(const double rhs) { return operator+=(Complex(rhs)); } Complex& operator-=(const Complex& rhs); Complex& operator-=(const double rhs) { return operator-=(Complex(rhs)); } Complex& operator*=(const Complex& rhs); Complex& operator*=(const double rhs); Complex& operator/=(const Complex& rhs); Complex& operator/=(const double rhs); Complex& operator-(); std::ostream& writeTo(std::ostream& ostrm) const; std::istream& readFrom(std::istream& istrm); double re{ 0.0 }; double im{ 0.0 }; static const char leftBrace{ '{' }; static const char separator{ ',' }; static const char rightBrace{ '}' }; }; Complex operator+(const Complex& lhs, const Complex& rhs); Complex operator-(const Complex& lhs, const Complex& rhs); Complex operator*(const Complex& lhs, const Complex& rhs); Complex operator/(const Complex& lhs, const Complex& rhs); Complex operator+(const Complex& lhs, const double& rhs); Complex operator-(const Complex& lhs, const double& rhs); Complex operator*(const Complex& lhs, const double& rhs); Complex operator/(const Complex& lhs, const double& rhs); Complex operator+(const double& lhs, const Complex& rhs); Complex operator-(const double& lhs, const Complex& rhs); std::ostream& operator<<(std::ostream& ostrm, const Complex& rhs); std::istream& operator>>(std::istream& istrm, Complex& rhs); bool testParse(const std::string& str); #endif // ! COMPLEX_H <file_sep>/stacka/stacka.cpp #include "stacka.h" #include <algorithm> #include <stdexcept> using namespace std; StackA::~StackA() { delete[] pArray_; pArray_ = nullptr; } StackA::StackA(const ptrdiff_t& size) { pArray_ = new int[size]; physSize_ = size; } void StackA::resize(const int& size) { if (size == physSize_) return; logicSize_ = min(logicSize_, size); physSize_ = size; int* pNew = new int[size]; for (ptrdiff_t i = 0; i < logicSize_; i++) { *(pNew + i) = *(pArray_ + i); } swap(pNew, pArray_); } void StackA::push(const int& v) { if (physSize_ == logicSize_) resize(physSize_ + 1); *(pArray_ + logicSize_) = v; logicSize_++; } const ptrdiff_t& StackA::size() { return logicSize_; } const ptrdiff_t& StackA::capacity() { return physSize_; } void StackA::pop() { if (logicSize_) logicSize_--; } int& StackA::top() { if (logicSize_ == 0) { throw (out_of_range("size of stack is 0")); } return *(pArray_ + logicSize_ - 1); } bool StackA::isEmpty() { return (!logicSize_); } void StackA::clear() { logicSize_ = 0; } StackA& StackA::operator=(const StackA& st) { StackA tmp(st.physSize_); tmp.logicSize_ = st.logicSize_; for (ptrdiff_t i = 0; i < st.logicSize_; i++) { *(tmp.pArray_ + i) = *(st.pArray_ + i); } swap(this->pArray_, tmp.pArray_); swap(this->logicSize_, tmp.logicSize_); swap(this->physSize_, tmp.physSize_); return *this; } StackA::StackA(const StackA& st) { *this = st; }<file_sep>/vec3dT/vec3dT.h #ifndef VEC3DT_H #define VEC3DT_H template<typename T> struct Vec3dT { public: Vec3dT() = default; Vec3dT(const Vec3dT& v) = default; Vec3dT(const T& xi, const T& yi, const T& zi); ~Vec3dT() = default; Vec3dT& operator+=(const Vec3dT& rhs); Vec3dT& operator-=(const Vec3dT& rhs); Vec3dT<double>& operator*=(const double& rhs); Vec3dT<double>& operator/=(const double& rhs); double length() const; bool operator==(const Vec3dT& rhs); bool operator!=(const Vec3dT& rhs); Vec3dT& operator=(const Vec3dT& rhs); public: T x{ T() }; T y{ T() }; T z{ T() }; static const char leftBrace = '{'; static const char rightBrace = '}'; static const char dotcomma = ';'; }; template <typename T> bool Vec3dT<T>::operator==(const Vec3dT<T>& rhs) { if ((x == rhs.x) && (y == rhs.y) && (z == rhs.z)) { return true; } else { return false; } } template <typename T> bool Vec3dT<T>::operator!=(const Vec3dT<T>& rhs) { return (!operator==(rhs)); } template <typename T> Vec3dT<T>& Vec3dT<T>::operator+=(const Vec3dT<T>& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } template <typename T> Vec3dT<T> operator+(const Vec3dT<T>& lhs, const Vec3dT<T>& rhs) { Vec3dT<T> l(lhs); l += rhs; return l; } template <typename T> Vec3dT<T>& Vec3dT<T>::operator-=(const Vec3dT<T>& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } template <typename T> Vec3dT<T> operator-(const Vec3dT<T>& lhs, const Vec3dT<T>& rhs) { Vec3dT<T> l(lhs); l -= rhs; return l; } template <typename T> Vec3dT<T>::Vec3dT(const T& xi, const T& yi, const T& zi) : x{ xi } , y{ yi } , z{ zi } { }; template <typename T> Vec3dT<T>& Vec3dT<T>::operator=(const Vec3dT<T>& rhs) { x = rhs.x; y = rhs.y; z = rhs.z; return *this; } double eps = 0.000001; bool Vec3dT<double>::operator==(const Vec3dT<double>& rhs) { if ( (abs(x - rhs.x) < eps) && (abs(y - rhs.y) < eps) && (abs(z - rhs.z) < eps) ) { return true; } else { return false; } } Vec3dT<double>& Vec3dT<double>::operator*=(const double& rhs) { x *= rhs; y *= rhs; z *= rhs; return *this; } Vec3dT<double>& Vec3dT<double>::operator/=(const double& rhs) { x /= rhs; y /= rhs; z /= rhs; return *this; } Vec3dT<double> operator*(const Vec3dT<double>& lhs, const double& rhs) { Vec3dT<double> g = lhs; return g.operator*=(rhs); } Vec3dT<double> operator/(const Vec3dT<double>& lhs, const double& rhs) { Vec3dT<double> g = lhs; return g.operator/=(rhs); } Vec3dT<double> operator*(const double& lhs, const Vec3dT<double>& rhs) { double a = lhs; Vec3dT<double> b = rhs; return b.operator*=(a); } double Vec3dT<double>::length() const { return sqrt(x*x + y*y + z*z); } double dotProduct(const Vec3dT<double>& lhs, const Vec3dT<double>& rhs) { return (lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z); } Vec3dT<double> crossProduct(const Vec3dT<double>& lhs, const Vec3dT<double>& rhs) { double x = lhs.y * rhs.z - lhs.z * rhs.y; double y = lhs.z * rhs.x - lhs.x * rhs.z; double z = lhs.x * rhs.y - lhs.y * rhs.x; return Vec3dT<double>(x, y, z); } #endif // VEC3DT_H <file_sep>/rational/rational.cpp #include "Rational.h" #include <iostream> #include <sstream> #include <stdexcept> int GCD(int a, int b) { while (b) { a %= b; int c = a; a = b; b = c; } return a; } int LCD(int a, int b) { return (a*b / GCD(a, b)); } std::ostream& operator<<(std::ostream& ostrm, const Rational& rhs) { return rhs.writeTo(ostrm); } std::istream& operator>>(std::istream& istrm, Rational& rhs) { return rhs.readFrom(istrm); } Rational::Rational(const int nume) : Rational(nume, 1) { } Rational::Rational(const int nume, const int denume) : num(nume) , denum(denume) { if (0 == denum) // had (denum = 0) thing... now I understand { throw ("Denumenator hasn't be 0"); } int g = (GCD(nume,denume)); num /= g; denum /= g; if (denum < 0) { num = -num; denum = -denum; } } std::ostream& Rational::writeTo(std::ostream& ostrm) const { ostrm << num << slash << denum; return ostrm; } std::istream& Rational::readFrom(std::istream& istrm) { int numerator(0); char line(0); int denumerator(0); istrm >> numerator >> line >> denumerator; if (istrm.good()) { if (((Rational::doubledot == line)||(Rational::slash == line)) && (denumerator > 0)) { num = numerator; denum = denumerator; *this = Rational(num, denum); } else { istrm.setstate(std::ios_base::failbit); } } return istrm; } void Rational::normalizeWith(Rational& b) { int denumee = LCD(denum, b.denum); int anum = num * (denumee / denum); int bnum = b.num * (denumee / b.denum); num = anum; denum = denumee; b.num = bnum; b.denum = denumee; } bool Rational::operator==(const Rational& rhs) { Rational a(num, denum); Rational b(rhs); a.normalizeWith(b); return ((a.num == b.num) && (a.denum == b.denum)); } bool Rational::operator==(const int& rhs) { return operator==(Rational(rhs)); }; bool Rational::operator!=(const Rational& rhs) { return !operator==(rhs); } bool Rational::operator!=(const int& rhs) { return operator!=(Rational(rhs)); } Rational& Rational::operator+=(const Rational& rhs) { Rational rhss(rhs); normalizeWith(rhss); num = num + rhss.num; *this = Rational(num, denum); return *this; } Rational& Rational::operator-=(const Rational& rhs) { Rational rhss(rhs); normalizeWith(rhss); num = num - rhss.num; *this = Rational(num, denum); return *this; } Rational& Rational::operator*=(const Rational& rhs) { num *= rhs.num; denum *= rhs.denum; *this = Rational(num, denum); if (denum < 0) { num = -num; denum = -denum; } return *this; } Rational& Rational::operator/=(const Rational& rhs) { Rational r(rhs); if (r < 0) { r.num = -r.num; r = Rational(r.denum, r.num); r.num = -r.num; } else { r = Rational(r.denum, r.num); } return (operator*=(r)); }; Rational operator+ (const Rational& lhs, const int& rhs) { return (lhs + Rational(rhs)); }; Rational operator- (const Rational& lhs, const int& rhs) { return (lhs - Rational(rhs)); }; Rational operator* (const Rational& lhs, const int& rhs) { return (lhs * Rational(rhs)); }; Rational operator/ (const Rational& lhs, const int& rhs) { return (lhs / Rational(rhs)); }; Rational operator+ (const int& lhs, const Rational& rhs) { return (Rational(lhs) + rhs); }; Rational operator- (const int& lhs, const Rational& rhs) { return (Rational(lhs) - rhs); }; Rational operator* (const int& lhs, const Rational& rhs) { return (Rational(lhs) * rhs); }; Rational operator/ (const int& lhs, const Rational& rhs) { return (Rational(lhs) / rhs); }; bool Rational::operator<=(const Rational rhs) { return (operator==(rhs) || operator<(rhs)); } bool Rational::operator>=(const Rational rhs) { return (operator==(rhs) || operator>(rhs)); } bool Rational::operator>(const int rhs) { return operator>(Rational(rhs)); }; bool Rational::operator<(const int rhs) { return operator<(Rational(rhs)); }; Rational& Rational::operator+=(const int lhs) { return operator+=(Rational(lhs)); } Rational& Rational::operator-=(const int lhs) { return operator-=(Rational(lhs)); } Rational& Rational::operator*=(const int lhs) { return operator*=(Rational(lhs)); } Rational& Rational::operator/=(const int lhs) { return operator/=(Rational(lhs)); } bool Rational::operator<(const Rational& rhs) { Rational a(num, denum); Rational b(rhs); a.normalizeWith(b); return (a.num < b.num); } bool Rational::operator>(const Rational& rhs) { Rational a(num, denum); Rational b(rhs); a.normalizeWith(b); return (a.num > b.num); } Rational operator+(const Rational& lhs, const Rational& rhs) { Rational s(lhs); s += rhs; return s; } Rational operator-(const Rational& lhs, const Rational& rhs) { Rational s(lhs); s -= rhs; return s; } Rational operator*(const Rational& lhs, const Rational& rhs) { Rational s(lhs); s *= rhs; return s; } Rational operator/(const Rational& lhs, const Rational& rhs) { Rational s(lhs); s /= rhs; return s; } Rational operator-(const Rational& rhs) { return operator-(0, rhs); }; void RationalBasicTest(std::ostream& ostrm, const Rational& a, const Rational& b) { Rational h(a); ostrm << a << " + " << b << " = " << (a + b) << std::endl; ostrm << a << " - " << b << " = " << (a - b) << std::endl; ostrm << a << " * " << b << " = " << (a * b) << std::endl; ostrm << a << " / " << b << " = " << (a / b) << std::endl; ostrm << a << " < " << b << " <=> " << ((h < b) ? "true" : "false") << std::endl; ostrm << a << " > " << b << " <=> " << ((h > b) ? "true" : "false") << std::endl; ostrm << a << " == " << b << " <=> " << ((h == b) ? "true" : "false") << std::endl; ostrm << a << " != " << b << " <=> " << ((h != b) ? "true" : "false") << std::endl; ostrm << "-------------------" << std::endl; }; /* void RationalBasicTest(std::ostream& ostrm, const int& a, const Rational& b) { int h(a); ostrm << a << " + " << b << " = " << (a + b) << std::endl; ostrm << a << " - " << b << " = " << (a - b) << std::endl; ostrm << a << " * " << b << " = " << (a * b) << std::endl; ostrm << a << " / " << b << " = " << (a / b) << std::endl; ostrm << a << " < " << b << " <=> " << ((h < b) ? "true" : "false") << std::endl; ostrm << a << " > " << b << " <=> " << ((h > b) ? "true" : "false") << std::endl; ostrm << a << " == " << b << " <=> " << ((h == b) ? "true" : "false") << std::endl; ostrm << a << " != " << b << " <=> " << ((h != b) ? "true" : "false") << std::endl; ostrm << "-------------------" << std::endl; };*/ void RationalBasicTest(std::ostream& ostrm, const Rational& a, const int& b) { Rational h(a); ostrm << a << " + " << b << " = " << (a + b) << std::endl; ostrm << a << " - " << b << " = " << (a - b) << std::endl; ostrm << a << " * " << b << " = " << (a * b) << std::endl; ostrm << a << " / " << b << " = " << (a / b) << std::endl; ostrm << a << " < " << b << " <=> " << ((h < b) ? "true" : "false") << std::endl; ostrm << a << " > " << b << " <=> " << ((h > b) ? "true" : "false") << std::endl; ostrm << a << " == " << b << " <=> " << ((h == b) ? "true" : "false") << std::endl; ostrm << a << " != " << b << " <=> " << ((h != b) ? "true" : "false") << std::endl; ostrm << "-------------------" << std::endl; }; <file_sep>/matrix/matrix.cpp #include "matrix.h" #include <stdexcept> #include <cmath> ptrdiff_t& Matrix::length() { return length_; } ptrdiff_t& Matrix::colNum() { return nCol_; } ptrdiff_t& Matrix::rowNum() { return nRow_; } Matrix::Matrix(const ptrdiff_t& nRow, const ptrdiff_t& nCol) { if ((nRow < 0)||(nCol < 0)) { throw (invalid_argument("You cannot simply set array size to negative!")); } nRow_ = nRow; nCol_ = nCol; length_ = nCol * nRow; if ((nRow_ != 0) && (nCol_ != 0)) { ppData_ = new double*[nRow_]; for (ptrdiff_t i = 0; i < nRow_; i++) { ppData_[i] = new double[nCol_]; } } } Matrix::~Matrix() { for (int i = 0; i < nRow_; i++) { delete[] ppData_[i]; ppData_[i] = nullptr; } delete[] ppData_; ppData_ = nullptr; } double& Matrix::operator()(const ptrdiff_t i, const ptrdiff_t j) { if (i >= nRow_) { throw (out_of_range("Index is out of range!")); } if (j >= nCol_) { throw (out_of_range("Index is out of range!")); } return *(*(ppData_ + i) + j); } const double& Matrix::operator()(const ptrdiff_t i, const ptrdiff_t j) const { if (i >= nRow_) { throw (out_of_range("Index is out of range!")); } if (j >= nCol_) { throw (out_of_range("Index is out of range!")); } return *(*(ppData_ + i) + j); } Matrix::Matrix(const Matrix& m) :nRow_ (m.nRow_) ,nCol_ (m.nCol_) ,length_ (m.length_) { ppData_ = new double*[nRow_]; for (ptrdiff_t i = 0; i < nRow_; i++) { ppData_[i] = new double[nCol_]; } for (ptrdiff_t i = 0; i < nRow_; i++) { for (ptrdiff_t j = 0; j < nCol_; j++) { *(*(ppData_ + i) + j) = *(*(m.ppData_ + i) + j); } } } void Matrix::swapWith(Matrix& m) { swap(nRow_, m.nRow_); swap(nCol_, m.nCol_); swap(length_, m.length_); swap(ppData_, m.ppData_); } Matrix& Matrix::operator=(const Matrix& obj) { if (this != &obj) { this->swapWith(Matrix(obj)); } return *this; } Matrix& Matrix::operator+=(const Matrix& m) { if ((nCol_ != m.nCol_) || (nRow_ != m.nRow_)) { throw (invalid_argument("You can't plus matrixes with different sizes!")); } for (ptrdiff_t i = 0; i < nRow_; i++) { for (ptrdiff_t j = 0; j < nCol_; j++) { *(*(ppData_ + i) + j) += *(*(m.ppData_ + i) + j); } } return *this; } Matrix& Matrix::operator-=(const Matrix& m) { if ((nCol_ != m.nCol_) || (nRow_ != m.nRow_)) { throw (invalid_argument("You can't plus matrixes with different sizes!")); } for (ptrdiff_t i = 0; i < nRow_; i++) { for (ptrdiff_t j = 0; j < nCol_; j++) { *(*(ppData_ + i) + j) -= *(*(m.ppData_ + i) + j); } } return *this; } Matrix& Matrix::operator*=(const double& rhs) { for (ptrdiff_t i = 0; i < nRow_; i++) { for (ptrdiff_t j = 0; j < nCol_; j++) { *(*(ppData_ + i) + j) *= rhs; } } return *this; } Matrix operator+(const Matrix& lhs, const Matrix& rhs) { Matrix m(lhs); return m += rhs; } Matrix operator-(const Matrix& lhs, const Matrix& rhs) { Matrix m(lhs); return m -= rhs; } Matrix operator*(const Matrix& lhs, const double& rhs) { Matrix m(lhs); return m *= rhs; } Matrix operator*(const double& lhs, const Matrix& rhs) { Matrix m(rhs); return (m *= lhs); } double eps = 0.000001; bool Matrix::operator==(const Matrix& rhs) { if (nRow_ != rhs.nRow_) return false; if (nCol_ != rhs.nCol_) return false; for (ptrdiff_t i = 0; i < nRow_; i++) { for (ptrdiff_t j = 0; j < nCol_; j++) { double tmp = *(*(ppData_ + i) + j) - *(*(rhs.ppData_ + i) + j); if (abs(tmp) > eps) return false; } } return true; } bool Matrix::operator!=(const Matrix& rhs) { return !(this->operator==(rhs)); } Matrix& Matrix::operator*=(const Matrix& m) { if (nCol_ != m.nRow_) { throw (invalid_argument("You can't multiply 2 matrixes if first's nCol not equals second's nRow!")); } Matrix result(nRow_, m.nCol_); Matrix copy(*this); for (ptrdiff_t i = 0; i < result.nRow_; i++) { for (ptrdiff_t j = 0; j < result.nCol_; j++) { double tmpres = 0; for (ptrdiff_t k = 0; k < nCol_; k++) { tmpres += copy(i, k) * m(k, j); } result(i, j) = tmpres; } } this->swapWith(result); return *this; } Matrix operator*(const Matrix& lhs, const Matrix& rhs) { return Matrix(lhs) *= rhs; }<file_sep>/matrix/matrix_test.cpp #include "matrix.h" #include <iostream> void matrixOut(Matrix& m) { for (ptrdiff_t i = 0; i < m.rowNum(); i++) { for (ptrdiff_t j = 0; j < m.colNum(); j++) { cout << m(i, j) << " "; } cout << endl; } cout << "Row number = " << m.rowNum() << endl; cout << "Col number = " << m.colNum() << endl; cout << "Length = " << m.length() << endl; } void matrixIn(Matrix& m) { for (ptrdiff_t i = 0; i < m.rowNum(); i++) { for (ptrdiff_t j = 0; j < m.colNum(); j++) { m(i, j) = m.colNum()*i + j; } } } int main() { Matrix m1(); Matrix m2(3, 3); Matrix m6(4, 3); Matrix m7(3, 4); matrixIn(m2); matrixIn(m6); matrixIn(m7); Matrix m6x(m6); matrixOut(m6); cout << endl << endl; matrixOut(m7); cout << endl << endl; cout << "---------m2---------" << endl; matrixOut(m2); cout << "-------m3(m2)-------" << endl; Matrix m3(m2); matrixOut(m3); cout << "--------m4=m2-------" << endl; Matrix m4; m4 = m2; matrixOut(m4); cout << "-------m5+=m4-------" << endl; Matrix m5(m4); m5 += m4; matrixOut(m5); cout << "-------m6+=m4-------" << endl; try { m6 += m4; } catch (invalid_argument e) { cout << "I tried to summ matrixes with different sizes but I couldn't" << endl; } cout << "-------m4-=m2-------" << endl; m4 -= m2; matrixOut(m4); cout << "-------m6-=m4-------" << endl; try { m6 -= m4; } catch (invalid_argument e) { cout << "I tried to deduct matrixes with different sizes but I couldn't" << endl; } cout << "--------m9*=5-------" << endl; Matrix m9(m2); m9 *= 5; matrixOut(m9); cout << "-------m2+m2-------" << endl; matrixOut(m2 + m2); cout << "-------m6+m4-------" << endl; try { Matrix m13(m6 + m4); } catch (invalid_argument e) { cout << "I tried to summ matrixes with different sizes but I couldn't" << endl; } cout << "-------m2-m2-------" << endl; matrixOut(m2 - m2); cout << "-------m6-m4-------" << endl; try { Matrix m13(m6 - m4); } catch (invalid_argument e) { cout << "I tried to deduct matrixes with different sizes but I couldn't" << endl; } cout << "-------m2==m2-------" << endl; cout << ((m2 == m2) ? "true" : "false") << endl; cout << "-------m4==m2-------" << endl; cout << ((m4 == m2) ? "true" : "false") << endl; cout << "-------m4!=m2-------" << endl; cout << ((m4 != m2) ? "true" : "false") << endl; cout << "-------m6x*=m7-------" << endl; m6x *= m7; matrixOut(m6x); cout << "-------m6*=m6-------" << endl; try { m6 *= m6; } catch (invalid_argument e) { cout << "I tried to multiply two unmultiplyeble matrixes but I couldn't!" << endl; } cout << "-------m6*m7-------" << endl; matrixOut(m6*m7); cout << "-------m6*m6-------" << endl; try { matrixOut(m6 * m6); } catch (invalid_argument e) { cout << "I tried to multiply two unmultiplyeble matrixes but I couldn't!" << endl; } return 0; }<file_sep>/stackl/stackl.h #ifndef STACKL_H #define STACKL_H #include <cstddef> class StackL { public: StackL() = default; StackL(const StackL& st); ~StackL(); StackL& operator=(const StackL& rhs); void clear(); void push(const int& data); void pop(); int& top(); const int& top() const; bool isEmpty() const; private: struct Node { Node* pNext_ = nullptr; int data_ = int(0); Node(Node* pNode, const int& v) :pNext_(pNode) ,data_(v) { } }; Node* pHead_ = nullptr; }; #endif <file_sep>/coursework/main.cpp #define _SCL_SECURE_NO_WARNINGS #include <string> #include <sstream> #include <iostream> #include <map> #include <vector> #include <fstream> #include <algorithm> #include <experimental/filesystem> namespace fs = std::experimental::filesystem; #include "tiny_dnn/tiny_dnn.h" typedef std::map<tiny_dnn::label_t, std::map<tiny_dnn::label_t, int>> conf_m; typedef std::tuple<std::string, double, double, double, double> nn_datas; using namespace std; using namespace tiny_dnn; const string sep = ";"; int number_of_dots = 0; string root_path = ""; string path_to_models = ""; string path_to_data = ""; string path_to_databases = ""; int number_of_tested = 0; tiny_dnn::core::backend_t backend_type = tiny_dnn::core::default_engine(); std::vector<tiny_dnn::label_t> test_labels; std::vector<tiny_dnn::vec_t> test_images; std::set<std::string> nns; static void construct_net(tiny_dnn::network<tiny_dnn::sequential> &nn, tiny_dnn::core::backend_t backend_type); string find_file_name(string& full_path) { string res = ""; ptrdiff_t index = full_path.size(); --index; while (index >= 0 && full_path[index] != '\\') { res = full_path[index] + res; --index; } return res; } bool stream_is_empty(std::stringstream& pFile) { return pFile.peek() == std::ifstream::traits_type::eof(); } bool istream_is_empty(std::istream& pFile) { return pFile.peek() == std::istream::traits_type::eof(); } double Precision_i(const conf_m& m, int i) { int num = 0; if (m.find(i) != m.end() && m.at(i).find(i) != m.at(i).end()) num = m.at(i).at(i); int denum = 0; for (int j = 0; j <= 9; j++) { if (m.find(i) != m.end() && m.at(i).find(j) != m.at(i).end()) denum += m.at(i).at(j); } if (denum > 0) return (double)(num) / denum; else return 0; } double Recall_i(const conf_m& m, int i) { int num = 0; if (m.find(i) != m.end() && m.at(i).find(i) != m.at(i).end()) num = m.at(i).at(i); int denum = 0; for (int j = 0; j <= 9; j++) { if (m.find(j) != m.end() && m.at(j).find(i) != m.at(j).end()) denum += m.at(j).at(i); } if (denum > 0) return (double)(num) / denum; else return 0; } double Precision(const conf_m& m) { int denumm = 10; double totalPrecition = 0; for (int i = 0; i <= 9; i++) { double val = Precision_i(m, i); if (val == 0) denumm -= 1; totalPrecition += val; } return totalPrecition / denumm; } double Recall(const conf_m& m) { int denumm = 10; double totalRecall = 0; for (int i = 0; i <= 9; i++) { double val = Recall_i(m, i); if (val == 0) denumm -= 1; totalRecall += val; } return totalRecall / denumm; } double F1_i(const conf_m& m, int i) { return 2 * (Precision_i(m, i)*Recall_i(m, i)) / (Precision_i(m, i) + Recall_i(m, i)); } double F1(const conf_m& m) { return 2 * (Precision(m)*Recall(m)) / (Precision(m) + Recall(m)); } void fill_massives() { std::cout << "loading databases" << std::endl; std::cout << "Loading test labels" << std::endl; tiny_dnn::parse_mnist_labels(root_path + path_to_databases + "/t10k-labels.idx1-ubyte", &test_labels); std::cout << "Loading test images" << std::endl; tiny_dnn::parse_mnist_images(root_path + path_to_databases + "/t10k-images.idx3-ubyte", &test_images, -1.0, 1.0, 2, 2); std::cout << "loading done!" << std::endl; } static std::tuple<double, double, double, double> testing( tiny_dnn::network<tiny_dnn::sequential>& nn, tiny_dnn::core::backend_t backend_type, std::vector<tiny_dnn::label_t>& test_labels, std::vector<tiny_dnn::vec_t>& test_images, std::string net_name, std::ofstream& ofstr) { tiny_dnn::result res = nn.test(test_images, test_labels); double prec = Precision(res.confusion_matrix); double rec = Recall(res.confusion_matrix); double f1 = F1(res.confusion_matrix); double acc = (double)res.num_success / res.num_total; std::vector<std::vector<double>> dec_values; ofstr << 1000 * (double)res.num_success / res.num_total << sep << 1000 * prec << sep << 1000 * rec << sep << 1000 * f1 << endl; std::cout << res.num_success << "/" << res.num_total << " " << prec << " " << rec << " " << f1 << std::endl; return std::make_tuple(acc, prec, rec, f1); } static void construct_net(tiny_dnn::network<tiny_dnn::sequential> &nn, tiny_dnn::core::backend_t backend_type) { // connection table [Y.Lecun, 1998 Table.1] #define O true #define X false // clang-format off static const bool tbl[] = { O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O, O, X, X, X, O, O, O, X, X, O, X, O, O, O, X, O, O, O, X, X, O, O, O, O, X, X, O, X, O, O, X, X, O, O, O, X, X, O, O, O, O, X, O, O, X, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O }; // clang-format on #undef O #undef X // construct nets // // C : convolution // S : sub-sampling // F : fully connected // clang-format off using fc = tiny_dnn::layers::fc; using conv = tiny_dnn::layers::conv; using ave_pool = tiny_dnn::layers::ave_pool; using tanh = tiny_dnn::activation::tanh; using tiny_dnn::core::connection_table; using padding = tiny_dnn::padding; nn << conv(32, 32, 5, 1, 6, // C1, 1@32x32-in, 6@28x28-out padding::valid, true, 1, 1, backend_type) << tanh() << ave_pool(28, 28, 6, 2) // S2, 6@28x28-in, 6@14x14-out << tanh() << conv(14, 14, 5, 6, 16, // C3, 6@14x14-in, 16@10x10-out connection_table(tbl, 6, 16), padding::valid, true, 1, 1, backend_type) << tanh() << ave_pool(10, 10, 16, 2) // S4, 16@10x10-in, 16@5x5-out << tanh() << conv(5, 5, 5, 16, 120, // C5, 16@5x5-in, 120@1x1-out padding::valid, true, 1, 1, backend_type) << tanh() << fc(120, 10, true, backend_type) // F6, 120-in, 10-out << tanh(); } const enum cmds { START, BEST, WORST }; const std::map<std::string, int> cmdMap { { "--start", START }, { "--best", BEST }, { "--worst", WORST } }; void start(int argc, int i, char** argv); void best(int argc, int i, char** argv); void worst(int argc, int i, char** argv); void Initialize() { cout << "Initialization..." << endl; string s = ""; ifstream configfile("config.txt"); cout << "reading from config..." << endl; getline(configfile, s); number_of_dots = stoi(s.substr(s.find('=') + 1)); getline(configfile, s); root_path = s.substr(s.find('=') + 1); getline(configfile, s); path_to_models = (s.substr(s.find('=') + 1)); getline(configfile, s); path_to_data = (s.substr(s.find('=') + 1)); getline(configfile, s); path_to_databases = (s.substr(s.find('=') + 1)); getline(configfile, s); number_of_tested = stoi(s.substr(s.find('=') + 1)); cout << "----- starting with these parameters -----" << endl; cout << "number_of_dots = " << number_of_dots << endl; cout << "root_path = " << root_path << endl; cout << "path_to_models = " << path_to_models << endl; cout << "path_to_data = " << path_to_data << endl; cout << "path_to_databases = " << path_to_databases << endl; cout << "number_of_tested = " << number_of_tested << endl; cout << "------------------------------------------" << endl; } int main(int argc, char** argv) { Initialize(); for (int i = 1; i < argc; i++) { string command = ""; command = argv[i]; if (cmdMap.find(command) != cmdMap.end()) { cout << "--------------------" << endl; switch (cmdMap.at(command)) { case START: cout << "invoking 'start' command" << endl; start(argc, i, argv); break; case BEST: cout << "invoking 'best' command" << endl; best(argc, i, argv); break; case WORST: cout << "invoking 'worst-tests' command" << endl; worst(argc, i, argv); break; } } } } void start(int argc, int i, char** argv) { set<string> nns; i++; string cur = ""; while (!(cur[0] == '-' && cur[1] == '-') && i < argc) { cur = argv[i]; try { std::ifstream ifs((root_path + path_to_models + cur).c_str(), std::ios::binary | std::ios::in); if ((ifs.fail() || ifs.bad()) && cur != "all") throw (nn_error("err")); if (cur != "all") nns.insert(cur); if (cur == "all") cout << "going to use all models from root_directory/models_directory" << endl; } catch (nn_error qwe) { cout << "net with name " << cur << " is not found" << endl; } i++; if (i < argc) cur = argv[i]; } if (cur == "all") { for (auto& p : fs::directory_iterator(root_path + path_to_models)) { // cout << p << endl; stringstream tmpstr(ios::in | ios::out); tmpstr << p; string namecur; while (!stream_is_empty(tmpstr)) { string s; tmpstr >> s; namecur += s; } namecur = find_file_name(namecur); nns.insert(namecur); } } if (nns.begin() != nns.end() && test_images.size() == 0) fill_massives(); try { std::cout << "start testing" << std::endl; if (nns.begin() == nns.end()) std::cout << "no nets are opened" << std::endl; std::ofstream general_i; general_i << "name" + sep + "accuracy" + sep + "precision" + sep + "recall" + sep + "f1" << endl; if (nns.begin() != nns.end()) general_i = std::ofstream((root_path + path_to_data + "general_info.csv").c_str()); for (std::set<std::string>::iterator curnet = nns.begin(); curnet != nns.end(); curnet++) { tiny_dnn::network<tiny_dnn::sequential> cur_nn; construct_net(cur_nn, backend_type); cur_nn.load(path_to_models + (*curnet)); std::cout << "currently testing " + (*curnet) << std::endl; std::ofstream ofs((path_to_data + (*curnet) + ".csv").c_str()); ofs << "accuracy;precision;recall;f1" << endl; double macro_av_acc = 0; double macro_av_prec = 0; double macro_av_rec = 0; double macro_av_f1 = 0; for (int i = 0; i < number_of_dots; i++) { std::vector<tiny_dnn::label_t> test_labels_r; std::vector<tiny_dnn::vec_t> test_images_r; for (int cur = 0; cur < number_of_tested; cur++) { int randcur = rand() % test_images.size(); test_labels_r.push_back(test_labels[randcur]); test_images_r.push_back(test_images[randcur]); } try { auto res = testing(cur_nn, backend_type, test_labels_r, test_images_r, (*curnet), ofs); macro_av_acc += get<0>(res); macro_av_prec += get<1>(res); macro_av_rec += get<2>(res); macro_av_f1 += get<3>(res); } catch (tiny_dnn::nn_error &err) { std::cerr << "Exception: " << err.what() << std::endl; } } macro_av_acc /= number_of_dots; macro_av_prec /= number_of_dots; macro_av_rec /= number_of_dots; macro_av_f1 /= number_of_dots; general_i << (*curnet) << sep << macro_av_acc << sep << macro_av_prec << sep << macro_av_rec << sep << macro_av_f1 << endl; ofs.close(); } general_i.close(); std::cout << "stop testing" << std::endl; } catch (std::exception& e) { std::cout << "some error has occured" << std::endl; } catch (tiny_dnn::nn_error& er) { std::cout << "some error has occured" << std::endl; } } void best(int argc, int i, char** argv) { i++; string cur = ""; if (i < argc) { cur = argv[i]; } else return; ptrdiff_t num = 0; try { num = stoi(cur); } catch (std::exception e) { return; } vector<nn_datas> nns; string data_cur; ifstream general_i_stream(root_path + path_to_data + "general_info.csv"); while (!istream_is_empty(general_i_stream)) { getline(general_i_stream, data_cur); string name = data_cur.substr(0, data_cur.find(sep)); data_cur = data_cur.substr(data_cur.find(sep) + 1); double acc = stod(data_cur.substr(0, data_cur.find(sep))); data_cur = data_cur.substr(data_cur.find(sep) + 1); double prec = stod(data_cur.substr(0, data_cur.find(sep))); data_cur = data_cur.substr(data_cur.find(sep) + 1); double rec = stod(data_cur.substr(0, data_cur.find(sep))); data_cur = data_cur.substr(data_cur.find(sep) + 1); double f1 = stod(data_cur.substr(0, data_cur.find(sep))); nns.push_back(make_tuple(name, acc, prec, rec, f1)); } num = min(static_cast<ptrdiff_t>(nns.size()), num); std::ofstream beststr; if (nns.begin() != nns.end()) beststr = std::ofstream((root_path + path_to_data + "best.txt").c_str()); cout << "output of best " << num << " models" << endl; cout << "best by accuracy" << endl; beststr << "output of best " << num << " models" << endl; beststr << "best by accuracy" << endl; sort(nns.begin(), nns.end(), [](nn_datas& lhs, nn_datas& rhs) -> bool { return get<1>(lhs) > get<1>(rhs); }); for (ptrdiff_t i = 0; i < num; ++i) { cout << i + 1 << " " << get<0>(nns[i]) << " " << get<1>(nns[i]) << endl; beststr << i + 1 << " " << get<0>(nns[i]) << " " << get<1>(nns[i]) << endl; } cout << "best by precision" << endl; beststr << "best by precision" << endl; sort(nns.begin(), nns.end(), [](nn_datas& lhs, nn_datas& rhs) -> bool { return get<2>(lhs) > get<2>(rhs); }); for (ptrdiff_t i = 0; i < num; ++i) { cout << i + 1 << " " << get<0>(nns[i]) << " " << get<2>(nns[i]) << endl; beststr << i + 1 << " " << get<0>(nns[i]) << " " << get<2>(nns[i]) << endl; } cout << "best by recall" << endl; beststr << "best by recall" << endl; sort(nns.begin(), nns.end(), [](nn_datas& lhs, nn_datas& rhs) -> bool { return get<3>(lhs) > get<3>(rhs); }); for (ptrdiff_t i = 0; i < num; ++i) { cout << i + 1 << " " << get<0>(nns[i]) << " " << get<3>(nns[i]) << endl; beststr << i + 1 << " " << get<0>(nns[i]) << " " << get<3>(nns[i]) << endl; } cout << "best by f1" << endl; beststr << "best by f1" << endl; sort(nns.begin(), nns.end(), [](nn_datas& lhs, nn_datas& rhs) -> bool { return get<4>(lhs) > get<4>(rhs); }); for (ptrdiff_t i = 0; i < num; ++i) { cout << i + 1 << " " << get<0>(nns[i]) << " " << get<4>(nns[i]) << endl; beststr << i + 1 << " " << get<0>(nns[i]) << " " << get<4>(nns[i]) << endl; } beststr.close(); } void worst(int argc, int i, char** argv) { i++; string cur = ""; if (i < argc) { cur = argv[i]; } else return; ptrdiff_t num = 0; try { num = stoi(cur); } catch (std::exception e) { return; } if (test_labels.size() == 0) fill_massives(); set<string> nns; vector<int> right = (vector<int>(test_labels.size(), 0)); for (auto& p : fs::directory_iterator(root_path + path_to_models)) { // cout << p << endl; stringstream tmpstr(ios::in | ios::out); tmpstr << p; string namecur; while (!stream_is_empty(tmpstr)) { string s; tmpstr >> s; namecur += s; } namecur = find_file_name(namecur); nns.insert(namecur); } num = min(static_cast<ptrdiff_t>(right.size()), num); for (auto curnet = nns.cbegin(); curnet != nns.cend(); curnet++) { tiny_dnn::network<tiny_dnn::sequential> cur_nn; construct_net(cur_nn, backend_type); cur_nn.load(path_to_models + (*curnet)); cout << "currently testing " << *curnet << endl; const ptrdiff_t mass_size = test_labels.size(); for (ptrdiff_t i = 0; i < mass_size; ++i) { auto vec_l = vector<label_t>(1, test_labels[i]); auto vec_i = vector<vec_t>(1, test_images[i]); tiny_dnn::result res = cur_nn.test(vec_i, vec_l); right[i] += res.num_success; if ((i + 1) % 1000 == 0) cout << i + 1 << " tests done!" << endl; } } vector<pair<int, int>> worst; for (ptrdiff_t i = 0; i < right.size(); i++) { worst.push_back(make_pair(i + 1, right[i])); } sort(worst.begin(), worst.end(), [](pair<int, int>& a, pair<int, int>& b) { return a.second < b.second; }); std::ofstream worststr((root_path + path_to_data + "worst-tests.txt").c_str()); int nnsnum = nns.size(); cout << "worst tests" << endl; worststr << "worst tests" << endl; for (ptrdiff_t i = 0; i < num; i++) { cout << worst[i].first << " - " << static_cast<double>(worst[i].second) / nnsnum << "%" << endl; worststr << worst[i].first << " - " << static_cast<double>(worst[i].second) / nnsnum << "%" << endl; } }<file_sep>/priorityqueuel/priorityqueuel_test.cpp #include "priorityqueuel.h" #include <iostream> using namespace std; void out_all(const PriorityQueueL& qu) { PriorityQueueL copy = qu; cout << "full queue now: "; while (!copy.isEmpty()) { cout << copy.top() << " "; copy.pop(); } cout << endl; } void pushandout(PriorityQueueL& qu, const int& n) { qu.push(n); out_all(qu); } void popandout(PriorityQueueL& qu) { qu.pop(); out_all(qu); } int main() { PriorityQueueL qu; try { qu.top(); } catch (runtime_error e) { cout << "I tried to get top from empty Queue but I couldn't" << endl; } pushandout(qu, 2); cout << "top now: " << qu.top() << endl; pushandout(qu, 3); pushandout(qu, 10); cout << "top now: " << qu.top() << endl; pushandout(qu, 4); pushandout(qu, 1); pushandout(qu, 5); popandout(qu); popandout(qu); cout << "--------" << endl; PriorityQueueL qu2 = qu; PriorityQueueL qu3; PriorityQueueL qu4; qu4.push(666); out_all(qu2); qu2 = qu3; pushandout(qu2, 999); qu2 = qu4; out_all(qu2); qu2 = qu; out_all(qu2); qu2 = qu4; out_all(qu2); cout << "qu2 is empty? : " << (qu2.isEmpty() ? "true" : "false") << endl; qu2.clear(); cout << "qu2 is empty? : " << (qu2.isEmpty() ? "true" : "false") << endl; //int qweqweqwe; //cin >> qweqweqwe; }<file_sep>/queuea/queuea.h #ifndef QUEUEA_H #define QUEUEA_H #include <cstddef> class QueueA { public: QueueA() = default; QueueA(const ptrdiff_t& size); QueueA(const QueueA& q); ~QueueA(); QueueA& operator=(QueueA& q); const int& top(); void push(const int& v); void pop(); void clear(); const bool isEmpty() const; void resize(const ptrdiff_t& size); private: int* pArray_ = nullptr; ptrdiff_t size = 0; ptrdiff_t capacity = 0; ptrdiff_t indexHead = 0; ptrdiff_t indexTail = 0; }; #endif // !QUEUEA_H <file_sep>/stacka/stacka_test.cpp #include <iostream>; #include "stacka.h" using namespace std; void out_top(StackA& st) { cout << "top element is " << st.top() << endl; } int main() { StackA st1; st1.resize(2); st1.push(3); out_top(st1); cout << "current logic size: " << st1.size() << endl; cout << "current phys size: " << st1.capacity() << endl; cout << "stack is empty: " << st1.isEmpty() << endl; st1.push(4); out_top(st1); st1.push(5); out_top(st1); st1.pop(); out_top(st1); st1.pop(); st1.pop(); try { out_top(st1); } catch (out_of_range e) { cout << "couldn't get top from empty stack" << endl; } cout << "stack is empty: " << st1.isEmpty() << endl; st1.push(3); cout << endl; cout << "----- copying -----" << endl; StackA st2; st2 = st1; cout << "st2 --------" << endl; out_top(st2); cout << "current logic size: " << st2.size() << endl; cout << "current phys size: " << st2.capacity() << endl; cout << "st1 --------" << endl; out_top(st1); cout << "current logic size: " << st1.size() << endl; cout << "current phys size: " << st1.capacity() << endl; cout << endl; cout << "----- copying operator -----" << endl; StackA st3(st1); cout << "st3 --------" << endl; out_top(st3); cout << "current logic size: " << st3.size() << endl; cout << "current phys size: " << st3.capacity() << endl; cout << "st1 --------" << endl; out_top(st1); cout << "current logic size: " << st1.size() << endl; cout << "current phys size: " << st1.capacity() << endl; //int qweqweqwe; //cin >> qweqweqwe; }<file_sep>/vec3d/vec3d.h #ifndef VEC3D_H #define VEC3D_H #include <iosfwd> struct Vec3d { public: std::istream& Vec3d::readFrom(std::istream& istrm); std::ostream& Vec3d::writeTo(std::ostream& ostrm) const; Vec3d& operator+=(const Vec3d& rhs); Vec3d& operator-=(const Vec3d& rhs); Vec3d& operator*=(const double& rhs); Vec3d& operator/=(const double& rhs); bool operator==(const Vec3d& rhs); bool operator!=(const Vec3d& rhs); Vec3d& operator=(const Vec3d& rhs); double length() const; Vec3d(const double xin, const double yin, const double zin) : x(xin) , y(yin) , z(zin) { } Vec3d(const Vec3d& v) = default; Vec3d() = default; ~Vec3d() = default; public: double x = 0.0; double y = 0.0; double z = 0.0; static const char leftBrace = '{'; static const char rightBrace = '}'; static const char dotcomma = ';'; }; Vec3d operator-(const Vec3d& rhs); Vec3d operator+(const Vec3d& lhs, const Vec3d& rhs); Vec3d operator-(const Vec3d& lhs, const Vec3d& rhs); Vec3d operator*(const Vec3d& lhs, const double& rhs); Vec3d operator/(const Vec3d& lhs, const double& rhs); Vec3d operator*(const double& lhs, const Vec3d& rhs); std::istream& operator>>(std::istream& istrm, Vec3d& rhs); std::ostream& operator<<(std::ostream& ostrm, const Vec3d& rhs); double dotProduct(const Vec3d& lhs, const Vec3d& rhs); Vec3d crossProduct(const Vec3d& lhs, const Vec3d& rhs); #endif // VEC3D_H<file_sep>/rational/rational.h #ifndef RATIONAL_H #define RATIONAL_H #include <iosfwd> class Rational { private: static const char slash{ '/' }; static const char doubledot{ ':' }; int num{ 0 }; int denum{ -1 }; public: Rational() {} Rational(const Rational& rat) :num (rat.num) ,denum (rat.denum) { }; ~Rational() = default; explicit Rational(const int num); Rational(const int num, const int denum); bool operator==(const Rational& rhs); bool operator==(const int& rhs); bool operator!=(const Rational& rhs); bool operator!=(const int& rhs); bool operator>(const Rational& lhs); bool operator<(const Rational& rhs); bool operator>(const int rhs); bool operator<(const int rhs); bool operator<=(const Rational rhs); bool operator>=(const Rational rhs); Rational& operator+=(const Rational& lhs); Rational& operator+=(const int lhs); Rational& operator-=(const Rational& lhs); Rational& operator-=(const int lhs); Rational& operator*=(const Rational& lhs); Rational& operator*=(const int lhs); Rational& operator/=(const Rational& lhs); Rational& operator/=(const int lhs); void normalizeWith(Rational& b); std::ostream& writeTo(std::ostream& ostrm) const; std::istream& readFrom(std::istream& istrm); }; Rational operator+ (const Rational& lhs, const Rational& rhs); Rational operator- (const Rational& lhs, const Rational& rhs); Rational operator* (const Rational& lhs, const Rational& rhs); Rational operator/ (const Rational& lhs, const Rational& rhs); Rational operator+ (const Rational& lhs, const int& rhs); Rational operator- (const Rational& lhs, const int& rhs); Rational operator* (const Rational& lhs, const int& rhs); Rational operator/ (const Rational& lhs, const int& rhs); Rational operator+ (const int& lhs, const Rational& rhs); Rational operator- (const int& lhs, const Rational& rhs); Rational operator* (const int& lhs, const Rational& rhs); Rational operator/ (const int& lhs, const Rational& rhs); Rational operator-(const Rational& rhs); std::ostream& operator<<(std::ostream& ostrm, const Rational& rhs); std::istream& operator>>(std::istream& istrm, Rational& rhs); void RationalBasicTest(std::ostream& ostrm, const Rational& lhs, const Rational& rhs); void RationalBasicTest(std::ostream& ostrm, const Rational& lhs, const int& rhs); #endif // !COMPLEX_H <file_sep>/Interval1d/interval1d_test.cpp #include <iostream> #include "Interval1d.h" using namespace std; int main() { Interval1d i1(); Interval1d i2(true, 2, 4, false); Interval1d i3(i2); Interval1d i4(true, 5, 7, false); Interval1d i5(false, 2, 4, false); cout << i2 << endl << i3 << endl; cout << i2.length() << endl; cout << i3.isIntersepting(i2) << endl; cout << i4 << endl << i5 << endl; //cout << "interseption " << i5.interseptionWith(i4); int qwe; cin >> qwe; return 0; }<file_sep>/array/array_test.cpp #include "array.h" #include <iostream> #include <sstream> #include <cstddef> void writeArray(Array& arr, string name) { cout << "array " << name << " ==> "; for (int i = 0; i < arr.size(); i++) { cout << arr[i] << " "; } cout << endl; } int main() { Array abc(); //writeArray(abc, "abc"); Array b(5); b[0] = 1; b[1] = 2; b[2] = 6; b[3] = 2; b[4] = 5; Array c(b); Array d(c); Array e(0); try { e.erase(1234); } catch (length_error e) { cout << "I've tried to erase from empty array but I couldn't!" << endl; } e = c; try { b[5] = 3; } catch (out_of_range e) { cout << "I've tried to set element with index out of range to something but I couldn't!" << endl; } writeArray(b, "b"); writeArray(c, "c, copy of b"); writeArray(e, "e = c"); e.insert(4, 1541); try { e.insert(-1, 2); } catch (invalid_argument e) {cout << "I've tried to insert into negative index but I couldn't!" << endl;} try { e.insert(6, 2); } catch (out_of_range e) {cout << "I've tried to insert into index out of range but I couldn't!" << endl;} writeArray(e, "e after insertion"); try { e.erase(-1); } catch (invalid_argument e) { cout << "I've tried to erase from negative index but I couldn't!" << endl; } try { e.erase(1234); } catch (out_of_range e) { cout << "I've tried to erase index out of range but I couldn't!" << endl; } e.erase(4); writeArray(e, "e after erasing"); e.resize(7); cout << "array e after resizing: size = " << e.size() << "; capacity = " << e.capacity() << endl; writeArray(e, "e"); e.resize(3); writeArray(e, "e after another resizing"); try { e.resize(-1); } catch (invalid_argument e) {cout << "I've tried to set size to negative but I couldn't!" << endl;} b.push_back(123); writeArray(b, "b"); b.pop_back(); writeArray(b, "b"); }<file_sep>/array/array.cpp #include "array.h" #include <stdexcept> #include <iostream> Array::~Array(){ delete[] pData_; pData_ = nullptr; } Array::Array(const int& sz) { if (sz < 0) { throw (invalid_argument("You cannot simply set array size to negative!")); } physSize_ = sz; logicSize_ = sz; if (sz != 0) { pData_ = (new int[logicSize_]); } } Array::Array(const Array& arr) : physSize_ (arr.physSize_) , logicSize_(arr.logicSize_) { pData_ = new int[physSize_]; for (int i = 0; i < logicSize_; i++) { *(pData_ + i) = *(arr.pData_ + i); } } int& Array::operator[](const ptrdiff_t i) { if (i >= logicSize_) { throw (out_of_range ("Index is out of range!")); } return *(pData_ + i); } const int& Array::operator[](const ptrdiff_t i) const { if (i >= logicSize_) { throw (out_of_range("Index is out of range!")); } return *(pData_ + i); }; ptrdiff_t Array::size() const { return this->logicSize_; } ptrdiff_t Array::capacity() const { return physSize_; } Array& Array::operator=(const Array& obj) { if (this != &obj) { this->swapWith(Array(obj)); } return *this; } void Array::swapWith(Array& rhs) { swap(physSize_, rhs.physSize_); swap(logicSize_, rhs.logicSize_); swap(pData_, rhs.pData_); } void Array::resize(const ptrdiff_t& newCap) { if (newCap < 0) { throw (invalid_argument("You cannot simply set new array capacity to negative!")); } Array tmp(newCap); tmp.logicSize_ = newCap < this->logicSize_ ? newCap : this->logicSize_; for (int i = 0; i < tmp.logicSize_; i++) { *(tmp.pData_ + i) = *(pData_ + i); } if (logicSize_ == 0) { pData_ = nullptr; } this->swapWith(tmp); }; void Array::insert(ptrdiff_t i, int data) { if (i < 0) { throw (invalid_argument("You cannot simply insert into element with negative index!")); } if (i >= logicSize_) { throw (out_of_range("You cannot simply insert into element with index that is more than array size!")); } if (logicSize_ == physSize_) { this->resize(physSize_ + 1); } logicSize_++; for (int index = i+1; index < logicSize_; index++) { *(pData_ + index) = *(pData_ + index - 1); } *(pData_ + i) = data; //return *this; } void Array::erase(ptrdiff_t i) { if (logicSize_ == 0) { throw (length_error("You cannot erase from empty array!")); } if (i < 0) { throw (invalid_argument("You cannot simply erase negative element!")); } if (i >= logicSize_) { throw (out_of_range("You cannot simply erase element with index that is more than array size!")); } for (int index = i; index < logicSize_ - 1; index++) { *(pData_ + index) = *(pData_ + index + 1); } logicSize_--; if (logicSize_ == 0) { pData_ = nullptr; } //return *this; } void Array::push_back(const int num) { if (logicSize_ == physSize_) { this->resize(physSize_ + 1); } logicSize_++; this->insert(logicSize_ - 1, num); if (logicSize_ == physSize_) { this->resize(physSize_ - 1); } //return *this; } void Array::pop_back() { this->erase(logicSize_ - 1); //return *this; } Array::Array() :physSize_{ 0 } , logicSize_{ 0 } , pData_{ nullptr } { }<file_sep>/queuea/queuea.cpp #include "queuea.h" #include <algorithm> using namespace std; QueueA::~QueueA() { delete[] pArray_; } QueueA::QueueA(const ptrdiff_t& size) { if (size != capacity) { pArray_ = new int[size]; capacity = size; } } void QueueA::clear() { size = 0; indexHead = 0; indexTail = 0; } void QueueA::push(const int& v) { if (size == capacity) { resize(capacity + 1); } if (indexTail == capacity - 1) { indexTail = 0; *pArray_ = v; size++; } else { indexTail++; *(pArray_ + indexTail) = v; size++; } } void QueueA::resize(const ptrdiff_t& size) { QueueA tmp; tmp.pArray_ = new int[size]; if (this->size != 0) { if (indexHead <= indexTail) { for (ptrdiff_t i = indexHead; i < indexHead + size; i++) { *(tmp.pArray_ + i) = *(this->pArray_ + i); } } else { for (ptrdiff_t i = indexHead; i < capacity; i++) { } } } swap(this->pArray_, tmp.pArray_); swap(this->indexHead, tmp.indexHead); swap(this->indexTail, tmp.indexTail); } const int& QueueA::top() { return *(pArray_ + indexHead); } const bool QueueA::isEmpty() const { return !(bool)(this->size); }<file_sep>/vec3dT/vec3dT_test.cpp #include <iostream> #include <sstream> #include "vec3dT.h" using namespace std; template<typename T> void VOUT(Vec3dT<T>& lhs); template <typename T> void VoperOUT(Vec3dT<T>& lhs, const string oper, Vec3dT<T>& rhs); template <typename T> void VoperOUT(Vec3dT<T>& lhs, const string oper, double& rhs); int main() { double a = 4.0; Vec3dT<string> v4 ("a","b","c"); Vec3dT<string> v3("b","a","c"); Vec3dT<double> v(2.1, 2.2, 2.3); Vec3dT<double> v1(2.10000001, 2.2, 2.3); Vec3dT<double> v2(); VoperOUT(v, "+", v1); VOUT(v1 + v); cout << endl; VoperOUT(v, "-", v1); VOUT(v1 - v); cout << endl; VoperOUT(v, "*", a); VOUT(v1 * a); cout << endl; VoperOUT(v, "/", a); VOUT(v1 / a); cout << endl; VoperOUT(v, "==", v1); cout << (v == v1); cout << endl; VoperOUT(v, "!=", v1); cout << (v != v1); cout << endl; VoperOUT(v3, "==", v4); cout << (v3 == v4); cout << endl; VoperOUT(v3, "!=", v4); cout << (v3 != v4); cout << endl; cout << "length of "; VOUT(v); cout << " is " << v.length() << endl; cout << "dot product of "; VOUT(v); cout << " and "; VOUT(v1); cout << " is " << dotProduct(v, v1) << endl; cout << "cross product of "; VOUT(v); cout << " and "; VOUT(v1); cout << " is "; VOUT(crossProduct(v, v1)); cout << endl; //cin >> a; return 0; } template <typename T> void VOUT(Vec3dT<T>& lhs) { cout << "{ " << lhs.x << "; " << lhs.y << "; " << lhs.z << " }"; } template <typename T> void VoperOUT(Vec3dT<T>& lhs, const string oper, Vec3dT<T>& rhs) { VOUT(lhs); cout << " " << oper << " "; VOUT(rhs); cout << " = "; } template <typename T> void VoperOUT(Vec3dT<T>& lhs, const string oper, double& rhs) { VOUT(lhs); cout << " " << oper << " "; cout << (rhs); cout << " = "; }<file_sep>/complex/complex_test.cpp #include "complex.h" #include <iostream> int main() { using namespace std; Complex z; Complex v; double h(3.5); cout << "{1.0 , 2.3} + {0.75 , -0.7} = " << Complex(1.0, 2.3) + Complex(0.75, -0.7) << endl; cout << "{1.0 , 2.3} - {0.0 , -0.7} = " << Complex(1.0, 2.3) - Complex(0.0, -0.7) << endl; cout << "{1.0 , 2.3} * {3.0 , 2.1} = " << Complex(1.0, 2.3) * Complex(3.0, 2.1) << endl; cout << "{1.0 , 2.3} / {3.1 , 1.0} = " << Complex(1.0, 2.3) + Complex(3.1, 1.0) << endl; cout << "Epsilon for doubles in this case is 0.00001" << endl; cout << "{1.0 , 1.0} == {1.000009 , 1.0} <=> " << ((Complex(1.0, 1.0) == Complex(1.000009, 1.0)) ? "true" : "false") << endl; cout << "{1.0 , 1.0} == {1.00001 , 1.0} <=> " << ((Complex(1.0, 1.0) == Complex(1.00001, 1.0)) ? "true" : "false") << endl; cout << "{1.0 , 1.0} != {1.000009 , 1.0} <=> " << ((Complex(1.0, 1.0) != Complex(1.000009, 1.0)) ? "true" : "false") << endl; cout << "{1.0 , 1.0} != {1.00001 , 1.0} <=> " << ((Complex(1.0, 1.0) != Complex(1.00001, 1.0)) ? "true" : "false") << endl; cout << "Input first complex number" << endl; cin >> v; cout << "Input second complex number" << endl; cin >> z; cout << v << " + " << z << " = " << v + z << endl; cout << v << " - " << z << " = " << v - z << endl; cout << v << " * " << z << " = " << v * z << endl; cout << v << " / " << z << " = " << v / z << endl; cout << v << " + " << h << " = " << v + h << endl; cout << v << " - " << h << " = " << v - h << endl; cout << v << " * " << h << " = " << v * h << endl; cout << v << " / " << h << " = " << v / h << endl; testParse("{8.9,9 }"); testParse("{8.9, 9}"); testParse("{ 8.9,9}"); testParse("{ 8.9,9"); int j(0); cin >> j; return 0; } <file_sep>/string_matrix/string_matrix.h #ifndef STRING_MATRIX_H #define STRING_MATRIX_H #include <cstddef> #include <string> class String_Matrix { public: String_Matrix() = default; String_Matrix(const ptrdiff_t& l, const ptrdiff_t& w); String_Matrix(const String_Matrix& m); ~String_Matrix(); String_Matrix& operator=(const String_Matrix& m); private: ptrdiff_t length_; ptrdiff_t weigth_; std::string* pArray_; }; #endif<file_sep>/Interval1d/interval1d.h #ifndef INTERVAL1D_H #define INTERVAL1D_H #include <sstream> #include<iostream>; class Interval1d { public: Interval1d() = default; ~Interval1d() = default; Interval1d(const Interval1d& i); Interval1d(const bool& ileftBraceisRound, const double& ileft, const double& iright, const bool& irightBraceisRound); std::ostream& writeTo(std::ostream& ostrm) const; //std::istream& readFrom(std::istream& istrm); double length(); bool isIntersepting(const Interval1d& i); Interval1d interseptionWith(Interval1d& i); private: bool leftBraceisRound = 0; double left = 0.0; double right = 0.0; bool rightBraceisRound = 0; bool isNull = false; const char dotcomma = ';'; }; std::ostream& operator<<(std::ostream& ostrm, Interval1d& i); #endif<file_sep>/Interval1d/interval1d.cpp #include "interval1d.h" Interval1d::Interval1d(const bool& ileftBraceisRound, const double& ileft, const double& iright, const bool& irightBraceisRound) : leftBraceisRound{ ileftBraceisRound } , left{ ileft } , right{ iright } , rightBraceisRound{ irightBraceisRound } { this->isNull = (left == right) && (leftBraceisRound || rightBraceisRound); } Interval1d::Interval1d(const Interval1d& i) : leftBraceisRound {i.leftBraceisRound} , left{ i.left } , right{ i.right } , rightBraceisRound{ i.rightBraceisRound } { this->isNull = (left == right) && (leftBraceisRound || rightBraceisRound); } double Interval1d::length() { return (right - left); } bool Interval1d::isIntersepting(const Interval1d& i) { if ((right < i.left) || (i.right < left)) { return false; } if (((right == i.left) && (rightBraceisRound || i.leftBraceisRound)) || ((i.right == left) && (i.rightBraceisRound || leftBraceisRound))) { return false; } return true; } std::ostream& Interval1d::writeTo(std::ostream& ostrm) const { if (isNull) { ostrm << "null"; } else { ostrm << (leftBraceisRound ? "(" : "[") << " "; ostrm << left << dotcomma << " " << right; ostrm << (rightBraceisRound ? ")" : "]") << " "; } return ostrm; }; std::ostream& operator<<(std::ostream& ostrm, Interval1d& i) { return (i.writeTo(ostrm)); }; /* Interval1d Interval1d::interseptionWith(Interval1d& i) { if (left < i.right) { return Interval1d(leftBraceisRound, left, i.right, i.rightBraceisRound); } if (i.left < right) { return Interval1d(i.leftBraceisRound, i.left, right, rightBraceisRound); } return Interval1d(true, 0, 0, true); // null interval; } */ /* std::istream& Interval1d::readFrom(std::istream& istrm) { }; */ //subinterval //interseptionwith //concatenation
f858f850b22f850e41ba5e70db42333298748ea7
[ "C++" ]
34
C++
GhostKicker/fadeev_a_u
601c6bf68eb3ce99b6d153735d916e2939c083ec
91ee5d8c8e85bd798c5c9486e255f0410c3059d1
refs/heads/master
<file_sep>from flask_wtf import Form from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import Required, Length, Email, Regexp, EqualTo from wtforms import ValidationError from ..models import User class LoginForm(Form): email = StringField('Email', validators=[Required(), Length(1,64), Email()]) password = PasswordField('<PASSWORD>', validators=[Required()]) remember_me = BooleanField('keep me logged in') submit = SubmitField('Log in') class RegistrationForm(Form): email = StringField('Email', validators=[Required(), Length(1,64), Email()]) username = StringField('Username', validators=[ Required(), Length(1,64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$',0,'Username must have only letters, numbers, dots, or underscores')]) password = PasswordField('<PASSWORD>', validators=[Required(), EqualTo('<PASSWORD>',message='Passwords must match')]) password2 = PasswordField('Confirm Password', validators=[Required()]) submit = SubmitField('Register') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Email already registed.') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Username already in use.') class ChangePasswordForm(Form): old_password = PasswordField('Your Old <PASSWORD>', validators=[Required()]) password = PasswordField('<PASSWORD>', validators=[Required(), EqualTo('<PASSWORD>',message='Passwords must match')]) password2 = PasswordField('<PASSWORD>', validators=[Required()]) submit = SubmitField('Change Password') class ForgetPasswordForm(Form): email = StringField('Email', validators=[Required(), Length(1,64), Email()]) submit = SubmitField('Submit') class PasswordOnlyForm(Form): password=PasswordField('New Password', validators=[Required(), EqualTo('password2',message='Passwords must match')]) password2=PasswordField('Confirm Password', validators=[Required()]) submit=SubmitField('Submit')<file_sep>import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = 'a complex string' SQLALCHEMY_COMMIT_ON_TEARDOWN = True FLASK_MAIL_SUBJECT_PREFIX = '[From Admin]' FLASK_MAIL_SENDER = '<EMAIL>' FLASK_ADMIN = 'titian' @staticmethod def init_app(app): pass class DevelopmentConfig(Config): DEBUG = True MAIL_SERVER = 'smtp.126.com' MAIL_PORT = 25 MAIL_USE_TLS = True MAIL_USERNAME = os.environ.get('MAIL_USERNAME') MAIL_PASSWORD = <PASSWORD>('MAIL_PASSWORD') SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URI') or \ 'sqlite:///'+os.path.join(basedir, 'data-dev.sqlite') class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URI') or \ 'sqlite:///'+os.path.join(basedir, 'data-test.sqlite') class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URI') or \ 'sqlite:///'+os.path.join(basedir, 'data.sqlite') @classmethod def init_app(cls, app): import logging from logging.handlers import SMTPHandler credentials = None secure =None if getattr(cls, 'MAIL_USERNAME', None) is not None: credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD) if getattr(cls, 'MAIL_USE_TLS', None): secure = () mail_handler = SMTPHandler( mailhost = (cls.MAIL_SERVER, cls,MAIL_PORT), fromaddr = cls.FLASK_MAIL_SENDER, toaddrs = [cls.FLASK_ADMIN], subjects = cls.FLASK_MAIL_SUBJECT_PREFIX + ' Application Error', credentials = credentials, secure = secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) config = { 'development':DevelopmentConfig, 'testing':TestingConfig, 'production':ProductionConfig, 'default':DevelopmentConfig } <file_sep># titian My Real First <file_sep>from flask import render_template from flask_mail import Message from . import mail from manage import app def send_email(to, subject, template, **kwargs): msg=Message(app.config['FLASK_MAIL_SUBJECT_PREFIX']+subject, sender=app.config['FLASK_MAIL_SENDER'], recipients=[to]) msg.body=render_template(template + '.txt',**kwargs) mail.send(msg)<file_sep>from datetime import datetime from flask import render_template,session,redirect,url_for, flash, abort, request from flask_login import login_required, current_user from . import main from .. import db from ..models import User, Permission, Post, Comment, Role from .forms import PostForm, EditProfileForm, EditProfileAdminForm, CommentForm from ..decorators import admin_required, permission_required @main.route('/', methods=['GET', 'POST']) def index(): form=PostForm() if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit(): post = Post(body=form.body.data, author=current_user._get_current_object()) db.session.add(post) return redirect(url_for('.index')) page = request.args.get('page', 1, type=int) pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page) posts = pagination.items return render_template('index.html', form=form, posts=posts, pagination=pagination) @main.route('/user/<username>') def user(username): user = User.query.filter_by(username=username).first() if user is None: abort(404) page = request.args.get('page',1,type=int) pagination = user.posts.order_by(Post.timestamp.desc()).paginate(page) posts = pagination.items return render_template('user.html', user=user, posts=posts, pagination=pagination) @main.route('/post/<int:id>',methods=['GET', 'POST']) def post(id): post = Post.query.get_or_404(id) form = CommentForm() if form.validate_on_submit(): comment = Comment(body=form.body.data, post=post, author=current_user._get_current_object()) db.session.add(comment) flash('Your comment has been sent') return redirect(url_for('.post', id=post.id, page=-1)) page = request.args.get('page', 1, type=int) if page==-1: page = (post.comments.count() - 1) / 20 + 1 pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(page, per_page=20, error_out=False) comments = pagination.items return render_template('post.html', posts=[post], form=form, comments=comments, pagination=pagination) @main.route('/edit-profile', methods=['GET', 'POST']) @login_required def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name=form.name.data current_user.location=form.location.data current_user.about_me=form.about_me.data db.session.add(current_user) flash('Your profile has been updated.') return redirect(url_for('.user', username=current_user.username)) form.name.data=current_user.name form.location.data=current_user.location form.about_me.data=current_user.about_me return render_template('edit_profile.html', form=form) @main.route('/edit-profile/<int:id>',methods=['GET', 'POST']) @login_required @admin_required def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash('The profile has been changed.') return redirect(url_for('.user',username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data =user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user) @main.route('/edit/<int:id>',methods=['GET','POST']) @login_required def edit(id): post = Post.query.get_or_404(id) if current_user != post.author and not current_user.can(Permission.ADMINISTER): abort(403) form = PostForm() if form.validate_on_submit(): post.body = form.body.data db.session.add(post) flash('The post has been updated.') return redirect(url_for('.post', id=post.id)) form.body.data = post.body return render_template('edit_post.html', form=form) @main.route('/moderate') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(): page = request.args.get('page', 1, type=int) pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate(page) comments = pagination.items return render_template('moderate.html', comments=comments, pagination=pagination, page=page) @main.route('/moderate/enable/<int:id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate_enable(id): comment = Comment.query.get_or_404(id) comment.disabled = False db.session.add(comment) return redirect(url_for('.moderate', page=request.args.get('page', 1, type=int))) @main.route('/moderate/disable/<int:id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate_disable(id): comment = Comment.query.get_or_404(id) comment.disabled = True db.session.add(comment) return redirect(url_for('.moderate', page=request.args.get('page', 1, type=int))) @main.route('/delete/<int:id>') @login_required def delete(id): post = Post.query.get_or_404(id) if current_user.is_administrator or current_user == post.author: db.session.delete(post) flash('The post has been deleted.') return redirect(url_for('.index')) abort(403)
de7533fd37716e551a4f1325031b7786afc7cb75
[ "Markdown", "Python" ]
5
Python
lostitian/titian
1ba7f8ee840ff6e695b5933637df384928f06d0b
7660ef9390efce1dee5d08ddb78c92100aa02ff2
refs/heads/master
<repo_name>rackerlabs/ip_associations_python_novaclient_ext<file_sep>/README.rst ===================================== ip_associations_python_novaclient_ext ===================================== Adds IP association extension support to python-novaclient. Install ======= :: pip install ip_associations_python_novaclient_ext Usage ===== This extension is autodiscovered once installed. :: nova ip-association Show an IP association nova ip-association-create Create an IP association nova ip-association-delete Delete an IP association nova ip-association-list List IP associations nova ip-association-show Show an IP association <file_sep>/ip_associations_python_novaclient_ext.py # Copyright 2015 Rackspace Hosting Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file 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. from novaclient import base, utils from novaclient import utils class IPAssociation(base.Resource): def delete(self): self.manager.delete(ip_association=self) class IPAssociationManager(base.ManagerWithFind): resource_class = base.Resource def list(self, server): return self._list('/servers/%s/ip_associations' % base.getid(server), 'ip_associations') def get(self, server, ip_association): return self._get('/servers/%s/ip_associations/%s' % ( base.getid(server), base.getid(ip_association)), 'ip_association') def delete(self, server, ip_association): self._delete('/servers/%s/ip_associations/%s' % ( base.getid(server), base.getid(ip_association))) def create(self, server, ip_association): body = {'ip_association': {}} # idempotent PUT response = self._update( '/servers/%s/ip_associations/%s' % ( base.getid(server), base.getid(ip_association)), body, 'ip_association') return response @utils.arg('instance_id', metavar='<instance_id>', help='ID of instance') @utils.arg('ip_association_id', metavar='<ip_association_id>', help='ID of IP association') def do_ip_association(cs, args): """ Show an IP association """ ip_association = cs.ip_associations_python_novaclient_ext.get( args.instance_id, args.ip_association_id) utils.print_dict(ip_association._info) do_ip_association_show = do_ip_association @utils.arg('instance_id', metavar='<instance_id>', help='ID of instance') def do_ip_association_list(cs, args): """ List IP associations """ ip_associations = cs.ip_associations_python_novaclient_ext.list( args.instance_id) utils.print_list(ip_associations, ['ID', 'Address']) @utils.arg('instance_id', metavar='<instance_id>', help='ID of instance') @utils.arg('ip_association_id', metavar='<ip_association_id>', help='ID of IP association') def do_ip_association_create(cs, args): """ Create an IP association """ ip_association = cs.ip_associations_python_novaclient_ext.create( args.instance_id, args.ip_association_id) utils.print_dict(ip_association._info) @utils.arg('instance_id', metavar='<instance_id>', help='ID of instance') @utils.arg('ip_association_id', metavar='<ip_association_id>', help='ID of IP association') def do_ip_association_delete(cs, args): """ Delete an IP association """ cs.ip_associations_python_novaclient_ext.delete( args.instance_id, args.ip_association_id)
352d7e60eea45c813c02f755fba23a37cad97faa
[ "Python", "reStructuredText" ]
2
reStructuredText
rackerlabs/ip_associations_python_novaclient_ext
800a79442e5c49543f51fa7c19df07a2318d336c
564d2371044691e61ed7d8f7d8ac3ff99fd1a42f
refs/heads/master
<file_sep><?php namespace Monolith\Bundle\CMSGeneratorBundle\Command; use Monolith\Bundle\CMSBundle\Entity\Language; use Monolith\Bundle\CMSBundle\Entity\Site; use Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\Question; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\Process; class InstallCommand extends ContainerAwareCommand { /** * @see Command */ protected function configure() { $this ->setDescription('Monolith CMS clean installer') ->setName('cms:install') ->addOption('sitename', 's', InputOption::VALUE_OPTIONAL, 'Site name [My]') ->addOption('username', 'u', InputOption::VALUE_OPTIONAL, 'Username [root]') ->addOption('email', null, InputOption::VALUE_OPTIONAL, 'Email [root@world.com]') ->addOption('password',null, InputOption::VALUE_OPTIONAL, 'Password [123]') ; } /** * @see Command * * @throws \InvalidArgumentException When namespace doesn't end with Bundle * @throws \RuntimeException When bundle can't be executed */ protected function execute(InputInterface $input, OutputInterface $output) { $appDir = realpath($this->getContainer()->get('kernel')->getRootDir()); $binDir = 'bin'; $finder = (new Finder())->directories()->depth('== 0')->name('*SiteBundle')->name('SiteBundle')->in($appDir.'/../src'); if ($finder->count() == 0) { $dialog = $this->getQuestionHelper(); $filesystem = new Filesystem(); if (!$input->getOption('no-interaction')) { $output->writeln('<error>Installing Monolith CMS. This prosess purge all database tables.</error>'); $confirm = $dialog->ask($input, $output, new Question('<comment>Are you shure?</comment> [y,N]: ', 'n')); if (strtolower($confirm) !== 'y') { $output->writeln('<info>Abort.</info>'); return false; } } $sitename = $input->getOption('sitename'); $username = $input->getOption('username'); $email = $input->getOption('email'); $password = $input->getOption('password'); if (empty($sitename)) { $sitename = $dialog->ask($input, $output, new Question('<comment>Site name</comment> [My]: ', 'My')); } if (empty($username)) { $username = $dialog->ask($input, $output, new Question('<comment>Username</comment> [root]: ', 'root')); } if (empty($email)) { $email = $dialog->ask($input, $output, new Question('<comment>Email</comment> [<EMAIL>]: ', '<EMAIL>')); } if (empty($password)) { $password = $dialog->ask($input, $output, new Question('<comment>Password</comment> [123]: ', '123')); } static::executeCommand($output, $binDir, 'doctrine:schema:drop --force'); static::executeCommand($output, $binDir, 'cms:generate:sitebundle --name='.$sitename); $filesystem->remove('app/config/install.yml'); $process = new Process('bash bin/warmup_cache'); // clear_cache $process->run(function ($type, $buffer) { /* if (Process::ERR === $type) { echo 'ERR > '.$buffer; } else { echo $buffer; } */ }); static::executeCommand($output, $binDir, 'doctrine:schema:update --force --complete --env=prod'); $output->writeln('<comment>Create super admin user:</comment>'); static::executeCommand($output, $binDir, "fos:user:create --super-admin $username $email $password"); // Создание языка, домена и сайта в БД. /** @var \Doctrine\ORM\EntityManager $em */ $em = $this->getContainer()->get('doctrine.orm.entity_manager'); //$user = $em->getRepository('SiteBundle:User')->findOneBy(['username' => $username]); $user = $this->getContainer()->get('cms.context')->getUserManager()->findUserBy(['username' => $username]); $locale = $this->getContainer()->getParameter('locale'); $language = $em->getRepository('CMSBundle:Language')->findOneBy(['code' => $locale]); if (empty($language)) { $language = new Language(); $language ->setCode($locale) ->setName(mb_strtoupper($locale)) ->setUser($user) ; $em->persist($language); $em->flush($language); } $site = $em->getRepository('CMSBundle:Site')->findOneBy([]); if (empty($site)) { $site = new Site($sitename); $site ->setLanguage($language) ->setTheme('default') ; $em->persist($site); $em->flush($site); } $skeletonComposerJson = 'vendor/monolith-software/cms-generator-bundle/Resources/composer.json'; if (!file_exists($skeletonComposerJson)) { $skeletonComposerJson = 'src/Monolith/Bundle/CMSGeneratorBundle/Resources/composer.json'; } $process = new Process("cp $skeletonComposerJson composer.json"); $process->mustRun(); } return null; } protected function getQuestionHelper() { $question = $this->getHelperSet()->get('question'); if (!$question || get_class($question) !== 'Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper') { $this->getHelperSet()->set($question = new QuestionHelper()); } return $question; } protected static function executeCommand(OutputInterface $output, $consoleDir, $cmd, $timeout = 300) { $php = escapeshellarg(static::getPhp(false)); $phpArgs = implode(' ', array_map('escapeshellarg', static::getPhpArguments())); $console = escapeshellarg($consoleDir.'/console'); $console .= ' --ansi'; $process = new Process($php.($phpArgs ? ' '.$phpArgs : '').' '.$console.' '.$cmd, null, null, null, $timeout); $process->run(function ($type, $buffer) use ($output) { $output->write($buffer); }); if (!$process->isSuccessful()) { throw new \RuntimeException(sprintf("An error occurred when executing the \"%s\" command:\n\n%s\n\n%s.", escapeshellarg($cmd), $process->getOutput(), $process->getErrorOutput())); } } protected static function getPhp($includeArgs = true) { $phpFinder = new PhpExecutableFinder(); if (!$phpPath = $phpFinder->find($includeArgs)) { throw new \RuntimeException('The php executable could not be found, add it to your PATH environment variable and try again'); } return $phpPath; } protected static function getPhpArguments() { $arguments = array(); $phpFinder = new PhpExecutableFinder(); if (method_exists($phpFinder, 'findArguments')) { $arguments = $phpFinder->findArguments(); } if (false !== $ini = php_ini_loaded_file()) { $arguments[] = '--php-ini='.$ini; } return $arguments; } } <file_sep><?php namespace Monolith\Bundle\CMSGeneratorBundle\Generator; use Sensio\Bundle\GeneratorBundle\Generator\Generator; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\DependencyInjection\Container; class ModuleGenerator extends Generator { private $filesystem; public function __construct(Filesystem $filesystem) { $this->filesystem = $filesystem; } public function generate($namespace, $bundle, $dir, $format) { $dir .= '/'.strtr($namespace, '\\', '/'); if (file_exists($dir)) { if (!is_dir($dir)) { throw new \RuntimeException(sprintf('Unable to generate the module as the target directory "%s" exists but is a file.', realpath($dir))); } $files = scandir($dir); if ($files != array('.', '..')) { throw new \RuntimeException(sprintf('Unable to generate the module as the target directory "%s" is not empty.', realpath($dir))); } if (!is_writable($dir)) { throw new \RuntimeException(sprintf('Unable to generate the module as the target directory "%s" is not writable.', realpath($dir))); } } $basename = substr($bundle, 0, -6); $parameters = array( 'namespace' => $namespace, 'bundle' => $bundle, 'format' => $format, 'bundle_basename' => $basename, 'bundle_basename_camelize' => Container::camelize($basename), 'extension_alias' => Container::underscore($basename), ); $this->renderFile('module/Bundle.php.twig', $dir.'/'.$bundle.'.php', $parameters); $this->renderFile('module/Controller.php.twig', $dir.'/Controller/'.Container::camelize($basename).'Controller.php', $parameters); $this->renderFile('module/ControllerAdmin.php.twig', $dir.'/Controller/Admin'.Container::camelize($basename).'Controller.php', $parameters); $this->renderFile('module/NodePropertiesFormType.php.twig', $dir.'/Form/Type/NodePropertiesFormType.php', $parameters); $this->renderFile('module/default.html.twig.twig', $dir.'/Resources/views/default.html.twig', $parameters); $this->renderFile('module/index_admin.html.twig.twig', $dir.'/Resources/views/Admin/index.html.twig', $parameters); $this->renderFile('module/routing.'.$format.'.twig', $dir.'/Resources/config/routing.'.$format, $parameters); $this->renderFile('module/routing_admin.'.$format.'.twig', $dir.'/Resources/config/routing_admin.'.$format, $parameters); $this->renderFile('module/routing_api.'.$format.'.twig', $dir.'/Resources/config/routing_api.'.$format, $parameters); $this->renderFile('module/services.'.$format.'.twig', $dir.'/Resources/config/services.'.$format, $parameters); $this->renderFile('module/settings.yml.twig', $dir.'/Resources/config/settings.yml', $parameters); $this->renderFile('module/messages.ru.yml', $dir.'/Resources/translations/messages.ru.yml', $parameters); $this->filesystem->mkdir($dir.'/Resources/public/css'); $this->filesystem->mkdir($dir.'/Resources/public/images'); $this->filesystem->mkdir($dir.'/Resources/public/js'); } } <file_sep><?php namespace Monolith\Bundle\CMSGeneratorBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class CMSGeneratorBundle extends Bundle { } <file_sep><?php namespace Monolith\Bundle\CMSGeneratorBundle\Composer; use Composer\Script\Event; use Sensio\Bundle\DistributionBundle\Composer\ScriptHandler as SymfonyScriptHandler; use Symfony\Component\Finder\Finder; use Symfony\Component\Process\Process; class ScriptHandler extends SymfonyScriptHandler { /** * @param $event Event A instance */ public static function installCms(Event $event) { $options = parent::getOptions($event); $appDir = $options['symfony-app-dir']; $binDir = $options['symfony-bin-dir']; if (null === $appDir) { return; } $finder = (new Finder())->directories()->depth('== 0')->name('*SiteBundle')->name('SiteBundle')->in($appDir.'/../src'); if ($finder->count() == 0) { $event->getIO()->write('<info>Installing Monolith CMS. This prosess purge all database tables.</info>'); $confirm = $event->getIO()->ask(sprintf('<question>%s</question> (<comment>%s</comment>): ', 'Are you shure?', 'Y'), 'Y'); if (strtoupper($confirm) != 'Y') { $event->getIO()->write('<comment>Skipped...</comment>'); return; } $sitename = $event->getIO()->ask(sprintf('<question>%s</question> (<comment>%s</comment>): ', 'Site name', 'My'), 'My'); /* @todo validation while ($sitename !== 'Test') { $event->getIO()->write('<comment>Incorrest site name. Retry again...</comment>'); $sitename = $event->getIO()->ask(sprintf('<question>%s</question> (<comment>%s</comment>): ', 'Site name', 'My'), 'My'); } */ $username = $event->getIO()->ask(sprintf('<question>%s</question> (<comment>%s</comment>): ', 'Username', 'root'), 'root'); $email = $event->getIO()->ask(sprintf('<question>%s</question> (<comment>%s</comment>): ', 'Email', '<EMAIL>'), '<EMAIL>'); $password = $event->getIO()->ask(sprintf('<question>%s</question> (<comment>%s</comment>): ', 'Password', '123'), '123'); static::executeCommand($event, $binDir, "cms:install --sitename={$sitename} --username={$username} --email={$email} --password={$password} --no-interaction", $options['process-timeout']); /* static::clearCacheHard(); static::executeCommand($event, $binDir, 'doctrine:schema:drop --force', $options['process-timeout']); static::executeCommand($event, $binDir, 'cms:generate:sitebundle --name='.$sitename, $options['process-timeout']); unlink($appDir.'/config/install.yml'); static::warmapCacheHard(); static::executeCommand($event, $binDir, 'doctrine:schema:update --force --complete', $options['process-timeout']); $event->getIO()->write('<comment>Create super admin user:</comment>'); static::executeCommand($event, $binDir, "fos:user:create --super-admin $username $email $password", $options['process-timeout']); static::executeCommand($event, $binDir, 'cms:generate:default-site-data', $options['process-timeout']); */ } } protected static function clearCacheHard() { $process = new Process('bash bin/clear_cache'); $process->run(function ($type, $buffer) { if (Process::ERR === $type) { echo 'ERR > '.$buffer; } else { echo $buffer; } }); } protected static function warmapCacheHard() { $process = new Process('bash bin/warmup_cache'); $process->run(function ($type, $buffer) { /* if (Process::ERR === $type) { echo 'ERR > '.$buffer; } else { echo $buffer; } */ }); } } <file_sep><?php declare(strict_types=1); namespace Monolith\Bundle\CMSGeneratorBundle\Command; use Monolith\Bundle\CMSBundle\Entity\Domain; use Monolith\Bundle\CMSBundle\Entity\Folder; use Monolith\Bundle\CMSBundle\Entity\Language; use Monolith\Bundle\CMSBundle\Entity\Site; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Filesystem; class DefaultSiteDataCommand extends ContainerAwareCommand { /** * @see Command */ protected function configure() { $this ->setDescription('Create Default Site Data') ->setName('cms:generate:default-site-data') ; } /** * @see Command * * @throws \InvalidArgumentException When namespace doesn't end with Bundle * @throws \RuntimeException When bundle can't be executed */ protected function execute(InputInterface $input, OutputInterface $output) { $output->write('Create Default Site Data:'); /** @var \Doctrine\ORM\EntityManager $em */ $em = $this->getContainer()->get('doctrine.orm.entity_manager'); $user = $em->getRepository('SiteBundle:User')->findOneBy([], ['id' => 'ASC']); $output->write(' Language'); $language = new Language(); $language ->setCode('ru') ->setName('Русский') ->setUser($user) ; $em->persist($language); $em->flush($language); $output->write(', Domain'); $domain = new Domain(); $domain ->setName('localhost') ->setUser($user) ->setLanguage($language) ; $em->persist($domain); $em->flush($domain); $output->write(', Folder'); $folder = new Folder(); $folder ->setUser($user) ->setTitle('Главная') ; $em->persist($folder); $em->flush($folder); $output->write(', Site'); $site = new Site(); $site ->setUser($user) ->setDomain($domain) ->setLanguage($language) ->setName('@todo default site') ->setRootFolder($folder) ->setTheme('default') ; $em->persist($site); $em->flush($site); $output->write(', Theme'); $fileSystem = new Filesystem(); $fileSystem->mirror('src/Monolith/Bundle/CMSGeneratorBundle/Resources/skeleton/theme/', 'themes/default/'); $output->write(' <info>OK</info>'.PHP_EOL); } } <file_sep><?php namespace Monolith\Bundle\CMSGeneratorBundle\Command; use Monolith\Bundle\CMSGeneratorBundle\Generator\ModuleGenerator; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ConfirmationQuestion; use Symfony\Component\Console\Question\Question; class GenerateModuleCommand extends GeneratorCommand { /** * @see Command */ protected function configure() { $this ->setDefinition([ new InputOption('namespace', '', InputOption::VALUE_REQUIRED, 'The namespace of the module to create'), new InputOption('dir', '', InputOption::VALUE_REQUIRED, 'The directory where to create the module'), new InputOption('bundle-name', '', InputOption::VALUE_REQUIRED, 'The optional module name'), ]) ->setDescription('Generates a module') ->setName('cms:generate:module') ; } /** * @see Command * * @throws \InvalidArgumentException When namespace doesn't end with Bundle * @throws \RuntimeException When bundle can't be executed */ protected function execute(InputInterface $input, OutputInterface $output) { $questionHelper = $this->getQuestionHelper(); if ($input->isInteractive()) { if (!$questionHelper->ask($input, $output, new ConfirmationQuestion($questionHelper->getQuestion('Do you confirm generation', 'yes', '?'), true))) { $output->writeln('<error>Command aborted</error>'); return 1; } } foreach (['namespace', 'dir'] as $option) { if (null === $input->getOption($option)) { throw new \RuntimeException(sprintf('The "%s" option must be provided.', $option)); } } $namespace = Validators::validateBundleNamespace($input->getOption('namespace')); if (!$bundle = $input->getOption('bundle-name')) { $bundle = strtr($namespace, ['\\' => '']); } $bundle = Validators::validateBundleName($bundle); $dir = Validators::validateTargetDir($input->getOption('dir'), $bundle, $namespace); $questionHelper->writeSection($output, 'Module generation'); if (!$this->getContainer()->get('filesystem')->isAbsolutePath($dir)) { $dir = getcwd().'/'.$dir; } $generator = $this->getGenerator(); $generator->generate($namespace, $bundle, $dir, 'yml'); $output->writeln('Generating the module code: <info>OK</info>'); $errors = []; $runner = $questionHelper->getRunner($output, $errors); // check that the namespace is already autoloaded $runner($this->checkAutoloader($output, $namespace, $bundle, $dir)); $questionHelper->writeGeneratorSummary($output, $errors); } protected function interact(InputInterface $input, OutputInterface $output) { $questionHelper = $this->getQuestionHelper(); $questionHelper->writeSection($output, 'Welcome to the Monolith CMS module generator'); // namespace $namespace = null; try { $namespace = $input->getOption('namespace') ? Validators::validateBundleNamespace($input->getOption('namespace')) : null; } catch (\Exception $error) { $output->writeln($questionHelper->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error')); } if (null === $namespace) { $output->writeln([ '', 'Each module is hosted under a namespace (like <comment>MySite/BlogModule</comment>).', 'The namespace should begin with a "vendor" name like your company name, your', 'project name, or your client name, followed by one or more optional category', 'sub-namespaces, and it should end with the module name itself', '(which must have <comment>Module</comment> as a suffix).', '', 'Use <comment>/</comment> instead of <comment>\\ </comment> for the namespace delimiter to avoid any problem.', '', ]); $acceptedNamespace = false; while (!$acceptedNamespace) { $question = new Question($questionHelper->getQuestion('Bundle namespace', $input->getOption('namespace')), $input->getOption('namespace')); $question->setValidator(function ($answer) { return Validators::validateBundleNamespace($answer, false); }); $namespace = $questionHelper->ask($input, $output, $question); // mark as accepted, unless they want to try again below $acceptedNamespace = true; // see if there is a vendor namespace. If not, this could be accidental if (false === strpos($namespace, '\\')) { // language is (almost) duplicated in Validators $msg = array(); $msg[] = ''; $msg[] = sprintf('The namespace sometimes contain a vendor namespace (e.g. <info>VendorName/BlogBundle</info> instead of simply <info>%s</info>).', $namespace, $namespace); $msg[] = 'If you\'ve *did* type a vendor namespace, try using a forward slash <info>/</info> (<info>Acme/BlogBundle</info>)?'; $msg[] = ''; $output->writeln($msg); $question = new ConfirmationQuestion($questionHelper->getQuestion( sprintf('Keep <comment>%s</comment> as the bundle namespace (choose no to try again)?', $namespace), 'yes' ), true); $acceptedNamespace = $questionHelper->ask($input, $output, $question); } } $input->setOption('namespace', $namespace); } // bundle name $bundle = null; try { $bundle = $input->getOption('bundle-name') ? Validators::validateBundleName($input->getOption('bundle-name')) : null; } catch (\Exception $error) { $output->writeln($questionHelper->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error')); } if (null === $bundle) { $bundle = strtr(preg_match('/ModuleBundle$/', $namespace) ? $namespace : $namespace.'ModuleBundle', ['\\ModuleBundle\\' => '', '\\' => '']); $output->writeln([ '', 'In your code, a module is often referenced by its name. It can be the', 'concatenation of all namespace parts but it\'s really up to you to come', 'up with a unique name (a good practice is to start with the vendor name).', 'Based on the namespace, we suggest <comment>'.$bundle.'</comment>.', '', ]); $question = new Question($questionHelper->getQuestion('Bundle name', $bundle), $bundle); $question->setValidator( array('Monolith\Bundle\CMSGeneratorBundle\Command\Validators', 'validateBundleName') ); $bundle = $questionHelper->ask($input, $output, $question); $input->setOption('bundle-name', $bundle); } // target dir $dir = null; try { $dir = $input->getOption('dir') ? Validators::validateTargetDir($input->getOption('dir'), $bundle, $namespace) : null; } catch (\Exception $error) { $output->writeln($questionHelper->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error')); } if (null === $dir) { $dir = dirname($this->getContainer()->getParameter('kernel.project_dir')).'/src'; $output->writeln([ '', 'The module can be generated anywhere. The suggested default directory uses', 'the standard conventions.', '', ]); $question = new Question($questionHelper->getQuestion('Target directory', $dir), $dir); $question->setValidator(function ($dir) use ($bundle, $namespace) { return Validators::validateTargetDir($dir, $bundle, $namespace); }); $dir = $questionHelper->ask($input, $output, $question); $input->setOption('dir', $dir); } // format $format = 'yml'; // summary $output->writeln([ '', $this->getHelper('formatter')->formatBlock('Summary before generation', 'bg=blue;fg=white', true), '', sprintf("You are going to generate a \"<info>%s\\%s</info>\" bundle\nin \"<info>%s</info>\" using the \"<info>%s</info>\" format.", $namespace, $bundle, $dir, $format), '', ]); } /** * @param OutputInterface $output * @param string $namespace * @param string $bundle * @param string $dir * * @return array */ protected function checkAutoloader(OutputInterface $output, $namespace, $bundle, $dir) { $output->write('Checking that the bundle is autoloaded: '); if (!class_exists($namespace.'\\'.$bundle)) { return [ '- Edit the <comment>composer.json</comment> file and register the bundle', ' namespace in the "autoload" section:', '', ]; } } /** * @return ModuleGenerator */ protected function createGenerator() { return new ModuleGenerator($this->getContainer()->get('filesystem')); } } <file_sep><?php namespace Monolith\Bundle\CMSGeneratorBundle\Command; use Monolith\Bundle\CMSGeneratorBundle\Generator\SiteBundleGenerator; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\Question; class GenerateSiteBundleCommand extends GeneratorCommand { /** * @see Command */ protected function configure() { $this ->setDefinition([ new InputOption('name', '', InputOption::VALUE_REQUIRED, 'Site name.'), ]) ->setDescription('Generate SiteBundle for Monolith CMS') ->setName('cms:generate:sitebundle') ; } /** * @see Command * * @throws \InvalidArgumentException When namespace doesn't end with Bundle * @throws \RuntimeException When bundle can't be executed */ protected function execute(InputInterface $input, OutputInterface $output) { $questionHelper = $this->getQuestionHelper(); $name = $input->getOption('name'); if (empty($name)) { $name = 'My'; $question = new Question($questionHelper->getQuestion('Site name.', $name), $name); $name = $questionHelper->ask($input, $output, $question); } $name = ucfirst($name); $dir = dirname($this->getContainer()->getParameter('kernel.project_dir')).'/src'; $format = 'yml'; $structure = 'no'; if (!$this->getContainer()->get('filesystem')->isAbsolutePath($dir)) { $dir = getcwd().'/'.$dir; } $bundle = 'SiteBundle'; $namespace = $name.$bundle; $generator = $this->getGenerator(); $generator->generate($namespace, $bundle, $dir, $format, $structure); $output->writeln('Generating the bundle code: <info>OK</info>'); $errors = array(); $runner = $questionHelper->getRunner($output, $errors); // check that the namespace is already autoloaded $runner($this->checkAutoloader($output, $namespace, $bundle, $dir)); if (!$errors) { $questionHelper->writeSection($output, "'$namespace' succesfuly created!"); } else { $questionHelper->writeSection($output, [ 'The command was not able to configure everything automatically.', 'You must do the following changes manually.', ], 'error'); $output->writeln($errors); } } protected function checkAutoloader(OutputInterface $output, $namespace, $bundle, $dir) { $output->write('Checking that the bundle is autoloaded: '); if (!class_exists($namespace.'\\'.$bundle)) { return array( '- Edit the <comment>composer.json</comment> file and register the bundle', ' namespace in the "autoload" section:', '', ); } } protected function createGenerator() { return new SiteBundleGenerator($this->getContainer()->get('filesystem')); } } <file_sep><?php namespace App; use Doctrine\ORM\Mapping as ORM; use Monolith\Bundle\CMSBundle\Model\UserModel; /** * @ORM\Entity * @ORM\Table(name="users") */ class User extends UserModel { }
9d5d50ff56ae607d1c6c1db61d5fa0eea7e14d83
[ "PHP" ]
8
PHP
monolith-software/cms-generator-bundle
8769027c6cf19257b85d01e93b46cb37f41c50e6
8921ae26444c07dae60c8b2408d3a9c72576c1fb
refs/heads/master
<repo_name>nNown/snake<file_sep>/Headers/player.h #pragma once #include <array> #include <iostream> #include <vector> class PlayerEntity { private: char _body; std::vector<std::array<unsigned int, 2>> _bodyPartsPositions; std::array<int, 2> _direction; bool _gameState; public: char Body() const; std::vector<std::array<unsigned int, 2>> BodyPartsPositions() const; std::array<int, 2> Direction() const; void SetDirection(const std::array<int, 2>& newDirection); bool GameState() const; void SetGameState(const bool& currentGameState); void AddBodyPart(const std::array<unsigned int, 2>& dimensions); void MovePlayer(const std::array<unsigned int, 2>& dimensions); PlayerEntity(); PlayerEntity(const char& body, const std::array<unsigned int, 2>& startingPosition); PlayerEntity(const PlayerEntity& player); ~PlayerEntity(); };<file_sep>/Headers/food.h #pragma once #include <array> #include <iostream> class FoodEntity { private: char _body; std::array<unsigned int, 2> _position; public: char Body() const; std::array<unsigned int, 2> Position() const; void SetPosition(const std::array<unsigned int, 2>& newPosition); FoodEntity(); FoodEntity(const std::array<unsigned int, 2>& position); FoodEntity(const char& body, const std::array<unsigned int, 2>& position); FoodEntity(const FoodEntity& food); ~FoodEntity(); };<file_sep>/Source/game.cpp #include <game.h> GameEntity* GameEntity::GameInstance = NULL; void GameEntity::Draw() { this->board->Player()->MovePlayer(this->board->Dimensions()); this->board->ManageFood(); this->board->Draw(); } void GameEntity::GetInput() { if((GetKeyState(VK_LEFT) & PressedKeyMask || GetKeyState(0x41) & PressedKeyMask) && this->board->Player()->Direction()[1] != 1) this->board->Player()->SetDirection({ 0, -1 }); else if((GetKeyState(VK_UP) & PressedKeyMask || GetKeyState(0x57) & PressedKeyMask) && this->board->Player()->Direction()[0] != 1) this->board->Player()->SetDirection({ -1, 0 }); else if((GetKeyState(VK_RIGHT) & PressedKeyMask || GetKeyState(0x44) & PressedKeyMask) && this->board->Player()->Direction()[1] != -1) this->board->Player()->SetDirection({ 0, 1 }); else if((GetKeyState(VK_DOWN) & PressedKeyMask || GetKeyState(0x53) & PressedKeyMask) && this->board->Player()->Direction()[0] != -1) this->board->Player()->SetDirection({ 1, 0 }); else if(GetKeyState(VK_ESCAPE) & PressedKeyMask) this->board->Player()->SetGameState(true); } void GameEntity::CursorState(const bool& state) { HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(out, &cursorInfo); cursorInfo.bVisible = state; SetConsoleCursorInfo(out, &cursorInfo); } bool GameEntity::GetGameState() const { return this->board->Player()->GameState(); } BoardEntity* GameEntity::Board() { return this->board; } GameEntity::GameEntity(const std::array<unsigned int, 2>& dimensions) { std::srand(std::time(nullptr)); this->board = new BoardEntity(dimensions, PlayerEntity('X', { 6, 15 }), FoodEntity({1 + rand() % (dimensions[0] - 2), 1 + rand() % (dimensions[1] - 2)})); } GameEntity* GameEntity::GetGameEntityInstance() { if(GameInstance == NULL) { return NULL; } return GameInstance; } GameEntity* GameEntity::GetGameEntityInstance(const std::array<unsigned int, 2>& dimensions) { if(GameInstance == NULL) { GameInstance = new GameEntity(dimensions); } return GameInstance; } <file_sep>/Source/board.cpp #include <board.h> std::array<unsigned int, 2> BoardEntity::Dimensions() const { return this->_dimensions; } PlayerEntity* BoardEntity::Player() { return &(this->_player); } FoodEntity* BoardEntity::Food() { return &(this->_food); } void BoardEntity::Draw() { for(unsigned int i = 0; i < this->_dimensions[0]; i++) { for(unsigned int j = 0; j < this->_dimensions[1]; j++) { try { if(i == 0 || i == this->_dimensions[0] - 1) this->_board[i][j] = '-'; else if(j == 0 || j == this->_dimensions[1] - 1) this->_board[i][j] = '|'; else if(i == this->_food.Position()[0] && j == this->_food.Position()[1]) this->_board[i][j] = this->_food.Body(); else this->_board[i][j] = 0; for(unsigned int k = 0; k < this->_player.BodyPartsPositions().size(); k++) { if(i == this->_player.BodyPartsPositions()[k][0] && j == this->_player.BodyPartsPositions()[k][1]) this->_board[i][j] = this->_player.Body(); } std::cout << this->_board[i][j]; } catch(const std::out_of_range& ex) { std::cout << "Out of range exception caught:: " << ex.what() << std::endl; } } std::cout << std::endl; } } void BoardEntity::ManageFood() { if(this->_player.BodyPartsPositions()[0][0] == this->_food.Position()[0] && this->_player.BodyPartsPositions()[0][1] == this->_food.Position()[1]) { this->_player.AddBodyPart(this->_dimensions); this->_food.SetPosition({1 + rand() % (this->_dimensions[0] - 2), 1 + rand() % (this->_dimensions[1] - 2)}); } } BoardEntity::BoardEntity(const std::array<unsigned int, 2>& _dimensions, const PlayerEntity& player, const FoodEntity& food) { this->_dimensions = std::array<unsigned int, 2>(_dimensions); this->_board = std::vector<std::vector<char>>(this->_dimensions[0], std::vector<char>(this->_dimensions[1], 0)); this->_player = PlayerEntity(player); this->_food = FoodEntity(food); } BoardEntity::~BoardEntity() { std::cout << "_board destroyed" << std::endl; }<file_sep>/Makefile GXX = g++ CPPFLAGS = -Wall -Wextra -Wno-unused-parameter LDFLAGS = -I./Headers/ STDFLAG = -std=c++17 OPTIMALIZATION = -Ofast all: debug debug: Source/main.cpp Source/board.cpp Source/player.cpp Source/food.cpp Source/game.cpp $(GXX) $(CPPFLAGS) $(LDFLAGS) $(STDFLAG) -o main $^ $(OPTIMALIZATION) <file_sep>/Headers/game.h #pragma once #include <array> #include <board.h> #include <ctime> #include <cstdlib> #include <food.h> #include <player.h> #include <windows.h> #define PressedKeyMask 0x8000 class GameEntity { private: static GameEntity* GameInstance; BoardEntity* board; GameEntity(const std::array<unsigned int, 2>& dimensions); public: void Draw(); void GetInput(); void CursorState(const bool& state); bool GetGameState() const; BoardEntity* Board(); static GameEntity* GetGameEntityInstance(); static GameEntity* GetGameEntityInstance(const std::array<unsigned int, 2>& dimensions); };<file_sep>/Headers/board.h #pragma once #include <array> #include <iostream> #include <player.h> #include <food.h> #include <vector> class BoardEntity { private: std::array<unsigned int, 2> _dimensions; std::vector<std::vector<char>> _board; PlayerEntity _player; FoodEntity _food; public: std::array<unsigned int, 2> Dimensions() const; PlayerEntity* Player(); FoodEntity* Food(); void Draw(); void ManageFood(); BoardEntity(const std::array<unsigned int, 2>& dimensions, const PlayerEntity& player, const FoodEntity& food); ~BoardEntity(); };<file_sep>/Source/food.cpp #include <food.h> char FoodEntity::Body() const { return this->_body; } std::array<unsigned int, 2> FoodEntity::Position() const { return this->_position; } void FoodEntity::SetPosition(const std::array<unsigned int, 2>& newPosition) { this->_position = newPosition; } FoodEntity::FoodEntity() : _body('O'), _position({ 1, 1 }) {} FoodEntity::FoodEntity(const std::array<unsigned int, 2>& position) : _body('O'), _position(position) {} FoodEntity::FoodEntity(const char& body, const std::array<unsigned int, 2>& position) : _body(body), _position(position) {} FoodEntity::FoodEntity(const FoodEntity& food) : _body(food._body), _position(food._position) {} FoodEntity::~FoodEntity() { std::cout << "Food destroyed" << std::endl; }<file_sep>/Source/player.cpp #include <player.h> char PlayerEntity::Body() const { return this->_body; } std::vector<std::array<unsigned int, 2>> PlayerEntity::BodyPartsPositions() const { return this->_bodyPartsPositions; } std::array<int, 2> PlayerEntity::Direction() const { return this->_direction; } void PlayerEntity::SetDirection(const std::array<int, 2>& newDirection) { this->_direction = newDirection; } bool PlayerEntity::GameState() const { return this->_gameState; } void PlayerEntity::SetGameState(const bool& currentGameState) { this->_gameState = currentGameState; } void PlayerEntity::AddBodyPart(const std::array<unsigned int, 2>& dimensions) { std::array<unsigned int, 2> lastBodyPart = this->_bodyPartsPositions[_bodyPartsPositions.size() - 1]; if(lastBodyPart[0] == 1 && this->_direction[0] == 1) { lastBodyPart[0] = dimensions[0] - 2; } else if(lastBodyPart[0] == dimensions[0] - 2 && this->_direction[0] == -1) { lastBodyPart[0] = 1; } else if(lastBodyPart[1] == 1 && this->_direction[1] == 1) { lastBodyPart[1] = dimensions[1] - 2; } else if(lastBodyPart[1] == dimensions[1] - 2 && this->_direction[1] == -1) { lastBodyPart[1] = 1; } else { lastBodyPart[0] -= this->_direction[0]; lastBodyPart[1] -= this->_direction[1]; } _bodyPartsPositions.push_back(lastBodyPart); } void PlayerEntity::MovePlayer(const std::array<unsigned int, 2>& dimensions) { for(unsigned int i = this->_bodyPartsPositions.size() - 1; i > 0; i--) { this->_bodyPartsPositions[i] = this->_bodyPartsPositions[i - 1]; } if(this->_bodyPartsPositions[0][0] == 1 && this->_direction[0] == -1) { this->_bodyPartsPositions[0][0] = dimensions[0] - 2; } else if(this->_bodyPartsPositions[0][0] == dimensions[0] - 2 && this->_direction[0] == 1) { this->_bodyPartsPositions[0][0] = 1; } else if(this->_bodyPartsPositions[0][1] == 1 && this->_direction[1] == -1) { this->_bodyPartsPositions[0][1] = dimensions[1] - 2; } else if(this->_bodyPartsPositions[0][1] == dimensions[1] - 2 && this->_direction[1] == 1) { this->_bodyPartsPositions[0][1] = 1; } else { this->_bodyPartsPositions[0][0] += this->_direction[0]; this->_bodyPartsPositions[0][1] += this->_direction[1]; } for(unsigned int i = this->_bodyPartsPositions.size() - 1; i > 0; i--) { if(_bodyPartsPositions[0] == _bodyPartsPositions[i]) this->SetGameState(true); } } PlayerEntity::PlayerEntity() : _body('X'), _bodyPartsPositions(std::vector<std::array<unsigned int, 2>>(1, { 0, 0 })), _direction(std::array<int, 2>({ 0, 0 })), _gameState(false) { } PlayerEntity::PlayerEntity(const char& body, const std::array<unsigned int, 2>& startingPosition) : _body(body), _bodyPartsPositions(std::vector<std::array<unsigned int, 2>>(1, startingPosition)), _direction(std::array<int, 2>({ 0, 0 })), _gameState(false) { } PlayerEntity::PlayerEntity(const PlayerEntity& player) : _body(player._body), _bodyPartsPositions(std::vector<std::array<unsigned int, 2>>(player._bodyPartsPositions)), _direction(std::array<int, 2>(player._direction)), _gameState(false) { } PlayerEntity::~PlayerEntity() { std::cout << "Player destroyed" << std::endl; }<file_sep>/Source/main.cpp #include <game.h> #include <windows.h> void cls(GameEntity* gameEntity, BoardEntity* board); int main() { GameEntity* gameEntity = GameEntity::GetGameEntityInstance({25, 40}); // cls(gameEntity, gameEntity->Board()); std::system("cls"); // TEMPORARY while(!gameEntity->GetGameState()) { gameEntity->GetInput(); gameEntity->Draw(); // Sleep(75); // std::system("cls"); cls(gameEntity, gameEntity->Board()); } std::exit(0); } void cls(GameEntity* gameEntity, BoardEntity* board) { static const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO csbi; COORD topLeft = { (SHORT)board->Dimensions()[0], (SHORT)board->Dimensions()[1] }; if(!GetConsoleScreenBufferInfo(hOut, &csbi)) { abort(); } DWORD length = (board->Dimensions()[0] - 4) * (board->Dimensions()[1] - 4); DWORD written; FillConsoleOutputCharacter(hOut, TEXT(' '), length, topLeft, &written); FillConsoleOutputAttribute(hOut, csbi.wAttributes, length, topLeft, &written); SetConsoleCursorPosition(hOut, { 0, 0 }); gameEntity->CursorState(false); }
bad061552221334178612abeae95018837e44987
[ "Makefile", "C++" ]
10
C++
nNown/snake
ff9ddbaf86c2d8d289f3c1743c614c8eca662d76
894c20daafb8207153c280be1a377ced254c72cb
refs/heads/master
<repo_name>NCR-CoDE/gitbook-plugin-gitversion<file_sep>/README.md # Gitbook git version plugin Access git version info as a filter * `{{ "Branch is " | gitBranch }}` -> Branch is master * `{{ "Tag is " | gitTag }}` -> Tag is foo * `{{ "Short hash is " | gitShort }}` -> Short hash is 30f47b0 * `{{ "Long hash is " | gitLong }}` -> Long hash is 30f47b0f030c21bbf8129246f0f2e42e3e4f8576 <file_sep>/index.js var gitShort = 'no version'; var gitLong = 'no version'; var gitTag = 'no tag'; var gitBranch = 'no branch'; module.exports = { filters: { gitLong: function(name) { return name + gitLong; }, gitShort: function(name) { return name + gitShort; }, gitTag: function(name) { return name + gitTag; }, gitBranch: function(name) { return name + gitBranch; } }, // Hook process during build hooks: { // This is called before the book is generated "init": function() { console.log("Reading git version info"); var git = require('git-rev-sync'); gitTag = git.tag(); gitBranch = git.branch(); gitLong = git.long(); gitShort = git.short(); }, } };
33a955e6d2d6a784c868c1db0ae6ee222455c235
[ "Markdown", "JavaScript" ]
2
Markdown
NCR-CoDE/gitbook-plugin-gitversion
eca56ed1b5043b096ac8c894ba81d25fc70d9c91
37bd1e1fdfd7fff64197f41bea9004b896302e2e
refs/heads/master
<repo_name>edwardsiu/webmerge_to_onehub<file_sep>/content.js var inputElems = document.getElementsByTagName("input"); var submitButton = inputElems[inputElems.length - 1]; chrome.runtime.sendMessage({ event: "load" }); submitButton.addEventListener("click", function() { data = parseWebMergeForm(); chrome.runtime.sendMessage({event: "merge", data: data}); }); function parseWebMergeForm() { var formData = {} var fields = document.getElementsByClassName("field"); var fieldLabel; var fieldValue; var i; for (i=0; i<fields.length; i++) { fieldLabel = fields[i].getElementsByClassName("label")[0].innerHTML.slice(0, -1); fieldValue = fields[i].getElementsByTagName("input")[0].value; formData[fieldLabel] = fieldValue; } return JSON.stringify(formData); }<file_sep>/options.js // Saves options to chrome.storage function save_options() { var clientId = document.getElementById('client_id').value; var clientSecret = document.getElementById('client_secret').value; var workspaceId = document.getElementById('workspace_id').value; var folderId = document.getElementById('folder_id').value; chrome.storage.sync.set({ oneHubClientId: clientId, oneHubClientSecret: clientSecret, workspaceId: workspaceId, folderId: folderId }, function () { // Let the extension know that options were updated // and that it should reauthorize itself with OneHub chrome.runtime.sendMessage({ event: "optionsUpdate" }); // Update status to let user know options were saved. var status = document.getElementById('status'); status.textContent = 'Options saved.'; setTimeout(function () { status.textContent = ''; }, 750); }); } // Load the configuration saved in chrome storage into the options window function restore_options() { chrome.storage.sync.get({ oneHubClientId: "", oneHubClientSecret: "", workspaceId: "", folderId: "" }, function (items) { document.getElementById('client_id').value = items.oneHubClientId; document.getElementById('client_secret').value = items.oneHubClientSecret; document.getElementById('workspace_id').value = items.workspaceId; document.getElementById('folder_id').value = items.folderId; document.getElementById('redirect_uri').textContent = chrome.identity.getRedirectURL(); }); } document.addEventListener('DOMContentLoaded', restore_options); document.getElementById('save').addEventListener('click', save_options);
d6a066b8a15191c4309361c2d57aabd5b0978a0c
[ "JavaScript" ]
2
JavaScript
edwardsiu/webmerge_to_onehub
56759c44e5c6282768c70780714bb8254457fff9
4161971f13e98384aebc1861ffd36b1112c1a885
refs/heads/main
<file_sep>package com.bravo.user.dao.model; import java.time.LocalDateTime; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import com.bravo.user.model.dto.ProfileSaveDto; import lombok.Data; @Entity @Data @Table(name = "profile") public class Profile { @Id @Column(name = "id") private String id; @Column(name = "image_ref", nullable = false) private String imageRef; @Column(name = "updated", nullable = false) private LocalDateTime updated; public Profile() { super(); this.id = UUID.randomUUID().toString(); this.updated = LocalDateTime.now(); } public Profile(final ProfileSaveDto dto) { this(); this.imageRef = dto.getImageRef(); } } <file_sep>package com.bravo.user.dao.model.mapper; import com.bravo.user.MapperArgConverter; import com.bravo.user.dao.model.Profile; import com.bravo.user.dao.model.User; import com.bravo.user.model.dto.ProfileReadDto; import com.bravo.user.model.dto.UserReadDto; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.converter.ConvertWith; import org.junit.jupiter.params.provider.CsvFileSource; import ma.glasnost.orika.impl.DefaultMapperFactory; class ResourceMapperTest { @ParameterizedTest @CsvFileSource( resources = ("/convertUserTests.csv"), delimiter = '$', lineSeparator = ">" ) void convertUserTest( @ConvertWith(MapperArgConverter.class) User user, @ConvertWith(MapperArgConverter.class) UserReadDto userReadDto) { Assertions.assertEquals(userReadDto, new ResourceMapper( new DefaultMapperFactory.Builder().build().getMapperFacade()).convertUser(user)); } @ParameterizedTest @CsvFileSource( resources = ("/convertProfileTests.csv"), delimiter = '$', lineSeparator = ">" ) void convertProfileTest( @ConvertWith(MapperArgConverter.class) Profile profile, @ConvertWith(MapperArgConverter.class) ProfileReadDto profileReadDto) { Assertions.assertEquals(profileReadDto, new ResourceMapper( new DefaultMapperFactory.Builder().build().getMapperFacade()).convertProfile(profile)); } }
4e3d48bf12fceb1bb8d32085005ee4be82c2005f
[ "Java" ]
2
Java
bravocw/candidate-sample-java
fef4ca829423cf40b85835dfe7bbe7b76064aaaf
439f7faaeb7f1e7f8dab30a13b24dedda59d254e
refs/heads/main
<repo_name>Leiserg/studyJS<file_sep>/test.js // 'use strict'; // let start = document.getElementById('start'), // salaryAmount = document.querySelector('.salary-amount'); // document.getElementById('start').addEventListener('click', appData.getBlock); <file_sep>/script copy.js 'use strict'; let startBtn = document.getElementById('start'), canselBtn = document.getElementById('cancel'), btnPlus = document.getElementsByTagName('button'), incomePlus = btnPlus[0], expensesPlus = btnPlus[1], checkbox = document.querySelector('#deposit-check'), additionalIncomeItem = document.querySelectorAll('.additional_income-item'), budgetMonthValue = document.getElementsByClassName('budget_month-value')[0], budgetDayValue = document.getElementsByClassName('budget_day-value')[0], expensesMonthValue = document.getElementsByClassName('expenses_month-value')[0], additionalIncomeValue = document.getElementsByClassName('additional_income-value')[0], additionalExpensesValue = document.getElementsByClassName('additional_expenses-value')[0], incomePeriodValue = document.getElementsByClassName('income_period-value')[0], targetMonthValue = document.getElementsByClassName('target_month-value')[0], salaryAmount = document.querySelector('.salary-amount'), incomeTitle = document.querySelector('.income-title'), incomeAmount = document.querySelector('.income-amount'), expensesTitle = document.querySelector('.expenses-title'), expensesAmount = document.querySelector('.expenses-amount'), additionalExpenses = document.querySelector('.additional_expenses'), depositAmount = document.querySelector('.deposit-amount'), depositPercent = document.querySelector('.deposit-percent'), expensesItems = document.querySelectorAll('.expenses-items'), periodSelect = document.querySelector('.period-select'), periodAmount = document.querySelector('.period-amount'), additionalExpensesItem = document.querySelector('.additional_expenses-item'), targetAmout = document.querySelector('.target-amount'), incomeItems = document.querySelectorAll('.income-items'); periodAmount = document.querySelector('.period-amount'); let isNumber = function(n) { return !isNaN(parseFloat(n)) && isFinite(n); }; let appData = { budget: 0, budgetDay: 0, budgetMonth: 0, income: {}, incomeMonth: 0, addIncome: [], expenses: {}, expensesMonth: 0, addExpenses: [], deposit: false, percentDeposit: 0, moneyDeposit: 0, period: 0, start: function() { let allInput = document.querySelectorAll('.input[type = text]'); allInput.forEach(function(item){ item.setAttribute('disabled', 'true'); }); incomePlus.setAttribute('disabled', 'true'); expensesPlus.setAttribute('disabled', 'true'); startBtn.style.display = 'none'; canselBtn.style.display = 'block'; console.log(this); this.budget = +salaryAmount.value; console.log('salaryAmount: ', salaryAmount.value); this.getExpenses(); this.getIncome(); this.getExpensesMonth(); this.getAddExpenses(); this.getAddIncome(); this.getBudget(); this.getInfoDeposit(); this.getStatusIncome(); this.showResult(); }, newStart: function(){ const _this = this; _this.start.call(_this); }, getBlock: function(){ if (salaryAmount.value === '' || isNaN(salaryAmount.value) || salaryAmount.value == 0){ startBtn.disabled = true; } else { startBtn.disabled = false; } }, showResult: function(){ const _this = this; budgetMonthValue.value = this.budgetMonth; budgetDayValue.value = this.budgetDay; expensesMonthValue.value = this.expensesMonth; additionalExpensesValue.value = this.addExpenses.join(', '); additionalIncomeValue.value = this.addIncome.join(', '); targetMonthValue.value = Math.ceil (this.getTargetMonth()); incomePeriodValue.value = this.calcSavedMoney(); periodSelect.addEventListener('change', function(){ incomePeriodValue.value = _this.calcSavedMoney(); }); }, addExpensesBlock: function(){ let cloneExpensesItems = expensesItems[0].cloneNode(true); expensesItems[0].parentNode.insertBefore(cloneExpensesItems, expensesPlus); expensesItems = document.querySelectorAll('.expenses-items'); if (expensesItems.length === 3) { expensesPlus.style.display = 'none'; } }, getExpenses: function(){ const _this = this; expensesItems.forEach(function(item){ let itemExpenses = item.querySelector('.expenses-title').value; let cashExpenses = item.querySelector('.expenses-amount').value; if(itemExpenses !== '' && cashExpenses !== ''){ _this.expenses[itemExpenses] = cashExpenses; } }); }, addIncomeBlock: function(){ let cloneIncomeItems = incomeItems[0].cloneNode(true); incomeItems[0].parentNode.insertBefore(cloneIncomeItems, incomePlus); incomeItems = document.querySelectorAll('.income-items'); if (incomeItems.length === 3) { incomePlus.style.display = 'none'; } }, getIncome: function(){ const _this = this; incomeItems.forEach(function(item){ let itemIncome = item.querySelector('.income-title').value; let cashIncome = item.querySelector('.income-amount').value; if(itemIncome !== '' && cashIncome !== ''){ _this.income[itemIncome] = cashIncome; } }); for(let key in this.income){ this.incomeMonth += +this.income[key]; } }, getAddExpenses: function(){ const _this = this; let addExpenses = additionalExpensesItem.value.split(','); addExpenses.forEach(function(item){ item = item.trim(); if(item !== ''){ _this.addExpenses.push(item); } }); }, getAddIncome: function (){ const _this = this; additionalIncomeItem.forEach(function(item){ let itemValue = item.value.trim(); if (itemValue !== ''){ _this.addIncome.push(itemValue); } }); }, eventFunc: function(event){ periodAmount.innerHTML = periodSelect.value; }, getExpensesMonth: function() { for (let key in this.expenses) { this.expensesMonth += +this.expenses[key]; } }, getBudget: function() { this.budgetMonth = this.budget + this.incomeMonth - this.expensesMonth; this.budgetDay = Math.ceil(this.budgetMonth / 30); }, getTargetMonth: function() { return targetAmout.value / this.budgetMonth; }, calcSavedMoney: function(){ return this.budgetMonth * periodSelect.value; }, getStatusIncome: function() { if(this.budgetDay > 1200) { console.log('У вас высокий уровень дохода'); } else if(this.budgetDay >= 600 && this.budgetDay <= 1200) { console.log('У вас средний уровень дохода'); } else if(this.budgetDay > 0 && this.budgetDay < 600) { console.log('К сожалению Ваш уровень дохода ниже среднего'); }else { console.log('Что-то пошло не так'); } }, getInfoDeposit: function() { if (this.deposit) { this.percentDeposit = prompt('Какой годовой процент?', 10); while (!isNumber(this.percentDeposit)) { this.percentDeposit = prompt('Во сколько это обойдется?'); } this.moneyDeposit = prompt('Какая сумма заложена?', 10000); while (!isNumber(this.moneyDeposit)) { this.moneyDeposit = prompt('Во сколько это обойдется?'); } } }, reset: function(){ let inputTextData = document.querySelectorAll('.data input[type = text]'); let resultInputAll = document.querySelectorAll('.data input[type = text]'); inputTextData.forEach(function(element){ element.value = ''; element.removeAttribute('disabled'); periodSelect.value = '0'; periodAmount.innerHTML = periodSelect.value; }); resultInputAll.forEach(function(element){ element.value = ''; }); for (let i = 1; i < incomeItems.length; i++){ incomeItems[i].parentNode.removeChild(incomeItems[i]); incomePlus.style.display = 'block'; } } }; startBtn.disabled = true; startBtn.addEventListener('click', appData.bind(newStart)); salaryAmount.addEventListener('input', appData.getBlock); incomePlus.addEventListener('click', appData.addIncomeBlock); expensesPlus.addEventListener('click', appData.addExpensesBlock); periodSelect.addEventListener('input', appData.eventFunc); canselBtn.addEventListener('click', appData.reset.bind(appData));
3e03e9723ff0c01e7b1325c8d6bb43b2b2343f2f
[ "JavaScript" ]
2
JavaScript
Leiserg/studyJS
4a0d6db6cffcd6c5b72b48a041768f9a7f720789
dc19503fe34b6b6e5a2c3308d72ff01b3e486c5a
refs/heads/master
<file_sep><?php $requestedBy = $_POST['Username']; $debugMode = true; $applicationIconPath = 'assets/images/applicationIcon.jpg'; $applicationIconCaption = "$requestedBy's lense"; $result = "<?xml version=\"1.0\" encoding=\"utf-8\"?> <config> <debugMode>$debugMode</debugMode> <applicationIconPath caption=\"$applicationIconCaption\">$applicationIconPath</applicationIconPath> </config>"; echo $result; ?>
9509c5f600fa5078c10c1844cd1df4e4051539b1
[ "PHP" ]
1
PHP
andCulture/FlexMeetup
ca491cdd9b96bac00ce5600ebe75d2faa414557a
94546ee6c6b1cb387d023119e0fcbf6f792b9e54
refs/heads/master
<file_sep>require 'rake' namespace :schedulable do desc 'prints the names of the schedulable types' task show_schedulables: :environment do Schedule.all.uniq.pluck(:schedulable_type).each do |schedulable_type| puts schedulable_type end end desc 'Builds occurrences for schedulable models' task build_occurrences: :environment do Schedule.all.uniq.pluck(:schedulable_type).each do |schedulable_type| clazz = schedulable_type.constantize occurrences_associations = Schedulable::ActsAsSchedulable.occurrences_associations_for(clazz) occurrences_associations.each do |association| clazz.send("build_" + association.to_s) end end end end <file_sep>class ScheduleInput < SimpleForm::Inputs::Base def input(wrapper_options) # Init options input_options||= {} # I18n weekdays = Date::DAYNAMES.map(&:downcase) weekdays = weekdays.slice(1..7) << weekdays.slice(0) day_names = I18n.t('date.day_names', default: "") day_names = day_names.blank? ? weekdays.map { |day| day.capitalize } : day_names.slice(1..7) << day_names.slice(0) day_labels = Hash[weekdays.zip(day_names)] # Pass in default month names when missing in translations month_names = I18n.t('date.month_names', default: "") month_names = month_names.blank? ? Date::MONTHNAMES : month_names # Pass in default order when missing in translations date_order = I18n.t('date.order', default: "") date_order = date_order.blank? ? [:year, :month, :day] : date_order # Setup date_options date_options = { order: date_order, use_month_names: month_names } # Input html options input_html_options[:type] ||= input_type if html5? # Get config options config_options = Schedulable.config.simple_form.present? ? Schedulable.config.simple_form : {} # Merge input options input_options = config_options.merge(input_options) # Input options input_options[:interval] = !input_options[:interval].nil? ? input_options[:interval] : false input_options[:until] = !input_options[:until].nil? ? input_options[:until] : false input_options[:count] = !input_options[:count].nil? ? input_options[:count] : false # Setup input types input_types = {date: :date, time: :time, datetime: :datetime}.merge(input_options[:input_types] || {}) @builder.simple_fields_for(attribute_name.to_sym, @builder.object.send("#{attribute_name}") || @builder.object.send("build_#{attribute_name}")) do |b| # Javascript element id field_id = b.object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/,"_").sub(/_$/,"") b.template.content_tag("div", {id: field_id}) do b.input(:rule, collection: ['singular', 'daily', 'weekly', 'monthly'], label_method: lambda { |v| I18n.t("schedulable.rules.#{v}", default: v.capitalize) }, label: false, include_blank: false) << template.content_tag("div", {data: {group: 'singular'}}) do b.input :date, date_options.merge({as: input_types[:date]}) end << template.content_tag("div", {data: {group: 'weekly'}}) do b.input :day, collection: weekdays, label_method: lambda { |v| ("&nbsp;" + day_labels[v]).html_safe}, boolean_style: :nested, as: :check_boxes end << template.content_tag("div", {data: {group: 'monthly'}}) do b.simple_fields_for :day_of_week, OpenStruct.new(b.object.day_of_week || {}) do |db| template.content_tag("div", class: 'form-group' + (b.object.errors[:day_of_week].any? ? " has-error" : "")) do b.label(:day_of_week, error: true) << template.content_tag("div", nil, style: 'min-width: 280px; display: table') do template.content_tag("div", nil, style: 'display: table-row') do template.content_tag("span", nil, style: 'display: table-cell;') << ['1st', '2nd', '3rd', '4th', 'last'].reduce(''.html_safe) { | content, item | content << template.content_tag("span", I18n.t("schedulable.monthly_week_names.#{item}", default: item.to_s), style: 'display: table-cell; text-align: center') } end << weekdays.reduce(''.html_safe) do | content, weekday | content << template.content_tag("div", nil, style: 'display: table-row') do template.content_tag("span", day_labels[weekday] || weekday, style: 'display: table-cell') << db.collection_check_boxes(weekday.to_sym, [1, 2, 3, 4, -1], lambda { |i| i} , lambda { |i| "&nbsp;".html_safe}, boolean_style: :inline, label: false, checked: db.object.send(weekday), inline_label: false, item_wrapper_tag: nil) do |cb| template.content_tag("span", style: 'display: table-cell; text-align: center;') { cb.check_box(class: "check_box") } end end end end << b.error(:day_of_week) end end end << template.content_tag("div", data: {group: 'singular,daily,weekly,monthly'}) do b.input :time, date_options.merge({as: input_types[:time]}) end << (if input_options[:interval] template.content_tag("div", data: {group: 'daily,weekly,monthly'}) do b.input :interval end else b.input(:interval, as: :hidden, input_html: {value: 1}) end) << (if input_options[:until] template.content_tag("div", data: {group: 'daily,weekly,monthly'}) do b.input :until, date_options.merge({as: input_types[:datetime]}) end else b.input(:until, as: :hidden, input_html: {value: nil}) end) << if input_options[:count] template.content_tag("div", data: {group: 'daily,weekly,monthly'}) do b.input :count end else b.input(:count, as: :hidden, input_html: {value: 0}) end end << template.javascript_tag( "(function() {" << " var container = document.querySelectorAll('##{field_id}'); container = container[container.length - 1]; " << " var select = container.querySelector(\"select[name*='rule']\"); " << " function update() {" << " var value = this.value;" << " [].slice.call(container.querySelectorAll(\"*[data-group]\")).forEach(function(elem) { " << " var groups = elem.getAttribute('data-group').split(',');" << " if (groups.indexOf(value) >= 0) {" << " elem.style.display = ''" << " } else {" << " elem.style.display = 'none'" << " }" << " });" << " }" << " if (jQuery) { jQuery(select).on('change', update); } else { select.addEventListener('change', update); }" << " update.call(select);" << "})()" ) end end end <file_sep>module Schedulable module ScheduleSupport def self.param_names [:id, :sched_date, :sched_time, :start_time, :start_time_date, :start_time_time, :end_time, :end_time_date, :end_time_time, :rule, :until, :until_date, :until_time, :count, :interval, :effective_time, :effective_time_date, :effective_time_time, :timezone, day: [], day_of_week: [monday: [], tuesday: [], wednesday: [], thursday: [], friday: [], saturday: [], sunday: []]] end end end <file_sep>module Schedulable module ActsAsSchedulable extend ActiveSupport::Concern included do end module ClassMethods def set_up_accessor(arg) # getter class_eval("def #{arg};@#{arg};end") # setter class_eval("def #{arg}=(val);@#{arg}=val;end") end def acts_as_schedulable(name, options = {}) name ||= :schedule # var to store occurrences with errors set_up_accessor('occurrences_with_errors') has_one name, as: :schedulable, dependent: :destroy, class_name: 'Schedule' accepts_nested_attributes_for name if options[:occurrences] # setup association if options[:occurrences].is_a?(String) || options[:occurrences].is_a?(Symbol) occurrences_association = options[:occurrences].to_sym options[:occurrences] = {} else occurrences_association = options[:occurrences][:name] options[:occurrences].delete(:name) end options[:occurrences][:class_name] = occurrences_association.to_s.classify options[:occurrences][:as] ||= :schedulable options[:occurrences][:dependent] ||= :destroy options[:occurrences][:autosave] ||= true has_many occurrences_association, options[:occurrences] # table_name occurrences_table_name = occurrences_association.to_s.tableize # remaining remaining_occurrences_options = options[:occurrences].clone remaining_occurrences_association = ('remaining_' << occurrences_association.to_s).to_sym has_many remaining_occurrences_association, -> { where("#{occurrences_table_name}.start_time >= ?", Time.zone.now.to_datetime).order('start_time ASC') }, remaining_occurrences_options # previous previous_occurrences_options = options[:occurrences].clone previous_occurrences_association = ('previous_' << occurrences_association.to_s).to_sym has_many previous_occurrences_association, -> { where("#{occurrences_table_name}.start_time < ?", Time.zone.now.to_datetime).order('start_time DESC') }, previous_occurrences_options ActsAsSchedulable.add_occurrences_association(self, occurrences_association) after_save "build_#{occurrences_association}".to_sym self.class.instance_eval do define_method("build_#{occurrences_association}") do # build occurrences for all events # TODO: only invalid events schedulables = all schedulables.each { |schedulable| schedulable.send("build_#{occurrences_association}") } end end define_method "build_#{occurrences_association}_after_update" do schedule = send(name) send("build_#{occurrences_association}") if schedule.changes.any? end define_method "build_#{occurrences_association}" do # build occurrences for events schedule = send(name) if schedule.present? # Set dates change will be effective from now = Time.zone.now effective_time_for_changes = schedule.local_effective_time.nil? ? now : schedule.local_effective_time # Store details about schedulable schedulable = schedule.schedulable terminating = schedule.rule != 'singular' && (schedule.until.present? || schedule.count.present? && schedule.count > 1) self.occurrences_with_errors = [] if self.occurrences_with_errors.nil? # Set the max date to go till max_period = Schedulable.config.max_build_period || 1.year max_time = (now + max_period).to_time max_time = terminating ? [max_time, schedule.to_icecube.last.start_time].min : max_time # Generate the start times of the occurrences if schedule.rule == 'singular' occurrences = [IceCube::Occurrence.new(schedule.local_start_time, schedule.local_end_time)] else # Get schedule occurrences all_occurrences = schedule.to_icecube.occurrences_between(effective_time_for_changes, max_time) occurrences = [] # Filter valid dates all_occurrences.each_with_index do |occurrence_item, index| if occurrence_item.present? && occurrence_item.start_time >= effective_time_for_changes if occurrence_item.start_time <= max_time occurrences << occurrence_item else max_time = [max_time, occurrence_item.start_time].min end end end end # Determine update mode update_mode = Schedulable.config.update_mode || :datetime update_mode = :index if schedule.rule == 'singular' # Get existing remaining records occurrences_records = schedulable.send("remaining_#{occurrences_association}") # Fields that are going to be extracted from the schedulable # and copied over to the occurrence. these should be configured # at the model schedulable_fields = options[:schedulable_fields] || {} schedulable_fields_data = schedulable_fields.reduce({}) do |acum, f| acum[f] = self.send(f) acum end # Save occurrences that should be in our database. Bear in mind there's two cases # here - a new generation with no existing records and an update # var occurrences is what the schedule should be # var occurrences_records stores actual DB records occurrences.each_with_index do |occurrence, index| if update_mode == :index if schedule.rule == 'singular' # remaining_#{occurrences_association} doesn't work for singular events existing_records = [schedulable.send(occurrences_association).first] else existing_records = [occurrences_records[index]] end elsif update_mode == :datetime existing_records = occurrences_records.select do |record| record.start_time == occurrence end else existing_records = [] end # Merge with start/end time occurrence_data = schedulable_fields_data.merge(start_time: occurrence.start_time, end_time: occurrence.end_time) # Create/Update records if existing_records.any? existing_records.each do |existing_record| existing_record.update_from_schedulable = true self.occurrences_with_errors << existing_record unless existing_record.update(occurrence_data) end else new_record = occurrences_records.build(occurrence_data) self.occurrences_with_errors << new_record unless new_record.save end end # Re-load the records as we've created new ones occurrences_records = schedulable.send("remaining_#{occurrences_association}") # Remove no-longer needed records record_count = 0 destruction_list = occurrences_records.select do |occurrence_record| # Note no_longer_relevant uses cached occurrences as it's more efficient event_time = occurrence_record.start_time event_in_future = event_time > effective_time_for_changes no_longer_relevant = !occurrences.include?(event_time) || occurrence_record.start_time > max_time if schedule.rule == 'singular' && record_count > 0 mark_for_destruction = event_in_future elsif schedule.rule != 'singular' && no_longer_relevant mark_for_destruction = event_in_future else mark_for_destruction = false end record_count += 1 mark_for_destruction end destruction_list.each(&:destroy) end end end end end def self.occurrences_associations_for(clazz) @@schedulable_occurrences ||= [] @@schedulable_occurrences.select do |item| item[:class] == clazz end.map do |item| item[:name] end end def self.add_occurrences_association(clazz, name) @@schedulable_occurrences ||= [] @@schedulable_occurrences << { class: clazz, name: name } end end end ActiveRecord::Base.send :include, Schedulable::ActsAsSchedulable <file_sep>class CreateSchedules < ActiveRecord::Migration[5.1] def self.up create_table :schedules do |t| t.references :schedulable, polymorphic: true t.datetime :start_time t.datetime :end_time t.string :rule t.string :interval t.string :timezone t.text :day t.text :day_of_week t.datetime :until t.integer :count t.timestamps end end def self.down drop_table :schedules end end <file_sep>module Schedulable module Model class Schedule < ActiveRecord::Base serialize :day serialize :day_of_week, Hash belongs_to :schedulable, polymorphic: true attr_accessor :effective_time validates_presence_of :rule validates_presence_of :start_time validates_presence_of :end_time # validates_presence_of :date, if: Proc.new { |schedule| schedule.rule == 'singular' } validate :validate_day, if: Proc.new { |s| s.rule == 'weekly' } validate :validate_day_of_week, if: Proc.new { |s| s.rule == 'monthly' } def to_icecube return schedule_obj end def to_s if self.rule == 'singular' IceCube::Occurrence.new(local_start_time, local_end_time).to_s else schedule_obj.to_s end end # The database stores the date/time as the user enters it. However AR returns it to us in # the server timezone, which isn't what we want. We therefore have methods that add the # correct timezone to that time. # We can't store the UTC time of a class as that changes with DST - for example a 7am class # is really at 7am in the winter and 6am in the summer (when +1 DST applies). IE for a given # class it has two UTC times depending on the time of year # So there are three ways to get the start time - 1) As the user sees it (db version) 2) with # correct timezone info on it as a ruby object 3) in UTC def local_start_time if self.timezone && start_time Time.find_zone(self.timezone).local(start_time.year, start_time.month, start_time.day, start_time.hour, start_time.min, start_time.sec) else start_time end end def local_end_time if self.timezone && end_time Time.find_zone(self.timezone).local(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.min, end_time.sec) else end_time end end def local_until_time if self.timezone && self.until Time.find_zone(self.timezone).local(self.until.year, self.until.month, self.until.day, self.until.hour, self.until.min, self.until.sec) else self.until end end def local_effective_time if self.timezone && effective_time Time.find_zone(self.timezone).local(effective_time.year, effective_time.month, effective_time.day, effective_time.hour, effective_time.min, effective_time.sec) else effective_time end end def utc_start_time local_start_time.utc end def utc_end_time local_end_time.utc end def utc_until_time local_until_time.utc end def utc_effective_time local_effective_time.utc end def self.param_names [:id, :start_time, :end_time, :rule, :until, :count, :interval, day: [], day_of_week: [monday: [], tuesday: [], wednesday: [], thursday: [], friday: [], saturday: [], sunday: []]] end def schedule_obj @schedule ||= generate_schedule end def generate_schedule self.rule ||= "singular" self.interval ||= 1 self.count ||= 0 # As we won't ever want to deal with historic events we start from today # (this improves the speed of IceCube) time_in_zone = Time.find_zone(self.timezone).now start_time_for_today = local_start_time.change(year: time_in_zone.year, month: time_in_zone.month, day: time_in_zone.day) end_time_for_today = local_end_time.change(year: time_in_zone.year, month: time_in_zone.month, day: time_in_zone.day) ice_cube_schedule = IceCube::Schedule.new(start_time_for_today, end_time: end_time_for_today) if self.rule && self.rule != 'singular' self.interval = self.interval.present? ? self.interval.to_i : 1 rule = IceCube::Rule.send("#{self.rule}", self.interval) if local_until_time rule.until(local_until_time) end if self.count && self.count.to_i > 0 rule.count(self.count.to_i) end if self.day days = self.day.reject(&:empty?) if self.rule == 'weekly' days.each do |day| rule.day(day.to_sym) end elsif self.rule == 'monthly' days = {} day_of_week.each do |weekday, value| days[weekday.to_sym] = value.reject(&:empty?).map { |x| x.to_i } end rule.day_of_week(days) end end ice_cube_schedule.add_recurrence_rule(rule) end ice_cube_schedule end private # We create private methods for these to stop them being accessed outside the class # With the timezone returned they're incorrect and therefore should not be used other # than to get a time in the right zone via local_start_time def start_time read_attribute(:start_time) end def end_time read_attribute(:end_time) end def start_time=(time) write_attribute(:start_time, time) end def end_time=(time) write_attribute(:end_time, time) end def validate_day day.reject! { |c| c.empty? } if !day.any? errors.add(:day, :empty) end end def validate_day_of_week any = false day_of_week.each { |key, value| value.reject! { |c| c.empty? } if value.length > 0 any = true break end } if !any errors.add(:day_of_week, :empty) end end end end end <file_sep>module Schedulable module FormHelper STYLES = { default: { field_html: {class: 'field'}, input_wrapper: {tag: 'div'} }, bootstrap: { field_html: {class: ''}, num_field_html: {class: 'form-control'}, date_select_html: {class: 'form-control'}, date_select_wrapper: {tag: 'div', class: 'form-inline'}, datetime_select_html: {class: 'form-control'}, datetime_select_wrapper: {tag: 'div', class: 'form-inline'}, collection_select_html: {class: 'form-control'}, collection_check_boxes_item_wrapper: {tag: 'div', class: 'btn-group-toggle'} } } def self.included(base) ActionView::Helpers::FormBuilder.instance_eval do include FormBuilderMethods end end module FormBuilderMethods def schedule_select(attribute, input_options = {}) template = @template available_periods = input_options[:available_periods] || ['singular', 'daily', 'weekly', 'monthly'] # I18n weekdays = Date::DAYNAMES.map(&:downcase) weekdays = weekdays.slice(1..7) << weekdays.slice(0) # day_names = I18n.t('date.day_names', default: "") # day_names = day_names.blank? ? weekdays.map { |day| day.capitalize } : day_names.slice(1..7) << day_names.slice(0) # day_labels = Hash[weekdays.zip(day_names)] day_labels = Hash[weekdays.zip(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'])] # Pass in default month names when missing in translations month_names = I18n.t('date.month_names', default: "") month_names = month_names.blank? ? Date::MONTHNAMES : month_names # Pass in default order when missing in translations date_order = I18n.t('date.order', default: [:year, :month, :day]) date_order = date_order.map { |order| order.to_sym } # Setup date_options date_options = { order: date_order, use_month_names: month_names } datetime_options = { minute_step: 5 } # Get config options config_options = Schedulable.config.form_helper.present? ? Schedulable.config.form_helper : {style: :default} # Merge input options input_options = config_options.merge(input_options) # Setup input types input_types = {date: :date_select, start_time: :time_select, end_time: :time_select, datetime: :datetime_select}.merge(input_options[:input_types] || {}) # Setup style option if input_options[:style].is_a?(Symbol) || input_options[:style].is_a?(String) style_options = STYLES.has_key?(input_options[:style]) ? STYLES[input_options[:style]] : STYLES[:default] elsif input_options[:style].is_a?(Hash) style_options = input_options[:style] else style_options = STYLES[:default] end # Merge with input options style_options = style_options.merge(input_options) # Init style properties style_options[:field_html]||= {} style_options[:label_html]||= {} style_options[:label_wrapper]||= {} style_options[:input_html]||= {} style_options[:input_wrapper]||= {} style_options[:number_field_html]||= {} style_options[:number_field_wrapper]||= {} style_options[:date_select_html]||= {} style_options[:date_select_wrapper]||= {} style_options[:time_select_html]||= {} style_options[:time_select_wrapper]||= {} style_options[:collection_select_html]||= {} style_options[:collection_select_wrapper]||= {} style_options[:collection_check_boxes_item_html]||= {} style_options[:collection_check_boxes_item_wrapper]||= {} # Merge with default input selector style_options[:number_field_html] = style_options[:input_html].merge(style_options[:number_field_html]) style_options[:number_field_wrapper] = style_options[:input_wrapper].merge(style_options[:number_field_wrapper]) style_options[:date_select_html] = style_options[:input_html].merge(style_options[:date_select_html]) style_options[:date_select_wrapper] = style_options[:input_wrapper].merge(style_options[:date_select_wrapper]) style_options[:collection_select_html] = style_options[:input_html].merge(style_options[:collection_select_html]) style_options[:collection_select_wrapper] = style_options[:input_wrapper].merge(style_options[:collection_select_wrapper]) style_options[:collection_check_boxes_item_html] = style_options[:input_html].merge(style_options[:collection_check_boxes_item_html]) style_options[:collection_check_boxes_item_wrapper] = style_options[:input_wrapper].merge(style_options[:collection_check_boxes_item_wrapper]) # Here comes the logic... # Javascript element id field_id = @object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/,"_").sub(/_$/,"") + "_" + attribute.to_s @template.content_tag("div", {id: field_id, class: 'col-12'}) do @template.content_tag("div", {class: 'form-row'}) do self.fields_for(attribute, @object.send(attribute.to_s) || @object.send("build_" + attribute.to_s)) do |f| # Rule Select @template.content_tag("div", style_options[:field_html].merge(class: 'col-12 mb-1') ) do select_output = f.collection_select(:rule, available_periods, lambda { |v| return v}, lambda { |v| I18n.t("schedulable.rules.#{v}", default: v.capitalize) }, {include_blank: false}, style_options[:collection_select_html]) content_wrap(@template, select_output, style_options[:collection_select_wrapper]) end << # Weekly Checkboxes @template.content_tag("div", style_options[:field_html].merge({class: 'col-12 mb-2 mt-2', data: {group: 'weekly'}})) do content_wrap(@template, f.label(:day), style_options[:label_wrapper]) << @template.content_tag("div", class: 'row row-days') do f.collection_check_boxes(:day, weekdays, lambda { |v| return v}, lambda { |v| (day_labels[v]).html_safe}) do |cb| check_box_output = cb.check_box(style_options[:collection_check_boxes_item_html]) text = cb.text nested_output = cb.label({class: 'btn btn-lg btn-outline-success', style: 'width: 100%'}) do |l| check_box_output + text end wrap = content_wrap(@template, nested_output, style_options[:collection_check_boxes_item_wrapper]) content_wrap(@template, wrap, tag: 'div', class: 'col') end end end << # Monthly Checkboxes @template.content_tag("div", style_options[:field_html].merge({data: {group: 'monthly'}})) do f.fields_for :day_of_week, OpenStruct.new(f.object.day_of_week || {}) do |db| content_wrap(@template, f.label(:day_of_week), style_options[:label_wrapper]) << @template.content_tag("div", nil, style: 'min-width: 280px; display: table') do @template.content_tag("div", nil, style: 'display: table-row') do @template.content_tag("span", nil, style: 'display: table-cell;') << ['1st', '2nd', '3rd', '4th', 'last'].reduce(''.html_safe) { | content, item | content << @template.content_tag("span", I18n.t("schedulable.monthly_week_names.#{item}", default: item.to_s), style: 'display: table-cell; text-align: center') } end << weekdays.reduce(''.html_safe) do | content, weekday | content << @template.content_tag("div", nil, style: 'display: table-row') do @template.content_tag("span", day_labels[weekday] || weekday, style: 'display: table-cell') << db.collection_check_boxes(weekday.to_sym, [1, 2, 3, 4, -1], lambda { |i| i} , lambda { |i| "&nbsp;".html_safe}, checked: db.object.send(weekday)) do |cb| @template.content_tag("span", style: 'display: table-cell; text-align: center') { cb.check_box() } end end end end end end << # StartTime Select @template.content_tag("div", class: 'form-group col-md-6', data: {group: 'singular,daily,weekly,monthly'}) do content_wrap(@template, f.label('Start date', style_options[:label_html]), style_options[:label_wrapper]) << @template.content_tag("div", class: 'input-group') do content_wrap(@template, f.text_field(:start_time_date, class: 'form-control datepicker')) << @template.content_tag("div", class: 'input-group-append') do '<button type="button" class="btn btn-primary"><i class="icon-calendar"></i></button>'.html_safe end end end << @template.content_tag("div", class: 'form-group col-md-6', data: {group: 'singular,daily,weekly,monthly'}) do content_wrap(@template, f.label('Time', style_options[:label_html]), style_options[:label_wrapper]) << @template.content_tag("div", class: 'input-group') do content_wrap(@template, f.text_field(:start_time_time, class: 'form-control')) << @template.content_tag("div", class: 'input-group-append') do '<button type="button" class="btn btn-primary"><i class="icon-clock"></i></button>'.html_safe end end end << # EndTime Select @template.content_tag("div", class: 'form-group col-md-6', data: {group: 'singular,daily,weekly,monthly'}) do content_wrap(@template, f.label('End date', style_options[:label_html]), style_options[:label_wrapper]) << @template.content_tag("div", class: 'input-group') do content_wrap(@template, f.text_field(:end_time_date, class: 'form-control datepicker')) << @template.content_tag("div", class: 'input-group-append') do '<button type="button" class="btn btn-primary"><i class="icon-calendar"></i></button>'.html_safe end end end << @template.content_tag("div", class: 'form-group col-md-6', data: {group: 'singular,daily,weekly,monthly'}) do content_wrap(@template, f.label('Time', style_options[:label_html]), style_options[:label_wrapper]) << @template.content_tag("div", class: 'input-group') do content_wrap(@template, f.text_field(:end_time_time, class: 'form-control')) << @template.content_tag("div", class: 'input-group-append') do '<button type="button" class="btn btn-primary"><i class="icon-clock"></i></button>'.html_safe end end end << # Optional Fields... # Interval Number Field (if input_options[:interval] @template.content_tag("div", style_options[:field_html].merge({data: {group: 'daily,weekly,monthly'}})) do content_wrap(@template, f.label(:interval, style_options[:label_html]), style_options[:label_wrapper]) << content_wrap(@template, f.number_field(:interval, style_options[:number_field_html]), style_options[:number_field_wrapper]) end else f.hidden_field(:interval, value: 1) end) << # Until Date Time Select (if input_options[:until] # Effective date Select @template.content_tag("div", class: 'form-group col-md-6', data: {group: 'singular,daily,weekly,monthly'}) do content_wrap(@template, f.label('Repeat until date', style_options[:label_html]), style_options[:label_wrapper]) << @template.content_tag("div", class: 'input-group') do content_wrap(@template, f.text_field(:until_date, class: 'form-control datepicker')) << @template.content_tag("div", class: 'input-group-append') do '<button type="button" class="btn btn-primary"><i class="icon-calendar"></i></button>'.html_safe end end end << @template.content_tag("div", class: 'form-group col-md-6', data: {group: 'singular,daily,weekly,monthly'}) do content_wrap(@template, f.label('Time', style_options[:label_html]), style_options[:label_wrapper]) << @template.content_tag("div", class: 'input-group') do content_wrap(@template, f.text_field(:until_time, class: 'form-control')) << @template.content_tag("div", class: 'input-group-append') do '<button type="button" class="btn btn-primary"><i class="icon-clock"></i></button>'.html_safe end end end else f.hidden_field(:until, value: nil) end) << # Count Number Field if input_options[:count] @template.content_tag("div", style_options[:field_html].merge({data: {group: 'daily,weekly,monthly'}})) do content_wrap(@template, f.label(:count, style_options[:label_html]), style_options[:label_wrapper]) << content_wrap(@template, f.number_field(:count, style_options[:number_field_html]), style_options[:number_field_wrapper]) end else f.hidden_field(:count, value: 0) end << # Effective date Select @template.content_tag("div", class: 'form-group col-md-6', data: {group: 'singular,daily,weekly,monthly'}) do content_wrap(@template, f.label('Effective date', style_options[:label_html]), style_options[:label_wrapper]) << @template.content_tag("div", class: 'input-group') do content_wrap(@template, f.text_field(:effective_time_date, class: 'form-control datepicker')) << @template.content_tag("div", class: 'input-group-append') do '<button type="button" class="btn btn-primary"><i class="icon-calendar"></i></button>'.html_safe end end end << @template.content_tag("div", class: 'form-group col-md-6', data: {group: 'singular,daily,weekly,monthly'}) do content_wrap(@template, f.label('Time', style_options[:label_html]), style_options[:label_wrapper]) << @template.content_tag("div", class: 'input-group') do content_wrap(@template, f.text_field(:effective_time_time, class: 'form-control')) << @template.content_tag("div", class: 'input-group-append') do '<button type="button" class="btn btn-primary"><i class="icon-clock"></i></button>'.html_safe end end end end end end << # Javascript template.javascript_tag( "(function() {" << " var container = document.querySelectorAll('##{field_id}'); container = container[container.length - 1]; " << " var select = container.querySelector(\"select[name*='rule']\"); " << " function update() {" << " var value = this.value;" << " [].slice.call(container.querySelectorAll(\"*[data-group]\")).forEach(function(elem) { " << " var groups = elem.getAttribute('data-group').split(',');" << " if (groups.indexOf(value) >= 0) {" << " elem.style.display = ''" << " } else {" << " elem.style.display = 'none'" << " }" << " });" << " }" << " if (typeof jQuery !== 'undefined') { jQuery(select).on('change', update); } else { select.addEventListener('change', update); }" << " update.call(select);" << " document.querySelectorAll('.row-days input[checked]').forEach(function(element){" << " element.closest('label.btn').classList.add('active');" << " });" << " function toggleActiveClass(event){ event.target.closest('label.btn').classList.toggle('active');} " << " document.querySelectorAll('input[type=checkbox]').forEach(function(element){" << " element.addEventListener('change', toggleActiveClass )" << " });" << "})()" ) end private def content_wrap(template, content, options = nil) if options.present? && options.has_key?(:tag) template.content_tag(options[:tag], content, options.except(:tag)) else content end end end end end
1a6f7847a17fdf8d93ea1ab0da7a2a6a07d54989
[ "Ruby" ]
7
Ruby
georgepalmer/schedulable
d29ea6a6c7e75167aa84aa2b3bafefdc57b61031
a3f4fec209d95d452fca0e034a79a6e40d07cd63
refs/heads/master
<repo_name>BurgerLUA/burgerbaseweapons<file_sep>/lua/burgerbase/modules/css/shared/css_convars.lua BURGERBASE:INIT_MassInclude("burgerbase/modules/css/shared/convars/","shared",false)<file_sep>/lua/autorun/sh_burger_init.lua BURGERBASE = {} function BURGERBASE:INIT_Initialize() print("[BURGERBASE] Initializing BURGERBASE....") BURGERBASE:INIT_MassInclude("burgerbase/core/","shared",false) BURGERBASE:INIT_MassInclude("burgerbase/modules/","shared",true,1) end function BURGERBASE:INIT_MassInclude(folder,realm,includesub,times) if not times then times = 1 end local Files, Folders = file.Find(folder .. "*","LUA") local num,filename for num,filename in pairs(Files) do if realm == "shared" or realm == "client" then if CLIENT then print("[BURGERBASE] Attempting to include file:",folder .. filename) end include(folder .. filename) AddCSLuaFile(folder .. filename) end if realm == "shared" or realm == "server" then if SERVER then print("[BURGERBASE] Attempting to include file:",folder .. filename) include(folder .. filename) end end end if includesub and times >= 1 then times = times - 1 local num,filename for num,foldername in pairs(Folders) do BURGERBASE:INIT_MassInclude(folder .. foldername .. "/",realm,includesub,times) end end end BURGERBASE.AmmoTypes = {} function BURGERBASE:AddAmmoType(realname,ammodata) local CallName = ammodata.name game.AddAmmoType(ammodata) BURGERBASE.AmmoTypes[CallName] = realname print("Adding ammo type " .. CallName) if CLIENT then language.Add(CallName .. "_ammo",realname) end end function BURGERBASE:GetStoredAmmoType(callname) return BURGERBASE.AmmoTypes[callname] end BURGERBASE:AddAmmoType("12 Gauge Buckshot",{ name = "bb_12gauge", dmgtype = DMG_BULLET, }) BURGERBASE:AddAmmoType("12 Gauge Slug",{ name = "bb_12gaugeslug", dmgtype = DMG_BULLET, }) BURGERBASE:AddAmmoType("5.7mm",{ name = "bb_57mm", dmgtype = DMG_BULLET, }) BURGERBASE:AddAmmoType(".45 ACP",{ name = "bb_45acp", dmgtype = DMG_BULLET, }) BURGERBASE:AddAmmoType("9mm",{ name = "bb_9mm", dmgtype = DMG_BULLET, }) BURGERBASE:AddAmmoType(".50 AE",{ name = "bb_50ae", dmgtype = DMG_BULLET, }) BURGERBASE:AddAmmoType("5.56mm",{ name = "bb_556mm", dmgtype = DMG_BULLET, }) BURGERBASE:AddAmmoType("7.62mm",{ name = "bb_762mm", dmgtype = DMG_BULLET, }) BURGERBASE:AddAmmoType(".338",{ name = "bb_338", dmgtype = DMG_BULLET, }) BURGERBASE:AddAmmoType(".357 SIG",{ name = "bb_357sig", dmgtype = DMG_BULLET, }) BURGERBASE:AddAmmoType("HE Grenade",{ name = "bb_hegrenade", dmgtype = DMG_BLAST, }) BURGERBASE:AddAmmoType("Flash Grenade",{ name = "bb_flashgrenade", dmgtype = DMG_BLAST, }) BURGERBASE:AddAmmoType("Smoke Grenade",{ name = "bb_smokegrenade", dmgtype = DMG_BLAST, }) BURGERBASE:INIT_Initialize()<file_sep>/lua/burgerbase/modules/css/css_loadfiles.lua BURGERBASE:INIT_MassInclude("burgerbase/modules/css/shared/","shared",false) BURGERBASE:INIT_MassInclude("burgerbase/modules/css/server/","server",false) BURGERBASE:INIT_MassInclude("burgerbase/modules/css/client/","client",false)<file_sep>/lua/weapons/weapon_hl2_stunstick.lua if CLIENT then killicon.AddFont( "weapon_hl2_stunstick", "HL2MPTypeDeath", "!", Color( 255, 80, 0, 255 ) ) end SWEP.Category = "BurgerBase: Half Life 2" SWEP.PrintName = "Stunstick" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Melee" SWEP.Cost = 0 SWEP.CSSMoveSpeed = 240 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 0 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/c_stunstick.mdl" SWEP.WorldModel = "models/weapons/w_stunbaton.mdl" SWEP.VModelFlip = false SWEP.HoldType = "melee" game.AddAmmoType({name = "smod_metal"}) if CLIENT then language.Add("smod_metal_ammo","Metal") end SWEP.Primary.Damage = 55 SWEP.Primary.NumShots = 1 SWEP.Primary.ClipSize = 100 SWEP.Primary.SpareClip = 0 SWEP.Primary.Delay = 0.6 SWEP.Primary.Ammo = "smod_metal" SWEP.Primary.Automatic = true SWEP.Secondary.Damage = 0 SWEP.Secondary.NumShots = 1 SWEP.Secondary.ClipSize = -1 SWEP.Secondary.SpareClip = -1 SWEP.Secondary.Delay = 1 SWEP.Secondary.Ammo = "none" SWEP.Secondary.Automatic = false SWEP.RecoilMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 1 SWEP.HasCrosshair = false SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = false SWEP.MeleeSoundMiss = Sound("Weapon_StunStick.Melee_Miss") SWEP.MeleeSoundWallHit = Sound("Weapon_StunStick.Melee_HitWorld") SWEP.MeleeSoundFleshSmall = Sound("Weapon_StunStick.Melee_Hit") SWEP.MeleeSoundFleshLarge = Sound("Weapon_StunStick.Melee_Hit") SWEP.IronSightTime = 0.125 SWEP.IronSightsPos = Vector(-10, -10, 5) SWEP.IronSightsAng = Vector(0, 0, -45) SWEP.AddFOV = 10 SWEP.EnableBlocking = true SWEP.DamageFalloff = 40 SWEP.MeleeDamageType = DMG_SHOCK SWEP.MeleeDelay = 0 SWEP.MeleeBlockReduction = 0.25 SWEP.HasDurability = true SWEP.DurabilityPerHit = -5 SWEP.MeleeBlockReduction = 0.40 function SWEP:MeleeRange() return 40 end function SWEP:MeleeSize() return 24 end function SWEP:PrimaryAttack() if self:IsUsing() then return end if self:GetNextPrimaryFire() > CurTime() then return end if self.Owner:KeyDown(IN_ATTACK2) then return end self.Owner:SetAnimation(PLAYER_ATTACK1) local Delay = self.Primary.Delay local Damage = self.Primary.Damage*0.75 + (self.Primary.Damage*0.25*self:Clip1()*0.01) local Victim = self:StartSwing(Damage) if Victim and Victim ~= NULL then self:SendWeaponAnim(ACT_VM_HITCENTER) else self:SendWeaponAnim(ACT_VM_MISSCENTER) Delay = Delay*1.25 end self:SetNextPrimaryFire(CurTime() + Delay) self:SetNextSecondaryFire(CurTime() + Delay) end function SWEP:SpareThink() if self.Owner:KeyDown(IN_ATTACK2) then self.CSSMoveSpeed = 240*0.25 else self.CSSMoveSpeed = 240 end end function SWEP:SecondaryAttack() end function SWEP:Reload() --PrintTable(GetActivities(self)) end <file_sep>/lua/weapons/weapon_burger_cs_m4.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_m4", "csd", "w", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/m4a1") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "M4A1" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 3100 SWEP.CSSMoveSpeed = 230 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Description = "Your classic automatic rifle with a lot of stopping power. Comes with a silencer." SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/cstrike/c_rif_m4a1.mdl" SWEP.WorldModel = "models/weapons/w_rif_m4a1.mdl" SWEP.VModelFlip = false SWEP.HoldType = "ar2" SWEP.Primary.Damage = 33 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_M4A1.Single") SWEP.Primary.Cone = 0.005 SWEP.Primary.ClipSize = 30 SWEP.Primary.SpareClip = 90 SWEP.Primary.Delay = 0.09 --1/(666/60) SWEP.Primary.Ammo = "bb_556mm" SWEP.Primary.Automatic = true SWEP.WorldModel1 = "models/weapons/w_rif_m4a1.mdl" SWEP.WorldModel2 = "models/weapons/w_rif_m4a1_silencer.mdl" SWEP.Secondary.Sound = Sound("Weapon_M4A1.Silenced") SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 0.5 SWEP.RecoilSpeedMul = 1.25 SWEP.MoveConeMul = 1.25 SWEP.HeatMul = 1 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 0.75 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = true SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = false SWEP.DamageFalloff = 2000 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = false SWEP.IronSightTime = 0.5 SWEP.ZoomTime = 0.5 SWEP.IronSightsPos = Vector(-4.481, 0, 1) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(-2.01, -5, 0.602) SWEP.IronRunAng = Vector(-5, 15, -7.739) SWEP.IronMeleePos = Vector(3.417, -10, -13.87) SWEP.IronMeleeAng = Vector(-9.146, 70, -70) <file_sep>/lua/weapons/weapon_hl2_crossbow.lua if CLIENT then killicon.AddFont( "weapon_hl2_crossbow", "HL2MPTypeDeath", "1", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/sg552") end SWEP.Category = "BurgerBase: Half Life 2" SWEP.PrintName = "Crossbow" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 3500 SWEP.CSSMoveSpeed = 200 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/c_crossbow.mdl" SWEP.WorldModel = "models/weapons/w_crossbow.mdl" SWEP.VModelFlip = false SWEP.HoldType = "crossbow" SWEP.Primary.Damage = 100 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("weapons/crossbow/fire1.wav") SWEP.Primary.Cone = 0 SWEP.Primary.ClipSize = -1 SWEP.Primary.SpareClip = 36 SWEP.Primary.Delay = 0.5 SWEP.Primary.Ammo = "XBowBolt" SWEP.Primary.Automatic = false SWEP.RecoilMul = 0.5 SWEP.SideRecoilMul = 0.5 SWEP.MoveConeMul = 1 SWEP.HeatMul = 1 SWEP.HasScope = true SWEP.ZoomAmount = 7 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = true SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = false SWEP.HasDryFire = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = false SWEP.HasIronSights = false SWEP.EnableIronCross = false SWEP.HasGoodSights = false SWEP.IronSightTime = 0.25 SWEP.ZoomDelay = 0.125 SWEP.ZoomTime = 0 SWEP.IronSightsPos = Vector(-8, 0, 2.079) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(6.119, 0, -1.8) SWEP.IronRunAng = Vector(0, 28.141, 0) SWEP.IronMeleePos = Vector(-7.961, 0, -12.2) SWEP.IronMeleeAng = Vector(33.769, 0, 0) --[[ function SWEP:ShootBullet(Damage,Shots,Cone,Source,Direction,Source) self:ThrowObject("crossbow_bolt",4000) self:SendWeaponAnim(ACT_VM_RELOAD) self.Owner:SetAnimation(PLAYER_RELOAD) self.Owner:EmitSound("weapons/crossbow/reload1.wav") end --]] local ArrowModel = Model("models/crossbow_bolt.mdl") local ArrowSound = Sound("fofgunsounds/bow/hit1.wav") SWEP.UseSpecialProjectile = true SWEP.UseMuzzle = true SWEP.BulletAngOffset = Angle(-1,0,0) SWEP.HasHL2Pump = true SWEP.PumpAnimation = ACT_VM_RELOAD SWEP.PumpSound = Sound("weapons/crossbow/reload1.wav") function SWEP:ModBoltDelay() return 2.5 end function SWEP:ModProjectileTable(datatable) datatable.direction = datatable.direction*3000 datatable.hullsize = 4 datatable.resistance = (datatable.direction*0.05) + Vector(0,0,100) datatable.dietime = CurTime() + 10 datatable.id = "crossbow_bolt" return datatable end -- Register Bullet local datatable = {} datatable.drawfunction = function(datatable) if datatable.special and datatable.special ~= NULL then datatable.special:SetPos(datatable.pos) datatable.special:SetAngles( datatable.direction:GetNormalized():Angle() ) datatable.special:DrawModel() else datatable.special = ClientsideModel(ArrowModel, RENDERGROUP_OPAQUE ) end end datatable.diefunction = function(datatable) if CLIENT then if datatable.special and datatable.special ~= NULL then datatable.special:Remove() end end end datatable.hitfunction = function(datatable,traceresult) local Victim = traceresult.Entity local Attacker = datatable.owner local Inflictor = datatable.weapon if not IsValid(Attacker) then Attacker = Victim end if not IsValid(Inflictor) then Inflictor = Attacker end if IsValid(Attacker) and IsValid(Victim) and IsValid(Inflictor) then local DmgInfo = DamageInfo() DmgInfo:SetDamage( datatable.damage ) DmgInfo:SetAttacker( Attacker ) DmgInfo:SetInflictor( Inflictor ) DmgInfo:SetDamageForce( datatable.direction:GetNormalized() ) DmgInfo:SetDamagePosition( datatable.pos ) DmgInfo:SetDamageType( DMG_BULLET ) traceresult.Entity:DispatchTraceAttack( DmgInfo, traceresult ) end if SERVER and traceresult.HitWorld then local CreatedAmmo = BURGERBASE_FUNC_CreateAmmo(traceresult.HitPos - datatable.direction:GetNormalized()*10,datatable.direction:GetNormalized():Angle(),"XBowBolt",1,ArrowModel) local Phys = CreatedAmmo:GetPhysicsObject() CreatedAmmo:EmitSound(ArrowSound) SafeRemoveEntityDelayed(CreatedAmmo,30) end end BURGERBASE_RegisterProjectile("crossbow_bolt",datatable)<file_sep>/lua/weapons/weapon_hl2_spas.lua if CLIENT then killicon.AddFont( "weapon_hl2_spas", "HL2MPTypeDeath", "0", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/m3") end SWEP.Category = "BurgerBase: Half Life 2" SWEP.PrintName = "Shotgun" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Cost = 0 SWEP.CSSMoveSpeed = 230 SWEP.Slot = 2 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/c_shotgun.mdl" SWEP.WorldModel = "models/weapons/w_shotgun.mdl" SWEP.VModelFlip = false SWEP.HoldType = "ar2" SWEP.Primary.Damage = (56*3) / 7 SWEP.Primary.NumShots = 7 SWEP.Primary.Sound = Sound("weapons/shotgun/shotgun_fire7.wav") SWEP.Primary.Cone = 0.05 SWEP.Primary.ClipSize = 6 SWEP.Primary.SpareClip = 30 SWEP.Primary.Delay = 0.3 SWEP.Primary.Ammo = "Buckshot" SWEP.Primary.Automatic = true SWEP.ReloadSound = Sound("weapons/shotgun/shotgun_reload3.wav") SWEP.BurstSound = Sound("weapons/shotgun/shotgun_dbl_fire.wav") SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 0.5 SWEP.RecoilSpeedMul = 0.75 SWEP.MoveConeMul = 0.5 SWEP.HeatMul = 0.5 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.BurstOverride = 2 SWEP.BurstSpeedOverride = 0.1 SWEP.BurstHeatMul = 1.5 SWEP.HasScope = false SWEP.ZoomAmount = 0.25 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = true SWEP.HasBoltAction = false SWEP.HasBurstFire = true SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = true SWEP.HasFirstShotAccurate = false SWEP.DamageFalloff = 200 SWEP.Primary.Range = 400 SWEP.HasHL2Pump = true SWEP.PumpSound = Sound("weapons/shotgun/shotgun_cock.wav") SWEP.PenetrationLossScale = 0.5 SWEP.CanShootWhileSprinting = true SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.25 SWEP.IronSightsPos = Vector(-8.24, 0, 1.72) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(0, 0, 0) SWEP.IronRunAng = Vector(0, 26.03, 0) SWEP.IronMeleePos = Vector(0, -7.035, -3.619) SWEP.IronMeleeAng = Vector(-2.814, 42.21, -42.211) --[[ 1: act = 181 actname = ACT_VM_PRIMARYATTACK id = 1 2: act = 182 actname = ACT_VM_SECONDARYATTACK id = 2 3: act = 172 actname = ACT_VM_DRAW id = 3 4: act = 173 actname = ACT_VM_HOLSTER id = 4 5: act = 267 actname = ACT_SHOTGUN_RELOAD_START id = 5 6: act = 183 actname = ACT_VM_RELOAD id = 6 7: act = 268 actname = ACT_SHOTGUN_RELOAD_FINISH id = 7 8: act = 269 actname = ACT_SHOTGUN_PUMP id = 8 9: act = 186 actname = ACT_VM_DRYFIRE id = 9 10: act = 204 actname = ACT_VM_IDLE_LOWERED id = 10 11: act = 205 actname = ACT_VM_LOWERED_TO_IDLE id = 11 12: act = 203 actname = ACT_VM_IDLE_TO_LOWERED id = 12 13: act = 433 actname = ACT_VM_SPRINT_IDLE id = 13 14: act = 287 actname = ACT_RANGE_ATTACK_SHOTGUN id = 14 -------------------- 0 = idle01 1 = fire01 2 = altfire 3 = draw 4 = holster 5 = reload1 6 = reload2 7 = reload3 8 = pump 9 = dryfire 10 = lowered 11 = lowered_to_idle 12 = idle_to_lowered 13 = sprint_idle 14 = fire --]] <file_sep>/lua/effects/effect_burger_core_bullet.lua -- Copied from garry's tooltracer EFFECT.BulletMats = {} EFFECT.BulletMats[1] = Material( "effects/spark" ) EFFECT.BulletMats[2] = Material( "effects/gunshiptracer") EFFECT.BulletMats[3] = Material( "effects/laser_tracer" ) EFFECT.SmokeTrailMat = Material("trails/smoke") EFFECT.TubeTrailMat = Material("trails/tube") EFFECT.SmokeSpriteMat = Material("particle/smokestack") EFFECT.TubeSpriteMat = Material("particle/warp1_warp") --EFFECT.SmokeParticle = Material("particle/particle_smoke_dust") function EFFECT:Init( data ) local Magnitude = data:GetMagnitude() local Range = data:GetRadius() self.Damage = Magnitude self.Position = data:GetStart() self.WeaponEnt = data:GetEntity() self.Attachment = data:GetAttachment() self.StartPos = self:GetTracerShootPos( self.Position, self.WeaponEnt, self.Attachment ) -- Should return normal position if no weapon self.EndPos = data:GetOrigin() self.Direction = (self.StartPos - self.EndPos):GetNormalized() self.Distance = self.StartPos:Distance(self.EndPos) self.Width = ((Magnitude*50)^0.30)*0.3 self.Length = (Range*0.03)^1 self.DamageType = data:GetDamageType() self.SmokePercent = 0 local Ratio = self.Length/self.Width self.BulletSpeed = ( math.Clamp(Ratio * 100,2000,6000) + 2000 ) self.FadeTime = Range self.MaxFade = BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damagefalloffscale"):GetFloat() self.PositionPercent = -(self.Length/self.Distance) self:SetRenderBoundsWS( self.StartPos, self.EndPos ) self.SmokeLifeTime = self.Damage/20 -- Copied from Garrysmod Arrow Widget if self.WeaponEnt and self.WeaponEnt ~= NULL and (!self.WeaponEnt:IsWeapon() or !self.WeaponEnt:IsCarriedByLocalPlayer()) then local Distance, Position, WhatIsThis = util.DistanceToLine(self.StartPos,self.EndPos,EyePos()) local SoundSize = 256*self.Width if Distance <= SoundSize then local VolumeMod = 1 - (Distance/SoundSize) sound.Play("Bullets.DefaultNearmiss",Position,75,100,VolumeMod) end end local Lifetime = self.Distance/self.BulletSpeed self.DieTime = CurTime() + math.max(Lifetime,self.SmokeLifeTime) end function EFFECT:Think() self.PositionPercent = self.PositionPercent + (self.BulletSpeed/self.Distance)*FrameTime() self.SmokePercent = self.SmokePercent + FrameTime()/self.SmokeLifeTime return self.DieTime > CurTime() end function EFFECT:Render() local DistanceTraveled = self.PositionPercent * self.Distance local AlphaMath = math.Clamp(math.min( (2) - (DistanceTraveled/self.FadeTime),1),self.MaxFade,1) local MinPos = LerpVector(math.Clamp(self.PositionPercent,0,1),self.StartPos,self.EndPos) local SmokeMinPos = LerpVector(math.Clamp(self.PositionPercent - 1,0,1),self.StartPos,self.EndPos) local ConvertMath = ( (self.Length*AlphaMath)/self.Distance ) local MaxPos = LerpVector(math.Clamp( (self.PositionPercent + ConvertMath),0,1),self.StartPos,self.EndPos) if self.PositionPercent <= 1 then if self.BulletMats[self.DamageType] then render.SetMaterial( self.BulletMats[self.DamageType] ) else render.SetMaterial( self.BulletMats[DMG_BULLET] ) end render.DrawBeam( MinPos , MaxPos, self.Width,0, 1, Color(255,255,255,255) ) end if self.DamageType == 1 then local SmokeMul =(1 - self.SmokePercent)/(2*self.Width) local SmokeOffset = Vector(0,0, self.SmokePercent )*1 local Size = self.Length + self.Width local LightColor = render.GetLightColor( EyePos() ) local Lightness = math.min(150,math.max(LightColor.x*255,LightColor.y*255,LightColor.z*255)) local SmokeAlpha = 100 * math.max(0,1-self.SmokePercent) local SpriteSize = (Size*0.075)*self.SmokePercent local SmokeColor = Color(Lightness,Lightness,Lightness,SmokeAlpha) render.SetMaterial( self.SmokeTrailMat ) render.DrawBeam( self.StartPos + SmokeOffset, MaxPos + SmokeOffset, SpriteSize,0, 1, SmokeColor) render.SetMaterial( self.SmokeSpriteMat ) render.DrawSprite( self.StartPos, SpriteSize*2, SpriteSize*2, SmokeColor ) end end <file_sep>/lua/weapons/weapon_burger_cs_deserteagle.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_deserteagle", "csd", "f", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/deserteagle") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "Desert Eagle" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Secondary" SWEP.Cost = 650 SWEP.CSSMoveSpeed = 250 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Description = "Accurate high-damage handcannon. Headshots are usually fatal." SWEP.Slot = 1 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/cstrike/c_pist_deagle.mdl" SWEP.WorldModel = "models/weapons/w_pist_deagle.mdl" SWEP.VModelFlip = false SWEP.HoldType = "revolver" SWEP.Primary.Damage = 54 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_DEagle.Single") SWEP.Primary.Cone = 0.001 SWEP.Primary.ClipSize = 7 SWEP.Primary.SpareClip = 35 SWEP.Primary.Delay = 0.225 SWEP.Primary.Ammo = "bb_50ae" SWEP.Primary.Automatic = false SWEP.RecoilMul = 2 SWEP.SideRecoilMul = 1 SWEP.RecoilSpeedMul = 0.8 SWEP.MoveConeMul = 0.75 SWEP.HeatMul = 3 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 0.75 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = true SWEP.DamageFalloff = 3000 SWEP.CanShootWhileSprinting = true SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.25 SWEP.ZoomTime = 0.25 SWEP.IronSightsPos = Vector(-6.361, 10, 1.5) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(0, 0, 0) SWEP.IronRunAng = Vector(0, 0, 0) SWEP.IronMeleePos = Vector(-6.433, -13.468, -20) SWEP.IronMeleeAng = Vector(70, 0, 0) <file_sep>/lua/weapons/weapon_hl2_pistol.lua if CLIENT then killicon.AddFont( "weapon_hl2_pistol", "HL2MPTypeDeath", "-", Color( 255, 80, 0, 255 ) ) --SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/usp45") end SWEP.Category = "BurgerBase: Half Life 2" SWEP.PrintName = "Pistol" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Secondary" SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Cost = 0 SWEP.CSSMoveSpeed = 230 SWEP.Slot = 1 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/c_pistol.mdl" SWEP.WorldModel = "models/weapons/w_pistol.mdl" SWEP.VModelFlip = false SWEP.HoldType = "revolver" SWEP.Primary.Damage = 30 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("weapons/pistol/pistol_fire2.wav") SWEP.Primary.Cone = 0.005 SWEP.Primary.ClipSize = 18 SWEP.Primary.SpareClip = 150 SWEP.Primary.Delay = 0.1 SWEP.Primary.Ammo = "pistol" SWEP.Primary.Automatic = false SWEP.ReloadSound = Sound("weapons/pistol/pistol_reload1.wav") SWEP.RecoilMul = 2 SWEP.SideRecoilMul = 1 SWEP.RecoilSpeedMul = 0.75 SWEP.MoveConeMul = 0.5 SWEP.HeatMul = 0.25 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 0.75 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasDryFire = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = true SWEP.DamageFalloff = 1000 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.25 SWEP.IronSightsPos = Vector(-2.401, 0, 1.919) SWEP.IronSightsAng = Vector(0, 0, -70) SWEP.IronMeleePos = Vector(-3.481, 0, 3) SWEP.IronMeleeAng = Vector(15, 0, 22.513) SWEP.IronRunPos = Vector(0,0,0) SWEP.IronRunAng = Vector(0,0,0) <file_sep>/lua/weapons/weapon_burger_cs_p228.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_p228", "csd", "y", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/p228") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "P228" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Secondary" SWEP.Cost = 600 SWEP.CSSMoveSpeed = 250 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 1 SWEP.SlotPos = 1 SWEP.Description = "Inaccurate pistol that deals high damage. Headshots are fatal." SWEP.ViewModel = "models/weapons/cstrike/c_pist_p228.mdl" SWEP.WorldModel = "models/weapons/w_pist_p228.mdl" SWEP.VModelFlip = false SWEP.HoldType = "revolver" SWEP.Primary.Damage = 48 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_P228.Single") SWEP.Primary.Cone = 0.01 SWEP.Primary.ClipSize = 13 SWEP.Primary.SpareClip = 52 SWEP.Primary.Delay = 0.15 --1/(400/60) SWEP.Primary.Ammo = "bb_357sig" SWEP.Primary.Automatic = false SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 0.25 SWEP.RecoilSpeedMul = 1.25 SWEP.MoveConeMul = 0.5 SWEP.HeatMul = 0.5 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 0.75 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = false SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = true SWEP.DamageFalloff = 2000 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.25 SWEP.ZoomTime = 0.5 SWEP.IronSightsPos = Vector(-5.961, 0, 1.759) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(0, 0, 0) SWEP.IronRunAng = Vector(0, 0, 0) SWEP.IronMeleePos = Vector(-5.801, -13.468, -20) SWEP.IronMeleeAng = Vector(70, 0, 0)<file_sep>/lua/weapons/weapon_burger_cs_para.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_para", "csd", "z", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/m249") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "M249 PARA" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 5750 SWEP.CSSMoveSpeed = 220 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.Description = "Heavy machinegun that's good for clearing rooms." SWEP.ViewModel = "models/weapons/cstrike/c_mach_m249para.mdl" SWEP.WorldModel = "models/weapons/w_mach_m249para.mdl" SWEP.VModelFlip = false SWEP.HoldType = "ar2" SWEP.Primary.Damage = 35 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_M249.Single") SWEP.Primary.Cone = 0.0075 SWEP.Primary.ClipSize = 100 SWEP.Primary.SpareClip = 200 SWEP.Primary.Delay = 0.08 --1/(750/60) SWEP.Primary.Ammo = "bb_556mm" SWEP.Primary.Automatic = true SWEP.RecoilMul = 1.25 SWEP.SideRecoilMul = 0.25 SWEP.RecoilSpeedMul = 1.25 SWEP.MoveConeMul = 3 SWEP.HeatMul = 0.5 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 0.5 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = true SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = false SWEP.DamageFalloff = 2500 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = false SWEP.IronSightTime = 0.5 SWEP.ZoomTime = 0.5 SWEP.IronSightsPos = Vector(-5.961, 0, 2.279) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(-2.01, -5, 0.602) SWEP.IronRunAng = Vector(-5, 15, -7.739) SWEP.IronMeleePos = Vector(3.417, -10, -13.87) SWEP.IronMeleeAng = Vector(-9.146, 70, -70)<file_sep>/lua/burgerbase/core/client/menus/core.lua BURGERBASE:FUNC_MENU_AddTitle("Core - Weapon Settings",false) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_damagescale",false,"Weapon Damage Scale",2,2) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_recoilscale",false,"Recoil Scale",2,2) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_baseconescale",false,"Base Cone Scale",2,2) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_movementconescale",false,"Movement Cone Scale",2,2) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_heatconescale",false,"Recoil Cone Scale",2,2) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_damagefalloffscale",false,"Damage Falloff Scale",1,2) BURGERBASE:FUNC_MENU_AddTitle("Core - Damage Settings",false) BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_damage_enable",false,"Enable Custom Damage") BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_damage_sandboxfix",false,"Sandbox Fix") BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_damage_bodyscale",false,"Torso Damage Scale",5,2) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_damage_legscale",false,"Leg Damage Scale",5,2) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_damage_armscale",false,"Arm Damage Scale",5,2) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_damage_headscale",false,"Head Damage Scale",5,2) BURGERBASE:FUNC_MENU_AddTitle("Core - Penetration Settings",false) BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_enable_penetration",false,"Enable Bullet Penetration") BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_penetration_scale",false,"Penetration Scale",5,2) BURGERBASE:FUNC_MENU_AddTitle("Core - Spawning Settings",false) BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_ammo_loaded",false,"Give Loaded Weapons") BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_ammo_givespare",false,"Give Spare Magazines") BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_limit_equipped",false,"Equipment Setting",3,0) BURGERBASE:FUNC_MENU_AddTitle("Core - Drop Settings",false) BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_drops_enable",false,"Enable Weapon Drops") BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_drops_timed",false,"Enable Weapon Drop Timer") BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_drops_timer",false,"Drop Timer",600,0) BURGERBASE:FUNC_MENU_AddTitle("Core - Other Settings",false) BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_quick",false,"Allow Quick Grenades") BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_enable_mags",false,"Allow Cosmetic Magazines") BURGERBASE:FUNC_MENU_AddTitle("Core - Crosshair",true) BURGERBASE:FUNC_MENU_AddConVarCheckbox("cl_burgerbase_crosshair_dynamic",true,"Dynamic Crosshair") BURGERBASE:FUNC_MENU_AddConVarCheckbox("cl_burgerbase_crosshair_dot",true,"Center Dot") BURGERBASE:FUNC_MENU_AddConVarSlider("cl_burgerbase_crosshair_style",true,"Crosshair Style",5,0) BURGERBASE:FUNC_MENU_AddConVarSlider("cl_burgerbase_crosshair_length",true,"Crosshair Length",30,0) BURGERBASE:FUNC_MENU_AddConVarSlider("cl_burgerbase_crosshair_offset",true,"Crosshair Offset",10,0) BURGERBASE:FUNC_MENU_AddConVarCheckbox("cl_burgerbase_crosshair_smoothing",true,"Crosshair Smoothing") BURGERBASE:FUNC_MENU_AddConVarSlider("cl_burgerbase_crosshair_smoothing_mul",true,"Crosshair Smoothing Multiplier",2,2) BURGERBASE:FUNC_MENU_AddConVarSlider("cl_burgerbase_crosshair_color_r",true,"Red",255,0) BURGERBASE:FUNC_MENU_AddConVarSlider("cl_burgerbase_crosshair_color_g",true,"Green",255,0) BURGERBASE:FUNC_MENU_AddConVarSlider("cl_burgerbase_crosshair_color_b",true,"Blue",255,0) BURGERBASE:FUNC_MENU_AddConVarSlider("cl_burgerbase_crosshair_color_a",true,"Alpha",255,0) BURGERBASE:FUNC_MENU_AddConVarCheckbox("cl_burgerbase_crosshair_shadow",true,"Shadow") BURGERBASE:FUNC_MENU_AddTitle("Core - Viewmodel",true) BURGERBASE:FUNC_MENU_AddConVarSlider("cl_burgerbase_viewmodel_fov",true,"Viewmodel Add",45,0) BURGERBASE:FUNC_MENU_AddConVarCheckbox("cl_burgerbase_crosshair_neversights",true,"Disable Ironsights") BURGERBASE:FUNC_MENU_AddTitle("Core - Other",true) BURGERBASE:FUNC_MENU_AddConVarCheckbox("cl_burgerbase_customslots",true,"Enable Custom Slots") local function BURGERBASE_HOOK_OnPlayerChat(ply,text,teamChat,isDead) --print(text) if ply == LocalPlayer() then if text == "!burgerclient" then RunConsoleCommand("burgerbase_client") return true elseif text == "!burgerserver" then RunConsoleCommand("burgerbase_server") return true end end end hook.Add("OnPlayerChat","BURGERBASE_HOOK_OnPlayerChat",BURGERBASE_HOOK_OnPlayerChat) <file_sep>/lua/burgerbase/core/core_loadfiles.lua BURGERBASE:INIT_MassInclude("burgerbase/core/shared/","shared",false) BURGERBASE:INIT_MassInclude("burgerbase/core/server/","server",false) BURGERBASE:INIT_MassInclude("burgerbase/core/client/","client",false)<file_sep>/lua/weapons/weapon_burger_cs_scout.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_scout", "csd", "n", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/scout") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "<NAME>" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 2750 SWEP.CSSMoveSpeed = 260 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.Description = "Gives a boost to movement speed, is not affected by movement penalties." SWEP.ViewModel = "models/weapons/cstrike/c_snip_scout.mdl" SWEP.WorldModel = "models/weapons/w_snip_scout.mdl" SWEP.VModelFlip = false SWEP.HoldType = "ar2" SWEP.Primary.Damage = 75 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_Scout.Single") SWEP.Primary.Cone = 0.0003 SWEP.Primary.ClipSize = 10 SWEP.Primary.SpareClip = 90 SWEP.Primary.Delay = 1.25 --1/(48/60) SWEP.Primary.Ammo = "bb_762mm" SWEP.Primary.Automatic = false SWEP.RecoilMul = 0.3 SWEP.SideRecoilMul = 1 SWEP.RecoilSpeedMul = 1 SWEP.MoveConeMul = 0 SWEP.HeatMul = 1 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.HasScope = true SWEP.ZoomAmount = 9 SWEP.HasCrosshair = false SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = true SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = false SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = true SWEP.HasIdle = false SWEP.CanShootWhileSprinting = false SWEP.DamageFalloff = 8000 SWEP.HasIronSights = false SWEP.EnableIronCross = false SWEP.HasGoodSights = false SWEP.IronSightTime = 0.125 SWEP.ZoomDelay = 0.125 SWEP.ZoomTime = 0 SWEP.UseMuzzle = true SWEP.UseSpecialProjectile = false SWEP.IronSightsPos = Vector(-6.72, 0, 3.359) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(-2.01, -5, 0.602) SWEP.IronRunAng = Vector(-5, 15, -7.739) SWEP.IronMeleePos = Vector(3.417, -10, -13.87) SWEP.IronMeleeAng = Vector(-9.146, 70, -70) <file_sep>/lua/burgerbase/modules/css/client/menus/css_menus.lua BURGERBASE:FUNC_MENU_AddTitle("Counter-Strike - Equipment Settings",false) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_flashbang_dur",false,"Maximum Flashbang Blind Duration",10,1) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_smoke_dur",false,"Smokegrenade smoke Duration",30,0) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_he_damage",false,"HE Grenade Maximum Explosion Damage",300,0) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_he_radius",false,"HE Grenade Radius",1000,0) BURGERBASE:FUNC_MENU_AddTitle("Counter-Strike - C4 Settings",false) BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_c4_nonadmin",false,"Enable non-admin pickup.") BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_c4_time_explosion",false,"Explosion Delay",300,0) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_c4_time_defuse",false,"Defuse Time",60,0) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_c4_timelimit",false,"C4 Replant Delay",600,0) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_c4_damage",false,"Maximum Explosion Damage",1000,0) BURGERBASE:FUNC_MENU_AddConVarSlider("sv_burgerbase_c4_radius",false,"Explosion Radius",5000,0) BURGERBASE:FUNC_MENU_AddConVarCheckbox("sv_burgerbase_c4_notifyplayers",false,"Plant and Explosion Notifications")<file_sep>/lua/weapons/weapon_burger_cs_dualbertta.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_dualbertta", "csd", "s", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/elites") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "Dual Elites" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Secondary" SWEP.Cost = 800 SWEP.CSSMoveSpeed = 250 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Description = "Inaccurate akimbo guns that deal a moderate amount of damage." SWEP.Slot = 1 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/cstrike/c_pist_elite.mdl" SWEP.WorldModel = "models/weapons/w_pist_elite.mdl" SWEP.VModelFlip = false SWEP.HoldType = "duel" SWEP.Primary.Damage = 45 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_ELITE.Single") SWEP.Primary.Cone = 0.0025 SWEP.Primary.ClipSize = 30 SWEP.Primary.SpareClip = 120 SWEP.Primary.Delay = 0.12 --1/(750/60) SWEP.Primary.Ammo = "bb_9mm" SWEP.Primary.Automatic = false SWEP.RecoilMul = 1 SWEP.SideRecoilMul = -1 SWEP.RecoilSpeedMul = 1.25 SWEP.MoveConeMul = 0.5 SWEP.HeatMul = 2 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 0.5 SWEP.HasScope = false SWEP.ZoomAmount = 0.5 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasDual = true SWEP.HasFirstShotAccurate = true SWEP.SideRecoilBasedOnDual = true SWEP.CanShootWhileSprinting = true SWEP.DamageFalloff = 1000 SWEP.GetMagModel = "models/weapons/unloaded/pist_fiveseven_mag.mdl" SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.5 SWEP.ZoomTime = 0.5 SWEP.IronSightsPos = Vector(0, 0, 2) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(0, 0, 0) SWEP.IronRunAng = Vector(0, 0, 0) SWEP.IronMeleePos = Vector(-6, -13.468, -20) SWEP.IronMeleeAng = Vector(70, 0, 0) <file_sep>/lua/burgerbase/core/server/other/core_dropping.lua local AssociatedWeapons = { bb_hegrenade = "weapon_burger_cs_he", bb_flashgrenade = "weapon_burger_cs_flash", bb_smokegrenade = "weapon_burger_cs_smoke", ex_gasgrenade = "weapon_burger_ex_gas" } local function BURGERBASE_HOOK_DoPlayerDeath(ply) ply:SetNWString("cssprimary","") ply:SetNWString("csssecondary","") if BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_drops_enable",false):GetInt() == 1 then for k,v in pairs(ply:GetWeapons()) do BURGERBASE_FUNC_DropWeapon(ply,v) end BURGERBASE_FUNC_DropAmmo(ply,"all") end end hook.Add("DoPlayerDeath", "BURGERBASE_HOOK_DoPlayerDeath", BURGERBASE_HOOK_DoPlayerDeath ) local NextThink = 0 local function BURGERBASE_HOOK_Think() if NextThink <= CurTime() then for k,v in pairs(player.GetAll()) do for ammo,weapon in pairs(AssociatedWeapons) do if not v:HasWeapon(weapon) then if v:GetAmmoCount(ammo) > 0 then local NewWeapon = v:Give(weapon) NewWeapon.AlreadyGiven = true end end end end NextThink = CurTime() + 1 end end hook.Add("Think","BURGERBASE_HOOK_Think",BURGERBASE_HOOK_Think) function BURGERBASE_FUNC_ReplaceHL2Weapons() local ReplacementTable = {} ReplacementTable["weapon_357"] = "weapon_hl2_357" ReplacementTable["weapon_ar2"] = "weapon_hl2_ar2" ReplacementTable["weapon_crossbow"] = "weapon_hl2_crossbow" ReplacementTable["weapon_crowbar"] = "weapon_hl2_crowbar" ReplacementTable["weapon_frag"] = "weapon_burger_cs_he" ReplacementTable["weapon_pistol"] = "weapon_hl2_pistol" ReplacementTable["weapon_rpg"] = "weapon_hl2_rpg" ReplacementTable["weapon_shotgun"] = "weapon_hl2_spas" ReplacementTable["weapon_smg1"] = "weapon_hl2_smg" ReplacementTable["weapon_stunstick"] = "weapon_hl2_stunstick" for k,v in pairs(ents.GetAll()) do if v:IsWeapon() and ReplacementTable[v:GetClass()] then BURGERBASE_FUNC_CreateWeapon(ReplacementTable[v:GetClass()],v:GetPos(),v:GetAngles(),nil,nil) SafeRemoveEntity(v) end end end hook.Add("PostCleanupMap","BURGERBASE_FUNC_ReplaceHL2Weapons",BURGERBASE_FUNC_ReplaceHL2Weapons) BURGERBASE_FUNC_ReplaceHL2Weapons() function BURGERBASE_FUNC_CreateWeapon(class,pos,ang,ammooverride,spareoverride) local StoredWeapon = weapons.GetStored(class) if not StoredWeapon then print(string.upper("ERROR: BURGERBASE_FUNC_CreateWeapon() COULD NOT CREATE " .. class .. "!")) return false end if not spareoverride then spareoverride = StoredWeapon.Primary.SpareClip end if not ammooverride then ammooverride = StoredWeapon.Primary.ClipSize end local WeaponModel = StoredWeapon.WorldModel if StoredWeapon.DisplayModel then WeaponModel = StoredWeapon.DisplayModel end --print(WeaponModel) if WeaponModel && WeaponModel ~= "" then local CreatedWeapon = ents.Create("ent_burger_core_dropped_weapon") CreatedWeapon:SetPos(pos) CreatedWeapon:SetAngles(ang) CreatedWeapon:SetModel(WeaponModel) CreatedWeapon:SetNWString("class",class) CreatedWeapon:SetNWFloat("clip",ammooverride) CreatedWeapon:SetNWFloat("spare",spareoverride) CreatedWeapon:SetCustomCollisionCheck( true ) CreatedWeapon:Spawn() CreatedWeapon:Activate() return CreatedWeapon else return NULL end end function BURGERBASE_FUNC_CreateAmmo(pos,ang,ammotype,amount,model) if not model then model = "models/weapons/w_defuser.mdl" end local Ammo = ents.Create("ent_burger_core_ammo") Ammo.AmmoType = ammotype Ammo.AmmoAmount = amount Ammo.AmmoModel = model Ammo:SetPos( pos ) Ammo:SetAngles( ang ) Ammo:SetCustomCollisionCheck( true ) Ammo:Spawn() Ammo:Activate() return Ammo end function BURGERBASE_FUNC_CreateAmmoTable(pos,ang,ammotable,model) if not model then model = "models/weapons/w_defuser.mdl" end local Ammo = ents.Create("ent_burger_core_dropped_ammo") Ammo.AmmoTable = ammotable Ammo.AmmoModel = model Ammo:SetPos( pos ) Ammo:SetAngles( ang ) Ammo:SetCustomCollisionCheck( true ) Ammo:Spawn() Ammo:Activate() return Ammo end function BURGERBASE_FUNC_DropWeapon(ply,weapon) if weapon:IsScripted() then if weapon.BurgerBase ~= nil or weapon.Base == "weapon_burger_core_base" then local Class = weapon:GetClass() local StoredWeapon = weapons.GetStored(Class) local Pos = ply:GetPos() + ply:OBBCenter() local Ang = ply:EyeAngles() local Clip1 = weapon:Clip1() -- Ammo in the clip local Ammo1 = weapon:Ammo1() -- Ammo in reserve local CreatedWeapon = BURGERBASE_FUNC_CreateWeapon(Class,Pos,Ang,Clip1,0) if ply:Alive() then if StoredWeapon.WeaponType == "Throwable" then local AmmoToSet = math.Clamp(Ammo1 - 1,0,9999) ply:SetAmmo( AmmoToSet, weapon:GetPrimaryAmmoType() ) if AmmoToSet <= 0 then ply:StripWeapon(Class) end else ply:StripWeapon(Class) end elseif BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_drops_timed",false):GetInt() == 1 then if CreatedWeapon and CreatedWeapon ~= NULL then SafeRemoveEntityDelayed(CreatedWeapon,BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_drops_timer",false):GetInt()) end end if ply and CreatedWeapon and CreatedWeapon ~= NULL then CreatedWeapon:GetPhysicsObject():SetVelocity(ply:EyeAngles():Forward()*100) end end end end function BURGERBASE_FUNC_DropAmmo(ply,weapon,amount) local Pos = ply:GetPos() + ply:OBBCenter() local Ang = ply:EyeAngles() + Angle( math.Rand(1,360),math.Rand(1,360),math.Rand(1,360)) local DroppedAmmo = nil if weapon == "all" then local AllAmmoTable = {} for i = 1, 100 do AllAmmoTable[i] = ply:GetAmmoCount( i ) end if AllAmmoTable[1] then DroppedAmmo = BURGERBASE_FUNC_CreateAmmoTable(Pos,Ang,AllAmmoTable) ply:RemoveAllAmmo() end else local AmmoModel = "models/weapons/w_defuser.mdl" local AmmoType = weapon:GetPrimaryAmmoType() local AmmoCount = ply:GetAmmoCount(AmmoType) local ClipCount = weapon:GetMaxClip1() if weapon:IsScripted() and (weapon.BurgerBase or weapon.Base == "weapon_burger_core_base") then if weapon.WeaponType == "Throwable" then BURGERBASE_FUNC_DropWeapon(ply,weapon) return elseif weapon.GetMagModel then if file.Exists(weapon.GetMagModel,"GAME") then AmmoModel = weapon.GetMagModel end end end if ClipCount == -1 and weapon.Primary.SpareClip then ClipCount = math.Clamp(math.ceil(weapon.Primary.SpareClip * 0.1),-1,9999) end local AmmoCountToDrop = math.min(AmmoCount,ClipCount) if amount then AmmoCountToDrop = amount end if AmmoCountToDrop > 0 then DroppedAmmo = BURGERBASE_FUNC_CreateAmmo(Pos,Ang,AmmoType,AmmoCountToDrop,AmmoModel) if weapon.WeaponType == "Throwable" then if ply:GetAmmoCount(AmmoType) <= 0 then ply:StripWeapon(weapon:GetClass()) end end if ply:Alive() then ply:SetAmmo( math.Clamp(AmmoCount - AmmoCountToDrop,0,9999) , AmmoType) end end end if DroppedAmmo then DroppedAmmo:GetPhysicsObject():SetVelocity(ply:GetForward()*100) if BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_drops_timed",false):GetInt() == 1 then SafeRemoveEntityDelayed(DroppedAmmo,BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_drops_timer",false):GetInt()) end end end local function BURGERBASE_COMMAND_Dropping(ply,cmd,args,argStr) local Weapon = ply:GetActiveWeapon() if Weapon and Weapon:IsValid() then if cmd == "dropweapon" then BURGERBASE_FUNC_DropWeapon(ply,Weapon) elseif cmd == "dropammo" then BURGERBASE_FUNC_DropAmmo(ply,Weapon) end end end concommand.Add("dropweapon", BURGERBASE_COMMAND_Dropping) concommand.Add("dropammo", BURGERBASE_COMMAND_Dropping) <file_sep>/lua/burgerbase/core/shared/other/core_quickthrow.lua function BURGERBASE:SuperThrowCheck(ply,Weapon) if BURGERBASE:ThrowCheck(ply,Weapon,"weapon_burger_cs_he") then return true elseif BURGERBASE:ThrowCheck(ply,Weapon,"weapon_burger_ex_gas") then return true elseif BURGERBASE:ThrowCheck(ply,Weapon,"weapon_burger_cs_flash") then return true elseif BURGERBASE:ThrowCheck(ply,Weapon,"weapon_burger_cs_smoke") then return true else return false end end function BURGERBASE:ThrowCheck(ply,Weapon,class) if not ply:HasWeapon(class) then return false end if Weapon:GetClass() == class and not ply:IsBot() then return false end ply:SelectWeapon(class) return true end function BURGERBASE_HOOK_KeyPress(ply,key) if ply:KeyDown(IN_USE) or ply:IsBot() then if key == IN_ATTACK or ply:IsBot() then if ply:InVehicle() then return end local Weapon = ply:GetActiveWeapon() if not IsValid(Weapon) then return end if not Weapon:IsScripted() then return end if Weapon.Base ~= "weapon_burger_core_base" then return end if Weapon:IsBusy() == true then return end if !Weapon:CanQuickThrow() then return end if CLIENT then return end if not BURGERBASE:SuperThrowCheck(ply,Weapon) then return false end if Weapon.HasHolster then local ThrowDelay = Weapon.Owner:GetViewModel():SequenceDuration() timer.Simple(ThrowDelay + FrameTime(), function() Weapon = ply:GetActiveWeapon() if Weapon and Weapon ~= NULL then Weapon:QuickThrow() end end) else Weapon = ply:GetActiveWeapon() Weapon:QuickThrow() end end end end hook.Add("KeyPress","BURGERBASE_HOOK_KeyPress",BURGERBASE_HOOK_KeyPress) <file_sep>/lua/weapons/weapon_burger_cs_xm1014.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_xm1014", "csd", "B", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/xm1014") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "XM1014" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 3000 SWEP.CSSMoveSpeed = 240 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Description = "Semi-automatic shotgun that's good for clearing rooms. Comes with slug rounds." SWEP.Slot = 2 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/cstrike/c_shot_xm1014.mdl" SWEP.WorldModel = "models/weapons/w_shot_xm1014.mdl" SWEP.VModelFlip = false SWEP.HoldType = "ar2" SWEP.Primary.Damage = 22 SWEP.Primary.NumShots = 6 SWEP.Primary.Sound = Sound("Weapon_XM1014.Single") SWEP.Primary.Cone = 0.0325 SWEP.Primary.ClipSize = 7 SWEP.Primary.SpareClip = 32 SWEP.Primary.Delay = 0.25 --1/(240/60) SWEP.Primary.Ammo = "bb_12gauge" SWEP.Primary.Automatic = false SWEP.RecoilMul = 0.5 SWEP.SideRecoilMul = 0.25 SWEP.RecoilSpeedMul = 0.75 SWEP.MoveConeMul = 0.5 SWEP.HeatMul = 1 SWEP.CoolMul = 0.5 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 0.25 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = true SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = false SWEP.CanShootWhileSprinting = true SWEP.DamageFalloff = 200 SWEP.PenetrationLossScale = 0.5 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = false SWEP.IronSightTime = 0.5 SWEP.ZoomTime = 0.5 SWEP.IronRunPos = Vector(-2.01, 0.201, 0.602) SWEP.IronRunAng = Vector(-5, 15, -7.739) SWEP.IronSightsPos = Vector(-7, 0, 2.64) SWEP.IronSightsAng = Vector(0, -0.76, 0) SWEP.IronMeleePos = Vector(3.417, -10, -13.87) SWEP.IronMeleeAng = Vector(-9.146, 70, -70) SWEP.SpecialAmmo = {"bb_12gauge","bb_12gaugeslug"} function SWEP:SpecialGiveAmmo() self.Owner:GiveAmmo(12,"bb_12gaugeslug",false) end function SWEP:SpecialShots(shots) if self:GetPrimaryAmmo() == game.GetAmmoID("bb_12gaugeslug") then shots = 1 end return shots end function SWEP:SpecialDamage(damage) if self:GetPrimaryAmmo() == game.GetAmmoID("bb_12gaugeslug") then damage = 80 end return damage end function SWEP:SpecialFalloff(falloff) if self:GetPrimaryAmmo() == game.GetAmmoID("bb_12gaugeslug") then falloff = 1000 end return falloff end function SWEP:SpecialRecoil(recoil) if self:GetPrimaryAmmo() == game.GetAmmoID("bb_12gaugeslug") then recoil = recoil * 0.5 end return recoil end function SWEP:SpecialConePre(cone) if self:GetPrimaryAmmo() == game.GetAmmoID("bb_12gaugeslug") then cone = cone*0.25 end return cone end<file_sep>/lua/burgerbase/core/client/other_core.lua BURGERBASE:INIT_MassInclude("burgerbase/core/client/other/","client",false)<file_sep>/lua/weapons/weapon_burger_core_base/shared.lua local IsSingleplayer = false local ToggleZoom = true -- Weapon Information SWEP.Category = "Other" SWEP.PrintName = "Burger's Base" SWEP.Base = "weapon_base" SWEP.BurgerBase = true SWEP.WeaponType = "Primary" SWEP.Cost = 2500 SWEP.CSSMoveSpeed = 221 SWEP.CSSZoomSpeed = -1 -- Spawning SWEP.Spawnable = false SWEP.AdminOnly = false -- Slots SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.Weight = 0 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false -- Worldmodel SWEP.WorldModel = "models/weapons/w_rif_ak47.mdl" SWEP.DisplayModel = nil SWEP.HoldType = "ar2" -- Viewmodel SWEP.SwayScale = 0 SWEP.BobScale = 0 SWEP.ViewModel = "models/weapons/cstrike/c_rif_ak47.mdl" SWEP.ViewModelFlip = false SWEP.UseHands = true SWEP.IgnoreScopeHide = false SWEP.AddFOV = 0 -- Bullet Information SWEP.Primary.Damage = 36 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = nil SWEP.Primary.Cone = 0.0025 SWEP.Primary.ClipSize = 30 SWEP.Primary.SpareClip = 90 SWEP.Primary.Delay = 0.1 SWEP.Primary.Ammo = "bb_762mm" SWEP.Primary.Automatic = true SWEP.BulletEnt = nil -- Bullet Entity that is Spawned SWEP.SourceOverride = Vector(0,0,0) -- Projectile Spawn Offset SWEP.BulletAngOffset = Angle(0,0,0) -- Rotate the Projectile by this amount -- General Weapon Statistics SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 0.5 SWEP.SideRecoilBasedOnDual = false SWEP.RecoilSpeedMul = 1 SWEP.MoveConeMul = 1 SWEP.HeatMul = 1 SWEP.MaxHeat = 10 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.SideRecoilBasedOnDual = false SWEP.PenetrationLossMul = 1 SWEP.FatalHeadshot = false SWEP.TracerType = 1 SWEP.DamageFalloff = 3000 SWEP.ReloadTimeAdd = 0 SWEP.RandomSeed = 0 SWEP.ShootOffsetStrength = Angle(0,0,0) -- Recoil for OP Snipers -- Sounds SWEP.ZoomInSound = Sound("weapons/zoom.wav") SWEP.ZoomOutSound = Sound("weapons/zoom.wav") SWEP.ReloadSound = nil SWEP.BurstSound = nil SWEP.LastBulletSound = nil SWEP.PumpSound = nil SWEP.MeleeSoundMiss = Sound("weapons/foot/foot_fire.wav") SWEP.MeleeSoundWallHit = Sound("weapons/foot/foot_kickwall.wav") SWEP.MeleeSoundFleshSmall = Sound("weapons/foot/foot_kickbody.wav") SWEP.MeleeSoundFleshLarge = Sound("weapons/foot/foot_kickbody.wav") -- Features SWEP.HasIronSights = true SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasSpecialFire = true SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasSideRecoil = false SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = false SWEP.CanShootWhileSprinting = true SWEP.HasBuildUp = false -- Uses Minigun Buildup SWEP.UsesBuildUp = false -- Uses Buildup for Custom Reasons SWEP.BuildUpAmount = 10 SWEP.BuildUpCoolAmount = 50 SWEP.HasIdle = false SWEP.IdleOffset = 0 SWEP.DisableReloadUntilEmpty = false SWEP.IgnoreDrawDelay = false SWEP.EnableDropping = true -- Burst Settings SWEP.BurstSpeedOverride = 1 SWEP.BurstConeMul = 1 SWEP.BurstHeatMul = 1 SWEP.BurstZoomMul = 1 SWEP.BurstRecoilMul = 1 SWEP.BurstOverride = 3 SWEP.BurstCoolMul = 1 SWEP.BurstSpeedAbs = nil SWEP.BurstAnimationOverride = nil SWEP.BurstAnimationOnce = false -- Grenade SWEP.HasPreThrow = true -- Melee SWEP.MeleeDamage = 50 SWEP.EnableBlocking = false SWEP.MeleeDelay = 0.1 SWEP.MeleeDamageType = DMG_CLUB -- Zooming SWEP.HasIronCrosshair = true SWEP.IronSightTime = 0.125 SWEP.IronSightsPos = Vector(-3, 20, 0) SWEP.IronSightsAng = Vector(1.25, 1, 0) SWEP.ZoomAmount = 1 SWEP.ZoomDelay = 0 SWEP.ZoomTime = 0.5 -- Scope SWEP.HasScope = false SWEP.EnableDefaultScope = true SWEP.CustomScope = nil SWEP.CustomScopeSOverride = nil SWEP.CustomScopeCOverride = Color(0,0,0,255) SWEP.ColorOverlay = Color(0,0,0,0) -- Color Overlay when Zoomed -- Crosshair SWEP.HasCrosshair = true SWEP.CrosshairOverrideMat = nil SWEP.CrosshairOverrideSize = nil -- Tracers SWEP.EnableCustomTracer = true SWEP.CustomShootEffectsTable = nil SWEP.DamageType = 1 -- Magazine Mod SWEP.MagDelayMod = 0.75 SWEP.MagMoveMod = Vector(0,0,0) SWEP.MagAngMod = Angle(0,0,0) -- PLEASE TEST SWEP.DelayOverride = false -- Not really used anymore but w/e SWEP.Author = "Burger" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.CSMuzzleFlashes = true SWEP.CSMuzzleX = false -- Base Exclusive Stuff SWEP.Primary.DefaultClip = 0 -- Unused SWEP.Secondary.Ammo = "none" SWEP.Secondary.SpareClip = 0 SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.DrawAmmo = true SWEP.DrawCrosshair = false SWEP.CustomScopeSizeMul = 1 SWEP.RichochetSound = {} SWEP.RichochetSound[1] = Sound("weapons/fx/rics/ric1.wav") SWEP.RichochetSound[2] = Sound("weapons/fx/rics/ric2.wav") SWEP.RichochetSound[3] = Sound("weapons/fx/rics/ric3.wav") SWEP.RichochetSound[4] = Sound("weapons/fx/rics/ric4.wav") SWEP.RichochetSound[5] = Sound("weapons/fx/rics/ric5.wav") util.PrecacheSound("weapons/fx/rics/ric1.wav") util.PrecacheSound("weapons/fx/rics/ric2.wav") util.PrecacheSound("weapons/fx/rics/ric3.wav") util.PrecacheSound("weapons/fx/rics/ric4.wav") util.PrecacheSound("weapons/fx/rics/ric5.wav") if (CLIENT or game.SinglePlayer()) then SWEP.IsZoomed = false -- Data, Client SWEP.PunchAngleUp = Angle(0,0,0) -- Data, Client SWEP.PunchAngleDown = Angle(0,0,0) -- Data, Client SWEP.ClientCoolDown = 0 -- Data, Client SWEP.ClientCoolTime = 0 -- Data, Client SWEP.ClientCoolDownLeft = 0 -- Data, Client SWEP.ClientCoolTimeLeft = 0 -- Data, Client SWEP.StoredCrosshair = nil -- Data, Client SWEP.BoltDelay = 0 -- Data, Client SWEP.DesiredFOV = GetConVar("fov_desired"):GetFloat() or 70 -- Data, Client SWEP.ZoomOverlayDelay = 0 -- Data, Client SWEP.ZoomMod = 0 -- Data, Client end if SERVER then SWEP.AlreadyGiven = false -- Data, Server SWEP.HasMagIn = true -- Data, Server SWEP.DesiredFOV = 70 end SWEP.MeleeModel = Model("models/weapons/c_arms_cstrike.mdl") SWEP.IronDualSpacing = 1 SWEP.IronSightPosCurrent = Vector(0,0,0) SWEP.IronSightAngCurrent = Angle(0,0,0) SWEP.IronRunPos = Vector(0,-5,-20) SWEP.IronRunAng = Vector(45,10,0) SWEP.IronMeleePos = Vector(0,0,0) SWEP.IronMeleeAng = Vector(0,0,0) SWEP.IronShootPos = Vector(0,0,0) SWEP.IronShootAng = Vector(0,0,0) SWEP.VelAdd = 0 SWEP.BulletDelay = 0 SWEP.DryFireSound = Sound("weapons/clipempty_pistol.wav") SWEP.PumpAnimation = ACT_SHOTGUN_PUMP if CLIENT or game.SinglePlayer() then SWEP.DynamicScopeDesiredOffsetX = 0 SWEP.DynamicScopeDesiredOffsetY = 0 SWEP.DynamicScopeOffsetX = 0 SWEP.DynamicScopeOffsetY = 0 SWEP.ScopeMoveTime = 0 SWEP.ScopeMoveTimeStored = 0 end SWEP.CanCook = false SWEP.FuseTime = 5 SWEP.HasDurability = false SWEP.DurabilityPerHit = -10 function SWEP:SetupDataTables() -- Shared self:NetworkVar("Float",0,"CoolDown") self:SetCoolDown(0) self:NetworkVar("Float",1,"CoolTime") self:SetCoolTime(0) self:NetworkVar("Float",2,"NextShell") self:SetNextShell(0) self:NetworkVar("Float",3,"ReloadFinish") self:SetReloadFinish(0) self:NetworkVar("Float",4,"AttachDelay") self:SetAttachDelay(0) self:NetworkVar("Float",5,"NextFireDelay") self:SetNextFireDelay(0) self:NetworkVar("Float",6,"BuildUp") self:SetBuildUp(0) self:NetworkVar("Float",7,"NextHL2Pump") self:SetNextHL2Pump(0) self:NetworkVar("Float",8,"ThrowDelay") self:SetThrowDelay(0) self:NetworkVar("Float",9,"ThrowRemoveTime") self:SetThrowRemoveTime(0) self:NetworkVar("Float",10,"ThrowTime") self:SetThrowTime(0) self:NetworkVar("Float",11,"NextHolster") self:SetNextHolster(-1) self:NetworkVar("Float",12,"NextIdle") self:SetNextIdle(0) self:NetworkVar("Float",13,"NextMelee") self:SetNextMelee(0) self:NetworkVar("Float",14,"NextMeleeDamage") self:SetNextMeleeDamage(0) self:NetworkVar("Float",15,"BulletsPerSecond") self:SetBulletsPerSecond(0) self:NetworkVar("Float",16,"ClashTime") self:SetClashTime(0) self:NetworkVar("Float",17,"ScopeOffsetX") self:SetScopeOffsetX(0) self:NetworkVar("Float",18,"ScopeOffsetY") self:SetScopeOffsetY(0) self:NetworkVar("Float",19,"SharedZoomOverlayDelay") self:SetSharedZoomOverlayDelay(0) self:NetworkVar("Float",20,"SharedZoomMod") self:SetSharedZoomMod(0) self:NetworkVar("Float",21,"SharedBoltDelay") self:SetSharedBoltDelay(0) self:NetworkVar("Float",22,"GrenadeExplosion") self:SetGrenadeExplosion(0) self:NetworkVar("Float",23,"CoolDownLeft") self:SetCoolDownLeft(0) self:NetworkVar("Float",24,"CoolTimeLeft") self:SetCoolTimeLeft(0) self:NetworkVar("Float",25,"BulletQueue") self:SetBulletQueue(0) self:NetworkVar("Float",26,"BulletQueueDelay") self:SetBulletQueueDelay(0) self:NetworkVar("Float",31,"SpecialFloat") -- For Special Stuff self:SetSpecialFloat(0) self:NetworkVar("Int",0,"FireQueue") self:SetFireQueue(0) self:NetworkVar("Int",1,"PrimaryAmmo") self:SetPrimaryAmmo( game.GetAmmoID(self.Primary.Ammo) ) self:NetworkVar("Int",2,"SecondaryAmmo") self:SetSecondaryAmmo( game.GetAmmoID(self.Secondary.Ammo) ) self:NetworkVar("Int",31,"SpecialInt") self:SetSpecialInt(0) self:NetworkVar("Bool",0,"IsReloading") self:SetIsReloading( false ) self:NetworkVar( "Bool",1,"IsBurst" ) if self.AlwaysBurst then self:SetIsBurst( true ) else self:SetIsBurst( false ) end self:NetworkVar("Bool",2,"IsShotgunReload") self:SetIsShotgunReload( false ) self:NetworkVar("Bool",3,"IsSilenced") self:SetIsSilenced( false ) self:NetworkVar("Bool",4,"IsNormalReload") self:SetIsNormalReload( false ) self:NetworkVar("Bool",5,"IsLeftFire") self:SetIsLeftFire( false ) self:NetworkVar("Bool",6,"IsBlocking") -- For Special Stuff self:SetIsBlocking( false ) self:NetworkVar("Bool",7,"NeedsHL2Pump") self:SetNeedsHL2Pump( false ) self:NetworkVar("Bool",8,"CanHolster") self:SetCanHolster( true ) self:NetworkVar("Bool",9,"IsThrowing") self:SetIsThrowing( false ) self:NetworkVar("Bool",10,"QueueHolster") self:SetQueueHolster( false ) self:NetworkVar("Bool",11,"ForceHolster") self:SetForceHolster( false ) self:NetworkVar("Bool",12,"SharedZoom") self:SetSharedZoom( false ) self:NetworkVar("Bool",13,"ShouldMelee") self:SetShouldMelee( false ) self:NetworkVar("Bool",14,"IsAttacking") self:SetIsAttacking( false ) self:NetworkVar("Bool",31,"SpecialBool") self:SetSpecialBool( false ) self:NetworkVar("Entity",1,"NextHolsterWeapon") self:SetNextHolsterWeapon( nil ) self:NetworkVar("Entity",2,"NextMeleeEnt") self:SetNextMeleeEnt( nil ) self:NetworkVar("Angle",1,"SharedTrueAimAng") self:SetSharedTrueAimAng( Angle(0,0,0) ) end function SWEP:Initialize() -- shared if game.SinglePlayer() then IsSingleplayer = true end if CLIENT then if not self.Owner.BURGERBASE_ZoomMul then self.Owner.BURGERBASE_ZoomMul = {} end if not self.Owner.BURGERBASE_ZoomMul[self:GetClass()] then self.Owner.BURGERBASE_ZoomMul[self:GetClass()] = 1 end end if CLIENT or IsSingleplayer then if BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_customslots",true):GetFloat() == 1 then if self.WeaponType == "Primary" then self.Slot = 2 elseif self.WeaponType == "Secondary" then self.Slot = 1 end end end if SERVER then if not self.GetMagModel then self.GetMagModel = string.Replace( self.WorldModel,"/w_" , "/unloaded/" ) self.GetMagModel = string.Replace( self.GetMagModel , ".mdl" , "_mag.mdl") end if file.Exists(self.GetMagModel,"GAME") then self.GetMagModel = Model(self.GetMagModel) else self.GetMagModel = nil end end self:SpecialInitialize() if SERVER and self.Owner:IsNPC() then self:NPCInit() end if self.Owner:IsPlayer() then self:SCK_Initialize() end end function SWEP:NPCInit() -- shared self.Owner:SetCurrentWeaponProficiency( WEAPON_PROFICIENCY_PERFECT ) end function SWEP:GetCapabilities() -- shared return bit.bor( CAP_WEAPON_RANGE_ATTACK1, CAP_INNATE_RANGE_ATTACK1 ) end function SWEP:SpecialInitialize() -- shared end function SWEP:OwnerChanged() -- shared if SERVER then timer.Simple(FrameTime(), function() if not self.AlreadyGiven then if BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_ammo_loaded"):GetFloat() == 1 then self:SetClip1(self.Primary.ClipSize) end self:EquipAmmo(self.Owner) self.AlreadyGiven = true end end) end end function SWEP:SendWeaponAnimation(act,vm_index,rate) -- Thanks to the wiki for the idea -- Shared if not vm_index then vm_index = 0 end if not rate then rate = 1 end --print(self.AnimationRateTable[act] or 1) rate = rate * (self.AnimationRateTable[act] or 1) local ViewModel = self.Owner:GetViewModel( vm_index ) if !IsValid(ViewModel) then return end local Sequence = ViewModel:SelectWeightedSequence( act ) if ( Sequence == -1 ) then return end ViewModel:SendViewModelMatchingSequence( Sequence ) ViewModel:SetPlaybackRate( rate ) self:SetNextIdle(CurTime() + self:GetTrueSequenceDuration()) end function SWEP:SendSequence(anim,vm_index,rate) -- Shared if not vm_index then vm_index = 0 end if not rate then rate = 1 end local ViewModel = self.Owner:GetViewModel( vm_index ) if !IsValid(ViewModel) then return end ViewModel:SendViewModelMatchingSequence( ViewModel:LookupSequence( anim ) ) ViewModel:SetPlaybackRate( rate ) self:SetNextIdle(CurTime() + self:GetTrueSequenceDuration()) end function SWEP:SendSequencePlayer(anim) -- Shared local Seq = self.Owner:LookupSequence(anim) local SeqDur = self.Owner:SequenceDuration(Seq) self.Owner:AddVCDSequenceToGestureSlot( GESTURE_SLOT_ATTACK_AND_RELOAD, Seq, 0, true ) return SeqDur end function SWEP:DrawAnimation() -- Shared if not self.IgnoreDrawDelay then if self.HasSilencer then if self:GetIsSilenced() then self:SendWeaponAnimation(ACT_VM_DRAW_SILENCED) self.WorldModel = self.WorldModel2 else self:SendWeaponAnimation(ACT_VM_DRAW) self.WorldModel = self.WorldModel1 end else --[[ if self.HasDryFire and self:Clip1() == 0 then print("HI") self:SendWeaponAnimation(ACT_VM_DRAW_EMPTY) else --]] self:SendWeaponAnimation(ACT_VM_DRAW) --end end else self:SendWeaponAnimation(ACT_VM_RELOAD) self:EmitGunSound(self.ReloadSound) end end function SWEP:Deploy() -- Shared if IsSingleplayer then if not self.Owner.BURGERBASE_ZoomMul then self.Owner.BURGERBASE_ZoomMul = {} end if not self.Owner.BURGERBASE_ZoomMul[self:GetClass()] then self.Owner.BURGERBASE_ZoomMul[self:GetClass()] = 1 end end self:SetZoomed(false) self:CheckInventory() if IsValid(self.Owner:GetHands()) then self.Owner:GetHands():SetMaterial("") end self.Owner:DrawViewModel(true) self:DrawAnimation() if self.WeaponType ~= "Throwable" then self:SetNextPrimaryFire(CurTime() + self.Owner:GetViewModel():SequenceDuration() ) end self:SpecialDeploy() return true end function SWEP:SpecialDeploy() -- Shared end function SWEP:CheckInventory() -- Shared if SERVER then if BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_limit_equipped"):GetFloat() == 1 then for k,v in pairs (self.Owner:GetWeapons()) do if v.BurgerBase ~= nil then if v ~= self then if self.WeaponType == v.WeaponType and not (v.WeaponType == "Free" or v.WeaponType == "Throwable" or v.WeaponType == "Melee") then BURGERBASE_FUNC_DropWeapon(self.Owner,v) end end end end elseif BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_limit_equipped"):GetFloat() == 2 then for k,v in pairs (self.Owner:GetWeapons()) do if v.BurgerBase ~= nil then if v ~= self then if self.Slot == v.Slot and not (v.WeaponType == "Free" or v.WeaponType == "Throwable" or v.WeaponType == "Melee") then BURGERBASE_FUNC_DropWeapon(self.Owner,v) end end end end end end end function SWEP:SpecialHolster() -- Shared end function SWEP:Holster(nextweapon) -- Shared if not self:GetCanHolster() then return false end self:CancelReload() self:SetZoomed(false) self:SpecialHolster() if self.HasHolster then if self:GetForceHolster() then self:SCK_Holster() self:SetForceHolster(false) return true elseif self:GetQueueHolster() then self:SCK_Holster() local NextWeapon = self:GetNextHolsterWeapon() self:SetNextHolsterWeapon( nil ) self:SetQueueHolster( false ) self:SetNextHolster( -1 ) self:SetForceHolster(true) if SERVER then if self.Owner and self.Owner ~= NULL and NextWeapon and NextWeapon ~= NULL then self.Owner:SelectWeapon( NextWeapon:GetClass() ) end end return false else self:SetQueueHolster( true ) self:SendWeaponAnimation( ACT_VM_HOLSTER ) if self.Owner and self.Owner ~= NULL and self.Owner:GetViewModel() and self.Owner:GetViewModel() ~= NULL then local ViewDur = self:GetTrueSequenceDuration() self:SetNextHolster( CurTime() + ViewDur ) self:SetNextPrimaryFire(CurTime() + ViewDur ) end if SERVER then self:SetNextHolsterWeapon(nextweapon) end return false end end if CLIENT then self:SCK_Holster() end return true end function SWEP:HolsterThink() -- Shared if SERVER then if self.HasHolster and self:GetQueueHolster() then if self:GetNextHolster() <= CurTime() then self:Holster( self:GetNextHolsterWeapon() ) end end end end function SWEP:SetZoomed(shouldzoom) -- Shared self:SetSharedZoom(shouldzoom) self.IsZoomed = shouldzoom end function SWEP:GetZoomed() -- Shared if IsSingleplayer or SERVER then return self:GetSharedZoom() else return self.IsZoomed end end function SWEP:SetZoomOverlayDelay(num) -- Shared self:SetSharedZoomOverlayDelay(num) self.ZoomOverlayDelay = num end function SWEP:GetZoomOverlayDelay() -- Shared if IsSingleplayer or SERVER then return self:GetSharedZoomOverlayDelay() else return self.ZoomOverlayDelay end end function SWEP:GetZoomMod() -- Shared if IsSingleplayer or SERVER then return self:GetSharedZoomMod() else return self.ZoomMod end end function SWEP:SetZoomMod(num) -- Shared self:SetSharedZoomMod(num) self.ZoomMod = num end function SWEP:SetBoltDelay(num) -- Shared self.BoltDelay = num self:SetSharedBoltDelay(num) end function SWEP:GetBoltDelay() -- Shared if IsSingleplayer or SERVER then return self:GetSharedBoltDelay() else return self.BoltDelay end end SWEP.FireAlwaysAnimate = false function SWEP:CanQuickThrow() -- Shared return true end function SWEP:QuickThrowOverride() -- Shared end function SWEP:PrimaryAttack() -- Shared if not self:CanShoot() then return end if self:IsUsing() then if not self:CanQuickThrow() then self:QuickThrowOverride() end return end if not self:HasPrimaryAmmoToFire() then if self.FireAlwaysAnimate then self:HandleShootAnimations() end end if not self:CanPrimaryAttack() then return end self:WeaponDelay() -- don't predict, has delay self:HandleBurstDelay() -- don't predict self:AfterPump() -- don't predict, has animations if self.BulletDelay > 0 then if self.BulletDelaySound then self:EmitGunSound(self.BulletDelaySound) end self:SetNextFireDelay(CurTime() + self.BulletDelay ) self:SetFireQueue(1) else self:ShootGun() -- don't predict, has firebullets end end function SWEP:ShootGun(ammototake) -- Shared if not ammototake then ammototake = 1 end --[[ if !self.HasBurst or !self:GetIsBurst() or !self.BurstAnimationOnce then self:HandleShootAnimations() -- don't predict, has animations end --]] if !(self.HasBurstFire and self:GetIsBurst() and self.BurstAnimationOnce) then --print(self.HasBurstFire, self:GetIsBurst(), self.BurstAnimationOnce) self:HandleShootAnimations() end self:TakePrimaryAmmo(ammototake) self.Owner:SetAnimation(PLAYER_ATTACK1) self.Owner:MuzzleFlash() local Damage = self:SpecialDamage(self.Primary.Damage) local Shots = self:SpecialShots( self.Primary.NumShots ) local Cone = 0 if IsFirstTimePredicted() then Cone = self:HandleCone(self.Primary.Cone,false, (self.HasDual and self:GetIsLeftFire()) ) end self:SetBulletsPerSecond( self:GetBulletsPerSecond() + 1 ) self:PreShootBullet(Damage,Shots,Cone) -- don't predict if IsFirstTimePredicted() or IsSingleplayer then if self.HasBuildUp or self.UsesBuildUp then self:SetBuildUp( math.Clamp(self:GetBuildUp() + self.BuildUpAmount - (self:GetBuildUp()/10) ,0,100 ) ) end self:AfterZoom() -- Predict, Client Only self:AddRecoil() -- Predict self:WeaponSound() -- Predict self:AddHeat(Damage,Shots) end self:PostPrimaryFire() end function SWEP:HandleShootAnimations() -- Shared if self.BurstAnimationOverride and self:GetIsBurst() then self:WeaponAnimation(self:Clip1(),self.BurstAnimationOverride) elseif self.HasDual then if self:GetIsLeftFire() then self:WeaponAnimation(self:Clip1(),ACT_VM_SECONDARYATTACK) self:SetIsLeftFire(false) else self:WeaponAnimation(self:Clip1(),ACT_VM_PRIMARYATTACK) self:SetIsLeftFire(true) end else self:WeaponAnimation(self:Clip1(),ACT_VM_PRIMARYATTACK) end end function SWEP:CanShoot() -- Shared if self:IsBusy() then return false end if not self.CanShootWhileSprinting and self:IsSprinting() then return false end if self.WeaponType == "Throwable" then self:PreThrowObject() return false end return true end function SWEP:AfterPump() -- Shared if self.HasPumpAction and self.HasHL2Pump then self:SetNextPrimaryFire(CurTime() + 10) self:SetNeedsHL2Pump(true) self:SetNextHL2Pump(CurTime() + self.Primary.Delay) end if self:GetIsShotgunReload() then self:SetIsShotgunReload(false) self:SetIsReloading(false) self:SendWeaponAnimation( ACT_SHOTGUN_RELOAD_FINISH ) self:SetNextPrimaryFire(CurTime() + self:GetTrueSequenceDuration()) end end function SWEP:HandleBurstDelay() -- Shared if self.HasBurstFire or self.AlwaysBurst then if self:GetIsBurst() then if self:GetFireQueue() == 0 then local NumBullets = self.BurstOverride - 1 if self.BurstAnimationOnce then self:HandleShootAnimations() end self:SetNextFireDelay(CurTime() + self:GetBurstMath() ) self:SetFireQueue(NumBullets) end end end end function SWEP:GetBurstMath() -- Shared return self.BurstPerBulletDelay or (self.BurstSpeedOverride * self.Primary.Delay) / self.BurstOverride end function SWEP:SpecialDelay(delay) -- Shared return delay end function SWEP:GetDelay() -- Shared local Delay = self.Primary.Delay if self.HasBuildUp then Delay = Delay + ( (self.Primary.Delay*5) * (100 - self:GetBuildUp()) * 0.01 ) end if self.HasBurstFire or self.AlwaysBurst then if self:GetIsBurst() then if self.BurstPerVolleyDelay then Delay = self.BurstPerVolleyDelay elseif self.BurstSpeedAbs then Delay = self.BurstSpeedAbs else Delay = Delay * (self.BurstOverride*2) end end end if self.Owner:IsBot() and !self.Primary.Automatic then Delay = math.Clamp(Delay,1/8,100) end return self:SpecialDelay(Delay) end function SWEP:ModBoltDelay() -- Shared return self:SpecialDelay(self.Primary.Delay) end function SWEP:WeaponDelay() -- Shared if self.HasBoltAction then self:SetBoltDelay( CurTime() + self:ModBoltDelay() ) self:SetZoomOverlayDelay( CurTime() + self:ModBoltDelay() ) end self:SetNextPrimaryFire( CurTime() + self:GetDelay() ) end function SWEP:AfterZoom() -- Shared --[[ if self.HasScope then if self.HasBoltAction then if self:GetZoomed() then --self:SetZoomOverlayDelay( CurTime() + self.Owner:GetViewModel():SequenceDuration() ) --self:SetBoltDelay( CurTime() + self.Owner:GetViewModel():SequenceDuration() ) end end end --]] end function SWEP:GetScopeSway(Cone) -- Unknown local x = math.sin(CurTime()*0.5)*Cone*0.5*0.5 local y = math.cos(CurTime())*Cone*0.5 return x,y end SWEP.BulletQueueShots = 0 SWEP.BulletQueueDelay = 0.01 function SWEP:HandleBulletQueue() -- Shared if self.BulletQueueShots > 0 and self:GetBulletQueue() > 0 and self:GetBulletQueueDelay() <= CurTime() then local Damage = self:SpecialDamage(self.Primary.Damage) local Shots = math.min(self.BulletQueueShots,self:GetBulletQueue(),self:SpecialShots(self.Primary.NumShots)) local Cone = 0 if IsFirstTimePredicted() then Cone = self:HandleCone(self.Primary.Cone,false, (self.HasDual and self:GetIsLeftFire()) ) end self:PreShootBullet(Damage,Shots,Cone) self:SetBulletQueue( math.max(0,self:GetBulletQueue() - Shots)) self:SetBulletQueueDelay(CurTime() + self.BulletQueueDelay) end end function SWEP:BulletMethod01(Damage,Shots,Cone,WithPunchAngles) -- Shared local ConeMinusPrimary = Cone if Shots > 1 then ConeMinusPrimary = math.max(self.Primary.Cone,Cone - self.Primary.Cone) end local FireMul = 1 if self.HasDual and self:GetIsLeftFire() then FireMul = -1 end local PitchMulti = self:BulletRandomSeed(-100,100,0) / 100 local YawMulti = self:BulletRandomSeed(-100,100,0 + 100) / 100 local AngleToAdd = Angle(ConeMinusPrimary*PitchMulti*45,ConeMinusPrimary*YawMulti*45*FireMul,0) AngleToAdd:Normalize() local NewVector, NewAngle = LocalToWorld(Vector(0,0,0),AngleToAdd,Vector(0,0,0),WithPunchAngles) NewAngle:Normalize() if Shots == 1 then self:ShootBullet(Damage,Shots,0,self.Owner:GetShootPos(),NewAngle:Forward(),self.Owner) else for i=1, Shots do local NewPitchMulti = self:BulletRandomSeed(-100,100,i + Shots + self:GetFireQueue()) / 100 local NewYawMulti = self:BulletRandomSeed(-100,100,i + Shots + 100 + self:GetFireQueue()) / 100 local NewAngleToAdd = Angle(self.Primary.Cone*NewPitchMulti*45,self.Primary.Cone*NewYawMulti*45,0) NewAngleToAdd:Normalize() local NewNewVector, NewNewAngle = LocalToWorld(Vector(0,0,0),NewAngleToAdd,Vector(0,0,0),NewAngle) --NewNewAngle = NewAngle + NewAngleToAdd if Cone < self.Primary.Cone then NewNewAngle = NewAngle end NewNewAngle:Normalize() if self.Owner and self.Owner:IsValid() then self:ShootBullet(Damage,Shots,0,self.Owner:GetShootPos(),NewNewAngle:Forward(),self.Owner) end end end end function SWEP:BulletMethod02(Damage,Shots,WithPunchAngles) -- Shared local IsLeftFire = self:GetIsLeftFire() local RandomCone = 0 RandomCone = self:PreSeededCone(RandomCone,false,IsLeftFire) RandomCone = self:HandleConeMovement(RandomCone,false,IsLeftFire) local SeededCone = self.Primary.Cone SeededCone = self:HandleConeBase(SeededCone,false,IsLeftFire) SeededCone = self:SpecialConePre(SeededCone,false,IsLeftFire) SeededCone = self:HandleConeEquipment(SeededCone,false,IsLeftFire) SeededCone = self:HandleConeCooldown(SeededCone,false,IsLeftFire) SeededCone = self:SpecialConePost(SeededCone,false,IsLeftFire) local FireMul = 1 if self.HasDual and IsLeftFire then FireMul = -1 end for i=1, Shots do local PitchMulti = self:BulletRandomSeed(-100,100,0 + Shots+i) / 100 local YawMulti = self:BulletRandomSeed(-100,100,0 + 100 + Shots+i) / 100 local AngleToAdd = Angle(SeededCone*PitchMulti*45,SeededCone*YawMulti*45*FireMul,0) AngleToAdd:Normalize() local NewVector, NewAngle = LocalToWorld(Vector(0,0,0),AngleToAdd,Vector(0,0,0),WithPunchAngles) local ShootPos = self:GetPos() if self.Owner and self.Owner ~= NULL and self.Owner:IsPlayer() or self.Owner:IsNPC() then ShootPos = self.Owner:GetShootPos() end self:ShootBullet(Damage,Shots,RandomCone,ShootPos,NewAngle:Forward(),self.Owner) end end function SWEP:PreShootBullet(Damage,Shots,Cone) -- Don't predict -- Shared local WithPunchAngles = self:GetTrueShootAngles() --self:BulletMethod01(Damage,Shots,Cone,WithPunchAngles) self:BulletMethod02(Damage,Shots,WithPunchAngles) end function SWEP:PostPrimaryFire() -- Shared end SWEP.AnimationRateTable = {} function SWEP:WeaponAnimation(clip,animation) -- Shared if self:GetIsSilenced() then if clip == 1 and self.HasDryFire then animation = ACT_VM_DRYFIRE_SILENCED else animation = ACT_VM_PRIMARYATTACK_SILENCED end elseif self.HasDryFire and self.HasDual then if clip == 0 then animation = nil elseif clip <= 2 then if !self:GetIsLeftFire() then animation = ACT_VM_DRYFIRE_LEFT else animation = ACT_VM_DRYFIRE end end elseif clip == 1 and self.HasDryFire then animation = ACT_VM_DRYFIRE end if animation then self:SendWeaponAnimation(animation,0,1) end end function SWEP:WeaponSound() -- Shared local GunSound = self.Primary.Sound local SoundMul = 1 if self.LastBulletSound and self:Clip1() == 0 then GunSound = self.LastBulletSound end if self.HasSilencer then if self:GetIsSilenced() then GunSound = self.Secondary.Sound SoundMul = 0.1 end end if self.HasBurstFire or self.AlwaysBurst then if self.BurstSound != nil then if self:GetIsBurst() then GunSound = self.BurstSound end end end if GunSound ~= nil then self:EmitGunSound(GunSound, ((50 + self:SpecialDamage(self.Primary.Damage) )/100)*SoundMul ) end end function SWEP:SpecialConePre(Cone,IsCrosshair,IsLeftFire) -- Shared return Cone end function SWEP:SpecialConePost(Cone,IsCrosshair,IsLeftFire) -- Shared return Cone end function SWEP:HandleConeEquipment(Cone,IsCrosshair,IsLeftFire) -- Shared if (self.HasBurstFire or self.AlwaysBurst) then if self:GetIsBurst() then Cone = Cone * self.BurstConeMul end elseif self.HasSilencer then if self:GetIsSilenced() then Cone = Cone*0.9 end end return Cone end function SWEP:HandleConeCooldown(Cone,IsCrosshair,IsLeftFire) -- Shared if self.HasFirstShotAccurate and ((self:GetCoolDown() == 0 and !IsLeftFire) or (IsLeftFire and self:GetCoolDownLeft() == 0)) and IsCrosshair == false then Cone = 0 else if IsLeftFire then Cone = Cone + (self:GetCoolDownLeft()*self.HeatMul*0.01) else Cone = Cone + (self:GetCoolDown()*self.HeatMul*0.01) end end return Cone end function SWEP:HandleConeBase(Cone,IsCrosshair,IsLeftFire) -- Shared if self.Owner:IsPlayer() and !self.Owner:Crouching() then Cone = Cone * 1.25 end Cone = Cone * BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_baseconescale",false):GetFloat() return Cone end function SWEP:HandleConeMovement(Cone,IsCrosshair,IsLeftFire) -- Shared return Cone + self:GetMovementIntensity() end function SWEP:PreSeededCone(Cone,IsCrosshair,IsLeftFire) -- Shared return Cone end function SWEP:HandleCone(Cone,IsCrosshair,IsLeftFire) -- Shared Cone = self:HandleConeBase(Cone,IsCrosshair,IsLeftFire) Cone = self:SpecialConePre(Cone,IsCrosshair,IsLeftFire) Cone = self:HandleConeEquipment(Cone,IsCrosshair,IsLeftFire) Cone = self:HandleConeCooldown(Cone,IsCrosshair,IsLeftFire) Cone = self:SpecialConePost(Cone,IsCrosshair,IsLeftFire) Cone = self:PreSeededCone(Cone,IsCrosshair,IsLeftFire) Cone = self:HandleConeMovement(Cone,IsCrosshair,IsLeftFire) return Cone end function SWEP:GetMovementVelocity() -- Shared local Velocity = self.Owner:GetVelocity():Length() if (!self.Owner:IsOnGround() and !(self.Owner:WaterLevel() > 0)) then Velocity = math.max(Velocity*1.25,400) end return Velocity end function SWEP:GetMovementIntensity() -- Shared return math.Clamp( ( (self:GetMovementVelocity() * self.MoveConeMul * BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_movementconescale"):GetFloat()) ^ 1.75 ) * 0.000001, 0, 0.1) end function SWEP:SpecialFire() -- Shared self:Melee() end function SWEP:SecondaryAttack() -- Shared local ToggleZoomEnabled = ToggleZoom --BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_togglezoom",true):GetFloat() == 1 if IsFirstTimePredicted() then self:HandleCancelZoom() end if self:IsBusy() then return end if self:IsUsing() then if self.HasSpecialFire then self:SpecialFire() end elseif (IsFirstTimePredicted() or IsSingleplayer) then if self:CanZoom() and ToggleZoomEnabled and not self:IsSprinting() then self:HandleZoom(1) end end end function SWEP:HandleSprintCancelZoom() -- Shared if self:IsSprinting() and self:GetZoomed() then self:ZoomOut() end end function SWEP:HandleCancelZoom() -- Shared local ToggleZoomEnabled = ToggleZoom == true if ToggleZoomEnabled and self.HasBoltAction and self:GetZoomOverlayDelay() >= CurTime() and (self.HasScope or self.HasIronsights) then if self:GetZoomed() then self:ZoomOut() end end end function SWEP:HandleHoldToZoom() -- Shared --if (IsFirstTimePredicted() or IsSingleplayer) and not self:IsBusy() and not self:IsUsing() and BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_togglezoom",true):GetFloat() == 0 then if (IsFirstTimePredicted() or IsSingleplayer) and not self:IsBusy() and not self:IsUsing() and ToggleZoom == false then if self:GetZoomed() and (!self.Owner:KeyDown(IN_ATTACK2) or !self:CanZoom()) then self:ZoomOut() elseif self.Owner:KeyDown(IN_ATTACK2) and !self:GetZoomed() and self:CanZoom() then self:ZoomIn() end end end function SWEP:CanZoom() -- Shared return (self:CanBoltZoom() and (self.HasIronSights or self.HasScope)) end function SWEP:Melee() -- Shared if self:IsBusy() then return end if self:GetNextPrimaryFire() > CurTime() then return end self:SetNextPrimaryFire(CurTime() + 1) self.Owner:DoAnimationEvent( ACT_GMOD_GESTURE_MELEE_SHOVE_2HAND ) self:StartSwing(self.MeleeDamage) end function SWEP:SwitchFireMode() -- Shared if not (IsFirstTimePredicted() or IsSingleplayer) then return end if not (self:GetNextPrimaryFire() <= CurTime()) then return end local Message = "Semi-Automatic" if self.Primary.Automatic then Message = "Automatic" end if self:GetIsBurst() then self:SetIsBurst(false) if (CLIENT or IsSingleplayer) then self:EmitGunSound("weapons/smg1/switch_single.wav",0.01) end self.Owner:PrintMessage( HUD_PRINTCENTER, "Switched to "..Message ) else self:SetIsBurst(true) if (CLIENT or IsSingleplayer) then self:EmitGunSound("weapons/smg1/switch_burst.wav",0.01) end self.Owner:PrintMessage( HUD_PRINTCENTER, "Switched to Burst Fire Mode" ) end self:SetNextPrimaryFire(CurTime() + 0.25) end function SWEP:Silencer() -- Shared if self:IsBusy() then return end if self:GetIsSilenced() then self:SendWeaponAnimation(ACT_VM_DETACH_SILENCER) if not (IsFirstTimePredicted() or IsSingleplayer) then return end self.WorldModel = self.WorldModel1 self:SetIsSilenced(false) else self:SendWeaponAnimation(ACT_VM_ATTACH_SILENCER) if not (IsFirstTimePredicted() or IsSingleplayer) then return end self.WorldModel = self.WorldModel2 self:SetIsSilenced(true) end self:SetAttachDelay(CurTime() + self:GetTrueSequenceDuration()) end function SWEP:HandleZoom(delay) -- Shared if not (IsFirstTimePredicted()) then return end if not self:CanBoltZoom() then return end --if self:IsBusy() then return end if self:GetZoomed() then self:ZoomOut() else self:ZoomIn() end end function SWEP:ZoomIn() -- Shared if self.HasScope then if self.ZoomInSound then if CLIENT or IsSingleplayer then self.Owner:EmitSound(self.ZoomInSound,0.01) end end if self.ZoomDelay > 0 then self:SetZoomOverlayDelay(CurTime() + self.ZoomDelay) end end self:SetZoomed(true) end function SWEP:ZoomOut() -- Shared self:SetZoomed(false) if self.HasScope then if self.ZoomOutSound then if CLIENT then self.Owner:EmitSound(self.ZoomOutSound,0.01) end end if self.ZoomDelay > 0 then self:SetZoomOverlayDelay(0) end end end function SWEP:CanBoltZoom() -- Shared return !self.HasBoltAction or self:GetBoltDelay() <= CurTime() end function SWEP:SpecialZoom(fov) -- Shared return fov end function SWEP:CanPrimaryAttack() -- Shared if self:GetNextPrimaryFire() > CurTime() then return false end return true end function SWEP:CanSecondaryAttack() -- Shared if self:GetNextSecondaryFire() > CurTime() then return false end return true end function SWEP:SpecialDamage(damage) -- Shared return damage end function SWEP:SpecialShots(shots) -- Shared return shots end function SWEP:GetRecoilMath() -- Client? return self:SpecialDamage(self.Primary.Damage)*self:SpecialShots(self.Primary.NumShots)*self.RecoilMul*self.Primary.Delay*1.875 end function SWEP:SpecialRecoil(recoil) -- Client? return recoil end function SWEP:GetRecoilFinal() -- Client? local UpPunch = -self:GetRecoilMath() local SidePunch = 0 if (self.HasBurstFire or self.AlwaysBurst) and self:GetIsBurst() then UpPunch = UpPunch*self.BurstRecoilMul end local AvgBulletsShot = 0 if self.Primary.Automatic == true then local HeatMath = self:GetHeatMath( self:SpecialDamage(self.Primary.Damage) , self:SpecialShots(self.Primary.NumShots) ) if self.HasDual and self:GetIsLeftFire() then if SERVER or IsSingleplayer then AvgBulletsShot = (self:GetCoolDownLeft() / math.max(0.001,HeatMath) ) else AvgBulletsShot = (self.ClientCoolDownLeft / math.max(0.001,HeatMath) ) end else if SERVER or IsSingleplayer then AvgBulletsShot = (self:GetCoolDown() / math.max(0.001,HeatMath) ) else AvgBulletsShot = (self.ClientCoolDown / math.max(0.001,HeatMath) ) end end end UpPunch = UpPunch * ( 1 + AvgBulletsShot/ (1/self.Primary.Delay) ) local PredictedUpPunch = -UpPunch if CLIENT then PredictedUpPunch = -UpPunch + -self.PunchAngleUp.p end local DelayMul = 1 if self.Primary.Delay >= 0.5 and not self.DelayOverride then DelayMul = 0 end if self.HasSideRecoil then if self.SideRecoilBasedOnDual then if self:GetIsLeftFire() then SidePunch = UpPunch*1*self.SideRecoilMul else SidePunch = UpPunch*-1*self.SideRecoilMul end elseif DelayMul == 1 then if AvgBulletsShot > 2*DelayMul then SidePunch = UpPunch*self:BulletRandomSeedInt(-1,1)*self.SideRecoilMul end else SidePunch = UpPunch*self.SideRecoilMul end end if self.HasDownRecoil then if AvgBulletsShot > 3*DelayMul then UpPunch = UpPunch*self:BulletRandomSeedInt(-1,2)*self.SideRecoilMul end end if self.HasScope and self.ZoomAmount > 4 and self:GetZoomed() then UpPunch = UpPunch*0.5 SidePunch = SidePunch*0.5 end UpPunch = BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_recoilscale"):GetFloat() * UpPunch SidePunch = BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_recoilscale"):GetFloat() * SidePunch return self:SpecialRecoil(UpPunch), self:SpecialRecoil(SidePunch) end function SWEP:AddRecoil() -- Client? if CLIENT or IsSingleplayer then local UpPunch, SidePunch = self:GetRecoilFinal() self.PunchAngleUp = self.PunchAngleUp + Angle(UpPunch,SidePunch,0) + Angle(self.ShootOffsetStrength.p*self:BulletRandomSeed(-0.5,0.5,1),self.ShootOffsetStrength.y*self:BulletRandomSeed(-0.5,0.5,10),0) self.PunchAngleDown = self.PunchAngleDown + Angle(UpPunch,SidePunch,0) + Angle(self.ShootOffsetStrength.p*self:BulletRandomSeed(-0.5,0.5,100),self.ShootOffsetStrength.y*self:BulletRandomSeed(-0.5,0.5,1000),0) end end function SWEP:SpecialHeatMath(CoolDown) -- Shared return CoolDown end function SWEP:GetHeatMath(Damage,Shots) -- Shared local DamageMod = Damage*Shots*0.01 local ConeMod = (math.max(0.001,self.Primary.Cone)^-0.1) local WeightMod = math.Clamp(self.CSSMoveSpeed / 250,0.1,2) local BurstMod = 1 if (self.HasBurstFire or self.AlwaysBurst) and self:GetIsBurst() then BurstMod = self.BurstHeatMul end local CoolDown = DamageMod*ConeMod*WeightMod*BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_heatconescale"):GetFloat()*BurstMod return self:SpecialHeatMath(CoolDown) end function SWEP:AddHeat(Damage,Shots) -- Shared local CoolDown = self:GetHeatMath(Damage,Shots) local CoolTime = (self.Primary.Delay + 0.1)*self.CoolMul if self.HasBurstFire and self:GetIsBurst() then CoolTime = CoolTime * self.BurstCoolMul end if self.HasDual and self:GetIsLeftFire() then self:SetCoolDownLeft( math.Clamp(self:GetCoolDownLeft() + CoolDown,0,self.MaxHeat) ) self:SetCoolTimeLeft( CurTime() + CoolTime ) if CLIENT and self.Owner == LocalPlayer() then self.ClientCoolDownLeft = (math.Clamp(self.ClientCoolDownLeft + CoolDown,0,self.MaxHeat) + self:GetCoolDownLeft())/2 self.ClientCoolTimeLeft = CurTime() + CoolTime end else self:SetCoolDown( math.Clamp(self:GetCoolDown() + CoolDown,0,self.MaxHeat) ) self:SetCoolTime( CurTime() + CoolTime ) if CLIENT and self.Owner == LocalPlayer() then self.ClientCoolDown = (math.Clamp(self.ClientCoolDown + CoolDown,0,self.MaxHeat) + self:GetCoolDown())/2 self.ClientCoolTime = CurTime() + CoolTime end end end SWEP.UseSpecialProjectile = false SWEP.UseMuzzle = true function SWEP:ModProjectileTable(datatable) -- Shared local FalloffMod = math.Clamp(self.DamageFalloff,1,4000) local FalloffModDif = self.DamageFalloff - FalloffMod datatable.direction = datatable.direction*FalloffMod*4 datatable.hullsize = 2 datatable.usehull = true datatable.resistance = (datatable.direction*0.05) + Vector(0,0,math.Clamp(100 - FalloffModDif/4000,0,100)) datatable.dietime = CurTime() + 50 datatable.id = "css_bullet" return datatable end function SWEP:ShootProjectile(Damage, Shots, Cone, Source, Direction,AimCorrection) -- Client BURGERBASE_FUNC_ShootProjectile(self.Owner,self,Damage,Shots,Cone,Source,Direction,nil,true) end function SWEP:ShootBullet(Damage, Shots, Cone, Source, Direction,LastEntity) -- Shared if self then if self.UseSpecialProjectile then if CLIENT then self:ShootProjectile(Damage, Shots, Cone, Source, Direction,true) end elseif self.BulletEnt then if SERVER then self:ShootPhysicalObject(Source,Cone,Direction) end else local bullet = {} bullet.Damage = Damage * BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damagescale"):GetFloat() bullet.Num = 1 bullet.Spread = Vector(Cone, Cone, 0) bullet.Src = Source bullet.Dir = Direction bullet.AmmoType = self:GetPrimaryAmmo() bullet.HullSize = 0 bullet.Tracer = 0 bullet.Force = nil bullet.Callback = function(attacker,tr,dmginfo) self:BulletCallback(Damage,Direction,LastEntity,attacker,tr,dmginfo) end self.Owner:FireBullets(bullet) end end end function SWEP:BulletCallback(Damage,Direction,PreviousHitEntity,attacker,tr,dmginfo) -- Shared local CurrentHitEntity = tr.Entity if IsFirstTimePredicted() then self:TracerCreation(tr.HitPos,tr.StartPos,Direction,PreviousHitEntity) end if attacker:IsPlayer() then local Weapon = attacker:GetActiveWeapon() if Weapon and Weapon.DamageFalloff and Weapon:SpecialFalloff(Weapon.DamageFalloff) then if Weapon:SpecialFalloff(Weapon.DamageFalloff) > 0 then local MatterScale = BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damagefalloffscale"):GetFloat() local Falloff = Weapon:SpecialFalloff(Weapon.DamageFalloff) local Distance = tr.StartPos:Distance(tr.HitPos) local DamageScale = math.Clamp(math.min( (2) - (Distance/Falloff),1),0,1) local FinalValue = math.Clamp(DamageScale,MatterScale,1) dmginfo:ScaleDamage(FinalValue) end end if BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_enable_penetration"):GetFloat() == 1 then self:WorldBulletSolution(tr.HitPos,tr,Direction,Damage,CurrentHitEntity) end --[[ if SERVER then if tr.Entity:GetClass() == "prop_vehicle_prisoner_pod" or CurrentHitEntity:IsVehicle() then if CurrentHitEntity:GetDriver() ~= NULL then CurrentHitEntity:GetDriver():TakeDamageInfo(dmginfo) end end end --]] end end function SWEP:StartShortTrace(Pos,Direction,Distance,shouldcomp) -- Shared local data = {} data.start = Pos + Direction data.endpos = Pos + Direction*Distance data.mask = MASK_SHOT if shouldcomp and self.Owner:IsPlayer() then self.Owner:LagCompensation( true ) end local Trace = util.TraceLine(data) if shouldcomp and self.Owner:IsPlayer() then self.Owner:LagCompensation( false ) end return Trace end function SWEP:CalculateMaterialPenetration(mat) -- Shared local MatMul = 1 if mat == MAT_GLASS then MatMul = 0.5 elseif mat == MAT_SAND or mat == MAT_SNOW or mat == MAT_DIRT then MatMul = 2 elseif mat == MAT_ANTLION or mat == MAT_ALIENFLESH or mat == MAT_FLESH then MatMul = 0.75 elseif mat == MAT_CONCRETE then MatMul = 5 elseif mat == MAT_METAL then MatMul = 10 end return MatMul end function SWEP:BulletRandomGetSeed(seed) -- Shared seed = math.floor(seed) + self.RandomSeed + string.len(self.PrintName) local Precision = 1 if !self.Primary.Automatic then Precision = 0 end if self.HeatMul == 0 or self.DontSeedFire then return math.randomseed( CurTime() + seed ) elseif self.HasDual and self:GetIsLeftFire() then if self:GetCoolDownLeft() == self.MaxHeat then return math.randomseed( CurTime() + seed ) else return math.randomseed( math.Round(self:GetCoolDownLeft(),1) + seed) end else if self:GetCoolDown() == self.MaxHeat then return math.randomseed( CurTime() + seed ) else return math.randomseed( math.Round(self:GetCoolDown(),1) + seed) end end end function SWEP:BulletRandomSeedInt(min,max,seed) -- Shared if not seed then seed = 0 end self:BulletRandomGetSeed(seed) return math.random(min,max) end function SWEP:BulletRandomSeed(min,max,seed) -- Shared if not seed then seed = 0 end self:BulletRandomGetSeed(seed) return math.Rand(min,max) end function SWEP:WorldBulletSolution(Pos,OldTrace,Direction,Damage,PreviousHitEntity) -- Shared local Distance = 3 local Randomness = 0.05 --local NewDirection = (OldTrace.HitPos - OldTrace.StartPos):GetNormalized() local RangeMod = self:SpecialFalloff(self.DamageFalloff)/5000 local BulletAngleMod = math.Clamp(math.Clamp(RangeMod,0.25,0.5) * math.Rand(1 - (Randomness/2),1 + (Randomness/2)),0,0.5) local DirectionForRichochet = -2 * Direction:Dot(OldTrace.HitNormal) * OldTrace.HitNormal + Direction local OldDirectionForRichochet = DirectionForRichochet DirectionForRichochet:Normalize() local AngleOfAttack = math.deg( math.acos(DirectionForRichochet:Dot( Direction ) )) / 2 DirectionForRichochet = LerpVector(BulletAngleMod,DirectionForRichochet,Direction) DirectionForRichochet:Normalize() local LocalVec, LocalAng = WorldToLocal( Vector(0,0,0), Direction:Angle(), Vector(0,0,0), DirectionForRichochet:Angle() ) local mat = OldTrace.MatType local ShouldRichochet = AngleOfAttack < 30 and mat == MAT_METAL local CurrentHitEntity = OldTrace.Entity local ShouldPenetrate = AngleOfAttack < 1 or AngleOfAttack >= 30 local DamageMath = 0 if ShouldPenetrate then if IsValid(PreviousHitEntity) and (PreviousHitEntity:IsPlayer() or PreviousHitEntity:IsNPC()) then local Before = Direction*PreviousHitEntity:OBBMaxs() Distance = (Before):Length() end local MatMul = self:CalculateMaterialPenetration(mat) local DamageLoss = BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_penetration_scale"):GetFloat() * MatMul * math.max(0.1,self.PenetrationLossMul) * Distance DamageMath = math.Round(Damage - DamageLoss,2) elseif ShouldRichochet then DamageMath = math.Round((Damage * 0.9) - 1) Distance = 0 Direction = DirectionForRichochet if IsFirstTimePredicted() then --EmitSound(self.RichochetSound[math.random(1,#self.RichochetSound)],Pos, self:EntIndex(), CHAN_AUTO, 0.5, SNDLVL_NORM, SND_NOFLAGS, 100 ) end end local ShouldEmit = ( ShouldPenetrate or ShouldRichochet ) and DamageMath > 1 local trace = self:StartShortTrace(Pos,Direction,Distance,false) if ShouldEmit then if trace.StartSolid then if IsFirstTimePredicted() then self:WorldBulletSolution(Pos + Direction*Distance,trace,Direction,DamageMath,CurrentHitEntity) end else if IsFirstTimePredicted() then self:ShootBullet(DamageMath, 1, 0, Pos + Direction*Distance,Direction,CurrentHitEntity) end local BackTraceData = {} BackTraceData.start = Pos + Direction BackTraceData.endpos = Pos - Direction*Distance local BackTrace = util.TraceLine(BackTraceData) if IsFirstTimePredicted() then self:BulletEffect(BackTrace.HitPos,BackTrace.StartPos,BackTrace.Entity,BackTrace.SurfaceProps) end end end end function SWEP:TracerCreation(origin,start,direction,HitEntity) -- Shared if self.EnableCustomTracer then local TracerData = self:GenerateEffectData(origin,start,HitEntity,true) util.Effect( "effect_burger_core_bullet", TracerData ) end if self.CustomShootEffectsTable then local TracerData = self:GenerateEffectData(origin,start,HitEntity,false) for num,effectname in pairs(self.CustomShootEffectsTable) do util.Effect( effectname, TracerData ) end end end function SWEP:GenerateEffectData(origin,start,HitEntity,IsCSSTracer) -- Shared local Data = EffectData() Data:SetOrigin( origin ) Data:SetStart( start ) if HitEntity == self.Owner then if self.HasDual and self:GetIsLeftFire() then Data:SetAttachment( 2 ) else Data:SetAttachment( 1 ) end Data:SetEntity( self.Weapon ) else Data:SetAttachment( 0 ) Data:SetEntity( NULL ) end if IsCSSTracer then Data:SetMagnitude( self:SpecialDamage(self.Primary.Damage) ) Data:SetRadius(self:SpecialFalloff(self.DamageFalloff)) Data:SetDamageType(self.DamageType) end return Data end if SERVER then util.AddNetworkString("CSS_GunSounds") end function SWEP:EmitGunSound(GunSound,Level) -- Shared if GunSound and GunSound ~= NULL then --if CLIENT or IsSingleplayer then --print("HI?") self.Weapon:EmitSound(GunSound) --end --[[ if SERVER then local Position = self.Owner:GetPos() if sound.GetProperties(GunSound) then if IsFirstTimePredicted() then net.Start("CSS_GunSounds") net.WriteFloat(self.Weapon:EntIndex()) net.Broadcast() end end end --]] end end if CLIENT then -- Client net.Receive("CSS_GunSounds", function(len) local ply = LocalPlayer() local ID = net.ReadFloat() local Gun = Entity(ID) if not Gun or Gun == NULL or not Gun.Owner or Gun.Owner == NULL or Gun.Owner == ply then return end local GunSound = Gun.Primary.Sound local RealSoundTable = sound.GetProperties(GunSound) local Distance = math.floor(ply:GetPos():Distance(Gun:GetPos())) local FakePos = ply:EyePos() + (- Gun.Owner:GetShootPos() + ply:EyePos() ):GetNormalized()*50 local Power = ( Gun:SpecialDamage(Gun.Primary.Damage) * Gun:SpecialShots(Gun.Primary.NumShots) ) local Falloff = 1024 local Range = 20000 local Calc = math.Clamp(1 - ( (Distance - (Falloff*(Power/100)) ) / Range ),0,1 ) local SoundToPlay = RealSoundTable.sound if type(SoundToPlay) == "table" then SoundToPlay = SoundToPlay[math.random(1,#SoundToPlay)] end --print(Calc) EmitSound(SoundToPlay,FakePos,ID,CHAN_WEAPON,Calc,140,0,math.Clamp(100*Calc*1.25,0,100)) end) end function SWEP:BulletEffect(HitPos,StartPos,HitEntity,SurfaceProp,DamageType) -- Shared if not DamageType then DamageType = DMG_BULLET end if HitEntity:IsPlayer() then return end local effect = EffectData() effect:SetOrigin(HitPos) effect:SetStart(StartPos) effect:SetSurfaceProp(SurfaceProp) effect:SetDamageType(DamageType) if (CLIENT or IsSingleplayer) then effect:SetEntity(HitEntity) else effect:SetEntIndex(HitEntity:EntIndex()) end util.Effect("Impact", effect) end function SWEP:IsSprinting() -- Shared local SideVelocity = self.Owner:GetVelocity() SideVelocity = SideVelocity - Vector(0,0,SideVelocity.z) SideVelocity = SideVelocity:Length() return SideVelocity > 1 and self.Owner:IsOnGround() and self.Owner:KeyDown(IN_SPEED) end function SWEP:IsBusy() -- Shared if not self:GetCanHolster() then return true elseif self:GetIsReloading() then return true elseif self.HasSilencer and self:GetAttachDelay() > CurTime() then return true end return false end function SWEP:IsUsing() -- Shared if self.Owner:IsPlayer() and self.Owner:KeyDown(IN_USE) then return true end end function SWEP:ReloadSpecial() -- Shared if self.HasBurstFire then self:SwitchFireMode() elseif self.HasSilencer then self:Silencer() elseif self.SpecialAmmo then local OldAmmo = self:GetPrimaryAmmo() local ShouldSwitch = false if self.DisableReloadUntilEmpty and self:Clip1() > 0 then elseif self:GetPrimaryAmmo() == game.GetAmmoID(self.SpecialAmmo[1]) and self.Owner:GetAmmoCount(self.SpecialAmmo[2]) > 0 then self:SetPrimaryAmmo(game.GetAmmoID(self.SpecialAmmo[2])) if (CLIENT or IsSingleplayer) and IsFirstTimePredicted() then self.Owner:PrintMessage( HUD_PRINTTALK, "Switched to " .. language.GetPhrase("#" .. self.SpecialAmmo[2] .. "_ammo") .. " (Secondary)" ) end ShouldSwitch = true elseif self:GetPrimaryAmmo() == game.GetAmmoID(self.SpecialAmmo[2]) and self.Owner:GetAmmoCount(self.SpecialAmmo[1]) > 0 then self:SetPrimaryAmmo(game.GetAmmoID(self.SpecialAmmo[1])) if (CLIENT or IsSingleplayer) and IsFirstTimePredicted() then self.Owner:PrintMessage( HUD_PRINTTALK, "Switched to " .. language.GetPhrase("#" .. self.SpecialAmmo[1] .. "_ammo") .. " (Primary)" ) end ShouldSwitch = true end if ShouldSwitch then if SERVER then self.Owner:GiveAmmo(self:Clip1(),OldAmmo,true) end self:SetClip1(0) self:DoReload() end end end SWEP.SequenceDurationAdd = {} function SWEP:GetTrueSequenceDuration() -- Shared local ViewModel = self.Owner:GetViewModel() return ( ViewModel:SequenceDuration() * (1/ViewModel:GetPlaybackRate()) ) + (self.SequenceDurationAdd[ViewModel:GetSequenceActivity(ViewModel:GetSequence())] or 0) end function SWEP:DoReload() -- Shared if self:GetZoomed() then self:SetZoomed(false) end if SERVER then if self.HasPumpAction == false then if self:Clip1() > 0 then self.Owner:GiveAmmo(self:Clip1(),self:GetPrimaryAmmo(),true) self:SetClip1(0) end end end if self.HasSilencer then if self:GetIsSilenced() then self:SendWeaponAnimation(ACT_VM_RELOAD_SILENCED) else self:SendWeaponAnimation(ACT_VM_RELOAD) end else self:SendWeaponAnimation(ACT_VM_RELOAD) end if (CLIENT or IsSingleplayer) then if self.ReloadSound then if not self.HasPumpAction then self:EmitGunSound(self.ReloadSound) end end end if self.HasPumpAction then self:SendWeaponAnimation(ACT_SHOTGUN_RELOAD_START) self:SetNextShell(CurTime() + self:GetTrueSequenceDuration()) self:SetIsShotgunReload(true) else self:SetReloadFinish(CurTime() + self:GetTrueSequenceDuration() ) self:SetIsNormalReload(true) end self.Owner:SetAnimation(PLAYER_RELOAD) if SERVER then if BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_enable_mags"):GetFloat() == 1 then timer.Simple(self.MagDelayMod, function() if self.GetMagModel and self.HasMagIn then self.HasMagIn = false local EyeAngle = self.Owner:EyeAngles() local mag = ents.Create("ent_burger_core_debris") mag:SetPos(self.Owner:GetShootPos() + self.Owner:GetUp()*-12 + self.Owner:GetRight()*3) mag:SetModel(self.GetMagModel) mag:SetAngles(EyeAngle + self.MagAngMod) mag:Spawn() mag:Activate() if not self.HasDual then local Phys = mag:GetPhysicsObject() if Phys ~= nil and Phys ~= NULL then Phys:SetVelocity(self.MagMoveMod.x*EyeAngle:Right() + self.MagMoveMod.y*EyeAngle:Forward() + self.MagMoveMod.z*EyeAngle:Up()) end end SafeRemoveEntityDelayed(mag,30) if self.HasDual then local mag = ents.Create("ent_burger_core_debris") mag:SetPos(self.Owner:GetShootPos() + self.Owner:GetUp()*-12 + self.Owner:GetRight()*-3) mag:SetModel(self.GetMagModel) mag:SetAngles(EyeAngle + Angle(1,1,1) + self.MagAngMod ) mag:Spawn() mag:Activate() SafeRemoveEntityDelayed(mag,30) end end end) end end self:SetIsReloading(true) end function SWEP:Reload() -- Shared if self:IsBusy() then return end if self.Owner:KeyDown(IN_USE) then self:ReloadSpecial() return end if self:Clip1() >= self.Primary.ClipSize then return end if self:GetNextPrimaryFire() > CurTime() then return end if self.WeaponType == "Throwable" then return end if (self:Clip1() > 0 and self.DisableReloadUntilEmpty) then return end if self.Owner:GetAmmoCount(self:GetPrimaryAmmo()) == 0 then if self.Owner:IsBot() then self.Owner:GiveAmmo(self.Primary.ClipSize,self:GetPrimaryAmmo(),true) end return end self:DoReload() end SWEP.IronBoltPos = Vector(0,0,-2) SWEP.IronBoltAng = Vector(0,0,0) SWEP.IronIdlePos = Vector(0,0,0) SWEP.IronIdleAng = Vector(0,0,0) SWEP.IronReloadPos = Vector(0,0,0) SWEP.IronReloadAng = Vector(0,0,0) SWEP.HoldTypeBlocking = "melee2" function SWEP:HandleHoldType() -- shared if !self.CanShootWhileSprinting and self:IsSprinting() then self:SetHoldType("passive") elseif self.HoldTypeBlocking and self:GetIsBlocking() then self:SetHoldType(self.HoldTypeBlocking) elseif self:GetHoldType() ~= self.HoldType then self:SetHoldType(self.HoldType) end end function SWEP:HandleShotgunReloadCancel() -- Shared if self.Owner:KeyDown(IN_ATTACK) and self:GetIsShotgunReload() and self:GetIsReloading() and not self.Owner:IsBot() then self:FinishShotgunReload() end end SWEP.ClientTrueAimAng = Angle(0,0,0) function SWEP:GetTrueAimAng(prediction) if CLIENT and !prediction then return self.ClientTrueAimAng else return self:GetSharedTrueAimAng() end end function SWEP:SetTrueAimAng(var) self:SetSharedTrueAimAng(var) if CLIENT then self.ClientTrueAimAng = var end end function SWEP:GetTrueShootAngles(IgnorePrediction) -- Shared local ShootDir = self.Owner:GetAimVector() if self.Owner:IsPlayer() then ShootDir = self.Owner:GetEyeTrace().Normal end local WithPunchAngles = self.Owner:GetPunchAngle() + ShootDir:Angle() --local WithPunchAngles = (self.Owner:GetPunchAngle() + self:GetTrueAimAng() ) WithPunchAngles:Normalize() return WithPunchAngles end function BURGERBASE_SpecialGetBest(tab,dolarge) local Winner = tab[1] for k,v in pairs(tab) do if dolarge then if math.abs(Winner) < math.abs(v) then Winner = v end else if math.abs(Winner) > math.abs(v) then Winner = v end end end return Winner end function SWEP:CalculateAngleMovement(angle,movement) local MoveAngle = Angle(0,0,0) local Largest = math.abs(BURGERBASE_SpecialGetBest({angle.p,angle.y,angle.r},true)) if Largest ~= 0 then if angle.p ~= 0 then MoveAngle = MoveAngle + Angle(BURGERBASE_SpecialGetBest({angle.p,movement*(angle.p/Largest)},false),0,0) end if angle.y ~= 0 then MoveAngle = MoveAngle + Angle(0,BURGERBASE_SpecialGetBest({angle.y,movement*(angle.y/Largest)},false),0) end if angle.r ~= 0 then MoveAngle = MoveAngle + Angle(0,0,BURGERBASE_SpecialGetBest({angle.r,movement*(angle.r/Largest)},false)) end end return MoveAngle end function SWEP:HandleAimAngles() -- Shared local ShootAng = self.Owner:GetAimVector():Angle() -- Start Angle local DesiredAngOffset = Angle(0,0,0) if self.IronMeleeAng and IsMelee then DesiredAngOffset = DesiredAngOffset + Angle(self.IronMeleeAng.x,self.IronMeleeAng.y,self.IronMeleeAng.z) elseif self.IronReloadAng and self:GetIsReloading() then DesiredAngOffset = DesiredAngOffset + Angle(self.IronReloadAng.x,self.IronReloadAng.y,self.IronReloadAng.z) elseif self.IronRunAng and !self.CanShootWhileSprinting and self:IsSprinting() then DesiredAngOffset = DesiredAngOffset + Angle(self.IronRunAng.x,self.IronRunAng.y,self.IronRunAng.z) elseif self.IronBoltAng and self:GetBoltDelay() - self.ZoomDelay >= CurTime() then DesiredAngOffset = DesiredAngOffset + Angle(self.IronBoltAng.x,self.IronBoltAng.y,self.IronBoltAng.z) end ShootAng:RotateAroundAxis(ShootAng:Right(), DesiredAngOffset.x) ShootAng:RotateAroundAxis(ShootAng:Up(), DesiredAngOffset.y) ShootAng:RotateAroundAxis(ShootAng:Forward(), DesiredAngOffset.z) -- End Angle if self:GetZoomed() then self:SetTrueAimAng(ShootAng) return end local TrueAng = self:GetTrueAimAng() local AngDif = (ShootAng - TrueAng) AngDif:Normalize() local MoveMul = FrameTime()*4*(1/self.IronSightTime) local FinalMove = self:GetTrueAimAng(true) + self:CalculateAngleMovement(AngDif,MoveMul) self:SetTrueAimAng(FinalMove) end SWEP.ClientIronsightAng = nil function SWEP:GetViewModelPosition( pos, ang ) local OldPos = pos local OldAng = ang local DesiredPosOffset = Vector(0,0,0) local DesiredAngOffset = Angle(0,0,0) local ShouldSight = self:GetZoomed() or (self.EnableBlocking and self:GetIsBlocking() ) local EyeTrace = self.Owner:GetEyeTrace() local Adjust = 30 local DesiredDistanceMod = Adjust - math.min(Adjust,EyeTrace.HitPos:Distance(EyeTrace.StartPos)) local OwnerVelocity = self.Owner:GetVelocity():Length() local ZoomSpeed = 1 local TickRate = FrameTime() local TimeRate = self.IronSightTime local IsMelee = self:GetNextMelee() + self.MeleeDelay >= CurTime() local MeleeDif = math.Clamp( (self:GetNextMelee() - CurTime())/0.15 , 0 , 1) if self.IronSightAngSnap and self.IronSightPosSnap then TimeRate = 0.1 end if IsMelee then TimeRate = self.MeleeDelay end if ShouldSight then self.SwayScale = 0 self.BobScale = 0 else self.SwayScale = 1 self.BobScale = 1 end -- Start Position if self.IronSightsPos and ShouldSight then local BasePosOffset = self.IronSightsPos if BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_neversights",true):GetFloat() == 1 and self.HasScope == false then BasePosOffset = BasePosOffset - Vector(BasePosOffset.x/2,0,BasePosOffset.z/2) end if CLIENT then BasePosOffset = BasePosOffset * Vector(1,self.Owner.BURGERBASE_ZoomMul[self:GetClass()],1) end DesiredPosOffset = DesiredPosOffset + BasePosOffset if self.IronDualSpacing and self.HasDual then if self:GetIsLeftFire() then DesiredPosOffset = DesiredPosOffset - Vector(self.IronDualSpacing,0,0) else DesiredPosOffset = DesiredPosOffset + Vector(self.IronDualSpacing,0,0) end end elseif self.IronMeleePos and IsMelee then local Rad = math.rad(MeleeDif*180) DesiredPosOffset = DesiredPosOffset + Vector(math.sin(Rad)*self.IronMeleePos.x,math.cos(Rad)*self.IronMeleePos.y,self.IronMeleePos.z) elseif self.IronReloadPos and self:GetIsReloading() then DesiredPosOffset = DesiredPosOffset + self.IronReloadPos elseif self.IronRunPos and !self.CanShootWhileSprinting and self:IsSprinting() then DesiredPosOffset = DesiredPosOffset + self.IronRunPos elseif self.IronShootPos and self:GetCoolDown() > 0 then DesiredPosOffset = DesiredPosOffset + self.IronShootPos elseif self.IronBoltPos and self:GetBoltDelay() - self.ZoomDelay >= CurTime() then DesiredPosOffset = DesiredPosOffset + self.IronBoltPos elseif self.IronIdlePos then DesiredPosOffset = DesiredPosOffset + self.IronIdlePos end if not ShouldSight then DesiredPosOffset = DesiredPosOffset + Vector(math.sin(CurTime()*0.75),0,math.sin(CurTime()*0.75)) * 0.125 if self.Owner:Crouching() then DesiredPosOffset = DesiredPosOffset + Vector(0,0,2) end if not self.DistanceMod then self.DistanceMod = DesiredDistanceMod else self.DistanceMod = self.DistanceMod - (self.DistanceMod - DesiredDistanceMod)*TickRate end DesiredPosOffset = DesiredPosOffset - Vector(0,self.DistanceMod,0) end -- End Postion -- Start Angle if self.IronSightsAng and ShouldSight then DesiredAngOffset = DesiredAngOffset + Angle(self.IronSightsAng.x,self.IronSightsAng.y,self.IronSightsAng.z) elseif self.IronMeleeAng and IsMelee then DesiredAngOffset = DesiredAngOffset + Angle(self.IronMeleeAng.x,self.IronMeleeAng.y,self.IronMeleeAng.z) elseif self.IronReloadAng and self:GetIsReloading() then DesiredAngOffset = DesiredAngOffset + Angle(self.IronReloadAng.x,self.IronReloadAng.y,self.IronReloadAng.z) elseif self.IronRunAng and !self.CanShootWhileSprinting and self:IsSprinting() then DesiredAngOffset = DesiredAngOffset + Angle(self.IronRunAng.x,self.IronRunAng.y,self.IronRunAng.z) elseif self.IronShootAng and self:GetCoolDown() > 0 then DesiredAngOffset = DesiredAngOffset + Angle(self.IronShootAng.x,self.IronShootAng.y,self.IronShootAng.z) elseif self.IronBoltAng and self:GetBoltDelay() - self.ZoomDelay >= CurTime() then DesiredAngOffset = DesiredAngOffset + Angle(self.IronBoltAng.x,self.IronBoltAng.y,self.IronBoltAng.z) elseif self.IronIdleAng then DesiredAngOffset = DesiredAngOffset + Angle(self.IronIdleAng.x,self.IronIdleAng.y,self.IronIdleAng.z) end if not ShouldSight then DesiredAngOffset = DesiredAngOffset + Angle(-DesiredDistanceMod,0,0) DesiredPosOffset = Vector(DesiredPosOffset.x,DesiredPosOffset.y,DesiredPosOffset.z) DesiredAngOffset = Angle(DesiredAngOffset.p,DesiredAngOffset.y,DesiredAngOffset.r) end -- End Angle -- Start Final Calculation self.IronSightPosCurrent = self.IronSightPosCurrent - (self.IronSightPosCurrent-DesiredPosOffset)*TickRate*(1/math.Clamp(TimeRate,TickRate,3)) self.IronSightAngCurrent = self.IronSightAngCurrent - (self.IronSightAngCurrent-DesiredAngOffset)*TickRate*(1/math.Clamp(TimeRate,TickRate,3)) self.IronSightAngCurrent:Normalize() ang:RotateAroundAxis(ang:Right(), self.IronSightAngCurrent.x) ang:RotateAroundAxis(ang:Up(), self.IronSightAngCurrent.y) ang:RotateAroundAxis(ang:Forward(), self.IronSightAngCurrent.z) pos = pos + self.IronSightPosCurrent.x * ang:Right() pos = pos + self.IronSightPosCurrent.y * ang:Forward() pos = pos + self.IronSightPosCurrent.z * ang:Up() if ShouldSight then local PosDistance = DesiredPosOffset:Distance(self.IronSightPosCurrent) local AngDistance = Vector(DesiredAngOffset.x,DesiredAngOffset.y,DesiredAngOffset.z):Distance(Vector(self.IronSightAngCurrent.x,self.IronSightAngCurrent.y,self.IronSightAngCurrent.z)) if PosDistance < 0.25 then self.IronSightPosSnap = true end if AngDistance < 0.25 then self.IronSightAngSnap = true end else self.IronSightAngSnap = false self.IronSightPosSnap = false end -- End Final Calculation return pos, ang end function SWEP:Think() --Shared if CLIENT then -- not singleplayer if self.Owner.BURGERBASE_ZoomMul and self.Owner.BURGERBASE_ZoomMul[self:GetClass()] then if input.WasMousePressed( MOUSE_WHEEL_UP ) then self.Owner.BURGERBASE_ZoomMul[self:GetClass()] = math.Clamp(self.Owner.BURGERBASE_ZoomMul[self:GetClass()] + 0.1,0.1,1) elseif input.WasMousePressed( MOUSE_WHEEL_DOWN ) or input.WasMouseDoublePressed( MOUSE_WHEEL_DOWN ) then self.Owner.BURGERBASE_ZoomMul[self:GetClass()] = math.Clamp(self.Owner.BURGERBASE_ZoomMul[self:GetClass()] - 0.1,0.1,1) end end end --self:HandleAimAngles() self:HandleShotgunReloadCancel() self:HandleBulletQueue() self:HandleHoldType() self:HandleSprintCancelZoom() --self:HandleHoldToZoom() self:HandleCoolDown() -- don't predict self:HandleBuildUp() self:HandleHL2Pump() self:HandleShotgunReloadThinkAnimations() -- don't predict self:EquipThink() -- don't predict, ever self:HandleBurstFireShoot() -- don't predict, ever self:HandleReloadThink() -- don't predict, ever self:SpareThink() self:SwingThink() self:HolsterThink() self:IdleThink() self:HandleBulletsPerSecond() self:HandleZoomDelay() self:HandleBlocking() if (CLIENT or IsSingleplayer) then local FOVMOD = (45 + BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_viewmodel_fov",true):GetFloat() + self.AddFOV) * 0.75 if self.HasScope and self:GetZoomed() and not self.IgnoreScopeHide then if self.ZoomDelay <= 0 or self:GetZoomOverlayDelay() == -1 then FOVMOD = 120 end end self.ViewModelFOV = FOVMOD self:HandleZoomMod() if IsFirstTimePredicted() then self:RemoveRecoil() end end if CLIENT then -- Don't Singleplayer self:SetNextClientThink( CurTime() + FrameTime() ) end self:NextThink( CurTime() + FrameTime() ) return true end function SWEP:HandleBlocking() -- Shared if self.EnableBlocking then if self.Owner:KeyDown(IN_ATTACK2) then self:SetNextPrimaryFire(CurTime() + self.IronSightTime) end if SERVER then if self.Owner:KeyDown(IN_ATTACK2) and self:GetNextSecondaryFire() <= CurTime() then self:SetIsBlocking( true ) self:SetHoldType("melee2") else self:SetHoldType(self.HoldType) self:SetIsBlocking( false ) end end end end function SWEP:HandleAmmoSwitch() -- Shared end function SWEP:HandleZoomDelay() -- Shared if CLIENT or IsSingleplayer then if self:GetZoomOverlayDelay() > 0 and self:GetZoomOverlayDelay() <= CurTime() then self:SetZoomOverlayDelay(-1) end end end function SWEP:HandleBulletsPerSecond() -- Shared --if self:GetCoolTime() <= CurTime() then self:SetBulletsPerSecond( math.Clamp(self:GetBulletsPerSecond() - FrameTime(),0,100) ) --end end function SWEP:IdleAnimation() -- Shared self:SendWeaponAnimation(ACT_VM_IDLE) end function SWEP:IdleThink() -- Shared if self.HasIdle and self:GetNextIdle() <= CurTime() and not self:IsBusy() then self:IdleAnimation() end end function SWEP:SpareThink() -- Shared end function SWEP:HandleBuildUp() -- Shared if self.HasBuildUp or self.UsesBuildUp then if self:GetCoolTime() <= CurTime() then self:SetBuildUp( math.Clamp(self:GetBuildUp() - 0.015*self.BuildUpCoolAmount,0,100) ) end end end function SWEP:EmitDryFireSound() -- Shared if SERVER then self.Owner:EmitSound(self.DryFireSound) end self:SetNextPrimaryFire( math.max(self:GetNextPrimaryFire(),CurTime() + 0.25) ) end function SWEP:HasPrimaryAmmoToFire() -- Shared if self:Clip1() == -1 then if self.Primary.SpareClip ~= -1 and self.Owner:GetAmmoCount(self:GetPrimaryAmmo()) < 1 then self:EmitDryFireSound() return false else return true end elseif self:Clip1() <= 0 then self:EmitDryFireSound() return false end return true end function SWEP:HasSecondaryAmmoToFire() -- Shared if self:Clip2() == -1 then if self.Secondary.SpareClip ~= -1 and self.Owner:GetAmmoCount(self:GetSecondaryAmmo()) < 1 then self:EmitDryFireSound() return false else return true end elseif self:Clip2() <= 0 then self:EmitDryFireSound() return false end return true end function SWEP:HandleBurstFireShoot() -- Shared if self.HasBurstFire or self.AlwaysBurst or self.BulletDelay > 0 then if self:GetNextFireDelay() <= CurTime() and self:GetFireQueue() > 0 then self:SetNextFireDelay(CurTime() + self:GetBurstMath()) self:SetFireQueue(self:GetFireQueue() - 1) --if not self:CanPrimaryAttack() then return end if not self:CanShoot() then return end self:ShootGun() end end end function SWEP:HandleReloadThink() -- Shared if self:GetIsNormalReload() then --self:SetIsReloading(true) if self:GetReloadFinish() <= CurTime() and self:GetIsReloading() then if self.Owner:GetAmmoCount( self:GetPrimaryAmmo() ) >= self.Primary.ClipSize then self:SetClip1(self.Primary.ClipSize) self.Owner:RemoveAmmo(self.Primary.ClipSize,self:GetPrimaryAmmo()) self.HasMagIn = true else self:SetClip1(self.Owner:GetAmmoCount(self:GetPrimaryAmmo())) self.Owner:RemoveAmmo(self.Owner:GetAmmoCount(self:GetPrimaryAmmo()),self:GetPrimaryAmmo()) self.HasMagIn = true end self:SetIsNormalReload(false) self:SetIsReloading(false) end elseif self:GetIsShotgunReload() then self:SetIsReloading(true) if self:GetNextShell() <= CurTime() then if self.Owner:GetAmmoCount( self:GetPrimaryAmmo() ) > 0 and self:Clip1() < self.Primary.ClipSize then self:SendWeaponAnimation(ACT_VM_RELOAD) self:SetClip1( self:Clip1() + 1 ) self.Owner:RemoveAmmo(1,self:GetPrimaryAmmo()) self:SetNextShell( CurTime() + self:GetTrueSequenceDuration() ) if (CLIENT or IsSingleplayer) then if self.ReloadSound then self:EmitGunSound(self.ReloadSound) end end else self:FinishShotgunReload() end end end end function SWEP:FinishShotgunReload() -- Shared self:SendWeaponAnimation( ACT_SHOTGUN_RELOAD_FINISH ) self:SetNextPrimaryFire(CurTime() + self:GetTrueSequenceDuration()) self:SetIsShotgunReload(false) self:SetIsReloading(false) end function SWEP:CancelReload() -- Shared self:SetNextPrimaryFire(CurTime() + 0.1) self:SetIsReloading(false) end function SWEP:DoHL2Pump() -- Shared self:SendWeaponAnimation( self.PumpAnimation ) self:SetNextPrimaryFire(CurTime() + self:GetTrueSequenceDuration()) if (CLIENT or IsSingleplayer) and IsFirstTimePredicted() then if self.PumpSound then self.Owner:EmitSound(self.PumpSound) end end end function SWEP:HandleHL2Pump() -- Shared if self.HasPumpAction and self.HasHL2Pump and self:GetNeedsHL2Pump() and self:GetNextHL2Pump() ~= 0 and self:GetNextHL2Pump() <= CurTime() and not (self:GetZoomed() and self.HasScope) then if not (self:Clip1() == 0 or ( self:Ammo1() == 0 and self:Clip1() == -1) ) then self:DoHL2Pump() self:SetNeedsHL2Pump(false) else self:SetNextPrimaryFire(CurTime() + 0.1) self:SetNeedsHL2Pump(true) end self:SetNextHL2Pump(0) end end --[[ function SWEP:CustomAmmoDisplay() self.AmmoDisplay = self.AmmoDisplay or {} self.AmmoDisplay.Draw = true //draw the display? if self.Primary.ClipSize > 0 then self.AmmoDisplay.PrimaryClip = self:Clip1() //amount in clip self.AmmoDisplay.PrimaryAmmo = self:Ammo1() //amount in reserve end if self.Secondary.ClipSize > 0 then self.AmmoDisplay.SecondaryClip = self:Clip2() self.AmmoDisplay.SecondaryAmmo = self:Ammo2() end return self.AmmoDisplay //return the table end --]] function SWEP:HandleShotgunReloadThinkAnimations() -- Shared if self:GetNextPrimaryFire() <= CurTime() then if self:GetIsShotgunReload() then if self:GetNextShell() <= CurTime() then if self.Owner:GetAmmoCount( self:GetPrimaryAmmo() ) > 0 and self:Clip1() < self.Primary.ClipSize then self:SendWeaponAnimation(ACT_VM_RELOAD) self:SetNextPrimaryFire( CurTime() + self:GetTrueSequenceDuration() ) if (CLIENT or IsSingleplayer) then if self.ReloadSound then self:EmitGunSound(self.ReloadSound) end end end end elseif self:GetNeedsHL2Pump() and self:GetNextHL2Pump() == 0 and self:Clip1() > 0 then --print("HI") self:DoHL2Pump() self:SetNeedsHL2Pump(false) end end end function SWEP:HandleCoolDown() -- Shared local CoolMul = FrameTime()*self.CoolSpeedMul*4 if self:GetCoolTime() <= CurTime() then if self:GetCoolDown() ~= 0 then self:SetCoolDown(math.Clamp(self:GetCoolDown() - CoolMul,0,self.MaxHeat)) end end if self.HasDual and self:GetCoolTimeLeft() <= CurTime() then if self:GetCoolDownLeft() ~= 0 then self:SetCoolDownLeft(math.Clamp(self:GetCoolDownLeft() - CoolMul,0,self.MaxHeat)) end end if CLIENT and self.Owner == LocalPlayer() then if self.ClientCoolDown ~= 0 and self.ClientCoolTime <= CurTime() then self.ClientCoolDown = math.Clamp(self.ClientCoolDown - CoolMul,0,self.MaxHeat) end if self.ClientCoolDownLeft ~= 0 and self.ClientCoolTimeLeft <= CurTime() then self.ClientCoolDownLeft = math.Clamp(self.ClientCoolDownLeft - CoolMul,0,self.MaxHeat) end end end function SWEP:HandleZoomMod() -- Shared if self:GetZoomed() and self:GetZoomOverlayDelay() <= CurTime() then if self.ZoomDelay <= 0 or self:GetZoomOverlayDelay() == -1 then if self.HasIronSights then self:SetZoomMod( math.min(self:GetZoomMod() + FrameTime()*(1/self.ZoomTime),1) ) else self:SetZoomMod( 1 ) end end else if self.HasIronSights then self:SetZoomMod(math.max(self:GetZoomMod() - FrameTime()*(1/self.ZoomTime),0)) else self:SetZoomMod(0) end end end function SWEP:RemoveRecoil() -- Client local pUp = self:HandleLimits(self.PunchAngleUp.p) local yUp = self:HandleLimits(self.PunchAngleUp.y) local rUp = self:HandleLimits(self.PunchAngleUp.r) local pDown = self:HandleLimits(self.PunchAngleDown.p) local yDown = self:HandleLimits(self.PunchAngleDown.y) local rDown = self:HandleLimits(self.PunchAngleDown.r) local FrameMul = 0.015*15*self.RecoilSpeedMul local UpMul = 1 * FrameMul local DownMul = 0.75 * FrameMul local ModAngle = Angle(0,0,0) if self.PunchAngleUp ~= Angle(0,0,0) then local CurrentMod = Angle( (pUp*UpMul),(yUp*UpMul),(rUp*UpMul)) ModAngle = ModAngle + CurrentMod self.PunchAngleUp = self.PunchAngleUp - CurrentMod end if self.PunchAngleDown ~= Angle(0,0,0) then local CurrentMod = Angle( (pDown*DownMul),(yDown*DownMul),(rDown*DownMul)) ModAngle = ModAngle - CurrentMod self.PunchAngleDown = self.PunchAngleDown - CurrentMod end if ModAngle ~= Angle(0,0,0) then self.Owner:SetEyeAngles(self.Owner:EyeAngles() + ModAngle) end end function SWEP:HandleLimits(value) -- Unknown local Limit = 0.001 if value < Limit and value > -Limit then value = 0 end return value end function SWEP:SpecialFalloff(falloff) -- Shared return falloff end if CLIENT then -- Cleint BurgerBase_ContextMenuIsOpen = false function BurgerBase_ContextMenuOpen() BurgerBase_ContextMenuIsOpen = true end hook.Add("OnContextMenuOpen","BurgerBase_ContextMenuOpen",BurgerBase_ContextMenuOpen) function BurgerBase_ContextMenuClose() BurgerBase_ContextMenuIsOpen = false end hook.Add("OnContextMenuClose","BurgerBase_ContextMenuClose",BurgerBase_ContextMenuClose) end function SWEP:GetFakeDelay() -- Shared return -1 end function BURGERBASE_CalculateWeaponStats(owner,weapon,avoidfunctions) -- Shared local ReturnTable = {} if not (weapon and weapon ~= NULL and weapon.Base == "weapon_burger_core_base") then return ReturnTable end local EyeTrace = owner:GetEyeTrace() local EyePos = EyeTrace.StartPos local HitPos = EyeTrace.HitPos local MatType = EyeTrace.MatType -- Start Data local Damage = BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damagescale"):GetFloat() local Shots = 1 local Delay = 1 local ClipSize = weapon.Primary.ClipSize local Name = weapon.PrintName .. " | " .. weapon.Category local AmmoType = "none" if avoidfunctions then Damage = Damage * weapon.Primary.Damage Shots = weapon.Primary.NumShots Delay = weapon.Primary.Delay if CLIENT then AmmoType = language.GetPhrase(weapon.Primary.Ammo .. "_ammo") end else Damage = Damage * weapon:SpecialDamage(weapon.Primary.Damage) Shots = weapon:SpecialShots(weapon.Primary.NumShots) if weapon:GetPrimaryAmmo() and weapon:GetPrimaryAmmo() ~= -1 then if CLIENT then AmmoType = language.GetPhrase(game.GetAmmoName(weapon:GetPrimaryAmmo()) .. "_ammo") end end if weapon:GetFakeDelay() ~= -1 then Delay = weapon:GetFakeDelay() else Delay = weapon:GetDelay() end end Damage = math.Round(Damage, 2 ) local FullDamage = Damage * Shots local BulletsFired = 1 local SecondsPassed = 0 local TestKillTime = -1 local ClipSizeMath = math.Clamp(ClipSize-1,0,20) if ClipSizeMath < 1 then ClipSizeMath = 20 end for i=1, ClipSizeMath do if TestKillTime == -1 then if BulletsFired*FullDamage >= 100 then TestKillTime = SecondsPassed end end if !avoidfunctions and weapon:GetIsBurst() then SecondsPassed = SecondsPassed + weapon:GetBurstMath() if i % weapon.BurstOverride == 0 then SecondsPassed = SecondsPassed + Delay end else SecondsPassed = SecondsPassed + Delay end BulletsFired = BulletsFired + 1 end if TestKillTime == -1 then TestKillTime = 0 end local AverageDelay = SecondsPassed/(BulletsFired-1) local RPM = (1/AverageDelay)*60 local DPS = ((BulletsFired-1)*FullDamage)/(SecondsPassed) local KillTime = TestKillTime if !(ClipSize == -1) then DPS = math.Clamp(DPS,0,ClipSize*FullDamage) end -- Accuracy local Cone = weapon.Primary.Cone if not avoidfunctions then Cone = weapon:HandleCone(Cone,false,(weapon.HasDual and weapon:GetIsLeftFire())) end if not Cone then Cone = 0 end local BaseAccuracy = 0.1 local Accuracy = (BaseAccuracy - math.Clamp(Cone,0,BaseAccuracy)) / BaseAccuracy Accuracy = math.Round(Accuracy, 2 ) -- Range local FullRange = weapon.DamageFalloff if not avoidfunctions then FullRange = weapon:SpecialFalloff(weapon.DamageFalloff) end -- Bullet Penetration local MatCalc = 1 if not avoidfunctions then MatCalc = weapon:CalculateMaterialPenetration(MatType) end local PenetrationLossPerUnit = BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_penetration_scale"):GetFloat() * MatCalc * math.max(0.1,weapon.PenetrationLossMul or 1) * 1 local BulletPenetration = Damage / math.max(3,PenetrationLossPerUnit) ReturnTable.name = Name or "" ReturnTable.ammo = AmmoType or "none" ReturnTable.clip = ClipSize or -1 ReturnTable.damage = Damage or 0 ReturnTable.shots = Shots or 1 ReturnTable.delay = Delay or 1 ReturnTable.rpm = RPM or 0 ReturnTable.dps = DPS or 0 ReturnTable.killtime = KillTime or 1 ReturnTable.accuracy = Accuracy or 1 ReturnTable.range = FullRange or 100 ReturnTable.penetration = BulletPenetration or 1 return ReturnTable end function SWEP:EquipThink() -- Shared if self.WeaponType ~= "Throwable" then return end if self:GetIsThrowing() then local ShouldExplode = self:GetGrenadeExplosion() ~= 0 and self:GetGrenadeExplosion() <= CurTime() if self.CanCook and ShouldExplode then self:ThrowObject(self.Object,0) if self:Ammo1() > 0 then self:TakePrimaryAmmo(1) end self:SetGrenadeExplosion(0) self:RemoveGrenade() return end if !self.Owner:KeyDown(IN_ATTACK) and self:GetThrowDelay() ~= 0 and self:GetThrowDelay() <= CurTime() then self:SendWeaponAnimation(ACT_VM_THROW) self.Owner:SetAnimation(PLAYER_ATTACK1) self:SetThrowTime(CurTime() + self:GetTrueSequenceDuration()*0.33) self:SetThrowRemoveTime(CurTime() + self:GetTrueSequenceDuration()) self:SetThrowDelay(0) end if not ShouldExplode and self:GetThrowTime() ~= 0 and self:GetThrowTime() <= CurTime() then self:ThrowObject(self.Object,1000) if self:Ammo1() > 0 then self:TakePrimaryAmmo(1) end self:SetThrowTime(0) self:SetGrenadeExplosion(0) end if self:GetThrowRemoveTime() ~= 0 and self:GetThrowRemoveTime() <= CurTime() then self:RemoveGrenade() end end end function SWEP:RemoveGrenade() -- Shared self:SetCanHolster( true ) self:SetIsThrowing( false ) if self:Ammo1() > 0 then self:SendWeaponAnimation(ACT_VM_DRAW) else self:SwitchToPrimary() if SERVER then self:Remove(self.Weapon) end end self:SetThrowRemoveTime(0) end function SWEP:SwitchToPrimary() -- Shared if self.Owner and self.Owner ~= NULL then if self.Owner:IsBot() then if SERVER then local Weapons = self.Owner:GetWeapons() local WeaponFound = false for k,v in pairs(Weapons) do if not WeaponFound and self.Owner:HasWeapon(v:GetClass()) and v.Category == "Counter-Strike" then self.Owner:SetActiveWeapon(v) self.Owner:DrawWorldModel( true ) WeaponFound = true end end end elseif SERVER or (CLIENT and self.Owner == LocalPlayer()) then self.Owner:ConCommand("lastinv") end end end function SWEP:QuickThrow() -- Shared self:PreThrowObject(true) end function SWEP:PreThrowObject(override) -- Shared if self:IsUsing() and not override then return end self:SetNextPrimaryFire(CurTime() + self.Primary.Delay) local ThrowDelay = 0.15 if self.HasPreThrow then self:SendWeaponAnimation( ACT_VM_PULLPIN ) ThrowDelay = self:GetTrueSequenceDuration() end self:SetThrowDelay(CurTime() + ThrowDelay) self:SetGrenadeExplosion(CurTime() + self.FuseTime) self:SetCanHolster( false ) self:SetIsThrowing( true ) end function SWEP:ThrowObject(object,force) -- Shared if (CLIENT) then return end local EA = self.Owner:EyeAngles() local pos = self.Owner:GetShootPos() + EA:Right() * 5 - EA:Up() * 4 + EA:Forward() * 8 local ent = ents.Create(object) ent:SetPos(pos) ent:SetAngles(EA) ent:Spawn() ent:Activate() ent:SetOwner(self.Owner) ent.ExplodeTime = self:GetGrenadeExplosion() if ent:GetPhysicsObject():IsValid() then if object == "ent_hl2_gasparticle" then ent:GetPhysicsObject():SetVelocity( EA:Forward()*force + EA:Right()*math.random(-20,20) + EA:Up()*math.random(-20,20) + Vector(0,0,-10) ) else ent:GetPhysicsObject():SetVelocity(self.Owner:GetVelocity() + EA:Forward() * force + EA:Up()*50) end else ent:SetVelocity(self.Owner:GetVelocity() + EA:Forward() * force) end end function SWEP:QuickKnife() -- Shared end SWEP.MeleeCanParry = true function SWEP:StartSwing(damage,delay,entoverride,delayoverride) -- Shared if self.MeleeCanParry and self.MeleeDelay > 0 then self:SetClashTime(CurTime() + self.MeleeDelay*2) end if self.MeleeDelay > 0 then self:SetShouldMelee(true) self:SetNextMeleeDamage(damage) if delayoverride then self:SetNextMelee(CurTime() + delayoverride) else self:SetNextMelee(CurTime() + self.MeleeDelay) end self:SetNextMeleeEnt(entoverride) self:EmitGunSound(self.MeleeSoundMiss) else local Returner = self:MidSwing(damage,entoverride) if not (Returner and Returner ~= NULL) then self:EmitGunSound(self.MeleeSoundMiss) end self:FinishSwing(Returner,damage) return Returner end end function SWEP:AddDurability(amount) -- Shared self:SetClip1( math.Clamp(self:Clip1() + amount,0,100) ) if self:Clip1() <= 0 then self.Owner:EmitSound("physics/metal/sawblade_stick1.wav") if self and SERVER then self.Owner:StripWeapon(self:GetClass()) end end end function SWEP:SwingThink() -- Shared if self:GetShouldMelee() and self:GetNextMelee() <= CurTime() then local HitEntity = self:GetNextMeleeEnt() local Damage = self:GetNextMeleeDamage() HitEntity = self:MidSwing(Damage,HitEntity) self:SetShouldMelee(false) self:SetNextMeleeDamage(0) self:SetNextMeleeEnt(nil) self:FinishSwing(HitEntity,Damage) end end function SWEP:MeleeRange() -- Shared return 40 end function SWEP:MeleeSize() -- Shared return 40 end function SWEP:MidSwing(damage,entoverride) -- Shared if entoverride and entoverride ~= NULL then self:SendMeleeDamage(entoverride,damage,nil) return entoverride else local StartPos = self.Owner:GetShootPos() local EndPos = self.Owner:GetShootPos() + self.Owner:GetAimVector()*self:MeleeRange() local LineFilterFunction = self.Owner local HullFilterFunction = function(ent) return !(ent == self.Owner) and (ent:IsPlayer() or ent:IsNPC()) end local Bounds = Vector(self:MeleeSize(),self:MeleeSize(),self:MeleeSize()) local TraceResult = self:DoDoubleTrace(StartPos,EndPos,MASK_SHOT,Bounds,LineFilterFunction,HullFilterFunction) local Victim = TraceResult.Entity --if Victim and Victim ~= NULL then self:SendMeleeDamage(TraceResult.Entity,damage,TraceResult) --end return Victim end end function SWEP:FinishSwing(HitEntity,Damage) -- Shared end function SWEP:DoDoubleTrace(startpos,endpos,mask,bounds,linefilterfunction,hullfilterfunction) -- Shared local LineTraceData = {} LineTraceData.start = startpos LineTraceData.endpos = endpos LineTraceData.filter = linefilterfunction LineTraceData.mask = MASK_SHOT if self.Owner:IsPlayer() then self.Owner:LagCompensation( true ) end local LineTraceResult = util.TraceLine(LineTraceData) if self.Owner:IsPlayer() then self.Owner:LagCompensation( false ) end if LineTraceResult.Entity and LineTraceResult.Entity ~= NULL and LineTraceResult.Entity:Health() > 0 then return LineTraceResult else local HullTraceData = {} HullTraceData.start = startpos HullTraceData.endpos = endpos HullTraceData.filter = hullfilterfunction HullTraceData.mask = MASK_SHOT_HULL HullTraceData.mins = -bounds HullTraceData.maxs = bounds HullTraceData.ignoreworld = true if self.Owner:IsPlayer() then self.Owner:LagCompensation( true ) end local HullTraceResult = util.TraceHull(HullTraceData) if self.Owner:IsPlayer() then self.Owner:LagCompensation( false ) end if HullTraceResult.Entity and HullTraceResult.Entity ~= NULL and HullTraceResult.Entity:Health() > 0 then return HullTraceResult else return LineTraceResult end end end SWEP.MeleeBackStabMul = 2 SWEP.MeleeBlockRange = 90 + 45 SWEP.MeleeBlockReduction = 0.1 function SWEP:SendMeleeDamage(victim,damage,TraceResult) -- Shared if (victim and victim ~= NULL) and (victim:IsPlayer() or victim:IsNPC()) then local VictimAngles = victim:EyeAngles() local AttackerAngles = self.Owner:EyeAngles() VictimAngles:Normalize() AttackerAngles:Normalize() local NewAngles = VictimAngles - AttackerAngles NewAngles:Normalize() local Yaw = math.abs(NewAngles.y) if Yaw < 45 then damage = damage * self.MeleeBackStabMul end VictimWeapon = victim:GetActiveWeapon() if (VictimWeapon and VictimWeapon ~= NULL) and ((VictimWeapon.EnableBlocking and ((VictimWeapon:GetIsBlocking() and VictimWeapon:GetNextSecondaryFire() <= CurTime()) or ( VictimWeapon:GetClashTime() >= CurTime() and math.abs(VictimWeapon:GetClashTime() - self:GetClashTime()) > self.MeleeDelay ))) and (Yaw > 180 - self.MeleeBlockRange/2 and Yaw < 180 + self.MeleeBlockRange/2)) then damage = damage * self.MeleeBlockReduction self:DoMeleeDamage(damage, victim, TraceResult) VictimWeapon:BlockDamage(damage,self.Owner,self) self:SetShouldMelee(false) VictimWeapon:SetShouldMelee(false) else self:DoMeleeDamage(damage, victim, TraceResult) end else self:DoMeleeDamage(damage, victim, TraceResult) end end function SWEP:BlockDamage(damage,attacker,attackerweapon) -- Shared attacker:ViewPunch(Angle(math.Rand(-1,1),math.Rand(-1,1),math.Rand(-1,1))) self.Owner:ViewPunch(Angle(math.Rand(-1,1),math.Rand(-1,1),math.Rand(-1,1))) self.Owner:DoAnimationEvent( ACT_GMOD_GESTURE_MELEE_SHOVE_1HAND ) self:SetNextPrimaryFire(CurTime() + attackerweapon.Primary.Delay) self:SetNextSecondaryFire(CurTime() + attackerweapon.Primary.Delay) self:EmitSound(self.MeleeSoundWallHit) attackerweapon:SetNextPrimaryFire(CurTime() + 1.5) attackerweapon:SetNextSecondaryFire(CurTime() + 1.5) attackerweapon:EmitSound(self.MeleeSoundWallHit) end function SWEP:DoMeleeDamage(damage, victim, traceresult) -- Shared if victim and victim ~= NULL then if (victim:IsPlayer() or victim:IsNPC()) then if damage <= self:SpecialDamage(self.Primary.Damage) then self:EmitGunSound(self.MeleeSoundFleshSmall) else self:EmitGunSound(self.MeleeSoundFleshLarge) self:MeleeFleshEffect(victim) end else self:EmitGunSound(self.MeleeSoundWallHit) end local dmginfo = DamageInfo() dmginfo:SetDamage( damage ) dmginfo:SetDamageType( self.MeleeDamageType ) dmginfo:SetAttacker( self.Owner ) dmginfo:SetInflictor( self ) dmginfo:SetDamageForce( self.Owner:GetForward() ) if traceresult then victim:DispatchTraceAttack( dmginfo, traceresult ) elseif SERVER then victim:TakeDamageInfo(dmginfo) end if traceresult and IsFirstTimePredicted() then self:BulletEffect(traceresult.HitPos,traceresult.StartPos,victim,traceresult.SurfaceProps,self.MeleeDamageType) end end end function SWEP:MeleeFleshEffect(victim,traceresult) -- Shared local StartPos = self.Owner:EyePos() local HitPos = victim:GetPos() + victim:OBBCenter() local NormalShit = (StartPos - HitPos):GetNormalized() local effect = EffectData() effect:SetOrigin(HitPos) effect:SetStart(StartPos) effect:SetNormal(NormalShit) effect:SetFlags(3) effect:SetScale(6) effect:SetColor(0) effect:SetDamageType(self.MeleeDamageType) if CLIENT or IsSingleplayer then effect:SetEntity(victim) else effect:SetEntIndex(victim:EntIndex()) end util.Effect("bloodspray", effect) util.Effect("BloodImpact", effect) util.Decal( "Blood", StartPos, StartPos + NormalShit*100) util.Decal( "Blood", victim:GetPos(), victim:GetPos()) end function SWEP:GetActivities() -- Shared if CLIENT then local ent = self local k, v, t t = { } for k, v in ipairs( ent:GetSequenceList( ) ) do table.insert( t, { id = k, act = ent:GetSequenceActivity( k ), actname = ent:GetSequenceActivityName( k ) } ) end PrintTable(t) print("--------------------") PrintTable(self:GetSequenceList()) end end function SWEP:OnRemove() -- Shared if CLIENT then self:SCK_OnRemove() end end -------------------------------- --SWEP CONTSTRUCTION KIT STUFF-- -------------------------------- local datatable = {} local BulletMaterial = Material( "effects/spark" ) local SpriteMaterial = Material( "sprites/light_glow02_add" ) datatable.drawfunction = function(datatable) local Forward = datatable.direction:GetNormalized() local BulletLength = datatable.direction:Length()*0.01 local BulletWidth = datatable.damage*(16/100) render.SetMaterial( BulletMaterial ) render.DrawBeam( datatable.pos , datatable.pos + Forward*BulletLength, BulletWidth ,0, 1, Color(255,255,255,255) ) render.SetMaterial( SpriteMaterial ) render.DrawSprite( datatable.pos + Forward*BulletLength, BulletWidth*0.5, BulletWidth*0.5, Color(255,255,255,255) ) end datatable.diefunction = function(datatable) end datatable.hitfunction = function(datatable,traceresult) local Victim = traceresult.Entity local Attacker = datatable.owner local Inflictor = datatable.weapon if not IsValid(Attacker) then Attacker = Victim end if not IsValid(Inflictor) then Inflictor = Attacker end if IsValid(Attacker) and IsValid(Victim) and IsValid(Inflictor) and (not datatable.previoushit or datatable.previoushit ~= Victim) then local DmgInfo = DamageInfo() DmgInfo:SetDamage( datatable.damage ) DmgInfo:SetAttacker( Attacker ) DmgInfo:SetInflictor( Inflictor ) DmgInfo:SetDamageForce( datatable.direction:GetNormalized() ) DmgInfo:SetDamagePosition( datatable.pos ) DmgInfo:SetDamageType( DMG_BULLET ) datatable.previoushit = Victim traceresult.Entity:DispatchTraceAttack( DmgInfo, traceresult ) end if not traceresult.StartSolid then if SERVER and IsFirstTimePredicted() and !Victim:IsPlayer() then local effect = EffectData() effect:SetOrigin(traceresult.HitPos) effect:SetStart(traceresult.StartPos) effect:SetSurfaceProp(traceresult.SurfaceProps) effect:SetDamageType(DMG_BULLET) if (CLIENT or IsSingleplayer) then effect:SetEntity(Victim) else effect:SetEntIndex(Victim:EntIndex()) end util.Effect("Impact", effect) end end if datatable.damage >= 1 then return true else datatable.damage = datatable.damage - (traceresult.Fraction*datatable.direction:Length()) end end BURGERBASE_RegisterProjectile("css_bullet",datatable) local datatable = {} local NadeModel = Model("models/weapons/ar2_grenade.mdl") datatable.drawfunction = function(datatable) if datatable.special and datatable.special ~= NULL then datatable.special:SetPos(datatable.pos) datatable.special:SetAngles( datatable.direction:GetNormalized():Angle() ) datatable.special:DrawModel() else datatable.special = ClientsideModel(NadeModel, RENDERGROUP_OPAQUE ) end end datatable.hitfunction = function(datatable,traceresult) local Victim = traceresult.Entity local Attacker = datatable.owner local Inflictor = datatable.weapon if not IsValid(Attacker) then Attacker = Victim end if not IsValid(Inflictor) then Inflictor = Attacker end if IsValid(Attacker) and IsValid(Inflictor) then local DmgInfo = DamageInfo() DmgInfo:SetDamage( datatable.damage ) DmgInfo:SetAttacker( Attacker ) DmgInfo:SetInflictor( Inflictor ) DmgInfo:SetDamageForce( datatable.direction:GetNormalized() ) DmgInfo:SetDamagePosition( traceresult.HitPos ) DmgInfo:SetDamageType( DMG_SHOCK ) util.BlastDamageInfo( DmgInfo, traceresult.HitPos, 512 ) if IsFirstTimePredicted() then local effectdata = EffectData() effectdata:SetStart( traceresult.HitPos + datatable.direction:GetNormalized()*100) effectdata:SetOrigin( traceresult.HitPos) effectdata:SetScale( 1 ) effectdata:SetRadius( 1 ) util.Effect( "Explosion", effectdata) end end end datatable.diefunction = function(datatable) if CLIENT then if datatable.special and datatable.special ~= NULL then datatable.special:Remove() end end end BURGERBASE_RegisterProjectile("launched_grenade",datatable)<file_sep>/lua/burgerbase/core/shared/core_convars.lua BURGERBASE.StoredServerConVars = {} BURGERBASE.StoredClientConVars = {} function BURGERBASE:CONVARS_CreateStoredConvar(name,default,flags,description,clientside) if not flags then flags = FCVAR_REPLICATED + FCVAR_ARCHIVE + FCVAR_NOTIFY + FCVAR_SERVER_CAN_EXECUTE end if not default then default = 0 end if not description then description = "No description" end if not clientside then clientside = false end if clientside then BURGERBASE.StoredClientConVars[name] = CreateConVar(name,tostring(default), flags , description ) if CLIENT then print("Creating Client ConVar: " .. name) end else BURGERBASE.StoredServerConVars[name] = CreateConVar(name,tostring(default), flags , description ) if SERVER then print("Creating Server ConVar: " .. name) end end end function BURGERBASE:CONVARS_GetStoredConvar(name,clientside) if clientside then return BURGERBASE.StoredClientConVars[name] else return BURGERBASE.StoredServerConVars[name] end end BURGERBASE:INIT_MassInclude("burgerbase/core/shared/convars/","shared",false) <file_sep>/lua/weapons/weapon_burger_cs_fiveseven.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_fiveseven", "csd", "u", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/fiveseven") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "Five-seven" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Secondary" SWEP.Cost = 750 SWEP.CSSMoveSpeed = 250 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Description = "High capacity accurate pea-shooter. Good for finishing wounded off." SWEP.Slot = 1 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/cstrike/c_pist_fiveseven.mdl" SWEP.WorldModel = "models/weapons/w_pist_fiveseven.mdl" SWEP.VModelFlip = false SWEP.HoldType = "revolver" SWEP.Primary.Damage = 25 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_FiveSeven.Single") SWEP.Primary.Cone = 0.003 SWEP.Primary.ClipSize = 20 SWEP.Primary.SpareClip = 100 SWEP.Primary.Delay = 0.15 --1/(400/60) SWEP.Primary.Ammo = "bb_57mm" SWEP.Primary.Automatic = false SWEP.RecoilMul = 0.75 SWEP.SideRecoilMul = 0.5 SWEP.RecoilSpeedMul = 1.25 SWEP.MoveConeMul = 0.5 SWEP.HeatMul = 1 SWEP.CoolMul = 0.5 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 0.75 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = false SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = true SWEP.DamageFalloff = 2000 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.25 SWEP.ZoomTime = 0.25 SWEP.IronSightsPos = Vector(-5.75, 10, 2.079) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(0, 0, 0) SWEP.IronRunAng = Vector(0, 0, 0) SWEP.IronMeleePos = Vector(-6.433, -13.468, -20) SWEP.IronMeleeAng = Vector(70, 0, 0)<file_sep>/lua/weapons/weapon_hl2_357.lua if CLIENT then killicon.AddFont( "weapon_hl2_357", "HL2MPTypeDeath", ".", Color( 255, 80, 0, 255 ) ) -- killicon.AddFont( "ent_cs_crossbow_bolt", "HL2MPTypeDeath", "1", Color( 255, 80, 0, 255 ) ) -- killicon.AddFont( "ent_cs_combine_ball", "HL2MPTypeDeath", "8", Color( 255, 80, 0, 255 ) ) -- killicon.AddFont( "ent_cs_smg1_grenade", "HL2MPTypeDeath", "7", Color( 255, 80, 0, 255 ) ) end SWEP.Category = "BurgerBase: Half Life 2" SWEP.PrintName = ".357" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Secondary" SWEP.Cost = 0 SWEP.CSSMoveSpeed = 230 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 1 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/c_357.mdl" SWEP.WorldModel = "models/weapons/w_357.mdl" SWEP.VModelFlip = false SWEP.HoldType = "revolver" SWEP.Primary.Damage = 95 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("weapons/357/357_fire2.wav") SWEP.Primary.Cone = 0.002 SWEP.Primary.ClipSize = 6 SWEP.Primary.SpareClip = 36 SWEP.Primary.Delay = 1/(120/60) SWEP.Primary.Ammo = "357" SWEP.Primary.Automatic = false SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 0.25 SWEP.RecoilSpeedMul = 0.75 SWEP.MoveConeMul = 1 SWEP.HeatMul = 1 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 1 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = false SWEP.HasDryFire = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = true SWEP.BurstOverride = 6 SWEP.BurstConeMul = 10 SWEP.DamageFalloff = 3000 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.25 SWEP.IronSightsPos = Vector(-4.64, 20, 0) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(0, -12.664, -21.48) SWEP.IronRunAng = Vector(70, 0, 0) SWEP.IronMeleePos = Vector(-6.433, -13.468, -20) SWEP.IronMeleeAng = Vector(70, 0, 0) SWEP.UseSpecialProjectile = false SWEP.UseMuzzle = false function SWEP:ModProjectileTable(datatable) datatable.direction = datatable.direction*6000 datatable.hullsize = 1 datatable.usehull = true datatable.resistance = (datatable.direction*0.05) + Vector(0,0,100) datatable.dietime = CurTime() + 50 datatable.id = "css_bullet" return datatable end <file_sep>/lua/weapons/weapon_hl2_fists.lua if CLIENT then --killicon.AddFont( "weapon__crowbar", "HL2MPTypeDeath", "6", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/achievements/pistol_round_knife_kill") end SWEP.Category = "BurgerBase: Half Life 2" SWEP.PrintName = "Fists" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Free" SWEP.Cost = 0 SWEP.CSSMoveSpeed = 260 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 0 SWEP.SlotPos = 1 SWEP.ViewModel = Model( "models/weapons/c_arms.mdl" ) SWEP.WorldModel = "" SWEP.VModelFlip = false SWEP.HoldType = "fist" SWEP.Primary.Damage = 10 SWEP.Primary.Cone = 1 SWEP.Primary.NumShots = 1 SWEP.Primary.ClipSize = -1 SWEP.Primary.SpareClip = -1 SWEP.Primary.Delay = 0.4 SWEP.Primary.Ammo = "none" SWEP.Primary.Automatic = true SWEP.Secondary.Damage = 0 SWEP.Secondary.NumShots = 1 SWEP.Secondary.ClipSize = -1 SWEP.Secondary.SpareClip = -1 SWEP.Secondary.Delay = 0.5 SWEP.Secondary.Ammo = "none" SWEP.Secondary.Automatic = true SWEP.RecoilMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 1 SWEP.HasCrosshair = false SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = false SWEP.MeleeSoundMiss = Sound( "WeaponFrag.Throw" ) SWEP.MeleeSoundWallHit = Sound( "Flesh.ImpactHard" ) SWEP.MeleeSoundFleshSmall = Sound( "Flesh.ImpactHard" ) SWEP.MeleeSoundFleshLarge = Sound( "Flesh.ImpactHard" ) SWEP.DamageFalloff = 40 SWEP.MeleeDamageType = DMG_CRUSH SWEP.MeleeDelay = 0.2 SWEP.EnableBlocking = true SWEP.IronSightTime = 0.125 SWEP.IronSightsPos = Vector(0, -15, -5) SWEP.IronSightsAng = Vector(45, 0, 0) SWEP.MeleeBlockReduction = 0.5 --[[ 1: act = -1 actname = id = 1 2: act = -1 actname = id = 2 3: act = -1 actname = id = 3 4: act = -1 actname = id = 4 5: act = -1 actname = id = 5 6: act = -1 actname = id = 6 7: act = -1 actname = ACT_VM_FISTS_IDLE id = 7 8: act = -1 actname = ACT_VM_FISTS_IDLE id = 8 -------------------- 0 = reference 1 = seq_admire 2 = fists_draw 3 = fists_right 4 = fists_left 5 = fists_uppercut 6 = fists_holster 7 = fists_idle_01 8 = fists_idle_02 --]] function SWEP:MeleeRange() return 40 end function SWEP:MeleeSize() return 40 end function SWEP:PrimaryAttack() if self:IsUsing() then return end self.Owner:SetAnimation(PLAYER_ATTACK1) if self:GetIsLeftFire() then self:SendSequence("fists_left") self:SetIsLeftFire(false) else self:SendSequence("fists_right") self:SetIsLeftFire(true) end self:StartSwing(self.Primary.Damage) self:SetNextPrimaryFire(CurTime() + self.Primary.Delay*2) self:SetNextSecondaryFire(CurTime() + self.Primary.Delay) end function SWEP:FinishSwing(HitEntity,Damage) --[[ if HitEntity and HitEntity ~= NULL then if self:GetSpecialBool() then self:SetSpecialBool(false) elseif !self:GetIsLeftFire() and HitEntity:Health() > 0 then self:SetIsLeftFire(false) self:SetSpecialBool(true) self:SendSequence("fists_uppercut") self:StartSwing(self.Primary.Damage) self:SetNextPrimaryFire(CurTime() + self.Primary.Delay*2) end end --]] end SWEP.EnableBlocking = true function SWEP:SecondaryAttack() end function SWEP:Reload() end function SWEP:SpecialDeploy() self.Owner:DrawViewModel(true) self:SendSequence("fists_draw") self:SetNextPrimaryFire(CurTime() + self.Owner:GetViewModel():SequenceDuration()) end<file_sep>/lua/burgerbase/core/server/other/core_chatcommands.lua function BURGERBASE_HOOK_PlayerSay_CC(sender,text,teamChat) if sender:IsPlayer() then if text == "!burgerclient" then sender:ConCommand("burgerbase_client") return "" elseif text == "!burgerserver" then sender:ConCommand("burgerbase_server") return "" end end return text end hook.Add("PlayerSay","BURGERBASE_HOOK_PlayerSay_CC",BURGERBASE_HOOK_PlayerSay_CC) <file_sep>/lua/weapons/weapon_hl2_ar2.lua if CLIENT then killicon.AddFont( "weapon_hl2_ar2", "HL2MPTypeDeath", "2", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/sg552") end SWEP.Category = "BurgerBase: Half Life 2" SWEP.PrintName = "AR2" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 3500 SWEP.CSSMoveSpeed = 220 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/c_irifle.mdl" SWEP.WorldModel = "models/weapons/w_irifle.mdl" SWEP.VModelFlip = false SWEP.HoldType = "ar2" SWEP.Primary.Damage = 20 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("weapons/ar2/fire1.wav") SWEP.Primary.Cone = 0.006 SWEP.Primary.ClipSize = 30 SWEP.Primary.SpareClip = 90 SWEP.Primary.Delay = 0.1 SWEP.Primary.Ammo = "ar2" SWEP.Primary.Automatic = true SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 1 SWEP.RecoilSpeedMul = 2 SWEP.MoveConeMul = 2 SWEP.HeatMul = 0.5 SWEP.CoolMul = 0.5 SWEP.CoolSpeedMul = 1 SWEP.HasScope = true SWEP.ZoomAmount = 3 SWEP.HasCrosshair = true SWEP.HasCSSZoom = true SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = true SWEP.HasDryFire = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = false SWEP.DamageFalloff = 3000 SWEP.DamageType = 2 SWEP.HasIronSights = true SWEP.EnableIronCross = false SWEP.HasGoodSights = false SWEP.IronSightTime = 0.5 SWEP.ZoomTime = 0.125 SWEP.ZoomDelay = 0.125 SWEP.IronSightsPos = Vector(-5.801, 0, 1.08) SWEP.IronSightsAng = Vector(0, 0, -10) SWEP.IronRunPos = Vector(8.843, -7.035, -5) SWEP.IronRunAng = Vector(0, 45, 0) SWEP.IronMeleePos = Vector(0, -1.609, -0.202) SWEP.IronMeleeAng = Vector(-5.628, 35.879, -52.061)<file_sep>/lua/burgerbase/core/shared/core_other.lua BURGERBASE:INIT_MassInclude("burgerbase/core/shared/other/","shared",false)<file_sep>/lua/burgerbase/core/server/other_core.lua BURGERBASE:INIT_MassInclude("burgerbase/core/server/other/","server",false)<file_sep>/lua/burgerbase/core/client/other/flashbang_blind.lua local SmokeMat = Material("skybox/italydn") local ActualSmokeAmount = 0 local function BURGERBASE_HOOK_RenderScreenspaceEffects() local ply = LocalPlayer() if ply.IsBlinded == true then if ply.BlindAmount > 0 then local Mod = math.Clamp(ply.BlindAmount,0,1) local Settings = { [ "$pp_colour_brightness" ] = Mod, [ "$pp_colour_contrast" ] = 1, [ "$pp_colour_colour" ] = 1, [ "$pp_colour_addr" ] = 0, [ "$pp_colour_addg" ] = 0, [ "$pp_colour_addb" ] = 0, [ "$pp_colour_mulr" ] = 0, [ "$pp_colour_mulg" ] = 0, [ "$pp_colour_mulb" ] = 0 } DrawColorModify( Settings ) ply.BlindAmount = ply.BlindAmount - FrameTime()*0.5 else ply.BlindAmount = 0 ply.IsBlinded = false end end local IsInSmoke = false local SmokeAmount = 0 local Range = 125 for k,v in pairs(ents.FindByClass("ent_burger_cs_smoke")) do local Distance = ply:GetPos():Distance(v:GetPos()) if Distance <= Range and v:GetNWBool("IsDetonated",false) then IsInSmoke = true SmokeAmount = SmokeAmount + math.Clamp(Range - Distance,0,Range) / Range end end --print(SmokeAmount) if IsInSmoke or ActualSmokeAmount ~= 0 then local DesiredModAmount = math.Clamp(SmokeAmount*2,0,1) if ActualSmokeAmount < DesiredModAmount then -- Is less than ActualSmokeAmount = math.min(DesiredModAmount,ActualSmokeAmount + FrameTime()) elseif ActualSmokeAmount > DesiredModAmount then -- Is greater than ActualSmokeAmount = math.max(DesiredModAmount,ActualSmokeAmount - FrameTime()) end surface.SetMaterial(SmokeMat) surface.SetDrawColor( Color(200,200,200,ActualSmokeAmount*255) ) --surface.DrawTexturedRect( 0, 0, ScrW(), ScrH() ) surface.DrawRect( 0, 0, ScrW(), ScrH() ) end end hook.Add("RenderScreenspaceEffects","BURGERBASE_HOOK_RenderScreenspaceEffects",BURGERBASE_HOOK_RenderScreenspaceEffects) <file_sep>/lua/weapons/weapon_burger_cs_ak47.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_ak47", "csd", "b", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/ak47") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "AK-47" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 2500 SWEP.CSSMoveSpeed = 221 SWEP.Description = "Excels at long-to-medium range." SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/cstrike/c_rif_ak47.mdl" SWEP.WorldModel = "models/weapons/w_rif_ak47.mdl" SWEP.VModelFlip = false SWEP.HoldType = "ar2" SWEP.Primary.Damage = 36 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_AK47.Single") SWEP.Primary.Cone = 0.0025 SWEP.Primary.ClipSize = 30 SWEP.Primary.SpareClip = 90 SWEP.Primary.Delay = 0.1 SWEP.Primary.Ammo = "bb_762mm" SWEP.Primary.Automatic = true SWEP.RecoilMul = 2 SWEP.SideRecoilMul = 0.25 SWEP.RecoilSpeedMul = 1.125 SWEP.MoveConeMul = 2 SWEP.HeatMul = 0.5 SWEP.CoolMul = 0.75 SWEP.CoolSpeedMul = 1.25 SWEP.MaxHeat = 10 SWEP.HasScope = false SWEP.ZoomAmount = 1 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = false SWEP.DamageFalloff = 3000 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = false SWEP.IronSightTime = 0.5 SWEP.ZoomTime = 0.5 SWEP.IronSightsPos = Vector(-6.64, 20, 1) SWEP.IronSightsAng = Vector(1, 0, 0) SWEP.IronRunPos = Vector(8.843, -7.035, 0) SWEP.IronRunAng = Vector(0, 45, 0) SWEP.IronMeleePos = Vector(0, -1.609, -0.202) SWEP.IronMeleeAng = Vector(-5.628, 35.879, -52.061) <file_sep>/lua/weapons/weapon_burger_core_base/init.lua AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function SWEP:EquipAmmo(ply) -- server if BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_ammo_givespare"):GetFloat() == 1 or self.WeaponType == "Equipment" then ply:GiveAmmo(self.Primary.SpareClip,self:GetPrimaryAmmo(),false) ply:GiveAmmo(self.Secondary.SpareClip,self:GetSecondaryAmmo(),false) --print(self.Secondary.SpareClip,self:GetSecondaryAmmo()) elseif self.WeaponType == "Throwable" then ply:GiveAmmo(1,self:GetPrimaryAmmo(),false) end self:SpecialGiveAmmo() end function SWEP:SpecialGiveAmmo() -- server end function SWEP:ShootPhysicalObject(Source,Cone,Direction) -- Server local EyeTrace = self.Owner:GetEyeTrace() local TheEyePos = self.Owner:EyePos() local HitPos = EyeTrace.HitPos Source = Source + self.Owner:GetForward()*self.SourceOverride.y + self.Owner:GetRight()*self.SourceOverride.x + self.Owner:GetUp()*self.SourceOverride.z local Dir = (Source - HitPos) local Dir = Direction Dir:Normalize() local FinalAngles = Dir:Angle() + self.BulletAngOffset + Angle(self:BulletRandomSeed(-Cone,Cone),self:BulletRandomSeed(-Cone,Cone),0)*45 FinalAngles:Normalize() local Bullet = ents.Create(self.BulletEnt) if Bullet:IsValid() then Bullet:SetPos(Source) Bullet:SetAngles( FinalAngles ) Bullet:SetOwner(self.Owner) Bullet:Spawn() Bullet:Activate() else SafeRemoveEntity(Bullet) end if IsFirstTimePredicted() then self:TracerCreation(Source + Dir*100,Source,Dir,self.Owner) end end<file_sep>/lua/burgerbase/modules/css/client/css_menus.lua BURGERBASE:INIT_MassInclude("burgerbase/modules/css/client/menus/","client",false)<file_sep>/lua/weapons/weapon_burger_cs_usp.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_usp", "csd", "y", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/usp45") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "USP" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Secondary" SWEP.Cost = 500 SWEP.CSSMoveSpeed = 250 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Description = ".45 pistol that comes with a silencer" SWEP.Slot = 1 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/cstrike/c_pist_usp.mdl" SWEP.WorldModel = "models/weapons/w_pist_usp.mdl" SWEP.VModelFlip = false SWEP.HoldType = "revolver" SWEP.Primary.Damage = 34 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_USP.Single") SWEP.Primary.Cone = 0.004 SWEP.Primary.ClipSize = 12 SWEP.Primary.SpareClip = 100 SWEP.Primary.Delay = 0.15 --1/(400/60) SWEP.Primary.Ammo = "bb_45acp" SWEP.Primary.Automatic = false SWEP.WorldModel1 = "models/weapons/w_pist_usp.mdl" SWEP.WorldModel2 = "models/weapons/w_pist_usp_silencer.mdl" SWEP.Secondary.Sound = Sound("Weapon_USP.SilencedShot") SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 0.25 SWEP.RecoilSpeedMul = 1.5 SWEP.MoveConeMul = 0.5 SWEP.HeatMul = 0.5 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 0.75 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = true SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = false SWEP.HasDownRecoil = false SWEP.HasDryFire = true SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = true SWEP.DamageFalloff = 2000 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.25 SWEP.ZoomTime = 0.5 SWEP.IronSightsPos = Vector(-4, 0, 1.759) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(0, 0, 0) SWEP.IronRunAng = Vector(0, 0, 0) SWEP.IronMeleePos = Vector(-5.801, -13.468, -20) SWEP.IronMeleeAng = Vector(70, 0, 0)<file_sep>/lua/burgerbase/core/server/other/core_joinmessage.lua function BURGERBASE_HOOK_PlayerInitialSpawn( ply ) ply:SendLua( [[chat.AddText(Color(255,255,255), "This server is running BurgerBase weapons. Enter",Color(0,255,0)," !burgerclient ",Color(255,255,255),Color(255,255,255),"to access the player menu.")]] ) if not game.IsDedicated() then if ply == Entity(1) then ply:SendLua( [[chat.AddText(Color(255,255,255), "Enter",Color(0,255,0)," !burgerserver ",Color(255,255,255),Color(255,255,255),"to access the admin menu.")]] ) end end end hook.Add( "PlayerInitialSpawn", "BURGERBASE_HOOK_PlayerInitialSpawn", BURGERBASE_HOOK_PlayerInitialSpawn ) <file_sep>/lua/weapons/weapon_burger_cs_famas.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_famas", "csd", "t", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/famas") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "FAMAS" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 2250 SWEP.CSSMoveSpeed = 220 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Description = "General all-purpose rifle. Comes with a burst fire setting." SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/cstrike/c_rif_famas.mdl" SWEP.WorldModel = "models/weapons/w_rif_famas.mdl" SWEP.VModelFlip = false SWEP.HoldType = "ar2" SWEP.Primary.Damage = 30 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_FAMAS.Single") SWEP.Primary.Cone = 0.0033 SWEP.Primary.ClipSize = 25 SWEP.Primary.SpareClip = 90 SWEP.Primary.Delay = 0.09 --1/(666/60) SWEP.Primary.Ammo = "bb_556mm" SWEP.Primary.Automatic = true SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 0.25 SWEP.RecoilSpeedMul = 1.1 SWEP.MoveConeMul = 1.25 SWEP.HeatMul = 1 SWEP.CoolMul = 0.5 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 1 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = true SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = false SWEP.BurstConeMul = 1.5 SWEP.BurstHeatMul = 0.5 SWEP.BurstRecoilMul = 0.75 SWEP.BurstSpeedOverride = 1.25 SWEP.DamageFalloff = 2500 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = false SWEP.IronSightTime = 0.5 SWEP.ZoomTime = 0.5 SWEP.IronSightsPos = Vector(-5, 10, 3) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(-2.01, 0.201, 0.602) SWEP.IronRunAng = Vector(-5, 15, -7.739) SWEP.IronMeleePos = Vector(3.14, 4.623, 0) SWEP.IronMeleeAng = Vector(0, 46.431, -26.734)<file_sep>/lua/burgerbase/core/shared/other/core_ammocollision.lua local TableFamily = {"ent_burger_core_ammo","ent_burger_core_dropped_weapon","ent_burger_core_dropped_ammo","ent_burger_core_dropped_equipment"} function BURGERBASE_HOOK_ShouldCollide(ent1,ent2) if table.HasValue(TableFamily,ent1:GetClass()) and table.HasValue(TableFamily,ent2:GetClass()) then return false end end hook.Add("ShouldCollide","BURGERBASE_HOOK_ShouldCollide",BURGERBASE_HOOK_ShouldCollide) <file_sep>/lua/weapons/weapon_burger_core_template_explained.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_ak47", "csd", "b", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/ak47") end SWEP.Category = "Counter-Strike" -- The Weapon Category this weapon spawns in. SWEP.PrintName = "Example Weapon" -- The name of the weapon. SWEP.Base = "weapon_burger_core_base" -- The base the weapon uses. Should always be "weapon_burger_base" unless you know exactly what you're doing. SWEP.BurgerBase = true -- Confirmation that this uses Burger's Base. Should always be true unless you know exactly what you're doing. SWEP.WeaponType = "Primary" -- The weapon type of the weapon. Valid Values: Primary, Secondary, Free, Melee. SWEP.Cost = 2500 -- The Cost of the weapon. Doesn't do anything, but it's good for other developers to check the cost of the weapon (Like DarkRP) SWEP.CSSMoveSpeed = 221 -- The base movespeed of the weapon, in units per second. This movement value is scaled based on the player's actual movespeed. SWEP.Spawnable = false -- Should be spawnable by the Q menu, if the gamemode has one. SWEP.AdminOnly = false -- Only admins can spawn this weapon, if the gamemode has a q menu. SWEP.Slot = 3 -- Slot for the weapon. Subtract 1 from the initial slot value. (Example: If you want a weapon to be in slot 4, then set the slot to 3. Don't ask my why this is a thing, blame garry. SWEP.SlotPos = 1 -- Position of the slot in vertical form. Not really that useful, and it should be at 1. SWEP.Weight = 0 -- Priority of the weapon in terms of automatic weapon switching. Not the actual physical weight itself. SWEP.AutoSwitchTo = false -- Set to true if you want players to switch to this weapon if they get it, if the weapon's weight is higher than the previous weapon's weight. SWEP.AutoSwitchFrom = false -- Set to true if you want players to switch from this weapon if they get it, if the next weapon's weight is higher than the weapon's weight. SWEP.UseHands = true -- Set to true if you want players to use c_model (player specific) hands. Only works with some weapons that support this. SWEP.ViewModel = "models/weapons/cstrike/c_rif_ak47.mdl" -- The viewmodel of the weapon. SWEP.WorldModel = "models/weapons/w_rif_ak47.mdl" SWEP.DisplayWorldModel = nil SWEP.ViewModelFlip = false SWEP.HoldType = "ar2" SWEP.Primary.Damage = 36 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_AK47.Single") SWEP.Primary.Cone = 0.0025 SWEP.Primary.ClipSize = 30 SWEP.Primary.SpareClip = 90 SWEP.Primary.Delay = 0.1 SWEP.Primary.Ammo = "bb_762mm" SWEP.Primary.Automatic = true SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 0.5 SWEP.MoveConeMul = 1.5 SWEP.HeatMul = 1.5 SWEP.CoolMul = 0.6 SWEP.HasScope = false SWEP.HasCrosshair = true SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasIronSights = true SWEP.HasIronCrosshair = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.125 SWEP.IronSightsPos = Vector(-3, 20, 0) SWEP.IronSightsAng = Vector(1.25, 1, 0) SWEP.ZoomAmount = 1 SWEP.DamageFalloff = 3000 SWEP.AddFOV = -10<file_sep>/lua/weapons/weapon_burger_cs_aug.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_aug", "csd", "e", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/aug") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "AUG" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 3500 SWEP.CSSMoveSpeed = 221 SWEP.Description = "Excels at long-to-medium range. Comes with a scope." SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/cstrike/c_rif_aug.mdl" SWEP.WorldModel = "models/weapons/w_rif_aug.mdl" SWEP.VModelFlip = false SWEP.HoldType = "smg" SWEP.Primary.Damage = 32 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_AUG.Single") SWEP.Primary.Cone = 0.001 SWEP.Primary.ClipSize = 30 SWEP.Primary.SpareClip = 90 SWEP.Primary.Delay = 0.09 SWEP.Primary.Ammo = "bb_556mm" SWEP.Primary.Automatic = true SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 0.5 SWEP.RecoilSpeedMul = 0.9 SWEP.MoveConeMul = 2 SWEP.HeatMul = 0.25 SWEP.CoolMul = 0.75 SWEP.CoolSpeedMul = 1 SWEP.MaxHeat = 10 SWEP.HasScope = true SWEP.ZoomAmount = 3 SWEP.HasCrosshair = true SWEP.HasCSSZoom = true SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = false SWEP.DamageFalloff = 3000 SWEP.HasIronSights = false SWEP.EnableIronCross = false SWEP.HasGoodSights = true SWEP.IronSightTime = 0.5 SWEP.ZoomTime = 0.5 SWEP.ZoomDelay = 0.125 SWEP.IronSightsPos = Vector(-7.437, -7.035, 2.009) SWEP.IronSightsAng = Vector(0, 0, -36.401) SWEP.IronRunPos = Vector(-2.01, 0.201, 0.602) SWEP.IronRunAng = Vector(-5, 15, -7.739) SWEP.IronMeleePos = Vector(3.417, -14.674, -13.87) SWEP.IronMeleeAng = Vector(-9.146, 70, -70) <file_sep>/lua/burgerbase/core/shared/convars/core_convars_clientside.lua local ClientFCVar = FCVAR_ARCHIVE + FCVAR_USERINFO BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_language","english",ClientFCVar,"Language",true) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_togglezoom", 1, ClientFCVar, "Enables hold to zoom",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_customslots", 0, ClientFCVar, "Enables or disables the game forcing primary weapons into slot 3",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_viewmodel_fov", 20, ClientFCVar, "Viewmodel FOV to add to the weapon viewmodel.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_style", 1, ClientFCVar, "Style of the crosshair.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_length", 10, ClientFCVar, "Length in pixels of the crosshair.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_color_r", 255, ClientFCVar, "Red value of the crosshair.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_color_g", 255, ClientFCVar, "Green value of the crosshair.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_color_b", 255, ClientFCVar, "Blue value of the crosshiar.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_color_a", 255, ClientFCVar, "Alpha value of the crosshair.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_dynamic", 1, ClientFCVar, "Enables or disables crosshairs based on accuracy.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_dot", 0, ClientFCVar, "Enables or disables center dot crosshair.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_shadow", 1, ClientFCVar, "Enables or disables black outline around crosshairs.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_smoothing", 1, ClientFCVar, "Enables or disables crosshair smoothing.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_smoothing_mul",1, ClientFCVar, "Crosshair smoothing multiplier.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_neversights", 0, ClientFCVar, "Enables or disables real ironsighs.",true ) BURGERBASE:CONVARS_CreateStoredConvar("cl_burgerbase_crosshair_offset", 0, ClientFCVar, "Crosshair offset in pixels.",true ) <file_sep>/lua/weapons/weapon_burger_core_template.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_ak47", "csd", "b", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/ak47") end -- Weapon Information SWEP.Category = "Other" SWEP.PrintName = "Example Weapon" SWEP.Base = "weapon_burger_core_base" SWEP.BurgerBase = true SWEP.WeaponType = "Primary" SWEP.Cost = 2500 SWEP.CSSMoveSpeed = 221 -- Spawning SWEP.Spawnable = false SWEP.AdminOnly = false -- Slots SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.Weight = 0 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false -- Worldmodel SWEP.WorldModel = "models/weapons/w_rif_ak47.mdl" SWEP.DisplayModel = nil SWEP.HoldType = "ar2" -- Viewmodel SWEP.ViewModel = "models/weapons/cstrike/c_rif_ak47.mdl" SWEP.ViewModelFlip = false SWEP.UseHands = true SWEP.IgnoreScopeHide = false SWEP.AddFOV = 0 -- Bullet Information SWEP.Primary.Damage = 36 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_AK47.Single") SWEP.Primary.Cone = 0.0025 SWEP.Primary.ClipSize = 30 SWEP.Primary.SpareClip = 90 SWEP.Primary.Delay = 0.1 SWEP.Primary.Ammo = "bb_762mm" SWEP.Primary.Automatic = true SWEP.BulletEnt = nil -- Bullet Entity that is Spawned SWEP.SourceOverride = Vector(0,0,0) -- Projectile Spawn Offset SWEP.BulletAngOffset = Angle(0,0,0) -- Rotate the Projectile by this amount -- General Weapon Statistics SWEP.RecoilMul = 1 SWEP.SideRecoilMul = 0.5 SWEP.MoveConeMul = 1 SWEP.HeatMul = 1 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.PenetrationLossMul = 1 SWEP.SideRecoilBasedOnDual = false SWEP.FatalHeadshot = false SWEP.TracerType = 1 SWEP.DamageFalloff = 3000 SWEP.ReloadTimeAdd = 0 SWEP.ShootOffsetStrength = Angle(0,0,0) -- Recoil for OP Snipers -- Sounds SWEP.ZoomInSound = Sound("weapons/zoom.wav") SWEP.ZoomOutSound = Sound("weapons/zoom.wav") SWEP.ReloadSound = nil SWEP.BurstSound = nil SWEP.LastBulletSound = nil SWEP.PumpSound = nil SWEP.MeleeSoundMiss = nil SWEP.MeleeSoundWallHit = nil SWEP.MeleeSoundFleshSmall = nil SWEP.MeleeSoundFleshLarge = nil -- Features SWEP.HasIronSights = true SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasSpecialFire = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasBuildUp = false -- Uses Minigun Buildup SWEP.UsesBuildUp = false -- Uses Buildup for Custom Reasons SWEP.BuildUpAmount = 10 SWEP.BuildUpCoolAmount = 50 SWEP.HasIdle = false SWEP.IdleOffset = 0 SWEP.DisableReloadUntilEmpty = false SWEP.IgnoreDrawDelay = false SWEP.EnableDropping = true -- Melee SWEP.EnableBlocking = false SWEP.MeleeDelay = 0.05 SWEP.MeleeDamageType = DMG_SLASH -- Zooming SWEP.HasIronCrosshair = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.125 SWEP.IronSightsPos = Vector(-3, 20, 0) SWEP.IronSightsAng = Vector(1.25, 1, 0) SWEP.ZoomAmount = 1 SWEP.ZoomDelay = 0 -- Scope SWEP.HasScope = false SWEP.CustomScope = nil SWEP.CustomScopeSOverride = nil SWEP.CustomScopeCOverride = Color(0,0,0,255) SWEP.ColorOverlay = Color(0,0,0,0) -- Color Overlay when Zoomed -- Crosshair SWEP.HasCrosshair = true SWEP.CrosshairOverrideMat = nil SWEP.CrosshairOverrideSize = nil -- Tracers SWEP.EnableCustomTracer = true SWEP.CustomShootEffectsTable = nil -- Magazine Mod SWEP.MagDelayMod = 0.75 SWEP.MagMoveMod = Vector(0,0,0) SWEP.MagAngMod = Angle(0,0,0) -- PLEASE TEST SWEP.DelayOverride = false<file_sep>/lua/burgerbase/core/shared/other/core_movement.lua function BURGERBASE_HOOK_Move(ply,mv) if BURGERBASE and BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_speedmod",false):GetBool() then local ActiveWeapon = ply:GetActiveWeapon() local BaseSpeed = 250 local WeaponSpeed = 250 if ActiveWeapon and ActiveWeapon ~= NULL and ActiveWeapon.CSSMoveSpeed then WeaponSpeed = ActiveWeapon.CSSMoveSpeed if ActiveWeapon.CSSZoomSpeed and ActiveWeapon.CSSZoomSpeed ~= -1 and ActiveWeapon:GetSharedZoom() then WeaponSpeed = ActiveWeapon.CSSZoomSpeed end end if WeaponSpeed ~= -1 then local PreviousLimit = mv:GetMaxClientSpeed() local SpeedMod = (WeaponSpeed / BaseSpeed) local NewLimit = PreviousLimit * SpeedMod if ply:Crouching() then NewLimit = NewLimit * ply:GetCrouchedWalkSpeed() end if SERVER then --print(math.Round(CurTime(),2),"CSS:",PreviousLimit,NewLimit) end mv:SetMaxSpeed( NewLimit ) mv:SetMaxClientSpeed( NewLimit ) end end end hook.Add("Move","BURGERBASE_HOOK_Move",BURGERBASE_HOOK_Move)<file_sep>/lua/burgerbase/core/shared/other/core_flinching.lua function BURGERBASE_FUNC_TRANSLATEANIM(hitgroup) local AnimationTable = {} AnimationTable[HITGROUP_HEAD] = {"flinch_head_01","flinch_head_02"} AnimationTable[HITGROUP_CHEST] = {"flinch_01","flinch_02","flinch_stomach_01","flinch_stomach_02"} AnimationTable[HITGROUP_STOMACH] = {"flinch_01","flinch_02","flinch_stomach_01","flinch_stomach_02"} AnimationTable[HITGROUP_LEFTARM] = {"flinch_shoulder_l"} AnimationTable[HITGROUP_RIGHTARM] = {"flinch_shoulder_r"} AnimationTable[HITGROUP_LEFTLEG] = {"flinch_phys_01","flinch_phys_02"} AnimationTable[HITGROUP_RIGHTLEG] = {"flinch_phys_01","flinch_phys_02"} AnimationTable[HITGROUP_GEAR] = {"flinch_phys_01","flinch_phys_02"} local SelectedAnimationTable = AnimationTable[hitgroup] if not SelectedAnimationTable then SelectedAnimationTable = {"flinch_phys_01","flinch_phys_02"} end local SelectedAnimation = SelectedAnimationTable[math.random(1,#SelectedAnimationTable)] return SelectedAnimation end function BURGERBASE_FUNC_SENDSEQUENCE(ply,anim) local Seq = ply:LookupSequence(anim) local SeqDur = ply:SequenceDuration(Seq) ply:AddVCDSequenceToGestureSlot( GESTURE_SLOT_FLINCH, Seq, 0, true ) return SeqDur end if SERVER then function BURGERBASE_HOOK_FLINCHING(victim,hitgroup,dmginfo) net.Start("BURGERBASE_NET_FLINCH") net.WriteEntity(victim) net.WriteInt(hitgroup,4) net.Broadcast() end hook.Add("ScalePlayerDamage","BURGERBASE_HOOK_FLINCHING",BURGERBASE_HOOK_FLINCHING) util.AddNetworkString("BURGERBASE_NET_FLINCH") end if CLIENT then function BURGERBASE_NET_FLINCH(len) local victim = net.ReadEntity() local hitgroup = net.ReadInt(4) if victim and victim:IsValid() then BURGERBASE_FUNC_SENDSEQUENCE(victim,BURGERBASE_FUNC_TRANSLATEANIM(hitgroup)) end end net.Receive( "BURGERBASE_NET_FLINCH", BURGERBASE_NET_FLINCH ) end <file_sep>/lua/weapons/weapon_hl2_smg.lua if CLIENT then killicon.AddFont( "weapon_hl2_smg", "HL2MPTypeDeath", "/", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/mp5") end SWEP.Category = "BurgerBase: Half Life 2" SWEP.PrintName = "SMG1" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Cost = 0 SWEP.CSSMoveSpeed = 230 SWEP.Slot = 2 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/c_smg1.mdl" SWEP.WorldModel = "models/weapons/w_smg1.mdl" SWEP.VModelFlip = false SWEP.HoldType = "smg" SWEP.Primary.Damage = 20 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("weapons/smg1/smg1_fire1.wav") SWEP.Primary.Cone = .0025 SWEP.Primary.ClipSize = 45 SWEP.Primary.SpareClip = 120 SWEP.Primary.Delay = 1/(750/60) SWEP.Primary.Ammo = "smg1" SWEP.Primary.Automatic = true SWEP.ReloadSound = Sound("weapons/smg1/smg1_reload.wav") --SWEP.BurstSound = Sound("weapons/smg1/smg1_fireburst1.wav") SWEP.Secondary.Ammo = "SMG1_Grenade" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.SpareClip = 3 SWEP.RecoilMul = 2 SWEP.SideRecoilMul = 0.75 SWEP.RecoilSpeedMul = 1.25 SWEP.MoveConeMul = 0.5 SWEP.HeatMul = 0.75 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.BurstConeMul = 0.5 SWEP.BurstRecoilMul = 0.5 SWEP.HasScope = false SWEP.ZoomAmount = 0.25 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = true SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasDryFire = false SWEP.HasSpecialFire = true SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = true SWEP.DamageFalloff = 1000 SWEP.Object = "grenade_ar2" SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = true SWEP.IronSightTime = 0.25 SWEP.IronSightsPos = Vector(-6.4, 0, 1.039) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(0,0,0) SWEP.IronRunAng = Vector(0,0,0) SWEP.IronMeleePos = Vector(0, 0, 0) SWEP.IronMeleeAng = Vector(-9.146, 30.25, -37.991) function SWEP:CanQuickThrow() return !self:HasSecondaryAmmoToFire() end SWEP.UseMuzzle = true function SWEP:QuickThrowOverride() if self:GetNextPrimaryFire() > CurTime() then return end if self:GetNextSecondaryFire() > CurTime() then return end if self:IsBusy() then return end if !self:HasSecondaryAmmoToFire() then return end self:TakeSecondaryAmmo(1) self.Owner:SetAnimation(PLAYER_ATTACK1) self:WeaponAnimation(self:Clip1(),ACT_VM_SECONDARYATTACK) if (IsFirstTimePredicted() or game.SinglePlayer()) then if (CLIENT or game.SinglePlayer()) then self:AddRecoil() -- Predict end self:ShootProjectile(50, 1, 0, self.Owner:GetShootPos(), self.Owner:GetAimVector(),true) self:EmitGunSound("weapons/ar2/ar2_altfire.wav") end self:SetNextPrimaryFire(CurTime() + self.Primary.Delay*10*2) end function SWEP:ModProjectileTable(datatable) datatable.direction = datatable.direction*800 datatable.hullsize = 1 datatable.resistance = datatable.direction*0.1 + Vector(0,0,200) datatable.dietime = CurTime() + 10 datatable.id = "launched_grenade" datatable.hullsize = 1 return datatable end <file_sep>/lua/weapons/weapon_hl2_crowbar.lua if CLIENT then killicon.AddFont( "weapon_hl2_crowbar", "HL2MPTypeDeath", "6", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/achievements/pistol_round_knife_kill") end SWEP.Category = "BurgerBase: Half Life 2" SWEP.PrintName = "Crowbar" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Melee" SWEP.Cost = 0 SWEP.CSSMoveSpeed = 240 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 0 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/c_crowbar.mdl" SWEP.WorldModel = "models/weapons/w_crowbar.mdl" SWEP.VModelFlip = false SWEP.HoldType = "melee" SWEP.Primary.Damage = 25 SWEP.Primary.NumShots = 1 SWEP.Primary.ClipSize = -1 SWEP.Primary.SpareClip = -1 SWEP.Primary.Delay = 0.34 SWEP.Primary.Ammo = "none" SWEP.Primary.Automatic = true SWEP.Secondary.Damage = 0 SWEP.Secondary.NumShots = 1 SWEP.Secondary.ClipSize = -1 SWEP.Secondary.SpareClip = -1 SWEP.Secondary.Delay = 0 SWEP.Secondary.Ammo = "none" SWEP.Secondary.Automatic = true SWEP.RecoilMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 1 SWEP.HasCrosshair = false SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = false SWEP.EnableBlocking = true SWEP.IronSightTime = 0.125 SWEP.IronSightsPos = Vector(-10, -10, 5) SWEP.IronSightsAng = Vector(0, 0, -45) SWEP.MeleeSoundMiss = Sound("Weapon_Crowbar.Single") SWEP.MeleeSoundWallHit = Sound("Flesh.BulletImpact") SWEP.MeleeSoundFleshSmall = Sound("Weapon_Crowbar.Melee_Hit") SWEP.MeleeSoundFleshLarge = Sound("Weapon_Crowbar.Melee_Hit") SWEP.DamageFalloff = 55 SWEP.MeleeDamageType = DMG_CLUB SWEP.MeleeDelay = 0 SWEP.MeleeBlockReduction = 0.25 function SWEP:MeleeRange() return 55 end function SWEP:MeleeSize() return 32 end function SWEP:PrimaryAttack() if self:IsUsing() then return end if self:GetNextPrimaryFire() > CurTime() then return end if self.Owner:KeyDown(IN_ATTACK2) then return end self.Owner:SetAnimation(PLAYER_ATTACK1) local Delay = self.Primary.Delay local Victim = self:StartSwing(self.Primary.Damage) if Victim and Victim ~= NULL then self:SendWeaponAnim(ACT_VM_HITCENTER) else self:SendWeaponAnim(ACT_VM_MISSCENTER) Delay = Delay*1.25 end self:SetNextPrimaryFire(CurTime() + Delay) self:SetNextSecondaryFire(CurTime() + Delay) end function SWEP:SecondaryAttack() end function SWEP:SpareThink() if self.Owner:KeyDown(IN_ATTACK2) then self.CSSMoveSpeed = 240*0.25 else self.CSSMoveSpeed = 240 end end function SWEP:Reload() end --[[ function SWEP:SpecialDeploy() self:CheckInventory() self.Owner:DrawViewModel(true) self:SendWeaponAnim(ACT_VM_DRAW) self:SetNextPrimaryFire(CurTime() + self.Owner:GetViewModel():SequenceDuration()) return true end --]] <file_sep>/lua/weapons/weapon_burger_core_base/cl_init.lua include("shared.lua") function SWEP:TranslateFOV(fov) -- Client local ZoomAmount = self.ZoomAmount if (self.HasBurstFire or self.AlwaysBurst) and self:GetIsBurst() then ZoomAmount = ZoomAmount*self.BurstZoomMul end ZoomAmount = self:SpecialZoom(ZoomAmount) local ZoomMag = 1 if self.Owner.BURGERBASE_ZoomMul and self.Owner.BURGERBASE_ZoomMul[self:GetClass()] then ZoomMag = 1 + ( self:GetZoomMod() * ZoomAmount * math.Clamp(self.Owner.BURGERBASE_ZoomMul[self:GetClass()],0,1) ) end return fov / ZoomMag end function SWEP:AdjustMouseSensitivity() -- Client return (self.Owner:GetFOV() / self.DesiredFOV) end function SWEP:DrawHUDBackground() -- Client local x = ScrW() local y = ScrH() self:DrawContextMenu(x,y) if LocalPlayer():ShouldDrawLocalPlayer() then local HitPos = LocalPlayer():GetEyeTrace().HitPos local Screen = HitPos:ToScreen() x = Screen.x * 2 y = Screen.y * 2 end local length = BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_length",true):GetFloat() local width = 1 local fovbonus = self.DesiredFOV / self.Owner:GetFOV() local r = BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_color_r",true):GetFloat() local g = BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_color_g",true):GetFloat() local b = BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_color_b",true):GetFloat() local a = BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_color_a",true):GetFloat() local VelCone = self.Owner:GetVelocity():Length()*0.0001 local LeftCone = 0 local RightCone = 0 --[[ if BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_dynamic",true):GetFloat() == 0 then LeftCone = math.Clamp(self.Primary.Cone*900,0,x/2) RightCone = math.Clamp(self.Primary.Cone*900,0,x/2) else LeftCone = math.Clamp(self:HandleCone(self.Primary.Cone,true,true)*900,0,x/2)*fovbonus RightCone = math.Clamp(self:HandleCone(self.Primary.Cone,true,false)*900,0,x/2)*fovbonus end --]] --LeftCone = self:HandleCone(self.Primary.Cone,true,true) * fovbonus --RightCone = ( *ScrW()*0.5 ) * (90/self.Owner:GetFOV()) local ConeAngle = (self:HandleCone(self.Primary.Cone,true,false)*360) -- THE IS THE CONE, IN AN ANGLE. 360 MEANS IT SHOOTS ALL AROUND local LeftConeAngle = (self:HandleCone(self.Primary.Cone,true,true)*360) -- THE IS THE CONE, IN AN ANGLE. 360 MEANS IT SHOOTS ALL AROUND local FOV = self.Owner:GetFOV() -- THIS IS THE FOV. 360 MEANS IT SHOWS ALL AROUND -- OK SO A FOV OF 360 AND A CONEANGLE OF 360 MEANS THAT THE CONE GAP SHOULD BE 1 * ScrW() -- OK SO A FOV OF 90 AND A CONEANGLE OF 90 MEANS THAT THE CONE GAP SHOULD BE 1 * ScrW() -- OK SO A FOV OF 90 AND A CONEANGLE OF 45 MEANS THAT THE CONE GAP SHOULD BE 0.5 * ScrW() --print(ConeAngle) RightCone = (ConeAngle/FOV) * ScrH() * 0.25 LeftCone = (LeftConeAngle/FOV) * ScrH() * 0.25 --[[ if not IsSingleplayer then if BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_smoothing",true):GetFloat() == 1 then if not self.StoredCrosshair then self.StoredCrosshair = Cone end local SmoothingMul = BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_smoothing_mul",true):GetFloat() * 0.015 * fovbonus if Cone > self.StoredCrosshair then self.StoredCrosshair = math.min(Cone,self.StoredCrosshair + 500 * SmoothingMul ) elseif Cone < self.StoredCrosshair then self.StoredCrosshair = math.max(Cone,self.StoredCrosshair - 300 * SmoothingMul ) end ConeToSend = self.StoredCrosshair end end --]] if self.HasScope then if self:GetZoomed() then if self.ZoomDelay <= 0 or self:GetZoomOverlayDelay() <= CurTime() then if LocalPlayer():ShouldDrawLocalPlayer() then self:DrawCustomCrosshair(x,y,RightCone,length,width,r,g,b,a) else self:DrawCustomScope(x,y,RightCone,r,g,b,a) end if not self.IgnoreScopeHide then self.Owner:DrawViewModel(false) end else self.Owner:DrawViewModel(true) end else self.Owner:DrawViewModel(true) end end if (self.HasCrosshair or (self.Owner:IsPlayer() and self.Owner:IsBot())) and not self.Owner:InVehicle() then if self.HasDual then local LeftAlpha = a local RightAlpha = a if !self:GetIsLeftFire() then RightAlpha = RightAlpha * 0.5 else LeftAlpha = LeftAlpha * 0.5 end self:DrawCustomCrosshair(x,y,LeftCone,length,width,r,g,b,LeftAlpha) self:DrawCustomCrosshair(x,y,RightCone,length,width,r,g,b,RightAlpha) else self:DrawCustomCrosshair(x,y,RightCone,length,width,r,g,b,a) end end self:DrawSpecial(RightCone) end function SWEP:DrawContextMenu(x,y) -- Client if BurgerBase_ContextMenuIsOpen == true then local x = ScrW() local y = ScrH() local BasePosX = 192 local BasePosY = 108 local Font = "DermaLarge" local FontSize = 36 local EyeTrace = self.Owner:GetEyeTrace() local EyePos = EyeTrace.StartPos local HitPos = EyeTrace.HitPos local WeaponStats = BURGERBASE_CalculateWeaponStats(self.Owner,self) draw.RoundedBox( 8, ScrW()*0.1 - FontSize , ScrH()*0.1 - FontSize, BasePosX*3 + FontSize*2, FontSize*15, Color(0,0,0,200 ) ) local TextColor = Color(239,184,55,255) local PrimaryColor = Color(239,184,55,100) local SecondaryColor = TextColor surface.SetFont( "DermaLarge" ) surface.SetTextColor( TextColor ) surface.SetDrawColor( PrimaryColor ) draw.NoTexture() -- Title local PosNumber = 0 surface.SetTextPos( BasePosX,BasePosY ) surface.DrawText( WeaponStats.ammo .. " " .. WeaponStats.name ) surface.DrawRect( BasePosX, BasePosY + FontSize, BasePosX*3, 2 ) -- Damage local FullDamage = WeaponStats.damage * WeaponStats.shots PosNumber = PosNumber + 2 surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3, FontSize ) surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3 * math.Clamp((FullDamage/100),0,1), FontSize ) surface.SetTextPos( BasePosX,BasePosY + FontSize*PosNumber ) local DamageText = " Damage: " .. math.Round(FullDamage,0) if WeaponStats.shots > 1 then DamageText = DamageText .. " (" .. WeaponStats.damage .. " x " .. WeaponStats.shots .. ")" end surface.DrawText( DamageText ) -- Firerate PosNumber = PosNumber + 2 surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3, FontSize ) surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3 * math.Clamp((WeaponStats.rpm/600),0,1), FontSize ) surface.SetTextPos( BasePosX,BasePosY + FontSize*PosNumber ) surface.DrawText( " RPM: " .. math.Round(WeaponStats.rpm,0)) -- Damage Per Second PosNumber = PosNumber + 2 surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3, FontSize ) surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3 * math.Clamp(WeaponStats.dps/600,0,1), FontSize ) surface.SetTextPos( BasePosX,BasePosY + FontSize*PosNumber ) surface.DrawText( " DPS: " .. math.Round(WeaponStats.dps,2)) -- Kill Time PosNumber = PosNumber + 2 surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3, FontSize ) surface.SetDrawColor( SecondaryColor ) surface.SetTextColor( SecondaryColor ) surface.SetFont( "DermaDefault" ) local TimeOffset = 0 for i=0, self:Clip1() - 1 do local Spacing = WeaponStats.delay if self:GetIsBurst() then Spacing = self:GetBurstMath() if (i+1) % self.BurstOverride == 0 then Spacing = Spacing + WeaponStats.delay end end local XPos = BasePosX + TimeOffset*BasePosX*3 local YOffset = (-(i % 2) * FontSize) - ((i % 2)*25) if TimeOffset <= 1 then surface.DrawRect( XPos, BasePosY + FontSize*PosNumber, 2, FontSize ) draw.SimpleText( math.Round(TimeOffset,2), "DermaDefault", XPos,BasePosY + FontSize*PosNumber + FontSize + YOffset,TextColor,TEXT_ALIGN_CENTER,TEXT_ALIGN_TOP) draw.SimpleText( "(" .. (i+1)*math.Round(FullDamage,0) .. ")", "DermaDefault", XPos,BasePosY + FontSize*PosNumber + FontSize + 10 + YOffset,TextColor,TEXT_ALIGN_CENTER,TEXT_ALIGN_TOP) TimeOffset = TimeOffset + Spacing end end surface.SetFont( "DermaLarge" ) surface.SetTextColor( TextColor ) surface.SetDrawColor( PrimaryColor ) surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3 * math.Clamp(WeaponStats.killtime/1,0,1), FontSize ) surface.SetTextPos( BasePosX,BasePosY + FontSize*PosNumber ) surface.DrawText( " Kill Time: " .. math.Round(WeaponStats.killtime,2) .. " seconds") -- Accuracy PosNumber = PosNumber + 2 surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3, FontSize ) surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3 * WeaponStats.accuracy, FontSize ) surface.SetTextPos( BasePosX,BasePosY + FontSize*PosNumber ) surface.DrawText( " Accuracy: " .. math.Round(WeaponStats.accuracy*100,2) .. "%") --[[ --Bullet Penetration PosNumber = PosNumber + 2 surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3, FontSize ) surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3 * 0.5, FontSize ) surface.SetTextPos( BasePosX,BasePosY + FontSize*PosNumber ) surface.SetTextPos( BasePosX,BasePosY + FontSize*PosNumber ) surface.DrawText( " Penetration: " .. BulletPenetration .. " units") --]] -- Range local BaseRange = WeaponStats.range*2 local ViewDistance = HitPos:Distance(EyePos) local MatterScale = BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damagefalloffscale"):GetFloat() PosNumber = PosNumber + 2 surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3, FontSize ) surface.DrawRect( BasePosX, BasePosY + FontSize*PosNumber, BasePosX*3 * 0.5, FontSize ) surface.SetTextPos( BasePosX,BasePosY + FontSize*PosNumber ) surface.DrawText( " Range: " .. math.Round(WeaponStats.range/(64/1.22),2) .. " meters") local PolyBaseX = BasePosX + (BasePosX*3 * 0.5) local PolyBaseY = BasePosY + FontSize*PosNumber local TriAngle = { {x = PolyBaseX,y = PolyBaseY}, {x = PolyBaseX + BasePosX*3*0.5*(1-MatterScale),y = PolyBaseY + FontSize*(1-MatterScale)}, {x = PolyBaseX,y = PolyBaseY + FontSize*(1-MatterScale)}, } surface.DrawPoly( TriAngle ) surface.DrawRect( PolyBaseX, PolyBaseY + FontSize * ( 1 - MatterScale), BasePosX*1.5 , FontSize*MatterScale ) surface.SetDrawColor( SecondaryColor ) surface.DrawRect( BasePosX + BasePosX*3*math.Clamp(ViewDistance/(BaseRange),0,1), BasePosY + FontSize*PosNumber, 2, FontSize ) local DamageScale = math.min( (2) - (ViewDistance/WeaponStats.range),1) draw.SimpleText(math.Round(math.Clamp(DamageScale * FullDamage,FullDamage * MatterScale,FullDamage),2) .. " Damage", "DermaDefault", BasePosX + BasePosX*3*math.Clamp(ViewDistance/(BaseRange),0,1),BasePosY + FontSize*PosNumber + FontSize,TextColor,TEXT_ALIGN_CENTER,TEXT_ALIGN_TOP) surface.SetDrawColor( PrimaryColor ) end end function SWEP:DrawCustomCrosshair(x,y,Cone,length,width,r,g,b,a) -- Client local XRound = math.floor(x/2) local YRound = math.floor(y/2) local WRound = math.floor(width/2) local LRound = math.floor(length/2) if BurgerBase_ContextMenuIsOpen then XRound, YRound = self:ClientCursorClamp() end if self.CrosshairOverrideMat then surface.SetDrawColor(Color(255,255,255,255)) surface.SetMaterial(self.CrosshairOverrideMat) surface.DrawTexturedRectRotated(XRound,YRound,self.CrosshairOverrideSize,self.CrosshairOverrideSize,0) else local SizeOffset = BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_offset",true):GetFloat() local FinalCone = math.floor( math.Max(Cone,WRound*2,LRound/2) + SizeOffset ) local CrosshairShadow = BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_shadow",true):GetFloat() local CrosshairStyle = BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_style",true):GetFloat() local CrosshairDot = BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_dot",true):GetFloat() if !self:GetZoomed() or self.EnableIronCross or ( BURGERBASE:CONVARS_GetStoredConvar("cl_burgerbase_crosshair_neversights",true):GetFloat() == 1 and not self.HasScope) then if WRound == 0 then if CrosshairStyle >= 2 and CrosshairStyle <= 5 then local Offset = 0 if CrosshairStyle == 4 then Offset = LRound*2 elseif CrosshairStyle == 3 then Offset = LRound else Offset = 0 end if CrosshairShadow >= 1 then surface.DrawCircle(x/2,y/2, FinalCone + Offset - 1, Color(0,0,0,a)) surface.DrawCircle(x/2,y/2, FinalCone + Offset + 1, Color(0,0,0,a)) end end if CrosshairStyle >= 1 and CrosshairStyle <= 4 then if CrosshairShadow >= 1 then local RealLength = LRound*2 -- Start of Shadow Stuff local x1 = XRound + FinalCone + RealLength local x2 = XRound - FinalCone - RealLength local y3 = YRound + FinalCone + RealLength local y4 = YRound - FinalCone - RealLength local Offset = 1 surface.SetDrawColor(Color(0,0,0,a)) --Right surface.DrawLine(x1 - RealLength,YRound - Offset,x1 + Offset*2,YRound - Offset) surface.DrawLine(x1 - RealLength,YRound + Offset,x1 + Offset*2,YRound + Offset) --Left surface.DrawLine(x2 + RealLength,YRound - Offset,x2 - Offset*2,YRound - Offset) surface.DrawLine(x2 + RealLength,YRound + Offset,x2 - Offset*2,YRound + Offset) --Bottom surface.DrawLine(XRound - Offset,y3 - RealLength,XRound - Offset,y3 + Offset*2) surface.DrawLine(XRound + Offset,y3 - RealLength,XRound + Offset,y3 + Offset*2) --Top surface.DrawLine(XRound - Offset,y4 + RealLength,XRound - Offset,y4 - Offset*2) surface.DrawLine(XRound + Offset,y4 + RealLength,XRound + Offset,y4 - Offset*2) -- End of Shadow Stuff end -- Start of Normal Stuff if width > 1 then local x1 = XRound - WRound local x2 = XRound - WRound local y3 = YRound - WRound local y4 = YRound - WRound local y1 = YRound + math.max(FinalCone,0) local y2 = YRound - (LRound*2) - math.max(FinalCone,0) local x3 = XRound + math.max(FinalCone,0) local x4 = XRound - (LRound*2) - math.max(FinalCone,0) surface.SetDrawColor(r,g,b,a) surface.DrawRect( x1, y1, WRound*2, LRound*2 ) surface.DrawRect( x2, y2, WRound*2, LRound*2 ) surface.DrawRect( x3, y3, LRound*2, WRound*2 ) surface.DrawRect( x4, y4, LRound*2, WRound*2 ) else local x1 = XRound + FinalCone + LRound*2 local x2 = XRound - FinalCone - LRound*2 local y3 = YRound + FinalCone + LRound*2 local y4 = YRound - FinalCone - LRound*2 surface.SetDrawColor(r,g,b,a) surface.DrawLine( x1, YRound, XRound+FinalCone, YRound ) surface.DrawLine( x2, YRound, XRound-FinalCone, YRound ) surface.DrawLine( XRound, y3, XRound, YRound+FinalCone ) surface.DrawLine( XRound, y4, XRound, YRound-FinalCone ) end -- End of Normal Stuff end if CrosshairDot >= 1 then local Max = math.max(1,width) if CrosshairShadow >= 1 then if width <= 1 then surface.SetDrawColor(Color(0,0,0,a)) surface.DrawRect( XRound - WRound - 1, YRound - WRound - 1 , Max + 2, Max + 2 ) end end -- Start of Normal Stuff surface.SetDrawColor(r,g,b,a) surface.DrawRect( XRound - WRound, YRound - WRound , Max, Max ) end if CrosshairStyle >= 2 and CrosshairStyle <= 5 then local Offset = 0 if CrosshairStyle == 4 then Offset = LRound*2 elseif CrosshairStyle == 3 then Offset = LRound else Offset = 0 end -- Start of Normal Stuff surface.DrawCircle(XRound,YRound, FinalCone + Offset, Color(r,g,b,a)) -- End of Normal Stuff end end end end end function SWEP:DrawSpecial(Cone) -- Client end function SWEP:DrawCustomScope(x,y,Cone,r,g,b,a) -- Client local space = 1 local PositionOffsetX = 0 local PositionOffsetY = 0 if BurgerBase_ContextMenuIsOpen then PositionOffsetX, PositionOffsetY = self:ClientCursorClamp() PositionOffsetX = PositionOffsetX - x/2 PositionOffsetY = PositionOffsetY - y/2 end --[[ local XSub = 100*FrameTime() local YSub = 100*FrameTime() if self.DynamicScopeDesiredOffsetX > 0 and self.DynamicScopeDesiredOffsetX - XSub > 0 then self.DynamicScopeDesiredOffsetX = self.DynamicScopeDesiredOffsetX - XSub elseif self.DynamicScopeDesiredOffsetX < 0 and self.DynamicScopeDesiredOffsetX - XSub < 0 then self.DynamicScopeDesiredOffsetX = self.DynamicScopeDesiredOffsetX + XSub else self.DynamicScopeDesiredOffsetX = 0 end if self.DynamicScopeDesiredOffsetY > 0 and self.DynamicScopeDesiredOffsetY - YSub > 0 then self.DynamicScopeDesiredOffsetY = self.DynamicScopeDesiredOffsetY - YSub elseif self.DynamicScopeDesiredOffsetY < 0 and self.DynamicScopeDesiredOffsetY - YSub < 0 then self.DynamicScopeDesiredOffsetY = self.DynamicScopeDesiredOffsetY + YSub else self.DynamicScopeDesiredOffsetY = 0 end self.DynamicScopeOffsetX = self.DynamicScopeOffsetX - (self.DynamicScopeOffsetX - self.DynamicScopeDesiredOffsetX)*FrameTime() self.DynamicScopeOffsetY = self.DynamicScopeOffsetY - (self.DynamicScopeOffsetY - self.DynamicScopeDesiredOffsetY)*FrameTime() PositionOffsetX = PositionOffsetX + self.DynamicScopeOffsetX PositionOffsetY = PositionOffsetY + self.DynamicScopeOffsetY --]] --[[ local MoveVel = self:GetMovementVelocity() if MoveVel ~= 0 then self.ScopeMoveTime = self.ScopeMoveTime + 1*math.pi*FrameTime() self.ScopeMoveTimeStored = math.sin(self.ScopeMoveTime)*50 else if self.ScopeMoveTimeStored > 0 then self.ScopeMoveTimeStored = math.Clamp(self.ScopeMoveTimeStored - FrameTime(),0,1) elseif self.ScopeMoveTimeStored < 0 then self.ScopeMoveTimeStored = math.Clamp(self.ScopeMoveTimeStored + FrameTime(),-1,0) else self.ScopeMoveTimeStored = 0 end end PositionOffsetX = PositionOffsetX + self.ScopeMoveTimeStored --]] --[[ local Size = math.Clamp(Cone,3,x/2*0.33)/2 local OffsetX = math.sin(CurTime())*Size local OffsetY = math.cos(CurTime())*Size self.DynamicScopeOffsetX = self.DynamicScopeOffsetX - (self.DynamicScopeOffsetX - OffsetX)*FrameTime()*10 self.DynamicScopeOffsetY = self.DynamicScopeOffsetY - (self.DynamicScopeOffsetY - OffsetY)*FrameTime()*10 PositionOffsetX = PositionOffsetX + self.DynamicScopeOffsetX PositionOffsetY = PositionOffsetY + self.DynamicScopeOffsetY --]] if self.ColorOverlay.a > 0 then surface.SetDrawColor(self.ColorOverlay) surface.DrawRect(0-x/2 + PositionOffsetX, 0-y/2 + PositionOffsetY, x*2, y*2 ) end if self.CustomScope == nil then if self.EnableDefaultScope then surface.SetDrawColor(Color(0,0,0)) surface.SetMaterial(Material("gui/sniper_corner")) --[[ surface.DrawTexturedRectRotated(x/2 - y/4 + PositionOffsetX,y/2 - y/4 + PositionOffsetY,y/2 + space,y/2 + space,0-180-180) surface.DrawTexturedRectRotated(x/2 - y/4 + PositionOffsetX,y/2 + y/4 + PositionOffsetY,y/2 + space,y/2 + space,90-180-180) surface.DrawTexturedRectRotated(x/2 + y/4 + PositionOffsetX,y/2 + y/4 + PositionOffsetY,y/2 + space,y/2 + space,180-180-180) surface.DrawTexturedRectRotated(x/2 + y/4 + PositionOffsetX,y/2 - y/4 + PositionOffsetY,y/2 + space,y/2 + space,270-180-180) --]] local CenterX = x/2 local ScopeSize = y local ScopeSegmentSize = ScopeSize/2 surface.DrawTexturedRectRotated(CenterX - ScopeSegmentSize/2 + PositionOffsetX,ScopeSegmentSize - ScopeSegmentSize/2 + PositionOffsetY,ScopeSegmentSize + space,ScopeSegmentSize + space,0-180-180) surface.DrawTexturedRectRotated(CenterX - ScopeSegmentSize/2 + PositionOffsetX,ScopeSegmentSize + ScopeSegmentSize/2 + PositionOffsetY,ScopeSegmentSize + space,ScopeSegmentSize + space,90-180-180) surface.DrawTexturedRectRotated(CenterX + ScopeSegmentSize/2 + PositionOffsetX,ScopeSegmentSize + ScopeSegmentSize/2 + PositionOffsetY,ScopeSegmentSize + space,ScopeSegmentSize + space,180-180-180) surface.DrawTexturedRectRotated(CenterX + ScopeSegmentSize/2 + PositionOffsetX,ScopeSegmentSize - ScopeSegmentSize/2 + PositionOffsetY,ScopeSegmentSize + space,ScopeSegmentSize + space,270-180-180) end if self.ZoomAmount > 6 then surface.SetDrawColor(Color(0,0,0)) surface.DrawLine(x/2 + PositionOffsetX,0 + PositionOffsetY,x/2 + PositionOffsetX,y + PositionOffsetY) surface.DrawLine(0 + PositionOffsetX,y/2 + PositionOffsetY,x + PositionOffsetX,y/2 + PositionOffsetY) else if !self.EnableIronCross then surface.DrawCircle( x/2 + PositionOffsetX, y/2 + PositionOffsetY, 1 , Color(r,g,b,a) ) end end else local Size = y if self.CustomScopeSOverride then Size = self.CustomScopeSOverride end surface.SetDrawColor(self.CustomScopeCOverride) surface.SetMaterial(self.CustomScope) surface.DrawTexturedRectRotated(x/2 + PositionOffsetX,y/2 + PositionOffsetY,Size*self.CustomScopeSizeMul,Size*self.CustomScopeSizeMul,0) if self.EnableDefaultScope then surface.SetDrawColor(Color(0,0,0,255)) surface.SetMaterial(Material("vgui/scope_lens")) surface.DrawTexturedRectRotated(x/2 + PositionOffsetX,y/2 + PositionOffsetY,y,y,0) end end if !self.EnableIronCross then local Size = math.Clamp(Cone,3,x/2*0.33) if Size > 6 then surface.DrawCircle( x/2 + PositionOffsetX, y/2 + PositionOffsetY, Size , Color(r,g,b,a) ) end end if self.EnableDefaultScope then surface.SetDrawColor(Color(0,0,0)) local CenterX = x/2 local ScopeSize = y local ScopeSegmentSize = ScopeSize/2 surface.DrawRect( 0 + PositionOffsetX, 0 + PositionOffsetY, CenterX - ScopeSegmentSize, ScopeSize ) -- Left surface.DrawRect( CenterX + ScopeSegmentSize + PositionOffsetX, 0 + PositionOffsetY, CenterX - ScopeSegmentSize, ScopeSize ) -- Right end surface.SetDrawColor(Color(0,0,0)) surface.DrawRect( x + PositionOffsetX, 0 + PositionOffsetY, x, y) -- Right surface.DrawRect(-x + PositionOffsetX, 0 + PositionOffsetY, x, y) -- Left surface.DrawRect( -x + PositionOffsetX, y + PositionOffsetY, x*3, y) -- Bottom surface.DrawRect( -x + PositionOffsetX, -y + PositionOffsetY, x*3, y) -- Top end function SWEP:ClientCursorClamp() -- Client local x,y = input.GetCursorPos() x = math.Clamp(x,0,ScrW()) y = math.Clamp(y,0,ScrH()) return x,y end function SWEP:HUDShouldDraw( element ) -- Client if self:GetZoomed() and element == "CHudWeaponSelection" then return false end return true end function SWEP:PrintWeaponInfo( x, y, alpha ) -- Client end function SWEP:DrawWorldModel() -- Client self:SCK_DrawWorldModel() end function SWEP:ViewModelDrawn() -- Client self:SCK_ViewModelDrawn() end function SWEP:SCK_Initialize() -- Client // other initialize code goes here if CLIENT then // Create a new table for every weapon instance self.VElements = table.FullCopy( self.VElements ) self.WElements = table.FullCopy( self.WElements ) self.ViewModelBoneMods = table.FullCopy( self.ViewModelBoneMods ) self:SCK_CreateModels(self.VElements) // create viewmodels self:SCK_CreateModels(self.WElements) // create worldmodels // init view model bone build function if IsValid(self.Owner) then local vm = self.Owner:GetViewModel() if IsValid(vm) then self:SCK_ResetBonePositions(vm) // Init viewmodel visibility if (self.ShowViewModel == nil or self.ShowViewModel) then vm:SetColor(Color(255,255,255,255)) else // we set the alpha to 1 instead of 0 because else ViewModelDrawn stops being called vm:SetColor(Color(255,255,255,1)) // ^ stopped working in GMod 13 because you have to do Entity:SetRenderMode(1) for translucency to kick in // however for some reason the view model resets to render mode 0 every frame so we just apply a debug material to prevent it from drawing vm:SetMaterial("Debug/hsv") end end end end end function SWEP:SCK_Holster() -- Client if CLIENT and IsValid(self.Owner) then local vm = self.Owner:GetViewModel() if IsValid(vm) then self:SCK_ResetBonePositions(vm) end end end SWEP.vRenderOrder = nil function SWEP:SCK_ViewModelDrawn() -- Client local vm = self.Owner:GetViewModel() if !IsValid(vm) then return end if (!self.VElements) then return end self:SCK_UpdateBonePositions(vm) if (!self.vRenderOrder) then // we build a render order because sprites need to be drawn after models self.vRenderOrder = {} for k, v in pairs( self.VElements ) do if (v.type == "Model") then table.insert(self.vRenderOrder, 1, k) elseif (v.type == "Sprite" or v.type == "Quad") then table.insert(self.vRenderOrder, k) end end end for k, name in ipairs( self.vRenderOrder ) do local v = self.VElements[name] if (!v) then self.vRenderOrder = nil break end if (v.hide) then continue end local model = v.modelEnt local sprite = v.spriteMaterial if (!v.bone) then continue end local pos, ang = self:SCK_GetBoneOrientation( self.VElements, v, vm ) if (!pos) then continue end if (v.type == "Model" and IsValid(model)) then model:SetPos(pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ) ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) model:SetAngles(ang) //model:SetModelScale(v.size) local matrix = Matrix() matrix:Scale(v.size) model:EnableMatrix( "RenderMultiply", matrix ) if (v.material == "") then model:SetMaterial("") elseif (model:GetMaterial() != v.material) then model:SetMaterial( v.material ) end if (v.skin and v.skin != model:GetSkin()) then model:SetSkin(v.skin) end if (v.bodygroup) then for k, v in pairs( v.bodygroup ) do if (model:GetBodygroup(k) != v) then model:SetBodygroup(k, v) end end end if (v.surpresslightning) then render.SuppressEngineLighting(true) end render.SetColorModulation(v.color.r/255, v.color.g/255, v.color.b/255) render.SetBlend(v.color.a/255) model:DrawModel() render.SetBlend(1) render.SetColorModulation(1, 1, 1) if (v.surpresslightning) then render.SuppressEngineLighting(false) end elseif (v.type == "Sprite" and sprite) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z render.SetMaterial(sprite) render.DrawSprite(drawpos, v.size.x, v.size.y, v.color) elseif (v.type == "Quad" and v.draw_func) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) cam.Start3D2D(drawpos, ang, v.size) v.draw_func( self ) cam.End3D2D() end end end function SWEP:SCK_OnRemove() -- Client self:SCK_Holster() end SWEP.wRenderOrder = nil function SWEP:SCK_DrawWorldModel() if (self.ShowWorldModel == nil or self.ShowWorldModel) then self:DrawModel() end if (!self.WElements) then return end if (!self.wRenderOrder) then self.wRenderOrder = {} for k, v in pairs( self.WElements ) do if (v.type == "Model") then table.insert(self.wRenderOrder, 1, k) elseif (v.type == "Sprite" or v.type == "Quad") then table.insert(self.wRenderOrder, k) end end end if (IsValid(self.Owner)) then bone_ent = self.Owner else // when the weapon is dropped bone_ent = self end for k, name in pairs( self.wRenderOrder ) do local v = self.WElements[name] if (!v) then self.wRenderOrder = nil break end if (v.hide) then continue end local pos, ang if (v.bone) then pos, ang = self:SCK_GetBoneOrientation( self.WElements, v, bone_ent ) else pos, ang = self:SCK_GetBoneOrientation( self.WElements, v, bone_ent, "ValveBiped.Bip01_R_Hand" ) end if (!pos) then continue end local model = v.modelEnt local sprite = v.spriteMaterial if (v.type == "Model" and IsValid(model)) then model:SetPos(pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ) ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) model:SetAngles(ang) //model:SetModelScale(v.size) local matrix = Matrix() matrix:Scale(v.size) model:EnableMatrix( "RenderMultiply", matrix ) if (v.material == "") then model:SetMaterial("") elseif (model:GetMaterial() != v.material) then model:SetMaterial( v.material ) end if (v.skin and v.skin != model:GetSkin()) then model:SetSkin(v.skin) end if (v.bodygroup) then for k, v in pairs( v.bodygroup ) do if (model:GetBodygroup(k) != v) then model:SetBodygroup(k, v) end end end if (v.surpresslightning) then render.SuppressEngineLighting(true) end render.SetColorModulation(v.color.r/255, v.color.g/255, v.color.b/255) render.SetBlend(v.color.a/255) model:DrawModel() render.SetBlend(1) render.SetColorModulation(1, 1, 1) if (v.surpresslightning) then render.SuppressEngineLighting(false) end elseif (v.type == "Sprite" and sprite) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z render.SetMaterial(sprite) render.DrawSprite(drawpos, v.size.x, v.size.y, v.color) elseif (v.type == "Quad" and v.draw_func) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) cam.Start3D2D(drawpos, ang, v.size) v.draw_func( self ) cam.End3D2D() end end end function SWEP:SCK_GetBoneOrientation( basetab, tab, ent, bone_override ) local bone, pos, ang if (tab.rel and tab.rel != "") then local v = basetab[tab.rel] if (!v) then return end // Technically, if there exists an element with the same name as a bone // you can get in an infinite loop. Let's just hope nobody's that stupid. pos, ang = self:SCK_GetBoneOrientation( basetab, v, ent ) if (!pos) then return end pos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) else bone = ent:LookupBone(bone_override or tab.bone) if (!bone) then return end pos, ang = Vector(0,0,0), Angle(0,0,0) local m = ent:GetBoneMatrix(bone) if (m) then pos, ang = m:GetTranslation(), m:GetAngles() end if (IsValid(self.Owner) and self.Owner:IsPlayer() and ent == self.Owner:GetViewModel() and self.ViewModelFlip) then ang.r = -ang.r // Fixes mirrored models end end return pos, ang end function SWEP:SCK_CreateModels( tab ) if (!tab) then return end // Create the clientside models here because Garry says we can't do it in the render hook for k, v in pairs( tab ) do if (v.type == "Model" and v.model and v.model != "" and (!IsValid(v.modelEnt) or v.createdModel != v.model) and string.find(v.model, ".mdl") and file.Exists (v.model, "GAME") ) then v.modelEnt = ClientsideModel(v.model, RENDER_GROUP_VIEW_MODEL_OPAQUE) if (IsValid(v.modelEnt)) then v.modelEnt:SetPos(self:GetPos()) v.modelEnt:SetAngles(self:GetAngles()) v.modelEnt:SetParent(self) v.modelEnt:SetNoDraw(true) v.createdModel = v.model else v.modelEnt = nil end elseif (v.type == "Sprite" and v.sprite and v.sprite != "" and (!v.spriteMaterial or v.createdSprite != v.sprite) and file.Exists ("materials/"..v.sprite..".vmt", "GAME")) then local name = v.sprite.."-" local params = { ["$basetexture"] = v.sprite } // make sure we create a unique name based on the selected options local tocheck = { "nocull", "additive", "vertexalpha", "vertexcolor", "ignorez" } for i, j in pairs( tocheck ) do if (v[j]) then params["$"..j] = 1 name = name.."1" else name = name.."0" end end v.createdSprite = v.sprite v.spriteMaterial = CreateMaterial(name,"UnlitGeneric",params) end end end local allbones local hasGarryFixedBoneScalingYet = false function SWEP:SCK_UpdateBonePositions(vm) if self.ViewModelBoneMods then if (!vm:GetBoneCount()) then return end // !! WORKAROUND !! // // We need to check all model names :/ local loopthrough = self.ViewModelBoneMods if (!hasGarryFixedBoneScalingYet) then allbones = {} for i=0, vm:GetBoneCount() do local bonename = vm:GetBoneName(i) if (self.ViewModelBoneMods[bonename]) then allbones[bonename] = self.ViewModelBoneMods[bonename] else allbones[bonename] = { scale = Vector(1,1,1), pos = Vector(0,0,0), angle = Angle(0,0,0) } end end loopthrough = allbones end // !! ----------- !! // for k, v in pairs( loopthrough ) do local bone = vm:LookupBone(k) if (!bone) then continue end // !! WORKAROUND !! // local s = Vector(v.scale.x,v.scale.y,v.scale.z) local p = Vector(v.pos.x,v.pos.y,v.pos.z) local ms = Vector(1,1,1) if (!hasGarryFixedBoneScalingYet) then local cur = vm:GetBoneParent(bone) while(cur >= 0) do local pscale = loopthrough[vm:GetBoneName(cur)].scale ms = ms * pscale cur = vm:GetBoneParent(cur) end end s = s * ms // !! ----------- !! // if vm:GetManipulateBoneScale(bone) != s then vm:ManipulateBoneScale( bone, s ) end if vm:GetManipulateBoneAngles(bone) != v.angle then vm:ManipulateBoneAngles( bone, v.angle ) end if vm:GetManipulateBonePosition(bone) != p then vm:ManipulateBonePosition( bone, p ) end end else self:SCK_ResetBonePositions(vm) end end function SWEP:SCK_ResetBonePositions(vm) if (!vm:GetBoneCount()) then return end for i=0, vm:GetBoneCount() do vm:ManipulateBoneScale( i, Vector(1, 1, 1) ) vm:ManipulateBoneAngles( i, Angle(0, 0, 0) ) vm:ManipulateBonePosition( i, Vector(0, 0, 0) ) end end /************************** Global utility code **************************/ // Fully copies the table, meaning all tables inside this table are copied too and so on (normal table.Copy copies only their reference). // Does not copy entities of course, only copies their reference. // WARNING: do not use on tables that contain themselves somewhere down the line or you'll get an infinite loop function table.FullCopy( tab ) if (!tab) then return nil end local res = {} for k, v in pairs( tab ) do if (type(v) == "table") then res[k] = table.FullCopy(v) // recursion ho! elseif (type(v) == "Vector") then res[k] = Vector(v.x, v.y, v.z) elseif (type(v) == "Angle") then res[k] = Angle(v.p, v.y, v.r) else res[k] = v end end return res end<file_sep>/lua/weapons/weapon_burger_cs_ump.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_ump", "csd", "q", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/ump45") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "UMP45" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 1700 SWEP.CSSMoveSpeed = 250 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 2 SWEP.SlotPos = 1 SWEP.Description = "Powerful SMG that's excels at medium range." SWEP.ViewModel = "models/weapons/cstrike/c_smg_ump45.mdl" SWEP.WorldModel = "models/weapons/w_smg_ump45.mdl" SWEP.VModelFlip = false SWEP.HoldType = "smg" SWEP.Primary.Damage = 30 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("Weapon_UMP45.Single") SWEP.Primary.Cone = 0.004 SWEP.Primary.ClipSize = 25 SWEP.Primary.SpareClip = 100 SWEP.Primary.Delay = 0.09 --1/(666/60) SWEP.Primary.Ammo = "bb_45acp" SWEP.Primary.Automatic = true SWEP.RecoilMul = 2 SWEP.SideRecoilMul = 0.25 SWEP.RecoilSpeedMul = 1.25 SWEP.MoveConeMul = 0.5 SWEP.HeatMul = 0.75 SWEP.CoolMul = 1 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 0.5 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = true SWEP.CanShootWhileSprinting = true SWEP.DamageFalloff = 1500 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = false SWEP.IronSightTime = 0.25 SWEP.ZoomTime = 0.5 SWEP.IronSightsPos = Vector(-7.401, 0, 2.2) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronRunPos = Vector(-2.01, -5, 0.602) SWEP.IronRunAng = Vector(-5, 15, -7.739) SWEP.IronMeleePos = Vector(-5.801, -13.468, -20) SWEP.IronMeleeAng = Vector(70, 0, 0) <file_sep>/lua/burgerbase/core/shared/other/core_physicalbullets.lua BURGERBASE_RegisteredBullets = {} if not BURGERBASE_RegisteredBulletTemplates then BURGERBASE_RegisteredBulletTemplates = {} end function BURGERBASE_RegisterProjectile(id,DataTable) BURGERBASE_RegisteredBulletTemplates[id] = DataTable end function BUREGRBASE_HOOK_Tick_Bullets() for num,data in pairs(BURGERBASE_RegisteredBullets) do data = table.Copy(data) data.pos = data.pos + ( data.direction * engine.TickInterval() ) if data.target and IsValid(data.target) then local COM = data.target:GetPos() + data.target:OBBCenter() data.direction = ((COM - data.pos):GetNormal()*data.direction:Length()) - ( data.resistance * engine.TickInterval() ) else data.direction = data.direction - ( data.resistance * engine.TickInterval() ) end local TraceData = {} local HullSize = data.hullsize or 1 if SERVER then HullSize = HullSize*1.125 end TraceData.start = data.pos - ( data.direction * engine.TickInterval() ) TraceData.endpos = data.pos TraceData.mask = MASK_SHOT TraceData.filter = function(ent) return (ent ~= data.owner and ent ~= data.weapon) end local TraceResult = {} local TraceResultHull = {} TraceResult = util.TraceLine(TraceData) if data.usehull then TraceData.maxs = Vector(HullSize,HullSize,HullSize) TraceData.mins = Vector(-HullSize,-HullSize,-HullSize) TraceResultHull = util.TraceHull(TraceData) end if TraceResult.Hit then if not data.hitfunction(data,TraceResult) then data.diefunction(data) data = nil end elseif TraceResultHull.Hit and TraceResultHull.Entity and TraceResultHull.Entity:Health() > 0 then if not data.hitfunction(data,TraceResultHull) then data.diefunction(data) data = nil end elseif data.dietime <= CurTime() then data.diefunction(data) data = nil end if data == nil then table.remove(BURGERBASE_RegisteredBullets,num) else data.tickfunction(data) BURGERBASE_RegisteredBullets[num] = data end end end hook.Add("Tick","BUREGRBASE_HOOK_Tick_Bullets",BUREGRBASE_HOOK_Tick_Bullets) function BURGERBASE_HOOK_PostCleanupMap_Bullets() BURGERBASE_RegisteredBullets = {} end hook.Add("PostCleanupMap","BURGERBASE_HOOK_PostCleanupMap_Bullets",BURGERBASE_HOOK_PostCleanupMap_Bullets) local DefaultMaterial = Material("sprites/physg_glow1") function BURGERBASE_FUNC_ShootProjectile(Attacker,Inflictor,Damage,Shots,Cone,Source,Direction,Target,SendToServer) if IsFirstTimePredicted() then local Offset = Vector(0,0,0) if CLIENT then if IsValid(Inflictor) and IsValid(Attacker) and Inflictor:IsWeapon() and Attacker:IsPlayer() then if Inflictor.UseMuzzle then local HitPos = Attacker:GetEyeTrace().HitPos local DirectionOffset = Direction - Attacker:GetAimVector() local ViewModel = Attacker:GetViewModel() local MuzzleData = ViewModel:GetAttachment( 1 ) if MuzzleData then Offset = Source - MuzzleData.Pos Source = MuzzleData.Pos Direction = (HitPos - Source):GetNormalized() + DirectionOffset end end end end Direction:Rotate(AngleRand()*Cone) local datatable = {} datatable.weapon = Inflictor datatable.owner = Attacker datatable.pos = Source datatable.offset = Offset datatable.direction = Direction datatable.target = Target datatable.damage = Damage datatable.usehull = true datatable.hullsize = 8 datatable.resistance = Vector(0,0,0) datatable.dietime = CurTime() + 30 datatable.special = nil datatable.id = "css_bullet" datatable = Inflictor:ModProjectileTable(datatable) datatable.sendtoserver = SendToServer BURGERBASE_FUNC_AddBullet(datatable) end end function BURGERBASE_FUNC_AddBullet(datatable) local NewTable = {} NewTable.weapon = datatable.weapon NewTable.owner = datatable.owner NewTable.pos = datatable.pos NewTable.offset = datatable.offset NewTable.direction = datatable.direction NewTable.damage = datatable.damage or 10 NewTable.hullsize = datatable.hullsize or 1 NewTable.usehull = datatable.usehull or false NewTable.target = datatable.target or nil NewTable.resistance = datatable.resistance or Vector(0,0,0) NewTable.dietime = datatable.dietime or (CurTime() + 10) NewTable.id = datatable.id or "crossbow_bolt" NewTable.sendtoserver = datatable.sendtoserver if SERVER then --print("Sending to all Clients...") net.Start("BURGERBASE_SendBulletToClient") net.WriteTable(NewTable) net.WriteFloat(CurTime()) net.Broadcast() end if CLIENT and NewTable.sendtoserver == true and NewTable.weapon:IsWeapon() and LocalPlayer() == NewTable.weapon.Owner then --print("Sending to Server...") net.Start("BURGERBASE_SendBulletToServer") net.WriteTable(NewTable) net.WriteFloat(CurTime()) net.SendToServer() end local RegisteredTable = BURGERBASE_RegisteredBulletTemplates[NewTable.id] or {} NewTable.drawfunction = RegisteredTable.drawfunction or function(data) end NewTable.diefunction = RegisteredTable.diefunction or function(data) end NewTable.tickfunction = RegisteredTable.tickfunction or function(data) end NewTable.hitfunction = RegisteredTable.hitfunction or function(data,traceresult) end table.Add(BURGERBASE_RegisteredBullets,{NewTable}) end if SERVER then util.AddNetworkString( "BURGERBASE_SendBulletToClient" ) util.AddNetworkString( "BURGERBASE_SendBulletToServer" ) net.Receive("BURGERBASE_SendBulletToServer", function(len,ply) local DataTable = net.ReadTable() local Time = net.ReadFloat() local id = DataTable.id local Difference = CurTime() - Time DataTable.sendtoserver = false --DataTable.pos = DataTable.pos + DataTable.direction*Difference table.Add(DataTable,BURGERBASE_RegisteredBulletTemplates[id]) BURGERBASE_FUNC_AddBullet(DataTable) end) end local BulletMat = Material( "sprites/physg_glow1" ) if CLIENT then net.Receive("BURGERBASE_SendBulletToClient", function(len) local DataTable = net.ReadTable() local id = DataTable.id local Time = net.ReadFloat() local Difference = CurTime() - Time DataTable.sendtoserver = false if !(DataTable.weapon:IsWeapon() and LocalPlayer() == DataTable.weapon.Owner) then table.Add(DataTable,BURGERBASE_RegisteredBulletTemplates[id]) BURGERBASE_FUNC_AddBullet(DataTable) end end) function BUREGRBASE_HOOK_3D_Bullets() for num,data in pairs(BURGERBASE_RegisteredBullets) do data.drawfunction(data) end end hook.Add("PreDrawEffects","BUREGRBASE_HOOK_3D_Bullets",BUREGRBASE_HOOK_3D_Bullets) end<file_sep>/lua/weapons/weapon_hl2_rpg.lua if CLIENT then killicon.AddFont( "ent_hl2_rocket", "HL2MPTypeDeath", "3", Color( 255, 80, 0, 255 ) ) killicon.AddFont( "weapon_hl2_rocket", "HL2MPTypeDeath", "3", Color( 255, 80, 0, 255 ) ) end SWEP.Category = "BurgerBase: Half Life 2" SWEP.PrintName = "RPG" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 3500 SWEP.CSSMoveSpeed = 100 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/c_rpg.mdl" SWEP.WorldModel = "models/weapons/w_rocket_launcher.mdl" SWEP.VModelFlip = false SWEP.HoldType = "rpg" game.AddAmmoType({name = "css_rocket"}) if CLIENT then language.Add("css_rocket_ammo","RPG") end SWEP.Primary.Damage = 200 SWEP.Primary.NumShots = 1 SWEP.Primary.Sound = Sound("weapons/rpg/rocketfire1.wav") SWEP.Primary.Cone = .00125 SWEP.Primary.ClipSize = -1 SWEP.Primary.SpareClip = 1 SWEP.Primary.Delay = 1/(30/60) SWEP.Primary.Ammo = "css_rocket" SWEP.Primary.Automatic = true SWEP.RecoilMul = 0.01 SWEP.SideRecoilMul = 0 SWEP.MoveConeMul = 0 SWEP.HeatMul = 0 SWEP.HasScope = true SWEP.ZoomAmount = 3 SWEP.HasCrosshair = true SWEP.HasCSSZoom = true SWEP.HasPumpAction = false SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = false SWEP.HasDryFire = false SWEP.HasIronSights = false SWEP.EnableIronCross = false SWEP.HasGoodSights = false SWEP.IronSightTime = 0.5 SWEP.IronSightsPos = Vector(0, 0, 0) SWEP.IronSightsAng = Vector(0, 0, 0) function SWEP:ShootBullet(Damage,Shots,Cone,Source,Direction,Source) self:ThrowObject("ent_hl2_rocket",10000) self:SendWeaponAnim(ACT_VM_RELOAD) end<file_sep>/lua/burgerbase/core/server/other/core_damage.lua function BURGERBASE_HOOK_ScalePlayerDamage(ply, hitgroup, dmginfo) local DamageScale,DamageOverride = BURGERBASE_FUNC_GetDamageScale(ply,hitgroup,dmginfo) if not DamageScale then dmginfo:SetDamage(DamageOverride) else dmginfo:ScaleDamage(DamageScale) end end function BURGERBASE_FUNC_GetDamageScale(ply,hitgroup,dmginfo) local Inflictor = dmginfo:GetInflictor() local DamageScale = 1 local Damage = nil if Inflictor ~= NULL and Inflictor ~= nil then if Inflictor:IsPlayer() then Weapon = Inflictor:GetActiveWeapon() end end if Weapon ~= NULL and Weapon ~= nil then if Weapon.FatalHeadshot and hitgroup == HITGROUP_HEAD then local Damage = math.max(dmginfo:GetDamage(),ply:Health()) return nil,Damage end end if BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damage_enable",false):GetBool() then if BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damage_sandboxfix",false):GetBool() then if ( hitgroup == HITGROUP_HEAD ) then DamageScale = DamageScale*0.5 elseif ( hitgroup == HITGROUP_LEFTARM || hitgroup == HITGROUP_RIGHTARM || hitgroup == HITGROUP_LEFTLEG || hitgroup == HITGROUP_RIGHTLEG || hitgroup == HITGROUP_GEAR ) then DamageScale = DamageScale*4 end end if hitgroup == HITGROUP_LEFTLEG || hitgroup == HITGROUP_RIGHTLEG then DamageScale = DamageScale * BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damage_legscale",false):GetFloat() elseif hitgroup == HITGROUP_LEFTARM || hitgroup == HITGROUP_RIGHTARM then DamageScale = DamageScale * BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damage_armscale",false):GetFloat() elseif hitgroup == HITGROUP_HEAD then DamageScale = DamageScale * BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damage_headscale",false):GetFloat() else DamageScale = DamageScale * BURGERBASE:CONVARS_GetStoredConvar("sv_burgerbase_damage_bodyscale",false):GetFloat() end end return DamageScale,Damage end hook.Add("ScalePlayerDamage","BURGERBASE_HOOK_ScalePlayerDamage",BURGERBASE_HOOK_ScalePlayerDamage) hook.Add("ScaleNPCDamage","BURGERBASE_HOOK_ScalePlayerDamage",BURGERBASE_HOOK_ScalePlayerDamage) if not BURGERBASE_StoredWeaponKills then BURGERBASE_StoredWeaponKills = {} end function BURGERBASE_HOOK_PlayerDeath_Tracker(victim,inflictor,attacker ) if inflictor == attacker and attacker:IsPlayer() and attacker:GetActiveWeapon() and attacker:GetActiveWeapon():IsValid() then inflictor = attacker:GetActiveWeapon() end --print(victim,inflictor,attacker) if victim:IsValid() and victim:IsPlayer() and attacker:IsValid() and attacker:IsPlayer() and inflictor:IsValid() and inflictor.BurgerBase == true then if not BURGERBASE_StoredWeaponKills[inflictor:GetClass()] then BURGERBASE_StoredWeaponKills[inflictor:GetClass()] = 1 else BURGERBASE_StoredWeaponKills[inflictor:GetClass()] = BURGERBASE_StoredWeaponKills[inflictor:GetClass()] + 1 end --print(inflictor:GetClass(),BURGERBASE_StoredWeaponKills[inflictor:GetClass()]) end end hook.Add("PlayerDeath","BURGERBASE_HOOK_PlayerDeath_Tracker",BURGERBASE_HOOK_PlayerDeath_Tracker) concommand.Add("nerfme2", function( ply, cmd, args, argStr) local Keys = table.GetKeys( BURGERBASE_StoredWeaponKills ) table.sort( Keys, function( a, b ) return BURGERBASE_StoredWeaponKills[a] < BURGERBASE_StoredWeaponKills[b] end) for i=1, #Keys do local k = Keys[i] local v = BURGERBASE_StoredWeaponKills[k] print("-------------------------") print("Weapon: ",k) print("Kills: ",v) end print("-------------------------") end) concommand.Add( "nerfme", function( ply,cmd,args,argStr ) local PlayerHealth = 100 local AllWeapons = weapons.GetList() local MyWeapons = {} for k,SWEP in pairs(AllWeapons) do if SWEP.Base == "weapon_burger_core_base" and (SWEP.WeaponType == "Primary" or SWEP.WeaponType == "Secondary") and SWEP.Spawnable then local ReturnTable = BURGERBASE_CalculateWeaponStats(ply,SWEP,true) local ID = SWEP.PrintName MyWeapons[ID] = {} MyWeapons[ID].Damage = ReturnTable.damage * ReturnTable.shots --MyWeapons[ID].Delay = ReturnTable.delay MyWeapons[ID].DPS = ReturnTable.dps MyWeapons[ID].KillTime = ReturnTable.killtime -- --[[ local PrintName = SWEP.PrintName local Damage = SWEP.Primary.NumShots * SWEP.Primary.Damage local Delay = math.Clamp(SWEP.Primary.Delay,FrameTime(),60) if !SWEP.Primary.Automatic and Delay < 0.1 then Delay = 0.1 end if SWEP.HasHL2Pump then Delay = Delay + 1 end local ClipSize = SWEP.Primary.ClipSize if ClipSize == -1 then ClipSize = 250 end local ClipDamage = Damage * ClipSize local DPS = math.min(ClipDamage,math.floor(( 1 / Delay) * Damage )) local KillTime = math.Round((math.ceil(PlayerHealth/Damage) - 1) * (Delay),2) MyWeapons[PrintName] = {} MyWeapons[PrintName].DPS = DPS MyWeapons[PrintName].KillTime = KillTime --]] end end local Keys = table.GetKeys( MyWeapons ) if argStr == "time" then table.sort( Keys, function( a, b ) if MyWeapons[a].KillTime == MyWeapons[b].KillTime then return a < b else return MyWeapons[a].KillTime > MyWeapons[b].KillTime end end ) else table.sort( Keys, function( a, b ) if MyWeapons[a].DPS == MyWeapons[b].DPS then return a < b else return MyWeapons[a].DPS < MyWeapons[b].DPS end end ) end for i=1, #Keys do local k = Keys[i] local v = MyWeapons[k] print("-------------------------") print("Weapon: ",k) print("Damage: ",v.Damage) print("DPS: ",v.DPS) print("KillTime: ",v.KillTime) end end ) <file_sep>/lua/weapons/weapon_burger_cs_m3.lua if CLIENT then killicon.AddFont( "weapon_burger_cs_m3", "csd", "k", Color( 255, 80, 0, 255 ) ) SWEP.WepSelectIcon = surface.GetTextureID("vgui/gfx/vgui/m3") end SWEP.Category = "BurgerBase: Counter-Strike" SWEP.PrintName = "M3 Super90" SWEP.Base = "weapon_burger_core_base" SWEP.WeaponType = "Primary" SWEP.Cost = 1700 SWEP.CSSMoveSpeed = 220 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Description = "Your run-of-the-mill pump action shotgun. Comes with slug ammo." SWEP.Slot = 2 SWEP.SlotPos = 1 SWEP.ViewModel = "models/weapons/cstrike/c_shot_m3super90.mdl" SWEP.WorldModel = "models/weapons/w_shot_m3super90.mdl" SWEP.VModelFlip = false SWEP.HoldType = "ar2" SWEP.Primary.Damage = 26*0.8 SWEP.Primary.NumShots = 9 SWEP.Primary.Sound = Sound("Weapon_M3.Single") SWEP.Primary.Cone = 0.03 SWEP.Primary.ClipSize = 8 SWEP.Primary.SpareClip = 32 SWEP.Primary.Delay = 0.88 --1/(68/60) SWEP.Primary.Ammo = "bb_12gauge" SWEP.Primary.Automatic = false SWEP.RecoilMul = 0.2 SWEP.SideRecoilMul = 0.25 SWEP.RecoilSpeedMul = 0.75 SWEP.MoveConeMul = 0.5 SWEP.HeatMul = 1.5 SWEP.CoolMul = 0.5 SWEP.CoolSpeedMul = 1 SWEP.HasScope = false SWEP.ZoomAmount = 0.25 SWEP.HasCrosshair = true SWEP.HasCSSZoom = false SWEP.HasPumpAction = true SWEP.HasBoltAction = false SWEP.HasBurstFire = false SWEP.HasSilencer = false SWEP.HasDoubleZoom = false SWEP.HasSideRecoil = true SWEP.HasDownRecoil = false SWEP.HasFirstShotAccurate = false SWEP.CanShootWhileSprinting = true SWEP.DamageFalloff = 300 SWEP.PenetrationLossScale = 0.5 SWEP.HasIronSights = true SWEP.EnableIronCross = true SWEP.HasGoodSights = false SWEP.IronSightTime = 0.5 SWEP.ZoomTime = 0.5 SWEP.IronRunPos = Vector(-2.01, 0.201, 0.602) SWEP.IronRunAng = Vector(-5, 15, -7.739) SWEP.IronSightsPos = Vector(-7.68, 0, 3.359) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.IronMeleePos = Vector(3.417, -10, -13.87) SWEP.IronMeleeAng = Vector(-9.146, 70, -70) SWEP.SpecialAmmo = {"bb_12gauge","bb_12gaugeslug"} function SWEP:SpecialGiveAmmo() self.Owner:GiveAmmo(12,"bb_12gaugeslug",false) end function SWEP:SpecialShots(shots) if self:GetPrimaryAmmo() == game.GetAmmoID("bb_12gaugeslug") then shots = 1 end return shots end function SWEP:SpecialDamage(damage) if self:GetPrimaryAmmo() == game.GetAmmoID("bb_12gaugeslug") then damage = 90 end return damage end function SWEP:SpecialFalloff(falloff) if self:GetPrimaryAmmo() == game.GetAmmoID("bb_12gaugeslug") then falloff = 1000 end return falloff end function SWEP:SpecialRecoil(recoil) if self:GetPrimaryAmmo() == game.GetAmmoID("bb_12gaugeslug") then recoil = recoil * 2 end return recoil end function SWEP:SpecialConePre(cone) if self:GetPrimaryAmmo() == game.GetAmmoID("bb_12gaugeslug") then cone = cone*0.25 end return cone end <file_sep>/lua/burgerbase/core/client/menus_core.lua BURGERBASE.ServerMenuConvars = {} BURGERBASE.ClientMenuConvars = {} function BURGERBASE:FUNC_MENU_GetBurgerBaseWeapons() local ReturnTable = {} for k,v in pairs(weapons.GetList()) do if v.Base == "weapon_burger_core_base" then table.Add(ReturnTable,{v.ClassName}) end end return ReturnTable end function BURGERBASE:FUNC_MENU_AddConVarSlider(convar,clientside,description,max,round) local RealmTable = nil if clientside then RealmTable = BURGERBASE.ClientMenuConvars else RealmTable = BURGERBASE.ServerMenuConvars end local TableCount = table.Count(RealmTable) RealmTable[TableCount] = { type = "DNumSlider", text = description, ConVar = BURGERBASE:CONVARS_GetStoredConvar(convar,clientside), min = 0, max = max, round = round, } end function BURGERBASE:FUNC_MENU_AddConVarCheckbox(convar,clientside,description,realm) local RealmTable = nil if clientside then RealmTable = BURGERBASE.ClientMenuConvars else RealmTable = BURGERBASE.ServerMenuConvars end local TableCount = table.Count(RealmTable) RealmTable[TableCount] = { type = "DCheckBoxLabel", text = description, ConVar = BURGERBASE:CONVARS_GetStoredConvar(convar,clientside), } end function BURGERBASE:FUNC_MENU_AddTitle(title,clientside) local RealmTable = nil if clientside then RealmTable = BURGERBASE.ClientMenuConvars else RealmTable = BURGERBASE.ServerMenuConvars end local TableCount = table.Count(RealmTable) RealmTable[TableCount] = { type = "Divider", } RealmTable[TableCount + 1] = { type = "DLabel", text = title, font = "DermaLarge", textcolor = Color(0,0,0,255) } end function BURGERBASE_FUNC_MENU_ServerMenu() if SERVER then return end local ply = LocalPlayer() local x = ScrW() local y = ScrH() local BaseList = BURGERBASE:CreateBaseFrame(x*0.05,x*0.05,x*0.4,y*1 - x*0.1) for num,data in pairs(BURGERBASE.ServerMenuConvars) do BURGERBASE:CreateElement(BaseList,data) end end if CLIENT then concommand.Add( "burgerbase_server", BURGERBASE_FUNC_MENU_ServerMenu) end function BURGERBASE_FUNC_MENU_ClientMenu() if SERVER then return end local ply = LocalPlayer() local x = ScrW() local y = ScrH() local BaseList = BURGERBASE:CreateBaseFrame(x*0.05,x*0.05,x*0.4,y*1 - x*0.1) for num,data in pairs(BURGERBASE.ClientMenuConvars) do BURGERBASE:CreateElement(BaseList,data) end end if CLIENT then concommand.Add( "burgerbase_client", BURGERBASE_FUNC_MENU_ClientMenu) end function BURGERBASE:CreateBaseFrame(x,y,w,h) local SpaceOffset = 10 local BaseFrame = vgui.Create("DFrame") BaseFrame:SetSize(w,h) BaseFrame:SetPos(x,y) BaseFrame:SetVisible( true ) BaseFrame:SetDraggable( false ) BaseFrame:ShowCloseButton( true ) BaseFrame:SetTitle(" ") BaseFrame:MakePopup() BaseFrame.Paint = function(self,w,h) draw.RoundedBoxEx( 4, 0, 0, w, h, Color( 255, 255, 255, 150 ), true,true,true,true ) end local BaseScroll = vgui.Create("DScrollPanel",BaseFrame) BaseScroll:StretchToParent(SpaceOffset,SpaceOffset + 40,SpaceOffset,SpaceOffset) BaseScroll:Center() local LW, LH = BaseScroll:GetSize() local BaseList = vgui.Create("DIconLayout",BaseScroll) BaseList:SetSize(LW - SpaceOffset*2 - 20,LH - SpaceOffset) -- 20 is for the scrollbars BaseList:SetPos(SpaceOffset,0) BaseList:SetSpaceX(0) BaseList:SetSpaceY(0) return BaseList end function BURGERBASE:CreateElement(BaseList,data) local LW, LH = BaseList:GetSize() local Tester = BaseList:Add("DPanel") Tester:SetSize(LW,200) function Tester:Paint(w,h) end local ElementType = data.type if ElementType == "Divider" then local Element = vgui.Create("DPanel",Tester) Element:SetSize(LW,50) function Element:Paint(w,h) draw.RoundedBox( 0, 0, h/2, w, 1, Color(0,0,0,255) ) end elseif ElementType == "DLabel" then local Element = vgui.Create(ElementType,Tester) Element:SetText(data.text) Element:SetFont(data.font) Element:SetTextColor(data.textcolor) Element:SizeToContents() elseif ElementType == "DCheckBoxLabel" then local Element = vgui.Create(ElementType,Tester) Element:SetText(data.text) Element:SetDark(true) Element:SetValue() Element:SizeToContents() Element:SetSize(LW,20) if data.ConVar:GetBool() then Element:SetChecked(true) end function Element:OnChange() local Value = 0 if self:GetChecked() then Value = 1 end RunConsoleCommand(data.ConVar:GetName(),tostring(Value)) end Element:SetTooltip( data.ConVar:GetHelpText() .. " Default: " .. data.ConVar:GetDefault() ) elseif ElementType == "DNumSlider" then local Element = vgui.Create(ElementType,Tester) Element:SetText(data.text) Element:SetDark(true) Element:SetMin( data.min ) Element:SetMax( data.max ) Element:SetSize(LW,20) Element:SetDecimals( data.round ) Element:SetValue(data.ConVar:GetFloat()) Element:UpdateNotches() function Element:OnValueChanged(newvalue) newvalue = math.Round(newvalue,self:GetDecimals()) self:SetValue(newvalue) RunConsoleCommand(data.ConVar:GetName(),tostring(newvalue)) end Element:SetTooltip( data.ConVar:GetHelpText() .. " Default: " .. data.ConVar:GetDefault() ) end Tester:SizeToChildren(false,true) end BURGERBASE:INIT_MassInclude("burgerbase/core/client/menus/","client",false)
df31e148d4d7059bca87cbb881c51dc3323b991c
[ "Lua" ]
53
Lua
BurgerLUA/burgerbaseweapons
723edbc47f8746f01e6cdcfd78e3517a88b35d86
fd9210dc0dc8cd78f66b24fdbf4a56836b180e0d
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Member; use App\Position; use App\Club; use App\Region; use App\User; use App\Exports\MemberExport; use Maatwebsite\Excel\Facades\Excel; use Illuminate\Support\Facades\Hash; use Maatwebsite\Excel\Concerns\FromQuery; use Maatwebsite\Excel\Concerns\Exportable; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { $dataPosition = Position::all(); $Club = Club::count(); $Region = Region::count(); $Member = Member::count(); $dataMember = Member::take(10)->get(); $dataClub = Club::take(10)->with('members')->get(); $dataRegion = Region::take(10)->with('members')->get(); return view('home', compact('dataClub','dataRegion','dataMember','Club', 'Region', 'Member')); } public function regions() { $dataPosition = Position::all(); $Club = Club::count(); $Region = Region::count(); $Member = Member::count(); $dataRegion = Region::with('members')->get(); return view('region', compact('dataRegion','Club', 'Region', 'Member')); } public function clubs() { $dataPosition = Position::all(); $Club = Club::count(); $Region = Region::count(); $Member = Member::count(); $dataClub = Club::with('members')->get(); return view('clubs', compact('dataClub','Club', 'Region', 'Member')); } public function about() { return("About"); } public function updateaccount(Request $req) { $data = User::find($req->id); $data->name = $req->name; $data->email = $req->email; $data->password = <PASSWORD>($req->password); $data->save(); return response()->json($data); } public function members(){ $dataPosition = Position::all(); $dataClub = Club::all(); $dataRegion = Region::all(); $dataMember = Member::latest()->paginate(50); return view('members',compact('dataMember','dataPosition', 'dataClub', 'dataRegion')); } public function deletemember(Request $req){ Member::find($req->id)->delete(); return response()->json(); } public function viewregions($regionname){ $dataPosition = Position::all(); $dataClub = Club::all(); $dataRegion = Region::all(); $dataMember = Member::where('region','=', $regionname) ->latest() ->get(); return view('regionmemberlist',compact('dataMember','dataPosition', 'dataClub', 'dataRegion')); } public function viewclub($clubname){ $dataPosition = Position::all(); $dataClub = Club::all(); $dataRegion = Region::all(); $dataMember = Member::where('club','=', $clubname) ->latest() ->get(); return view('clubmemberlist',compact('dataMember','dataPosition', 'dataClub', 'dataRegion')); } public function editmembers(Request $request) { //dd($request); $data = Member::find($request->id); $data->fname = $request->fname; $data->mname = $request->mname; $data->lname = $request->lname; $data->personalidnumber = $request->personalid; $data->clubidnumber = $request->clubnumber; $data->regionalidnumber = $request->regnumber; $data->position = $request->position; $data->club = $request->club; $data->region = $request->region; $data->address = $request->address; $data->personalcontact = $request->contactnum; $data->bloodtype = $request->bloodtype; $data->contactperson = $request->contactperson; $data->contactpersonnumber = $request->contactpersonnum; $data->relation = $request->relation; $data->email = $request->email; $data->website = $request->website; $data->tin = $request->tin; $data->philhealth = $request->philhealth; $data->sssgsis = $request->sssgsis; $data->pagibig = $request->pagibig; $data->bdate = $request->birthdate; $data->religion = $request->religion; $data->save(); return response()->json($data); } public function addmembers(Request $request) { //dd($request->positionadd); $data = new Member(); $data->fname = $request->fnameadd; $data->mname = $request->mnameadd; $data->lname = $request->lnameadd; $data->personalidnumber = $request->personalidadd; $data->clubidnumber = $request->clubnumberadd; $data->regionalidnumber = $request->regnumberadd; $data->position = $request->positionadd; $image = $request->file('input_img'); $name = time().'.'.$image->getClientOriginalExtension(); $destinationPath = public_path('/member'); $image->move($destinationPath, $name); $data->pic = $name; $data->club = $request->clubadd; $data->region = $request->regionadd; $data->address = $request->addressadd; $data->personalcontact = $request->contactnumadd; $data->bloodtype = $request->bloodtypeadd; $data->contactperson = $request->contactpersonadd; $data->contactpersonnumber = $request->contactpersonnumadd; $data->relation = $request->relationadd; $data->email = $request->emailadd; $data->website = $request->websiteadd; $data->tin = $request->tinadd; $data->philhealth = $request->philhealthadd; $data->sssgsis = $request->sssgsisadd; $data->pagibig = $request->pagibigadd; $data->bdate = $request->birthdateadd; $data->religion = $request->religionadd; $data->save(); $dataPosition = Position::where('positionname', '=', $request->positionadd)->count(); if($dataPosition == 0 ){ $position = new Position(); $position->positionname = $request->positionadd; $position->save(); } $dataClub = Club::where('clubname', '=',$request->clubadd)->count(); if($dataClub == 0 ){ $Club = new Club(); $Club->clubname = $request->clubadd; $Club->save(); } $dataRegion = Region::where('regioname', '=',$request->regionadd); if($dataRegion == 0 ){ $Region = new Region(); $Region->regioname = $request->regionadd; $Region->save(); } return redirect()->back()->with('success','Member Successfully Added!'); //return response()->json($data); } public function memberssearch (Request $request){ if($request->ajax()) { $dataMember = Member::where('fname','LIKE','%'.$request->search."%") ->orWhere('lname','LIKE','%'.$request->search."%") ->orWhere('mname','LIKE','%'.$request->search."%") ->orWhere('personalidnumber','LIKE','%'.$request->search."%") ->orWhere('clubidnumber','LIKE','%'.$request->search."%") ->orWhere('regionalidnumber','LIKE','%'.$request->search."%") ->latest() ->get(); $output=""; if($dataMember) { foreach ($dataMember as $key => $Member) { $output.='<tr> <td>'.$Member->personalidnumber.'</td> <td>'.ucwords($Member->lname).', '.ucwords($Member->fname).' '.ucwords($Member->mname).'</td> <td>'.ucwords($Member->region).'</td> <td><a href="javascript:;" class="quickview btn btn-xs btn-info" data-id="'.$Member->id.'" data-personalid="'.$Member->personalidnumber.'" data-clubnumber="'.$Member->clubidnumber.'" data-regnumber="'.$Member->regionalidnumber.'" data-club="'.ucwords($Member->club).'" data-region="'.ucwords($Member->region).'" data-position="'.ucwords($Member->position).'" data-address="'.ucwords($Member->address).'" data-contactnum="'.$Member->personalcontact.'" data-bloodtype="'.$Member->bloodtype.'" data-contactperson="'.ucwords($Member->contactperson).'" data-contactpersonnum="'.$Member->contactpersonnumber.'" data-relation="'.ucwords($Member->relation).'" data-email="'.$Member->email.'" data-website="'.$Member->website.'" data-tin="'.$Member->tin.'" data-birthdate="'.$Member->bdate.'" data-philhealth="'.$Member->philhealth.'" data-sssgsis="'.$Member->sssgsis.'" data-pagibig="'.$Member->pagibig.'" data-religion="'.$Member->pagibig.'" data-name="'.ucwords($Member->lname).', '.ucwords($Member->fname).' '.ucwords($Member->mname).'" data-fname="'.ucwords($Member->fname).'" data-lname="'.ucwords($Member->lname).'" data-mname="'.ucwords($Member->mname).'"> <i class="fa fa-search"> </i> Quick View</a> </td>'; $output .='</tr>'; } return Response($output); } } } public function regionsearch (Request $request){ //dd($request); if($request->ajax()) { $dataMember = Member::where('region','LIKE','%'.$request->search."%") ->latest() ->get(); $output=""; if($dataMember) { $num = 1; foreach ($dataMember as $key => $Member) { $output.='<tr> <td>'.$num.'</td> <td>'.$Member->personalidnumber.'</td> <td>'.ucwords($Member->lname).', '.ucwords($Member->fname).' '.ucwords($Member->mname).'</td> <td>'.ucwords($Member->club).'</td> <td class="quickviewcol"><a href="javascript:;" class="quickview btn btn-xs btn-info" data-id="'.$Member->id.'" data-personalid="'.$Member->personalidnumber.'" data-clubnumber="'.$Member->clubidnumber.'" data-regnumber="'.$Member->regionalidnumber.'" data-club="'.ucwords($Member->club).'" data-region="'.ucwords($Member->region).'" data-position="'.ucwords($Member->position).'" data-address="'.ucwords($Member->address).'" data-contactnum="'.$Member->personalcontact.'" data-bloodtype="'.$Member->bloodtype.'" data-contactperson="'.ucwords($Member->contactperson).'" data-contactpersonnum="'.$Member->contactpersonnumber.'" data-relation="'.ucwords($Member->relation).'" data-email="'.$Member->email.'" data-website="'.$Member->website.'" data-tin="'.$Member->tin.'" data-birthdate="'.$Member->bdate.'" data-philhealth="'.$Member->philhealth.'" data-sssgsis="'.$Member->sssgsis.'" data-pagibig="'.$Member->pagibig.'" data-religion="'.$Member->pagibig.'" data-name="'.ucwords($Member->lname).', '.ucwords($Member->fname).' '.ucwords($Member->mname).'" data-fname="'.ucwords($Member->fname).'" data-lname="'.ucwords($Member->lname).'" data-mname="'.ucwords($Member->mname).'"> <i class="fa fa-search"> </i> Quick View</a> </td>'; $output .='</tr>'; $num += 1; } return Response($output); } } } public function clubsearch (Request $request){ //dd($request); if($request->ajax()) { $dataMember = Member::where('club','LIKE','%'.$request->search."%") ->latest() ->get(); $output=""; if($dataMember) { $num = 1; foreach ($dataMember as $key => $Member) { $output.='<tr> <td>'.$num.'</td> <td>'.$Member->personalidnumber.'</td> <td>'.ucwords($Member->lname).', '.ucwords($Member->fname).' '.ucwords($Member->mname).'</td> <td>'.ucwords($Member->club).'</td> <td class="quickviewcol"><a href="javascript:;" class="quickview btn btn-xs btn-info" data-id="'.$Member->id.'" data-personalid="'.$Member->personalidnumber.'" data-clubnumber="'.$Member->clubidnumber.'" data-regnumber="'.$Member->regionalidnumber.'" data-club="'.ucwords($Member->club).'" data-region="'.ucwords($Member->region).'" data-position="'.ucwords($Member->position).'" data-address="'.ucwords($Member->address).'" data-contactnum="'.$Member->personalcontact.'" data-bloodtype="'.$Member->bloodtype.'" data-contactperson="'.ucwords($Member->contactperson).'" data-contactpersonnum="'.$Member->contactpersonnumber.'" data-relation="'.ucwords($Member->relation).'" data-email="'.$Member->email.'" data-website="'.$Member->website.'" data-tin="'.$Member->tin.'" data-birthdate="'.$Member->bdate.'" data-philhealth="'.$Member->philhealth.'" data-sssgsis="'.$Member->sssgsis.'" data-pagibig="'.$Member->pagibig.'" data-religion="'.$Member->pagibig.'" data-name="'.ucwords($Member->lname).', '.ucwords($Member->fname).' '.ucwords($Member->mname).'" data-fname="'.ucwords($Member->fname).'" data-lname="'.ucwords($Member->lname).'" data-mname="'.ucwords($Member->mname).'"> <i class="fa fa-search"> </i> Quick View</a> </td>'; $output .='</tr>'; $num += 1; } return Response($output); } } } use Exportable; public function downloadExcel($type) { return Excel::download(new MemberExport, 'members.csv'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMembersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('members', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('regionalidnumber'); $table->string('clubidnumber'); $table->string('personalidnumber'); $table->string('fname'); $table->string('lname'); $table->string('mname'); $table->string('position'); $table->string('club'); $table->string('region'); $table->string('address'); $table->string('personalcontact'); $table->string('bloodtype'); $table->string('contactperson'); $table->string('contactpersonnumber'); $table->string('relation'); $table->string('idtype'); $table->string('idnumber'); $table->string('email'); $table->string('website'); $table->string('tin'); $table->string('bdate'); $table->string('philhealth'); $table->string('sssgsis'); $table->string('pagibig'); $table->string('religion'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('members'); } } <file_sep><?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('auth.login'); }); Route::post('/adminlogin', 'LoginController@adminLogin')->name('adminLogin'); Auth::routes(); // route with middleware on controller Route::group(['middleware' =>'adminAuth','prefix' => 'admin'], function(){ Route::get('/home', 'HomeController@index')->name('home'); Route::get('/about', 'HomeController@about')->name('about'); Route::get('/members', 'HomeController@members')->name('members'); Route::post('/members/add', 'HomeController@addmembers')->name('addmembers'); Route::post('/deletemember', 'HomeController@deletemember')->name('deletemember'); Route::post('/members/edit', 'HomeController@editmembers')->name('editmembers'); Route::get('/regions', 'HomeController@regions')->name('regions'); Route::get('/regions/{regionname}', 'HomeController@viewregions')->name('viewregions'); Route::get('/clubs', 'HomeController@clubs')->name('clubs'); Route::get('/clubs/{clubname}', 'HomeController@viewclub')->name('viewclub'); Route::get('/memberssearch', 'HomeController@memberssearch')->name('memberssearch'); Route::get('/regionsearch', 'HomeController@regionsearch')->name('regionsearch'); Route::get('/clubsearch', 'HomeController@clubsearch')->name('clubsearch'); Route::post('/updateaccount', 'HomeController@updateaccount')->name('updateaccount'); Route::get('/downloadExcel/{type}', 'HomeController@downloadExcel')->name('downloadExcel'); }); // end route with middleware
473df10e80396f73d767a292eed51a44949e9316
[ "PHP" ]
3
PHP
gegejosper/ems
55346590b02da55f84c7d683ac6ca6f650b4e6b6
7d726a81c537cf0c6659b497baa23487613544e1
refs/heads/master
<repo_name>akeske/biMysql<file_sep>/index_stu.php <?php if (version_compare(PHP_VERSION, '5.3.7', '<')) { exit("Sorry, Simple PHP Login does not run on a PHP version smaller than 5.3.7 !"); } else if (version_compare(PHP_VERSION, '5.5.0', '<')) { require_once("libraries/password_compatibility_library.php"); } require_once("config/db.php"); require_once("classes/Login.php"); $login = new Login(); require_once("classes/Student.php"); $student = new Student(); $_SESSION['page'] = "student"; ?> <html> <head> <title>Temporal database - Students</title> <meta charset='utf-8'> <link rel="stylesheet" href="css/buttons.css"> <link rel="stylesheet" href="css/forms.css"> <link rel="stylesheet" href="css/tables.css"> <link rel="stylesheet" href="css/styles.css"> <!-- Add jQuery library --> <script type="text/javascript" src="lib/jquery-1.10.1.min.js"></script> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="source/jquery.fancybox.js?v=2.1.5"></script> <link rel="stylesheet" type="text/css" href="source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script type="text/javascript"> $(document).ready(function() { $('.fancybox').fancybox({ maxWidth : 860, maxHeight : 600, fitToView : false, width : '100%', height : '100%', autoSize : false, closeClick : false, openEffect : 'none', closeEffect : 'none' }); }); </script> <link rel="stylesheet" type="text/css" href="css/tcal.css" /> <script type="text/javascript" src="js/tcal.js"></script> <script src="js/script.js"></script> </head> <body> <table id="mainTable"> <tr><td></td><td><?php include("menu.php"); ?></td></tr> <tr> <td width="280px"> <?php if ($login->isUserLoggedIn() == true) { include("views/logged_in.php"); } else { include("views/not_logged_in.php"); } ?> <form method="post" action="" onClick="window.location.reload()"> <input type="button" value="Refresh page" class="pure-button pure-button-primary"> </form> </td> <td> <?php if ($login->isUserLoggedIn() == true) { ?> <fieldset id="fieldset"> <legend>Student</legend> <?php include("views/student.php"); ?> </fieldset> <?php } ?> </td> </tr> </table> </body> </html> <file_sep>/classes/Student.php <?php class Student{ public $db_connection = null; public $errors = array(); public $messages = array(); public function __construct(){ if (isset($_POST["editStudent"])) { $this->editStudent(); } if (isset($_POST["insertStudent"])) { $this->insertStudent(); } if (isset($_POST["findStudentForm"])) { $this->findStudentForm(); } } public function connect(){ $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$this->db_connection->set_charset("utf8")) { $this->errors[] = $this->db_connection->error; } } public function findStudentForm(){ $this->connect(); if (!$this->db_connection->connect_errno) { $parts = explode ('/' , $_POST['findDateStudent']); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $findDate=$day.$month.$year."000000"; $sql = "SELECT * FROM student WHERE '".$findDate."' BETWEEN valid_start AND IFNULL(valid_end, '2099-12-31 00:00:00') AND trans_end IS NULL AND student_id = '".$_GET['stu_id']."' ORDER BY valid_start DESC LIMIT 1"; return $sql; } else { $this->errors[] = "Database connection problem: ".$this->db_connection->connect_error; } } private function editStudent(){ $date = date('Y-m-d H:i:s', time()); if (empty($_POST['validEnd']) && empty($_POST['new_validEnd']) && empty($_POST['new_validStart']) && empty($_POST['new_address'])) { $this->errors[] = "There are missing a lot information."; }elseif (empty($_POST['stu_id'])) { $this->errors[] = "Student ID field was empty."; }elseif(!empty($_POST['new_address']) && !empty($_POST['new_validStart']) && empty($_POST['new_validEnd']) && empty($_POST['validEnd']) ){ $this->errors[] = "If you want to insert new info you have to close previous valid end."; }else{ $this->connect(); if (!$this->db_connection->connect_errno) { $id = $this->db_connection->real_escape_string(strip_tags($_POST['id'], ENT_QUOTES)); $sql = "SELECT * FROM student WHERE id = ".$id; $result = $this->db_connection->query($sql); $row = $result->fetch_array(); if($_POST['validEnd']!=""){ $sql = "UPDATE student SET read_level = 'admin', trans_end = '".$date."' WHERE id = ".$id; $this->db_connection->query($sql); $parts = explode ('/' , $_POST['validEnd']); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validEnd=$day.$month.$year."000000"; $sql = "INSERT INTO student (id, student_id, name, address, valid_start, valid_end, trans_start, trans_end, read_level) VALUES (NULL, '".$row['student_id']."', '".$row['name']."', '".$row['address']."', '".$row['valid_start']."', '".$validEnd."', '".$date."', NULL, 'admin');"; $this->db_connection->query($sql); } if(!empty($_POST['new_address']) && !empty($_POST['new_validStart'])){ $parts = explode ('/' , $_POST['new_validStart']); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $new_validStart=$day.$month.$year."000000"; if($_POST['new_validEnd']!=""){ $parts = explode ('/' , $_POST['new_validEnd']); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $new_validEnd=$day.$month.$year."000000"; }else{ $new_validEnd = ""; } if($new_validEnd==""){ $sql = "INSERT INTO student (id, student_id, name, address, valid_start, valid_end, trans_start, trans_end, read_level) VALUES (NULL, '".$row['student_id']."', '".$row['name']."', '".$_POST['new_address']."', '".$new_validStart."', NULL, CURRENT_TIMESTAMP, NULL, 'admin,secretary,student');"; }else{ $sql = "INSERT INTO student (id, student_id, name, address, valid_start, valid_end, trans_start, trans_end, read_level) VALUES (NULL, '".$row['student_id']."', '".$row['name']."', '".$_POST['new_address']."', '".$new_validStart."', '".$new_validEnd."', CURRENT_TIMESTAMP, NULL, 'admin');"; } $result_insert_student = $this->db_connection->query($sql); if ($result_insert_student) { $this->messages[] = "New student has id: " . $this->db_connection->insert_id; }else{ $this->errors[] = "Error: " . $sql . "<br>" . mysqli_error($this->db_connection); } } else { $sql = "UPDATE user SET is_enable = 'false' WHERE id = ".$row['student_id']; $this->db_connection->query($sql); $this->messages[] = "The student <b>".$row['name']."</b> canoot any more log in."; } $result->free(); $this->db_connection->close(); } else { $this->errors[] = "Database connection problem: ".$this->db_connection->connect_error; } } } private function insertStudent(){ if (empty($_POST['name'])) { $this->errors[] = "Username field was empty."; } elseif (empty($_POST['address'])) { $this->errors[] = "Address field was empty."; } else { $this->connect(); $name = $this->db_connection->real_escape_string(strip_tags($_POST['name'], ENT_QUOTES)); $address = $this->db_connection->real_escape_string(strip_tags($_POST['address'], ENT_QUOTES)); $sql = "SELECT * FROM user WHERE name = '" . $name . "';"; $query_check_user_name = $this->db_connection->query($sql); if ($query_check_user_name->num_rows == 1) { $this->errors[] = "Sorry, that username is already taken."; }else{ if (!$this->db_connection->connect_errno) { $user_password_hash = password_hash($<PASSWORD>, PASSWORD_DEFAULT); $sql = "INSERT INTO user (id, name, password, type, is_enable) VALUES (NULL, '".$name."', '".$user_password_hash."', 'student', 'true');"; $result_insert_musician = $this->db_connection->query($sql); $new_stu_id = $this->db_connection->insert_id; $sql = "SELECT MAX(student_id) FROM student"; $result = $this->db_connection->query($sql); if( mysqli_num_rows($result) == 0){ $new_stu_id = 1; }else{ $row = $result->fetch_array(); $new_stu_id = $row[0] + 1; } $parts = explode ('/' , $_POST['validStart']); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validStart=$day.$month.$year."000000"; if($_POST['validEnd']!=""){ $parts = explode ('/' , $_POST['validEnd']); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validEnd=$day.$month.$year."000000"; }else{ $validEnd = ""; } if($validEnd==""){ $sql = "INSERT INTO student (id, student_id, name, address, valid_start, valid_end, trans_start, trans_end, read_level) VALUES (NULL, '".$new_stu_id."', '".$name."', '".$address."', '".$validStart."', NULL, CURRENT_TIMESTAMP, NULL, 'admin,student,secretary');"; }else{ $sql = "INSERT INTO student (id, student_id, name, address, valid_start, valid_end, trans_start, trans_end, read_level) VALUES (NULL, '".$new_stu_id."', '".$name."', '".$address."', '".$validStart."', '".$validEnd."', CURRENT_TIMESTAMP, NULL, 'admin');"; } $result_insert_student = $this->db_connection->query($sql); if ($result_insert_student) { $this->messages[] = "New student has id: " . $this->db_connection->insert_id; }else{ $this->errors[] = "Error: " . $sql . "<br>" . mysqli_error($this->db_connection); } $sql = "INSERT INTO audit (id, user_id, table_name, query, trans_time) VALUES (NULL, '".$_SESSION['user_id']."', 'student', 'inserted new student: ".$name."', CURRENT_TIMESTAMP);"; $this->db_connection->query($sql); $this->db_connection->close(); } else { $this->errors[] = "Database connection problem: ".$this->db_connection->connect_error; } } } } public function displayDateStudent($date, $type){ if($date!=""){ if($type=="valid"){ $parts1 = explode (' ' , $date); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; return $day."/".$month."/".$year; }else{ $parts1 = explode (' ' , $date); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $parts = explode (':' , $parts1[1]); $sec=$parts[2]; $min=$parts[1]; $hour=$parts[0]; return $day."/".$month."/".$year."&nbsp;".$hour.":".$min.":".$sec; } } } } <file_sep>/views/logged_in.php <!-- if you need user information, just put them into the $_SESSION variable and output them here --> Hey, <b><?php echo $_SESSION['user_name']." (".$_SESSION['user_id'].")"; ?></b>. <br> Your privileges is <b><?php echo $_SESSION['user_type']; ?></b>.<br><br> <!-- because people were asking: "index.php?logout" is just my simplified form of "index.php?logout=true" --> <a href="index.php?logout">Logout</a> <file_sep>/views/audit.php <datalist id="user_names"> <?php $audit->connect(); if (!$audit->db_connection->connect_errno) { $sql = "SELECT id, name FROM user GROUP BY name"; $result = $audit->db_connection->query($sql); if( mysqli_num_rows($result) != 0){ while($row = $result->fetch_array() ){ ?> <option value="<?php echo $row['name']; ?>"> <?php } // $result->free(); } }?> </datalist> <table id="table2"> <tr> <td> <?php if ($_SESSION['user_type']!="admin") { ?> <?php } ?> <form method="post" action="index_aud.php" name="insertMucisianForm" class="pure-form"> <fieldset id="fieldset"> <legend>Select user</legend> <input list="user_names" id="name" size="20" class="login_input" type="text" placeholder="Audit for user" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,30}" autocomplete="off" name="name" maxlength="30"/> <input type="submit" class="pure-button pure-button-primary" name="search" value="Search" /> </fieldset> </form> <fieldset id="fieldset"> <legend>List of queries</legend> <div id="overflow"> <table id="table1"> <thead class="fixedHeader1"> <tr> <th>ID</th> <th>User&nbsp;name</th> <th>Table&nbsp;name</th> <th>Query</th> <th>Time</th> </tr> </thead> <tbody class="scrollContent1"> <?php if (!$audit->db_connection->connect_errno) { if(isset($_POST['name'])){ if($_POST['name']!=""){ $addSql = "WHERE u.name = '".$_POST['name']."'"; }else{ $addSql = ""; } }else{ $addSql = ""; } $sql = "SELECT a.id, a.user_id, a.table_name, a.query, a.trans_time, u.name FROM audit a LEFT JOIN user u on u.id = a.user_id $addSql ORDER BY a.trans_time DESC"; echo $sql; $result = $audit->db_connection->query($sql); $even = 1; if( mysqli_num_rows($result) != 0){ while($row = $result->fetch_array() ){ if($even==0){ ?> <tr> <?php $even=1; }else{ ?> <tr class="even"> <?php $even=0; } ?> <td><?php echo $row['id']; ?></td> <td><?php echo $row['name']."(".$row['user_id'].")"; ?></td> <td><?php echo $row['table_name']; ?></td> <td><?php echo $row['query']; ?></td> <td><?php echo $row['trans_time']; ?></td> </tr> <?php } $result->free(); } $audit->db_connection->close(); }else{ } ?> </tbody> </table> </div> </fieldset> </td> </tr> </table> <file_sep>/views/instrument.php <?php if (isset($instrument)) { if ($instrument->errors) { foreach ($instrument->errors as $error) { echo $error; } } if ($instrument->messages) { foreach ($instrument->messages as $message) { echo $message; } } } ?> <table id="table2"> <tr> <td> <?php if ($_SESSION['user_type']=="admin" || $_SESSION['user_type']=="secretary") { ?> <form method="post" action="index_ins.php" name="insertInstrument" class="pure-form"> <fieldset id="fieldset"> <legend>Insert new instrument</legend> <input id="ins_name" size="20" class="login_input" type="text" placeholder="Instrument name" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,30}" autocomplete="off" name="ins_name" required maxlength="30"/> <input type="submit" class="pure-button pure-button-primary" name="insertInstrument" value="Insert" /> </fieldset> </form> <?php } ?> <fieldset id="fieldset"> <legend>List of instruments</legend> <div id="overflow"> <table id="table1"> <thead class="fixedHeader1"> <tr> <th>ID&nbsp;instrument</th> <th>Name</th> <?php if($_SESSION['user_type']=="admin"){ ?> <th>Trans&nbsp;Start</th> <th>Trans&nbsp;End</th> <?php } if($_SESSION['user_type']!="student" && $_SESSION['user_type']!="musician"){ ?> <th>Delete</th> <?php } ?> </tr> </thead> <tbody class="scrollContent1"> <?php $instrument->connect(); if (!$instrument->db_connection->connect_errno) { if($_SESSION['user_type']=="admin"){ $sql = "SELECT instrument_id, name, trans_start, trans_end FROM instrument ORDER BY name"; }else{ $sql = "SELECT instrument_id, name, trans_start, trans_end FROM instrument WHERE trans_end IS NULL ORDER BY name"; } echo $sql; $result = $instrument->db_connection->query($sql); $even = 1; if( mysqli_num_rows($result) != 0){ while($row = $result->fetch_array() ){ if($even==0){ ?> <tr> <?php $even=1; }else{ ?> <tr class="even"> <?php $even=0; } ?> <td width="100"><?php echo $row['instrument_id']; ?></td> <td><?php echo $row['name']; ?></td> <?php if($_SESSION['user_type']=="admin"){ ?> <td><?php echo $instrument->displayDate($row['trans_start'], "trans"); ?></td> <td><?php echo $instrument->displayDate($row['trans_end'], "trans"); ?></td> <?php } if($_SESSION['user_type']!="student" && $row['trans_end']==NULL){ ?> <td> <form method="post" action="index_ins.php" name="insertInstrument" class="pure-form"> <input id="id_ins" name="id_ins" type="hidden" value= "<?php echo $row['instrument_id']; ?>" /> <input id="name_ins" name="name_ins" type="hidden" value= "<?php echo $row['name']; ?>" /> <input type="submit" class="pure-button pure-button-primary" name="deleteInstrument" value="Delete" /> </form> </td> <?php } ?> </tr> <?php } $result->free(); } $instrument->db_connection->close(); }else{ } ?> </tbody> </table> </div> </fieldset> </td> </tr> </table> <file_sep>/views/musician.php <?php if (isset($musician)) { if ($musician->errors) { foreach ($musician->errors as $error) { echo $error; } } if ($musician->messages) { foreach ($musician->messages as $message) { echo $message; } } } ?> <table id="table2"> <tr> <td> <?php if ($_SESSION['user_type']=="admin" || $_SESSION['user_type']=="secretary") { ?> <form method="post" action="index_mus.php" name="insertMucisianForm" class="pure-form"> <fieldset id="fieldset"> <legend>Insert new musician</legend> <input id="name" size="15" class="login_input" type="text" placeholder="Musician name" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,30}" autocomplete="off" name="name" required maxlength="30"/> <input id="telephone" size="15" class="login_input" type="text" name="telephone" required autocomplete="off" placeholder="Telephone" required maxlength="12"/> <input autocomplete="off" type="text" name="validStart" class="tcal" id="validStart" size="14" placeholder="Valid start" required maxlength="12"/> <input autocomplete="off" type="text" name="validEnd" class="tcal" id="validEnd" size="14" placeholder="Valid end" maxlength="12"/> <input type="submit" class="pure-button pure-button-primary" name="insertMusician" value="Insert" /> </fieldset> </form> <form method="post" action="index_mus.php" name="musicialSqlForm" class="pure-form"> <fieldset id="fieldset"> <legend>Your SQL query</legend> Table name: musician <br> Fields: id , musician_id , name, telephone , valid_start , valid_end , trans_start , trans_end <br> <input id="musicianSql" name="musicianSql" type="text" placeHolder="Please insert your desirable SQL script" class="login_input" size="50"/> <input type="submit" class="pure-button pure-button-primary" name="musicianSqlSubmit" value="Exec" /> </fieldset> </form> <?php } ?> <fieldset id="fieldset"> <legend>List of musicians</legend> <div id="overflow"> <table id="table1"> <thead class="fixedHeader1"> <?php if ($_SESSION['user_type']=="student") { ?> <tr> <th>Name</th> <th>Telephone</th> </tr> <?php }else{ ?> <tr> <?php if ($_SESSION['user_type']=="musician") { ?> <th>Name</th> <th>Telephone</th> <?php }else{ ?> <th>ID</th> <th>ID&nbsp;musician</th> <th>Name</th> <th>Telephone</th> <th>Valid&nbsp;Start</th> <th>Valid&nbsp;End</th> <th>Trans&nbsp;Start</th> <th>Trans&nbsp;End</th> <?php if($_SESSION['user_type']!="student"){ ?> <th>Edit</th> <?php } } ?> </tr> <?php } ?> </thead> <tbody class="scrollContent1"> <?php $musician->connect(); if (!$musician->db_connection->connect_errno) { if(isset($_POST['musicianSqlSubmit']) && $_POST['musicianSql']!=null){ $sql = $_POST['musicianSql']; }else{ if ($_SESSION['user_type']=="admin") { $sql = "SELECT * FROM musician HAVING read_level LIKE '%admin%' ORDER BY name, musician_id, valid_start, trans_end DESC"; }elseif ($_SESSION['user_type']=="student" || $_SESSION['user_type']=="musician") { $sql = "SELECT name, telephone, read_level, trans_end, valid_end FROM musician HAVING read_level LIKE '%student%' ORDER BY name ASC"; }else{ $sql = "SELECT * FROM musician HAVING read_level LIKE '%secretary%' ORDER BY name, valid_start, trans_end DESC"; } } echo $sql; $result = $musician->db_connection->query($sql); $even = 1; if( mysqli_num_rows($result) != 0){ while($row = $result->fetch_array() ){ if($row['valid_end']==null && $row['trans_end']==null){ $style = "\"font-weight:bold; color:rgb(0, 120, 231);\""; }else{ $style = ""; } if($even==0){ ?> <tr style=<?php echo $style; ?> > <?php $even=1; }else{ ?> <tr class="even" style=<?php echo $style; ?> > <?php $even=0; } if ($_SESSION['user_type']=="student" || $_SESSION['user_type']=="musician") { ?> <td><?php echo $row['name']; ?></td> <td><?php echo $row['telephone']; ?></td> <?php }else{ ?> <td><?php echo $row['id']; ?></td> <td><?php echo $row['musician_id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['telephone']; ?></td> <td><?php echo $musician->displayDate($row['valid_start'], "valid"); ?></td> <td><?php echo $musician->displayDate($row['valid_end'], "valid"); ?></td> <td><?php echo $musician->displayDate($row['trans_start'], "trans"); ?></td> <td><?php echo $musician->displayDate($row['trans_end'], "trans"); ?></td> <?php if($row['valid_end']==null && $row['trans_end']==null && $_SESSION['user_type']!="student"){ ?> <td><a class="fancybox fancybox.iframe" href="musician_info.php?id=<?php echo $row['id']; ?>&mus_id=<?php echo $row['musician_id']; ?>">Edit</a></td> <?php } }?> </tr> <?php } $result->free(); } $musician->db_connection->close(); }else{ } ?> </tbody> </table> </div> </fieldset> </td> </tr> </table> <file_sep>/classes/Instrument.php <?php class Instrument{ public $db_connection = null; public $errors = array(); public $messages = array(); public function __construct(){ if (isset($_POST["deleteInstrument"])) { $this->deleteInstrument(); } if (isset($_POST["insertInstrument"])) { $this->insertInstrument(); } } public function connect(){ $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$this->db_connection->set_charset("utf8")) { $this->errors[] = $this->db_connection->error; } } private function deleteInstrument(){ if (empty($_POST['id_ins'])) { $this->errors[] = "There are missing a lot information."; } else { $this->connect(); if (!$this->db_connection->connect_errno) { $id_ins = $this->db_connection->real_escape_string(strip_tags($_POST['id_ins'], ENT_QUOTES)); $name_ins = $this->db_connection->real_escape_string(strip_tags($_POST['name_ins'], ENT_QUOTES)); $sql = "UPDATE instrument SET trans_end = CURRENT_TIMESTAMP WHERE instrument_id = '".$id_ins."'"; $this->db_connection->query($sql); $sql = "INSERT INTO audit (id, user_id, table_name, query, trans_time) VALUES (NULL, '".$_SESSION['user_id']."', 'instrument', 'deleted instrument: ".$name_ins."', CURRENT_TIMESTAMP);"; $this->db_connection->query($sql); $this->db_connection->close(); } else { $this->errors[] = "Database connection problem: ".$this->db_connection->connect_error; } } } private function insertInstrument(){ if (empty($_POST['ins_name'])) { $this->errors[] = "Some fields are empty."; } else { $this->connect(); if (!$this->db_connection->connect_errno) { $ins_name = $this->db_connection->real_escape_string($_POST['ins_name']); $sql = "INSERT INTO instrument (instrument_id, name, trans_start, trans_end) VALUES (NULL, '".$ins_name."', CURRENT_TIMESTAMP, NULL);"; $result_insert_instrument = $this->db_connection->query($sql); if ($result_insert_instrument) { $this->messages[] = "New instrument has id: " . $this->db_connection->insert_id; }else{ $this->errors[] = "Error: " . $sql . "<br>" . mysqli_error($this->db_connection); } $sql = "INSERT INTO audit (id, user_id, table_name, query, trans_time) VALUES (NULL, '".$_SESSION['user_id']."', 'instrument', 'insert new instrument: ".$ins_name."', CURRENT_TIMESTAMP);"; $this->db_connection->query($sql); $this->db_connection->close(); } else { $this->errors[] = "Database connection problem: ".$this->db_connection->connect_error; } } } public function displayDate($date, $type){ if($date!=""){ if($type=="valid"){ $parts1 = explode (' ' , $date); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; return $day."/".$month."/".$year; }else{ $parts1 = explode (' ' , $date); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $parts = explode (':' , $parts1[1]); $sec=$parts[2]; $min=$parts[1]; $hour=$parts[0]; return $day."/".$month."/".$year."&nbsp;".$hour.":".$min.":".$sec; } } } } <file_sep>/_installation/conservatory.sql 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 utf8 */; CREATE DATABASE IF NOT EXISTS `conservatory` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; USE `conservatory`; DROP TABLE IF EXISTS `audit`; CREATE TABLE IF NOT EXISTS `audit` ( `id` int(10) NOT NULL, `user_id` int(10) NOT NULL, `table_name` enum('instrument','musician','student','teaching','register','login','logout') NOT NULL, `query` mediumblob NOT NULL, `trans_time` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1; DROP TABLE IF EXISTS `instrument`; CREATE TABLE IF NOT EXISTS `instrument` ( `instrument_id` int(10) NOT NULL, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `trans_start` timestamp NULL DEFAULT NULL, `trans_end` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; DROP TABLE IF EXISTS `musician`; CREATE TABLE IF NOT EXISTS `musician` ( `id` int(10) NOT NULL, `musician_id` int(10) NOT NULL, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `telephone` varchar(15) COLLATE utf8_unicode_ci NOT NULL, `valid_start` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `valid_end` timestamp NULL DEFAULT NULL, `trans_start` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `trans_end` timestamp NULL DEFAULT NULL, `read_level` set('admin','secretary','student','') COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; DROP TABLE IF EXISTS `student`; CREATE TABLE IF NOT EXISTS `student` ( `id` int(10) NOT NULL, `student_id` int(10) NOT NULL, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `address` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `valid_start` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `valid_end` timestamp NULL DEFAULT NULL, `trans_start` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `trans_end` timestamp NULL DEFAULT NULL, `read_level` set('student','admin','secretary','') COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; DROP TABLE IF EXISTS `teaching`; CREATE TABLE IF NOT EXISTS `teaching` ( `id` int(10) NOT NULL, `teaching_id` int(10) NOT NULL, `student_id` int(10) NOT NULL, `musician_id` int(10) NOT NULL, `instrument_id` int(10) NOT NULL, `valid_start` timestamp NULL DEFAULT NULL, `valid_end` timestamp NULL DEFAULT NULL, `read_level` set('student','admin','secretary','') COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; DROP TABLE IF EXISTS `user`; CREATE TABLE IF NOT EXISTS `user` ( `id` int(10) NOT NULL, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `type` set('admin','secretary','student','musician') COLLATE utf8_unicode_ci NOT NULL, `is_enable` enum('true','false') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'false' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; INSERT INTO `user` (`id`, `name`, `password`, `type`, `is_enable`) VALUES (0, 'admin', <PASSWORD>', '<PASSWORD>', 'true'); ALTER TABLE `audit` ADD PRIMARY KEY (`id`); ALTER TABLE `instrument` ADD PRIMARY KEY (`instrument_id`); ALTER TABLE `musician` ADD PRIMARY KEY (`id`); ALTER TABLE `student` ADD PRIMARY KEY (`id`); ALTER TABLE `teaching` ADD PRIMARY KEY (`id`), ADD KEY `id` (`id`); ALTER TABLE `user` ADD PRIMARY KEY (`id`); ALTER TABLE `audit` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1; ALTER TABLE `instrument` MODIFY `instrument_id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1; ALTER TABLE `musician` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1; ALTER TABLE `student` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1; ALTER TABLE `teaching` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1; /*!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 */; <file_sep>/classes/Login.php <?php class Login{ private $db_connection = null; public $errors = array(); public $messages = array(); public function __construct(){ session_start(); if (isset($_GET["logout"])) { $this->doLogout(); }elseif(isset($_POST["login"])) { $this->dologinWithPostData(); } } private function dologinWithPostData(){ $pattern = '/select|union|insert|delete|or/i'; if (empty($_POST['user_name'])) { $this->errors[] = "Username field was empty."; } elseif (empty($_POST['user_password'])) { $this->errors[] = "Password field was empty."; } elseif(preg_match($pattern, $_POST['user_name'], $matches, PREG_OFFSET_CAPTURE) || preg_match($pattern, $_POST['user_password'], $matches, PREG_OFFSET_CAPTURE) ){ $this->errors[] = "TRY HARDER!!!!"; } else { $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$this->db_connection->set_charset("utf8")) { $this->errors[] = $this->db_connection->error; } if (!$this->db_connection->connect_errno) { $user_name = $this->db_connection->real_escape_string($_POST['user_name']); $sql = "SELECT name, password, type, id, is_enable FROM user WHERE name = '" . $user_name . "';"; $result_of_login_check = $this->db_connection->query($sql); if ($result_of_login_check->num_rows == 1) { $result_row = $result_of_login_check->fetch_object(); if($result_row->is_enable == false){ $this->errors[] = "This user does not exist."; } else { if (password_verify($_POST['user_password'], $result_row->password)) { $_SESSION['user_name'] = $result_row->name; $_SESSION['user_type'] = $result_row->type; $_SESSION['user_id'] = $result_row->id; $_SESSION['user_login_status'] = 1; $sql = "INSERT INTO audit (id, user_id, table_name, query, trans_time) VALUES (NULL, '".$_SESSION['user_id']."', 'login', 'user logged in: ".$_SESSION['user_name']."', CURRENT_TIMESTAMP);"; $this->db_connection->query($sql); $this->db_connection->close(); } else { $this->errors[] = "Wrong password. Try again."; } } } else { $this->errors[] = "This user does not exist."; } } else { $this->errors[] = "Database connection problem."; } } } public function doLogout(){ if(isset($_SESSION['user_id'])){ $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$this->db_connection->set_charset("utf8")) { $this->errors[] = $this->db_connection->error; } $this->messages[] = "You have been logged out."; $sql = "INSERT INTO audit (id, user_id, table_name, query, trans_time) VALUES (NULL, '".$_SESSION['user_id']."', 'logout', 'user logged out: ".$_SESSION['user_name']."', CURRENT_TIMESTAMP);"; $this->db_connection->query($sql); $this->db_connection->close(); } $_SESSION = array(); session_destroy(); } public function isUserLoggedIn(){ if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1) { return true; } return false; } } <file_sep>/student_info.php <?php session_start(); require_once("config/db.php"); require_once("classes/Student.php"); $student = new Student(); if (isset($student)) { if ($student->errors) { foreach ($student->errors as $error) { echo $error; } } if ($student->messages) { foreach ($student->messages as $message) { echo $message; } } } if(isset($_GET['id'])){ $pattern = '/select|union|insert|delete|or/i'; if(preg_match($pattern, $_GET['stu_id'], $matches, PREG_OFFSET_CAPTURE) || preg_match($pattern, $_GET['id'], $matches, PREG_OFFSET_CAPTURE) ){ $this->errors[] = "TRY HARDER!!!!"; }else{ $stu_id = $_GET['stu_id']; $id = $_GET['id']; $student->connect(); if (!$student->db_connection->connect_errno) { $sql = "SELECT * FROM student WHERE id = '".$_GET['id']."';"; $result = $student->db_connection->query($sql); $row = $result->fetch_array(); $name = $row['name']; $address = $row['address']; if($row['valid_start']!=null){ $parts1 = explode (' ' , $row['valid_start']); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validStart = $day."/".$month."/".$year; } if($row['valid_end']!=null){ $parts1 = explode (' ' , $row['valid_end']); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validEnd = $day."/".$month."/".$year; } $result->free(); $student->db_connection->close(); } } } ?> <html> <head> <link rel="stylesheet" href="css/buttons.css"> <link rel="stylesheet" href="css/forms.css"> <link rel="stylesheet" href="css/tables.css"> <link rel="stylesheet" href="css/styles.css"> <link rel="stylesheet" type="text/css" href="css/tcal.css" /> <script type="text/javascript" src="js/tcal.js"></script> </head> <body> <table id="table2"> <?php if ($_SESSION['user_type']=="admin" || $_SESSION['user_type']=="secretary") { ?> <tr> <td> <form method="post" action="student_info.php?id=<?php echo $row['id']; ?>&stu_id=<?php echo $stu_id; ?>" name="editStudentForm" class="pure-form"> <fieldset id="fieldset"> <legend>Set valid end for student</legend> <input value="<?php if(isset($_GET['id'])){ echo $stu_id; } ?>" id="stu_id" size="1" type="hidden" autocomplete="off" name="stu_id" maxlength="12"/> <input value="<?php if(isset($_GET['id'])){ echo $id; } ?>" id="id" size="1" type="hidden" autocomplete="off" name="id" maxlength="12"/> <input disabled value="<?php if(isset($_GET['id'])){ echo $stu_id; } ?>" size="1" type="text" autocomplete="off" maxlength="12"/> <input disabled value="<?php if(isset($_GET['id'])){ echo $name; } ?>" size="14" type="text" autocomplete="off" maxlength="30"/> <input disabled value="<?php if(isset($_GET['id'])){ echo $address; } ?>" size="14" type="text" autocomplete="off" maxlength="30"/> <input disabled value="<?php if(isset($_GET['id'])){ echo $validStart; } ?>" autocomplete="off" type="text" class="tcal" size="14" placeholder="Valid start" maxlength="12"/> <input autocomplete="off" type="text" name="validEnd" class="tcal" id="validEnd" size="14" placeholder="Valid end"/> </fieldset> <fieldset id="fieldset"> <legend>Insert new info about student</legend> <input disabled value="<?php if(isset($_GET['id'])){ echo $stu_id; } ?>" size="1" type="text" autocomplete="off" maxlength="12"/> <input disabled value="<?php if(isset($_GET['id'])){ echo $name; } ?>" size="14" type="text" autocomplete="off" maxlength="12"/> <input value="" id="new_address" size="14" type="text" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,30}" name="new_address" autocomplete="off" placeholder="New address" maxlength="12"/> <input value="" autocomplete="off" type="text" name="new_validStart" class="tcal" id="new_validStart" size="14" placeholder="Valid start" maxlength="12"/> <input value="" autocomplete="off" type="text" name="new_validEnd" class="tcal" id="new_validEnd" size="14" placeholder="Valid end" maxlength="12"/> </fieldset> <p align="right"> <input type="submit" class="pure-button pure-button-primary" name="editStudent" value="Edit / Insert" /> </p> </form> <form method="post" action="student_info.php?id=<?php echo $row['id']; ?>&stu_id=<?php echo $stu_id; ?>&find=1" name="findStudentForm" class="pure-form"> <fieldset id="fieldset"> <legend>Find address</legend> <input autocomplete="off" type="text" name="findDateStudent" class="tcal" id="findDateStudent" size="30" placeholder="Date" maxlength="12"/> <input type="submit" class="pure-button pure-button-primary" name="findStudent" value="Find" /> </fieldset> </form> <form method="post" action="" onClick="window.location.reload()"> <p align="right"> <input type="button" value="Refresh page" class="pure-button pure-button-primary"> </p> </form> <fieldset id="fieldset"> <legend>Results of student</legend> <div> <table id="table1"> <tr> <th>ID</th> <th>ID&nbsp;student</th> <th>Name</th> <th>Address</th> <th>Valid&nbsp;Start</th> <th>Valid&nbsp;End</th> <th>Trans&nbsp;Start</th> <th>Trans&nbsp;End</th> </tr> <?php $student->connect(); if (!$student->db_connection->connect_errno) { if ($_SESSION['user_type']=="admin") { $sql = "SELECT * FROM student WHERE student_id = '".$stu_id."' HAVING read_level LIKE '%admin%' ORDER BY valid_start, trans_end DESC"; }elseif ($_SESSION['user_type']=="student") { $sql = "SELECT * FROM student WHERE student_id = '".$stu_id."' HAVING read_level LIKE '%student%' ORDER BY valid_start, trans_end DESC"; }else{ $sql = "SELECT * FROM student WHERE student_id = '".$stu_id."' HAVING read_level LIKE '%secretary%' ORDER BY valid_start, trans_end DESC"; } if(isset($_GET['find']) && $_POST['findDateStudent']!=""){ $sql = $student->findStudentForm(); } echo $sql; $result = $student->db_connection->query($sql); $even = 0; while( $row = $result->fetch_array() ){ if($row['valid_end']==null && $row['trans_end']==null){ $style = "\"font-weight:bold; color:rgb(0, 120, 231);\""; }else{ $style = ""; } if($even==0){ ?> <tr style=<?php echo $style; ?>> <?php $even=1; }else{ ?> <tr class="even" style=<?php echo $style; ?>> <?php $even=0; }?> <td><?php echo $row['id']; ?></td> <td><?php echo $row['student_id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['address']; ?></td> <td><?php echo $student->displayDateStudent($row['valid_start'], "valid"); ?></td> <td><?php echo $student->displayDateStudent($row['valid_end'], "valid"); ?></td> <td><?php echo $student->displayDateStudent($row['trans_start'], "trans"); ?></td> <td><?php echo $student->displayDateStudent($row['trans_end'], "trans"); ?></td> </tr> <?php } $result->free(); $student->db_connection->close(); }else{ } ?> </table> </div> </fieldset> </td> </tr> <?php }else{ echo "You have no authority to be here!!!"; } ?> </table> </body> </html> <file_sep>/views/not_logged_in.php <?php // show potential errors / feedback (from login object) if (isset($login)) { if ($login->errors) { foreach ($login->errors as $error) { echo $error; } } if ($login->messages) { foreach ($login->messages as $message) { echo $message; } } } ?> <form method="post" action="index.php" name="loginform" class="pure-form pure-form-stacked"> <fieldset> <legend>Login</legend> <input id="login_input_username" class="login_input" type="text" placeholder="User name" name="user_name" required /> <input id="login_input_password" class="login_input" type="password" placeholder="<PASSWORD>" name="user_password" autocomplete="off" required /> <input type="submit" name="login" value="Log in" class="pure-button pure-button-primary"/> </fieldset> </form> <a href="register.php">Register new account</a> <file_sep>/menu.php <?php if( isset($_SESSION['user_type']) ){ ?> <div id='cssmenu'> <ul> <li <?php if(isset($_SESSION['page'])){ if($_SESSION['page']=='index') { echo "class='active'"; } } ?> ><a href='index.php'><span>Home</span></a></li> <li <?php if(isset($_SESSION['page'])){ if($_SESSION['page']=='musician') { echo "class='active'"; } } ?> ><a href='index_mus.php'><span>Musicians</span></a></li> <li <?php if(isset($_SESSION['page'])){ if($_SESSION['page']=='student') { echo "class='active'"; } } ?> ><a href='index_stu.php'><span>Students</span></a></li> <li <?php if(isset($_SESSION['page'])){ if($_SESSION['page']=='instrument') { echo "class='active'"; } } ?> ><a href='index_ins.php'><span>Instrument</span></a></li> <li <?php if(isset($_SESSION['page'])){ if($_SESSION['page']=='teaching') { echo "class='active'"; } } ?> class='last'><a href='index_tea.php'><span>Teaching</span></a></li> <?php if($_SESSION['user_type'] == "admin"){ ?> <li <?php if(isset($_SESSION['page'])){ if($_SESSION['page']=='audit') { echo "class='active'"; } } ?> class='last'><a href='index_aud.php'><span>Audit</span></a></li> <?php } ?> </ul> </div> <?php } ?> <file_sep>/views/teaching.php <?php if (isset($teaching)) { if ($teaching->errors) { foreach ($teaching->errors as $error) { echo $error; } } if ($teaching->messages) { foreach ($teaching->messages as $message) { echo $message; } } } ?> <datalist id="student_names"> <?php $teaching->connect(); $sql = "SELECT name, read_level FROM student GROUP BY student_id, read_level HAVING read_level LIKE '%secretary%'"; $result = $teaching->db_connection->query($sql); if( mysqli_num_rows($result) != 0){ while($row = $result->fetch_array() ){ ?> <option value="<?php echo $row['name']; ?>"> <?php } $result->free(); } ?> </datalist> <datalist id="musician_names"> <?php $sql = "SELECT name, read_level FROM musician GROUP BY musician_id, read_level HAVING read_level LIKE '%secretary%'"; $result = $teaching->db_connection->query($sql); if( mysqli_num_rows($result) != 0){ while($row = $result->fetch_array() ){ ?> <option value="<?php echo $row['name']; ?>"> <?php } $result->free(); } ?> </datalist> <datalist id="instrument_names"> <?php $sql = "SELECT name, trans_end FROM instrument WHERE trans_end IS NULL GROUP BY instrument_id"; $result = $teaching->db_connection->query($sql); if( mysqli_num_rows($result) != 0){ while($row = $result->fetch_array() ){ ?> <option value="<?php echo $row['name']; ?>"> <?php } $result->free(); } $teaching->db_connection->close(); ?> </datalist> <table id="table2"> <tr> <td> <?php if ($_SESSION['user_type']=="admin" || $_SESSION['user_type']=="secretary") { ?> <form method="post" action="index_tea.php" name="insertTeachingForm" class="pure-form"> <fieldset id="fieldset"> <legend>Insert new teaching</legend> <input list="student_names" id="stu_name" size="15" class="login_input" type="text" placeholder="Student name" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,30}" autocomplete="off" name="stu_name" required maxlength="30"/> <input list="musician_names" id="mus_name" size="15" class="login_input" type="text" placeholder="Musician name" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,30}" autocomplete="off" name="mus_name" required maxlength="30"/> <input list="instrument_names" id="ins_name" size="15" class="login_input" type="text" placeholder="Instrument name" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,30}" autocomplete="off" name="ins_name" required maxlength="30"/> <input autocomplete="off" type="text" name="validStart" class="tcal" id="validStart" size="14" placeholder="Valid start" required maxlength="12"/> <input autocomplete="off" type="text" name="validEnd" class="tcal" id="validEnd" size="14" placeholder="Valid end" maxlength="12"/> <input type="submit" class="pure-button pure-button-primary" name="insertTeaching" value="Insert" /> </fieldset> </form> <form method="post" action="index_tea.php" name="teachingSqlForm" class="pure-form"> <fieldset id="fieldset"> <legend>Your SQL query</legend> Table name: teaching <br> Fields: teaching_id , student_id , musician_id , instrument_id , valid_start , valid_end <br> <input id="teachingSql" name="teachingSql" type="text" placeHolder="Please insert your desirable SQL script" class="login_input" size="50"/> <input type="submit" class="pure-button pure-button-primary" name="teachingSqlSubmit" value="Exec" /> </fieldset> </form> <?php } ?> <fieldset id="fieldset"> <legend>List of teachings</legend> <div id="overflow"> <table id="table1"> <thead class="fixedHeader1"> <tr> <?php if($_SESSION['user_type']=="musician"){ ?> <th>Student</th> <th>Musician</th> <th>Instrument</th> <?php }else{ ?> <th>ID</th> <th>ID&nbsp;teaching</th> <th>Student</th> <th>Musician</th> <th>Instrument</th> <th>Valid&nbsp;Start</th> <th>Valid&nbsp;End</th> <?php if($_SESSION['user_type']!="student" && $_SESSION['user_type']!="musician"){ ?> <th>Edit</th> <?php } } ?> </tr> </thead> <tbody class="scrollContent1"> <?php $teaching->connect(); if (!$teaching->db_connection->connect_errno) { if(isset($_POST['teachingSqlSubmit']) && $_POST['teachingSql']!=null){ $sql = $_POST['teachingSql']; }else{ if ($_SESSION['user_type']=="student") { $sql = "SELECT DISTINCT t.id, t.teaching_id, t.student_id, t.musician_id, t.instrument_id, i.name as ins_name, s.name as stu_name, m.name as mus_name, t.valid_start, t.valid_end, t.read_level FROM teaching t LEFT JOIN instrument i ON i.instrument_id = t.instrument_id LEFT JOIN student s ON s.student_id = t.student_id LEFT JOIN musician m ON m.musician_id = t.musician_id WHERE t.student_id = '".$_SESSION['user_id']."' HAVING read_level LIKE '%student%' ORDER BY s.name, t.valid_start ASC, t.teaching_id"; }elseif ($_SESSION['user_type']=="musician") { $sql = "SELECT DISTINCT t.id, t.teaching_id, t.student_id, t.musician_id, t.instrument_id, i.name as ins_name, s.name as stu_name, m.name as mus_name, t.valid_start, t.valid_end, t.read_level FROM teaching t LEFT JOIN instrument i ON i.instrument_id = t.instrument_id LEFT JOIN student s ON s.student_id = t.student_id LEFT JOIN musician m ON m.musician_id = t.musician_id WHERE t.musician_id = '".$_SESSION['user_id']."' HAVING read_level LIKE '%student%' ORDER BY s.name, t.valid_start ASC, t.teaching_id"; }elseif ($_SESSION['user_type']=="secretary") { $sql = "SELECT DISTINCT t.id, t.teaching_id, t.student_id, t.musician_id, t.instrument_id, i.name as ins_name, s.name as stu_name, m.name as mus_name, t.valid_start, t.valid_end, t.read_level FROM teaching t LEFT JOIN instrument i ON i.instrument_id = t.instrument_id LEFT JOIN student s ON s.student_id = t.student_id LEFT JOIN musician m ON m.musician_id = t.musician_id HAVING read_level LIKE '%secretary%' ORDER BY s.name, t.valid_start ASC, t.teaching_id"; }else{ $sql = "SELECT DISTINCT t.id, t.teaching_id, t.student_id, t.musician_id, t.instrument_id, i.name as ins_name, s.name as stu_name, m.name as mus_name, t.valid_start, t.valid_end, t.read_level FROM teaching t LEFT JOIN instrument i ON i.instrument_id = t.instrument_id LEFT JOIN student s ON s.student_id = t.student_id LEFT JOIN musician m ON m.musician_id = t.musician_id HAVING read_level LIKE '%admin%' ORDER BY s.name, t.valid_start ASC, t.teaching_id"; } } echo $sql; $result = $teaching->db_connection->query($sql); $even = 1; if( mysqli_num_rows($result) != 0){ while($row = $result->fetch_array() ){ $sql = "SELECT * FROM teaching WHERE teaching_id = ".$row['teaching_id']; $result1 = $teaching->db_connection->query($sql); if( mysqli_num_rows($result1) == 1){ $style = "\"font-weight:bold; color:rgb(0, 120, 231);\""; }else{ $style = ""; } if($even==0){ ?> <tr style=<?php echo $style; ?> > <?php $even=1; }else{ ?> <tr class="even" style=<?php echo $style; ?> > <?php $even=0; } if($_SESSION['user_type']=="musician"){ ?> <td><?php echo $row['stu_name']." (".$row['student_id'].")"; ?></td> <td><?php echo $row['mus_name']." (".$row['musician_id'].")"; ?></td> <td><?php echo $row['ins_name']." (".$row['instrument_id'].")"; ?></td> <?php }else{ ?> <td><?php echo $row['id']; ?></td> <td><?php echo $row['teaching_id']; ?></td> <td><?php echo $row['stu_name']." (".$row['student_id'].")"; ?></td> <td><?php echo $row['mus_name']." (".$row['musician_id'].")"; ?></td> <td><?php echo $row['ins_name']." (".$row['instrument_id'].")"; ?></td> <td><?php echo $teaching->displayDate($row['valid_start'], "valid"); ?></td> <td><?php echo $teaching->displayDate($row['valid_end'], "valid"); ?></td> <?php if( mysqli_num_rows($result1) == 1 && ($_SESSION['user_type']!="musician" && $_SESSION['user_type']!="student") ){ ?> <td><a class="fancybox fancybox.iframe" href="teaching_info.php?tea_id=<?php echo $row['teaching_id']; ?>">Edit</a></td> <?php } } $result1->free();?> </tr> <?php } $result->free(); } $teaching->db_connection->close(); }else{ } ?> </tbody> </table> </div> </fieldset> </td> </tr> </table> <file_sep>/register.php <?php if (version_compare(PHP_VERSION, '5.3.7', '<')) { exit("Sorry, Simple PHP Login does not run on a PHP version smaller than 5.3.7 !"); } else if (version_compare(PHP_VERSION, '5.5.0', '<')) { require_once("libraries/password_compatibility_library.php"); } require_once("config/db.php"); require_once("classes/Login.php"); $login = new Login(); require_once("classes/Registration.php"); $registration = new Registration(); ?> <html> <head> <title>Temporal database - Register</title> <meta charset='utf-8'> <link rel="stylesheet" href="css/buttons.css"> <link rel="stylesheet" href="css/forms.css"> <link rel="stylesheet" href="css/tables.css"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <table id="mainTable"> <tr> <td width="280px"> <?php if ($login->isUserLoggedIn() == true) { include("views/logged_in.php"); } else { include("views/register.php"); } ?> </td> </tr> </table> </body> </html> <file_sep>/classes/Registration.php <?php class Registration{ private $db_connection = null; public $errors = array(); public $messages = array(); public function __construct(){ if (isset($_POST["register"])) { $this->registerNewUser(); } } private function registerNewUser(){ $pattern = '/select|union|insert|delete|or/i'; if (empty($_POST['user_name'])) { $this->errors[] = "Empty Username"; } elseif (empty($_POST['user_password_new']) || empty($_POST['user_password_repeat'])) { $this->errors[] = "Empty Password"; } elseif ($_POST['user_password_new'] !== $_POST['user_password_repeat']) { $this->errors[] = "Password and password repeat are not the same"; } elseif (strlen($_POST['user_password_new']) < 4) { $this->errors[] = "Password has a minimum length of 4 characters"; } elseif (strlen($_POST['user_name']) > 64 || strlen($_POST['user_name']) < 2) { $this->errors[] = "Username cannot be shorter than 2 or longer than 64 characters"; } elseif (!preg_match('/^[a-z\d]{2,64}$/i', $_POST['user_name'])) { $this->errors[] = "Username does not fit the name scheme: only a-Z and numbers are allowed, 2 to 64 characters"; } elseif(preg_match($pattern, $_POST['user_name'], $matches, PREG_OFFSET_CAPTURE) || preg_match($pattern, $_POST['user_password_new'], $matches, PREG_OFFSET_CAPTURE) || preg_match($pattern, $_POST['user_password_repeat'], $matches, PREG_OFFSET_CAPTURE) ){ $this->errors[] = "TRY HARDER!!!!"; } elseif (!empty($_POST['user_name']) && strlen($_POST['user_name']) <= 64 && strlen($_POST['user_name']) >= 2 && preg_match('/^[a-z\d]{2,64}$/i', $_POST['user_name']) && !empty($_POST['user_password_new']) && !empty($_POST['user_password_repeat']) && ($_POST['user_password_new'] === $_POST['user_password_repeat']) ) { $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$this->db_connection->set_charset("utf8")) { $this->errors[] = $this->db_connection->error; } if (!$this->db_connection->connect_errno) { $user_name = $this->db_connection->real_escape_string(strip_tags($_POST['user_name'], ENT_QUOTES)); $user_password = $_POST['<PASSWORD>_password_new']; $user_password_hash = password_hash($user_password, PASSWORD_DEFAULT); $sql = "SELECT * FROM user WHERE name = '" . $user_name . "';"; $query_check_user_name = $this->db_connection->query($sql); if ($query_check_user_name->num_rows == 1) { $this->errors[] = "Sorry, that username is already taken."; } else { $sql = "INSERT INTO user (name, password, type, is_enable) VALUES('" . $user_name . "', '" . $user_password_hash . "', '".$_POST['type']."', 'true');"; $query_new_user_insert = $this->db_connection->query($sql); if ($query_new_user_insert) { $this->messages[] = "Your account has been created successfully. You can now log in."; } else { $this->errors[] = "Sorry, your registration failed. Please go back and try again."; } $sql = "INSERT INTO audit (id, user_id, table_name, query, trans_time) VALUES (NULL, '".$this->db_connection->insert_id."', 'register', 'user registration: ".$user_name."', CURRENT_TIMESTAMP);"; $this->db_connection->query($sql); } } else { $this->errors[] = "Sorry, no database connection."; } } else { $this->errors[] = "An unknown error occurred."; } } } <file_sep>/views/register.php <?php if (isset($registration)) { if ($registration->errors) { foreach ($registration->errors as $error) { echo $error; } } if ($registration->messages) { foreach ($registration->messages as $message) { echo $message; } } } ?> <form method="post" action="register.php" name="registerform" class="pure-form pure-form-stacked"> <fieldset> <legend>Register</legend> <input id="login_input_username" class="login_input" type="text" placeholder="User name" pattern="[a-zA-Z0-9]{2,64}" name="user_name" required maxlength="20" /> <input id="login_input_password_new" class="login_input" type="<PASSWORD>" name="<PASSWORD>_password_new" pattern=".{4,}" required autocomplete="off" placeholder="<PASSWORD>" /> <input id="login_input_password_repeat" class="login_input" type="<PASSWORD>" name="user_password_repeat" pattern=".{4,}" required autocomplete="off" placeholder="<PASSWORD>" /> <select id="type" name="type"> <option value="1"> admin </option> <option value="2" selected> secretary </option> </select> <input type="submit" class="pure-button pure-button-primary" name="register" value="Register" /> </fieldset> </form> <a href="index.php">Back to Login Page</a> <file_sep>/classes/Teaching.php <?php class Teaching{ public $db_connection = null; public $errors = array(); public $messages = array(); public function __construct(){ if (isset($_POST["editTeaching"])) { $this->editTeaching(); } if (isset($_POST["insertTeaching"])) { $this->insertTeaching(); } if (isset($_POST["findMucisianForm"])) { $this->findMucisianForm(); } } public function connect(){ $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$this->db_connection->set_charset("utf8")) { $this->errors[] = $this->db_connection->error; } } public function findMucisianForm(){ $this->connect(); if (!$this->db_connection->connect_errno) { $parts = explode ('/' , $_POST['findDateMusician']); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $findDate=$day.$month.$year."000000"; $sql = "SELECT * FROM musician WHERE '".$findDate."' BETWEEN valid_start AND IFNULL(valid_end, '2099-12-31 00:00:00') AND trans_end IS NULL AND musician_id = '".$_GET['mus_id']."' ORDER BY valid_start DESC LIMIT 1"; return $sql; } else { $this->errors[] = "Database connection problem: ".$this->db_connection->connect_error; } } private function editTeaching(){ $date = date('Y-m-d H:i:s', time()); if (empty($_POST['new_validEnd'])) { $this->errors[] = "There are missing a lot information."; } else { $this->connect(); if (!$this->db_connection->connect_errno) { $sql = "SELECT * FROM teaching WHERE teaching_id = ".$_POST['tea_id']; $result = $this->db_connection->query($sql); if( mysqli_num_rows($result) == 1){ $row = $result->fetch_array(); $sql = "UPDATE teaching SET read_level = 'admin' WHERE id = ".$row['id']; $this->db_connection->query($sql); $parts = explode ('/' , $_POST['new_validEnd']); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $new_validEnd=$day.$month.$year."000000"; $sql = "INSERT INTO teaching (id, teaching_id, student_id, musician_id, instrument_id, valid_start, valid_end, read_level) VALUES (NULL, '".$row['teaching_id']."', '".$row['student_id']."', '".$row['musician_id']."', '".$row['instrument_id']."', '".$row['valid_start']."', '".$new_validEnd."', 'admin');"; $this->db_connection->query($sql); $result->free(); $this->db_connection->close(); }else{ $this->errors[] = "You can not change again the valid end."; } } else { $this->errors[] = "Database connection problem: ".$this->db_connection->connect_error; } } } private function insertTeaching(){ if (empty($_POST['stu_name']) && empty($_POST['mus_name']) && empty($_POST['ins_name']) ) { $this->errors[] = "Some fields are empty."; } else { $this->connect(); if (!$this->db_connection->connect_errno) { $ok1 = 0; $ok2 = 0; $ok3 = 0; $ins_name = $this->db_connection->real_escape_string($_POST['ins_name']); $stu_name = $this->db_connection->real_escape_string($_POST['stu_name']); $mus_name = $this->db_connection->real_escape_string($_POST['mus_name']); $sql1 = "SELECT instrument_id, name FROM instrument WHERE name = '".$ins_name."' GROUP BY instrument_id"; $sql2 = "SELECT student_id, name FROM student WHERE name = '".$stu_name."' GROUP BY student_id"; $sql3 = "SELECT musician_id, name FROM musician WHERE name = '".$mus_name."' GROUP BY musician_id"; $result1 = $this->db_connection->query($sql1); if( mysqli_num_rows($result1) != 0){ $ok1 = 1; $row = $result1->fetch_array(); $ins_id = $row['instrument_id']; $result1->free(); } $result2 = $this->db_connection->query($sql2); if( mysqli_num_rows($result2) != 0){ $ok2 = 1; $row = $result2->fetch_array(); $stu_id = $row['student_id']; $result2->free(); } $result3 = $this->db_connection->query($sql3); if( mysqli_num_rows($result3) != 0){ $ok3 = 1; $row = $result3->fetch_array(); $mus_id = $row['musician_id']; $result3->free(); } if($ok1==1 && $ok2==1 && $ok3==1){ $parts = explode ('/' , $_POST['validStart']); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validStart=$day.$month.$year."000000"; if($_POST['validEnd']!=""){ $parts = explode ('/' , $_POST['validEnd']); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validEnd=$day.$month.$year."000000"; }else{ $validEnd = ""; } $sql = "SELECT MAX(teaching_id) AS maxTeachID FROM teaching"; $result1 = $this->db_connection->query($sql); if( mysqli_num_rows($result1) != 0){ $row1 = $result1->fetch_array(); $nextTeachID = $row1['maxTeachID']; $result1->free(); $nextTeachID++; }else{ $nextTeachID = 0; } if($validEnd==""){ $sql = "INSERT INTO teaching (id, teaching_id, student_id, musician_id, instrument_id, valid_start, valid_end, read_level) VALUES (NULL, '".$nextTeachID."', '".$stu_id."', '".$mus_id."', '".$ins_id."', '".$validStart."', NULL, 'admin,secretary,student');"; }else{ $sql = "INSERT INTO teaching (id, teaching_id, student_id, musician_id, instrument_id, valid_start, valid_end, read_level) VALUES (NULL, '".$nextTeachID."', '".$stu_id."', '".$mus_id."', '".$ins_id."', '".$validStart."', '".$validEnd."', 'admin');"; } $result_insert_musician = $this->db_connection->query($sql); if ($result_insert_musician) { $this->messages[] = "New teaching has id: " . $this->db_connection->insert_id; }else{ $this->errors[] = "Error: " . $sql . "<br>" . mysqli_error($this->db_connection); } $sql = "INSERT INTO audit (id, user_id, table_name, query, trans_time) VALUES (NULL, '".$_SESSION['user_id']."', 'teaching', 'insert new teaching for student: ".$stu_id."', CURRENT_TIMESTAMP);"; $this->db_connection->query($sql); $this->db_connection->close(); } else { $this->errors[] = "The names you have given are incorrect!"; } } else { $this->errors[] = "Database connection problem: ".$this->db_connection->connect_error; } } } public function displayDate($date, $type){ if($date!=""){ if($type=="valid"){ $parts1 = explode (' ' , $date); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; return $day."/".$month."/".$year; }else{ $parts1 = explode (' ' , $date); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $parts = explode (':' , $parts1[1]); $sec=$parts[2]; $min=$parts[1]; $hour=$parts[0]; return $day."/".$month."/".$year."&nbsp;".$hour.":".$min.":".$sec; } } } } <file_sep>/musician_info.php <?php // python sqlmap.py -u "http://127.0.0.1/biTempMysql/musician_info.php?id=70&mus_id=2" --dbs --threads=5 --eta --batch --is-dba -v 2 --technique=BEUST -t "/home/user/Έγγραφα/aa.txt" --fresh-queries > "/home/user/Έγγραφα/after.txt" // python sqlmap.py -u "http://127.0.0.1/biTempMysql/musician_info.php?id=70&mus_id=2" --threads=5 --batch --technique=BEUST --tables -D conservatory --fresh-queries > "/home/user/Έγγραφα/after_tables.txt" // python sqlmap.py -u "http://127.0.0.1/biTempMysql/musician_info.php?id=70&mus_id=2" --threads=5 --batch --technique=BEUST --columns -D conservatory -T user --fresh-queries > "/home/user/Έγγραφα/after_table_user_fields.txt" // python sqlmap.py -u "http://127.0.0.1/biTempMysql/musician_info.php?id=70&mus_id=2" --threads=5 --batch --technique=BEUST --dump -D conservatory -T user --fresh-queries > "/home/user/Έγγραφα/after_table_user_dump.txt" // print_r($matches); // http://regex101.com/ // http://www.unixwiz.net/techtips/sql-injection.html // http://hakipedia.com/index.php/SQL_Injection session_start(); require_once("config/db.php"); require_once("classes/Musician.php"); $musician = new Musician(); if (isset($musician)) { if ($musician->errors) { foreach ($musician->errors as $error) { echo $error; } } if ($musician->messages) { foreach ($musician->messages as $message) { echo $message; } } } if(isset($_GET['id'])){ $pattern = '/select|union|insert|delete|or/i'; if(preg_match($pattern, $_GET['mus_id'], $matches, PREG_OFFSET_CAPTURE) || preg_match($pattern, $_GET['id'], $matches, PREG_OFFSET_CAPTURE) ){ $this->errors[] = "TRY HARDER!!!!"; }else{ $mus_id = $_GET['mus_id']; $id = $_GET['id']; $musician->connect(); if (!$musician->db_connection->connect_errno) { $sql = "SELECT * FROM musician WHERE id = '".$_GET['id']."';"; $result = $musician->db_connection->query($sql); $row = $result->fetch_array(); $id_musician = $row['musician_id']; $name = $row['name']; $telephone = $row['telephone']; if($row['valid_start']!=null){ $parts1 = explode (' ' , $row['valid_start']); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validStart = $day."/".$month."/".$year; } if($row['valid_end']!=null){ $parts1 = explode (' ' , $row['valid_end']); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validEnd = $day."/".$month."/".$year; } $result->free(); $musician->db_connection->close(); } } } ?> <html> <head> <link rel="stylesheet" href="css/buttons.css"> <link rel="stylesheet" href="css/forms.css"> <link rel="stylesheet" href="css/tables.css"> <link rel="stylesheet" href="css/styles.css"> <link rel="stylesheet" type="text/css" href="css/tcal.css" /> <script type="text/javascript" src="js/tcal.js"></script> </head> <body> <table id="table2"> <?php if ($_SESSION['user_type']=="admin" || $_SESSION['user_type']=="secretary") { ?> <tr> <td> <form method="post" action="musician_info.php?id=<?php echo $row['id']; ?>&mus_id=<?php echo $row['musician_id']; ?>" name="editMucisianForm" class="pure-form"> <fieldset id="fieldset"> <legend>Set valid end for musician</legend> <input value="<?php if(isset($_GET['id'])){ echo $mus_id; } ?>" id="mus_id" size="1" type="hidden" autocomplete="off" name="mus_id" maxlength="12"/> <input value="<?php if(isset($_GET['id'])){ echo $id; } ?>" id="id" size="1" type="hidden" autocomplete="off" name="id" maxlength="12"/> <input disabled value="<?php if(isset($_GET['id'])){ echo $mus_id; } ?>" size="1" type="text" autocomplete="off" maxlength="12"/> <input disabled value="<?php if(isset($_GET['id'])){ echo $name; } ?>" size="14" type="text" autocomplete="off" maxlength="30"/> <input disabled value="<?php if(isset($_GET['id'])){ echo $telephone; } ?>" size="14" type="text" autocomplete="off" maxlength="12"/> <input disabled value="<?php if(isset($_GET['id'])){ echo $validStart; } ?>" autocomplete="off" type="text" class="tcal" size="14" placeholder="Valid start" maxlength="12"/> <input value="<?php if(isset($validEnd)){ echo $validEnd; } ?>" autocomplete="off" type="text" name="validEnd" class="tcal" id="validEnd" size="14" placeholder="Valid end"/> </fieldset> <fieldset id="fieldset"> <legend>Insert new info about musician</legend> <input disabled value="<?php if(isset($_GET['id'])){ echo $mus_id; } ?>" size="1" type="text" autocomplete="off" maxlength="12"/> <input disabled value="<?php if(isset($_GET['id'])){ echo $name; } ?>" size="14" type="text" autocomplete="off" maxlength="30"/> <input value="" id="new_telephone" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,12}" size="14" type="text" name="new_telephone" autocomplete="off" placeholder="New Telephone" maxlength="12"/> <input value="" autocomplete="off" type="text" name="new_validStart" class="tcal" id="new_validStart" size="14" placeholder="Valid start" maxlength="12"/> <input value="" autocomplete="off" type="text" name="new_validEnd" class="tcal" id="new_validEnd" size="14" placeholder="Valid end" maxlength="12"/> </fieldset> <p align="right"> <input type="submit" class="pure-button pure-button-primary" name="editMusician" value="Edit / Insert" /> </p> </form> <form method="post" action="musician_info.php?id=<?php echo $row['id']; ?>&mus_id=<?php echo $row['musician_id']; ?>&find=1" name="findMucisianForm" class="pure-form"> <fieldset id="fieldset"> <legend>Find telephone number</legend> <input autocomplete="off" type="text" name="findDateMusician" class="tcal" id="findDateMusician" size="30" placeholder="Date" maxlength="12"/> <input type="submit" class="pure-button pure-button-primary" name="findMusician" value="Find" /> </fieldset> </form> <form method="post" action="" onClick="window.location.reload()"> <p align="right"> <input type="button" value="Refresh page" class="pure-button pure-button-primary"> </p> </form> <fieldset id="fieldset"> <legend>Results of musician</legend> <div> <table id="table1"> <tr> <th>ID</th> <th>ID&nbsp;musician</th> <th>Name</th> <th>Telephone</th> <th>Valid&nbsp;Start</th> <th>Valid&nbsp;End</th> <th>Trans&nbsp;Start</th> <th>Trans&nbsp;End</th> </tr> <?php $musician->connect(); if (!$musician->db_connection->connect_errno) { if ($_SESSION['user_type']=="admin") { $sql = "SELECT * FROM musician WHERE musician_id = '".$mus_id."' HAVING read_level LIKE '%admin%' ORDER BY valid_start, trans_end DESC"; }elseif ($_SESSION['user_type']=="student") { $sql = "SELECT * FROM musician WHERE musician_id = '".$mus_id."' HAVING read_level LIKE '%student%' ORDER BY valid_start, trans_end DESC"; }else{ $sql = "SELECT * FROM musician WHERE musician_id = '".$mus_id."' HAVING read_level LIKE '%secretary%' ORDER BY valid_start, trans_end DESC"; } if(isset($_GET['find']) && $_POST['findDateMusician']!=""){ $sql = $musician->findMucisianForm(); } echo $sql; $result = $musician->db_connection->query($sql); $even = 0; while( $row = $result->fetch_array() ){ if($row['valid_end']==null && $row['trans_end']==null){ $style = "\"font-weight:bold; color:rgb(0, 120, 231);\""; }else{ $style = ""; } if($even==0){ ?> <tr style=<?php echo $style; ?>> <?php $even=1; }else{ ?> <tr class="even" style=<?php echo $style; ?>> <?php $even=0; }?> <td><?php echo $row['id']; ?></td> <td><?php echo $row['musician_id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['telephone']; ?></td> <td><?php echo $musician->displayDate($row['valid_start'], "valid"); ?></td> <td><?php echo $musician->displayDate($row['valid_end'], "valid"); ?></td> <td><?php echo $musician->displayDate($row['trans_start'], "trans"); ?></td> <td><?php echo $musician->displayDate($row['trans_end'], "trans"); ?></td> </tr> <?php } $result->free(); $musician->db_connection->close(); }else{ } ?> </table> </div> </fieldset> </td> </tr> <?php }else{ echo "You have no authority to be here!!!"; } ?> </table> </body> </html> <file_sep>/README.md # bitemporal Mysql example 1. **ref:** [1](www) <file_sep>/teaching_info.php <?php session_start(); require_once("config/db.php"); require_once("classes/Teaching.php"); $teaching = new Teaching(); if (isset($teaching)) { if ($teaching->errors) { foreach ($teaching->errors as $error) { echo $error; } } if ($teaching->messages) { foreach ($teaching->messages as $message) { echo $message; } } } if(isset($_GET['tea_id'])){ $pattern = '/select|union|insert|delete|or/i'; if(preg_match($pattern, $_GET['tea_id'], $matches, PREG_OFFSET_CAPTURE) && preg_match($pattern, $_GET['id'], $matches, PREG_OFFSET_CAPTURE) ){ $this->errors[] = "TRY HARDER!!!!"; }else{ $tea_id = $_GET['tea_id']; $teaching->connect(); if (!$teaching->db_connection->connect_errno) { $sql = "SELECT * FROM teaching WHERE teaching_id = '".$_GET['tea_id']."';"; $result = $teaching->db_connection->query($sql); $row = $result->fetch_array(); $teaching_id = $row['teaching_id']; $student_id = $row['student_id']; $musician_id = $row['musician_id']; $instrument_id = $row['instrument_id']; $valid_start = $row['valid_start']; $valid_end = $row['valid_end']; if($row['valid_start']!=null){ $parts1 = explode (' ' , $row['valid_start']); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validStart = $day."/".$month."/".$year; } if($row['valid_end']!=null){ $parts1 = explode (' ' , $row['valid_end']); $parts = explode ('-' , $parts1[0]); $day=$parts[2]; $month=$parts[1]; $year=$parts[0]; $validEnd = $day."/".$month."/".$year; } $result->free(); $teaching->db_connection->close(); } } } $teaching->connect(); $sql = "SELECT name FROM student WHERE student_id = '".$student_id."';"; $result = $teaching->db_connection->query($sql); if( mysqli_num_rows($result) != 0){ $row = $result->fetch_array(); $stu_name = $row['name']; $result->free(); } $sql = "SELECT name FROM musician WHERE musician_id = '".$musician_id."';"; $result = $teaching->db_connection->query($sql); if( mysqli_num_rows($result) != 0){ $row = $result->fetch_array(); $mus_name = $row['name']; $result->free(); } $sql = "SELECT name FROM instrument WHERE instrument_id = '".$instrument_id."';"; $result = $teaching->db_connection->query($sql); if( mysqli_num_rows($result) != 0){ $row = $result->fetch_array(); $ins_name = $row['name']; $result->free(); } $teaching->db_connection->close(); ?> <html> <head> <link rel="stylesheet" href="css/buttons.css"> <link rel="stylesheet" href="css/forms.css"> <link rel="stylesheet" href="css/tables.css"> <link rel="stylesheet" href="css/styles.css"> <link rel="stylesheet" type="text/css" href="css/tcal.css" /> <script type="text/javascript" src="js/tcal.js"></script> </head> <body> <table id="table2"> <?php if ($_SESSION['user_type']=="admin" || $_SESSION['user_type']=="secretary") { ?> <tr> <td> <form method="post" action="teaching_info.php?tea_id=<?php echo $tea_id; ?>" name="editStudentForm" class="pure-form"> <fieldset id="fieldset"> <legend>Set valid end for teaching</legend> <input value="<?php if(isset($_GET['tea_id'])){ echo $tea_id; } ?>" id="tea_id" size="1" type="hidden" autocomplete="off" name="tea_id" maxlength="12"/> <input disabled value="<?php if(isset($_GET['tea_id'])){ echo $stu_name; } ?>" list="student_names" id="stu_name" size="15" class="login_input" type="text" placeholder="Student name" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,30}" autocomplete="off" name="stu_name" required maxlength="30"/> <input disabled value="<?php if(isset($_GET['tea_id'])){ echo $mus_name; } ?>" list="musician_names" id="mus_name" size="15" class="login_input" type="text" placeholder="Musician name" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,30}" autocomplete="off" name="mus_name" required maxlength="30"/> <input disabled value="<?php if(isset($_GET['tea_id'])){ echo $ins_name; } ?>" list="instrument_names" id="ins_name" size="15" class="login_input" type="text" placeholder="Instrument name" pattern="[a-zA-Z0-9\s\u00a1-\uffff]{2,30}" autocomplete="off" name="ins_name" required maxlength="30"/> <input disabled value="<?php if(isset($_GET['tea_id'])){ echo $validStart; } ?>" autocomplete="off" type="text" name="validStart" class="tcal" id="validStart" size="14" placeholder="Valid start" required maxlength="12"/> <input value="<?php if(isset($validEnd)){ echo $validEnd; } ?>" autocomplete="off" type="text" name="new_validEnd" class="tcal" id="new_validEnd" size="14" placeholder="Valid end"/> </fieldset> <p align="right"> <input type="submit" class="pure-button pure-button-primary" name="editTeaching" value="Edit" /> </p> </form> </td> </tr> <?php }else{ echo "You have no authority to be here!!!"; } ?> </table> </body> </html>
3485ee7c62689c615dc59447c77a96c0ed01289b
[ "Markdown", "SQL", "PHP" ]
20
PHP
akeske/biMysql
eb43f17f1858fbd5da2cc64ca2303ccd6799500c
10d4b0c01397c2c33b00f16448fbd615a8079905
refs/heads/master
<repo_name>Beim/wikipediaSearch<file_sep>/README.md # wikipediaSearch [搜索维基百科条目](http://htmlpreview.github.io/?https://github.com/Beim/wikipediaSearch/blob/master/index.html) <file_sep>/index.js let rce = React.createElement.bind() let JSON_CALLBACK = function(res){ let inputTag = document.getElementById('dataInput') inputTag.value = JSON.stringify(res.query.search) let buttonTag = document.getElementById('dataButton') buttonTag.click() } let myTop = React.createClass({ getInitialState: function(){ return { svalue: '' } }, svalueHandler: function(e){ this.setState({svalue: e.target.value}) }, search: function(){ let url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=' + this.state.svalue + '&callback=JSON_CALLBACK' let scriptTag = document.createElement('script') scriptTag.setAttribute('src', url) document.body.appendChild(scriptTag) }, render: function(){ return ( rce('div', null, rce('div', {'className': 'form-group'}, rce('div', {'className': 'col-xs-12'}, rce('a', {'href': 'https://en.wikipedia.org/wiki/Special:Random', 'target': '_blank'}, 'Click here for a random article ') ), rce('div', {'className': 'col-xs-8'}, rce('input', {'type': 'text', 'className': 'form-control', 'value': this.state.svalue, 'onChange': this.svalueHandler}) ), rce('div', {'className': 'col-xs-4'}, rce('button', {'type': 'button', 'className': 'btn btn-primary', 'onClick': this.search}, 'search') ) ) ) ) } }) let myList = React.createClass({ getInitialState: function(){ return{ } }, newPage: function(e){ let target = e.target while(target.tagName !== 'DIV'){ target = target.parentNode } let title = target.attributes['data-title'].value window.open('https://en.wikipedia.org/wiki/'+title) }, render: function(){ let data = this.props.data let list = data.map((value, index) => { return rce('div', {'className': 'item', 'key': 'listitem' + index, 'onClick': this.newPage, 'data-title': value.title}, rce('p', {'className': 'title'}, rce('b', null, value.title) ), rce('p', {'className': 'snip', 'dangerouslySetInnerHTML': {'__html': value.snippet}}) ) }) return ( rce('div', null, rce('div', null, '.'), list ) ) } }) let total = React.createClass({ getInitialState: function(){ return{ data: [] } }, dataHandler: function(e){ let inputTag = document.getElementById('dataInput') let data = JSON.parse(inputTag.value) this.setState({data: data}) }, render: function(){ return ( rce('div', null, rce('input', {'onChange': this.dataHandler, 'id': 'dataInput', 'style': {'display': 'none'}}), rce('button', {'onClick': this.dataHandler, 'id': 'dataButton', 'style': {'display': 'none'}}), rce(myTop, null), rce(myList, {'data': this.state.data}) ) ) } }) ReactDOM.render(rce(total,null), document.getElementById('container'))
2a15a175387db881ba929d38c9e7500761ffe7e7
[ "Markdown", "JavaScript" ]
2
Markdown
Beim/wikipediaSearch
dd5d45342df9e394cb14cf1e31846899d496849d
5808fba97ae7799553125f32bfbee9ac58524ff7
refs/heads/main
<repo_name>VelveteenClaymore/scatterplot-with-heatmap-and-proportional-sizing<file_sep>/main.py # This is an attempt to make a program that adjusts the colors of scatter plots # such that the values of the output have colors which line up with the colormap. # For example, if red represents high values and blue represents low values, # then, the dots near the top of the plot will be redder than the dots at the bottom. import matplotlib.pyplot as plt import numpy as np output_count = 100 # Need this as a global variable to run smoother. x = np.arange(0, output_count) y = np.random.randint(100, size=output_count) # Make a colors array to pull values of the colormap from # this array needs to have numerical values to represent the # values of the color map. colors = np.arange(0, 100) final_colors = np.array([]) # Much like the colors array, the sizes array is determined by the y-value it receives. sizes = np.arange(0, 100) # 100 is the max because y's max is also 100. final_sizes = np.array([]) def color_sorter(num): # Value of output = its value on the colormap. # This let's us have dynamic coloring. # This constrains the y-axis to be 100 at most since the colormap # only goes to 100. return colors[num] def size_sorter(num): # Literally just scales it to its own value. # Allows for dynamic sizing. return sizes[num] # Final_colors is iterated through each iteration. The update is adding a value as # determined by the color picker function. The current iteration of y's value is # judged via the logic and returns the proper color. for element in y: final_colors = np.append(final_colors, color_sorter(element)) for element in y: final_sizes = np.append(final_sizes, 10 * size_sorter(element)) # The 10 is a random scalar to make the proportions bigger. plt.scatter(x, y, s=final_sizes, c=final_colors, cmap='CMRmap', alpha=0.5) plt.show() <file_sep>/README.md # scatterplot-with-heatmap-and-proportional-sizing Using the matplotlib Python module to create a dynamic scatter plot.
8d310b46a4a2730e27340e748c5435e58954bdbe
[ "Markdown", "Python" ]
2
Python
VelveteenClaymore/scatterplot-with-heatmap-and-proportional-sizing
e08443011eff1e7017d71d005fdd4d023162c6fd
179203be6d917e7fbb7d999f460e3e3a550b67ac
refs/heads/master
<file_sep><?php namespace App\Events; use App\Events\Event; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Storage; class CreateFileToDB extends Event { use SerializesModels; private $fileName; /** * @return mixed */ public function getFileName() { return $this->fileName; } /** * @return mixed */ public function getDataJSON() { return $this->dataJSON; } private $dataJSON; /** * Create a new event instance. * * @return void */ function __construct($fileName, $dataJSON) { $this->fileName = $fileName; $this->dataJSON = $dataJSON; } public function createFile($fileName, $dataJSON){ Storage::put($fileName, $dataJSON); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Zizaco\Entrust\EntrustRole; class Role extends EntrustRole { use SoftDeletes; /** * @var array */ protected $dates = ['deleted_at']; /** * Save role Pivot * @param $rolesInput * @return array */ public static function prepareRolesForSave($rolesInput){ $roles = static::all(); $prepareRoles = []; foreach($rolesInput as $roleId){ array_walk($roles, function(&$value) use ($roleId, &$prepareRoles){ if($value = (int) $roleId) { $prepareRoles[] = $roleId; } }); } return $prepareRoles; } /** * Display role Pivot * @param $roles * @return array */ public static function prepareRolesForDisplay($roles){ $prepareRoles = static::all()->toArray(); foreach($roles as $role) { array_walk($prepareRoles, function(&$value) use(&$role){ if($role->name == $value['name']) $value['checked'] = true; }); } return $prepareRoles; } } <file_sep><?php /** * Created by PhpStorm. * User: ron * Date: 30/03/2015 * Time: 12:40 */ namespace App\Impl\Repository\User; use App\Impl\Repository\Repository; interface UserInterface extends Repository { /** * Save data * @param $request * @param $rolesInput * @return mixed */ public function save($request, $rolesInput); /** * Check email exists * @param $email * @return mixed */ public function checkEmail($email); /** * check edit email exists * @param $id * @param $email * @return mixed */ public function checkEditEmail($id, $email); /** * @param $id * @return mixed */ public function getUserRole($id); /** * Eloquent wherein * @param $column * @param array $data * @return mixed */ public function whereIn($column,array $data); /** * Eloquent restore * @param $id * @return mixed */ public function restore($id); /** * restore multi record * @param $column * @param array $ids * @return mixed */ public function restoreMultiRecord($column, array $ids); /** * Eloquent paginate * @param $adj * @param array $params * @return mixed */ public function paginate($adj, array $params); /** * Search data * @param $optionDisplay * @param $search * @param $adj * @param array $params * @return mixed */ public function search($optionDisplay, $search, $adj, array $params); /** * sort Role in users * @param $sort * @return mixed */ // public function sortPivotRoles($sort); }<file_sep><?php namespace App\Models; use bar\baz\source_with_namespace; use Illuminate\Database\Eloquent\Model; use Zizaco\Entrust\EntrustPermission; use Illuminate\Database\Eloquent\SoftDeletes; class Permission extends EntrustPermission { use SoftDeletes; protected $dates = ['deleted_at']; public static function preparePermissionsForSave($permissionsInput){ //$permissions = $this->all()->toArray(); $permissions = self::all()->toArray(); $preparePermission = []; foreach($permissionsInput as $key => $permission){ array_walk($permissions, function(&$value) use (&$permission, &$preparePermission, &$key){ if($permission == (int) $value['id']) { $preparePermission[] = $permission; }elseif($key == (int) $value['id'] && $permission == 'on' ) { $preparePermission[] = $key; } }); } return $preparePermission; } public static function preparePermissionsForDisplay($permissions){ $preparePermissions = self::all()->toArray(); foreach($permissions as $permission){ array_walk($preparePermissions, function(&$value) use (&$permission){ if($permission->name == $value['name']){ $value['checked'] = true; } }); } return $preparePermissions; } } <file_sep><?php namespace App\Impl\Flash; /** * Created by PhpStorm. * User: ron * Date: 30/03/2015 * Time: 14:01 */ use Illuminate\Session\Store as Session; class FlashNotifier { /** * Session * @var $session */ protected $session; public function __construct(Session $session){ $this->session = $session; } public function success($key, $message){ $this->message($key, $message, 'success'); } public function error($key, $message){ $this->message($key, $message, 'danger'); } public function message($key, $message, $level = 'info'){ $this->session->flash($key, $message); $this->session->flash('flash.level', $level); } }<file_sep><?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. | */ /** * pattern Route */ Route::pattern('id', '[\d]+'); /**-------------------------- * Role Route * -------------------------- */ Route::group(['namespace' => 'Admin', 'prefix' => 'admin', 'middleware' => 'auth'], function() { /* * Admin Route */ get('/', 'AdminsController@index'); /* * Role Route */ get('role', ['as' => 'role', 'uses' => 'AdminRolesController@index']); get('role/create', 'AdminRolesController@getCreate'); get('role/edit/{id}', 'AdminRolesController@getEdit'); get('role/delete/{id}', 'AdminRolesController@delete'); get('role/restore/{id}', 'AdminRolesController@restore'); post('role/checkname', 'AdminRolesController@checkName'); post('role', 'AdminRolesController@postIndex'); post('role/create', 'AdminRolesController@postCreate'); post('role/edit', 'AdminRolesController@postEdit'); /* * Permission Route */ get('permission', ['as' => 'permission', 'uses' => 'PermissionsController@index']); get('permission/create', 'PermissionsController@getCreate'); get('permission/edit/{id}', 'PermissionsController@getEdit'); get('permission/delete/{id}', 'PermissionsController@getDelete'); get('permission/restore/{id}', 'PermissionsController@restore'); post('permission', 'PermissionsController@postIndex'); post('permission/create', 'PermissionsController@postCreate'); post('permission/edit', 'PermissionsController@postEdit'); post('permission/checkname', 'PermissionsController@checkName'); /* * User Route */ get('users', ['as' => 'admin.users', 'uses' => 'UsersController@index']); get('users/create', 'UsersController@getCreate'); get('users/edit/{id}', 'UsersController@getEdit'); get('users/delete/{id}', 'UsersController@delete'); get('users/restore/{id}', 'UsersController@restore'); get('users/checkEmail', 'UsersController@checkEmail'); get('users/checkEditEmail', 'UsersController@checkEditEmail'); get('users/{id}', 'UsersController@test'); post('users/create', 'UsersController@postCreate'); post('users/edit', 'UsersController@postEdit'); post('users', 'UsersController@postIndex'); }); get('test', function(\Illuminate\Http\Request $request){ $user = \App\Models\User::find(1); dd($user->ability(['admin'], ['test']), array_get($request->route()->getAction(), 'any', false)); }); Route::get('home', 'HomeController@index'); get('/', ['uses' =>'HomeController@index', 'permission' => 'temp']); Route::controllers([ 'auth' => 'Auth\AuthController', 'password' => '<PASSWORD>', ]); /** * Entrust Filter */ /*\Entrust::routeNeedsRole('admin', ['admin', 'manage-post', 'manage-product', 'manage-role', 'manage-user', 'mod'], null, false); \Entrust::routeNeedsRoleOrPermission('admin/role*', ['admin', 'mod', 'manage-role'], ['create-role', 'read-role', 'edit-role', 'delete-role'], null, false); \Entrust::routeNeedsRoleOrPermission('admin/users*', ['admin','mod', 'manage-users'], ['create-users', 'read-users', 'edit-users', 'delete-users'], null, false);*/ //\Entrust::routeNeedsRole('admin/users*', 'manage-users', Redirect::to('/')); <file_sep><?php namespace App\Http\Controllers\Admin; use App\Events\CreateFileToDB; use App\Helper\SortOrder; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Impl\Repository\Permission\PermissionInterface; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\Session; class PermissionsController extends Controller { use SortOrder; /** * @var PermissionInterface */ protected $permission; /** * @param PermissionInterface $permssion */ function __construct(PermissionInterface $permssion) { $this->permission = $permssion; } /** * @param Request $request * @return \Illuminate\View\View */ public function index(Request $request){ $sort = $this->sort($request)['sort']; $orderBy = $this->sort($request)['orderBy']; $permissions = $this->permission->paginate(10,compact('sort', 'orderBy')); $permissions->setPath('/admin/permission'); if($request->ajax()){ if($request->get('option') == 'displaydelete'){ $permissions = $this->permission->OnlyTrashedPaginate(10, compact('sort', 'orderBy')); } if($request->has('search') ){ $permissions = $this->permission->search( $request->get('option'), $request->get('search'),10, compact('sort', 'orderBy') ); } return \Response::json(view('admin.permission.pagination', compact('permissions')) ->with('search', $request->get('search'))->with('selected', $request->get('option'))->render()); } if($request->has('search')){ $permissions = $this->permission->search( $request->get('option'), $request->get('search'),10, compact('sort', 'orderBy') ); return view('admin.permission.index', compact('permissions')) ->with('selected', $request->get('option'))->with('search', $request->get('search')); } if(Session::has('selected')){ $permissions = $this->permission->OnlyTrashedPaginate(10, compact('sort', 'orderBy')); return view('admin.permission.index', compact('permissions'))->with('selected', Session::get('selected')); } return view('admin.permission.index', compact('permissions')); } /** * Post Option * @param Request $request * @return $this */ public function postIndex(Request $request){ $sort = null; $orderBy = null; if(is_array($request['selectedCheck']) && !empty($request['option'])) { foreach($request['selectedCheck'] as $id){ $ids[] = $id; } } if($request['option'] == 'delete') { if(empty($ids)){ \Flash::error('flash_notification.message', 'Chưa chọn mã muốn xóa'); return \Redirect::back(); } $this->permission->whereIn('id', $ids)->delete(); \Flash::success('flash_notification.message', 'Xóa thành công'); return redirect()->back(); }elseif($request['option'] == 'displaydelete') { $permissions = $this->permission->OnlyTrashedPaginate(10, compact('sort', 'orderBy')); $permissions->setPath('/admin/permission'); return view('admin.permission.index', compact('permissions'))->with('selected', $request['option']); }elseif($request['option'] == 'displayall'){ $permissions = $this->permission->paginate(10, compact('sort', 'orderBy')); $permissions->setPath('/admin/permission'); return view('admin.permission.index', compact('permissions'))->with('selected', $request['option']); }elseif($request['option'] == 'restore' && isset($ids) && $ids != null){ if($this->permission->OnlyTrashedPaginate(10, compact('sort', 'orderBy')) != null) { $this->permission->whereIn('id', $ids)->restore(); \Flash::success('flash_notification.message', 'Restore data successfully'); return redirect()->back()->with('selected', 'displaydelete'); } return redirect()->back(); } return redirect()->back(); } /** * @return \Illuminate\View\View */ public function getCreate(){ return view('admin.permission.create'); } /** * @param Requests\FormPermission $form * @return Redirect */ public function postCreate(Requests\FormPermission $form){ if(!$this->permission->save($form)) { \Flash::error('flash_notification.message', 'Failed saved'); }else{ \Flash::success('flash_notification.message', 'Add the Permission successfully'); } return redirect('admin/permission'); } /** * @param $id * @param Request $request * @return Redirect */ public function getDelete($id, Request $request){ if($request->isMethod('GET') && $request->ajax()) { if($this->permission->delete($id)) { return \Response::json(['status' => true]); } } if($this->permission->delete($id)) { \Flash::success('flash_notification.message', 'Delete the Permission successfully'); }else{ \Flash::error('flash_notification.message', 'Failed delete'); } return redirect('admin/permission'); } /** * @param $id * @return \Illuminate\View\View */ public function getEdit($id){ $permission = $this->permission->getById($id); return view('admin.permission.edit', compact('permission')); } /** * @param Requests\FormPermission $request * @return Redirect|string */ public function postEdit(Requests\FormPermission $request){ if($request->ajax() && $request->get('_token') == session('_token')){ if($this->permission->save($request)) { return \Response::json([ 'data' => $this->permission->getById($request->get('id')) ]); }else return 'false'; } if( $this->permission->save($request)) { \Flash::success('flash_notification.message', 'Edit the Permission successfully'); }else{ \Flash::error('flash_notification.message', 'Failed Edit'); } return redirect('admin/permission'); } /** * @param Request $request * @return string */ public function checkName(Request $request){ return $this->permission->checkName($request->get('id'), $request->get('name')) ? 'true' : 'false'; } public function restore($id, Request $request){ if($request->ajax()){ if($this->permission->restore($id)) return 'true'; return 'false'; } if($this->permission->restore($id)){ \Flash::success('flash_notification.message', 'Edit the Permission successfully'); return redirect()->back()->with('selected', 'displaydelete'); } \Flash::error('flash_notification.message', 'Failed Edit'); return redirect()->back(); } } <file_sep><?php /** * Created by PhpStorm. * User: ron * Date: 30/03/2015 * Time: 11:48 */ namespace App\Impl\Repository; interface Repository { /** * Get all data * @return mixed */ public function all(); /** * Remove data * @param $id * @return mixed */public function delete($id); /** * Get one data * @param $id * @return mixed */public function getById($id); /** * Eager Loading Repository * @param array $with : name table */ public function make(array $with = []); /** * Display data softDeleted combine Paginate * @param $adj * @param array $params * @return mixed */ public function onlyTrashed(); /** * @param $adjPaginate * @param array $paramsSort * @return mixed */ public function OnlyTrashedPaginate($adjPaginate,array $paramsSort); /** * @param $key * @param $value * @return mixed */ public function lists($key, $value); }<file_sep><?php /** * Created by PhpStorm. * User: ron * Date: 20/05/2015 * Time: 08:13 */ namespace App\Helper; trait SortOrder { public function sort($request){ $sort = $request->has('sort') ? $request->get('sort') : null; $orderBy = $request->get('orderBy'); return ['sort' => $sort, 'orderBy' => $orderBy]; } }<file_sep><?php namespace App\Impl\Repository\Role; use App\Http\Requests\RoleFormRule; /** * Created by PhpStorm. * User: ron * Date: 30/03/2015 * Time: 12:53 */ use App\Impl\Repository\AbstractEloquentRepository; use App\Models\Role; use Illuminate\Http\Request; class RoleEloquent extends AbstractEloquentRepository implements RoleInterface{ /** * App\Model\Role * @var $role */ protected $model; /** * Contructor * @param $role */ function __construct(Role $role) { $this->model = $role; } /** * Insert or Edit data Role * @param RoleFormRule $request * @return mixed */ public function save($request, $preparePermissionsForSave) { if( ! $request->has('id')) { $role = new Role(); } else { $role = $this->getById($request->get('id')); } $role->name = $request['name']; $role->display_name = $request['display_name']; $role->description = $request['description']; $role->save(); $role->perms()->sync($preparePermissionsForSave); return $role->id; } /** * @param $id * @return mixed */ public function restoreAssignedPermissionForRole($id) { // $role = $this->getById($id); } /** * @param $column * @param $values * @return mixed */ public function whereIn($column, $values) { return $this->model->whereIn($column, $values); } /** * Entrust restore * @param $id * @return mixed */ public function restore($id) { return $this->whereIn('id', [$id])->restore() ? true : false; } /** * @param $display * @param $search * @param $adj * @param array $params * @return mixed */ public function search($display, $search, $adj, array $params) { if($display == 'displaydelete'){ return $this->checkSort($params) ? $this->onlyTrashed()->where('name', 'LIKE', '%'.$search.'%')->orderBy($params['sort'], $params['orderBy'])->paginate($adj) : $this->onlyTrashed()->where('name', 'LIKE', '%'.$search.'%')->paginate($adj); } return $this->checkSort($params) ? $this->whereByName($search)->orderBy($params['sort'], $params['orderBy'])->paginate($adj) : $this->whereByName($search)->paginate($adj); } /** * @param $search * @return mixed */ public function whereByName($search) { return $this->whereEloquent('name', '%' . $search . '%', 'LIKE'); } }<file_sep><?php namespace App\Handlers\Events; use App\Events\CreateFileToDB; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldBeQueued; class FileCreating { /** * Create the event handler. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param CreateFileToDB $event * @return void */ public function handle(CreateFileToDB $event) { $event->createFile($event->getFileName(), $event->getDataJSON()); } } <file_sep><?php /** * Created by PhpStorm. * User: ron * Date: 30/03/2015 * Time: 12:41 */ namespace App\Impl\Repository\User; use App\Impl\Repository\AbstractEloquentRepository; use App\Models\User; class UserEloquent extends AbstractEloquentRepository implements UserInterface { /** * App\Model\User * @var $user */ protected $model; public function __construct(User $user){ $this->model = $user; } /** * @return mixed */ public function all(){ return $this->make(['roles'])->get(); } /** * Save data * @param $request * @param $rolesInput * @return mixed */ public function save($request, $rolesInput) { if($request->has('id')) { $user = $this->getById($request->get('id')); }else { $user = new User(); $user->password = \Hash::<PASSWORD>('<PASSWORD>'); } $user->name = $request->get('name'); $user->email = $request->get('email'); $bool = $user->save(); if($bool) $user->roles()->sync($rolesInput); return $bool; } /** * @param $email * @return mixed */ public function checkEmail($email) { return $this->whereEloquent('email', $email)->get(); } /** * @param $id * @return mixed */ public function getUserRole($id){ return $this->make(['roles' => function($q) { $q->get(['id', 'name']); }])->get(['id', 'name', 'email'])->find($id); } /** * @param $id * @param $email * @return mixed */ public function checkEditEmail($id, $email) { return $this->whereEloquent('id', $id, '!=')->where('email', '=', $email)->get(); } /** * @param $column * @param $data * @return mixed */ public function whereIn($column,array $data) { return $this->model->whereIn($column, $data); } /** * @param $column * @param array $ids * @return mixed */ public function restoreMultiRecord($column, array $ids){ return $this->whereIn($column, $ids)->restore(); } /** * @param $id * @return mixed */ public function restore($id){ return $this->whereIn('id', [$id])->restore(); } /** * @param int $adj * @param array $params * @return mixed */ public function paginate($adj, array $params){ if($params['sort'] == 'roles'){ $users = $this->make(['roles'])->paginate($adj); foreach($users as $user){ if($params['orderBy'] == 'desc'){ $user->roles->sortByDesc(function($role){ return $role->id;}); }else{ $user->roles->sortBy(function($role){ return $role->id;}); } } return $users; } return $this->checkSort($params) ? $this->make(['roles'])->orderBy($params['sort'], $params['orderBy'])->paginate($adj) : $this->make(['roles'])->paginate($adj); } /** * @param int $adj * @param array $params * @return mixed */ public function OnlyTrashedPaginate($adj, array $params) { if($params['sort'] == 'roles'){ $users = $this->onlyTrashed()->paginate($adj); foreach($users as $user){ if($params['orderBy'] == 'desc'){ $user->roles->sortByDesc(function($role){ return $role->id;}); }else{ $user->roles->sortBy(function($role){ return $role->id;}); } } return $users; } return ($this->checkSort($params)) ? $this->onlyTrashed()->orderBy($params['sort'], $params['orderBy'])->paginate($adj) : $this->onlyTrashed()->paginate($adj); } /** * @param $optionDisplay * @param $search * @param $adj * @param array $params * @return mixed */ public function search($optionDisplay, $search, $adj, array $params) { if($optionDisplay == 'displaydelete') return $this->checkSort($params) ? $this->onlyTrashed()->where('name', 'LIKE', '%'.$search.'%') ->orderBy($params['sort'], $params['orderBy'])->paginate($adj) : $this->onlyTrashed()->where('name', 'LIKE', '%'.$search.'%')->paginate($adj); return $this->checkSort($params) ? $this->whereEloquent('name', '%'.$search.'%', 'LIKE') ->orderBy($params['sort'], $params['orderBy'])->paginate($adj) : $this->whereEloquent('name', '%'.$search.'%', 'LIKE')->paginate($adj); } /** * sort Role in users * @param $sort * @return mixed */ /* public function sortPivotRoles($sort) { $users = $this->paginate('10', ['sort' => null, 'orderBy' => null]); foreach($users as $user){ if($sort == 'desc'){ $user->roles->sortByDesc(function($role){ return $role->id;}); }else{ $user->roles->sortBy(function($role){ return $role->id;}); } } return $users; }*/ }<file_sep><?php function sortBy($routeName,$column, $display, $search = null){ $orderBy = Request::get('orderBy') == 'asc' ? 'desc' : 'asc'; return link_to_route($routeName, $display, ['sort' => $column, 'orderBy' => $orderBy, 'search' => $search]); } <file_sep><?php namespace App\Impl\Flash; use Illuminate\Support\ServiceProvider; /** * Created by PhpStorm. * User: ron * Date: 30/03/2015 * Time: 13:59 */ class FlashServiceProvider extends ServiceProvider{ /** * Register the service provider. * * @return void */ public function register() { $this->app->bind('flash', 'App\Impl\Flash\FlashNotifier'); } }<file_sep><?php namespace App\Http\Controllers\Admin; use App\Helper\SortOrder; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Impl\Repository\Permission\PermissionInterface; use App\Impl\Repository\Role\RoleInterface; use App\Models\Permission; use App\Models\Role; use App\Models\User; use Illuminate\Http\Request; use App\Impl\Flash\FlashFacade as Flash; use Illuminate\Http\Response; use Illuminate\Session\Store; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Session; class AdminRolesController extends Controller { use SortOrder; /** * App\User * @var $user */ protected $user; /** * App\Impl\Repository\Role\RoleInterface * @var $role */ protected $role; /** * App\Permission * @var $permission */ protected $permission; function __construct(User $user,RoleInterface $role,PermissionInterface $permission) { $this->user = $user; $this->role = $role; $this->permission = $permission; } public function index(Request $request){ $permissions = $this->permission->all(); $sort = $this->sort($request)['sort']; $orderBy = $this->sort($request)['orderBy']; $roles = $this->role->paginate(10, compact('sort', 'orderBy')); $roles->setPath('/admin/role'); if($request->ajax()){ if($request->get('option') == 'displaydelete') $roles = $this->role->OnlyTrashedPaginate(10, compact('sort', 'orderBy')); if($request->get('search')) $roles = $this->role->search($request->get('option'),$request->get('search'), 10 , compact('sort', 'orderBy')); return \Response::json(view('admin.role.pagination', compact('roles', 'permissions')) ->with('search', $request->get('search')) ->with('selected', $request->get('selected'))->render()); } if($request->has('search')){ $roles = $this->role->search($request->get('option'),$request->get('search'), 10 , compact('sort', 'orderBy')); return view('admin.role.index', compact('roles', 'permissions')) ->with('search', $request->get('search')) ->with('selected', $request->get('option')); } if(Session::has('selected')) { $roles = $this->role->OnlyTrashedPaginate(10, compact('sort', 'order')); return view('admin.role.index', compact('roles', 'permissions'))->with('selected', Session::get('selected')); } return view('admin.role.index', compact('roles','permissions')); } public function postIndex(Request $request){ $sort = $this->sort($request)['sort']; $orderBy = $this->sort($request)['orderBy']; if(is_array($request['selectedCheck']) && !empty($request['option'])) { foreach($request['selectedCheck'] as $id){ $ids[] = $id; } } $permissions = $this->permission->all(); if($request['option'] == 'delete') { if(empty($ids)){ Flash::error('flash_notification.message', 'Chưa chọn mã muốn xóa'); return \Redirect::back(); } $this->role->whereIn('id', $ids)->delete(); Flash::success('flash_notification.message', 'Xóa thành công'); return redirect()->back(); }elseif($request['option'] == 'displaydelete') { $roles = $this->role->OnlyTrashedPaginate(10, compact('sort', 'orderBy')); return view('admin.role.index', compact('roles', 'permissions'))->with('selected', $request['option']); }elseif($request['option'] == 'displayall'){ $roles = $this->role->paginate(10, compact('sort', 'orderBy')); return view('admin.role.index', compact('roles', 'permissions'))->with('selected', $request['option']); }elseif($request['option'] == 'restore' && isset($ids) && $ids != null){ $this->role->whereIn('id', $ids)->restore(); Flash::success('flash_notification.message', 'Restore data successfully'); return redirect()->back()->with('selected', 'displaydelete'); } return redirect()->back(); } public function getCreate(){ $permissions = $this->permission->all(); $permissionsFinally = []; foreach($permissions as $permission){ $tmp = explode('-', $permission->name); $displays[] = end($tmp); } $displays = array_values(array_unique($displays)); foreach($displays as $display){ for($i = 0; $i < count($permissions); $i++){ $tmp = explode('-', $permissions[$i]->name); $tmp = end($tmp); if($tmp == $display){ $permissionsFinally[$display][] = $permissions[$i]; } } } return view('admin.role.create', compact('permissions', 'permissionsFinally')); } public function postCreate(Requests\RoleFormRule $request){ if( ! $this->role->save($request, Permission::preparePermissionsForSave($request->get('permissions')))) { Flash::error('flash_notification.message', 'Failed saved'); }else { Flash::success('flash_notification.message', 'Add the Role successfully'); } return redirect('admin/role'); } public function delete($id, Request $request){ if($request->isMethod('GET') && $request->ajax()) { if($this->role->delete($id)) { return \Response::json(['status' => true]); } } if($this->role->delete($id) != 0){ Flash::success('flash_notification.message', 'Delete the Role successfulyy'); } else Flash::error('flash_notification.message', 'Failed saved'); return redirect('admin/role'); } public function getEdit($id){ $role = $this->role->getById($id); $permissions = Permission::preparePermissionsForDisplay($role->perms()->get()); $permissionsFinally = []; foreach($permissions as $permission){ $tmp = explode('-', $permission['name']); $displays[] = end($tmp); } $displays = array_values(array_unique($displays)); foreach($displays as $display){ for($i = 0; $i < count($permissions); $i++){ $tmp = explode('-', $permissions[$i]['name']); $tmp = end($tmp); if($tmp == $display){ $permissionsFinally[$display]['data'][] = $permissions[$i]; } } } foreach($permissionsFinally as $key => $permissions){ $i = 0; array_walk($permissions['data'], function($values) use(&$i){ if(array_key_exists('checked', $values)){ $i++; } }); if($i == count($permissions['data'])){ $permissionsFinally[$key]['checkAll'] = true; } } return \Response::json(view('admin.role.edit', compact('role', 'permissions', 'permissionsFinally'))->render()); } public function postEdit(Requests\RoleFormRule $request){ if($request->ajax()){ if($this->role->save($request, Permission::preparePermissionsForSave($request->get('permissions')))){ return \Response::json(['data' => $this->role->getById($request->get('id'))]); } return 'false'; } if( ! $this->role->save($request, Permission::preparePermissionsForSave($request->get('permissions')))) { Flash::error('flash_notification.message', 'Failed saved'); }else { Flash::success('flash_notification.message', 'Add the Role successfully'); } return redirect('admin/role'); } public function checkName(Request $request){ return $role = $this->role->checkName($request->get('id'), $request->get('name')) ? 'true' : 'false'; } public function restore($id, Request $request){ if($request->ajax()) { if($this->role->restore($id)) return 'true'; return 'false'; } if($this->role->restore($id)) { Flash::success('flash_notification.message', 'Restore successfully'); return redirect()->back()->with('selected', 'displaydelete'); } Flash::error('flash_notification.message', 'Failed restore'); return redirect()->back(); } } <file_sep><?php namespace App\Http\ComposerView; use Illuminate\Contracts\View\View; /** * Created by PhpStorm. * User: ron * Date: 08/04/2015 * Time: 10:56 */ class SelectOptionComposer { private $list = [ '' => 'Options', 'displayall' => 'Display All', 'displaydelete' => 'Display deleted data', 'delete' => 'Delete', ]; private $listResote = [ '' => 'Options', 'displayall' => 'Display All', 'displaydelete' => 'Display deleted data', 'restore' => 'Restore data', ]; public function compose(View $view){ $view->with('select', $this->list); $view->with('listRestore', $this->listResote); } }<file_sep><?php namespace App\Impl\Repository; /** * Created by PhpStorm. * User: ron * Date: 07/04/2015 * Time: 18:02 */ abstract class AbstractEloquentRepository { /** * Get all data * @return mixed */ public function all(){ return $this->model->all(); } /** * Remove data * @param $id * @return mixed */ public function delete($id){ $model = $this->getById($id); return $model->delete(); } /** * Get one data * @param $id */ public function getById($id){ return $this->model->findOrFail($id); } /** * Eager loading Eloquent * @param array $with * @return mixed */ public function make(array $with = []){ return $this->model->with($with); } /** * @param $key * @param $value * @return mixed */ public function lists($key, $value) { return $this->all()->lists($key, $value); } /** * @param $column * @param $values * @param string $operator * @return mixed */ public function whereEloquent($column, $values, $operator = '=') { return $this->model->where($column, $operator, $values); } /** * Paginator Eloquent * @param int $adj * @param array $params : key['sort', 'orderBy'] * @return mixed */ public function paginate($adj, array $params) { return ($this->checkSort($params)) ? $this->model->query()->orderBy($params['sort'], $params['orderBy'])->paginate($adj) : $this->model->query()->paginate($adj); } /** * Eloquent onlyTrashed * @return mixed */ public function onlyTrashed(){ return $this->model->query()->onlyTrashed(); } /** * Display data softDeleted combine Paginate * @param int $adj : perPage * @param array $params : key['sort', 'orderBy'] * @return mixed */ public function OnlyTrashedPaginate($adj, array $params) { return ($this->checkSort($params)) ? $this->onlyTrashed()->orderBy($params['sort'], $params['orderBy'])->paginate($adj) : $this->onlyTrashed()->paginate($adj); } /** * check condition is name exists * @param $id * @param $name * @return bool */ public function checkName($id, $name){ if($id == 0 && $id == null) $model = $this->model->query()->where('name', '=', $name); else $model = $this->model->query()->where('name', '=', $name)->where('id', '!=', $id)->get(); if($model->count() != 0) { return false; } return true; } /** * @param array $params * @return bool */ public function checkSort(array $params) { return $params['sort'] != null && $params['orderBy']; } }<file_sep><?php namespace App\Impl\Repository\Permission; use App\Events\CreateFileToDB; use App\Http\Requests\FormPermissionCreate; use App\Impl\Repository\AbstractEloquentRepository; use App\Models\Permission; /** * Created by PhpStorm. * User: ron * Date: 09/04/2015 * Time: 16:32 */ class PermissionEloquent extends AbstractEloquentRepository implements PermissionInterface{ /* * Permission $model */ protected $model; function __construct(Permission $model) { $this->model = $model; } public function save($request) { if($request->has('id')) { $permission = $this->getById($request->get('id')); }else { $permission = new Permission; } $permission->name = $request->get('name'); $permission->display_name = $request->get('display_name'); $permission->description = $request->get('description'); $bool = $permission->save(); event(new CreateFileToDB('permission.json', $this->all())); return $bool; } public function delete($id) { $bool = parent::delete($id); if($bool){ event(new CreateFileToDB('permission.json', $this->all()->toJSON())); } return $bool; } public function whereIn($column, $data) { return $this->model->whereIn($column, $data); } /** * Eloqent Restore * @return mixed */ public function restore($id) { return $this->whereIn('id', [$id])->restore() ? true : false; } public function whereByName($search) { return $this->model->whereEloquent('name', 'LIKE', '%'.$search.'%'); } public function search($display, $search, $adj, array $params) { //dd($display, $this->onlyTrashed()->where('name', 'LIKE', '%'.$search.'%')->paginate($adj)); if($display == 'displaydelete') return $this->checkSort($params) ? $this->onlyTrashed()->where('name', 'LIKE', '%'.$search.'%') ->orderBy($params['sort'], $params['orderBy']) ->paginate($adj) : $this->onlyTrashed()->where('name', 'LIKE', '%'.$search.'%')->paginate($adj); return ($this->checkSort($params)) ? $this->whereByName($search)->orderBy($params['sort'], $params['orderBy'])->paginate($adj) : $this->whereByName($search)->paginate($adj); } }<file_sep><?php namespace App\Impl\Repository\Permission; use App\Http\Requests\FormPermissionCreate; use App\Impl\Repository\Repository; interface PermissionInterface extends Repository{ /** * @param $request * @return mixed */ public function save($request); /** * @param $id * @param $name * @return mixed */ public function checkName($id, $name); /** * @param $adj * @param array $params * @return mixed */ public function paginate($adj, array $params); /** * @param $column * @param $data * @return mixed */ public function whereIn($column, $data); /** * @param $display * @param $search * @param $adj * @param array $params * @return mixed */ public function search($display, $search, $adj,array $params); /** * Eloqent Restore * @param int $id * @return mixed */ public function restore($id); }<file_sep><?php namespace App\Http\Controllers\Admin; use App\Helper\SortOrder; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Impl\Repository\Role\RoleInterface; use App\Impl\Repository\User\UserInterface; use App\Models\Role; use App\Models\User; use Illuminate\Http\Request; class UsersController extends Controller { use SortOrder; /* * App\Impl\Repository\User\UserInterface * @var $user */ protected $user; /** * @var RoleInterface */ protected $role; function __construct(UserInterface $user, RoleInterface $role) { $this->user = $user; $this->role = $role; } public function index(Request $request){ $sort = $this->sort($request)['sort']; $orderBy = $this->sort($request)['orderBy']; /* if($sort == 'roles') { $users = $this->user->sortPivotRoles($orderBy); }else{*/ $users = $this->user->paginate(10, compact('sort', 'orderBy')); //} if($request->ajax()) { if($request->get('option') == 'displaydelete'){ $users = $this->user->OnlyTrashedPaginate(10, compact('sort', 'orderBy')); } if($request->has('search') ){ $users = $this->user->search( $request->get('option'), $request->get('search'),10, compact('sort', 'orderBy') ); } return \Response::json(view('admin.user.pagination', compact('users')) ->with('search', $request->get('search'))->with('selected', $request->get('option'))->render()); } if(\Session::has('selected')) { $users = $this->user->OnlyTrashedPaginate(10, compact('sort', 'orderBy')); return view('admin.user.index', compact('users'))->with('selected', \Session::get('selected')); } if($request->has('search')){ $users = $this->user->search($request->get('option'), $request->get('search'), 10, compact('sort', 'orderBy')); return view('admin.user.index', compact('users')) ->with('selected', $request->get('option'))->with('search', $request->get('search')); } return view('admin.user.index', compact('users')); } public function postIndex(Request $request){ $sort = null; $orderBy = null; if(is_array($request['selectedCheck']) && !empty($request['option'])) { foreach($request['selectedCheck'] as $id){ $ids[] = $id; } } if($request['option'] == 'delete') { if(empty($ids)){ \Flash::error('flash_notification.message', 'Chưa chọn mã muốn xóa'); return \Redirect::back(); } $this->user->whereIn('id', $ids)->delete(); \Flash::success('flash_notification.message', 'Xóa thành công'); return redirect()->back(); }elseif($request['option'] == 'displaydelete') { $users = $this->user->OnlyTrashedPaginate(10, compact('sort', 'orderBy')); $users->setPath('/admin/users'); return view('admin.user.index', compact('users'))->with('selected', $request['option']); }elseif($request['option'] == 'displayall'){ $users = $this->user->paginate(10, compact('sort', 'orderBy')); $users->setPath('/admin/users'); return view('admin.user.index', compact('users'))->with('selected', $request['option']); }elseif($request['option'] == 'restore' && isset($ids) && $ids != null){ if($this->user->restoreMultiRecord('id', $ids) > 0){ \Flash::success('flash_notification.message', 'Restore data successfully'); return redirect()->back()->with('selected', 'displaydelete'); } \Flash::error('flash_notification.message', 'Restore data Failed'); return redirect()->back(); } return redirect()->back(); } public function getCreate(){ $roles = $this->role->lists('name', 'id'); return view('admin.user.create', compact('roles')); } public function postCreate(Requests\FormUsers $request) { if($this->user->save($request, Role::prepareRolesForSave($request->get('roles')))) { \Flash::success('flash_notification.message', 'Edit successfully'); return redirect('/admin/users'); } \Flash::error('flash_notification.message', 'Failed Edit'); return redirect()->back(); } public function getEdit($id, Request $request){ if($request->ajax()) { $user = $this->user->getById($id); $roles = $this->role->lists('name', 'id'); return \Response::json(view('admin.user.edit', compact('user', 'roles'))->render()); } return \App::abort(403, 'Unauthorized action'); } public function postEdit(Requests\FormUsers $request){ if($request->ajax()) { if($this->user->save($request, Role::prepareRolesForSave($request->get('roles')))) { return \Response::json(['data' => $this->user->getUserRole($request->get('id'))]); } return \Response::json(['data' => 'failed']); } return \App::abort(403, 'Unauthorized action'); } public function delete($id, Request $request){ if($request->ajax()) { if($this->user->delete($id)){ return \Response::json(['status' => true]); } return \Response::json(['status' => false]); } if($this->user->delete($id)){ \Flash::success('flash_notification.message', 'Delete successfully'); return redirect('/admin/users'); } \Flash::error('flash_notification.message', 'Failed Edit'); return redirect()->back(); } public function restore($id, Request $request){ if($request->ajax()){ if($this->user->restore($id)) return 'true'; return 'false'; } if($this->user->restore($id)) { \Flash::success('flash_notification.message', 'Restore successfully'); return redirect()->back()->with('selected', 'displaydelete'); } \Flash::error('flash_notification.message', 'Failed restore'); return redirect()->back(); } public function test($id){ $temp = User::with(['roles' => function($q) { $q->get(['id', 'name']); }])->get(['id', 'name'])->find($id); $users = $this->user->getUserRole($id); dd( $users->toArray()); } public function checkEmail(Request $request){ if($request->ajax()) { if(count($this->user->checkEmail($request->get('email'))) != 0) return 'false'; return 'true'; } return \App::abort(403, 'Unauthorized action'); } public function checkEditEmail(Request $request){ // dd(); //return User::query()->where('id', '!=', $request->get('id'))->where('email', '=', $request->get('email'))->get(); // return count($this->user->checkEditEmail($request->get('id'), $request->get('email'))); if($request->ajax()){ if(count($this->user->checkEditEmail($request->get('id'), $request->get('email'))) !=0) return 'false'; return 'true'; } return \App::abort(403, 'Unauthorized action'); } } <file_sep><?php /** * Created by PhpStorm. * User: ron * Date: 30/03/2015 * Time: 11:53 */ namespace App\Impl\Repository; use App\Impl\Repository\Permission\PermissionEloquent; use App\Impl\Repository\Role\RoleEloquent; use App\Impl\Repository\User\UserEloquent; use App\Models\Permission; use App\Models\Role; use App\Models\User; use Illuminate\Support\ServiceProvider; class RepositoryServiceProvider extends ServiceProvider{ /** * Register the service provider. * * @return void */ public function register() { $this->app->bind('App\Impl\Repository\Permission\PermissionInterface', function() { return new PermissionEloquent(new Permission()); }); $this->app->bind('App\Impl\Repository\Role\RoleInterface', function() { return new RoleEloquent(new Role); }); $this->app->bind('App\Impl\Repository\User\UserInterface', function(){ return new UserEloquent(new User()); }); } }<file_sep><?php /** * Created by PhpStorm. * User: ron * Date: 29/03/2015 * Time: 14:45 */ $factory('App\Models\User', [ 'name' => $faker->userName, 'email' => $faker->email, 'password' => <PASSWORD>('<PASSWORD>'), ]);<file_sep><?php namespace App\Impl\Repository\Role; /** * Created by PhpStorm. * User: ron * Date: 30/03/2015 * Time: 12:48 */ use App\Http\Requests\RoleFormRule; use App\Impl\Repository\Repository; interface RoleInterface extends Repository{ /** * Insert or Edit data Role * @param RoleFormRule $request * @return mixed */ public function save($request, $preparePermissionsForSave); /** * @param $column * @param $values * @return mixed */ public function whereIn($column, $values); /** * @param $id * @param $name * @return mixed */ public function checkName($id, $name); /** * @param $adj * @param array $params * @return mixed */ public function paginate($adj, array $params); /** * @param $display * @param $search * @param $adj * @param array $params * @return mixed */ public function search($display, $search, $adj, array $params); /** * @param $id * @return mixed */ public function restoreAssignedPermissionForRole($id); /** * Entrust restore * @param $id * @return mixed */ public function restore($id); }<file_sep><?php namespace App\Providers; use Illuminate\Support\ServiceProvider; /** * Created by PhpStorm. * User: ron * Date: 08/04/2015 * Time: 10:58 */ class ViewComposerServiceProvider extends ServiceProvider { public function boot() { $this->composerSelectOption(); } public function composerSelectOption(){ view()->composer([ 'admin.role.index', 'admin.permission.index', 'admin.user.index' ],'App\Http\ComposerView\SelectOptionComposer'); } /** * Register the service provider. * * @return void */ public function register() { // TODO: Implement register() method. } }
de2a6b9849b412a3cfdabf00c2da842489203cd0
[ "PHP" ]
24
PHP
nguyenphuocnhatthanh/MyProject
fd31e37194e6ba78844416abe154d08b73a3ad5d
e0082e5c11f3e28d0d5858f3a8a5a2e604864dea
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # Important: before running this demo, make certain that grovepi & ATT_IOT # are in the same directory as this script, or installed so that they are globally accessible import logging logging.getLogger().setLevel(logging.INFO) import grovepi #provides pin support import ATT_IOT as IOT #provide cloud support from time import sleep #pause the app #set up the ATT internet of things platform IOT.DeviceId = "" IOT.ClientId = "" IOT.ClientKey = "" #define each sensor sensorName = "Button" sensorPin = 5 actuatorPin = 6 #set up the pins grovepi.pinMode(sensorPin,"INPUT") grovepi.pinMode(actuatorPin,"OUTPUT") #callback: handles values sent from the cloudapp to the device def on_message(id, value): print("unknown actuator: " + id) IOT.on_message = on_message #make certain that the device & it's features are defined in the cloudapp IOT.connect() IOT.addAsset(sensorPin, sensorName, "Push button", False, "boolean") IOT.subscribe() IOT.send("false", sensorPin) buttonVal = False; sensorVal = False; while True: try: sensorRead = grovepi.digitalRead(sensorPin) if sensorRead == 255: continue if sensorVal != sensorRead: sensorVal = sensorRead if sensorVal: buttonVal = not buttonVal if buttonVal: IOT.send("true", sensorPin) grovepi.digitalWrite(actuatorPin, 1) else: IOT.send("false", sensorPin) grovepi.digitalWrite(actuatorPin, 0) except IOError: print "error reading sensor" <file_sep>#!/bin/sh # launcher.sh # navigate to home dir, then to this dir, execute the python script, then back home LOGFILE=/home/pi/hackathon/MCE3/restart.log writelog() { now='date' echo ="$now $*" >> $LOGFILE } sleep 1 # pause so the os can init the pins writelog "Starting" while true; do cd / cd home/pi cd hackathon/MCE3 #sudo python HouseButton.py #sudo python HouseLED.py writelog "Exited with status $?" writelog "Restarting" done cd / <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # Important: before running this demo, make certain that grovepi & ATT_IOT # are in the same directory as this script, or installed so that they are globally accessible import logging logging.getLogger().setLevel(logging.INFO) import grovepi #provides pin support import ATT_IOT as IOT #provide cloud support from time import sleep #pause the app #set up the ATT internet of things platform IOT.DeviceId = "" IOT.ClientId = "" IOT.ClientKey = "" #define each sensor actuatorName = "LED" actuatorPin = 6 #set up the pins grovepi.pinMode(actuatorPin,"OUTPUT") #callback: handles values sent from the cloudapp to the device def on_message(id, value): if id.endswith(str(actuatorPin)) == True: value = value.lower() #make certain that the value is in lower case, for 'True' vs 'true' if value == "true": grovepi.digitalWrite(actuatorPin, 1) IOT.send("true", actuatorPin) #provide feedback to the cloud that the operation was succesful elif value == "false": grovepi.digitalWrite(actuatorPin, 0) IOT.send("false", actuatorPin) #provide feedback to the cloud that the operation was succesful else: print("unknown value: " + value) else: print("unknown actuator: " + id) IOT.on_message = on_message #make certain that the device & it's features are defined in the cloudapp IOT.connect() IOT.addAsset(actuatorPin, actuatorName, "Status LED", True, "boolean") IOT.subscribe() while True: sleep(3)
3487e2be3184b4d1de7fcf05b3eb013b956486ff
[ "Python", "Shell" ]
3
Python
allthingstalk/hackathon
e803d812f85d5775c5a1e96cc32e98c28975c5ab
4862b16d9a16b626dd2193ddebb6a4dedd1e0684
refs/heads/master
<repo_name>roryhubbard/wall-bot<file_sep>/main.py import math import matplotlib.pyplot as plt from robot_model import WallBot from animation import AxData, Animator def main(animate): dt = .005 goal_x = 1 goal_theta = -math.pi / 4 robot = WallBot(2.25, .2, 1., dt) bot_states = [robot.observe()] gripper_coords = [robot.get_gripper_coordinates()] robot.switch_grip() last_two_swings = False final_hold_count = 0 i = 0 while 1: i+=1 robot.update() bot_states.append(robot.observe()) gripper_coords.append(robot.get_gripper_coordinates()) if robot.goal_state_reached: final_hold_count += 1 if final_hold_count >= 10: break if last_two_swings: robot.final_swing_control(goal_x, goal_theta) elif robot.rotation_switched: robot.switch_grip() if abs(goal_x - robot.get_gripper_coordinates()[0][0]) < robot.l / 2: last_two_swings = True bot_x = list(map(lambda x: x[0], bot_states)) bot_y = list(map(lambda x: x[1], bot_states)) bot_theta = list(map(lambda x: x[2] * 180 / math.pi, bot_states)) gripper_x = list(map(lambda x: list(zip(*x))[0], gripper_coords)) gripper_y = list(map(lambda x: list(zip(*x))[1], gripper_coords)) fig, ax = plt.subplots() ax.plot([goal_x, goal_x], [0, -.5], '--') ax.set_aspect('equal') if animate: ax_data = [ AxData(gripper_x, gripper_y, 'position', plot_history=False), ] animator = Animator(1/2, ax_data, dt, fig, ax, show_legend=False) animator.set_save_path('/home/raven.ravenind.net/r103943/Desktop/a') animator.run() else: ax.plot(bot_x, bot_y, label='position') # ax.plot(bot_theta, label='theta') ax.set_title('Position') ax.set_xlabel('x (m)') ax.set_ylabel('y (m)') ax.set_aspect('equal') plt.show() plt.close() if __name__ == "__main__": plt.rcParams['figure.figsize'] = [16, 10] plt.rcParams['savefig.facecolor'] = 'black' plt.rcParams['figure.facecolor'] = 'black' plt.rcParams['figure.edgecolor'] = 'white' plt.rcParams['axes.facecolor'] = 'black' plt.rcParams['axes.edgecolor'] = 'white' plt.rcParams['axes.labelcolor'] = 'white' plt.rcParams['axes.titlecolor'] = 'white' plt.rcParams['xtick.color'] = 'white' plt.rcParams['ytick.color'] = 'white' plt.rcParams['text.color'] = 'white' plt.rcParams["figure.autolayout"] = True # plt.rcParams['legend.facecolor'] = 'white' animate = True main(animate) <file_sep>/play_trained_Q.py import gym import numpy as np import torch from utils import get_greedy_action import math import matplotlib.pyplot as plt from robot_model import WallBot from environment import Environment from animation import AxData, Animator def main(animate): Q = torch.load('trained_Q.pth') Q.eval() m = 2 dt = .01 goal_x = .4 goal_theta = math.pi / 4 robot = WallBot(2.25, .2, 1., dt) env = Environment(robot, goal_x, goal_theta) bot_states = [env.robot.observe()] gripper_coords = [env.robot.get_gripper_coordinates()] done = False state = torch.tensor(env.reset() * m) while not done: action = get_greedy_action( Q, state.unsqueeze(0)) new_state, reward, done = env.step(action.item()) state = torch.tensor(state[1:].tolist() + new_state) bot_states.append(env.robot.observe()) gripper_coords.append(env.robot.get_gripper_coordinates()) bot_x = list(map(lambda x: x[0], bot_states)) bot_y = list(map(lambda x: x[1], bot_states)) bot_theta = list(map(lambda x: x[2] * 180 / math.pi, bot_states)) gripper_x = list(map(lambda x: list(zip(*x))[0], gripper_coords)) gripper_y = list(map(lambda x: list(zip(*x))[1], gripper_coords)) fig, ax = plt.subplots() # ax.set_aspect('equal') if animate: ax_data = [ AxData(gripper_x, gripper_y, 'position', plot_history=False), ] animator = Animator(1/2, ax_data, dt, fig, ax) animator.run() else: ax.plot(bot_x, bot_y, label='position') # ax.plot(bot_theta, label='theta') ax.set_title('Position') ax.set_xlabel('x (m)') ax.set_ylabel('y (m)') ax.set_aspect('equal') plt.show() plt.close() if __name__ == "__main__": plt.rcParams['figure.figsize'] = [16, 10] plt.rcParams['savefig.facecolor'] = 'black' plt.rcParams['figure.facecolor'] = 'black' plt.rcParams['figure.edgecolor'] = 'white' plt.rcParams['axes.facecolor'] = 'black' plt.rcParams['axes.edgecolor'] = 'white' plt.rcParams['axes.labelcolor'] = 'white' plt.rcParams['axes.titlecolor'] = 'white' plt.rcParams['xtick.color'] = 'white' plt.rcParams['ytick.color'] = 'white' plt.rcParams['text.color'] = 'white' plt.rcParams["figure.autolayout"] = True # plt.rcParams['legend.facecolor'] = 'white' animate = True main(animate) <file_sep>/network_update.py import random import torch import torch.nn as nn def sgd_update(Q, Q_target, D, mini_batch_size, discount_factor, optimizer, criterion): mini_batch = random.sample(D, mini_batch_size) mini_batch = list(zip(*mini_batch)) non_final_mask = torch.tensor( tuple(map(lambda next_state: next_state is not None, mini_batch[3]))) non_final_next_states = [ next_state for next_state in mini_batch[3] if next_state is not None ] if not non_final_next_states: return non_final_next_states = torch.stack(non_final_next_states) state_batch = torch.stack(mini_batch[0]) action_batch = torch.stack(mini_batch[1]) reward_batch = torch.cat(mini_batch[2]) state_action_values = Q(state_batch).gather(1, action_batch) next_state_values = torch.zeros(mini_batch_size) next_state_values[non_final_mask] = Q_target( non_final_next_states).detach().max(1)[0] y = reward_batch + discount_factor * next_state_values loss = criterion(state_action_values, y.unsqueeze(1)) optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(Q.parameters(), 1) optimizer.step() <file_sep>/robot_model.py import math from enum import Enum import numpy as np G = 9.81 class GripState(Enum): BOTH = 0 LEFT = 1 RIGHT = 2 NEITHER = 3 class WallBot: def __init__(self, mass, length, friction, dt): self.dt = dt self.m = mass self.l = length self.fr = friction self.reset() def reset(self): self.theta = math.pi / 2 self.theta_dot = 0. self.x = self.l / 2 * math.sin(self.theta) self.x_dot = 0. self.y = -self.l / 2 * math.cos(self.theta) self.y_dot = 0. self.grip_state = GripState.BOTH self.rotation_switched = False self.last_swing = False self.goal_state_reached = False def switch_grip(self): self.grip_state = GripState.LEFT \ if self.grip_state is GripState.RIGHT \ else GripState.RIGHT self.theta += math.pi self.theta = math.atan2(math.sin(self.theta), math.cos(self.theta)) self.theta_dot = 0. self.x_dot = 0. self.y_dot = 0. def hold(self): self.grip_state = GripState.BOTH self.theta_dot = 0. self.x_dot = 0. self.y_dot = 0. def release(self): self.grip_state = GripState.NEITHER def final_swing_control(self, goal_x, goal_theta): if self.last_swing: theta_error = abs(goal_theta - math.atan(math.tan(self.theta))) if theta_error < 5 * math.pi / 180: self.hold() self.goal_state_reached = True return goal_grip = goal_x - self.l / 2 * math.sin(goal_theta) if self.get_gripper_coordinates()[1][0] >= goal_grip: self.switch_grip() self.last_swing = True def update(self): if self.grip_state is GripState.BOTH: return elif self.grip_state is GripState.NEITHER: self.x += self.x_dot * self.dt self.y_dot += G * self.dt self.y += self.y_dot * self.dt else: prev_rotation_dir = np.sign(self.theta_dot) self.theta_dot += (-G / (self.l / 2) * math.sin(self.theta) - self.fr / self.m * self.theta_dot) * self.dt theta_updated = self.theta + self.theta_dot * self.dt self.x += self.l / 2 * (math.sin(theta_updated) - math.sin(self.theta)) self.y -= self.l / 2 * (math.cos(theta_updated) - math.cos(self.theta)) self.theta = math.atan2(math.sin(theta_updated), math.cos(theta_updated)) if prev_rotation_dir != 0 \ and prev_rotation_dir != np.sign(self.theta_dot): self.rotation_switched = True else: self.rotation_switched = False def observe(self): return (self.x, self.y, self.theta) def get_gripper_coordinates(self): return [ (self.x - self.l / 2 * math.sin(self.theta), self.y + self.l / 2 * math.cos(self.theta)), (self.x + self.l / 2 * math.sin(self.theta), self.y - self.l / 2 * math.cos(self.theta)), ] <file_sep>/train.py import math from copy import deepcopy from collections import deque from robot_model import WallBot from environment import Environment import torch import torch.nn as nn import torch.optim as optim from q_network import QNetwork from utils import annealed_epsilon, get_epsilon_greedy_action, save_stuff from network_update import sgd_update def deep_qlearning(env, nepisodes, discount_factor, N, C, mini_batch_size, replay_start_size, sgd_update_frequency, initial_exploration, final_exploration, final_exploration_episode, lr, alpha, m): n_actions = 3 Q = QNetwork(n_actions) Q_target = deepcopy(Q) Q_target.eval() optimizer = optim.RMSprop(Q.parameters(), lr=lr, alpha=alpha) criterion = nn.MSELoss() D = deque(maxlen=N) # replay memory last_Q_target_update = 0 last_sgd_update = 0 episode_rewards = [] for i in range(nepisodes): state = torch.tensor(env.reset() * m) episode_reward = 0 done = False while not done: epsilon = annealed_epsilon( initial_exploration, final_exploration, final_exploration_episode, i) action = get_epsilon_greedy_action( Q, state.unsqueeze(0), epsilon, n_actions) new_state, reward, done = env.step(action.item()) reward = torch.tensor([reward]) episode_reward += reward.item() if done: next_state = None episode_rewards.append(episode_reward) else: next_state = torch.tensor(state[1:].tolist() + new_state) D.append((state, action, reward, next_state)) state = next_state if len(D) < replay_start_size: continue last_sgd_update += 1 if last_sgd_update < sgd_update_frequency: continue last_sgd_update = 0 sgd_update(Q, Q_target, D, mini_batch_size, discount_factor, optimizer, criterion) last_Q_target_update += 1 if last_Q_target_update % C == 0: Q_target = deepcopy(Q) Q_target.eval() if i % 1000 == 0: save_stuff(Q, episode_rewards) print(f'episodes completed = {i}') return Q, episode_rewards def main(): dt = .01 goal_x = .4 goal_theta = math.pi / 4 robot = WallBot(2.25, .2, 1., dt) env = Environment(robot, goal_x, goal_theta) nepisodes = 500000 # train for a total of 50 million frames discount_factor = 0.99 N = 100000 # replay memory size (paper uses 1000000) C = 1000 # number of steps before updating Q target network mini_batch_size = 32 replay_start_size = 10000 # minimum size of replay memory before learning starts sgd_update_frequency = 4 # number of action selections in between consecutive SGD updates initial_exploration = 1. # initial epsilon valu3 final_exploration = 0.1 # final epsilon value final_exploration_episode = 100000 # number of frames over which the epsilon is annealed to its final value lr = 0.01 # learning rate used by RMSprop alpha = 0.99 # alpha value used by RMSprop m = 2 # number of consecutive frames to stack for input to Q network Q, episode_rewards = deep_qlearning( env, nepisodes, discount_factor, N, C, mini_batch_size, replay_start_size, sgd_update_frequency, initial_exploration, final_exploration, final_exploration_episode, lr, alpha, m) save_stuff(Q, episode_rewards) if __name__ == "__main__": main() <file_sep>/plot_episode_rewards.py import matplotlib.pyplot as plt import pickle import numpy as np plt.rcParams['figure.figsize'] = [16, 10] plt.rcParams['savefig.facecolor'] = 'black' plt.rcParams['figure.facecolor'] = 'black' plt.rcParams['figure.edgecolor'] = 'white' plt.rcParams['axes.facecolor'] = 'black' plt.rcParams['axes.edgecolor'] = 'white' plt.rcParams['axes.labelcolor'] = 'white' plt.rcParams['axes.titlecolor'] = 'white' plt.rcParams['xtick.color'] = 'white' plt.rcParams['ytick.color'] = 'white' plt.rcParams['text.color'] = 'white' plt.rcParams["figure.autolayout"] = True # plt.rcParams['legend.facecolor'] = 'white' with open("episode_rewards.txt", "rb") as f: episode_rewards = pickle.load(f) averaged_episode_rewards = np.convolve( episode_rewards, np.ones(100)/100, mode='valid') fig, ax = plt.subplots() # ax.plot(episode_rewards, label='true') ax.plot(averaged_episode_rewards, label='averaged') ax.legend() plt.show() plt.close() <file_sep>/q_network.py import torch import torch.nn as nn import torch.nn.functional as F class QNetwork(nn.Module): def __init__(self, n_actions): super().__init__() self.fl1 = nn.Linear(2, 32) self.fl2 = nn.Linear(32, n_actions) def forward(self, x): h = F.relu(self.fl1(x)) h = self.fl2(h) return h <file_sep>/utils.py from collections import deque import random import numpy as np import pickle import torch def annealed_epsilon(initial_exploration, final_exploration, final_exploration_frame, frames_count): """ Return linearly annealed exploration value """ return initial_exploration - (initial_exploration - final_exploration) \ * min(frames_count / final_exploration_frame, 1) def get_greedy_action(Q, state): with torch.no_grad(): return Q(state).max(1)[1].view(1) def get_epsilon_greedy_action(Q, state, epsilon, n_actions): """ Select a random action with probabily of epsilon or select the greedy action according to Q Input: - Q: network that maps states to actions - state: current state as given by the environment - epsilon: probability of exploring - n_actions: action space cardinality Output: - action """ return torch.tensor([random.choice(tuple(range(n_actions)))], dtype=torch.int64) \ if random.uniform(0.0, 1.0) < epsilon \ else get_greedy_action(Q, state) def save_stuff(Q, episode_rewards): torch.save(Q, 'trained_Q.pth') with open("episode_rewards.txt", "wb") as f: pickle.dump(episode_rewards, f) <file_sep>/animation.py import uuid from collections import OrderedDict import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation plt.rcParams['figure.figsize'] = [15, 10] plt.rcParams['savefig.facecolor'] = 'black' plt.rcParams['figure.facecolor'] = 'black' plt.rcParams['figure.edgecolor'] = 'white' plt.rcParams['axes.facecolor'] = 'black' plt.rcParams['axes.edgecolor'] = 'white' plt.rcParams['axes.labelcolor'] = 'white' plt.rcParams['axes.titlecolor'] = 'white' plt.rcParams['xtick.color'] = 'white' plt.rcParams['ytick.color'] = 'white' # plt.rcParams['legend.facecolor'] = 'white' plt.rcParams['text.color'] = 'white' plt.rcParams["figure.autolayout"] = True # TODO: add polar plot support # TODO: support for collection of axes objects def make_legend(ax, bbox_to_anchor=None, loc=None): handles, labels = ax.get_legend_handles_labels() by_label = OrderedDict(zip(labels, handles)) ax.legend(by_label.values(), by_label.keys(), bbox_to_anchor=bbox_to_anchor, loc=loc) class AxData: def __init__(self, x, y, label=None, scatter=False, plot_history=True, freeze_final=True, color=None, linestyle='-', marker='.', markersize=None): self.x = x self.y = y self.label = label self.scatter = scatter self.plot_history = plot_history self.freeze_final = freeze_final self.color = color self.marker = marker self.linestyle = linestyle self.markersize = markersize if label is None: self.label = str(uuid.uuid4()) self.legend = False else: self.legend = True if self.scatter: self.linestyle = '' class Animator: def __init__(self, speed_multiplier, ax_data, dt, fig, ax, show_legend=True): self.speed_multiplier = speed_multiplier self.ax_data = ax_data self.dt = dt self.fig = fig self.ax = ax self.artists = dict() self.bbox_to_anchor = dict() self.loc = dict() self.save_path = None self.static = False self.show_legend = show_legend def set_leg_loc(self, bbox_to_anchor, loc='center left', ax_key='*'): self.bbox_to_anchor[ax_key] = bbox_to_anchor self.loc[ax_key] = loc def set_ax_limits(self, xlim=None, ylim=None, ax_key='*'): ax = self.get_ax_from_ax_key(ax_key) if xlim is not None: ax.set_xlim(xlim) if ylim is not None: ax.set_ylim(ylim) def set_save_path(self, save_path): self.save_path = save_path def make_static_plot(self): self.static = True def run(self): self._establish_artists() if self.static: if self.save_path is not None: self.fig.savefig(self.save_path) else: num_frames = self._get_num_frames() frame_interval = int(self.dt / self.speed_multiplier * 1000) anim = FuncAnimation(self.fig, self._update_frame, init_func=self._init_animate, frames=num_frames, interval=frame_interval, blit=True) if self.save_path is not None: if '.mp4' not in self.save_path: self.save_path += '.mp4' anim.save(self.save_path) plt.show() plt.close() def get_ax_from_ax_key(self, ax_key): if ax_key == '*': ax = self.ax elif len(ax_key) > 1: ax = self.ax[int(ax_key[0])][int(ax_key[1])] else: ax = self.ax[int(ax_key)] return ax def _get_num_frames(self): num_frames = 0 if isinstance(self.ax_data, list): for val in self.ax_data: if len(val.x) > num_frames: num_frames = len(val.x) else: for values in self.ax_data.values(): for val in values: if len(val.x) > num_frames: num_frames = len(val.x) return num_frames def _get_ax_artist(self, ax, label, ax_data): return ax.plot([], [], label=label, color=ax_data.color, linestyle=ax_data.linestyle, marker=ax_data.marker, markersize=ax_data.markersize, ) def _add_artist(self, artist_key, ax_data, ax): if ax_data.legend: label = ax_data.label else: label = None self.artists[artist_key], = self._get_ax_artist( ax, label, ax_data) def _establish_artists(self): tmp_data = [] if isinstance(self.ax_data, list): self.ax_data = {'*': self.ax_data} for k, v in self.ax_data.items(): ax = self.get_ax_from_ax_key(k) for val in v: if val.scatter: tmp_data.append(ax.scatter(val.x, val.y)) else: if isinstance(val.x[0], tuple) \ or isinstance(val.x[0], list): for i in range(len(val.x)): tmp_data.extend(ax.plot(val.x[i], val.y[i])) else: tmp_data.extend(ax.plot(val.x, val.y)) self._add_artist(k+val.label, val, ax) if self.show_legend: make_legend(ax, self.bbox_to_anchor.get(k), self.loc.get(k)) if not self.static: for _ in range(len(tmp_data)): tmp_data.pop().remove() def _init_animate(self): artists = [] for artist in self.artists.values(): artist.set_data([], []) artists.append(artist) return artists def _update_frame(self, i): artists = [] if isinstance(self.ax_data, list): for val in self.ax_data: self._set_data(val.label, val, artists, i) else: for key, values in self.ax_data.items(): for val in values: self._set_data(key+val.label, val, artists, i) return artists def _set_data(self, artist_key, ax_data, artists, i): if i > len(ax_data.x) - 1: if ax_data.freeze_final: i = len(ax_data.x) - 1 else: return if ax_data.plot_history: self.artists[artist_key].set_data(ax_data.x[:i+1], ax_data.y[:i+1]) else: self.artists[artist_key].set_data(ax_data.x[i], ax_data.y[i]) artists.append(self.artists[artist_key]) <file_sep>/environment.py import math class Environment: def __init__(self, robot, goal_x, goal_theta): self.robot = robot self.goal_x = goal_x self.goal_theta = goal_theta self.step_counter = 0 def step(self, u): done = False if u == 1: self.robot.switch_grip() elif u == 2: self.robot.hold() self.robot.update() x_error = self.goal_x - self.robot.observe()[0] # theta_error = self.goal_theta - math.atan(math.tan(self.robot.observe()[2])) # state = [x_error, theta_error] state = [x_error] # cost = 100 * x_error**2 + theta_error**2 / 10 reward = -x_error**2 self.step_counter += 1 if self.step_counter >= 100: done = True return state, reward, done def reset(self): self.robot.reset() x_error = self.goal_x - self.robot.observe()[0] # theta_error = self.goal_theta - self.robot.observe()[2] # state = [x_error, theta_error] state = [x_error] self.step_counter = 0 return state
389cd3de8ca4c590e57215fc72346ba203f721d3
[ "Python" ]
10
Python
roryhubbard/wall-bot
424ec3fe7b0239d1fdcaf98d6e91463c84354386
aada5387076755da88851e4e6f4c1c57ff17129d
refs/heads/master
<repo_name>jay412/Old-Grip<file_sep>/README.md # Old-Grip (This is an older version of Grip, see newer version) An Android app that calculates meal-sharing costs between a group of people. Currently in development of additional features such as: - Maintaining a history of bills (database) - Sending a copy of the split bill to an email - Calculate total cost by entering each item's value and name for reference - Add a preference for tax rate - Optimize custom tip and # of people sharing with a dropdown and/or pop-up - Edit main activity layout # Instructions 1) Enter value for Total Meal Cost 2) Tap Calculate Tax button to calculate tax for meal (currently set for NYC tax rate) 3) Tap 15% or 20% to calculate tips for the meal or enter a value and tap Custom Tip 4) Enter the number of people sharing 5) Tap the Calculate Total button to calculate the grand total for each person to pay 6) Open the menu and tap Clear to clear all fields <file_sep>/app/src/main/java/jay412/grip/TotalMealActivity.java package jay412.grip; import android.app.ActionBar; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class TotalMealActivity extends AppCompatActivity { private int[] mPrice; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_total_meal); ActionBar actionBar = this.getActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.add_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); } else if(id == R.id.action_add) { AlertDialog.Builder builder = new AlertDialog.Builder(TotalMealActivity.this); LayoutInflater inflater = getLayoutInflater(); final View dialogView = inflater.inflate(R.layout.dialog_template, null); final EditText mItem = dialogView.findViewById(R.id.et_item); final EditText mPrice = dialogView.findViewById(R.id.et_price); builder.setTitle("Add A New Item"); builder.setView(dialogView) .setPositiveButton(R.string.add, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //add button String itemName = mItem.getText().toString(); String price = mPrice.getText().toString(); Log.i("Item Name: ", itemName); Log.i("Price: ", price); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); final AlertDialog dialog = builder.create(); dialog.show(); } return super.onOptionsItemSelected(item); } }
a66203d4f13ee013fb6ddf4f806da5119517c25a
[ "Markdown", "Java" ]
2
Markdown
jay412/Old-Grip
6eae02b136785e32b7f464a1654f67c3bba75ea1
97c5aeae632d647e56ebe67a4ad0498ad7a4dbbf
refs/heads/master
<repo_name>protonet/posco<file_sep>/cluster/ship.rb =begin { name = "string" ifname = "string" ipv4_addr = "v.x.y.z/p4|DHCP" ipv4_gw = "v.x.y.zg|NULL" ipv6_addr = "v6::z6/p6" ipv6_gw = "v6::z6g" ipv4_transit = "vt.xt.yt.zt/p4" } =end def make_ship(region, parameter) return region.hosts.add(parameter['name'], "flavour" => "nixian", "dialect" => parameter['dialect']||"ubuntu", "packager" => true, "vagrant_deploy" => Construqt::Hosts::Vagrant.new.box("ubuntu/xenial64") .add_cfg('config.vm.network "public_network", bridge: "bridge0"') ) do |host| region.interfaces.add_device(host, "lo", "mtu" => "9000", :description=>"#{host.name} lo", "address" => region.network.addresses.add_ip(Construqt::Addresses::LOOOPBACK)) host.configip = host.id ||= Construqt::HostId.create do |my| addr = region.network.addresses if parameter['ipv4_addr'] == "DHCP" addr = addr.add_ip(Construqt::Addresses::DHCPV4) else addr = addr.add_ip(parameter['ipv4_addr']) end if parameter['ipv4_gw'] addr = addr.add_route("0.0.0.0/0#INTERNET", parameter['ipv4_gw']) end addr = addr.add_ip(parameter['ipv6_addr']) addr = addr.add_route("2000::/3#INTERNET", parameter['ipv6_gw']) addr = addr.add_route("fd00::/8#INTERNET", parameter['ipv6_gw']) my.interfaces << region.interfaces.add_device(host, parameter['ifname'], "mtu" => 1500, "address" => addr, 'proxy_neigh' => Construqt::Tags.resolver_adr_net(parameter['proxy_neigh_host'], parameter['proxy_neigh_net'], Construqt::Addresses::IPV6), "firewalls" => ["host-outbound", "icmp-ping", "ssh-srv", "border-masq"]+ (parameter['firewalls']||[]) + ["block"]) #binding.pry end region.interfaces.add_bridge(host, "br169", "mtu" => 1500, "interfaces" => [], "address" => region.network.addresses .add_ip(parameter['ipv4_intern']) .add_ip(parameter['ipv6_intern'])) end end <file_sep>/cluster/certor_service.rb module Certor module Renderer module Nixian class Ubuntu def initialize(service) @service = service end def interfaces(host, ifname, iface, writer, family = nil) return unless iface.address puts "#{@service.name} #{host.name} #{ifname}" # host.result.add(self, <<MAINCF, Construqt::Resources::Rights.root_0644(Construqt::Resources::Component::POSTFIX), "etc", "postfix", "main.cf") ## #{@service.get_server_iface.host.name} #{@service.get_server_iface.address.first_ipv4} #inet_protocols = all #myhostname = #{iface.host.name} #mynetworks = #{iface.address.first_ipv4.network.to_string} #{iface.address.first_ipv6 && iface.address.first_ipv6.network.to_string} #MAINCF end end end end class Service include Construqt::Util::Chainable attr_reader :name attr_accessor :services chainable_attr_value :server_iface, nil def initialize(name) @name = name end end end Construqt::Flavour::Nixian::Dialect::Ubuntu::Services.add_renderer(Certor::Service, Certor::Renderer::Nixian::Ubuntu) <file_sep>/cluster/etcd_service.rb module Etcd class Service include Construqt::Util::Chainable attr_reader :name attr_accessor :services chainable_attr_value :server_iface, nil def initialize(name) @name = name end def self.add_component(cps) cps.register(Etcd::Service).add('etcd') end end module Renderer module Nixian class Ubuntu def initialize(service) @service = service end def interfaces(host, ifname, iface, writer, family = nil) return unless iface.address puts "#{@service.name} #{host.name} #{ifname} #{Construqt::Tags.find("ETCD_S").map{|i| i.container.name }}" domainname = "#{host.name}.#{host.region.network.domain}" cert_pkt = host.region.network.cert_store.find_package(domainname) host.result.add(self, cert_pkt.cert.content, Construqt::Resources::Rights.root_0600(Etcd::Service), "etc", "letsencrypt", "live", domainname, "cert.pem") host.result.add(self, cert_pkt.cacerts.map{|i|i.content}.join("\n"), Construqt::Resources::Rights.root_0600(Etcd::Service), "etc", "letsencrypt", "live", domainname, "fullchain.pem") host.result.add(self, cert_pkt.key.content, Construqt::Resources::Rights.root_0600(Etcd::Service), "etc", "letsencrypt", "live", domainname, "privkey.pem") ## #{@service.get_server_iface.host.name} #{@service.get_server_iface.address.first_ipv4} #inet_protocols = all Construqt::Tags.find("ETCD_S").each do |i| next if i.container.host.name == host.name domainname = "#{i.container.host.name}.#{host.region.network.domain}" cert_pkt = host.region.network.cert_store.find_package(domainname) host.result.add(self, cert_pkt.cert.content, Construqt::Resources::Rights.root_0600(Etcd::Service), "etc", "letsencrypt", "live", domainname, "cert.pem") host.result.add(self, cert_pkt.cacerts.map{|i|i.content}.join("\n"), Construqt::Resources::Rights.root_0600(Etcd::Service), "etc", "letsencrypt", "live", domainname, "fullchain.pem") end #myhostname = #{iface.host.name} #mynetworks = #{iface.address.first_ipv4.network.to_string} #{iface.address.first_ipv6 && iface.address.first_ipv6.network.to_string} #MAINCF end end end end end Construqt::Flavour::Nixian::Dialect::Ubuntu::Services.add_renderer(Etcd::Service, Etcd::Renderer::Nixian::Ubuntu) <file_sep>/cluster/cluster.rb begin require 'pry' rescue LoadError end CONSTRUQT_PATH = ENV['CONSTRUQT_PATH'] || '../../../' [ "#{CONSTRUQT_PATH}/ipaddress/ruby/lib", "#{CONSTRUQT_PATH}/construqt/core/lib", "#{CONSTRUQT_PATH}/construqt/flavours/plantuml/lib", "#{CONSTRUQT_PATH}/construqt/flavours/gojs/lib", "#{CONSTRUQT_PATH}/construqt/flavours/nixian/core/lib", "#{CONSTRUQT_PATH}/construqt/flavours/nixian/dialects/ubuntu/lib", "#{CONSTRUQT_PATH}/construqt/flavours/nixian/dialects/coreos/lib", "#{CONSTRUQT_PATH}/construqt/flavours/mikrotik/lib", "#{CONSTRUQT_PATH}/construqt/flavours/ciscian/core/lib", "#{CONSTRUQT_PATH}/construqt/flavours/ciscian/dialects/hp/lib", "#{CONSTRUQT_PATH}/construqt/flavours/unknown/lib" ].each { |path| $LOAD_PATH.unshift(path) } require 'rubygems' require 'construqt' require 'construqt/flavour/nixian' require 'construqt/flavour/nixian/dialect/ubuntu' require 'construqt/flavour/nixian/dialect/coreos' require_relative 'ship.rb' require_relative 'service.rb' require_relative 'firewall.rb' def setup_region(name, network) region = Construqt::Regions.add(name, network) nixian = Construqt::Flavour::Nixian::Factory.new nixian.add_dialect(Construqt::Flavour::Nixian::Dialect::Ubuntu::Factory.new) nixian.add_dialect(Construqt::Flavour::Nixian::Dialect::CoreOs::Factory.new) region.flavour_factory.add(nixian) if ARGV.include?('plantuml') require 'construqt/flavour/plantuml.rb' region.add_aspect(Construqt::Flavour::Plantuml.new) end region.network.ntp.add_server(region.network.addresses.add_ip('172.16.31.10').add_ip('172.16.58.3')).timezone('MET') region.users.add('menabe', 'group' => 'admin', 'full_name' => '<NAME>', 'public_key' => <<KEY, 'email' => '<EMAIL>') ssh-rsa A<KEY>NW8wE4pjyotDJ8jaW2d7oVIMdWqE2M9Z1sLqDDdhHdVMFxk6Hl2XfqeqO2Jnst7qzbHAN/S3hvSwysixWJEcLDVG+cg1KRwz4qafCU5oHSp8aNNOk4RZozboFjac17nOmfPfnjC/LLayjSkEBZ+eFi+njZRLDN92k3PvHYFEB3USbHYzICsuDcf+L4cslX03g7w== openpgp:0x5F1BE34D KEY region.users.add('martin', 'group' => 'admin', 'full_name' => '<NAME>', 'public_key' => <<KEY, 'email' => '<EMAIL>') ssh-rsa AAA<KEY>2<KEY>G5uO8WF72Wh6uLAsFOgae7lgFn4R/<KEY>wa<KEY>fv<KEY>Gv<KEY>+fPrUs/17Yeq<KEY>iEnph6fg<KEY>qPqMV7vKrMnYd0Q/NzqVkSdX5SOBrVKui18JRbCrxz5Ld9Jk2SsaR/kEBOdM/QlT6PHCxlVGd0JSdMb6DtvehPH+DdUHI4jdydH6Pq/gHU9SeMdy0J/ZJJuCLit392AnZm50lB366LSEcm423Kb3W5JdClyg8Q/+Kw2HXoQHwS4qX1SxW8UtOmwo2iVwA9E4a2L7ymAu7c7yHKozZg+mKnkO+XUgcLod9GKylVFtsOmu9kHBDIi3M<KEY>== <PASSWORD>@cer<PASSWORD>ssh KEY ['dns_service.rb', 'etcd_service.rb', 'certor_service.rb', 'posco_service.rb', 'sni_proxy_service.rb', 'tunator_service.rb'].each { |f| require_relative f } region.services.add(Dns::Service.new('DNS')) region.services.add(Etcd::Service.new('ETCD')) region.services.add(Certor::Service.new('CERTOR')) region.services.add(SniProxy::Service.new('SNIPROXY')) region.services.add(Posco::Service.new('POSCO')) region.services.add(Tunator::Service.new('TUNATOR')) region end def cluster_json return <<JSON { "etcbinds":[ { "name":"eu-0", "ipv4_extern":"10.24.1.200/24", "ipv4_addr":"10.24.1.200/24", "ipv4_gw":"10.24.1.1", "ipv6_addr":"fd00::10:24:1:200/64", "ipv6_gw":"fd00::10:24:1:1", "ipv4_intern":"169.254.200.1/24", "ipv6_intern":"fd00::169:254:200:1/112" }, { "name":"eu-1", "ipv4_extern":"10.24.1.201/24", "ipv4_addr":"10.24.1.201/24", "ipv4_gw":"10.24.1.1", "ipv6_addr":"fd00::10:24:1:201/64", "ipv6_gw":"fd00::10:24:1:1", "ipv4_intern":"169.254.201.1/24", "ipv6_intern":"fd00::169:254:201:1/112" }, { "name":"us-0", "ipv4_extern":"10.24.1.202/24", "ipv4_addr":"10.24.1.202/24", "ipv4_gw":"10.24.1.1", "ipv6_addr":"fd00::10:24:1:202/64", "ipv6_gw":"fd00::10:24:1:1", "ipv4_intern":"169.254.202.1/24", "ipv6_intern":"fd00::169:254:202:1/112" }], "vips":[ { "name":"eu-0", "ipv4_extern":"10.24.1.210/24", "ipv4_addr":"10.24.1.210/24", "ipv4_gw":"10.24.1.1", "ipv6_addr":"fd00::10:24:1:210/64", "ipv6_gw":"fd00::10:24:1:1", "ipv4_intern":"169.254.210.1/24", "ipv6_intern":"fd00::169:254:210:1/112" }, { "name":"eu-1", "ipv4_extern":"10.24.1.211/24", "ipv4_addr":"10.24.1.211/24", "ipv4_gw":"10.24.1.1", "ipv6_addr":"fd00::10:24:1:211/64", "ipv6_gw":"fd00::10:24:1:1", "ipv4_intern":"169.254.211.1/24", "ipv6_intern":"fd00::169:254:211:1/112" }, { "name":"us-0", "ipv4_extern":"10.24.1.212/24", "ipv4_addr":"10.24.1.212/24", "ipv4_gw":"10.24.1.1", "ipv6_addr":"fd00::10:24:1:212/64", "ipv6_gw":"fd00::10:24:1:1", "ipv4_intern":"169.254.212.1/24", "ipv6_intern":"fd00::169:254:212:1/112" }], "certs":{ "path":"../../certs/" }, "domain":"protonet.io", "email":"<EMAIL>" } JSON end def get_config fname = "#{ENV['USER']}.cfg.json" obj = JSON.parse(if File.exists?(fname) IO.read(fname) else cluster_json end) end network = Construqt::Networks.add('protonet') network.set_domain(get_config['domain']) network.set_contact(get_config['email']) network.set_dns_resolver(network.addresses.set_name('NAMESERVER') .add_ip('8.8.8.8') .add_ip('8.8.4.4') .add_ip('fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b') .add_ip('fc00:e968:6179::de52:7100'), [network.domain]) region = setup_region('protonet', network) firewall(region) base = 200 def pullUp(p) OpenStruct.new(p.merge( 'ipv4_addr' => IPAddress.parse(p['ipv4_addr']), 'ipv4_gw' => IPAddress.parse(p['ipv4_gw']), 'ipv6_addr' => IPAddress.parse(p['ipv6_addr']), 'ipv6_gw' => IPAddress.parse(p['ipv6_gw']), 'ipv4_intern' => IPAddress.parse(p['ipv4_intern']), 'ipv6_intern' => IPAddress.parse(p['ipv6_intern']) )) end def get_config_and_pullUp(key) get_config[key].map{|x| pullUp(x) } end def load_certs(network) Dir.glob(File.join(get_config["certs"]["path"]||'/etc/letsencrypt/live',"*")).each do|dname| next unless File.directory?(dname) Construqt.logger.info "Reading Certs for #{File.basename(dname)}" network.cert_store.create_package(File.basename(dname), network.cert_store.add_private(File.basename(dname),IO.read(File.join(dname,'privkey.pem'))), network.cert_store.add_cert(File.basename(dname),IO.read(File.join(dname,'cert.pem'))), [network.cert_store.add_cacert(File.basename(dname),IO.read(File.join(dname,'chain.pem')))] ) end end load_certs(network) etcbinds = get_config_and_pullUp("etcbinds").map do |j| mother_firewall(j.name) ship = make_ship(region, 'name' => "etcbind-#{j.name}", 'firewalls' => ["#{j.name}-ipv4-map-dns", "#{j.name}-ipv4-map-certor","#{j.name}-ipv6-etcd"], 'ifname' => 'enp0s8', 'proxy_neigh_host' => "##{j.name}_GW_S##{j.name}_DNS_S##{j.name}_ETCD_S##{j.name}_CERTOR_S", 'ipv4_addr' => "#{j.ipv4_addr.to_string}##{j.name}_DNS_S##{j.name}_CERTOR_S", 'ipv4_gw' => j.ipv4_gw.to_s, 'ipv6_addr' => j.ipv6_addr.to_string, 'ipv6_gw' => j.ipv6_gw.to_s, 'ipv4_intern' => j.ipv4_intern.to_string, 'ipv6_intern' => "#{j.ipv6_intern.to_string}##{j.name}_GW_S#GW_S") ipv4 = j.ipv4_intern.inc ipv6 = j.ipv6_intern.inc make_service(region, 'service' => 'DNS', 'mother' => ship, 'mother_if' => 'br169', 'name' => "dns-#{j.name}", 'firewalls' => ['dns-srv'], 'ifname' => 'eth0', 'rndc_key' => 'total geheim', 'domains' => [{ 'name' => 'construqt.net', 'basefile' => 'costruqt.net.zone' }], 'ipv4_addr' => "#{ipv4.to_string.to_s}##{j.name}-DNS_MAPPED", 'ipv4_gw' => j.ipv4_intern.to_s, 'ipv6_addr' => "#{ipv6.to_string}##{j.name}-DNS_MAPPED##{j.name}_DNS_S#DNS_S", 'ipv6_gw' => j.ipv6_intern.to_s) ipv4 = ipv4.inc ipv6 = ipv6.inc make_service(region, 'service' => 'ETCD', 'mother' => ship, 'mother_if' => 'br169', 'name' => "etcd-#{j.name}", 'firewalls' => ['etcd-srv'], 'ifname' => 'eth0', 'rndc_key' => 'total geheim', 'domains' => [{ 'name' => 'construqt.n:et', 'basefile' => 'costruqt.net.zone' }], 'ipv6_addr' => "#{ipv6.to_string}##{j.name}-ETCD_MAPPED##{j.name}_ETCD_S#ETCD_S", 'ipv6_gw' => j.ipv6_intern.to_s) ipv4 = ipv4.inc ipv6 = ipv6.inc make_service(region, 'service' => 'CERTOR', 'mother' => ship, 'mother_if' => 'br169', 'name' => "certor-#{j.name}", 'firewalls' => ["#{j.name}-map-https-8443"], 'ifname' => 'eth0', 'rndc_key' => 'total geheim', 'domains' => [{ 'name' => 'construqt.net', 'basefile' => 'costruqt.net.zone' }], 'ipv4_addr' => "#{ipv4.to_string.to_s}##{j.name}-CERTOR_MAPPED#CERTOR_S", 'ipv4_gw' => "169.254.#{base}.1", 'ipv6_addr' => "#{ipv6.to_string}##{j.name}-CERTOR_MAPPED##{j.name}_CERTOR_S#CERTOR_S", 'ipv6_gw' => j.ipv6_intern.to_s) base += 1 ship end vips = get_config_and_pullUp("vips").map do |j| ship = make_ship(region, 'name' => "vips-#{j.name}", 'ifname' => j.iface||'enp0s8', 'dialect' => j.dialect, 'firewalls' => ["#{j.name}-ipv4-map-sni", "#{j.name}-posco"], 'proxy_neigh_host' => "##{j.name}_SNI_S##{j.name}_POSCO_S##{j.name}_TUNATOR_S", 'proxy_neigh_net' => "##{j.name}_TUNATOR_S_NET", 'ipv4_addr' => "#{j.ipv4_addr.to_string}#DNS_S#CERTOR_S", 'ipv4_gw' => j.ipv4_gw.to_s, 'ipv6_addr' => j.ipv6_addr.to_string, 'ipv6_gw' => j.ipv6_gw.to_s, 'ipv4_intern' => j.ipv4_intern.to_string, 'ipv6_intern' => j.ipv6_intern.to_string) ipv4 = j.ipv4_intern.inc ipv6 = j.ipv6_intern.inc make_service(region, 'service' => 'SNIPROXY', 'mother' => ship, 'mother_if' => 'br169', 'name' => "sniproxy-#{j.name}", 'firewalls' => ['https-srv'], 'ifname' => 'eth0', 'rndc_key' => 'total geheim', 'domains' => [{ 'name' => 'construqt.net', 'basefile' => 'costruqt.net.zone' }], 'ipv6_addr' => "#{ipv6.to_string}#SNIPROXY_S##{j.name}-SNI_MAPPED##{j.name}_SNI_S", 'ipv6_gw' => j.ipv6_intern.to_string) ipv4 = ipv4.inc ipv6 = ipv6.inc make_service(region, 'service' => 'POSCO', 'mother' => ship, 'mother_if' => 'br169', 'name' => "poscos-#{j.name}", 'firewalls' => ['https-srv'], 'ifname' => 'eth0', 'rndc_key' => 'total geheim', 'domains' => [{ 'name' => 'construqt.net', 'basefile' => 'costruqt.net.zone' }], 'ipv6_addr' => "#{ipv6.to_string}#POSCO_S##{j.name}-posco##{j.name}-POSCO_MAPPED##{j.name}_POSCO_S", 'ipv6_gw' => j.ipv6_intern.to_string) ipv4 = ipv4.inc ipv6 = ipv6.inc tunator_firewall(j.name) tunator_block_ofs = j.ipv6_intern.size().shr(1) tunator_block = j.ipv6_intern.network.add_num(tunator_block_ofs).change_prefix(119) region.network.addresses.add_ip("#{tunator_block.to_string}##{j.name}_TUNATOR_S_NET") make_service(region, 'service' => 'TUNATOR', 'mother' => ship, 'mother_if' => 'br169', 'name' => "tunators-#{j.name}", 'firewalls' => ["#{j.name}-tunator"], 'ifname' => 'eth0', 'rndc_key' => 'total geheim', 'domains' => [{ 'name' => 'construqt.net', 'basefile' => 'costruqt.net.zone' }], 'ipv6_proxy_neigh' => "##{j.name}_TUNATOR_S_NET", 'ipv4_addr' => "#{ipv4.to_string}", 'ipv4_gw' => j.ipv4_intern.to_string, 'ipv6_addr' => "#{ipv6.to_string}#TUNATOR_S##{j.name}-tunator##{j.name}_TUNATOR_S", 'ipv6_gw' => j.ipv6_intern.to_string) end region.hosts.add('cerberus', "flavour" => "nixian", "dialect" => "ubuntu") do |host| region.interfaces.add_device(host, "lo", "mtu" => "9000", :description=>"#{host.name} lo", "address" => region.network.addresses.add_ip(Construqt::Addresses::LOOOPBACK)) host.configip = host.id ||= Construqt::HostId.create do |my| my.interfaces << iface = region.interfaces.add_device(host, "eth0", "mtu" => 1500, "address" => region.network.addresses.add_ip(Construqt::Addresses::DHCPV4),"firewalls" => ["border-masq"]) end region.interfaces.add_bridge(host, 'bridge0',"mtu" => 1500, "interfaces" => [], "address" => region.network.addresses.add_ip("10.24.1.1/24", "dhcp" => Construqt::Dhcp.new.start("10.24.1.100").end("10.24.1.110").domain("cerberus")) .add_ip("fd00::10:24:1:1/64")) end Construqt.produce(region)
377105916f7a7a39ec9d01c84cbc5868a9fff975
[ "Ruby" ]
4
Ruby
protonet/posco
fd0d5d9d447fd65462ef1d924e8cf19156b5cd06
717f16aa620a794d5368a3174246d5a30bbe05fc
refs/heads/main
<file_sep>from datetime import datetime from todoapp import db class Uses(db.Model): id = db.Column(db.Integer, primary_key=True) public_id = db.Column(db.String(500), unique=True) email = db.Column(db.String(120), unique=True) password = db.Column(db.String(500)) todos = db.relationship('Todo', backref='user', lazy='dynamic') def __repr__(self): return self.email class Todo(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(200)) data = db.Column(db.DateTime,default = datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey('uses.id'), nullable=False)<file_sep>from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config['SECRET_KEY'] = '<KEY>' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todoapp.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) migrate = Migrate(app, db) from todoapp import routes<file_sep>import React from 'react' import {BrowserRouter,Switch,Route} from 'react-router-dom' import HomePage from './pages/HomePage' import LoginPage from './pages/LoginPage' import RegisterPage from './pages/RegisterPage' const Router = () => { return ( <BrowserRouter> <Switch> <Route exact path='/' component={HomePage} /> <Route exact path="/login" component={LoginPage} /> <Route exact path="/register" component={RegisterPage} /> </Switch> </BrowserRouter> ) } export default Router <file_sep>from sqlalchemy.orm import session from todoapp import app,db from todoapp.models import Uses as User,Todo from werkzeug.security import generate_password_hash, check_password_hash from flask import request,jsonify import uuid import datetime import jwt from functools import wraps def token_required(f): @wraps(f) def decorator(*args, **kwargs): token = None if "access-token" in request.headers: token = request.headers['access-token'] if not token: return jsonify({"error":"Token is Required"}) try: data = jwt.decode(token,app.config['SECRET_KEY'],algorithms=["HS256"]) login_user = User.query.filter_by(public_id=data['public_id']).first() if not login_user: return jsonify({"error":"No User Found"}) except Exception as e: return jsonify({"error":str(e)}) return f(login_user,*args, **kwargs) return decorator @app.route('/') @token_required def home(login_user,*args, **kwargs): print("home login_user------------>",login_user) return jsonify({"message":"Hello World"}) @app.route("/api/add-get-todo",methods=["GET","POST"]) @token_required def add_get_todo(login_user,*args, **kwargs): if request.method=="POST": try: title = request.get_json()["title"] new_todo = Todo(title=title,user_id=login_user.id) db.session.add(new_todo) db.session.commit() return jsonify({"message":"Todo Created !"}) except Exception as e: return jsonify({"error":str(e)}) user_todos = Todo.query.filter_by(user_id=login_user.id) all_todo=[] for todo in user_todos: single_todo = {} single_todo["id"] =todo.id single_todo["title"] =todo.title single_todo["data"] =todo.data all_todo.append(single_todo) return jsonify({"data":all_todo}) @app.route("/api/edit-delete-todo",methods=["DELETE","POST"]) @token_required def edit_delete_todo(login_user,*args, **kwargs): if request.method == "POST": todoid = request.get_json()["todoid"] title = request.get_json()["title"] todo = Todo.query.filter_by(user_id=login_user.id,id=todoid).first() if not todo: return jsonify({"message":f"No Todo Found or This is not Your Todo !"}) todo.title=title db.session.commit() return jsonify({"message":"Todo is Updated !"}) if request.method == "DELETE": todoid = request.get_json()["todoid"] todo = Todo.query.filter_by(user_id=login_user.id,id=todoid).first() if not todo: return jsonify({"message":f"No Todo Found or This is not Your Todo !"}) db.session.delete(todo) db.session.commit() return jsonify({"message":"Todo is Deleted Successfully!"}) @app.route("/api/get-todo/<todoid>") @token_required def getTodo(login_user,todoid,*args, **kwargs): todo = Todo.query.filter_by(user_id=login_user.id,id=todoid).first() single_todo = {} single_todo["id"] =todo.id single_todo["title"] =todo.title single_todo["data"] =todo.data return jsonify({"data":single_todo}) @app.route("/api/register",methods=['POST']) def register(): data = request.get_json() print("data------->",data) try: hash_password = generate_password_hash(data['password'], method='sha256') user = User(email=data['email'], password=<PASSWORD>,public_id=str(uuid.uuid4())) db.session.add(user) db.session.commit() return jsonify({"message":"User was Created!"}) except Exception as e: return jsonify({"error":str(e)}) @app.route("/api/login",methods=["POST"]) def login(): data = request.get_json() print("login------->",data) if not data or not data["email"] or not data["password"]: return jsonify({"message":"Email and Password is Required."}) user = User.query.filter_by(email=data["email"]).first() if not user: return jsonify({"message":"No user found."}) if check_password_hash(user.password,data['password']): token = jwt.encode({"public_id":user.public_id,'exp':datetime.datetime.utcnow()+ datetime.timedelta(minutes=4500)},app.config['SECRET_KEY'],"HS256") return jsonify({"token":token}) return jsonify({"message":"Somthing is Wrong.Try Again!"}) <file_sep>alembic==1.7.3 click==8.0.1 colorama==0.4.4 dataclasses==0.8 Flask==2.0.1 Flask-Migrate==3.1.0 Flask-SQLAlchemy==2.5.1 greenlet==1.1.1 importlib-metadata==4.8.1 importlib-resources==5.2.2 itsdangerous==2.0.1 Jinja2==3.0.1 Mako==1.1.5 MarkupSafe==2.0.1 python-dotenv==0.19.0 SQLAlchemy==1.4.23 typing-extensions==3.10.0.2 Werkzeug==2.0.1 zipp==3.5.0 <file_sep>import React from 'react' const RegisterPage = () => { return ( <div> <h1>Register Now</h1> <p>Login Now</p> </div> ) } export default RegisterPage <file_sep># Flask-and-React-js-Todo-List-App-in-Bangla <!-- ### [🔥🔥Part - 0]() --> ## [See Videos](https://www.youtube.com/playlist?list=PLsC9YeVUTz3_fqXYxLRxIIQfYWII7vLe4) ### [🔥🔥Part - 0 - No Code For This Video ](#) ### [🔥🔥Part - 1](https://github.com/codewithrafiq/Flask-and-React-js-Todo-List-App-in-Bangla/tree/a5e5ff059ba5a363a734f2b60c5c3746fb700994) ### [🔥🔥Part - 2](https://github.com/codewithrafiq/Flask-and-React-js-Todo-List-App-in-Bangla/tree/440dd5165b2190420fc0f78e0edc6219e9a2c515) ### [🔥🔥Part - 3](https://github.com/codewithrafiq/Flask-and-React-js-Todo-List-App-in-Bangla/tree/18bce6c5094b2fa83ad5d9de920b363a1abaa984) <file_sep>import React from 'react' import {Grid} from '@mui/material' const LoginPage = () => { return ( <Grid container direction="column" justifyContent="center" alignItems="center" spacing={3} > <h1>Login Now</h1> <p>Register Now</p> </Grid> ) } export default LoginPage
92b70381977d4e1126942b72b110c6e87cb7f1f3
[ "JavaScript", "Python", "Text", "Markdown" ]
8
Python
codewithrafiq/Flask-and-React-js-Todo-List-App-in-Bangla
bc90a50e9af68e1403b81d6e39bcd810a069e0c5
7083579438b69a4a7139866bfcde63d9f81231ce
refs/heads/master
<repo_name>SirTyz/tylercox.design<file_sep>/app/scripts/controllers/about.js 'use strict'; /** * @ngdoc function * @name nodeAppApp.controller:AboutCtrl * @description * # AboutCtrl * Controller of the nodeAppApp */ angular.module('nodeAppApp') .controller('DumpsCtrl', function () { //Animation declarations var turnRight = new Bounce(); turnRight.rotate({ from: 0, to: 360, duration: 2000 }); var rightReturn = new Bounce(); rightReturn.rotate({ from: 360, to: 0, duration: 2000 }); var bumpUp = new Bounce(); bumpUp.scale({ from: {x: 0.5, y: 0.5}, to: {x: 1, y: 1}, duration: 2000 }); var slideIn = new Bounce(); slideIn.translate({ from: { x: 0, y: -2500 }, to: { x: 0, y: 0 }, duration: 2000 }); var slideUp = new Bounce(); slideUp.translate({ from: { x: 0, y: 0 }, to: { x: 0, y: -250} }); var slideDown = new Bounce(); slideDown.translate({ from: { x: 0, y: -250}, to: { x: 0, y: 0} }); //Animation binding with elements //Navbar $(".socialContainer a i").mouseenter(function(){ console.log(this); turnRight.applyTo($(this)); }); $(".socialContainer a i").mouseleave(function(){ console.log(this); rightReturn.applyTo($(this)); }); $(".navbar li").mouseenter(function(){ bumpUp.applyTo($(this)); }); //WebDump Animations $(".webDump1").mouseenter(function(){ console.log('I made it here.') slideUp.applyTo($(".faceText1")); slideUp.applyTo($(".descriptorText1")); }); $(".webDump1").mouseleave(function(){ console.log('I made it here.') slideDown.applyTo($(".faceText1")); slideDown.applyTo($(".descriptorText1")); }); $(".webDump2").mouseenter(function(){ console.log('I made it here.') slideUp.applyTo($(".faceText2")); slideUp.applyTo($(".descriptorText2")); }); $(".webDump2").mouseleave(function(){ console.log('I made it here.') slideDown.applyTo($(".faceText2")); slideDown.applyTo($(".descriptorText2")); }); $(".webDump3").mouseenter(function(){ console.log('I made it here.') slideUp.applyTo($(".faceText3")); slideUp.applyTo($(".descriptorText3")); }); $(".webDump3").mouseleave(function(){ console.log('I made it here.') slideDown.applyTo($(".faceText3")); slideDown.applyTo($(".descriptorText3")); }); $(".webDump4").mouseenter(function(){ console.log('I made it here.') slideUp.applyTo($(".faceText4")); slideUp.applyTo($(".descriptorText4")); }); $(".webDump4").mouseleave(function(){ console.log('I made it here.') slideDown.applyTo($(".faceText4")); slideDown.applyTo($(".descriptorText4")); }); $(".webDump5").mouseenter(function(){ console.log('I made it here.') slideUp.applyTo($(".faceText5")); slideUp.applyTo($(".descriptorText5")); }); $(".webDump5").mouseleave(function(){ console.log('I made it here.') slideDown.applyTo($(".faceText5")); slideDown.applyTo($(".descriptorText5")); }); //Page Slide Animations slideIn.applyTo($(".outerCenterContainer")); slideIn.applyTo($(".innerCenterContainer")); //About Button $(".aboutButton").mouseenter(function(){ bumpUp.applyTo($(this)); }); });
a08d5e50bea82edda03b8a46d84703c58dc21830
[ "JavaScript" ]
1
JavaScript
SirTyz/tylercox.design
07b69e0832253ff3da6aa2403c6937edfb1760f6
4fc15061dc260716baaa753d17f156a8c31a66e4
refs/heads/master
<file_sep>require("dotenv").config(); const TelegramBot = require("node-telegram-bot-api"); const _ = require("lodash"); // stored messages that can be send by the bot let data = require("./messages.json"); const consejos = data.mensajes; // replace the value below with the Telegram token you receive from @BotFather const token = process.env.BOT_TOKEN; // Create a bot that uses 'polling' to fetch new updates const bot = new TelegramBot(token, { polling: true }); // Set response for command start bot.onText(/\/start/, msg => { bot.sendMessage( msg.chat.id, "Bienvenido, escribe acamica o agregame un grupo y respondere cuando hablen de mi" ); }); // Set response for command Acamica bot.on("message", msg => { const consejo = _.sample(consejos); var chatId = msg.chat.id; var messageId = msg.message_id; var user = msg.from.first_name; // Set response if acamica is named if ( msg.text .toString() .toLowerCase() .includes("acamica") ) { // send a recomendation bot.sendMessage(chatId, "<code>" + consejo + "</code> \u{1F60E}", { parse_mode: "HTML" }); } else if ( msg.text .toString() .toLowerCase() .endsWith("hola") ) { // reply to 'hi' message in silence bot.sendMessage(chatId, `<code>Buenas ${user} </code> \u{1F4BB}`, { parse_mode: "HTML", disable_notification: true, reply_to_message_id: messageId }); } }); // for debugging errors bot.on("polling_error", err => console.log(err));
c1aaaa9bb72f785e6fd8c8bc786ceb7ff9bae1a1
[ "JavaScript" ]
1
JavaScript
MartoBigOdi/acamicusbot
ad2163508dd8a7798a164782390aa48afa7af942
d3e3763352f21ee7ec6f2c0c8e12d1c04f06b3c0
refs/heads/master
<file_sep>// MIT License // // Copyright (c) 2018 Ambiesoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // libwnmain.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include <Windows.h> #include <tlhelp32.h> #include <set> #include <iostream> #include <sstream> #include <functional> #include "lsMisc/stdosd/SetPrority.h" #include "lsMisc/CommandLineString.h" #include "lsMisc/CreateProcessCommon.h" #include "lsMisc/GetLastErrorString.h" #include "lsMisc/tstring.h" #include "lsMisc/stdosd/stdosd.h" #include "libwinnice.h" #include "helper.h" using namespace Ambiesoft; using namespace Ambiesoft::stdosd; using namespace std; // TODO: implement std::set<std::wstring> gOptions = { L"--helpmore", L"-h", }; wstring op(wstring option) { assert(gOptions.find(option) != gOptions.end()); return option; } // TODO: implement wstring GetHammingSuggest(wstring option) { return wstring(); } bool gWaiting; BOOL WINAPI CtrlHandler(DWORD fdwCtrlType) { switch (fdwCtrlType) { // Handle the CTRL-C signal. case CTRL_C_EVENT: if (gWaiting) { printf("winnice ignores Ctrl-C event.\n"); return TRUE; } } return FALSE; } set<DWORD> GetProcessIDFromExecutable(LPCTSTR pExe) { set<DWORD> retVec; PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { // TODO: Fullpath and Filename compare properly if (lstrcmpi(entry.szExeFile, pExe) == 0) { retVec.insert(entry.th32ProcessID); } } } CloseHandle(snapshot); return retVec; } template<typename chartype> basic_string<chartype> stdGetEnv(const basic_string<chartype>& s) { chartype buff[1024]; buff[0] = 0; size_t req; _wgetenv_s(&req, buff, s.c_str()); return buff; } template<typename stringtype> bool IsExecutableExtension(stringtype s) { if (s.empty()) return false; stringtype env = stdGetEnv(stringtype(MYL("PATHEXT"))); vector<stringtype> vExts = stdSplitString(env, MYL(";")); if (s[0] != MYL('.')) s = MYL('.') + s; for (auto&& ext : vExts) { if (lstrcmpi(ext.c_str(), s.c_str()) == 0) return true; } return false; } tstring ModifyCommand(const tstring& command) { CCommandLineStringBase<tchar> cms(command); if (cms.getCount() == 0) return command; tstring exe = cms.getArg(0); tstring ext = stdGetFileExtension(exe); if (ext.empty()) return MYL("cmd /c ") + command; if (!IsExecutableExtension(ext)) return MYL("cmd /c ") + command; // extension is executable return command; } inline void ShowOutput(const wstring& s) { ShowOutputW(s); } inline void ShowOutput(const wstringstream& s) { ShowOutputW(s); } inline void ShowError(const wstring& s) { ShowErrorW(s); } inline void ShowError(const wstringstream& s) { ShowErrorW(s); } wstring GetNextArgOrShowError(size_t& i, size_t count, const CCommandLineString& cms, const tstring option) { if ((i + 1) == count) { ShowError(MYL("No argument for ") + option); return tstring(); } ++i; tstring next = cms.getArg(i); if (next.empty()) { ShowError(option + MYL(" is empty")); return tstring(); } return next; } enum TargetType { TARGET_NONE, TARGET_FIND_FROM_EXECUTABLE, TARGET_NEW_PROCESS, }; enum ERROR_LEVEL { ERROR_LEVEL_NONE, ERROR_LEVEL_NORMAL, ERROR_LEVEL_DEBUG, }; int LibWinNiceMainW( bool bGui, int argc, const wchar_t* const* argv, WNUShowInformationW wnuShowOutputW, WNUShowInformationW wnuShowErrorW) { gUFShowOutputW = wnuShowOutputW; gUFShowErrorW = wnuShowErrorW; CCommandLineStringBase<tchar> cms(argc,argv); Process::CPUPRIORITY cpuPriority = Process::CPUPRIORITY::CPU_NONE; Process::IOPRIORITY ioPriority = Process::IOPRIORITY::IO_NONE; Process::MEMORYPRIORITY memPriority = Process::MEMORYPRIORITY::MEMORY_NONE; bool showCommand = false; bool exitifsetpriorityfailed = false; bool detachNewProcess = bGui ? true : false; bool newProcess = false; size_t nSubcommandStartIndex = -1; const size_t count = cms.getCount(); set<DWORD> pidsToProcess; ERROR_LEVEL errorLevel = ERROR_LEVEL_NORMAL; { // ensure these 2 sets are in this scope set<wstring> targetExes; set<DWORD> targetPIDs; if (count <= 1) { ShowError(L"No arguments"); return 1; } for (size_t i = 1; i < count; ++i) { tstring option = cms.getArg(i); if (false) ; else if (option == MYL("--cpu-high")) cpuPriority = Process::CPU_HIGH; else if (option == MYL("--cpu-abovenormal")) cpuPriority = Process::CPU_ABOVENORMAL; else if (option == MYL("--cpu-normal")) cpuPriority = Process::CPU_NORMAL; else if (option == MYL("--cpu-belownormal")) cpuPriority = Process::CPU_BELOWNORMAL; else if (option == MYL("--cpu-idle")) cpuPriority = Process::CPU_IDLE; else if (option == MYL("--cpu-default")) cpuPriority = Process::CPU_NONE; else if (option == MYL("--io-high")) ioPriority = Process::IO_NORMAL; // IO_HIGH; else if (option == MYL("--io-abovenormal")) ioPriority = Process::IO_NORMAL; // IO_ABOVENORMAL; else if (option == MYL("--io-normal")) ioPriority = Process::IO_NORMAL; else if (option == MYL("--io-belownormal")) ioPriority = Process::IO_BELOWNORMAL; else if (option == MYL("--io-idle")) ioPriority = Process::IO_IDLE; else if (option == MYL("--io-default")) ioPriority = Process::IO_NONE; else if (option == MYL("--mem-high")) memPriority = Process::MEMORY_HIGH; else if (option == MYL("--mem-abovenormal")) memPriority = Process::MEMORY_HIGH; else if (option == MYL("--mem-normal")) memPriority = Process::MEMORY_HIGH; else if (option == MYL("--mem-belownormal")) memPriority = Process::MEMORY_BELOWNORMAL; else if (option == MYL("--mem-idle")) memPriority = Process::MEMORY_IDLE; else if (option == MYL("--mem-default")) memPriority = Process::MEMORY_NONE; else if (option == MYL("--all-high")) { cpuPriority = Process::CPU_HIGH; ioPriority = Process::IO_NORMAL; memPriority = Process::MEMORY_HIGH; } else if (option == MYL("--all-abovenormal")) { cpuPriority = Process::CPU_ABOVENORMAL; ioPriority = Process::IO_NORMAL; memPriority = Process::MEMORY_HIGH; } else if (option == MYL("--all-normal")) { cpuPriority = Process::CPU_NORMAL; ioPriority = Process::IO_NORMAL; memPriority = Process::MEMORY_HIGH; } else if (option == MYL("--all-belownormal")) { cpuPriority = Process::CPU_BELOWNORMAL; ioPriority = Process::IO_BELOWNORMAL; memPriority = Process::MEMORY_BELOWNORMAL; } else if (option == MYL("--all-idle")) { cpuPriority = Process::CPU_IDLE; ioPriority = Process::IO_IDLE; memPriority = Process::MEMORY_IDLE; } else if (option == MYL("--show-command")) showCommand = true; else if (option == MYL("--exit-if-setpriority-failed")) exitifsetpriorityfailed = true; else if (option == MYL("--detach-newprocess")) detachNewProcess = true; else if (option == MYL("--wait-newprocess")) detachNewProcess = false; else if (option == MYL("--executable")) { tstring exe = GetNextArgOrShowError(i, count, cms, option); if (exe.empty()) { ShowError(L"No executable specified"); return 1; } targetExes.insert(exe); } else if (option == MYL("--pid")) { tstring pids = GetNextArgOrShowError(i, count, cms, option); if (pids.empty()) return 1; vector<tstring> vPids = stdSplitString(pids, MYL(",")); if (vPids.empty()) { ShowError(MYL("Pid parsed empty")); return 1; } // not yet set assert(targetPIDs.empty()); // Check pid is a number for (auto&& pid : vPids) { if (!stdIsTdigit(pid)) { ShowError(stdFormat(MYL("pid %s is not a number"), pid.c_str())); return 1; } // TODO: To tochar in osd targetPIDs.insert(_wtol(pid.c_str())); } } else if (option == MYL("--new-process")) { newProcess = true; } else if (option == MYL("-v")) { ShowVersionW(); return 0; } else if (option == MYL("-h") || option == MYL("/h") || option == MYL("--help")) { ShowHelpW(); return 0; } else if (option == op(L"--helpmore")) { ShowHelpW(true); return 0; } else if (option == MYL("--error-level")) { tstring errorLevelString = GetNextArgOrShowError(i, count, cms, option); if (errorLevelString.empty()) { ShowError(L"No error level specified"); return 1; } if (errorLevelString == L"normal") { // default } else if (errorLevelString == L"debug") { errorLevel = ERROR_LEVEL_DEBUG; } else { wstringstream wss; wss << L"Unknown error level '" << errorLevelString << "'" << endl; ShowError(wss.str()); return 1; } } else if (option == MYL("--show-nooutput")) { gShowNoOutput = true; } else if (option == MYL("--show-noerror")) { gShowNoError = true; } else if (option.size() > 1 && option[0] == MYL('-')) { wstringstream message; message << (MYL("Unknown option:") + option) << endl; message << GetHammingSuggest(option) << endl; ShowError(message.str()); return 1; } else { if (option == MYL("-")) { // treat next argument as main arg if ((i + 1) == count) { ShowError(MYL("Insufficient argument after '-'")); return 1; } ++i; option = cms.getArg(i); // and fall through } // --new-process is omittable //if (targetType != TARGET_NONE && targetType != TARGET_NEW_PROCESS) //{ // ShowError(MYL("Both --executable and --new-process could not be specified.")); // return 1; //} //targetType = TARGET_NEW_PROCESS; nSubcommandStartIndex = i; break; } } // Set pid for processing for (auto&& exe : targetExes) { set<DWORD> vs = GetProcessIDFromExecutable(exe.c_str()); if (vs.empty() && errorLevel >= ERROR_LEVEL_DEBUG) { tstringstream tss; tss << MYL("\"") << exe << MYL("\"") << MYL(" ") << MYL("not found") << endl; ShowError(tss); } else { pidsToProcess.insert(vs.begin(), vs.end()); } } pidsToProcess.insert(targetPIDs.begin(), targetPIDs.end()); } bool isProcessed = false; if (!pidsToProcess.empty()) { isProcessed = true; //if (()) //{ // ShowError(MYL("Target process not found")); // return 1; //} if (cpuPriority == Process::CPU_NONE && ioPriority == Process::IO_NONE && memPriority == Process::MEMORY_NONE) { ShowError(MYL("No priorities specified")); return 1; } tstringstream errorMessage; int err; for (auto&& dwProcessID : pidsToProcess) { err = DoSetPriority(dwProcessID, cpuPriority,ioPriority,memPriority, exitifsetpriorityfailed, errorMessage); if(err != 0 && exitifsetpriorityfailed) { ShowError(errorMessage); return err; } } if (err != 0) { ShowError(errorMessage); return err; } } if(newProcess) { isProcessed = true; tstring newcommnad = cms.subString(nSubcommandStartIndex); if (newcommnad.empty()) { tstringstream tss; tss << MYL("No command to run") << endl; ShowError(tss); return 1; } if (showCommand) { tstringstream tss; tss << newcommnad << endl; ShowOutput(tss); } DWORD dwLastError = 0; HANDLE hProcess = NULL; DWORD dwProcessID = 0; HANDLE hThread = NULL; if (!CreateProcessCommon( NULL, bGui ? newcommnad.c_str() : ModifyCommand(newcommnad).c_str(), FALSE, &dwLastError, WaitProcess_None, INFINITE, &hProcess, &dwProcessID, &hThread, NULL, TRUE)) { wstringstream wss; wss << L"Failed to CreateProcess (LastError=" << dwLastError << L")" << endl; ShowError(wss.str()); return dwLastError; } unique_ptr<HANDLE, std::function<void(HANDLE*)>> hProcess_free(&hProcess, [](HANDLE* pH) { DVERIFY(::CloseHandle(*pH)); }); unique_ptr<HANDLE, std::function<void(HANDLE*)>> hThread_free(&hThread, [](HANDLE* pH) { DVERIFY(::CloseHandle(*pH)); }); if (!bGui) { if (!SetConsoleCtrlHandler(CtrlHandler, TRUE)) { DWORD dwLastError = GetLastError(); wstringstream wss; wss << L"SetConsoleCtrlHandler Failed (LastError=" << dwLastError << L")" << endl; ShowError(wss.str()); return dwLastError; } } if (!(cpuPriority == Process::CPU_NONE && ioPriority == Process::IO_NONE && memPriority == Process::MEMORY_NONE)) { tstringstream errorMessage; int err = DoSetPriority(dwProcessID, cpuPriority,ioPriority,memPriority, exitifsetpriorityfailed, errorMessage); if (err != 0) { ShowError(errorMessage); if (exitifsetpriorityfailed) { TerminateProcess(hProcess, -1); return err; } } } if (!ResumeThread(hThread)) { ShowError(MYL("Resuming failed")); TerminateProcess(hProcess, -1); return 1; } if (detachNewProcess) { return 0; } gWaiting = true; WaitForSingleObject(hProcess, INFINITE); gWaiting = false; DWORD dwExitCode = -1; if (!GetExitCodeProcess(hProcess, &dwExitCode)) { DWORD dwLastError = GetLastError(); wstringstream wss; wss << MYL("Failed to get exit code (LastError=") << dwLastError << MYL(")") << endl; ShowError(wss.str()); return dwLastError; } return dwExitCode; } if (!isProcessed) { ShowOutput(MYL("No operation to process")); } return 0; } //int LibWinNiceMainA( // bool bGui, // WNUShowInformationA wnuShowOutputA, // WNUShowInformationA wnuShowErrorA) //{ // return 0; //} <file_sep>// MIT License // // Copyright (c) 2018 Ambiesoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "StdAfx.h" #include <sstream> // #include "../../tstring.h" #include "lsMisc/GetLastErrorString.h" #include "libwinnice.h" #include "helper.h" using namespace Ambiesoft::stdosd; WNUShowInformationW gUFShowOutputW; WNUShowInformationW gUFShowErrorW; bool gShowNoOutput = false; bool gShowNoError = false; #define CHECK_USERFUNC(func) do { if(!func) {return;}} while(false) using namespace std; using namespace Ambiesoft; void ShowOutputW(const wchar_t* pMessage) { if (gShowNoOutput) return; CHECK_USERFUNC(gUFShowOutputW); gUFShowOutputW(pMessage); } void ShowOutputW(const std::wstring& s) { ShowOutputW(s.c_str()); } void ShowOutputW(const std::wstringstream& s) { ShowOutputW(s.str()); } void ShowErrorW(const wchar_t* pMessage) { if (gShowNoError) return; CHECK_USERFUNC(gUFShowErrorW); gUFShowErrorW(pMessage); } void ShowErrorW(const std::wstring& message) { ShowErrorW(message.c_str()); } void ShowErrorW(const std::wstringstream& message) { ShowErrorW(message.str()); } tstring GetErrorWithLastErrorW(int err, DWORD pid) { wstring errorMessage = GetLastErrorString(err); if (!errorMessage.empty()) errorMessage = MYL(": \"") + errorMessage + MYL("\""); wstringstream wss; wss << L"Failed to set priority of process " << pid << " with error" << MYL("(") << err << MYL(")") << errorMessage << endl; return wss.str(); } void ShowVersionW() { CHECK_USERFUNC(gUFShowOutputW); wstringstream wss; wss << APPNAME << MYL(" v") << APPVERSION << endl; gUFShowOutputW(wss.str().c_str()); } void ShowHelpW(bool more) { CHECK_USERFUNC(gUFShowOutputW); wstringstream wss; wss << APPNAME << endl; wss << L" Set process priority" << endl; wss << endl; wss << L"options:" << endl; wss << L" [--cpu-high | --cpu-abovenormal | --cpu-normal | --cpu-belownormal | --cpu-idle | --cpu-default]" << std::endl; wss << L" [--io-high | --io-abovenormal | --io-normal | --io-belownormal | --io-idle | --io-default]" << endl; wss << L" [--mem-high | --mem-abovenormal | --mem-normal | --mem-belownormal | --mem-idle | --mem-default]" << endl; wss << L" [--all-abovenormal | --all-normal | --all-belownormal | --all-idle]" << endl; wss << L" Currenly, '--io-high' and '--io-abovenormal' is equal to '--io-normal'." << endl; wss << L" Likewise, '--mem-abovenormal' and '--mem-normal' is equal to '--mem-high'." << endl; wss << endl; wss << L" [--show-nooutput] [--show-noerror] " << endl; wss << L" Will not show standard output or error output." << endl; wss << endl; wss << L" [--show-command]" << endl; wss << L" Show the command for creating a new process." << endl; wss << endl; wss << L" [--exit-if-setpriority-failed]" << endl; wss << L" [--detach-newprocess | --wait-newprocess]" << endl; wss << L" Whether or not to wait new process to finish. Default value is different between winnice and winnicew, " L"winnice's default value is '--wait-newprocess' and winnicew's one is '--detach-newprocess'." << endl; wss << endl; wss << L" [--executable Executable [--executable Executable]]..." << endl; wss << L" Specify executables" << endl; wss << endl; wss << L" [--pid PID1[,PID2,PID3,...]]" << endl; wss << L" Specify process IDs" << endl; wss << endl; wss << L" [--new-process]" << endl; wss << L" Launch a new process, this option should be put at last of command line. " "In this case, All strings after this option will be a command line string to launch a process." << endl; wss << L" If this option is not a last one, The position of the first unaware string will be the start of the command line string to launch a process." << endl; wss << endl; wss << L" [- NotOptionArg]" << endl; wss << L" If '-' appears after '--new-process', next argument will be treated as executable." << endl; if (!more) { wss << endl; wss << L"Run with '--helpmore' for more help." << endl; gUFShowOutputW(wss.str().c_str()); return; } wss << endl; wss << L"Priority options" << endl; wss << L" Latter argument overrides former one. '--all-idle --cpu-default' will affect only IO and MEM." << endl; wss << L" Above 'Normal' priority for IO and MEM are not supported." << endl; wss << endl; wss << L"--show-command" << endl; wss << L" show commnad to run" << endl; wss << endl; wss << L"--exit-if-setpriority-failed" << endl; wss << L" Exit if setting priority failed (not run commnad)." << endl; wss << endl; wss << L"--detach-newprocess" << endl; wss << L" Exit after starting commnad(not wait it)." << endl; wss << endl; wss << L"--new-process" << endl; wss << L" (Omitable) create a new process and set priority" << endl; wss << endl; wss << L"--error-level" << endl; wss << L" 'normal' or 'debug', default is 'normal'" << endl; wss << endl; gUFShowOutputW(wss.str().c_str()); } int DoSetPriority(DWORD dwProcessID, Process::CPUPRIORITY cpuPriority, Process::IOPRIORITY ioPriority, Process::MEMORYPRIORITY memPriority, bool exitifsetpriorityfailed, tstringstream& errorMessage) { int lastError = 0; int err; // CPU err = Process::SetProirity( dwProcessID, cpuPriority, Process::IO_NONE, Process::MEMORY_NONE); if (err != 0) { lastError = err; errorMessage << MYL("CPU:") << GetErrorWithLastErrorW(err, dwProcessID) << endl; if (exitifsetpriorityfailed) { return err; } } // IO err = Process::SetProirity( dwProcessID, Process::CPU_NONE, ioPriority, Process::MEMORY_NONE); if (err != 0) { lastError = err; errorMessage << MYL("IO:") << GetErrorWithLastErrorW(err, dwProcessID) << endl; if (exitifsetpriorityfailed) { return err; } } // MEMORY err = Process::SetProirity( dwProcessID, Process::CPU_NONE, Process::IO_NONE, memPriority); if (err != 0) { lastError = err; errorMessage << MYL("Memory:") << GetErrorWithLastErrorW(err, dwProcessID) << endl; if (exitifsetpriorityfailed) { return err; } } return lastError; } <file_sep>#pragma once #include <Windows.h> #include <shellapi.h> <file_sep># winnice Windows用のプロセスの優先度を設定するコマンドラインアプリです # 環境 Visual Studio 2022 ランタイムライブラリ # インストール ダウンロードしたアーカイブを実行して展開します # 2つの実行ファイル * *winnice.exe* はコンソールアプリです * *winnicew.exe* はGUIアプリです(コンソールを表示しません) # アンインストール 展開したファイルを削除します # 使い方 ### プロセスIDが12345のプロセスを*アイドル*にします ``` > winnice --cpu-idle --pid 12345 ``` ### プロセスIDはいくつでも指定できます ``` > winnice --cpu-idle --pid 12345,7890 ``` ### すべてのnotepad.exeの優先度を*アイドル*にします ``` > winnice --cpu-idle --executable notepad.exe ``` ### 'app.exe'のIO優先度を*アイドル*にします ``` > winnice.exe --io-idle --executable app.exe ``` ### メモ帳を起動しすべての優先度(CPU,IO,メモリ)を*アイドル*にせっていし、起動したプロセスを切り離します(終了を待ちません) ``` > winnice.exe --all-idle --detach-newprocess --new-process notepad ``` ### ライブラリとして使う ライブラリのインターフェイスはコマンドラインと同じです。 ``` #include "../libwinnice/libwinnice.h" int argc = 0; // First argument is dummy const wchar_t* commandLine = L"dummy.exe --all-idle --new-process notepad"; // Create argc and argv from command line std::unique_ptr<LPWSTR, void(*)(LPWSTR*)> pArgv(::CommandLineToArgvW(commandLine, &argc), [](LPWSTR* ptr) { ::LocalFree(ptr); }); int nRetNotepad = LibWinNiceMainW(false, argc, pArgv.get(), NULL, NULL); ``` # サポート ここ <https://github.com/ambiesoft/winnice/issues> に問題を投稿するか掲示板に投稿してください # コンタクト - 開発者: trueff - E-mail: <<EMAIL>> - ウェブサイト: <https://ambiesoft.com/> - 掲示板: <https://ambiesoft.com/minibbs/> - 開発: <https://github.com/ambiesoft/winnice><file_sep>// MIT License // // Copyright (c) 2018 Ambiesoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include "libwinnice.h" #include "lsMisc/stdosd/SetPrority.h" #define MYL(s) L ## s #define APPNAME MYL("winnice") #define APPVERSION MYL("1.2.1") extern WNUShowInformationW gUFShowOutputW; extern WNUShowInformationW gUFShowErrorW; extern bool gShowNoOutput; extern bool gShowNoError; void ShowOutputW(const wchar_t* pMessage); void ShowOutputW(const std::wstring& s); void ShowOutputW(const std::wstringstream& s); void ShowErrorW(const wchar_t* pMessage); void ShowErrorW(const std::wstring& message); void ShowErrorW(const std::wstringstream& message); tstring GetErrorWithLastErrorW(int err, DWORD pid); void ShowVersionW(); void ShowHelpW(bool more=false); int DoSetPriority(DWORD dwProcessID, Ambiesoft::stdosd::Process::CPUPRIORITY cpuPriority, Ambiesoft::stdosd::Process::IOPRIORITY ioPriority, Ambiesoft::stdosd::Process::MEMORYPRIORITY memPriority, bool exitifsetpriorityfailed, tstringstream& errorMessage); <file_sep># winnice Command line tool for setting Process Priority in Windows # Environment Visual Studio 2022 runtime library # Install Extract the downloaded archive and run *winnice_x.x.x.exe* # Two executables * *winnice.exe* is console app. * *winnicew.exe* is GUI app (shows no console). # Uninstall Remove files # Usage ### Set cpu priority of process 12345 to *idle*. ``` > winnice --cpu-idle --pid 12345 ``` ### You can specify many pids. ``` > winnice --cpu-idle --pid 12345,7890 ``` ### All notepad.exe instances will be *idle*. ``` > winnice --cpu-idle --executable notepad.exe ``` ### This sets IO priority of process 'app.exe' to *idle*. ``` > winnice.exe --io-idle --executable app.exe ``` ### Launch notepad, set all prorities (CPU,IO,Memory) to *idle* and detach it(not wait for it to finish). ``` > winnice.exe --all-idle --detach-newprocess --new-process notepad ``` ### Using it as a library The interface of the library is the same as the command line. ``` #include "../libwinnice/libwinnice.h" int argc = 0; // First argument is dummy const wchar_t* commandLine = L"dummy.exe --all-idle --new-process notepad"; // Create argc and argv from command line std::unique_ptr<LPWSTR, void(*)(LPWSTR*)> pArgv(::CommandLineToArgvW(commandLine, &argc), [](LPWSTR* ptr) { ::LocalFree(ptr); }); int nRetNotepad = LibWinNiceMainW(false, argc, pArgv.get(), NULL, NULL); ``` # Support If you have troubles, post *Issue* on <https://github.com/ambiesoft/winnice/issues>. # Contact - Author: <NAME> - E-mail: <<EMAIL>> - Webpage: <https://ambiesoft.com/> - Forum: <https://ambiesoft.com/minibbs/> - Development: <https://github.com/ambiesoft/winnice><file_sep>// MIT License // // Copyright (c) 2018 Ambiesoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // testtarget.cpp : Defines the entry point for the console application. // #include <Windows.h> #include <stdio.h> int gCtrlCCount; BOOL WINAPI CtrlHandler(DWORD fdwCtrlType) { switch (fdwCtrlType) { // Handle the CTRL-C signal. case CTRL_C_EVENT: ++gCtrlCCount; printf("Ctrl-C event. %d more event will close the application.\n", 5-gCtrlCCount); Beep(750, 300); return !(gCtrlCCount >= 5); // CTRL-CLOSE: confirm that the user wants to exit. case CTRL_CLOSE_EVENT: Beep(600, 200); printf("Ctrl-Close event\n\n"); return(TRUE); // Pass other signals to the next handler. case CTRL_BREAK_EVENT: Beep(900, 200); printf("Ctrl-Break event\n\n"); return FALSE; case CTRL_LOGOFF_EVENT: Beep(1000, 200); printf("Ctrl-Logoff event\n\n"); return FALSE; case CTRL_SHUTDOWN_EVENT: Beep(750, 500); printf("Ctrl-Shutdown event\n\n"); return FALSE; default: return FALSE; } } int main() { if (SetConsoleCtrlHandler(CtrlHandler, TRUE)) { printf("The Control Handler is installed.\n"); printf(" -- Now try pressing Ctrl+C or Ctrl+Break, or\n"); printf(" try logging off or closing the console...\n"); printf(" Pressing Ctrl-C five times will close the application.\n"); printf("(...waiting in a loop for events...)\n"); while (1) { Sleep(1000); } } else { printf("\nERROR: Could not set control handler"); return 1; } return 0; }
7273f5edc18bd9141cbb08e0b08f2fd441425b94
[ "Markdown", "C", "C++" ]
7
C++
ambiesoft/winnice
ffc5360f5d08f0c8907de0bd9df1b49f83fd6183
09040f6c0819bdfa8f45a72abe7e274361fd68a3
refs/heads/master
<repo_name>sasha-x/test.travel<file_sep>/migrations/m190730_140716_mk_foreign_keys.php <?php use yii\db\Migration; /** * Class m190730_140716_mk_foreign_keys */ class m190730_140716_mk_foreign_keys extends Migration { /** * {@inheritdoc} */ public function safeUp() { $this->addForeignKey('fk-trip_service-trip_id', 'trip_service', 'trip_id', 'trip', 'id'); $this->addForeignKey('fk-flight_segment-flight_id', 'flight_segment', 'flight_id', 'trip_service', 'id'); $this->execute("ALTER TABLE nemo_guide_etalon.airport_name MODIFY airport_id INT NULL DEFAULT NULL"); $this->execute("INSERT INTO nemo_guide_etalon.airport_name (airport_id,`value`) SELECT DISTINCT depAirportId, '' FROM cbt.flight_segment LEFT JOIN nemo_guide_etalon.airport_name ON depAirportId=airport_id WHERE airport_id IS NULL"); $this->addForeignKey('fk-flight_segment-depAirportId', 'flight_segment', 'depAirportId', 'nemo_guide_etalon.airport_name', 'airport_id'); } /** * {@inheritdoc} */ public function safeDown() { echo "This migration is partially non-convertible"; $this->dropForeignKey('fk-trip_service-trip_id', 'trip_service'); $this->dropForeignKey('fk-flight_segment-flight_id', 'flight_segment'); $this->dropForeignKey('fk-flight_segment-depAirportId', 'flight_segment'); $this->execute("DELETE FROM nemo_guide_etalon.airport_name WHERE airport_id IS NULL"); $this->execute("ALTER TABLE nemo_guide_etalon.airport_name MODIFY airport_id INT NOT NULL"); } } <file_sep>/models/TripQuery.php <?php namespace app\models; /** * This is the ActiveQuery class for [[Trip]]. * * @see Trip */ class TripQuery extends \yii\db\ActiveQuery { public function filterByCorpServAirport(int $corporate_id, int $service_id, int $airport_id) { return $this->andWhere(['corporate_id' => $corporate_id]) ->innerJoinWith([ 'tripServices' => function ($query) use ($airport_id){ $query->innerJoinWith('flightSegments', false) ->andWhere(['depAirportId' => $airport_id]); }, ], false) ->andWhere(['service_id' => $service_id]) ->distinct(); } } <file_sep>/controllers/SiteController.php <?php namespace app\controllers; use Yii; use yii\web\Controller; use yii\web\Response; use yii\filters\VerbFilter; use yii\data\ActiveDataProvider; use app\models\NemoAirportName; use app\models\Trip; use yii\web\NotFoundHttpException; class SiteController extends Controller { /** * {@inheritdoc} */ public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], ]; } /** * Displays homepage. * * @return string */ public function actionIndex() { return $this->redirect("/site/trip?corporate_id=3&service_id=2&airport_name=" . urlencode("Домодедово, Москва")); //airport_id=758 } /** * @param int $corporate_id * @param int $service_id * @param int $airport_id * * @return string */ public function actionTrip(int $corporate_id, int $service_id, string $airport_name) { //Probably non-production example $depAirport = NemoAirportName::findOne(['value' => $airport_name]); if(empty($depAirport)){ throw new NotFoundHttpException("Selected airport not found"); } $airport_id = $depAirport->airport_id; $query = Trip::find()->filterByCorpServAirport($corporate_id, $service_id, $airport_id) ->asArray(); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => 20, ], ]); return $this->render('trip', ['dataProvider' => $dataProvider]); } } <file_sep>/README.md Notes ===== 1. Что вызвало сомнения в постановке задачи: - направление связи между таблицами trip_service и flight_segment. Предположил обратное. - передача названия аэропорта в GET. В реальности ожидал бы airport_id (758) или code (DME). Вынес это в отдельный запрос. 2. По оптимизации индексов таблиц под эту конкретную задачу: удалил бы неиспользуемые. 3. По оптимизации под нагрузку: начал бы с - правильной настройки mysql - кеширования memcached результатов выборки из БД на фиксированое время (5с). <file_sep>/views/site/trip.php <?php /* @var $this yii\web\View */ use yii\grid\GridView; $this->title = Yii::$app->name = 'Trip Table'; ?> <div class="site-index"> <p> <?php echo GridView::widget([ 'dataProvider' => $dataProvider, ]); ?> </div>
06fa795ddb99a3ab64fd359a6e81e96f954fa227
[ "Markdown", "PHP" ]
5
PHP
sasha-x/test.travel
332be06333faa23608ab02274d8389734b091c7e
1766f7d2dc261debf6df536d01b09a156ab07105
refs/heads/master
<file_sep>package functionitegretion.customfunction; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; /** * 获取程序的版本号,程序名 * * @author TA * */ public class CustomUtils { /** 获取VersionName */ // public static String getVersionName(Context context) { // try { // PackageInfo pi = // context.getPackageManager().getPackageInfo(context.getPackageName(), 0); // return pi.versionName; // } catch (NameNotFoundException e) { // e.printStackTrace(); // return context.getString(R.string.NotFindVersionName); // } // } /** * 获取VersionCode 版本号 */ public static int getVersionCode(Context context) { try { PackageInfo pi = context.getPackageManager().getPackageInfo( context.getPackageName(), 0); return pi.versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); return 0; } } /** * 获取应用程序名称 */ public static String getApplicationName(Context context) { PackageManager packageManager = null; ApplicationInfo applicationInfo = null; try { packageManager = context.getApplicationContext() .getPackageManager(); applicationInfo = packageManager.getApplicationInfo( context.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { applicationInfo = null; } String applicationName = (String) packageManager .getApplicationLabel(applicationInfo); return applicationName; } }<file_sep># Function 简单工具类 包括: 百度定位 文字转语音播放 mp3文件播放 二维码扫描、带logo二维码生成 图片压缩 序列化与反序列化 文件压缩 日期格式转换 <file_sep>package functionitegretion.customfunction.player; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.Toast; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SynthesizerListener; /** * 引擎播放实现类 * @author ThinkPad User * */ public class IFlyTTS extends IPlayer { private static IFlyTTS _tts; private static HashMap<Context, IFlyTTS> _players = null; private SpeechSynthesizer _speech; private SharedPreferences _shared; private boolean _playEnd = false; private String _content = ""; private List<OnPlayCompleted> listeners = null; private Toast _toast; /** * 构造函数 * * @param context */ private IFlyTTS(Context context) { // 初始化合成对象 _speech = SpeechSynthesizer.createSynthesizer(context, initListener); _shared = context.getSharedPreferences("com.iflytek.setting", Context.MODE_PRIVATE); _speech.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL); // 设置发音人 voicer为空默认通过语音+界面指定发音人。 _speech.setParameter(SpeechConstant.VOICE_NAME, ""); // 设置播放器音频流类型 _speech.setParameter(SpeechConstant.STREAM_TYPE, _shared.getString("stream_preference", "1"));// 0则为听筒 } /** * 初始化监听。 */ private InitListener initListener = new InitListener() { @Override public void onInit(int code) { if (code != ErrorCode.SUCCESS) { _toast.setText("初始化失败,错误码:" + code); _toast.show(); } } }; /** * 单例模式实例化 * * @param context * @return TTS合成引擎 */ public static IPlayer getInstance(Context context) { if (null == _players) { _players = new HashMap<Context, IFlyTTS>(); } if (_players.containsKey(context)) { return _players.get(context); } _tts = new IFlyTTS(context); _players.put(context, _tts); return _tts; } /** * 添加语音播报完成事件 */ @Override public void setOnPlayCompleted(OnPlayCompleted listener) { if (null == listeners) { listeners = new ArrayList<OnPlayCompleted>(); } listeners.add(listener); } /** * 移除语音播报完成事件 */ @Override public void removeOnPlayCompleted(OnPlayCompleted listener) { if (null != listeners && listeners.contains(listener)) { listeners.remove(listener); } } /** * 是否播报完成 */ @Override public boolean isCompleted() { return _playEnd; } /** * 获取语音播报内容 */ @Override public String getContent() { return _content; } /** * 开始语音播报 */ @Override public void doPlay(String content) { if (!_playEnd) { doStop(); } try { int code = _speech.startSpeaking(content, listener); _content = content; if (code != ErrorCode.SUCCESS) { _toast.setText("未安装离线包"); _toast.show(); } } catch (Exception e) { } } /** * 语音播报事件 */ private SynthesizerListener listener = new SynthesizerListener() { @Override public void onBufferProgress(int arg0, int arg1, int arg2, String arg3) { } @Override public void onCompleted(SpeechError arg0) { _playEnd = true; if (arg0 == null) { if (null != listeners && listeners.size() > 0) { synchronized (listeners) { for (int i = 0; i < listeners.size(); i++) { OnPlayCompleted lis = listeners.get(i); lis.PlayCompleted(); } } } } else if (arg0 != null) { /* * _toast.setText(arg0.getPlainDescription(true)); * _toast.show(); */ } } @Override public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) { } @Override public void onSpeakBegin() { _playEnd = false; } @Override public void onSpeakPaused() { } @Override public void onSpeakProgress(int arg0, int arg1, int arg2) { } @Override public void onSpeakResumed() { } }; /** * 终止语音播报 */ @Override public void doStop() { if (null != _speech) { _speech.stopSpeaking(); } listener.onCompleted(null); } } <file_sep>package functionitegretion.customfunction; import java.util.Hashtable; import android.graphics.Bitmap; import android.widget.ImageView; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; /** * 编码转二维码图片并显示 * * @author TA */ public class CreateQRImage { /** * * @param source * 数据资源(编码) * @param imageview * 需要显示到的imageview * @param width * 、height 生成的二维码的宽高 */ public void createQRImage(String source, ImageView imageview, int width, int height) { try { // 判断URL合法性 if (source == null || "".equals(source) || source.length() < 1) { return; } Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 图像数据转换,使用了矩阵转换 BitMatrix bitMatrix = new QRCodeWriter().encode(source, BarcodeFormat.QR_CODE, width, height, hints); int[] pixels = new int[width * height]; // 下面这里按照二维码的算法,逐个生成二维码的图片, // 两个for循环是图片横列扫描的结果 for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (bitMatrix.get(x, y)) { pixels[y * width + x] = 0xff000000; } else { pixels[y * height + x] = 0xffffffff; } } } // 生成二维码图片的格式,使用ARGB_8888 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); // 显示到一个ImageView上面 imageview.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } } } <file_sep>package functionitegretion.customfunction.player; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.content.Context; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnPreparedListener; /** * MP3文件播放实现类 * @author TA * */ public class MP3Player extends IPlayer { private static MP3Player _Player; private static MediaPlayer _MediaPlayer; private List<OnPlayCompleted> listeners = null; private static HashMap<Context, MP3Player> _Players = null; private String _content = ""; private boolean _playEnd = false; /** * 构造函数 * @param context */ private MP3Player(Context context) { _MediaPlayer = new MediaPlayer(); _MediaPlayer.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer arg0) { _playEnd = true; if (null != listeners && listeners.size() > 0) { synchronized (listeners) { for (int i = 0; i < listeners.size(); i++) { OnPlayCompleted lis = listeners.get(i); lis.PlayCompleted(); } } } } }); _MediaPlayer.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { _playEnd = false; _MediaPlayer.start(); } }); } /** * 单例模式初始化MP3播放器 * * @param context * @return MP3播放器 */ public static IPlayer getInstance(Context context) { if (null == _Player) { _Players = new HashMap<Context, MP3Player>(); } if (_Players.containsKey(context)) { return _Players.get(context); } _Player = new MP3Player(context); _Players.put(context, _Player); return _Player; } /** * 添加语音播报完成事件 */ @Override public void setOnPlayCompleted(OnPlayCompleted listener) { if (null == listeners) { listeners = new ArrayList<OnPlayCompleted>(); } listeners.add(listener); } /** * 移除语音播报完成事件 */ @Override public void removeOnPlayCompleted(OnPlayCompleted listener) { if (null != listeners && listeners.contains(listener)) { listeners.remove(listener); } } /** * 语音播报是否完成 */ @Override public boolean isCompleted() { return _playEnd; } /** * 获取语音播报内容 */ @Override public String getContent() { return _content; } /** * 执行语音播报 */ @Override public void doPlay(String content) { try { if (_MediaPlayer.isPlaying()) doStop(); _MediaPlayer.reset(); _MediaPlayer.setDataSource(content); _MediaPlayer.prepareAsync(); _content = content; } catch (Exception e) { e.printStackTrace(); } } /** * 终止语音播报 */ @Override public void doStop() { if (null != _MediaPlayer) { _MediaPlayer.stop(); } _playEnd = true; if (null != listeners && listeners.size() > 0) { synchronized (listeners) { for (int i = 0; i < listeners.size(); i++) { OnPlayCompleted lis = listeners.get(i); lis.PlayCompleted(); } } } } @Override protected void finalize() throws Throwable { _MediaPlayer.release(); super.finalize(); } } <file_sep>package functionitegretion.customfunction.player; import functionitegretion.customfunction.player.IPlayer.PLAY_TYPE; import android.content.Context; /** * ²¥·Å¹¤³§Àà * @author ThinkPad User * */ public class PlayFactory { private static IPlayer _Player; public static IPlayer getInstance(Context context, PLAY_TYPE type){ if(type == PLAY_TYPE.IFlyTTS){ _Player = IFlyTTS.getInstance(context); } else if(type == PLAY_TYPE.MP3){ _Player = MP3Player.getInstance(context); } return _Player; } } <file_sep>package functionitegretion.customfunction.wifi; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; /** * WIFI操作类 * * @author TA */ public class WifiUnitl { private static WifiUnitl unitl; private WifiManager manager; private Context context; private WifiUnitl(Context context) { this.context = context; manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); } /** * 单例模式 */ public static WifiUnitl getInstantiation(Context context) { if (unitl == null) { unitl = new WifiUnitl(context); } return unitl; } /** * Wifi是否已开启 */ public boolean isWifiEnabled() { return manager.isWifiEnabled(); } /** * 获取已连接的wifi的ssid */ public String getConnectedWifi() { String ssid = null; if (isWifiEnabled()) { ssid = manager.getConnectionInfo().getSSID().replace("\"", ""); } return ssid; } /** * 获取所有设置过的Wifi */ public List<WifiConfiguration> getConfiguredWifi() { return manager.getConfiguredNetworks(); } /** * 获取所有已配置的Wifi名字 */ public List<String> getConfiguredWifiName() { List<WifiConfiguration> listWifi = getConfiguredWifi(); List<String> listname = new ArrayList<String>(); // String[] WifiName = new String[listcof.size()]; for(int i = 0; i < listWifi.size(); i++){ // WifiName[i] = (String) listcof.get(i).SSID.subSequence(1, listcof.get(i).SSID.length()-1); listname.add((String) listWifi.get(i).SSID.subSequence(1, listWifi.get(i).SSID.length()-1)); } return listname; } /** * 根据SSID获取Wifi配置 */ public WifiConfiguration isExsits(String SSID) { List<WifiConfiguration> configs = manager.getConfiguredNetworks(); for (WifiConfiguration cfg : configs) { if (cfg.SSID.equals("\"" + SSID + "\"")) { return cfg; } } return null; } /** * 连接到指定Wifi */ public void connectToWifi(String name) { if (!isWifiEnabled()) { manager.setWifiEnabled(true); } while (manager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { try { Thread.currentThread(); Thread.sleep(100); } catch (Exception e) { } } for (WifiConfiguration wifi : manager.getConfiguredNetworks()) { if (wifi.SSID.equals(name)) { manager.enableNetwork(manager.addNetwork(wifi), false); break; } } } /** * 重新连接到Wifi */ public void connectToWifi(String SSID, String Password) { if (!isWifiEnabled()) { manager.setWifiEnabled(true); } while (manager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { try { Thread.currentThread(); Thread.sleep(100); } catch (Exception e) { } } WifiConfiguration cfg = initConfiguration(SSID, Password); if (cfg == null) return; for (WifiConfiguration wifi : manager.getConfiguredNetworks()) { manager.removeNetwork(wifi.networkId); } while (!isWifiConnected()) { manager.enableNetwork(manager.addNetwork(cfg), false); } } /** * 检测Wifi是否已连接 */ public boolean isWifiConnected() { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifiNetworkInfo = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); return wifiNetworkInfo.isConnected(); } /** * 根据SSID和密码初始化Wifi配置 */ private WifiConfiguration initConfiguration(String SSID, String Password) { WifiConfiguration cfg = new WifiConfiguration(); cfg.allowedAuthAlgorithms.clear(); cfg.allowedGroupCiphers.clear(); cfg.allowedKeyManagement.clear(); cfg.allowedPairwiseCiphers.clear(); cfg.allowedProtocols.clear(); cfg.SSID = "\"" + SSID + "\""; /** * 无密码方式 cfg.wepKeys[0] = ""; * cfg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); * cfg.wepTxKeyIndex = 0; */ /** * WEP加密模式 cfg.preSharedKey = "\""+<PASSWORD>+"\""; cfg.hiddenSSID = true; * cfg * .allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); * cfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); * cfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); * cfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); * cfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); * cfg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); * cfg.wepTxKeyIndex = 0; */ cfg.preSharedKey = "\"" + <PASSWORD> + "\""; cfg.hiddenSSID = true; cfg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); cfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); cfg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); cfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); cfg.allowedProtocols.set(WifiConfiguration.Protocol.WPA); cfg.status = WifiConfiguration.Status.ENABLED; return cfg; } } <file_sep>package functionitegretion.customfunction; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import org.apache.http.util.EncodingUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; import android.util.Xml; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; public class SerializableHelper { private static SerializableHelper _serializer; public static SerializableHelper Instantiation() { if (_serializer == null) { _serializer = new SerializableHelper(); } return _serializer; } // [start] 实现了Serializable接口的序列化与反序列化 /** * 使用writeObject写入Xml * @param path 持久化对象路径 * @param object 需要序列化的对象 */ public void doSerializer(String path,Object object){ try{ FileOutputStream fstream = new FileOutputStream(new File(path)); ObjectOutputStream stream = new ObjectOutputStream(fstream); stream.writeObject(object); }catch(Exception e){ e.printStackTrace(); } } /** * 使用readObject解析持久化对象数据 * @param path 持久化对象数据地址 * @return 反序列化的对象 */ public Object doDeserialize(String path){ try{ FileInputStream instream = new FileInputStream(new File(path)); ObjectInputStream stream = new ObjectInputStream(instream); return stream.readObject(); }catch(Exception e){ e.printStackTrace(); return null; } } // [end] // [start] XmlSerializer序列化 private void Serializer(Object object,XmlSerializer serializer){ try{ Field[] fields = object.getClass().getFields(); for (Field item : fields) { serializer.startTag(null, item.getName()); if(item.getType().getName().toString().equals("java.util.ArrayList")){ Serializer(item.getType(), serializer); } else{ serializer.text(item.get(object) == null ? "" : item.get(object).toString()); } serializer.endTag(null, item.getName()); } }catch(Exception e){ e.printStackTrace(); } } /** * 单个对象序列化成Xml * * @param object * 待序列化的对象 * @param fos * Xml输出流 * @return */ public void doSerializer(Object object, String path) { try { FileOutputStream stream = new FileOutputStream(path); XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(stream, "UTF-8"); serializer.startDocument("UTF-8", true); serializer.startTag(null, object.getClass().getSimpleName()); Serializer(object, serializer); serializer.endTag(null, object.getClass().getSimpleName()); serializer.endDocument(); } catch (Exception e) { e.printStackTrace(); } } /** * List<T>序列化成Xml * * @param list * 待序列化的对象 * @param fos * Xml输出流 */ public <T> void doSerializer(List<T> list, String path) { try { FileOutputStream stream = new FileOutputStream(path); XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(stream, "UTF-8"); serializer.startDocument("UTF-8", true); serializer.startTag(null, list.getClass().getSimpleName()); for (T item : list) { serializer.startTag(null, item.getClass().getSimpleName()); Serializer(item, serializer); serializer.endTag(null, item.getClass().getSimpleName()); } serializer.endTag(null, list.getClass().getSimpleName()); serializer.endDocument(); } catch (Exception e) { e.printStackTrace(); } } // [end] // [start] XStream序列化xml /** * XStream生成xml * @param obj 待序列化对象 * @param path 序列化xml地址 */ public void doXStreamToXml(Object obj, String path){ try { FileOutputStream stream = new FileOutputStream(path); XStream x = new XStream(new DomDriver()); stream.write(x.toXML(obj).getBytes("UTF-8")); } catch (Exception e) { e.printStackTrace(); } } /** * XStream解析xml * @param path 待解析xml地址 * @return 解析结果 */ public Object doXSteamToObject(String path){ try{ FileInputStream stream = new FileInputStream(path); byte [] buffer = new byte[stream.available()]; stream.read(buffer); XStream x = new XStream(new DomDriver()); x.autodetectAnnotations(true); return x.fromXML(EncodingUtils.getString(buffer, "UTF-8")); }catch(Exception e){ e.printStackTrace(); return null; } } // [end] // [start] 对应XmlSerializer的解析 未实现(枚举反射问题) @SuppressWarnings("unchecked") public <T> List<T> doDeserialize(T obj, String path){ List<T> result = null; try { FileInputStream stream = new FileInputStream(path); XmlPullParser parser = Xml.newPullParser(); parser.setInput(stream,"utf-8"); String classname = obj.getClass().getSimpleName(); Field[] fields = obj.getClass().getFields(); String name = ""; for (int i = parser.getEventType(); i != XmlPullParser.END_DOCUMENT; i = parser.next()) { switch (i) { case XmlPullParser.START_TAG: name = parser.getName(); if ("ArrayList".equals(name)) { result = new ArrayList<T>(); } else if (classname.equals(name)) { obj = (T)obj.getClass().newInstance(); }else{ for(Field item : fields){ if(item.getName().equals(name)){ item.set(obj, parser.nextText()); } } } break; case XmlPullParser.END_TAG: if (parser.getName().equals(classname)) { result.add(obj); obj = (T)obj.getClass().newInstance(); } break; } } } catch (Exception e) { e.printStackTrace(); } return result; } // [end] } <file_sep>package functionitegretion.customfunction; import java.text.SimpleDateFormat; import java.util.Date; /** * 日期格式转换帮助类 * * @author TA * */ public abstract class DateTimeHelper { /** * 格式化日期 年-月-日 时:分:秒 */ public static SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");// 小写的mm表示的是分钟 /** * 当前日期时间 */ public static String getNow() { Date date = new Date(); return sdf.format(date); } /** * 格式为"mm:ss" 分:秒 */ public static SimpleDateFormat shortTimeFormater = new SimpleDateFormat( "HH:mm");// 小写的mm表示的是分钟 /** * 格式为"HH:mm:ss" 时:分:秒 */ public static SimpleDateFormat timeFormater = new SimpleDateFormat( "HH:mm:ss");// 小写的mm表示的是分钟 /** * 获取指定格式的日期字符串 * * @param formater * 格式字符串 * @return */ public static String dateToString(String formater) { return new SimpleDateFormat(formater).format(new Date()); } /** * 获取指定格式的日期字符串 * * @param formater * 格式字符串 * @param date * 需要格式化的Date * @return */ public static String dateToString(Date date, String formater) { return new SimpleDateFormat(formater).format(date); } } <file_sep>package functionitegretion.customfunction.loction; import java.util.List; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.Log; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.location.LocationClientOption.LocationMode; import com.baidu.location.Poi; /** * 百度定位实现demo * @author TA * */ public class BaiduLocation { private LocationClient mLocationClient = null; private BDLocationListener myListener = new MyLocationListener(); private Context mycontext; private Handler handler; public BaiduLocation(Context context,Handler handlers){ this.mycontext = context; this.handler = handlers; if (mLocationClient == null) { mLocationClient = new LocationClient(mycontext); //声明LocationClient类 } mLocationClient.registerLocationListener( myListener ); //注册监听函数 } /** * 配置并开启定位 */ public void initLocationclient() { LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationMode.Battery_Saving);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系 option.setScanSpan(1000);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要 option.setOpenGps(true);//可选,默认false,设置是否使用gps option.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 option.setIgnoreKillProcess(false);//可选,默认false,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认杀死 option.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集 option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤gps仿真结果,默认需要 mLocationClient.setLocOption(option);//设置 LocationClientOption mLocationClient.start();//启动定位sdk mLocationClient.requestLocation();//请求定位,异步返回,结果在locationListener中获取. } /** * 结束定位SDK */ public void setLocationClientStop() { mLocationClient.stop(); } /** * 定位监听事件 * @author TA * */ public class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { //Receive Location Message message = new Message(); StringBuffer sb = new StringBuffer(256); sb.append("time : "); sb.append(location.getTime()); //时间 sb.append("\nerror code : "); sb.append(location.getLocType());//获取定位类型 sb.append("\nlatitude : "); sb.append(location.getLatitude());//获取纬度坐标 sb.append("\nlontitude : "); sb.append(location.getLongitude());//获取经度 sb.append("\nradius : "); sb.append(location.getRadius());//获取定位精度,默认值0.0f if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果 sb.append("\nspeed : "); sb.append(location.getSpeed());// 单位:公里每小时 sb.append("\nsatellite : "); sb.append(location.getSatelliteNumber()); sb.append("\nheight : "); sb.append(location.getAltitude());// 单位:米 sb.append("\ndirection : "); sb.append(location.getDirection());// 单位度 sb.append("\naddr : "); sb.append(location.getAddrStr()); //地址信息 sb.append("\ndescribe : "); sb.append("gps定位成功"); message.obj = location.getAddrStr().trim(); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果 sb.append("\naddr : "); sb.append(location.getAddrStr()); //地址信息 sb.append("\noperationers : "); sb.append(location.getOperators()); //运营商信息 sb.append("\ndescribe : "); sb.append("网络定位成功"); location.getProvince(); location.getCity();// 省、市 location.getStreet(); location.getBuildingName();//街道、建筑物名字 message.obj = location.getAddrStr().trim(); } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果 sb.append("\ndescribe : "); sb.append("离线定位成功,离线定位结果也是有效的"); } else if (location.getLocType() == BDLocation.TypeServerError) { sb.append("\ndescribe : "); sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到<EMAIL>,会有人追查原因"); } else if (location.getLocType() == BDLocation.TypeNetWorkException) { sb.append("\ndescribe : "); sb.append("网络不同导致定位失败,请检查网络是否通畅"); } else if (location.getLocType() == BDLocation.TypeCriteriaException) { sb.append("\ndescribe : "); sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机"); } sb.append("\nlocationdescribe : "); sb.append(location.getLocationDescribe());// 位置语义化信息 List<Poi> list = location.getPoiList();// POI数据 if (list != null) { sb.append("\npoilist size = : "); sb.append(list.size()); for (Poi p : list) { sb.append("\npoi= : "); sb.append(p.getId() + " " + p.getName() + " " + p.getRank()); } } handler.sendMessage(message); Log.i("BaiduLocationApiDem", sb.toString()); } } } <file_sep>package functionitegretion.http; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import java.util.Map.Entry; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import android.content.Context; import android.net.wifi.WifiManager; import android.os.Handler; import android.os.Message; public class HttpHelpers { HttpClient httpClient = CustomerHttpClient.getHttpClient(); // private void CheckAndOpenWifi(){ // WifiManager wifiManager = (WifiManager)ApplicationData.context.getSystemService(Context.WIFI_SERVICE); // if (!wifiManager.isWifiEnabled()) { // wifiManager.setWifiEnabled(true); // } // } @SuppressWarnings("unused") private String doGet(String url) throws ClientProtocolException, IOException { // CheckAndOpenWifi(); HttpGet request = new HttpGet(url); // 发送GET请求,并将响应内容转换成字符串 String response = httpClient.execute(request, new BasicResponseHandler()); return response; } /** * Post提交数据 * @param url 服务器API地址 * @param postData 需要提交的JSON数据 * @param handler 提交完成处理程序 */ public void doPost(String url, String postData, Handler handler) { // CheckAndOpenWifi(); MyThread thread = new MyThread(url, postData,null, handler); new Thread(thread).start(); } /** * Post提交数据 * @param url 服务器API地址 * @param params 需要提交的参数HashMap * @param handler 提交完成处理程序 */ public void doPost(String url,Map<String, Object> params, Handler handler){ // CheckAndOpenWifi(); MyThread thread = new MyThread(url, null, params, handler); new Thread(thread).start(); } public class MyThread implements Runnable { private Handler post; private String url; private String postData; private Map<String, Object> params; public MyThread(String _url, String _postData,Map<String, Object> params, Handler _post) { this.url = _url; this.postData = _postData; this.post = _post; this.params = params; } @Override public void run() { String result = ""; if(params == null){ result = HttpHelpers.this.doPost(url, postData); }else{ result = HttpHelpers.this.doPost(url, params); } Message msg = new Message(); msg.what = 1; msg.obj = result; post.sendMessage(msg); } } private String doPost(String strAction, Map<String, Object> params){ try{ URL url = new URL(strAction); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("accept", "*/*"); connection.connect(); // POST请求 StringBuilder sbData = new StringBuilder(); for(Entry<String, Object> entry : params.entrySet()){ sbData.append(entry.getKey()); sbData.append("="); sbData.append(URLEncoder.encode(entry.getValue().toString(),"utf-8")); sbData.append("&"); } sbData.deleteCharAt(sbData.length() - 1); OutputStream os = (OutputStream) connection.getOutputStream(); os.write(sbData.toString().getBytes()); os.flush(); os.close(); // 读取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } reader.close(); // 断开连接 connection.disconnect(); String strResult = sb.toString(); strResult = strResult.indexOf("</html>") >= 0 ? "" : strResult; return strResult; }catch(Exception e){ return ""; } } private String doPost(String strAction, String params) { try { // 创建连接 URL url = new URL(strAction); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/Json"); connection.connect(); // POST请求 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(params); out.flush(); out.close(); // 读取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } reader.close(); // 断开连接 connection.disconnect(); String strResult = sb.toString(); strResult = strResult.indexOf("</html>") >= 0 ? "" : strResult; return strResult; } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } } <file_sep>package functionitegretion.customfunction; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; /** * 横向进度条dialog * * @author TA */ public class CustomProgressdialog { private ProgressDialog mprogressdialog; private AlertDialog.Builder dialog; /** * 进度条弹窗 */ public ProgressDialog Dialogs(Context context) { mprogressdialog = new ProgressDialog(context); // 设置横向进度条风格 mprogressdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mprogressdialog.setTitle("提示"); // 设置标题 // mpdialog.setIcon(R.drawable.icon); //设置图标 mprogressdialog.setMessage("这是横向进度条"); // 设置内容 mprogressdialog.setMax(100); mprogressdialog.setProgress(0); mprogressdialog.setSecondaryProgress(50); mprogressdialog.setIndeterminate(false); // 设置进度条是否可以不明确 mprogressdialog.setCancelable(true); // 设置进度条是否可以取消 // mprogressdialog.setButton("确定", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int whic) { // // TODO Auto-generated method stub // dialog.cancel(); //取消 // } // }); mprogressdialog.show(); // 显示进度条 return mprogressdialog; } public void initDialog(Context context) { dialog = new AlertDialog.Builder(context); dialog.setTitle("提示"); dialog.setMessage("数据正在处理中,请稍候..."); dialog.show(); } public void hidProgressDialog() { if (dialog != null) { ((DialogInterface) dialog).cancel(); } } }
4b43423d610a6452dee27151d1f7c57356a86814
[ "Markdown", "Java" ]
12
Java
TAskyworld/Function
17499973656677350e9a5cf5110bb812795d1e39
d7a70d713d3a8b6abad20608ea793e33bdfd4a23
refs/heads/master
<file_sep>package com.example.webintegration; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.CustomTarget; import com.bumptech.glide.request.transition.Transition; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; Button btnBckgnd, btnRetr, btnHttp; LinearLayout mLinearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i(TAG, "onCreate: "); mLinearLayout = findViewById(R.id.rel_layout); btnRetr = findViewById(R.id.btn_retr); btnBckgnd = findViewById(R.id.btn_bckgnd); btnHttp = findViewById(R.id.btn_http); btnHttp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i1 = new Intent(MainActivity.this, HttpNew.class); startActivity(i1); } }); btnBckgnd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changeBackground(); } }); btnRetr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, RetrTask.class); startActivity(intent); } }); } private void changeBackground() { Log.i(TAG, "changeBackground: "); Glide.with(MainActivity.this) .load("https://i.stack.imgur.com/7vMmx.jpg") .into(new CustomTarget<Drawable>() { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) { mLinearLayout.setBackground(resource); } @Override public void onLoadCleared(@Nullable Drawable placeholder) { } }); } }
60a4870bac1579db235d5ac9d019641c675f87fe
[ "Java" ]
1
Java
PR72510/WebIntegration
b4ff40ae31a95a7f03fdc43fde824860fa5b6ed0
20908a11fd16996255a211a186ea8bff58d6233f
refs/heads/master
<file_sep>require './lib/BuildingBlocks/caesar_cipher.rb' require './lib/BuildingBlocks/stock_picker.rb' require './lib/BuildingBlocks/substrings.rb' require './lib/BuildingBlocks/bubble_sort.rb' require './lib/BuildingBlocks/enumerable.rb' <file_sep>def substrings(test_string, dictionary) results = {} words = test_string.split(' ') #test each word in test_string against each word in dictionary words.each do |test_word| dictionary.each do |dictionary_word| #downcase as test is not case sensitive test_word = test_word.downcase # If the dictionary word is found in a scan of the test word # Add the word to the hash and set its value to 1 # If the word is already in the hash incrament its value by 1 if test_word.scan(dictionary_word).length != 0 results[dictionary_word] = (results.has_key? dictionary_word) ? results[dictionary_word] + 1 : 1 end end #end dictionary loop end #end words loop results end<file_sep>def bubble_sort(list) list = bubble_sort_by(list) do |left, right| left > right end list end def bubble_sort_by(list) #initalize variables used to optimize sort to not waste compute cycles sorted = false passes = 0 #keep looping until no swaps happen until sorted == true sorted = true #loop for length of array minus the n passes already done as end of array is sorted (0..list.length-passes).each do |i| #break out of loop if you are at end of array as to stay in bounds if i+1 >= list.length then break end #test against bloc condition logic_result = yield(list[i], list[i+1]) #if logic_result is a number convert to a boolean if logic_result.is_a? Integer logic_result = logic_result < 1 ? false : true end #if true then swap values if logic_result sorted = false temp = list[i] list[i] = list[i+1] list[i+1] = temp end #end if swap end #end list loop passes += 1 end #end until sorted loop list end<file_sep># coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "Building Blocks" spec.version = '1.0' spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.summary = %q{A collection of small odin projects} spec.description = %q{A collection of the 3 projects from the Building Blocks exersize from The Odin Project} spec.homepage = "http://ollis.me/" spec.license = "MIT" spec.files = ['lib/buildingblocks.rb'] spec.executables = ['bin/buildingblocks'] spec.test_files = ['tests/test_blocks.rb'] spec.require_paths = ["lib"] end<file_sep>module Enumerable def my_each return self unless block_given? for i in self yield(i) end end def my_each_with_index return self unless block_given? for i in (0...self.size) yield(self[i], i) end end def my_select return self unless block_given? results = [] self.my_each do |i| if yield(i) results.push(i) end end results end def my_all? return self unless block_given? self.my_each do |i| if !yield(i) return false end end return true end def my_any? return self unless block_given? self.my_each do |i| if yield(i) return true end end return false end def my_none? return self unless block_given? self.my_each do |i| if yield(i) return false end end return true end def my_count self.length end def my_map return self unless block_given? results = [] self.my_each do |i| results.push(yield(i)) end results end end <file_sep>def stock_picker(price_array) low = 0 high = 0 split = 0 #Loop though the array twice to test all numbers against each other price_array.each_with_index do |low_price, low_index| price_array.each_with_index do |high_price, high_index| # if the split from the current high and low price is better than last found split # and the low day(index) is before high day(index) # set them to the record low, high, and split if high_price - low_price > split && low_index < high_index low = low_index high = high_index split = high_price - low_price end end # end high price loop end # end low price loop [low, high] end<file_sep>def caesar_cipher(encrypt, mod) #Split string into char array encrypt_array = encrypt.split('') #Loop though array with index to modify current itteration encrypt_array.each_with_index do |v, i| #Convert letter into numerical value numerical_letter = encrypt_array[i].ord #If char was upper case and will pass Z with modifier loop to A and continue if numerical_letter + mod > 90 && numerical_letter <= 90 numerical_letter = ( numerical_letter - 90 ) + ( 65 + mod - 1 ) #If char was lower case and will pass Z with modifier loop to A and continue elsif numerical_letter + mod > 122 && numerical_letter >= 97 numerical_letter = ( numerical_letter - 122 ) + ( 97 + mod - 1 ) #If char wont pass Z but is not a punctuation mark elsif numerical_letter > 65 numerical_letter += mod end #put numeric value into char array replacing old char value encrypt_array[i] = numerical_letter end #convert int array into string by using Array#pack encrypt_array.pack("c*") end
b6956e01e0cf78d552faeea44beb53e4a2e4467f
[ "Ruby" ]
7
Ruby
nicollis/BuildingBlocks
4568fbe115f81a037901146948141ca514046905
384105cede6665453b3216c26c80793e4e5490c5
refs/heads/master
<file_sep>FROM dnhsoft/jira-base:6.x ADD https://www.atlassian.com/software/jira/downloads/binary/atlassian-jira-6.4-x64.bin /jira-install.bin RUN /assets/install.sh <file_sep>#!/bin/bash TAG=$1 echo "Checking the html contents..." docker ps curl -LI localhost:8080 > ./temp.test FOUND_TXT=$(cat ./temp.test | grep "200 OK") if [ "$FOUND_TXT" == "" ]; then echo "Test failed for jira $TAG!" echo "[$(date +%Y-%m-%d-%H-%m-%S)] Test failed for jira $TAG" >> ./logs/tests.log else echo "Test passed for jira $TAG!" fi <file_sep># docker-jira Docker Jira images <file_sep>FROM dnhsoft/jira-base:6.x ADD https://www.atlassian.com/software/jira/downloads/binary/atlassian-jira-6.3.8-x64.bin /jira-install.bin RUN /assets/install.sh <file_sep>#!/bin/bash TAG=$1 echo "Starting test of jira $TAG..." mkdir -p logs docker build --no-cache -t jiratest:$TAG ./../$TAG #echo "Starting jira $TAG container..." docker run -d --name jiratest -p 8080:80 jiratest:$TAG ./test-html-content.sh $TAG #echo "Killing jira $TAG container and images..." docker stop jiratest docker rm jiratest docker rmi jiratest:$TAG echo "Finished test of jira $TAG"<file_sep>#!/bin/bash #stop on error set -e # Tests are under construction # ./test-single.sh 6.4.1
7b86a46ef955da2b64b3dda2022d42265536e6f7
[ "Markdown", "Dockerfile", "Shell" ]
6
Dockerfile
dnhsoft/docker-jira
818ddeaf2cc5e0960e5103f1e5762c7a148cd60d
a05f1c8d84ce320fce973d93dda5af73385579b4
refs/heads/master
<repo_name>13J-Programmers/gourmet-front<file_sep>/src/app/orders/purchase/purchase.component.ts import { Component, OnInit } from '@angular/core'; import { OrdersService } from '../shared/orders.service'; import { Order } from '../shared/order.model'; @Component({ selector: 'app-purchase', templateUrl: './purchase.component.html', styleUrls: ['./purchase.component.styl'] }) export class PurchaseComponent implements OnInit { private startX = 0; private isRelease = false; public isModalOpen = false; public orderStatus = ''; public orderResponse: Order; public beforePurchaseOrders: Order[]; public currentOrder: Order | null; public currentOrderStyles: {}; constructor(private ordersService: OrdersService) { } ngOnInit() { this.fetchBeforePurchaseOrders(); setInterval(() => { this.fetchBeforePurchaseOrders(); }, 5000); } fetchBeforePurchaseOrders() { this.ordersService.fetchBeforePurchaseOrders() .subscribe(res => { this.beforePurchaseOrders = res; this.currentOrder = this.beforePurchaseOrders.length > 0 ? this.beforePurchaseOrders[0] : null; }); } purchaseOrder (orderId: number) { this.ordersService.purchaseOrder(orderId) .subscribe(res => { this.orderResponse = this.currentOrder; this.orderStatus = 'success'; this.isModalOpen = true; this.beforePurchaseOrders = res; this.currentOrder = this.beforePurchaseOrders.length > 0 ? this.beforePurchaseOrders[0] : null; }, e => { this.orderResponse = null; this.orderStatus = 'error'; this.isModalOpen = true; }); } calcPrice(order: Order): number { return order.order_details.map(orderItem => { return orderItem.amount; }).reduce((prev, current) => { return prev + current; }, 0); } onTouchStart(event) { this.startX = event.changedTouches[0].pageX; this.isRelease = false; } onTouchEnd(event) { if (event.changedTouches[0].pageX - this.startX > 120) { this.purchaseOrder(this.currentOrder.id); } this.currentOrderStyles = { 'left.px': 0 }; this.isRelease = true; } onTouchMove(event) { const left = event.changedTouches[0].pageX - this.startX; this.currentOrderStyles = { 'left.px': left }; event.preventDefault(); } assetsPath(name) { if (name !== '') { return `../../../assets/images/icons/${name}.svg`; } else { return ''; } } closeModal() { this.isModalOpen = false; this.orderStatus = ''; } } <file_sep>/src/app/orders/deliver/deliver.component.ts import { Component, OnInit, HostListener, OnDestroy } from '@angular/core'; import { OrdersService } from '../shared/orders.service'; import { Order } from '../shared/order.model'; @Component({ selector: 'app-deliver', templateUrl: './deliver.component.html', styleUrls: ['./deliver.component.styl'] }) export class DeliverComponent implements OnInit, OnDestroy { constructor(private ordersService: OrdersService) { } public isModalOpen = false; public orderStatus = ''; public orderResponse: Order; public beforeDeliverOrders: Order[]; public currentOrder: Order; public deliveredOrders: Order[] = []; ngOnInit() { this.fetchBeforeDeliverOrders(); setInterval(() => { this.fetchBeforeDeliverOrders(); }, 5000); } ngOnDestroy() { } fetchBeforeDeliverOrders() { this.ordersService.fetchBeforeDeliverOrders() .subscribe(res => { this.beforeDeliverOrders = res; this.currentOrder = this.beforeDeliverOrders[0]; }); } deliverOrder(id: number) { this.ordersService.deliverOrder(id) .subscribe(res => { this.orderResponse = this.currentOrder; this.orderStatus = 'success'; this.isModalOpen = true; if (this.deliveredOrders.length > 1) { this.deliveredOrders.shift(); } this.deliveredOrders.push(this.currentOrder); this.beforeDeliverOrders = res; this.currentOrder = this.beforeDeliverOrders[0]; }, e => { this.orderResponse = null; this.orderStatus = 'error'; this.isModalOpen = true; }); } @HostListener('document:keydown', ['$event']) onKeyDown(event) { if (this.currentOrder && event.keyCode === 13) { this.deliverOrder(this.currentOrder.id); } } assetsPath(name) { if (name !== '') { return `../../../assets/images/icons/${name}.svg`; } else { return ''; } } closeModal() { this.isModalOpen = false; this.orderStatus = ''; } } <file_sep>/src/app/orders/orders-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { OrdersComponent } from './orders.component'; import { RegisterComponent } from './register/register.component'; import { PurchaseComponent } from './purchase/purchase.component'; import { DeliverComponent } from './deliver/deliver.component'; const routes: Routes = [ { path: '', component: OrdersComponent, }, { path: 'orders/register', component: RegisterComponent, }, { path: 'orders/purchase', component: PurchaseComponent, }, { path: 'orders/deliver', component: DeliverComponent, }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class OrdersRoutingModule { } <file_sep>/src/app/orders/shared/orders.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { environment } from '../../../environments/environment'; import { Product } from './product.model'; import { Order, OrderDetailsAttribute } from './order.model'; @Injectable() export class OrdersService { constructor(private http: HttpClient) { } // 全商品を取得 fetchProducts (): Observable<Product[]> { const requestUrl = this.makeUrl('products/'); return this.http.get<Product[]>(requestUrl); } // 会計前のリストを取得 fetchBeforePurchaseOrders (): Observable<Order[]> { const requestUrl = this.makeUrl(`groups/${environment.group.id}/purchase`); return this.http.get<Order[]>(requestUrl); } // 配達前のリスト fetchBeforeDeliverOrders (): Observable<Order[]> { const requestUrl = this.makeUrl(`groups/${environment.group.id}/deliver`); return this.http.get<Order[]>(requestUrl); } registerOrder (orderDetails: OrderDetailsAttribute[]): Observable<Order> { const requestUrl = this.makeUrl(`groups/${environment.group.id}/register_orders`); const body = { order: { order_details_attributes: orderDetails.map ((orderItem) => orderItem.makeRequestBody()) } }; return this.http.post<Order>(requestUrl, body); } purchaseOrder (id: number): Observable<Order[]> { const requestUrl = this.makeUrl(`groups/${environment.group.id}/purchase/${id}/commit`); return this.http.post<Order[]>(requestUrl, {}); } deliverOrder (id: number): Observable<Order[]> { const requestUrl = this.makeUrl(`groups/${environment.group.id}/deliver/${id}/commit`); return this.http.post<Order[]>(requestUrl, {}); } private makeUrl(url: string): string { const scheme = environment.api.ssl ? 'https' : 'http'; return `${scheme}://${environment.api.host}:${environment.api.port}/api/${url}`; } } <file_sep>/src/environments/environment.prod.ts export const environment = { production: true, api: { host: 'jagasale-2017.tk', port: 80, ssl: false, }, group: { id: 1, }, }; <file_sep>/src/app/orders/orders.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { OrdersRoutingModule } from './orders-routing.module'; import { OrdersComponent } from './orders.component'; import { RegisterComponent } from './register/register.component'; import { PurchaseComponent } from './purchase/purchase.component'; import { OrdersService } from './shared/orders.service'; import { DeliverComponent } from './deliver/deliver.component'; import { RegisterItemComponent } from './register/register-item/register-item.component'; import { BgImgDirective } from 'shared/bg-img.directive'; import { StatusModalComponent } from './shared/status-modal/status-modal.component'; @NgModule({ imports: [ CommonModule, HttpClientModule, OrdersRoutingModule, ], declarations: [ OrdersComponent, RegisterComponent, PurchaseComponent, DeliverComponent, RegisterItemComponent, BgImgDirective, StatusModalComponent, ], providers: [ OrdersService, ], }) export class OrdersModule { } <file_sep>/src/app/orders/shared/status-modal/animation.ts import { trigger, state, style, animate, transition } from '@angular/animations'; export const animations = trigger( 'modalState', [ state('open', style({ opacity: 1, transform: 'scale(1)' })), state('close', style({ opacity: 0, transform: 'scale(1.1)' })), transition('* => open', [ style({ opacity: 0, transform: 'scale(1.1)' }), animate('100ms ease-in') ]), transition('* => close', animate('100ms ease-in')) ] ) <file_sep>/src/app/orders/shared/order.model.ts export class OrderDetailsAttribute { constructor ( public productId: number, public quantity: number ) { } public makeRequestBody(): any { return { product_id: this.productId, quantity: this.quantity, }; } } export class OrderDetail { constructor ( public id: number, public quantity: number, public amount: number, public product_name: string ) { } } export class Order { constructor ( public id: number, public date: string, public purchased_at: string | null, public delivered_at: string | null, public order_details: OrderDetail[] ) { } } <file_sep>/src/app/orders/register/register-item/register-item.component.ts import { Component, EventEmitter, Input, OnInit, Output, } from '@angular/core'; import { Product } from '../../shared/product.model'; @Component({ selector: 'app-register-item', templateUrl: './register-item.component.html', styleUrls: ['./register-item.component.styl'] }) export class RegisterItemComponent implements OnInit { @Input() product: Product; @Input() productCount = 0; @Output() purchaseProduct: EventEmitter<any> = new EventEmitter(); @Output() cancelProduct: EventEmitter<any> = new EventEmitter(); private defaultTop = document.documentElement.clientWidth > 400 ? 60 : 30; private startY = 0; private isRelease = false; private isSale = false; public productItemStyles = { 'top.px': this.defaultTop }; constructor() { } ngOnInit() { } assetsPath(name: string) { if (name.includes('_sale')) { this.isSale = true; name = name.replace('_sale', ''); } const path = `../../../../assets/images/${name}.jpg`; return path; } onTouchStart($event) { this.startY = $event.changedTouches[0].pageY; this.isRelease = false; } onTouchMove($event) { const top = this.defaultTop + $event.changedTouches[0].pageY - this.startY; this.productItemStyles = { 'top.px': top }; $event.preventDefault(); } onTouchEnd($event) { const diff = $event.changedTouches[0].pageY - this.startY; if (diff > 50) { this.purchaseProduct.emit(this.product); } if (diff < -50) { this.cancelProduct.emit(this.product); } this.isRelease = true; this.productItemStyles = { 'top.px': this.defaultTop }; } } <file_sep>/src/app/shared/bg-img.directive.ts import { Directive, ElementRef, Input, OnChanges, SimpleChanges } from '@angular/core'; @Directive({ selector: '[appBgImg]' }) export class BgImgDirective implements OnChanges { constructor(private el: ElementRef) { } @Input() src: string; ngOnChanges (changes: SimpleChanges) { if (changes.src.currentValue) { this.el.nativeElement.style.background = `url(${this.src}) center center / cover no-repeat`; } } } <file_sep>/src/app/orders/orders.component.ts import { Component, OnInit } from '@angular/core'; import { OrdersService } from './shared/orders.service'; @Component({ selector: 'app-orders', templateUrl: './orders.component.html', styleUrls: ['./orders.component.styl'] }) export class OrdersComponent implements OnInit { public ordersItems = [ { name: '注文', link: '/orders/register'}, { name: '会計', link: '/orders/purchase'}, { name: '調理', link: '/orders/deliver'} ]; constructor(private ordersService: OrdersService) { } ngOnInit() { } } <file_sep>/src/app/orders/register/register.component.ts import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Product } from '../shared/product.model'; import { Order, OrderDetailsAttribute } from '../shared/order.model'; import { OrdersService } from '../shared/orders.service'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.styl'] }) export class RegisterComponent implements OnInit { public products: Product[]; public currentOrder: OrderDetailsAttribute[] = []; public isModalOpen = false; public orderStatus = ''; public orderResponse: Order; constructor(private ordersService: OrdersService) { } ngOnInit() { this.fetchProducts(); setInterval(() => { this.fetchProducts(); }, 5000); } fetchProducts() { this.ordersService.fetchProducts() .subscribe(res => { this.products = res; this.products.sort((a, b) => { if (a.id < b.id) { return -1; } if (a.id > b.id) { return 1; } return 0; }); }); } addProduct(product: Product) { const index = this.currentOrder.findIndex(c => c.productId === product.id); if (index !== -1) { this.currentOrder[index].quantity += 1; } else { const newOrder = new OrderDetailsAttribute(product.id, 1); this.currentOrder.push(newOrder); } } decrementProduct(product: Product) { const index = this.currentOrder.findIndex(c => c.productId === product.id); if (index !== -1) { this.currentOrder[index].quantity -= 1; if (this.currentOrder[index].quantity === 0) { this.currentOrder.splice(index, 1); } } } getProductCount(product: Product): number { const index = this.currentOrder.findIndex(c => c.productId === product.id); if (index !== -1) { return this.currentOrder[index].quantity; } else { return 0; } } registerOrder() { if (this.currentOrder.length !== 0) { this.ordersService.registerOrder(this.currentOrder) .subscribe(res => { this.orderResponse = res; this.orderStatus = 'success'; this.isModalOpen = true; this.currentOrder = []; this.fetchProducts(); }, err => { this.orderResponse = null; this.orderStatus = 'error'; this.isModalOpen = true; }); } } calcPrice() { const price = this.currentOrder.map(c => { const product = this.products.find(p => p.id === c.productId); return c.quantity * product.price; }).reduce((a, b) => a + b, 0); return price; } assetsPath(name) { if (name !== '') { return `../../../assets/images/icons/${name}.svg`; } else { return ''; } } closeModal() { this.isModalOpen = false; this.orderStatus = ''; } } <file_sep>/src/app/orders/shared/status-modal/status-modal.component.ts import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core'; import { animations } from './animation'; @Component({ selector: 'app-status-modal', templateUrl: './status-modal.component.html', styleUrls: ['./status-modal.component.styl'], animations: [ animations ] }) export class StatusModalComponent implements OnInit, OnChanges { @Input() isOpen: Boolean; @Input() time: number; @Output() onClose: EventEmitter<any> = new EventEmitter(); private innerStatus = 'close'; constructor() { } ngOnInit() { } ngOnChanges(changes: SimpleChanges) { if (changes.isOpen.currentValue) { this.innerStatus = 'open'; const openTime = this.time ? this.time : 2000; setTimeout(() => { this.innerStatus = 'close'; }, openTime); setTimeout(() => { this.onClose.emit(null); }, openTime + 100); } } }
883392c8a982dce8cb84a2205a20ca9acbebe977
[ "TypeScript" ]
13
TypeScript
13J-Programmers/gourmet-front
33c6ba14833bdc1a5ab6c75be431503f64e92a5e
1d5daa69a0e0046609c5e6ddbcc1a27d683a37dd
refs/heads/master
<repo_name>14amoore/ms2FinalTest10<file_sep>/README.md # MS2 Final Project: This is the final working version of the final project I completed for my Major Studio 2 class during the Spring of 2019.<file_sep>/index.js console.log(`Let's see what we get!`); const Twit = require('twit'); const config = require('./config.js'); const say = require('say'); const Sentiment = require('sentiment'); const player = require('play-sound')(opts = {}); const T = new Twit(config); const params = ('statuses/filter', { follow: ['822215679726100480', '1020930595', '138203134'], }); const stream = T.stream('statuses/filter', params, gotData); function gotData(err, data, response) { const texts = data.statuses; for (let i = 0; i < texts.length; i++) { console.log(texts[i].text); } } stream.on('tweet', function(tweet, err) { const sentiment = new Sentiment(); const result = sentiment.analyze( tweet.text ); // console.log(tweet.user.screen_name + tweet.text); // // console.dir(result); // console.log(result.score); const song = result.score; function sing(song) { if (result.score <= 0 && result.score >= -1) { return './assets/gulls.wav'; } else if (result.score < -1 && result.score >= -2) { return './assets/flamingo.wav'; } else if (result.score < -2 && result.score >= -3) { return './assets/magpie.wav'; } else if (result.score < -3 && result.score >= -4) { return './assets/raven.wav'; } else if (result.score < -4 && result.score > -5) { return './assets/owl.wav'; } else if (result.score > 0 && result.score <= 1) { return './assets/robin.wav'; } else if (result.score > 1 && result.score <= 2) { return './assets/tui.wav'; } else if (result.score > 2 && result.score <= 3) { return './assets/kookaburra.wav'; } else if (result.score > 3 && result.score <= 4) { return './assets/fluiter.wav'; } else { return './assets/rooster.wav'; } } player.play(sing(song), {afplay: ['-v', 0.2]}, function(err) { if (err) throw err; }); const twit = (tweet.user.screen_name + tweet.text); function talk(twit) { rand = Math.random(); if (rand < 0.1) { console.log(twit); return twit; } else { console.log('tweet skipped'); } } function rando(vox) { rand = Math.random(); if (rand <= 0.2) { return 'Alex'; } else if (rand > 0.2 && rand <= 0.4) { return 'Daniel'; } else if (rand > 0.4 && rand <= 0.6) { return 'Fiona'; } else if (rand > 0.4 && rand <= 0.8) { return 'Fred'; } else { return 'Karen'; } } const vox = ['Alex', 'Daniel', 'Fiona', 'Fred', 'Karen']; say.speak(talk(twit), rando(vox)); });
0b23f375150c95a836a210229e623148bf2a0857
[ "Markdown", "JavaScript" ]
2
Markdown
14amoore/ms2FinalTest10
83e07922e4cbc80245a0837228809e2e6e6cc018
d5b770ad69afa7b209ed1b5ac27f2f30fb240c79
refs/heads/master
<file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n; int k; cin>>n>>k; vector<int> a; int total = 0; for(int i = 0 ; i<n;i++) { a.push_back( 5 *(i+1)); total += a[i]; } vector<int>b; for(int i = 0 ; i<=total ; i++) b.push_back(i); int l = -1; int r = total+1; while(l+1<r) { int m = (l+r)/2; if(m+k <= 240) l = m; else r = m; } int ans = 0;int t = 0; //cout<<l<<"\n"; for(int i = 0 ; i<n ; i++) { t+=a[i];//cout<<t<<"\n"; ans++; if(t > l) { cout<<ans-1; break; } if(t == l) { cout<<ans; break; } } } <file_sep># CompitetiveProgramming My life journey if i qualify IOI
1949a69cc3b4f6ac7a2c088f1a372ec871df6538
[ "Markdown", "C++" ]
2
C++
akkumarkumar/CompitetiveProgramming
74bb4915d4ee046e4af76141cf9fa5bb8af939a9
d42d0465bba43774a970c51efe5223c63a1b3f45
refs/heads/master
<repo_name>imonweb/SharePosts<file_sep>/README.md # SharePosts PHP MVC <file_sep>/app/views/inc/header.php <!DOCTYPE html> <html lang=“en”> <head> <!-- Required meta tags --> <meta charset="utf-8"> <!-- Mobile Specific Meta --> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title><?php echo SITENAME; ?></title> <meta name=“description” content=“Bootstrap”> <meta name="author" content="<NAME>"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="<?php echo URLROOT; ?>/css/style.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"> </head> <body> <?php require APPROOT . '/views/inc/navbar.php'; ?> <div class="container">
620b00032ba3601d449faa5ffd195a8c6ab45976
[ "Markdown", "PHP" ]
2
Markdown
imonweb/SharePosts
04acde83e681f48d2fdb9d8e02a7ced875310c26
6a6bddec44752b573220dad2fcf53fc631de76ec
refs/heads/master
<file_sep>#include <sstream> #include "MyHashTable.h" using namespace std; // Default constructor. Do not modiify. MyHashTable::MyHashTable() { for (size_t i = 0; i < CAPACITY; i++) { table[i] = new vector<pair<string, int>>; } } // Simple hash function. Do not modify. size_t MyHashTable::hash(string name) const { size_t accumulator = 0; for (size_t i = 0; i < name.size(); i++) { accumulator += name.at(i); } return accumulator % CAPACITY; } void MyHashTable::insertItem(string name, int perm) { int index = hash(name); table[index]->push_back(std::make_pair(name,perm)); } void MyHashTable::deleteItem(string name) { for(size_t i=0; i < this -> CAPACITY; i++){ for(vector<std::pair<std::string, int>>::iterator j = table[i]->begin(); j!= table[i]->end(); j++){ if(j->first == name){ table[i]->erase(j); return; } } } return; } string MyHashTable::toString() const { std::ostringstream oss; for(size_t i=0; i < this -> CAPACITY; i++){ oss<< i <<":"; if (table[i]->empty()) { oss<< "[]"<<endl; } else{ oss<<"["; for(vector<std::pair<std::string, int>>::iterator j = table[i]->begin(); j!= table[i]->end(); j++){ oss<<"("<< j->first<<","<<j->second<<")"; } oss<< "]"<<endl; } } return oss.str(); } MyHashTable::MyHashTable(const MyHashTable &orig) { for (size_t i = 0; i < CAPACITY; i++) { delete table[i]; table[i] = new vector<pair<string, int>>; } for(size_t i=0; i < CAPACITY; i++){ for(vector<std::pair<std::string, int>>::iterator j = orig.table[i]->begin(); j!= orig.table[i]->end(); j++){ this->table[i]->push_back(std::make_pair(j->first,j->second)); } } } MyHashTable::~MyHashTable() { for (size_t i = 0; i < CAPACITY; i++){ table[i]->clear(); delete table[i]; } }
e52bb28d35c4ad814825fcd285e0071e36ae10c7
[ "C++" ]
1
C++
kalebkwok/lab_sail
8c71f563edcb2cdd28da8f4b139586798584858c
ddbdf218becc2bdffd584e3001846d0f7dc89af8
refs/heads/master
<file_sep>import pandas as pd data def load_csv(filename): data=pd.read_csv(filename) print(data.head(5),data.shape) return data def clean_data(): data = load_csv("netflix_titles.csv") new_data= data.dropna() return new_data Datasdfgsd<file_sep>print("Module 3") dfgd
eb1aff7626538d69fed08af0335697f7ec445d9d
[ "Python" ]
2
Python
shubhamkj5/DataScienceE
85acdee802e07667d3194a4e19720370a9e6ff86
ca8237f423b6809099f5622dca09533663f76efb
refs/heads/master
<file_sep>package de.hasenburg.iotdsg.helper import de.hasenburg.geobroker.commons.model.spatial.Geofence import units.Distance import units.Distance.Unit.* import units.Time import units.Time.Unit.* class Stats { private var numberOfPingMessages = 0 private var clientDistanceTravelled = Distance(0, M) private var numberOfPublishedMessages = 0 private var totalPayloadSize = 0 private var numberOfOverlappingSubscriptionGeofences = 0 private var numberOfSubscribeMessages = 0 private var numberOfOverlappingMessageGeofences = 0 /***************************************************************** * Get Stats ****************************************************************/ fun getNumberOfPingMessages(): Int { return numberOfPingMessages } fun getNumberOfPublishedMessages(): Int { return numberOfPublishedMessages } fun getNumberOfSubscribeMessages(): Int { return numberOfSubscribeMessages } fun getClientDistanceTravelled(): Distance { return clientDistanceTravelled } fun getNumberOfOverlappingSubscriptionGeofences(): Int { return numberOfOverlappingSubscriptionGeofences } fun getNumberOfOverlappingMessageGeofences(): Int { return numberOfOverlappingMessageGeofences } fun getTotalPayloadSize(): Int { return totalPayloadSize } /***************************************************************** * Add Stats ****************************************************************/ fun addPingMessage() { numberOfPingMessages++ } fun addSubscribeMessage() { numberOfSubscribeMessages++ } fun addPublishMessage() { numberOfPublishedMessages++ } fun addPayloadSize(size: Int) { totalPayloadSize += size } /** * @param distance - distance travelled by the client */ fun addClientDistanceTravelled(distance: Distance) { clientDistanceTravelled += distance } /** * Counts and stores the number of overlapping subscription geofences. * */ fun addSubscriptionGeofenceOverlaps(geofence: Geofence, brokerAreas: List<Geofence>) { var intersects = -1 // own broker brokerAreas.forEach { if (geofence.intersects(it)) { intersects++ } } numberOfOverlappingSubscriptionGeofences += intersects } /** * Counts and stores the number of overlapping message geofences. * */ fun addMessageGeofenceOverlaps(geofence: Geofence, brokerAreas: List<Geofence>) { var intersects = -1 // own broker brokerAreas.forEach { if (geofence.intersects(it)) { intersects++ } } numberOfOverlappingMessageGeofences += intersects } /***************************************************************** * Summary ****************************************************************/ fun getSummary(subsPerBrokerArea: List<Int>, pubsPerBrokerArea: List<Int>, timeToRunPerClient: Time): String { val subscribers = subsPerBrokerArea.stream().mapToInt { it }.sum() val publishers = pubsPerBrokerArea.stream().mapToInt { it }.sum() val clients = subscribers + publishers return getSummary(clients, timeToRunPerClient) } fun getSummary(clientsPerBrokerArea: List<Int>, timeToRunPerClient: Time): String { val clients = clientsPerBrokerArea.stream().mapToInt { it }.sum() return getSummary(clients, timeToRunPerClient) } @Suppress("LocalVariableName") fun getSummary(numberOfClients: Int, timeToRunPerClient: Time): String { val distancePerClient_KM = getClientDistanceTravelled().d(KM) / numberOfClients // km val runtime_S = timeToRunPerClient.d(S) //s return """ Data set characteristics: Number of ping messages: ${getNumberOfPingMessages()} (${getNumberOfPingMessages() / runtime_S} messages/s) Number of subscribe messages: ${getNumberOfSubscribeMessages()} (${getNumberOfSubscribeMessages() / runtime_S} messages/s) Number of publish messages: ${getNumberOfPublishedMessages()} (${getNumberOfPublishedMessages() / runtime_S} messages/s) Publish payload size: ${getTotalPayloadSize() / 1000.0}KB (${getTotalPayloadSize() / getNumberOfPublishedMessages()} bytes/message) Client distance travelled: ${getClientDistanceTravelled().d(KM)}km ($distancePerClient_KM km/client) Client average speed: ${distancePerClient_KM / timeToRunPerClient.d(H)} km/h Number of message geofence broker overlaps: ${getNumberOfOverlappingMessageGeofences()} Number of subscription geofence broker overlaps: ${getNumberOfOverlappingSubscriptionGeofences()} """ } }<file_sep>package de.hasenburg.iotdsg import de.hasenburg.geobroker.commons.model.spatial.Geofence import de.hasenburg.geobroker.commons.model.spatial.Location import de.hasenburg.geobroker.commons.randomName import de.hasenburg.iotdsg.helper.* import org.apache.logging.log4j.LogManager import org.locationtech.spatial4j.distance.DistanceUtils import units.Time import java.io.File import kotlin.random.Random private val logger = LogManager.getLogger() // -------- Brokers -------- private val brokerNames = listOf("Columbus", "Frankfurt", "Paris") private val brokerAreas = listOf(Geofence.circle(Location(39.961332, -82.999083), 5.0), Geofence.circle(Location(50.106732, 8.663124), 2.1), Geofence.circle(Location(48.877366, 2.359708), 2.1)) private val clientsPerBrokerArea = listOf(200, 200, 200) // -------- Geofences -------- values are in degree private const val subscriptionGeofenceDiameter = 50.0 * DistanceUtils.KM_TO_DEG private const val messageGeofenceDiameter = 50.0 * DistanceUtils.KM_TO_DEG // -------- Others -------- private const val directoryPath = "./validation" private const val topic = "data" private const val payloadSize = 20 // byte fun main() { validateBrokersDoNotOverlap(brokerAreas) prepareDir(directoryPath) val stats = Stats() val setup = getSetupString("de.hasenburg.iotdsg.ValidationDataGeneratorKt") logger.info(setup) File("$directoryPath/00_summary.txt").writeText(setup) for (b in 0..2) { // pick a broker val broker = getBrokerTriple(b, brokerNames, brokerAreas, clientsPerBrokerArea) logger.info("Calculating actions for broker ${broker.first}") // loop through clients for broker for (c in 1..broker.third) { if ((100.0 * c / broker.third) % 5.0 == 0.0) { logger.info("Finished ${100 * c / broker.third}%") } val clientName = randomName() logger.debug("Calculating actions for client $clientName") val file = File("$directoryPath/${broker.first}-0_$clientName.csv") val writer = file.bufferedWriter() writer.write(getHeader()) // ping (0 - 5000 ms) var location = Location.randomInGeofence(broker.second) writer.write(calculatePingAction(Random.nextInt(0, 5000), location, stats)) // subscribe (10000 - 15000 ms) writer.write(calculateSubscribeActions(Random.nextInt(10000, 15000), location, stats)) // 5 publish (20000 - 55000 ms) writer.write(calculatePublishActions(5, 20000, 55000, location, stats)) // ping (60000 - 65000 ms) location = Location.randomInGeofence(broker.second) writer.write(calculatePingAction(Random.nextInt(60000, 65000), location, stats)) // WARNING: I AM NOT INSIDE MY OWN SUBSCRIPTION GEOFENCE ANYMORE! -> messages might not be delivered to anyone // 5 publish (70000 - 105000 ms) writer.write(calculatePublishActions(5, 70000, 105000, location, stats)) // subscribe (110000 - 115000 ms) writer.write(calculateSubscribeActions(Random.nextInt(110000, 115000), location, stats)) // 5 publish (120000 - 155000 ms) writer.write(calculatePublishActions(5, 120000, 155000, location, stats)) // final ping as last message writer.write(calculatePingAction(155000, location, stats)) writer.flush() writer.close() } } val timeToRunPerClient = Time(155, Time.Unit.S) val output = stats.getSummary(clientsPerBrokerArea, timeToRunPerClient) logger.info(output) File("$directoryPath/00_summary.txt").appendText(output) } private fun calculatePingAction(timestamp: Int, location: Location, stats: Stats): String { stats.addPingMessage() return "$timestamp;${location.lat};${location.lon};ping;;;\n" } private fun calculateSubscribeActions(timestamp: Int, location: Location, stats: Stats): String { val actions = StringBuilder() val geofence = Geofence.circle(location, subscriptionGeofenceDiameter) actions.append("$timestamp;${location.lat};${location.lon};subscribe;" + "$topic;${geofence.wktString};\n") stats.addSubscriptionGeofenceOverlaps(geofence, brokerAreas) stats.addSubscribeMessage() return actions.toString() } private fun calculatePublishActions(@Suppress("SameParameterValue") count: Int, startTime: Int, endTime: Int, location: Location, stats: Stats): String { val actions = StringBuilder() val gap = (endTime - startTime) / count val geofence = Geofence.circle(location, messageGeofenceDiameter) for (i in 0 until count) { val start = startTime + i * gap val end = startTime + (i + 1) * gap val timestamp = Random.nextInt(start, end) actions.append("$timestamp;${location.lat};${location.lon};publish;" + "$topic;${geofence.wktString};$payloadSize\n") stats.addMessageGeofenceOverlaps(geofence, brokerAreas) stats.addPublishMessage() stats.addPayloadSize(payloadSize) } return actions.toString() }<file_sep>package de.hasenburg.iotdsg /** The main idea of this scenario is that subscribers know what kind of data they want to receive, while publishers know in what geo-context a data delivery makes sense. For example, a subscriber might want to continuously receive air temperature readings. But what temperature readings should he receive? While he could receive all readings of sensors in close proximity, this is not necessarily the most intelligent solution. A more advanced solution can be created when the sensors define the geo-context in which their data has relevance, as they have additional knowledge about the environment they operate in. Thus, in this scenario subscribers create subscriptions for a set of topics; these subscriptions are only updated rarely and do not consider any Geofence. However, as subscribers are moving, their location is updated often. On the other hand, publishers do not travel at all and publish to their topic messages that have a geofence. */ import de.hasenburg.geobroker.commons.model.spatial.Geofence import de.hasenburg.geobroker.commons.model.spatial.Location import de.hasenburg.geobroker.commons.randomName import de.hasenburg.iotdsg.helper.* import org.apache.logging.log4j.LogManager import org.locationtech.spatial4j.distance.DistanceUtils import units.Time import units.Time.Unit.* import java.io.File import kotlin.random.Random.Default.nextDouble import kotlin.random.Random.Default.nextInt private val logger = LogManager.getLogger() // -------- Brokers -------- private val brokerNames = listOf("Columbus", "Frankfurt", "Paris") private val brokerAreas = listOf(Geofence.circle(Location(39.961332, -82.999083), 5.0), Geofence.circle(Location(50.106732, 8.663124), 2.1), Geofence.circle(Location(48.877366, 2.359708), 2.1)) private val workloadMachinesPerBroker = listOf(3, 3, 3) private val subsPerBrokerArea = listOf(400, 400, 400) private val pubsPerBrokerArea = listOf(800, 800, 800) // -------- Subscribers -------- private const val minTravelSpeed = 2 // km/h private const val maxTravelSpeed = 8 // km/h private val minTravelTime = Time(5, S) private val maxTravelTime = Time(30, S) // random choice whether to subscribe to temperature or not private const val checkTemperatureSubscriptionProbability = 5 // % // -------- Publishers -------- private val minPubTimeGap = Time(10, S) private val maxPubTimeGap = Time(60, S) // -------- Message Geofences -------- values are in degree private const val minTemperatureMessageGeofenceDiameter = 1.0 * DistanceUtils.KM_TO_DEG private const val maxTemperatureMessageGeofenceDiameter = 25.0 * DistanceUtils.KM_TO_DEG private const val minAnnouncementMessageGeofenceDiameter = 10.0 * DistanceUtils.KM_TO_DEG private const val maxAnnouncementMessageGeofenceDiameter = 100.0 * DistanceUtils.KM_TO_DEG // -------- Messages -------- private const val temperatureTopic = "temperature" private const val temperaturePayloadSize = 100 private const val announcementTopic = "announcement" private const val minAnnouncementPayloadSize = 50 private const val maxAnnouncementPayloadSize = 500 // -------- Others -------- private const val directoryPath = "./context" private val warmupTime = Time(5, S) private val timeToRunPerClient = Time(15, MIN) fun main() { validateBrokersDoNotOverlap(brokerAreas) prepareDir(directoryPath) val stats = Stats() val setup = getSetupString("de.hasenburg.iotdsg.DataDisGeneratorKt") logger.info(setup) File("$directoryPath/00_summary.txt").writeText(setup) for (b in 0..2) { // for sensors val broker = getBrokerTriple(b, brokerNames, brokerAreas, subsPerBrokerArea, pubsPerBrokerArea) var currentWorkloadMachine: Int logger.info("Calculating publisher actions for broker ${broker.first}") // loop through publishers for broker for (pub in 1..broker.third.second) { currentWorkloadMachine = getCurrentWorkloadMachine(pub, broker.first, workloadMachinesPerBroker[b], broker.third.second) val clientName = randomName() logger.debug("Calculating actions for publisher $clientName") // file and writer val file = File("$directoryPath/${broker.first}-${currentWorkloadMachine}_$clientName.csv") val writer = file.bufferedWriter() writer.write(getHeader()) // vars val location = Location.randomInGeofence(broker.second) var timestamp = Time(nextInt(0, warmupTime.i(MS)), MS) // write fixed location of publisher writer.write(calculatePingAction(timestamp, location, stats)) timestamp = warmupTime // determine whether announcement or temperature val announcement = getTrueWithChance(10) while (timestamp <= timeToRunPerClient) { if (announcement) { writer.write(calculateAnnouncementPublishAction(timestamp, location, stats)) } else { writer.write(calculateTemperaturePublishAction(timestamp, location, stats)) } timestamp += Time(nextInt(minPubTimeGap.i(MS), maxPubTimeGap.i(MS)), MS) } // add a last ping message at runtime, as "last message" writer.write(calculatePingAction(timeToRunPerClient, location, stats)) writer.flush() writer.close() } logger.info("Calculating subscriber actions for broker ${broker.first}") // loop through subscribers for broker for (sub in 1..broker.third.first) { // for subscribers currentWorkloadMachine = getCurrentWorkloadMachine(sub, broker.first, workloadMachinesPerBroker[b], broker.third.first) val clientName = randomName() val clientDirection = nextDouble(0.0, 360.0) logger.debug("Calculating actions for client $clientName which travels in $clientDirection") // file and writer val file = File("$directoryPath/${broker.first}-${currentWorkloadMachine}_$clientName.csv") val writer = file.bufferedWriter() writer.write(getHeader()) // vars var location = Location.randomInGeofence(broker.second) var timestamp = Time(nextInt(0, warmupTime.i(MS)), MS) // send first ping and create initial subscriptions writer.write(calculatePingAction(timestamp, location, stats)) writer.write(calculateTemperatureSubscribeAction(timestamp, location, stats)) writer.write(calculateAnnouncementSubscribeAction(timestamp, location, stats)) timestamp = warmupTime while (timestamp <= timeToRunPerClient) { writer.write(calculatePingAction(timestamp, location, stats)) // renew temperature action? if (getTrueWithChance( checkTemperatureSubscriptionProbability)) { writer.write(calculateTemperatureSubscribeAction(timestamp, location, stats)) } val travelTime = Time(nextInt(minTravelTime.i(MS), maxTravelTime.i(MS)), MS) location = calculateNextLocation(broker.second, location, clientDirection, travelTime, minTravelSpeed, maxTravelSpeed, stats) timestamp += travelTime } // add a last ping message at runtime, as "last message" writer.write(calculatePingAction(timeToRunPerClient, location, stats)) writer.flush() writer.close() } } // only consider subscribers for client distance travelled and average speed val output = stats.getSummary(subsPerBrokerArea, timeToRunPerClient) logger.info(output) File("$directoryPath/00_summary.txt").appendText(output) } private fun calculatePingAction(timestamp: Time, location: Location, stats: Stats): String { stats.addPingMessage() return "${timestamp.i(MS)};${location.lat};${location.lon};ping;;;\n" } private fun calculateTemperatureSubscribeAction(timestamp: Time, location: Location, stats: Stats): String { val actions = StringBuilder() val geofence = Geofence.world() actions.append("${timestamp.i(MS) + 1};${location.lat};${location.lon};subscribe;$temperatureTopic;${geofence.wktString};\n") stats.addSubscribeMessage() return actions.toString() } private fun calculateAnnouncementSubscribeAction(timestamp: Time, location: Location, stats: Stats): String { val actions = StringBuilder() val geofence = Geofence.world() actions.append("${timestamp.i(MS) + 2};${location.lat};${location.lon};subscribe;$announcementTopic;${geofence.wktString};\n") stats.addSubscribeMessage() return actions.toString() } private fun calculateAnnouncementPublishAction(timestamp: Time, location: Location, stats: Stats): String { val actions = StringBuilder() val geofence = Geofence.circle(location, nextDouble(minAnnouncementMessageGeofenceDiameter, maxAnnouncementMessageGeofenceDiameter)) val payloadSize = nextInt(minAnnouncementPayloadSize, maxAnnouncementPayloadSize) actions.append("${timestamp.i(MS) + 3};${location.lat};${location.lon};publish;$announcementTopic;${geofence.wktString};$payloadSize\n") stats.addPayloadSize(payloadSize) stats.addMessageGeofenceOverlaps(geofence, brokerAreas) stats.addPublishMessage() return actions.toString() } private fun calculateTemperaturePublishAction(timestamp: Time, location: Location, stats: Stats): String { val actions = StringBuilder() val geofence = Geofence.circle(location, nextDouble(minTemperatureMessageGeofenceDiameter, maxTemperatureMessageGeofenceDiameter)) val payloadSize = temperaturePayloadSize actions.append("${timestamp.i(MS) + 3};${location.lat};${location.lon};publish;$temperatureTopic;${geofence.wktString};$payloadSize\n") stats.addPayloadSize(payloadSize) stats.addMessageGeofenceOverlaps(geofence, brokerAreas) stats.addPublishMessage() return actions.toString() } <file_sep>package de.hasenburg.iotdsg import de.hasenburg.geobroker.commons.model.spatial.Geofence import de.hasenburg.geobroker.commons.model.spatial.Location import de.hasenburg.geobroker.commons.randomName import de.hasenburg.iotdsg.helper.Stats import de.hasenburg.iotdsg.helper.getHeader import de.hasenburg.iotdsg.helper.getSetupString import de.hasenburg.iotdsg.helper.prepareDir import org.apache.logging.log4j.LogManager import org.locationtech.spatial4j.distance.DistanceUtils import units.Time import units.Time.Unit.MS import java.io.File import kotlin.random.Random private val logger = LogManager.getLogger() // -------- Brokers -------- val nClients = 100 // -------- Publishers -------- private val minPubTimeGap = Time(5, Time.Unit.S) private val maxPubTimeGap = Time(10, Time.Unit.S) private const val topic = "data" private const val payloadSize = 20 // byte // -------- Geofences -------- values are in degree private val geofenceCenter = Location(20.0, 20.0) private const val geofenceDiameter = 50.0 * DistanceUtils.KM_TO_DEG // -------- Others -------- private const val directoryPath = "./match_all" private val warmupTime = Time(30, Time.Unit.S) private val timeToRunPerClient = Time(15, Time.Unit.MIN) fun main() { prepareDir(directoryPath) val stats = Stats() val setup = getSetupString("de.hasenburg.iotdsg.MatchAllGeneratorKt") logger.info(setup) File("$directoryPath/00_summary.txt").writeText(setup) logger.info("Calculating actions") val geofence = Geofence.circle(geofenceCenter, geofenceDiameter) // loop through clients for broker for (c in 1..nClients) { if ((100.0 * c / nClients) % 5.0 == 0.0) { logger.info("Finished ${100 * c / nClients}%") } val clientName = randomName() logger.debug("Calculating actions for client $clientName") val file = File("$directoryPath/$clientName.csv") val writer = file.bufferedWriter() writer.write(getHeader()) val timestamp = Time(Random.nextInt(0, warmupTime.i(MS) - 1), MS) val location = Location.randomInGeofence(geofence) // put location writer.write(calculatePingAction(timestamp, location, stats)) // create subscription writer.write(calculateSubscribeActions(Time(timestamp.i(MS) + 1, MS), Location.randomInGeofence(geofence), geofence, stats)) // publish until end writer.write(calculatePublishActions(warmupTime, timeToRunPerClient, location, geofence, stats)) writer.flush() writer.close() } val output = stats.getSummary(nClients, timeToRunPerClient) logger.info(output) File("$directoryPath/00_summary.txt").appendText(output) } private fun calculatePingAction(timestamp: Time, location: Location, stats: Stats): String { stats.addPingMessage() return "${timestamp.i(MS)};${location.lat};${location.lon};ping;;;\n" } private fun calculateSubscribeActions(timestamp: Time, location: Location, geofence: Geofence, stats: Stats): String { val actions = StringBuilder() actions.append("${timestamp.i(MS)};${location.lat};${location.lon};subscribe;" + "$topic;${geofence.wktString};\n") stats.addSubscribeMessage() return actions.toString() } private fun calculatePublishActions(startTime: Time, endTime: Time, location: Location, geofence: Geofence, stats: Stats): String { val actions = StringBuilder() var timestamp = startTime + Time(Random.nextInt(minPubTimeGap.i(MS), maxPubTimeGap.i(MS)), MS) while (endTime > timestamp) { actions.append("${timestamp.i(MS)};${location.lat};${location.lon};publish;" + "$topic;${geofence.wktString};$payloadSize\n") stats.addPublishMessage() stats.addPayloadSize(payloadSize) timestamp = Time(timestamp.i(MS) + Random.nextInt(minPubTimeGap.i(MS), maxPubTimeGap.i(MS)), MS) } return actions.toString() }<file_sep>package units import org.apache.logging.log4j.LogManager private val logger = LogManager.getLogger() class Distance(private val distance: Double, private val unit: Unit) { constructor(distance: Int, unit: Unit) : this(distance.toDouble(), unit) enum class Unit { M, KM } /** * Depicts the factor of [distance] related to the internal default unit METER. */ private val factor = when (unit) { Unit.M -> 1.0 Unit.KM -> 1000.0 } fun d(targetUnit: Unit): Double { return when (targetUnit) { Unit.M -> (distance * factor) Unit.KM -> (distance * factor / 1000.0) } } fun i(targetUnit: Unit): Int { return d(targetUnit).toInt() } operator fun plus(otherDistance: Distance): Distance { // pick smaller unit as new internal unit val newUnit = if (unit < otherDistance.unit) unit else otherDistance.unit val e1 = d(newUnit) val e2 = otherDistance.d(newUnit) return Distance(e1 + e2, newUnit) } operator fun compareTo(otherDistance: Distance): Int { // idea: compare smallest time unit return d(Unit.M).compareTo(otherDistance.d(Unit.M)) } override fun toString(): String { return "~${i(Unit.M)}m" } } fun main() { logger.info("100 meters:") printAllUnits(Distance(100, Distance.Unit.M)) logger.info("3400 meters:") printAllUnits(Distance(3400, Distance.Unit.M)) logger.info("2.7 kilometers:") printAllUnits(Distance(2.7, Distance.Unit.KM)) logger.info("11 kilometers:") printAllUnits(Distance(11, Distance.Unit.KM)) logger.info("\nComparision") logger.info("100 meters is smaller than 0.4km: {}", Distance(100, Distance.Unit.M) < Distance(0.4, Distance.Unit.KM)) logger.info("1km is larger than 999 meters: {}", Distance(1, Distance.Unit.KM) > Distance(999, Distance.Unit.M)) logger.info("\nAddition") var d1 = Distance(2, Distance.Unit.KM) d1 += Distance(5, Distance.Unit.M) logger.info("2km + 5m = 2005m -> {}m", d1.i(Distance.Unit.M)) } private fun printAllUnits(distance: Distance) { logger.info("\t{}m", distance.d(Distance.Unit.M)) logger.info("\t{}km", distance.d(Distance.Unit.KM)) }<file_sep>package de.hasenburg.iotdsg /** In the OpenData scenario, IoT sensors publish their data to their respective topic, i.e., temperature, humidity, or barometric pressure. This data is supposed to be available world wide so no message geofence to restrain access based on regions, exist. Furthermore, in this scenario subscribers have an interest in data from sensors nearby and thus create subscriptions for different sensors in proximity. Each subscriber might have a different preference regarding the proximity, so the subscription geofences have arbitrary sizes, even different for the same subscriber for the available topics. */ import de.hasenburg.geobroker.commons.model.spatial.Geofence import de.hasenburg.geobroker.commons.model.spatial.Location import de.hasenburg.geobroker.commons.randomName import de.hasenburg.iotdsg.helper.* import org.apache.logging.log4j.LogManager import org.locationtech.spatial4j.distance.DistanceUtils import units.Distance import units.Distance.Unit.KM import units.Distance.Unit.M import units.Time import units.Time.Unit.* import java.io.File import kotlin.random.Random private val logger = LogManager.getLogger() // -------- Brokers -------- private val brokerNames = listOf("Columbus", "Frankfurt", "Paris") private val brokerAreas = listOf(Geofence.circle(Location(39.961332, -82.999083), 5.0), Geofence.circle(Location(50.106732, 8.663124), 2.1), Geofence.circle(Location(48.877366, 2.359708), 2.1)) private val workloadMachinesPerBroker = listOf(3, 3, 3) private val subsPerBrokerArea = listOf(400, 400, 400) private val pubsPerBrokerArea = listOf(800, 800, 800) // -------- Subscribers -------- private val minTravelDistance = Distance(500, M) private val maxTravelDistance = Distance(100, KM) private val minMobilityCheck = Time(3, S) private val maxMobilityCheck = Time(6, S) private const val mobilityProbability = 10 // % // -------- Subscription Geofences -------- values are in degree private const val minTemperatureSubscriptionGeofenceDiameter = 1.0 * DistanceUtils.KM_TO_DEG private const val maxTemperatureSubscriptionGeofenceDiameter = 100.0 * DistanceUtils.KM_TO_DEG private const val minHumiditySubscriptionGeofenceDiameter = 1.0 * DistanceUtils.KM_TO_DEG private const val maxHumiditySubscriptionGeofenceDiameter = 100.0 * DistanceUtils.KM_TO_DEG private const val minBarometricSubscriptionGeofenceDiameter = 1.0 * DistanceUtils.KM_TO_DEG private const val maxBarometricSubscriptionGeofenceDiameter = 100.0 * DistanceUtils.KM_TO_DEG // -------- Publishers -------- private val minPubTimeGap = Time(5, S) private val maxPubTimeGap = Time(15, S) // -------- Messages -------- private const val temperatureTopic = "temperature" private const val humidityTopic = "humidity" private const val barometricPressureTopic = "barometric_pressure" private const val temperaturePayloadSize = 100 private const val minHumidityPayloadSize = 130 private const val maxHumidityPayloadSize = 180 private const val minBarometerPayloadSize = 210 private const val maxBarometerPayloadSize = 240 // -------- Others -------- private const val directoryPath = "./environment" private val warmupTime = Time(5, S) private val timeToRunPerClient = Time(15, MIN) fun main() { validateBrokersDoNotOverlap(brokerAreas) prepareDir(directoryPath) val stats = Stats() val setup = getSetupString("de.hasenburg.iotdsg.OpenDataGeneratorKt") logger.info(setup) File("$directoryPath/00_summary.txt").writeText(setup) for (b in 0..2) { val broker = getBrokerTriple(b, brokerNames, brokerAreas, subsPerBrokerArea, pubsPerBrokerArea) var currentWorkloadMachine: Int logger.info("Calculating publisher actions for broker ${broker.first}") // loop through publishers for broker for (pub in 1..broker.third.second) { currentWorkloadMachine = getCurrentWorkloadMachine(pub, broker.first, workloadMachinesPerBroker[b], broker.third.second) val clientName = randomName() logger.debug("Calculating actions for publisher $clientName") // file and writer val file = File("$directoryPath/${broker.first}-${currentWorkloadMachine}_$clientName.csv") val writer = file.bufferedWriter() writer.write(getHeader()) // vars val location = Location.randomInGeofence(broker.second) var timestamp = Time(Random.nextInt(0, warmupTime.i(MS)), MS) // write fixed location of publisher writer.write(calculatePingAction(timestamp, location, stats)) timestamp = warmupTime // pick device topic val rnd = Random.nextInt(0, 3) // generate actions until time reached while (timestamp <= timeToRunPerClient) { writer.write(calculatePublishActions(timestamp, location, rnd, stats)) timestamp += Time(Random.nextInt(minPubTimeGap.i(MS), maxPubTimeGap.i(MS)), MS) } // add a last ping message at runtime, as "last message" writer.write(calculatePingAction(timeToRunPerClient, location, stats)) writer.flush() writer.close() } logger.info("Calculating subscriber actions for broker ${broker.first}") // loop through subscribers for broker for (sub in 1..broker.third.first) { // for subscribers currentWorkloadMachine = getCurrentWorkloadMachine(sub, broker.first, workloadMachinesPerBroker[b], broker.third.first) val clientName = randomName() logger.debug("Calculating actions for subscriber $clientName") // file and writer val file = File("$directoryPath/${broker.first}-${currentWorkloadMachine}_$clientName.csv") val writer = file.bufferedWriter() writer.write(getHeader()) // vars var location = Location.randomInGeofence(broker.second) var timestamp = Time(Random.nextInt(0, warmupTime.i(MS)), MS) // send first ping (needed for broker jurisdiction) and create initial subscriptions writer.write(calculatePingAction(timestamp, location, stats)) writer.write(calculateSubscribeActions(timestamp, location, stats)) timestamp = warmupTime // generate actions until time reached while (timestamp <= timeToRunPerClient) { if (getTrueWithChance(mobilityProbability)) { // we are mobile and travel somewhere else location = calculateNextLocation(broker.second, location, Random.nextDouble(0.0, 360.0), minTravelDistance, maxTravelDistance, stats) // no need to send ping as subscriber location is not important -> no message geofence writer.write(calculateSubscribeActions(timestamp, location, stats)) } timestamp += Time(Random.nextInt(minMobilityCheck.i(MS), maxMobilityCheck.i(MS)), MS) } // add a last ping message at runtime, as "last message" writer.write(calculatePingAction(timeToRunPerClient, location, stats)) writer.flush() writer.close() } } val output = stats.getSummary(subsPerBrokerArea, pubsPerBrokerArea, timeToRunPerClient) logger.info(output) File("$directoryPath/00_summary.txt").appendText(output) } private fun calculatePingAction(timestamp: Time, location: Location, stats: Stats): String { stats.addPingMessage() return "${timestamp.i(MS)};${location.lat};${location.lon};ping;;;\n" } private fun calculateSubscribeActions(timestamp: Time, location: Location, stats: Stats): String { val actions = StringBuilder() // temperature val geofenceTB = Geofence.circle(location, Random.nextDouble(minTemperatureSubscriptionGeofenceDiameter, maxTemperatureSubscriptionGeofenceDiameter)) actions.append("${timestamp.i(MS) + 1};${location.lat};${location.lon};subscribe;$temperatureTopic;${geofenceTB.wktString};\n") stats.addSubscriptionGeofenceOverlaps(geofenceTB, brokerAreas) stats.addSubscribeMessage() // humidity val geofenceHB = Geofence.circle(location, Random.nextDouble(minHumiditySubscriptionGeofenceDiameter, maxHumiditySubscriptionGeofenceDiameter)) actions.append("${timestamp.i(MS) + 2};${location.lat};${location.lon};subscribe;$humidityTopic;${geofenceHB.wktString};\n") stats.addSubscriptionGeofenceOverlaps(geofenceHB, brokerAreas) stats.addSubscribeMessage() // barometric pressure val geofenceBB = Geofence.circle(location, Random.nextDouble(minBarometricSubscriptionGeofenceDiameter, maxBarometricSubscriptionGeofenceDiameter)) actions.append("${timestamp.i(MS) + 3};${location.lat};${location.lon};subscribe;$barometricPressureTopic;${geofenceBB.wktString};\n") stats.addSubscriptionGeofenceOverlaps(geofenceBB, brokerAreas) stats.addSubscribeMessage() return actions.toString() } private fun calculatePublishActions(timestamp: Time, location: Location, topicIndex: Int, stats: Stats): String { val actions = StringBuilder() val geofence = Geofence.world() when (topicIndex) { 0 -> { // temperature condition actions.append("${timestamp.i(MS) + 4};${location.lat};${location.lon};publish;$temperatureTopic;${geofence.wktString};$temperaturePayloadSize\n") stats.addPublishMessage() stats.addPayloadSize(temperaturePayloadSize) } 1 -> { // humidity broadcast val payloadSize = Random.nextInt(minHumidityPayloadSize, maxHumidityPayloadSize) actions.append("${timestamp.i(MS) + 5};${location.lat};${location.lon};publish;$humidityTopic;${geofence.wktString};$payloadSize\n") stats.addPublishMessage() stats.addPayloadSize(payloadSize) } 2 -> { // barometric pressure broadcast val payloadSize = Random.nextInt(minBarometerPayloadSize, maxBarometerPayloadSize) actions.append("${timestamp.i(MS) + 6};${location.lat};${location.lon};publish;$barometricPressureTopic;${geofence.wktString};$payloadSize\n") stats.addPublishMessage() stats.addPayloadSize(payloadSize) } else -> { logger.warn("Topic index {} out of range, no data will be published", topicIndex) } } return actions.toString() } <file_sep>package de.hasenburg.iotdsg /** In the hiking scenario, clients travel on pre-defined routes and publish data to all other clients in close proximity on a regular basis. Our clients are hikers that use a messaging service to share information concerning their surroundings (e.g., the condition of the path they are taking), as well as to send text messages to other hikers nearby. Each published message has a message geofence that ensures that data is not sent to clients too far away to keep information local and prevent data being mined by third parties. Furthermore, each client creates a subscription with a geofence comprising the nearby area; note, that each message and subscription geofence can have a different shape and size as clients can define these based on their personal needs and preferences. */ import de.hasenburg.geobroker.commons.model.spatial.Geofence import de.hasenburg.geobroker.commons.model.spatial.Location import de.hasenburg.geobroker.commons.randomName import de.hasenburg.iotdsg.helper.* import org.apache.logging.log4j.LogManager import org.locationtech.spatial4j.distance.DistanceUtils.KM_TO_DEG import units.Distance import units.Distance.Unit.KM import units.Time import units.Time.Unit.* import java.io.File import kotlin.random.Random private val logger = LogManager.getLogger() // -------- Travel -------- private const val minTravelSpeed = 2 // km/h private const val maxTravelSpeed = 8 // km/h private val minTravelTime = Time(5, S) private val maxTravelTime = Time(30, S) // -------- Brokers -------- private val brokerNames = listOf("Columbus", "Frankfurt", "Paris") private val brokerAreas = listOf(Geofence.circle(Location(39.961332, -82.999083), 5.0), Geofence.circle(Location(50.106732, 8.663124), 2.1), Geofence.circle(Location(48.877366, 2.359708), 2.1)) // to split the workload evenly across multiple machines for a given broker private val workloadMachinesPerBroker = listOf(3, 3, 3) private val clientsPerBrokerArea = listOf(1200, 1200, 1200) // -------- Geofences -------- values are in degree private const val roadConditionSubscriptionGeofenceDiameter = 0.5 * KM_TO_DEG private const val roadConditionMessageGeofenceDiameter = 0.5 * KM_TO_DEG private const val minTextBroadcastSubscriptionGeofenceDiameter = 1.0 * KM_TO_DEG private const val maxTextBroadcastSubscriptionGeofenceDiameter = 50.0 * KM_TO_DEG private const val minTextBroadcastMessageGeofenceDiameter = 1.0 * KM_TO_DEG private const val maxTextBroadcastMessageGeofenceDiameter = 50.0 * KM_TO_DEG // -------- Messages -------- private const val roadConditionPublicationProbability = 10 // % private const val textBroadcastPublicationProbability = 50 // % private const val roadConditionPayloadSize = 100 // byte private const val minTextBroadcastPayloadSize = 10 // byte private const val maxTextBroadcastPayloadSize = 1000 // byte // -------- Others -------- private const val directoryPath = "./hiking" private const val roadConditionTopic = "road" private const val textBroadcastTopic = "text" private const val topicPermutations = 1 // e.g., 2 -> road/0, road/1 + text/0, text/1 private val subscriptionRenewalDistance = Distance(50, Distance.Unit.M) private val warmupTime = Time(5, S) private val timeToRunPerClient = Time(15, MIN) /** * Steps: * 1. pick broker * 2. pick a client -> random name * 3. loop: * - calculate next location and timestamp * - send: ping, subscribe, publish */ fun main() { validateBrokersDoNotOverlap(brokerAreas) prepareDir(directoryPath) val stats = Stats() val setup = getSetupString("de.hasenburg.iotdsg.HikingGeneratorKt") logger.info(setup) File("$directoryPath/00_summary.txt").writeText(setup) for (b in 0..2) { // pick a broker val broker = getBrokerTriple(b, brokerNames, brokerAreas, clientsPerBrokerArea) logger.info("Calculating actions for broker ${broker.first}") var currentWorkloadMachine: Int // loop through clients for broker for (c in 1..broker.third) { currentWorkloadMachine = getCurrentWorkloadMachine(c, broker.first, workloadMachinesPerBroker[b], broker.third) val clientName = randomName() val clientDirection = Random.nextDouble(0.0, 360.0) logger.debug("Calculating actions for client $clientName which travels in $clientDirection") // file and writer val file = File("$directoryPath/${broker.first}-${currentWorkloadMachine}_$clientName.csv") val writer = file.bufferedWriter() writer.write(getHeader()) // vars var location = Location.randomInGeofence(broker.second) var lastUpdatedLocation = location // needed to determine if subscription should be updated var timestamp = Time(Random.nextInt(0, warmupTime.i(MS)), MS) val topicPermutation = Random.nextInt(0, topicPermutations) // this geofence is only calculated once per client val geofenceTB = Geofence.circle(location, Random.nextDouble(minTextBroadcastSubscriptionGeofenceDiameter, maxTextBroadcastSubscriptionGeofenceDiameter)) // send first ping and create initial subscriptions writer.write(calculatePingAction(timestamp, location, stats)) writer.write(calculateSubscribeActions(timestamp, location, geofenceTB, topicPermutation, stats)) timestamp = warmupTime // generate actions until time reached while (timestamp <= timeToRunPerClient) { writer.write(calculatePingAction(timestamp, location, stats)) val travelledDistance = Distance(location.distanceKmTo(lastUpdatedLocation), KM) if (travelledDistance >= subscriptionRenewalDistance) { logger.debug("Renewing subscription for client $clientName") writer.write(calculateSubscribeActions(timestamp, location, geofenceTB, topicPermutation, stats)) lastUpdatedLocation = location } writer.write(calculatePublishActions(timestamp, location, topicPermutation, stats)) val travelTime = Time(Random.nextInt(minTravelTime.i(MS), maxTravelTime.i(MS)), MS) location = calculateNextLocation(broker.second, location, clientDirection, travelTime, minTravelSpeed, maxTravelSpeed, stats) timestamp += travelTime } // add a last ping message at runtime, as "last message" writer.write(calculatePingAction(timeToRunPerClient, location, stats)) writer.flush() writer.close() } } val output = stats.getSummary(clientsPerBrokerArea, timeToRunPerClient) logger.info(output) File("$directoryPath/00_summary.txt").appendText(output) } private fun calculatePingAction(timestamp: Time, location: Location, stats: Stats): String { stats.addPingMessage() return "${timestamp.i(MS)};${location.lat};${location.lon};ping;;;\n" } private fun calculateSubscribeActions(timestamp: Time, location: Location, geofenceTB: Geofence, topicPermutation: Int, stats: Stats): String { val actions = StringBuilder() // road condition val geofenceRC = Geofence.circle(location, roadConditionSubscriptionGeofenceDiameter) actions.append("${timestamp.i(MS) + 1};${location.lat};${location.lon};subscribe;" + "${permute(roadConditionTopic, topicPermutation)};${geofenceRC.wktString};\n") stats.addSubscriptionGeofenceOverlaps(geofenceRC, brokerAreas) stats.addSubscribeMessage() // text broadcast actions.append("${timestamp.i(MS) + 2};${location.lat};${location.lon};subscribe;" + "${permute(textBroadcastTopic, topicPermutation)};${geofenceTB.wktString};\n") stats.addSubscriptionGeofenceOverlaps(geofenceTB, brokerAreas) stats.addSubscribeMessage() return actions.toString() } private fun calculatePublishActions(timestamp: Time, location: Location, topicPermutation: Int, stats: Stats): String { val actions = StringBuilder() // road condition if (getTrueWithChance(roadConditionPublicationProbability)) { val geofenceRC = Geofence.circle(location, roadConditionMessageGeofenceDiameter) actions.append("${timestamp.i(MS) + 3};${location.lat};${location.lon};publish;" + "${permute(roadConditionTopic, topicPermutation)};${geofenceRC.wktString};$roadConditionPayloadSize\n") stats.addMessageGeofenceOverlaps(geofenceRC, brokerAreas) stats.addPublishMessage() stats.addPayloadSize(roadConditionPayloadSize) } // text broadcast if (getTrueWithChance(textBroadcastPublicationProbability)) { val geofenceTB = Geofence.circle(location, Random.nextDouble(minTextBroadcastMessageGeofenceDiameter, maxTextBroadcastMessageGeofenceDiameter)) val payloadSize = Random.nextInt(minTextBroadcastPayloadSize, maxTextBroadcastPayloadSize) actions.append("${timestamp.i(MS) + 4};${location.lat};${location.lon};publish;" + "${permute(textBroadcastTopic, topicPermutation)};${geofenceTB.wktString};$payloadSize\n") stats.addMessageGeofenceOverlaps(geofenceTB, brokerAreas) stats.addPublishMessage() stats.addPayloadSize(payloadSize) } return actions.toString() } fun permute(topic: String, permutation: Int): String { return "$topic/$permutation" }<file_sep>package units import org.apache.logging.log4j.LogManager import kotlin.math.pow private val logger = LogManager.getLogger() class Time(private val time: Double, private val unit: Unit) { constructor(time: Int, unit: Unit) : this(time.toDouble(), unit) enum class Unit { MS, S, MIN, H } /** * Depicts the factor of [time] related to the internal default unit SECONDS. */ private val factor = when (unit) { Unit.MS -> 10.0.pow(-3) Unit.S -> 1.0 Unit.MIN -> 60.0 Unit.H -> 60.0 * 60.0 } fun d(targetUnit: Unit): Double { return when (targetUnit) { Unit.MS -> (time * factor * 10.0.pow(3)) Unit.S -> (time * factor) Unit.MIN -> (time * factor / 60.0) Unit.H -> (time * factor / 60.0 / 60.0) } } fun i(targetUnit: Unit): Int { return d(targetUnit).toInt() } operator fun plus(otherTime: Time): Time { // pick smaller unit as new internal unit val newUnit = if (unit < otherTime.unit) unit else otherTime.unit val e1 = d(newUnit) val e2 = otherTime.d(newUnit) return Time(e1 + e2, newUnit) } operator fun compareTo(otherTime: Time): Int { // idea: compare smallest time unit return d(Unit.MS).compareTo(otherTime.d(Unit.MS)) } override fun toString(): String { return "~${i(Unit.S)}s" } } fun main() { logger.info("Conversions") logger.info("11 seconds:") printAllUnits(Time(11, Time.Unit.S)) logger.info("1377 milli-seconds:") printAllUnits(Time(1377, Time.Unit.MS)) logger.info("12 min:") printAllUnits(Time(12, Time.Unit.MIN)) logger.info("12.5 min:") printAllUnits(Time(12.5, Time.Unit.MIN)) logger.info("2 hours:") printAllUnits(Time(2, Time.Unit.H)) logger.info("\nComparision") logger.info("11 seconds is smaller than 0.5min: {}", Time(11, Time.Unit.S) < Time(0.5, Time.Unit.MIN)) logger.info("1 hours is larger than 59min: {}", Time(1, Time.Unit.H) > Time(59, Time.Unit.MIN)) logger.info("1 hours <= 60min: {}", Time(1, Time.Unit.H) <= Time(60, Time.Unit.MIN)) logger.info("\nAddition") var t1 = Time(2, Time.Unit.S) t1 += Time(5, Time.Unit.MS) logger.info("2s + 5ms = 2005ms -> {}ms", t1.i(Time.Unit.MS)) } private fun printAllUnits(time: Time) { logger.info("\t{}ms", time.d(Time.Unit.MS)) logger.info("\t{}s", time.d(Time.Unit.S)) logger.info("\t{}min", time.d(Time.Unit.MIN)) logger.info("\t{}h", time.d(Time.Unit.H)) }<file_sep># IoT Scenario Data Set Generator Prerequisite: - Clone [GeoBroker](https://github.com/MoeweX/geobroker) - Run `mvn install` in cloned directory <file_sep>package de.hasenburg.iotdsg.helper import de.hasenburg.geobroker.commons.model.spatial.Geofence import de.hasenburg.geobroker.commons.model.spatial.Location import org.apache.logging.log4j.LogManager import units.Distance import units.Distance.Unit.* import units.Time import units.Time.Unit.* import java.io.File import kotlin.random.Random private val logger = LogManager.getLogger() /***************************************************************** * Preparation ****************************************************************/ /** * Validates that the given [brokerAreas] do not overlap. If they do, kills the program. */ fun validateBrokersDoNotOverlap(brokerAreas: List<Geofence>) { for (ba in brokerAreas) { var numberOfOverlaps = 0 for (baI in brokerAreas) { if (ba.intersects(baI)) { numberOfOverlaps++ } } if (numberOfOverlaps > 1) { logger.fatal("Brokers should not overlap!") System.exit(1) } } } fun prepareDir(directoryPath: String) { val dir = File(directoryPath) if (dir.exists()) { logger.info("Deleting old content") dir.deleteRecursively() } dir.mkdirs() } fun getSetupString(className: String): String { // there should be another solution in the future: https://stackoverflow.com/questions/33907095/kotlin-how-can-i-use-reflection-on-packages val c = Class.forName(className) val stringBuilder = java.lang.StringBuilder("Setup:\n") for (field in c.declaredFields) { field.isAccessible = true if (field.name.contains("logger")) { // do not use variable } else { stringBuilder.append("\t").append(field.name).append(": ").append(field.get(c)).append("\n") } } return stringBuilder.toString() } /** * @return a header for a CSV file */ fun getHeader(): String { return "timestamp(ms);latitude;longitude;action_type;topic;geofence;payload_size\n" } /***************************************************************** * During generation ****************************************************************/ /** * @param i - index of the selected broker * @return Triple(brokerName, brokerArea, clientsUsingThisBroker) */ fun getBrokerTriple(i: Int, brokerNames: List<String>, brokerAreas: List<Geofence>, clientsPerBrokerArea: List<Int>): Triple<String, Geofence, Int> { return Triple(brokerNames[i], brokerAreas[i], clientsPerBrokerArea[i]) } /** * @param i - index of the selected broker * @return Triple(brokerName, brokerArea, Pair(subscribersUsingThisBroker, publishersUsingThisBroker)) */ fun getBrokerTriple(i: Int, brokerNames: List<String>, brokerAreas: List<Geofence>, subsPerBrokerArea: List<Int>, pubsPerBrokerArea: List<Int>): Triple<String, Geofence, Pair<Int, Int>> { return Triple(brokerNames[i], brokerAreas[i], Pair(subsPerBrokerArea[i], pubsPerBrokerArea[i])) } fun getCurrentWorkloadMachine(clientIndex: Int, brokerName: String, workloadMachines: Int, clientsAtThisBroker: Int): Int { // determine current workload machine if (workloadMachines == 0) { logger.info("Skipping actions for broker $brokerName as it does not have any workload machines") return 0 } val currentWorkloadMachine = clientIndex % workloadMachines if ((100.0 * clientIndex / clientsAtThisBroker) % 5.0 == 0.0) { logger.info("Finished ${100 * clientIndex / clientsAtThisBroker}%") } return currentWorkloadMachine } /** * Returns true with the given chance. * * @param chance - the chance to return true (0 - 100) * @return true, if lucky */ fun getTrueWithChance(chance: Int): Boolean { @Suppress("NAME_SHADOWING") var chance = chance // normalize if (chance > 100) { chance = 100 } else if (chance < 0) { chance = 0 } val random = Random.nextInt(1, 101) return random <= chance } /** * Calculates the next [Location] and adds the corresponding travel distance to [stats]. * * @return the next [Location] */ fun calculateNextLocation(brokerGeofence: Geofence, location: Location, clientDirection: Double, minTravelDistance: Distance, maxTravelDistance: Distance, stats: Stats): Location { // calculate travelled distance val distance = Distance(Random.nextDouble(minTravelDistance.d(M), maxTravelDistance.d(M)), M) logger.trace("Travelling for ${distance.d(M)}m.") return calculateNextLocation(brokerGeofence, location, clientDirection, distance, stats) } /** * Calculates the next [Location] and adds the corresponding travel distance to [stats]. * * @return the next [Location] */ fun calculateNextLocation(brokerGeofence: Geofence, location: Location, clientDirection: Double, travelTime: Time, minTravelSpeed: Int, maxTravelSpeed: Int, stats: Stats): Location { val travelSpeed = Random.nextInt(minTravelSpeed, maxTravelSpeed) // km/h val distance = Distance(travelSpeed * travelTime.d(H), KM) // km logger.trace("Travelling with $travelSpeed km/h for ${travelTime.d(S)} seconds which leads to ${distance.d(M)}m.") return calculateNextLocation(brokerGeofence, location, clientDirection, distance, stats) } private fun calculateNextLocation(brokerGeofence: Geofence, location: Location, clientDirection: Double, travelDistance: Distance, stats: Stats): Location { var nextLocation: Location var relaxFactor = 1.0 while (true) { // choose a direction (roughly in the direction of the client val direction = Random.nextDouble(clientDirection - 10.0, clientDirection + 10.0) nextLocation = Location.locationInDistance(location, travelDistance.d(KM), direction) // in case we are at the edge of a geofence, we need to relax it a little bit otherwise this will be an // infinite loop relaxFactor += 1.0 if (relaxFactor > 30) { // let's go back by 180 degree nextLocation = Location.locationInDistance(location, travelDistance.d(KM), direction + 180.0) } else if (relaxFactor > 32) { logger.warn("Location $location cannot be used to find another location.") return location } // only stop when we found the next location if (brokerGeofence.contains(nextLocation)) { stats.addClientDistanceTravelled(travelDistance) return nextLocation } } }
a693ebde806443d36319c972f3603b85a8467d45
[ "Markdown", "Kotlin" ]
10
Kotlin
MoeweX/IoTDSG
1b4ae639d3e5a644db16adc21b6d289ee20442b2
5ca44af2304ac2e8affafc68ea9ba7f0e6595b09
refs/heads/master
<repo_name>0x07DC/PHPJSPong<file_sep>/README.md PHPJSPong ========= PHP/JS/jQuery Pong kin to Apache Pong (logstalgia) Alternative to Apache Pong for server-side log viewing. I like Apache Pong, but I didn't like the installation process, so I made my own version, which I entitled PHPJSPong, inspired by Apache Pong. It's really easy to install, just copy the files to a directory, set the log URL in the php.php file and the password in the phppong.php file (at the top, at $_REQUEST['u']='password). After that, go to the page, i.e. mysite.com/phppong.php?u=password and you're done! This is version 1, but hopefully there will be more in the future, with updates and improvements, like having the pages disappear after they're done showing. <file_sep>/phppong.php <?php require('php.php'); if($_REQUEST['p']!="password") exit(); $logArr = runLogViewer(); //print_r($logArr); $startTime = isset($_REQUEST['startTime'])?$_REQUEST['startTime']:time()-(12);//(.25*24*60*60); $endTime = isset($_REQUEST['endTime'])?$_REQUEST['endTime']:time(); $jsLog = json_encode($logArr); ?> <html> <head> <title>PhpPong</title> <style> body { background-color: #000011; color: #ccccff; } .phpPong.table { margin:auto; height:90%; width: 87%; border:1px dotted black; background-color: #00440a; } .phpPong.table #ips { width:20%; height:100%; } .phpPong.table #pages { width:20%; height:100%; } .phpPong.time { position: absolute; font-size: 200%; font-weight: bold; font-family: "Courier New"; color:#eeddde; } .circle { border-radius: 50%; width:7px; height:7px; background-color: #0CD3B6; } </style> <script src="jquery-2.1.1.min.js"></script> </head> <body> <div class='phpPong time'></div> <table class='phpPong table'> <tr> <td id='ips'></td><td id='innerMove'></td><td id='pages'></td> </tr> </table> <script> window.inputLog = JSON.parse('<?php echo $jsLog ?>'); window.inputLogStartInd = -1; window.thisSecond = '<?php echo $startTime ?>'; window.endTime = '<?php echo $endTime ?>'; for(var i = 0; i < inputLog.length; i++){ if(inputLog[i].time >= thisSecond){ inputLogStartInd = i; thisSecond = inputLog[i].time; break; } } if(inputLogStartInd!=-1){ window.thisLogInd = inputLogStartInd; window.pagesListed = new Array(); window.ipsListed = new Array(); runLogViewer(); } else { runLogViewer(); console.log("No log entries, waiting 10 seconds"); setTimeout(function(){ getNewLog(getNewLog(endTime,Math.round((new Date()).getTime()/1000))); },10000) } function runLogViewer(){ this.logViewerInterval = setInterval(function(){ if(inputLogStartInd!=-1 && typeof inputLog[thisLogInd] != "undefined") if(inputLog[thisLogInd].time==thisSecond){ var entCount = 0; while(inputLog[thisLogInd].time==thisSecond){ var repeatPage = false; var repeatIp = false; var uid = Math.random(); //console.log(pagesListed); for(var i = 0; i < pagesListed.length; i++){ if(pagesListed[i][3]==inputLog[thisLogInd].file){ repeatPage = true; break; } } for(var i = 0; i < ipsListed.length; i++){ if(ipsListed[i][3]==inputLog[thisLogInd].ip){ repeatIp = true; break; } } if(!repeatPage){ pagesListed.push(['pageName','ent'+entCount,'s'+thisSecond,inputLog[thisLogInd].file]); $(".phpPong.table #pages").append('<div class="pageName ent'+entCount+' uid'+uid+'" id="s'+thisSecond+'">'+inputLog[thisLogInd].file+'</div>'); // make pagesListed to handle duplicates } if(!repeatIp){ ipsListed.push(['ipAdd','ent'+entCount,'s'+thisSecond,inputLog[thisLogInd].ip]); $(".phpPong.table #ips").append('<div class="ipAdd ent'+entCount+' uid'+uid+'" id="s'+thisSecond+'">'+inputLog[thisLogInd].ip+'</div>'); // make ipsListed to handle duplicates } /* console.log($('.ipAdd.ent'+entCount+'#s'+thisSecond));*/ var ipAddTop,ipAddLeft; if(!repeatIp){ ipAddTop = ($('.ipAdd.ent'+entCount+'#s'+thisSecond).offset().top - $(window).scrollTop()); ipAddLeft = ($('.ipAdd.ent'+entCount+'#s'+thisSecond).offset().left); } else { ipAddTop = ($('.ipAdd.'+ipsListed[i][1]+'#'+ipsListed[i][2]).offset().top - $(window).scrollTop())+5; ipAddLeft = ($('.ipAdd.'+ipsListed[i][1]+'#'+ipsListed[i][2]).offset().left); } $("body").append( '<div class="circle ent'+entCount+' ip'+inputLog[thisLogInd].ip+'" id="s'+thisSecond+'" \ style="position:absolute;\ top:'+ipAddTop+';\ left:'+ipAddLeft+';"></div>'); //console.log($('.pageName.ent'+entCount+'#s'+thisSecond).length); var pageNameTop,pageNameLeft; if(!repeatPage){ pageNameTop = ($('.pageName.ent'+entCount+'#s'+thisSecond).offset().top - $(window).scrollTop())+5; pageNameLeft = ($('.pageName.ent'+entCount+'#s'+thisSecond).offset().left); } else { pageNameTop = ($('.pageName.'+pagesListed[i][1]+'#'+pagesListed[i][2]).offset().top - $(window).scrollTop())+5; pageNameLeft = ($('.pageName.'+pagesListed[i][1]+'#'+pagesListed[i][2]).offset().left); } animCircle("ent"+entCount,"s"+thisSecond,pageNameTop,pageNameLeft); function animCircle(entCount, thisSecond,pageNameTop,pageNameLeft){ $('.circle.'+entCount+'#'+thisSecond).stop().animate({ 'top':pageNameTop+'px', 'left':pageNameLeft+'px' },2000, function(){ for(var i = 0; i < ipsListed.length; i++){ //console.log("thisIp: "+ipsListed[i][3]+" circleIp: "+$(this).attr('class').split(" ")[2].substring(2)); if($(this).attr('class').split(" ")[2].substring(2)==ipsListed[i][3]){ ipAddTop = ($('.ipAdd.'+ipsListed[i][1]+'#'+ipsListed[i][2]).offset().top - $(window).scrollTop())+5; ipAddLeft = ($('.ipAdd.'+ipsListed[i][1]+'#'+ipsListed[i][2]).offset().left); console.log("ipAddTop: "+ipAddTop); break; } } //console.log("ipAddLeft: "+ipAddLeft); $(this).animate({/* 'left':($('.ipAdd.'+$(this).attr('class').split(" ")[2]+'#'+$(this).attr('id')).offset().left),// Can modify this to make it more pong-like (bounce at inverted angle) 'top':($('.ipAdd.'+$(this).attr('class').split(" ")[2]+'#'+$(this).attr('id')).offset().top - $(window).scrollTop())+5*/ 'left':ipAddLeft,// Can modify this to make it more pong-like (bounce at inverted angle) 'top':ipAddTop },2000,function(){ for(var i = 0; i < ipsListed.length; i++){ if($(this).attr('class').split(" ")[2].substring(2)==ipsListed[i][3]){/* ipAddTop = ($('.ipAdd.'+ipsListed[i][1]+'#'+ipsListed[i][2]).offset().top - $(window).scrollTop()); ipAddLeft = ($('.ipAdd.'+ipsListed[i][1]+'#'+ipsListed[i][2]).offset().left);*/ console.log(ipsListed); if($('.ip'+ipsListed[i][3]).length>1){ $('.ipAdd.'+ipsListed[i][1]+'#'+ipsListed[i][2]).fadeOut(700,function(){$(this).remove();}); ipsListed.splice(i,1); } break; } } $(this).fadeOut(700,function(){$(this).remove();}); // Adjust all dots /* console.log($(".circle")); for(var i = 0; i < $(".circle").length; i++){ //$('.circle.'+$(".circle")[i].attr('class').split(" ")[1]+'#'+$(".circle")[i].attr('id')).stop(); if($(".circle:nth-child("+(i+1)+")").length != 0){ console.log($(".circle")); animCircle( $(".circle:nth-child("+(i+1)+")").attr('class').split(" ")[1], $(".circle:nth-child("+(i+1)+")").attr('id'), $('.ipAdd.'+$(".circle:nth-child("+(i+1)+")").attr('class').split(" ")[1]+'#'+$(".circle:nth-child("+(i+1)+")").attr('id')).offset().top, $('.ipAdd.'+$(".circle:nth-child("+(i+1)+")").attr('class').split(" ")[1]+'#'+$(".circle:nth-child("+(i+1)+")").attr('id')).offset().left ); } }*/ }); }); } entCount++; thisLogInd++; if(inputLog.length<=thisLogInd && window.gettingLog == false){ getNewLog(endTime,Math.round((new Date()).getTime()/1000)); clearInterval(this); break; } } } if(typeof inputLog[thisLogInd] != 'undefined' && (inputLog[thisLogInd].time<thisSecond || inputLog.length<=thisLogInd) && window.gettingLog == false){ getNewLog(endTime,Math.round((new Date()).getTime()/1000)); clearInterval(this); } console.log("thisLogInd: "+thisLogInd+" inputLog.length: "+inputLog.length); $(".phpPong.time").html(timeConverter((thisSecond+2))); thisSecond++; console.log("thisNewSecond: "+thisSecond); },1000); } //http://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript function timeConverter(UNIX_timestamp){ var a = new Date(UNIX_timestamp*1000); var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; var year = a.getFullYear(); var month = months[a.getMonth()]; var date = a.getDate(); var hour = a.getHours(); var min = a.getMinutes(); var sec = a.getSeconds(); var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ; return time; } window.gettingLog = false; function getNewLog(start,end){ console.log("No log data, waiting 10 seconds..."); window.gettingLog = true; setTimeout(function(){ $.post('serveLog.php',{'startTime':start,'endTime':end},function(data){ if(data.substring(0,1)=="<"){getNewLog(start,end);return;} resData = JSON.parse(data); inputLog = resData[0]; startTime = resData[2]; inputLogStartInd = -1; thisLogInd = 0; for(var i = 0; i < inputLog.length; i++){ if(inputLog[i].time >= thisSecond){ inputLogStartInd = thisLogInd = i; //thisLogInd = i; thisSecond = inputLog[i].time; console.log("New log retrieved"); endTime = resData[1]; break; } //console.log(inputLog[i].time); } if(inputLog.length == 0){ getNewLog(endTime,Math.round((new Date()).getTime()/1000)); } window.gettingLog = false; }); },10000); } </script> </body> </html><file_sep>/php.php <?php function runLogViewer(){ date_default_timezone_set('AMERICA/NEW_YORK'); $log = file_get_contents(''); $logArrPre = explode("\n",$log); $logArr = array(); for($i = 0; $i < count($logArrPre); $i++){ preg_match('/^[^\s]*/', $logArrPre[$i], $newIp); $newIp = $newIp[0]; preg_match('/\[(.*)\]/', $logArrPre[$i], $newTime); $newTime = $newTime[1]; preg_match('/"(.*)"/', $logArrPre[$i], $pageNType); $pageNType = $pageNType[1]; preg_match('/([^\s]*)\s([^\s]*)\s([^"])/', $pageNType, $newPageNType); $newType = $newPageNType[1]; $newPage = $newPageNType[2]; $newProt = $newPageNType[3]; $newRow = array( "ip"=>$newIp, "time"=>strtotime($newTime), "file"=>$newPage, "reqType"=>$newType, "reqProt"=>$newProt, ); $logArr[] = $newRow; } return $logArr; } ?><file_sep>/serveLog.php <?php require('php.php'); $logArr = runLogViewer(); //print_r($logArr); $startTime = isset($_REQUEST['startTime'])?$_REQUEST['startTime']:time()-12;//(5*24*60*60); $endTime = isset($_REQUEST['endTime'])?$_REQUEST['endTime']:time(); // Clean up old entries or new ones (out of schedule range) $tempLogArr = $logArr; $logArr = array(); //echo $startTime; for($i = 0; $i < count($tempLogArr); $i++){ if(($tempLogArr[$i]['time']>=$startTime) && ($tempLogArr[$i]['time']<=$endTime)){ $logArr[] = $tempLogArr[$i]; } //print_r($tempLogArr[$i])."\n"; } $jsLog = json_encode(array($logArr,$endTime,$startTime)); echo $jsLog; ?>
e3af0f561a25a27b6542ca75ee1d287cd1eca713
[ "Markdown", "PHP" ]
4
Markdown
0x07DC/PHPJSPong
357a1cda3bef54985a0e78a60a614442194d035f
e9463f2462266b97132d23551e729b62197da3dd
refs/heads/master
<file_sep>///** Duy: This is a very naive receiver. Please improve it! ///** int analogPin = 3; // potentiometer wiper (middle terminal) connected to analog pin 3 int val = 0; // variable to store the value read int bit_duration = 5; int threshold = 512; int i = 0; int ar[10]; // All possible 10 bit patterns - just for sure int data1[] = {1,0,1,0,1,0,1,0,1,0}; // bit 1 int data2[] = {0,1,0,1,0,1,0,1,0,1}; // bit 1 int data3[] = {1,1,0,1,1,0,1,1,0,1}; // bit 0 int data4[] = {1,0,1,1,0,1,1,0,1,1}; // bit 0 int data5[] = {0,1,1,0,1,1,0,1,1,0}; // bit 0 boolean tmp; void setup() { Serial.begin(9600); // setup serial } void loop() { while(1){ val = analogRead(analogPin); // read the input signal Serial.println(val); if (val>threshold) ar[i] = 1; else ar[i] = 0; i++; if (i>9) break; delay(bit_duration); } // i = 0; // delay(bit_duration); // decoding bit 1 // tmp = true; // for (i = 0;i<=9;i++){ // if (ar[i] != data1[i]){ tmp = false; // break; // } // } // // if (tmp) Serial.println(1); // else{ // tmp = true; // for (i = 0;i<=9;i++){ // if (ar[i] != data2[i]){ tmp = false; // break; // } // } // if (tmp) Serial.println(1); // } // // // decoding bit 0s // tmp = true; // for (i = 0;i<=9;i++){ // if (ar[i] != data3[i]){ // tmp = false; // break; // } // } // if (tmp) Serial.println(0); // else{ // tmp = true; // for (i = 0;i<=9;i++){ // if (ar[i] != data4[i]){ // tmp = false; // break; // } // } // if (tmp) Serial.println(0); // else{ // tmp = true; // for (i = 0;i<=9;i++){ // if (ar[i] != data5[i]){ tmp = false; // break; // } // } // if (tmp) Serial.println(0); // } // } } <file_sep>package com.example.vlc_project_open_campus; import android.support.v7.app.ActionBarActivity; //import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.text.SpannableStringBuilder; import android.util.Log; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Point; import android.os.Bundle; import android.view.Display; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; //import android.os.Build; public class MainActivity extends ActionBarActivity implements OnClickListener { private static final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; private float WIDTH, HEIGHT; private EditText edit; private ImageButton button1, button2; private IndoorMapView map_view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Display size WindowManager wm = (WindowManager)this.getSystemService(Context.WINDOW_SERVICE); Display disp = wm.getDefaultDisplay(); Point p = new Point(); disp.getSize(p); this.WIDTH = p.x; this.HEIGHT = p.y; LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); setContentView(layout); LinearLayout layoutin = new LinearLayout(this); layoutin.setOrientation(LinearLayout.HORIZONTAL); int size = Math.min(100, Math.max(20, (int)(WIDTH/10))); edit = new EditText(this); edit.setWidth((int)WIDTH-4*size); edit.setHeight((int)(1.5*size)); edit.setTextSize(18.0f); layoutin.addView(edit, new LinearLayout.LayoutParams(WC, WC)); Resources res = this.getResources(); Bitmap bmp1 = BitmapFactory.decodeResource(res, R.drawable.search_icon); Bitmap bmp2 = BitmapFactory.decodeResource(res, R.drawable.update_icon); bmp1 = Bitmap.createScaledBitmap(bmp1, size, size, false); bmp2 = Bitmap.createScaledBitmap(bmp2, size, size, false); button1 = new ImageButton(this); button1.setImageBitmap(bmp1); button1.setColorFilter(Color.rgb(0, 0, 128)); button1.setOnClickListener(this); layoutin.addView(button1, new LinearLayout.LayoutParams(WC, WC)); button2 = new ImageButton(this); button2.setImageBitmap(bmp2); button2.setColorFilter(Color.rgb(0, 0, 128)); button2.setOnClickListener(this); layoutin.addView(button2, new LinearLayout.LayoutParams(WC, WC)); layout.addView(layoutin,new LinearLayout.LayoutParams(WC, WC)); map_view = new IndoorMapView(this, WIDTH, HEIGHT); layout.addView(map_view, new LinearLayout.LayoutParams(WC, WC)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v==button1) { String str = ((SpannableStringBuilder)edit.getText()).toString(); Log.i("Button1", "Search!"); Log.i("TextEdit", str); map_view.setDestination(str); map_view.invalidate(); return; } if(v==button2) { Log.i("Button2", "Update!"); map_view.setCurrentLocation(); map_view.invalidate(); return; } } } <file_sep>package com.example.vlc_project_open_campus; import java.util.HashMap; import java.util.Map; import android.util.Log; class LEDInfo { private String name, bits; private int x, y; public LEDInfo(String name, int x, int y, String bits) { this.name = name; this.x = x; this.y = y; this.bits = bits; } public void print(int n) { Log.i("LEDInfo", String.valueOf(n) + ": " + name + " " + String.valueOf(x) + " " + String.valueOf(y) + " " + bits); } public String getName() { return this.name; } public int getX() { return this.x; } public int getY() { return this.y; } public String getBits() { return this.bits; } } public class LEDData { public Map<String, LEDInfo> data; public LEDData() { this.data = new HashMap<String, LEDInfo>(); } public void put(String str){ String[] array = str.split(","); data.put(array[0], new LEDInfo(array[0], Integer.parseInt(array[1]), Integer.parseInt(array[2]), array[3])); } public LEDInfo get(String name){ return data.get(name); } public LEDInfo get2(String bits){ for(String key : data.keySet()) { LEDInfo value = data.get(key); if(bits.equals(value.getBits())) return value; } return null; } } <file_sep># indoor-positioning Project title: Indoor localization and navigation using Visible Light Communications. Member: me Job: Design a whole system Language: Java and Arduino When: Dec. 2016 to Sep. 2017 Where: Aizu University Why: Make a project base on interested IoT problem and to confirm my research. Problems: + Real IPS based on VLC How: + Transmitter site: - Design signal and make Arduino run it - Create Amplify circuit to guarantee the source for LED + Receiver site: - Make a connection with smartphone - Decode signal, correct it and send it to smartphone + Smartphone: - Bluetooth connection require - Receive signal - Detect location and make a navigation by Dijkstra's algorithm in given graph - Display the shortest path from current location to destination Short explain: the transmitters include LED Arduino UNO circuit and amplify circuit always send a signal. The smartphone will make a Bluetooth connection require to the receiver. Then after the connection is established the receiver will detect the signal from transmitter and correct it then send it to smartphone. The smartphone compare it to data base and know which node we are belong to and collect the destination node from User input. We have a database to store the nodes and edges in graph made from local map. It is multi-floor plan. And use two nodes with Dijkstra's algorithm the shortest path will display to user. link of paper : https://ieeexplore.ieee.org/document/8517235 <file_sep>package com.example.vlc_project_open_campus; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.Vector; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.res.AssetManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; public class IndoorMapView extends View implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener { private static final float DOUBLE = 2; private static final String ROOM_INFO_FILE = "ROOM-Info_F3.csv"; private static final String POSITION_INFO_FILE = "PS-Info_F3.csv"; private static final String CONNECTION_INFO_FILE = "CN-Info_F3.csv"; private float WIDTH, HEIGHT; private float width, height; private float x, y; private float ratio; private boolean zoom_up; private String current, destination; private AlertDialog.Builder debug_dialog, warning_dialog; private Bitmap bmp1, bmp2; private GestureDetector gd; private Map<String, String> room_name; private LEDData led_data; private PathFinding path_finding; public IndoorMapView(Context context, float WIDTH, float HEIGHT) { super(context); this.setFocusable(true); // Display size this.WIDTH = WIDTH; this.HEIGHT = HEIGHT; this.x = 0; this.y = 0; this.current = null; this.destination = null; // Dialog this.debug_dialog = new AlertDialog.Builder(context); this.debug_dialog.setTitle("DEBUG MODE"); this.debug_dialog.setMessage( "Cannot connect Arduino via USB serial. The Application will be changed DEBUG MODE."); this.debug_dialog.setPositiveButton("OK", null); this.warning_dialog = new AlertDialog.Builder(context); this.warning_dialog.setTitle("WARNING!"); this.warning_dialog.setMessage( "Cannot Find the Destination or the Current Locaiton."); this.warning_dialog.setPositiveButton("OK", null); Vector<String> lines = new Vector<String>(); // Room Size & LED data lines = this.read(POSITION_INFO_FILE); this.led_data = new LEDData(); for(int i=0; i<lines.size(); i++){ if(i<3) { String[] tmp = lines.get(i).split(","); if(tmp[0].equals("WIDTH")) this.width = Integer.parseInt(tmp[1]); if(tmp[0].equals("HEIGHT")) this.height = Integer.parseInt(tmp[1]); } else { this.led_data.put(lines.get(i)); } } this.ratio = this.WIDTH/this.width; this.zoom_up = false; // Room name & Node lines = this.read(ROOM_INFO_FILE); this.room_name = new HashMap<String, String>(); for(int i=1; i<lines.size(); i++){ String[] tmp = lines.get(i).split(","); this.room_name.put(tmp[0], tmp[1]); } // Path Setting lines = this.read(CONNECTION_INFO_FILE); this.path_finding = new PathFinding(lines); // Get PNG map. Resources res = this.getContext().getResources(); Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.map_f3); this.bmp1 = Bitmap.createScaledBitmap( bmp, (int)WIDTH, (int)(height*ratio), false); // this.bmp2 = Bitmap.createScaledBitmap( // bmp, (int)(WIDTH*DOUBLE), (int)(height*ratio*DOUBLE), false); this.gd = new GestureDetector(context, this); } public void setCurrentLocation(){ this.current = null; USBSerialCommunication usb_serial = new USBSerialCommunication(9600, this.getContext()); String signal = usb_serial.run(); // NO INCOMING SIGNAL if(signal == null) { this.current = "EA"; // DEBUG MODE open this.debug_dialog.show(); // Show Dialog return; } if(signal.isEmpty()){ this.warning_dialog.show(); // Show Dialog return; } LEDInfo info = led_data.get2(signal); if(info == null) return; this.current = info.getName(); } public void setDestination(String destination){ path_finding.clear(); if(!destination.isEmpty() && this.current != null && !this.current.equals(destination) && this.room_name.containsKey(destination) && this.led_data.data.containsKey(this.room_name.get(destination))) { this.destination = this.room_name.get(destination); path_finding.setTree(this.destination); } else { this.warning_dialog.show(); // Show Dialog this.destination = null; } } private Vector<String> read(String file_name) { Vector<String> lines = new Vector<String>(); AssetManager as = getResources().getAssets(); try { InputStream is = as.open(file_name); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String str; while((str = br.readLine()) != null) lines.add(str); br.close(); } catch(IOException e) { Log.e("FileRead", "Cannot open " + file_name + "."); } return lines; } @SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.WHITE); Paint paint = new Paint(); canvas.drawBitmap(bmp1, -x, -y, paint); float ratio_ = (this.zoom_up ? this.ratio*2 : this.ratio); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.GREEN); paint.setStrokeWidth(6); // Draw path line. if(this.current != null && this.destination != null && path_finding.getParent(this.current) != null){ LEDInfo value1, value2; value1 = led_data.get(current); String name=current, parent=null; while(true){ parent = path_finding.getParent(name); if(name.equals(parent)) break; value2 = led_data.get(parent); canvas.drawLine(value1.getX()*ratio_-x, value1.getY()*ratio_-y, value2.getX()*ratio_-x, value2.getY()*ratio_-y, paint); value1 = value2; name = parent; } } float radius = (this.zoom_up ? 20.0f : 10.0f); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(1); if(this.current != null && led_data.data.containsKey(this.current)) { LEDInfo value = led_data.get(current); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.BLUE); canvas.drawCircle( value.getX()*ratio_-x, value.getY()*ratio_-y, radius, paint); } if(this.destination != null && led_data.data.containsKey(this.destination)) { LEDInfo value = led_data.get(destination); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.RED); canvas.drawCircle( value.getX()*ratio_-x, value.getY()*ratio_-y, radius, paint); } } // Touch Event @Override public boolean onTouchEvent(MotionEvent event) { Log.d("TouchEvent", "X:" + event.getX() + ",Y:" + event.getY()); if(this.gd.onTouchEvent(event)) return true; return super.onTouchEvent(event); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { // TODO Auto-generated method stub return true; } @Override public boolean onDoubleTap(MotionEvent e) { // TODO Auto-generated method stub /* Log.d("onDoubleTap","onDoubleTap"); this.zoom_up = !this.zoom_up; if(this.zoom_up) { this.x = Math.min(WIDTH, Math.max( 0, (this.x+e.getX())*DOUBLE - WIDTH/DOUBLE)); this.y = Math.min(2*HEIGHT-WIDTH, Math.max( 0, (this.y+e.getY())*DOUBLE - HEIGHT/DOUBLE)); } else { this.x = 0; this.y = Math.min(HEIGHT-WIDTH, Math.max( 0, (this.y+e.getY()-HEIGHT)/DOUBLE)); } this.invalidate(); */ return true; } @Override public boolean onDoubleTapEvent(MotionEvent e) { // TODO Auto-generated method stub return true; } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return true; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub Log.i("onScroll", "X: " + distanceX + ", Y: " + distanceY); if(this.zoom_up) { this.x = Math.min(WIDTH, Math.max(0, this.x+distanceX)); this.y = Math.min(2*HEIGHT-WIDTH, Math.max(0, this.y+distanceY)); } else { this.x = 0; this.y = Math.min(HEIGHT-WIDTH, Math.max(0, this.y+distanceY)); } this.invalidate(); return true; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub return true; } } <file_sep>package com.example.vlc_project_open_campus; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Vector; class TreeElement { public String name; public String parent; public ArrayList<String> path; public TreeElement(String name) { this.name = name; this.parent = null; this.path = new ArrayList<String>(); } } public class PathFinding { private Map<String, TreeElement> tree; public PathFinding(Vector<String> lines) { tree = new HashMap<String, TreeElement>(); String[] name = lines.get(0).split(","); for(int i=1; i<lines.size(); ++i) { TreeElement el = new TreeElement(name[i]); String[] str = lines.get(i).split(","); for(int j=1; j<str.length; ++j){ if(str[j].equals("1") && i!=j) el.path.add(name[j]); } tree.put(name[i], el); } } public void clear() { for(String key : tree.keySet()){ tree.get(key).parent = null; } } public void setTree(String root){ tree.get(root).parent = root; Queue<String> qu = new LinkedList<String>(); qu.offer(root); while(!qu.isEmpty()){ int size = qu.size(); for(int k=0; k<size; k++){ String name = qu.poll(); for(String item : tree.get(name).path) { if(tree.get(item).parent == null) { tree.get(item).parent = name; qu.offer(item); } } } } } public String getParent(String name) { return tree.get(name).parent; } } <file_sep>const int LED = 8; //led connects to digital pin 13 const int bit_duration = 5; //milisecond int location = 0; // location code: 0 or 1 void setup() { Serial.begin(115200); // Too high several hundred pinMode(LED, OUTPUT); //set the digital pin as output } void loop() { if (location == 1) { // code pattern: 10 digitalWrite(LED,1); //turn on the led delay(bit_duration); digitalWrite(LED,0); //turn on the led delay(bit_duration); } else { // code pattern 110 digitalWrite(LED,1); delay(bit_duration); digitalWrite(LED,1); delay(bit_duration); digitalWrite(LED,0); delay(bit_duration); } }
3614ecf089eb796dc740d14b85e5fb5c1f68bf2e
[ "Markdown", "Java", "C++" ]
7
C++
Hoangduc1248/indoor-positioning
04148c649c211fbcc1822e46252d0eba1f9f2388
59123b6320d76bce4e9b2e4d2afb2d089dba24ca
refs/heads/master
<file_sep>class Interpreter: def __init__(self): self.intcode = [] self.noun = 1 self.verb = 1 self.instructions = 4 def parseIntcode(self, file): """ Takes intcode from a text file and converts it into a list to be used for this IntcodeInterpreter :param file: name of the intcode file to read from """ with open("input.txt") as code: self.intcode = code.read().split(",") self.intcode = list(map(int, self.intcode)) def setInstructions(self, number): """ Sets the number of instructions (not really useful yet, hard coded as 4?) :param number: number of instructions """ self.instructions = number def setNoun(self, number): """ Sets the noun for the program :param number: integer to be used for the noun """ self.noun = number def setVerb(self, number): """ Sets the verb for the program :param number: integer to be used for the verb """ self.verb = number def runIntcode(self): """ Runs given intcode with current noun, verb, and instruction settings :return: the final integer stored in address 0 of the intcode """ self.intcode[1] = self.noun self.intcode[2] = self.verb for instructionPointer in range(0, len(self.intcode), self.instructions): instruction = self.intcode[instructionPointer] if instruction is 99: break else: # Hard coded for now parameter1 = self.intcode[instructionPointer + 1] parameter2 = self.intcode[instructionPointer + 2] parameter3 = self.intcode[instructionPointer + 3] if instruction is 1: self.intcode[parameter3] = self.intcode[parameter1] + self.intcode[parameter2] elif instruction is 2: self.intcode[parameter3] = self.intcode[parameter1] * self.intcode[parameter2] else: print("Bad opcode: " + str(self.intcode[i])) return self.intcode[0]<file_sep>from IntcodeInterpreter import Interpreter #Part 1 program1 = Interpreter() program1.parseIntcode("input.txt") program1.setNoun(12) program1.setVerb(2) print("Part 1: " +str(program1.runIntcode())) #Part 2 program2 = Interpreter() noun = 0 verb = 0 while noun < 100: program2.parseIntcode("input.txt") program2.setNoun(noun) program2.setVerb(verb) if program2.runIntcode() == 19690720: break verb += 1 if verb == 100: verb = 0 noun += 1 print("Part 2: " + str(100 * noun + verb))<file_sep>def fuelCalculation(mass: int): """ Calculates fuel needed based on mass :param mass: mass of fuel/module :return: mass of fuel required to lift passed mass """ return mass // 3.0 - 2 def totalFuelCalculation(mass: int): """ Calculates total fuel needed based on mass (including fuel needed for fuel) :param mass: mass of fuel/module :return: mass of fuel required to lift passed mass plus additional fuel """ requiredFuel = 0 mass = fuelCalculation(mass) while mass > 0: requiredFuel += mass mass = fuelCalculation(mass) return requiredFuel part1Fuel = 0 part2Fuel = 0 with open("input.txt") as modules: for mass in modules: part1Fuel += fuelCalculation(int(mass)) part2Fuel += totalFuelCalculation(int(mass)) print("Part 1: " + str(part1Fuel)) print("Part 2: " + str(part2Fuel))<file_sep># Advent of Code 2019 Solutions https://adventofcode.com/2019 Everything is done in python
041cdc9a2c6e98156b4cd78a796d8534b86ee11c
[ "Markdown", "Python" ]
4
Python
SamuelCurrid/advent-of-code-2019
57d6d0d649f1cdda6f8b90912bc0fcf7826ef421
9f79e3cfcfff173c472598a8b57b9a733c419e91
refs/heads/master
<repo_name>ntnvu/cloning-taskrabbit<file_sep>/scripts/services/comment.js 'use strict'; app.factory('Comment', function($firebaseArray){ var ref = firebase.database().ref(); var Comment = { comments: function(taskID){ return $firebaseArray(ref.child('comments').child(taskID)); }, addComment: function(taskId, comment){ var task_comments = this.comments(taskId); comment.datetime = firebase.database.ServerValue.TIMESTAMP; if(task_comments){ return task_comments.$add(comment); } } }; return Comment; })
70cf7f01633317a67a012ff148f9fb57fe25f86d
[ "JavaScript" ]
1
JavaScript
ntnvu/cloning-taskrabbit
ecaa91bbad95f8f8426127c3ffa05c152f692095
8343a782b3b6dc34063f4e24063582722d90fc8b
refs/heads/master
<file_sep># Typescript watch bug ## Preperation ```bash yarn install # or npm install ``` ## Testing When executing typescript on the clean git clone of this repo with the following command ... ```bash node_modules/.bin/tsc -w -p . ``` ... it corretly outputs: ``` src/index.ts:3:26 - error TS2339: Property 'x' does not exist on type 'Coords'. 3 console.log(getPoint().c.x); ~ src/lib.ts:7:13 - error TS2322: Type '{ x: number; y: number; }' is not assignable to type 'Coords'. Object literal may only specify known properties, and 'x' does not exist in type 'Coords'. 7 x: 1, ~~~~ src/interfaces/Point.ts:3:5 3 c: Coords ~ The expected type comes from property 'c' which is declared here on type 'PointWrapper' [16:39:08] Found 2 errors. Watching for file changes. ``` When we now change line 7 in src/interfaces/Point.ts to the correct form `x: number` (instead of x2), while the watch is still running, a bug occurs: ``` src/index.ts:3:26 - error TS2339: Property 'x' does not exist on type 'Coords'. 3 console.log(getPoint().c.x); ~ [16:39:31] Found 1 error. Watching for file changes. ``` If we now stop the tsc process and run it again it works correctly: ``` [16:39:54] Found 0 errors. Watching for file changes. ```<file_sep>import { Point } from "./Point"; export interface PointWrapper extends Point { }<file_sep>import { PointWrapper } from "./interfaces/PointWrapper"; export function getPoint(): PointWrapper { return { name: "test", c: { x: 1, y: 2 } } };<file_sep>export interface Point { name: string, c: Coords } export interface Coords { x2: number, y: number }<file_sep>import { getPoint } from "./lib"; console.log(getPoint().c.x);
1e4ec29a39819f3b5e32fab358efda52e909a511
[ "Markdown", "TypeScript" ]
5
Markdown
benurb/typescript-watch-bug
b20ab4ddb8b3ac3258c1cb433b14f2ed4374406f
b4f6a827ff03a3a79dcd078abb9650a146bb2d16
refs/heads/master
<file_sep>import UIKit //:# Range Demo // //: A Demo for iOS Development Tips Weekly //: by <NAME> (C)2018, All rights reserved //: For videos go to http://bit.ly/TipsLinkedInLearning //: For code go to http://bit.ly/AppPieGithub //: let myDesserts = ["Cannoli","Mochi","Bunelos","Pecan Pie","Ice Cream"] //: Closed range var total = 0 for number in 0...5{ total += number } total //: Half Open range total = 0 for number in 0..<5{ total += number } total //: Assigning ranges //: Use as array subscripts //: Membership
aab1648cad1b7271e974870b797794c6ad2394a2
[ "Swift" ]
1
Swift
MakeAppPiePublishing/Tips_05_11_RangeDemo_Begin
d0ce1cacf128e7ca293faef990823f1ddde9abf3
e0e2e73aa882cee564d85993e078fe2f3815fd89
refs/heads/master
<repo_name>naseemakhtar994/SegmentedControl<file_sep>/segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/Notifier.java package segmented_control.widget.custom.android.com.segmentedcontrol; import java.util.ArrayList; import java.util.List; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentClickListener; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentSelectRequestListener; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentSelectedListener; import static segmented_control.widget.custom.android.com.segmentedcontrol.utils.Utils.lazy; /** * Created by <NAME> on 9/8/2017. */ class Notifier<D> implements OnSegmentClickListener<D>, OnSegmentSelectedListener<D>, OnSegmentSelectRequestListener<D> { private List<OnSegmentClickListener<D>> onSegmentClickListeners; private List<OnSegmentSelectedListener<D>> onSegmentSelectedListeners; @SuppressWarnings("unchecked") private OnSegmentSelectRequestListener<D> onSegmentSelectRequestListener; @Override public void onSegmentClick(final SegmentViewHolder<D> segmentViewHolder) { onEvent(onSegmentClickListeners, new Consumer<OnSegmentClickListener<D>>() { @Override public void apply(OnSegmentClickListener<D> onSegmentClickListener) { onSegmentClickListener.onSegmentClick(segmentViewHolder); } }); } @Override public void onSegmentSelected(final SegmentViewHolder<D> segmentViewHolder, final boolean isSelected, final boolean isReselected) { onEvent(onSegmentSelectedListeners, new Consumer<OnSegmentSelectedListener<D>>() { @Override public void apply(OnSegmentSelectedListener<D> onSegmentSelectedListener) { onSegmentSelectedListener.onSegmentSelected(segmentViewHolder, isSelected, isReselected); } }); } @Override public boolean onSegmentSelectRequest(final SegmentViewHolder<D> segmentViewHolder) { return onSegmentSelectRequestListener == null || onSegmentSelectRequestListener.onSegmentSelectRequest(segmentViewHolder); } void addOnSegmentClickListener(OnSegmentClickListener<D> onSegmentClickListener) { onSegmentClickListeners = lazy(onSegmentClickListeners, new ArrayList<OnSegmentClickListener<D>>()); onSegmentClickListeners.add(onSegmentClickListener); } void addOnSegmentSelectListener(OnSegmentSelectedListener<D> onSegmentSelectedListener) { onSegmentSelectedListeners = lazy(onSegmentSelectedListeners, new ArrayList<OnSegmentSelectedListener<D>>()); onSegmentSelectedListeners.add(onSegmentSelectedListener); } void setOnSegmentSelectRequestListener(OnSegmentSelectRequestListener<D> onSegmentSelectRequestListener) { this.onSegmentSelectRequestListener = onSegmentSelectRequestListener; } private <T> void onEvent(List<T> eventListeners, Consumer<T> listenerConsumer) { if (eventListeners != null && eventListeners.size() != 0) { for (T t : eventListeners) { listenerConsumer.apply(t); } } } } <file_sep>/segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/item_row_column/SegmentViewHolder.java package segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.view.View; import section_layout.widget.custom.android.com.sectionlayout.distributive_section_layout.DistributiveSectionLayout; /** * Created by <NAME> on 9/7/2017. */ public abstract class SegmentViewHolder<D> extends DistributiveSectionLayout.ViewHolder<SegmentData<D>> { private SegmentData<D> segmentData; private final View.OnClickListener onSectionViewClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (segmentData != null) segmentData.getOnSegmentClickListener().onSegmentClick(SegmentViewHolder.this); } }; public SegmentViewHolder(@NonNull View sectionView) { super(sectionView); } @Override protected final void onBind(SegmentData<D> segmentData) { this.segmentData = segmentData; getSectionView().setOnClickListener(onSectionViewClickListener); onSegmentBind(segmentData.getSegmentData()); } public final void setSelected(boolean isSelected) { if (segmentData.isSelected() && isSelected) { segmentData.isSelected = true; onSegmentSelected(true, true); } else if (isSelected) { segmentData.isSelected = true; onSegmentSelected(true, false); } else { segmentData.isSelected = false; onSegmentSelected(false, false); } } /** * Override this method in order to define, performed action, selected, unselected, reselected * * @param isSelected, represent selected state * @param isReselected, represent reselected state */ public void onSegmentSelected(boolean isSelected, boolean isReselected) { } public int getAbsolutePosition() { return segmentData.absolutePosition; } public boolean isSelected() { return segmentData.isSelected; } public int getRow() { return segmentData.getRow(); } public int getColumn() { return segmentData.getColumn(); } public D getSegmentData() { return segmentData.getSegmentData(); } public int getSelectedStrokeColor() { return segmentData.getSelectedStrokeColor(); } public int getUnSelectedStrokeColor() { return segmentData.getUnSelectedStrokeColor(); } public int getStrokeWidth() { return segmentData.getStrokeWidth(); } public int getSelectBackgroundColor() { return segmentData.getSelectBackgroundColor(); } public int getUnSelectedBackgroundColor() { return segmentData.getUnSelectedBackgroundColor(); } public int getSelectedTextColor() { return segmentData.getSelectedTextColor(); } public int getUnSelectedTextColor() { return segmentData.getUnSelectedTextColor(); } public int getTextSize() { return segmentData.getTextSize(); } public Typeface getTypeFace(){return segmentData.getTypeFace();} public int getCurrentSize() { return segmentData.getCurrentSize(); } public int getColumnCount() { return segmentData.getColumnCount(); } public int getTextHorizontalPadding() { return segmentData.getTextHorizontalPadding(); } public int getTextVerticalPadding() { return segmentData.getTextVerticalPadding(); } public int getSegmentVerticalMargin() { return segmentData.getSegmentVerticalMargin(); } public int getSegmentHorizontalMargin() { return segmentData.getSegmentHorizontalMargin(); } public int getTopLeftRadius() { return segmentData.getTopLeftRadius(); } public int getTopRightRadius() { return segmentData.getTopRightRadius(); } public int getBottomRightRadius() { return segmentData.getBottomRightRadius(); } public int getBottomLeftRadius() { return segmentData.getBottomLeftRadius(); } public boolean isRadiusForEverySegment() { return segmentData.isRadiusForEverySegment(); } protected abstract void onSegmentBind(D segmentData); } <file_sep>/segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/SegmentedControlViewComponent.java package segmented_control.widget.custom.android.com.segmentedcontrol; import android.support.annotation.NonNull; import android.view.View; import android.widget.LinearLayout; import section_layout.widget.custom.android.com.sectionlayout.SectionLayout; import view_component.lib_android.com.view_component.base_view.ViewComponent; /** * Created by <NAME> on 9/5/2017. */ class SegmentedControlViewComponent<D> extends ViewComponent { final SectionLayout<D> verticalSectionLayout; SegmentedControlViewComponent(@NonNull View rootView) { super(rootView); //noinspection unchecked verticalSectionLayout = (SectionLayout<D>) getRootViewGroup().getChildAt(0); verticalSectionLayout.setOrientation(LinearLayout.VERTICAL); } } <file_sep>/segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/listeners/OnSegmentSelectRequestListener.java package segmented_control.widget.custom.android.com.segmentedcontrol.listeners; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; /** * Created by <NAME> on 9/12/2017. */ public interface OnSegmentSelectRequestListener<D> { /** * The event will be triggered before perform segment selection,and after segment click event * * @param segmentViewHolder, clicked segment view holder * @return false segment selection will be ignored, true segment selection will be performed */ boolean onSegmentSelectRequest(SegmentViewHolder<D> segmentViewHolder); } <file_sep>/segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/SegmentedControlControllerComponent.java package segmented_control.widget.custom.android.com.segmentedcontrol; import android.graphics.Typeface; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import section_layout.widget.custom.android.com.sectionlayout.SectionLayout; import section_layout.widget.custom.android.com.sectionlayout.distributive_section_layout.DistributiveSectionLayout; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row.SegmentRowAdapter; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row.SegmentRowViewHolder; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentAdapter; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentData; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentDecoration; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentClickListener; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentSelectRequestListener; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentSelectedListener; import view_component.lib_android.com.view_component.base_view.ControllerComponent; /** * Created by <NAME> on 9/5/2017. */ class SegmentedControlControllerComponent<D> extends ControllerComponent<SegmentedControlViewComponent<D>> { private final Configs configs = Configs.getDefault(); private SegmentViewHolder<D> lastClickedSegmentViewHolder; private final Notifier<D> notifier = new Notifier<>(); private final List<D> dataList = new ArrayList<>(); private final OnSegmentClickListener<D> onSegmentClickListener = new OnSegmentClickListener<D>() { @Override public void onSegmentClick(SegmentViewHolder<D> segmentViewHolder) { notifier.onSegmentClick(segmentViewHolder); if (segmentViewHolder.equals(lastClickedSegmentViewHolder)) { // on section reselected segmentViewHolder.setSelected(true); notifier.onSegmentSelected(segmentViewHolder, true, true); } else if (notifier.onSegmentSelectRequest(segmentViewHolder)) { // on section selected // unSelect the last one if (lastClickedSegmentViewHolder != null) { lastClickedSegmentViewHolder.setSelected(false); notifier.onSegmentSelected(lastClickedSegmentViewHolder, false, false); } // select the current lastClickedSegmentViewHolder = segmentViewHolder; segmentViewHolder.setSelected(true); notifier.onSegmentSelected(segmentViewHolder, true, false); } } }; private void addSegment(D segmentData) { if (getVerticalSectionLayout().size() == 0 || !canAddToLastRow()) { addNewRow(); } addSegmentToLastRow(segmentData); } // removeLastSelected = true private void removeAllSegments(boolean removeLastSelected) { for (int row = 0; row < getVerticalSectionLayout().size(); row++) { getHorizontalSectionLayout(row).removeAllSections(); } getVerticalSectionLayout().removeAllSections(); dataList.clear(); if (removeLastSelected) { lastClickedSegmentViewHolder = null; } } private void addSegmentToLastRow(D segmentData) { DistributiveSectionLayout<SegmentData<D>> horizontalSectionLayout = getHorizontalSectionLayout(getLastRowIndex()); horizontalSectionLayout .addSection(SegmentData.create(segmentData, onSegmentClickListener, getAbsolutePosition(getLastHorizontalSectionLayout().size(), getVerticalSectionLayout().size() - 1), getLastRowIndex(), horizontalSectionLayout.size(), size(), configs.columnCount, configs.segmentDecoration)); horizontalSectionLayout.requestLayout(); } private int[] getRowAndColumnWithAbsolutePosition(int position) { int smallDiff = position % configs.columnCount; int diff = position - smallDiff; int row = (diff / configs.columnCount) + (smallDiff == configs.columnCount ? 1 : 0); int column = position % configs.columnCount; return new int[]{row, column}; } void notifyConfigIsChanged() { if (dataList.size() == 0) return; List<D> itemsData = new ArrayList<>(dataList); removeAllSegments(false); addSegments(itemsData); if (lastClickedSegmentViewHolder != null) { setSelectedSegment(lastClickedSegmentViewHolder.getAbsolutePosition()); } } private boolean canAddToLastRow() { return getHorizontalSectionLayout(getLastRowIndex()).size() < configs.columnCount; } private void addNewRow() { //noinspection unchecked getVerticalSectionLayout().addSection(configs.willDistributeEvenly); } private SectionLayout getVerticalSectionLayout() { //noinspection ConstantConditions return getViewComponent().verticalSectionLayout; } private DistributiveSectionLayout<SegmentData<D>> getHorizontalSectionLayout(int row) { //noinspection unchecked SegmentRowViewHolder<D> segmentedViewHolder = (SegmentRowViewHolder<D>) getVerticalSectionLayout().getViewHolderForAdapterPosition(row); return segmentedViewHolder.getDistributiveSectionLayout(); } private DistributiveSectionLayout<SegmentData<D>> getLastHorizontalSectionLayout() { return getHorizontalSectionLayout(getLastRowIndex()); } private int getLastRowIndex() { return getVerticalSectionLayout().size() - 1; } SegmentViewHolder<D> findSegmentByAbsolutePosition(int position) { int[] point = getRowAndColumnWithAbsolutePosition(position); return findSegmentByColumnAndRow(point[0], point[1]); } SegmentViewHolder<D> findSegmentByColumnAndRow(int column, int row) { return (SegmentViewHolder<D>) getHorizontalSectionLayout(column).getViewHolderForAdapterPosition(row); } void forEachSegment(SegmentConsumer<D> segmentConsumer) { for (int row = 0; row < getVerticalSectionLayout().size(); row++) { DistributiveSectionLayout<SegmentData<D>> horizontalSectionLayout = getHorizontalSectionLayout(row); for (int column = 0; column < horizontalSectionLayout.size(); column++) { segmentConsumer.apply(findSegmentByColumnAndRow(row, column)); } } } void setAccentColor(int color) { configs.segmentDecoration = SegmentDecoration.createDefault(getContext(), color); } void setSelectedStrokeColor(int color) { configs.segmentDecoration.selectedStrokeColor = color; } void setUnSelectedStrokeColor(int color) { configs.segmentDecoration.unSelectedStrokeColor = color; } void setStrokeWidth(int width) { configs.segmentDecoration.strokeWidth = width; } void setSelectedBackgroundColor(int color) { configs.segmentDecoration.selectBackgroundColor = color; } void setUnSelectedBackgroundColor(int color) { configs.segmentDecoration.unSelectedBackgroundColor = color; } void setSelectedTextColor(int color) { configs.segmentDecoration.selectedTextColor = color; } void setUnSelectedTextColor(int color) { configs.segmentDecoration.unSelectedTextColor = color; } void setTextSize(int textSize) { configs.segmentDecoration.textSize = textSize; } void setTypeFace(Typeface typeFace) { configs.segmentDecoration.typeface = typeFace; } void setTextVerticalPadding(int padding) { configs.segmentDecoration.textVerticalPadding = padding; } void setTextHorizontalPadding(int padding) { configs.segmentDecoration.textHorizontalPadding = padding; } void setSegmentVerticalMargin(int margin) { configs.segmentDecoration.segmentVerticalMargin = margin; } void setSegmentHorizontalMargin(int margin) { configs.segmentDecoration.segmentHorizontalMargin = margin; } void setRadius(int radius) { setTopLeftRadius(radius); setTopRightRadius(radius); setBottomRightRadius(radius); setBottomLeftRadius(radius); } void setTopLeftRadius(int radius) { configs.segmentDecoration.topLeftRadius = radius; } void setTopRightRadius(int radius) { configs.segmentDecoration.topRightRadius = radius; } void setBottomRightRadius(int radius) { configs.segmentDecoration.bottomRightRadius = radius; } void setBottomLeftRadius(int radius) { configs.segmentDecoration.bottomLeftRadius = radius; } void setRadiusForEverySegment(boolean radiusForEverySegment) { configs.segmentDecoration.radiusForEverySegment = radiusForEverySegment; } void setAdapter(SegmentAdapter adapter) { //noinspection ConstantConditions, setAdapter will be called from SegmentedControl getViewComponent().verticalSectionLayout.withAdapter(new SegmentRowAdapter(adapter)); } void addSegments(D[] segmentDataArray) { if (segmentDataArray == null || segmentDataArray.length == 0) return; addSegments(new ArrayList<>(Arrays.asList(segmentDataArray))); } void addSegments(List<D> segmentDataList) { if (segmentDataList == null || segmentDataList.size() == 0) return; dataList.addAll(new ArrayList<>(segmentDataList)); for (D segmentData : dataList) { addSegment(segmentData); } } void removeAllSegments() { removeAllSegments(true); } void setDistributeEvenly(boolean willDistributeEvenly) { configs.willDistributeEvenly = willDistributeEvenly; } void setColumnCount(int columnCount) { configs.columnCount = columnCount; } void addOnSegmentClickListener(OnSegmentClickListener<D> onSegmentClickListener) { notifier.addOnSegmentClickListener(onSegmentClickListener); } void addOnSegmentSelectListener(OnSegmentSelectedListener<D> onSegmentSelectedListener) { notifier.addOnSegmentSelectListener(onSegmentSelectedListener); } void setOnSegmentSelectRequestListener(OnSegmentSelectRequestListener<D> onSegmentSelectRequestListener) { notifier.setOnSegmentSelectRequestListener(onSegmentSelectRequestListener); } void setSelectedSegment(int absolutePosition) { int[] point = getRowAndColumnWithAbsolutePosition(absolutePosition); setSelectedSegment(point[0], point[1]); } void setSelectedSegment(int column, int row) { onSegmentClickListener.onSegmentClick(findSegmentByColumnAndRow(column, row)); } SegmentViewHolder<D> getSelectedViewHolder() { return lastClickedSegmentViewHolder; } int[] getSelectedColumnAndRow() { return isSelected() ? new int[]{lastClickedSegmentViewHolder.getColumn(), lastClickedSegmentViewHolder.getRow()} : new int[]{-1, -1}; } int getSelectedAbsolutePosition() { return isSelected() ? lastClickedSegmentViewHolder.getAbsolutePosition() : -1; } boolean isSelected() { return lastClickedSegmentViewHolder != null; } int size() { return dataList.size(); } int getAbsolutePosition(int column, int row) { return row * configs.columnCount + column; } } <file_sep>/settings.gradle include ':app', ':segmentedcontrolmodule' <file_sep>/README.md # Android SegmentedControl + multi row support ### minSdk API 14+ ![N|Solid](https://raw.githubusercontent.com/RobertApikyan/SegmentedControl/release_v0.1/app/src/main/res/mipmap-hdpi/ic_launcher.png) [Demo App, Play store link](https://play.google.com/store/apps/details?id=segmented_control.widget.custom.android.com.segmentedcontrolexample&hl=en) [Or try demo App online !](https://appetize.io/app/y4e91xhxgp47956bf73da4z4yg) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) ## Segmented control for android, with a lot of customization properties <img src="https://raw.githubusercontent.com/RobertApikyan/SegmentedControl/release_v0.1/docs/intro.gif.gif" width="300" height="525" /> ## ScreenShots <img src="https://raw.githubusercontent.com/RobertApikyan/SegmentedControl/release_v0.1/docs/device-2017-09-14-133621.png" width="400" /> <img src="https://raw.githubusercontent.com/RobertApikyan/SegmentedControl/release_v0.1/docs/device-2017-09-14-133711.png" width="400" /> <img src="https://raw.githubusercontent.com/RobertApikyan/SegmentedControl/release_v0.1/docs/device-2017-09-14-133736.png" width="400" /> <img src="https://raw.githubusercontent.com/RobertApikyan/SegmentedControl/release_v0.1/docs/device-2017-09-14-133907.png" width="400" /> <img src="https://raw.githubusercontent.com/RobertApikyan/SegmentedControl/release_v0.1/docs/device-2017-09-14-134003.png" width="400" /> <img src="https://raw.githubusercontent.com/RobertApikyan/SegmentedControl/release_v0.1/docs/device-2017-09-14-202249.png" width="400" /> ## Download ### Gradle #### Add to project level build.gradle ```groovy allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` #### Add dependency to app module level build.gradle ```groovy dependencies { implementation 'com.github.RobertApikyan:SegmentedControl:1.0.4' } ``` ### Maven ```xml <repositories> <repository> <id>jitpack.io</id> <url>https://jitpack.io</url> </repository> </repositories> ``` #### Add dependency ```xml <dependency> <groupId>com.github.RobertApikyan</groupId> <artifactId>SegmentedControl</artifactId> <version>1.0.4</version> </dependency>ø ``` ### Done. ## Simple usage in XML ```xml <segmented_control.widget.custom.android.com.segmentedcontrol.SegmentedControl android:id="@+id/segmented_control" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="8dp" app:columnCount="3" app:distributeEvenly="true" app:textVerticalPadding="6dp" app:radius="12dp" app:segments="@array/your_array_data" /> ``` # Attributes ```xml <attr name="distributeEvenly" format="boolean" /> setDistributeEvenly(boolean) <attr name="columnCount" format="integer" /> setColumnCount(int) <attr name="segments" format="reference" /> addSegments(Object[]), addSegments(List) <attr name="selectedStrokeColor" format="color" /> setSelectedStrokeColor(int) <attr name="unSelectedStrokeColor" format="color" /> setUnSelectedStrokeColor(int) <attr name="strokeWidth" format="dimension" / setStrokeWidth(int) <attr name="selectedBackgroundColor" format="color" /> setSelectedBackgroundColor(int) <attr name="unSelectedBackgroundColor" format="color" /> setUnSelectedBackgroundColor(int) <attr name="selectedTextColor" format="color"/> setSelectedTextColor(int) <attr name="unSelectedTextColor" format="color"/> setUnSelectedTextColor(int) <attr name="textSize" format="dimension"/> setTextSize(int) <attr name="textHorizontalPadding" format="dimension"/> setTextHorizontalPadding(int) <attr name="textVerticalPadding" format="dimension"/> setTextVerticalPadding(int) <attr name="segmentVerticalMargin" format="dimension"/> setSegmentVerticalMargin(int) <attr name="segmentHorizontalMargin" format="dimension"/> setSegmentHorizontalMargin(int) <attr name="radius" format="dimension"/> setRadius(int) <attr name="topLeftRadius" format="dimension"/> setTopLeftRadius(int) <attr name="topRightRadius" format="dimension"/> setTopRightRadius(int) <attr name="bottomRightRadius" format="dimension"/> setBottomRightRadius(int) <attr name="bottomLeftRadius" format="dimension"/> setBottomLeftRadius(int) <attr name="radiusForEverySegment" format="boolean"/> setRadiusForEverySegment(boolean) <attr name="fontAssetPath" format="string"/> setTypeFace(TypeFace) ``` ### Note: After every configuration change call segmentedControl.notifyConfigIsChanged() method #### Example. ```java segmentedControl.setStrokeWidth(width.intValue()); segmentedControl.setColumnCount(columnCount); segmentedControl.notifyConfigIsChanged(); ``` > SegmentedControl uses SegmentAdapter and SegmentViewHolder for displaying segments. There are allready exist a default implementations for SegmentAdapter (SegmentAdapterImpl) and SegmentViewHolder (SegmentViewHolderImpl), but if you want to make your custom implementation... well here is the steps ### 1. define segment_item.xml inside layouts folder ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_margin="2dp" android:background="@color/colorPrimary" android:gravity="center" android:textColor="@color/colorAccent" android:textSize="14sp" /> </LinearLayout> ``` ### 2. Craete SegmentViewHolder instance AppSegmentViewHolder (here I define the segment generic data type as a String) ```java public class AppSegmentViewHolder extends SegmentViewHolder<String> { TextView textView; public AppSegmentViewHolder(@NonNull View sectionView) { super(sectionView); textView = (TextView) sectionView.findViewById(R.id.text_view); } @Override protected void onSegmentBind(String segmentData) { textView.setText(segmentData); } } ``` ### 3. Create SegmentAdapter instance ```java public class AppSegmentAdapter extends SegmentAdapter<String, AppSegmentViewHolder> { @NonNull @Override protected AppSegmentViewHolder onCreateViewHolder(@NonNull LayoutInflater layoutInflater, ViewGroup viewGroup, int i) { return new AppSegmentViewHolder(layoutInflater.inflate(R.layout.item_segment, null)); } } ``` ### 4. Pass the adapter to the segmentedControl ```java segmentedControl = (SegmentedControl) findViewById(R.id.segmented_control); segmentedControl.setAdapter(new AppSegmentAdapter()); ``` ### 5.Finally add segements data. ```java segmentedControl.addSegments(getResources().getStringArray(R.array.segments)); ``` ### Thatas it ) ### For custom implementation use SegmentedControlUtils helper class in order to define segment background type and background radius. [![View Robert Apikyan profile on LinkedIn](https://www.linkedin.com/img/webpromo/btn_viewmy_160x33.png)](https://www.linkedin.com/in/robert-apikyan-24b915130/) License ------- Copyright 2017 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 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. <file_sep>/segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/item_row_column/SegmentAdapter.java package segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column; import section_layout.widget.custom.android.com.sectionlayout.distributive_section_layout.DistributiveSectionLayout; /** * Created by <NAME> on 9/7/2017. */ public abstract class SegmentAdapter<D, VH extends SegmentViewHolder<D>> extends DistributiveSectionLayout.Adapter<SegmentData<D>, VH> { } <file_sep>/segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/item_row/SegmentRowViewHolder.java package segmented_control.widget.custom.android.com.segmentedcontrol.item_row; import android.support.annotation.NonNull; import android.view.View; import android.widget.LinearLayout; import section_layout.widget.custom.android.com.sectionlayout.SectionLayout; import section_layout.widget.custom.android.com.sectionlayout.distributive_section_layout.DistributiveSectionLayout; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentAdapter; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentData; /** * Created by <NAME> on 9/7/2017. */ public class SegmentRowViewHolder<D> extends SectionLayout.ViewHolder<Boolean> { private final DistributiveSectionLayout<SegmentData<D>> distributiveSectionLayout; SegmentRowViewHolder(@NonNull View sectionView, SegmentAdapter segmentAdapter) { super(sectionView); //noinspection unchecked distributiveSectionLayout = (DistributiveSectionLayout<SegmentData<D>>) sectionView; distributiveSectionLayout.setOrientation(LinearLayout.HORIZONTAL); distributiveSectionLayout.withAdapter(segmentAdapter); } @Override protected void onBind(Boolean willDistributeEvenly) { distributiveSectionLayout.distributeEvenly(willDistributeEvenly); } public DistributiveSectionLayout<SegmentData<D>> getDistributiveSectionLayout() { return distributiveSectionLayout; } } <file_sep>/segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/Configs.java package segmented_control.widget.custom.android.com.segmentedcontrol; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentDecoration; /** * Created by <NAME> on 9/7/2017. */ class Configs { static final int DEFAULT_COLUMN_COUNT = 2; boolean willDistributeEvenly; int columnCount; SegmentDecoration segmentDecoration = new SegmentDecoration(); static Configs getDefault() { Configs configs = new Configs(); configs.willDistributeEvenly = false; configs.columnCount = DEFAULT_COLUMN_COUNT; return configs; } } <file_sep>/segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/utils/Utils.java package segmented_control.widget.custom.android.com.segmentedcontrol.utils; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.support.annotation.IntRange; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; /** * Created by <NAME> on 9/8/2017. */ public class Utils { public static <T> T lazy(T nullable, T nonNull) { if (nullable == null) { nullable = nonNull; } return nullable; } /** * Utility method, use to define segment background type * * @param absolutePosition, Segment absolute position from {@link SegmentViewHolder#getAbsolutePosition()} * @param columnCount, from {@link SegmentViewHolder#getColumnCount()} * @param size, from {@link SegmentViewHolder#getCurrentSize()} * @return {@link SegmentBackgroundType} */ @SegmentBackgroundType public static int defineSegmentBackground(@IntRange(from = 0) int absolutePosition, @IntRange(from = 1) int columnCount, @IntRange(from = 1) int size) { // if only one item if (size == 1) { return SegmentBackgroundType.SINGLE_BG; } // if one column if (columnCount == 1) { // for first if (absolutePosition == 0) { return SegmentBackgroundType.TOP_SINGLE_BG; } // for last if (absolutePosition == size - 1) { return SegmentBackgroundType.BOTTOM_SINGLE_BG; } } // if not one column, but one row if (size <= columnCount) { if (absolutePosition == 0) { return SegmentBackgroundType.TOP_LEFT_SINGLE_BG; } if (absolutePosition == size - 1) { return SegmentBackgroundType.TOP_RIGHT_SINGLE_BG; } } // if not one column and multi row if (absolutePosition == 0) { return SegmentBackgroundType.TOP_LEFT_BG; } if (absolutePosition == columnCount - 1) { return SegmentBackgroundType.TOP_RIGHT_BG; } int notCompletedRowItemsCount = size % columnCount; int completeRowsItemsCount = size - notCompletedRowItemsCount; if (notCompletedRowItemsCount == 1 && absolutePosition == completeRowsItemsCount) { return SegmentBackgroundType.BOTTOM_SINGLE_BG; } if (notCompletedRowItemsCount == 0) { if (absolutePosition == size - columnCount) { return SegmentBackgroundType.BOTTOM_LEFT_BG; } if (absolutePosition == size - 1) { return SegmentBackgroundType.BOTTOM_RIGHT_BG; } } else if (notCompletedRowItemsCount > 0) { if (absolutePosition == size - notCompletedRowItemsCount) { return SegmentBackgroundType.BOTTOM_LEFT_BG; } if (absolutePosition == size - 1) { return SegmentBackgroundType.BOTTOM_RIGHT_BG; } } return SegmentBackgroundType.MIDDLE_BG; } /** * Use to define segment corner radius * * @param absolutePosition, Segment absolute position from {@link SegmentViewHolder#getAbsolutePosition()} * @param columnCount, from {@link SegmentViewHolder#getColumnCount()} * @param size, from {@link SegmentViewHolder#getCurrentSize()} * @param topLeftRadius, from {@link SegmentViewHolder#getTopLeftRadius()} * @param topRightRadius, from {@link SegmentViewHolder#getTopRightRadius()} ()} * @param bottomRightRadius, from {@link SegmentViewHolder#getBottomRightRadius()} * @param bottomLeftRadius, from {@link SegmentViewHolder#getBottomLeftRadius()} * @return, float[] corners radius, */ public static float[] defineRadiusForPosition(@IntRange(from = 0) int absolutePosition, @IntRange(from = 1) int columnCount, @IntRange(from = 1) int size, int topLeftRadius, int topRightRadius, int bottomRightRadius, int bottomLeftRadius) { @SegmentBackgroundType int bgType = defineSegmentBackground(absolutePosition, columnCount, size); switch (bgType) { case SegmentBackgroundType.BOTTOM_LEFT_BG: return createRadius(0, 0, 0, bottomLeftRadius); case SegmentBackgroundType.BOTTOM_RIGHT_BG: return createRadius(0, 0, bottomRightRadius, 0); case SegmentBackgroundType.BOTTOM_SINGLE_BG: return createRadius(0, 0, bottomRightRadius, bottomLeftRadius); case SegmentBackgroundType.MIDDLE_BG: return createRadius(0, 0, 0, 0); case SegmentBackgroundType.SINGLE_BG: return createRadius(topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius); case SegmentBackgroundType.TOP_LEFT_BG: return createRadius(topLeftRadius, 0, 0, 0); case SegmentBackgroundType.TOP_LEFT_SINGLE_BG: return createRadius(topLeftRadius, 0, 0, bottomLeftRadius); case SegmentBackgroundType.TOP_RIGHT_BG: return createRadius(0, topRightRadius, 0, 0); case SegmentBackgroundType.TOP_RIGHT_SINGLE_BG: return createRadius(0, topRightRadius, bottomRightRadius, 0); case SegmentBackgroundType.TOP_SINGLE_BG: return createRadius(topLeftRadius, topRightRadius, 0, 0); default: return createRadius(0, 0, 0, 0); } } public static float[] createRadius(float topLeft, float topRight, float bottomRight, float bottomLeft) { return new float[]{topLeft, topLeft, topRight, topRight, bottomRight, bottomRight, bottomLeft, bottomLeft}; } /** * * @param strokeWidth, stroke width * @param strokeColor, stroke color * @param argb, background color * @param radii, use {@link #defineRadiusForPosition(int, int, int, int, int, int, int)} method to define radii * @return background drawable */ public static Drawable getBackground(int strokeWidth, int strokeColor, int argb, float[] radii) { GradientDrawable drawable = new GradientDrawable(); drawable.setShape(GradientDrawable.RECTANGLE); drawable.setStroke(strokeWidth, strokeColor); drawable.setCornerRadii(radii); drawable.setColor(argb); return drawable; } }
e39fe0573b0114533ff27b61ea1ee31ca6168d8a
[ "Markdown", "Java", "Gradle" ]
11
Java
naseemakhtar994/SegmentedControl
0e73f9d51eb1c6f62c649fe75d7f1ef199ef8b32
1d622f6fc019b7a8d7d4826bda36a75c918fabf1
refs/heads/master
<repo_name>loopq/NumberPickerView<file_sep>/settings.gradle include ':app', ':numberpickerview2' <file_sep>/numberpickerview2/src/main/java/com/example/numberpickerview/widget/NumberPickerView.java package com.example.numberpickerview.widget; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.NumberPicker; import android.widget.PopupWindow; import com.example.numberpickerview.R; import com.example.numberpickerview.interfaces.ValueChooseListener; /** * Created by Administrator on 2016/10/9. */ public class NumberPickerView extends PopupWindow { private final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM ); FrameLayout dialogplus_content_container; // 遮罩层 private ViewGroup decorView;//activity的根View private ViewGroup rootView;//附加View 的 根View private int gravity = Gravity.BOTTOM; private NumberPicker numberPicker; private Context context; private ImageView cancel_action; private ImageView confirm_action; public NumberPickerView(final Activity context) { this.context = context; initViews(); } /** * 设置数字选择器最大值 * * @param maxValue */ public void setMaxValue(int maxValue) { numberPicker.setMaxValue(maxValue); } /** * 设置数字选择器最小值 * * @param minValue */ public void setMinValue(int minValue) { numberPicker.setMinValue(minValue); } protected void initViews() { LayoutInflater layoutInflater = LayoutInflater.from(context); decorView = (ViewGroup) ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content); rootView = (ViewGroup) layoutInflater.inflate(R.layout.add_popup_dialog, decorView, false); rootView.setLayoutParams(new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT )); numberPicker = (NumberPicker) rootView.findViewById(R.id.numberPicker); dialogplus_content_container = (FrameLayout) rootView.findViewById(R.id.dialogplus_content_container); cancel_action = (ImageView) rootView.findViewById(R.id.cancel_action); confirm_action = (ImageView) rootView.findViewById(R.id.confirm_action); dialogplus_content_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("zhuhu", "ssss"); decorView.removeView(rootView); } }); } /** * 显示popupWindow */ public void showPopupWindow() { decorView.addView(rootView); } /** * 设置取消窗口listener */ public void setOnCancelListener(final View.OnClickListener onCancelListener) { cancel_action.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCancelListener.onClick(v); decorView.removeView(rootView); } }); } /** * 设置确定取值listener */ public void setOnValueChooseListener(final ValueChooseListener listener) { confirm_action.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { decorView.removeView(rootView); listener.onValueChoose(numberPicker.getValue()); } }); } } <file_sep>/README.md # NumberPickerView # Code commit
3436d19fdb7c475b28137b08d17860d55baef62c
[ "Markdown", "Java", "Gradle" ]
3
Gradle
loopq/NumberPickerView
82013e49b92f05bb5d8355e6a732a64c10f9f915
9ec327cc60ef7450ef7fd34db3077711ee2567d3
refs/heads/master
<file_sep>package andreotticloud; import java.awt.Color; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JSpinner; /** * * @author <NAME> */ public final class JanelaCor extends javax.swing.JFrame { private final String corValida = "^#?[A-Fa-f0-9]+$"; private static String cores = "#A9A9A9,#808080,#696969,#000000", corFundo = "#ffffff",cor1Def = "#000000"; private static String cor1, cor2, cor3, cor4, corTemp1, corTemp2, corTemp3, corTemp4, corTempFundo; private static final Color CORDEFAULT = new Color(214,217,223); private static int qtdCoresAnt; public static boolean zerarInterface; /** * Creates new form Color * @param openCloud * @param wordCram */ public JanelaCor(boolean openCloud, boolean wordCram) { initComponents(); //cores que irão ser definidas após clicar em "OK" corTemp1 = corTemp2 = corTemp3 = corTemp4 = corTempFundo = null; //remover entrada do usuário pelo teclado no controle giratório JComponent editor = jSpinnerQtdCor.getEditor(); ((JSpinner.DefaultEditor)editor).getTextField().setFocusable(false); //quando muda-se a técnica as cores são reinicializadas if(zerarInterface){ qtdCoresAnt = 4; cor1 = cor2 = cor3 = cor4 = null; corFundo = "#ffffff"; zerarInterface=false; } //função que inicia os elementos da interface conforme a técnica selecionada iniciarConformeTecnica(openCloud, wordCram); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jPanelFundo = new javax.swing.JPanel(); jTextCorFundo = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel2 = new javax.swing.JLabel(); jPanelCor1 = new javax.swing.JPanel(); jPanelCor2 = new javax.swing.JPanel(); jTextCor2 = new javax.swing.JTextField(); jTextCor3 = new javax.swing.JTextField(); jPanelCor3 = new javax.swing.JPanel(); jTextCor4 = new javax.swing.JTextField(); jPanelCor4 = new javax.swing.JPanel(); jSeparator2 = new javax.swing.JSeparator(); jLabel3 = new javax.swing.JLabel(); jRadioButtonTC = new javax.swing.JRadioButton(); jRadioButtonTR = new javax.swing.JRadioButton(); jRadioButtonTG = new javax.swing.JRadioButton(); jRadioButtonTB = new javax.swing.JRadioButton(); jSpinnerQtdCor = new javax.swing.JSpinner(); jTextCor1 = new javax.swing.JTextField(); jButtonCancelar = new javax.swing.JButton(); jButtonOk = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jPanelFundo.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); javax.swing.GroupLayout jPanelFundoLayout = new javax.swing.GroupLayout(jPanelFundo); jPanelFundo.setLayout(jPanelFundoLayout); jPanelFundoLayout.setHorizontalGroup( jPanelFundoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 96, Short.MAX_VALUE) ); jPanelFundoLayout.setVerticalGroup( jPanelFundoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 104, Short.MAX_VALUE) ); jTextCorFundo.addCaretListener(new javax.swing.event.CaretListener() { public void caretUpdate(javax.swing.event.CaretEvent evt) { jTextCorFundoCaretUpdate(evt); } }); jLabel1.setText("Cor do fundo"); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); jLabel2.setText("Cor das palavras"); jPanelCor1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); javax.swing.GroupLayout jPanelCor1Layout = new javax.swing.GroupLayout(jPanelCor1); jPanelCor1.setLayout(jPanelCor1Layout); jPanelCor1Layout.setHorizontalGroup( jPanelCor1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanelCor1Layout.setVerticalGroup( jPanelCor1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 104, Short.MAX_VALUE) ); jPanelCor2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); javax.swing.GroupLayout jPanelCor2Layout = new javax.swing.GroupLayout(jPanelCor2); jPanelCor2.setLayout(jPanelCor2Layout); jPanelCor2Layout.setHorizontalGroup( jPanelCor2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 96, Short.MAX_VALUE) ); jPanelCor2Layout.setVerticalGroup( jPanelCor2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 104, Short.MAX_VALUE) ); jTextCor2.addCaretListener(new javax.swing.event.CaretListener() { public void caretUpdate(javax.swing.event.CaretEvent evt) { jTextCor2CaretUpdate(evt); } }); jTextCor3.addCaretListener(new javax.swing.event.CaretListener() { public void caretUpdate(javax.swing.event.CaretEvent evt) { jTextCor3CaretUpdate(evt); } }); jPanelCor3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); javax.swing.GroupLayout jPanelCor3Layout = new javax.swing.GroupLayout(jPanelCor3); jPanelCor3.setLayout(jPanelCor3Layout); jPanelCor3Layout.setHorizontalGroup( jPanelCor3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 96, Short.MAX_VALUE) ); jPanelCor3Layout.setVerticalGroup( jPanelCor3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 104, Short.MAX_VALUE) ); jTextCor4.addCaretListener(new javax.swing.event.CaretListener() { public void caretUpdate(javax.swing.event.CaretEvent evt) { jTextCor4CaretUpdate(evt); } }); jPanelCor4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); javax.swing.GroupLayout jPanelCor4Layout = new javax.swing.GroupLayout(jPanelCor4); jPanelCor4.setLayout(jPanelCor4Layout); jPanelCor4Layout.setHorizontalGroup( jPanelCor4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 96, Short.MAX_VALUE) ); jPanelCor4Layout.setVerticalGroup( jPanelCor4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 104, Short.MAX_VALUE) ); jLabel3.setText("Modelos"); buttonGroup1.add(jRadioButtonTC); jRadioButtonTC.setText("Tons de Cinza"); jRadioButtonTC.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jRadioButtonTCItemStateChanged(evt); } }); jRadioButtonTC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonTCActionPerformed(evt); } }); buttonGroup1.add(jRadioButtonTR); jRadioButtonTR.setText("Tons de Vermelho"); jRadioButtonTR.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonTRActionPerformed(evt); } }); buttonGroup1.add(jRadioButtonTG); jRadioButtonTG.setText("Tons de Verde"); jRadioButtonTG.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonTGActionPerformed(evt); } }); buttonGroup1.add(jRadioButtonTB); jRadioButtonTB.setText("Tons de Azul"); jRadioButtonTB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonTBActionPerformed(evt); } }); jSpinnerQtdCor.setEnabled(false); jSpinnerQtdCor.setValue(4); jSpinnerQtdCor.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { jSpinnerQtdCorStateChanged(evt); } }); jTextCor1.addCaretListener(new javax.swing.event.CaretListener() { public void caretUpdate(javax.swing.event.CaretEvent evt) { jTextCor1CaretUpdate(evt); } }); jButtonCancelar.setText("Cancelar"); jButtonCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCancelarActionPerformed(evt); } }); jButtonOk.setText("OK"); jButtonOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonOkActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButtonTG, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButtonTB, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(159, 159, 159) .addComponent(jButtonOk, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonCancelar)) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButtonTR, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButtonTC, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelFundo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextCorFundo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSpinnerQtdCor, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanelCor1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextCor1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelCor2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextCor2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelCor3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextCor3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelCor4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextCor4, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 598, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(13, 13, 13) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jSpinnerQtdCor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jPanelFundo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextCorFundo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelCor4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanelCor3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanelCor2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanelCor1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextCor3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextCor4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextCor2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jTextCor1)))) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jRadioButtonTC) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButtonTR) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButtonTG, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonCancelar) .addComponent(jButtonOk)) .addComponent(jRadioButtonTB)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents public void iniciarConformeTecnica(boolean openCloud, boolean wordCram){ //verifica se é a técnica "OpenCloud" if(openCloud){ //pra essa técnica é permitida apenas uma cor qtdCoresAnt = 1; jSpinnerQtdCor.setValue(1); jPanelCor2.setVisible(false); jPanelCor3.setVisible(false); jPanelCor4.setVisible(false); jTextCor2.setVisible(false); jTextCor3.setVisible(false); jTextCor4.setVisible(false); //altera o texto dos botões de "modelos de cor" jRadioButtonTC.setText("Preto"); jRadioButtonTB.setText("Azul"); jRadioButtonTG.setText("Verde"); jRadioButtonTR.setText("Vermelho"); } //caso seja a técnica "WordCram" else if(wordCram) //ativa a opção de adicionar mais cores jSpinnerQtdCor.setEnabled(true); //verifica se o usuário já havia definido uma cor if(cor1 != null){ jSpinnerQtdCor.setValue(qtdCoresAnt); //seta a cor do fundo e a primeira cor jPanelFundo.setBackground(java.awt.Color.decode(corFundo)); jTextCorFundo.setText(corFundo); jPanelCor1.setBackground(java.awt.Color.decode(cor1)); jTextCor1.setText(cor1); //deixa as demais cores não visíveis jPanelCor2.setVisible(false); jPanelCor3.setVisible(false); jPanelCor4.setVisible(false); jTextCor2.setVisible(false); jTextCor3.setVisible(false); jTextCor4.setVisible(false); //faz as verificações de quantidade de cores que o usuário havia selecionado if(qtdCoresAnt >= 2){ jTextCor2.setVisible(true); jPanelCor2.setVisible(true); jPanelCor2.setBackground(java.awt.Color.decode(cor2)); jTextCor2.setText(cor2); } if(qtdCoresAnt >= 3){ jPanelCor3.setVisible(true); jTextCor3.setVisible(true); jPanelCor3.setBackground(java.awt.Color.decode(cor3)); jTextCor3.setText(cor3); } if(qtdCoresAnt == 4){ jTextCor4.setVisible(true); jPanelCor4.setVisible(true); jPanelCor4.setBackground(java.awt.Color.decode(cor4)); jTextCor4.setText(cor4); } } //se o usuário não havia definido uma cor else //setar cores padrões jRadioButtonTC.setSelected(true); } private void jTextCorFundoCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextCorFundoCaretUpdate //coloca o '#' que inicia uma cor hexadecimal String corFinal = "#"; String cor = jTextCorFundo.getText(); //verifica se existe mais que um caracter no texto que define a cor if(cor.length()>0){ //verifica se o caracter inicial '#' não está presente if(!cor.substring(0, 1).equals("#")){ //adiciona o caracter '#' no inicio corFinal = corFinal.concat(cor); } //se já estiver presente o caracter '#" else{ //somente o adiciona a cor final corFinal = cor; } } //verifica se é uma cor válida if(isCor(corFinal) && corFinal.length()<8){ //colore o jPanel na interface jPanelFundo.setBackground(java.awt.Color.decode(corFinal)); //define a cor temporária que será confirmada no botão "ok" corTempFundo = corFinal; } //se não for uma cor valida else{ //colore o jPanel com uma cor padrão jPanelFundo.setBackground(CORDEFAULT); corTempFundo = null; } }//GEN-LAST:event_jTextCorFundoCaretUpdate private void jTextCor2CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextCor2CaretUpdate //coloca o '#' que inicia uma cor hexadecimal String corFinal = "#"; String cor = jTextCor2.getText(); //verifica se existe mais que um caracter no texto que define a cor if(cor.length()>0){ //verifica se o caracter inicial '#' não está presente if(!cor.substring(0, 1).equals("#")){ //adiciona o caracter '#' no inicio corFinal = corFinal.concat(cor); } //se já estiver presente o caracter '#" else{ //somente o adiciona a cor final corFinal = cor; } } //verifica se é uma cor válida if(isCor(corFinal) && corFinal.length()<8){ //colore o jPanel na interface jPanelCor2.setBackground(java.awt.Color.decode(corFinal)); //define a cor temporária que será confirmada no botão "ok" corTemp2 = corFinal; } //se não for uma cor valida else{ //colore o jPanel com uma cor padrão jPanelCor2.setBackground(CORDEFAULT); corTemp2 = null; } }//GEN-LAST:event_jTextCor2CaretUpdate private void jTextCor3CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextCor3CaretUpdate //coloca o '#' que inicia uma cor hexadecimal String corFinal = "#"; String cor = jTextCor3.getText(); //verifica se existe mais que um caracter no texto que define a cor if(cor.length()>0){ //verifica se o caracter inicial '#' não está presente if(!cor.substring(0, 1).equals("#")){ //adiciona o caracter '#' no inicio corFinal = corFinal.concat(cor); } //se já estiver presente o caracter '#" else{ //somente o adiciona a cor final corFinal = cor; } } //verifica se é uma cor válida if(isCor(corFinal) && corFinal.length()<8){ //colore o jPanel na interface jPanelCor3.setBackground(java.awt.Color.decode(corFinal)); //define a cor temporária que será confirmada no botão "ok" corTemp3 = corFinal; } //se não for uma cor valida else{ //colore o jPanel com uma cor padrão jPanelCor3.setBackground(CORDEFAULT); corTemp3 = null; } }//GEN-LAST:event_jTextCor3CaretUpdate private void jTextCor4CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextCor4CaretUpdate //coloca o '#' que inicia uma cor hexadecimal String corFinal = "#"; String cor = jTextCor4.getText(); //verifica se existe mais que um caracter no texto que define a cor if(cor.length()>0){ //verifica se o caracter inicial '#' não está presente if(!cor.substring(0, 1).equals("#")){ //adiciona o caracter '#' no inicio corFinal = corFinal.concat(cor); } //se já estiver presente o caracter '#" else{ //somente o adiciona a cor final corFinal = cor; } } //verifica se é uma cor válida if(isCor(corFinal) && corFinal.length()<8){ //colore o jPanel na interface jPanelCor4.setBackground(java.awt.Color.decode(corFinal)); //define a cor temporária que será confirmada no botão "ok" corTemp4 = corFinal; } //se não for uma cor valida else{ //colore o jPanel com uma cor padrão jPanelCor4.setBackground(CORDEFAULT); corTemp4 = null; } }//GEN-LAST:event_jTextCor4CaretUpdate private void jRadioButtonTCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonTCActionPerformed //seta as cores cinzas jTextCorFundo.setText("#ffffff"); jTextCor1.setText("#000000"); jTextCor2.setText("#696969"); jTextCor3.setText("#808080"); jTextCor4.setText("#A9A9A9"); }//GEN-LAST:event_jRadioButtonTCActionPerformed private void jRadioButtonTRActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonTRActionPerformed //seta as cores vermelhas jTextCorFundo.setText("#ffffff"); jTextCor1.setText("#FF0000"); jTextCor2.setText("#F00000"); jTextCor3.setText("#E00000"); jTextCor4.setText("#D00000"); }//GEN-LAST:event_jRadioButtonTRActionPerformed private void jRadioButtonTGActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonTGActionPerformed //seta as cores verdes jTextCorFundo.setText("#ffffff"); jTextCor1.setText("#00FF00"); jTextCor2.setText("#228B22"); jTextCor3.setText("#008000"); jTextCor4.setText("#006400"); }//GEN-LAST:event_jRadioButtonTGActionPerformed private void jRadioButtonTBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonTBActionPerformed //seta as cores azuis jTextCorFundo.setText("#ffffff"); jTextCor1.setText("#0000FF"); jTextCor2.setText("#0000CD"); jTextCor3.setText("#00008B"); jTextCor4.setText("#000080"); }//GEN-LAST:event_jRadioButtonTBActionPerformed private void jSpinnerQtdCorStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSpinnerQtdCorStateChanged //impedir que o usuário ultrapasse os limites de cores disponíveis if((int) jSpinnerQtdCor.getValue()>4){ jSpinnerQtdCor.setValue(4); } if((int) jSpinnerQtdCor.getValue()<1){ jSpinnerQtdCor.setValue(1); } //verifica a qtd selecionada no controle de cores e define a interface switch ((int) jSpinnerQtdCor.getValue()) { case 4: jPanelCor1.setVisible(true); jTextCor1.setVisible(true); jPanelCor2.setVisible(true); jTextCor2.setVisible(true); jPanelCor3.setVisible(true); jTextCor3.setVisible(true); jPanelCor4.setVisible(true); jTextCor4.setVisible(true); break; case 3: jPanelCor1.setVisible(true); jTextCor1.setVisible(true); jPanelCor2.setVisible(true); jTextCor2.setVisible(true); jPanelCor3.setVisible(true); jTextCor3.setVisible(true); jPanelCor4.setVisible(false); jTextCor4.setVisible(false); break; case 2: jPanelCor1.setVisible(true); jTextCor1.setVisible(true); jPanelCor2.setVisible(true); jTextCor2.setVisible(true); jPanelCor3.setVisible(false); jTextCor3.setVisible(false); jPanelCor4.setVisible(false); jTextCor4.setVisible(false); break; case 1: jPanelCor1.setVisible(true); jTextCor1.setVisible(true); jPanelCor2.setVisible(false); jTextCor2.setVisible(false); jPanelCor3.setVisible(false); jTextCor3.setVisible(false); jPanelCor4.setVisible(false); jTextCor4.setVisible(false); break; default: break; } }//GEN-LAST:event_jSpinnerQtdCorStateChanged private void jTextCor1CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextCor1CaretUpdate //coloca o '#' que inicia uma cor hexadecimal String corFinal = "#"; String cor = jTextCor1.getText(); //verifica se existe mais que um caracter no texto que define a cor if(cor.length()>0){ //verifica se o caracter inicial '#' não está presente if(!cor.substring(0, 1).equals("#")){ //adiciona o caracter '#' no inicio corFinal = corFinal.concat(cor); } //se já estiver presente o caracter '#" else{ //somente o adiciona a cor final corFinal = cor; } } //verifica se é uma cor válida if(isCor(corFinal) && corFinal.length()<8){ //colore o jPanel na interface jPanelCor1.setBackground(java.awt.Color.decode(corFinal)); //define a cor temporária que será confirmada no botão "ok" corTemp1 = corFinal; } //se não for uma cor valida else{ //colore o jPanel com uma cor padrão jPanelCor1.setBackground(CORDEFAULT); corTemp1 = null; } }//GEN-LAST:event_jTextCor1CaretUpdate private void jButtonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOkActionPerformed //armazena a quantidade de cores definida para iniciar a próxima instância JanelaCor.qtdCoresAnt = (int) jSpinnerQtdCor.getValue(); //verifica se alguma cor não foi definida corretamente if((corTemp1 == null && jPanelCor1.isVisible()) || (corTemp2 == null && jPanelCor2.isVisible()) || (corTemp3 == null && jPanelCor3.isVisible()) || (corTemp4 == null && jPanelCor4.isVisible()) || (corTempFundo == null && jPanelFundo.isVisible())){ JOptionPane.showMessageDialog(null, "Defina todas as corres corretamente", "Erro de Cor", JOptionPane.ERROR_MESSAGE); } else{ cor1 = corTemp1; corFundo = corTempFundo; cores = ""; cores = cores.concat(cor1); //verifica quais cores foram selecionadas na interface //a primeira cor e a cor do fundo não são verificadas //pois sempre devem ser selecionadas if (jPanelCor2.isVisible()){ cor2 = corTemp2; cores = cores.concat(",").concat(cor2); } if (jPanelCor3.isVisible()){ cor3 = corTemp3; cores = cores.concat(",").concat(cor3); } if (jPanelCor4.isVisible()){ cor4 = corTemp4; cores = cores.concat(",").concat(cor4); } dispose(); } }//GEN-LAST:event_jButtonOkActionPerformed private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed dispose(); }//GEN-LAST:event_jButtonCancelarActionPerformed private void jRadioButtonTCItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButtonTCItemStateChanged //seta as cores cinzas jTextCorFundo.setText("#ffffff"); jTextCor1.setText("#000000"); jTextCor2.setText("#696969"); jTextCor3.setText("#808080"); jTextCor4.setText("#A9A9A9"); }//GEN-LAST:event_jRadioButtonTCItemStateChanged public static String getCores() { return cores; } public static String getCorFundo() { return corFundo; } public static String getCor1() { if(cor1 != null) return cor1; else return cor1Def; } public boolean isCor(String cor){ return cor.matches(corValida); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButtonCancelar; private javax.swing.JButton jButtonOk; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanelCor1; private javax.swing.JPanel jPanelCor2; private javax.swing.JPanel jPanelCor3; private javax.swing.JPanel jPanelCor4; private javax.swing.JPanel jPanelFundo; private javax.swing.JRadioButton jRadioButtonTB; private javax.swing.JRadioButton jRadioButtonTC; private javax.swing.JRadioButton jRadioButtonTG; private javax.swing.JRadioButton jRadioButtonTR; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSpinner jSpinnerQtdCor; private javax.swing.JTextField jTextCor1; private javax.swing.JTextField jTextCor2; private javax.swing.JTextField jTextCor3; private javax.swing.JTextField jTextCor4; private javax.swing.JTextField jTextCorFundo; // End of variables declaration//GEN-END:variables } <file_sep>package wordCram; import andreotticloud.Representacao; import wordcram.Word; import java.util.ArrayList; import java.util.Iterator; import java.util.TreeSet; public class WordsReader { public static final String SEPARATOR = ","; TreeSet<Representacao> vetFreq; public WordsReader(TreeSet<Representacao> vetFreq){ this.vetFreq = vetFreq; } public Word[] getWords(){ ArrayList<Word> words = new ArrayList<>(); //percorre todo o vetor de frequência Iterator<Representacao> it = vetFreq.iterator(); Representacao rp; while(it.hasNext()){ //pega o próximo rp = it.next(); //adiciona a palavra e sua freqência Word word = new Word(rp.getPalavra(),(float)(rp.getFrequencia())); words.add(word); } return words.toArray(new Word[words.size()]); } } <file_sep>package andreotticloud; import java.io.IOException; import java.nio.charset.StandardCharsets; import static java.nio.file.Files.readAllLines; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author <NAME> */ public class StopWords { private static ArrayList<String> stop = new ArrayList<>();; private static ArrayList<String> palavrasRejeitadas = new ArrayList<>();; public StopWords() { } public static void iniciarStopWords(String nomeArq){ List<String> linhas; try { linhas = readAllLines(Paths.get("stop/"+nomeArq), StandardCharsets.UTF_8); for(int i=0; i<linhas.size(); i++){ stop.add(linhas.get(i)); } } catch (IOException ex) { Logger.getLogger(StopWords.class.getName()).log(Level.SEVERE, null, ex); } } public static ArrayList<String> getStop() { return stop; } public static void setStop(ArrayList<String> stop) { StopWords.stop = stop; } public static ArrayList<String> getPalavrasRejeitadas() { return palavrasRejeitadas; } public static void setPalavrasRejeitadas(ArrayList<String> palavrasRejeitadas) { StopWords.palavrasRejeitadas = palavrasRejeitadas; } } <file_sep>package andreotticloud; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; /** * * @author <NAME> */ public class JanelaPalavrasRem extends javax.swing.JFrame { public JanelaPalavrasRem() { initComponents(); //busca o vetor de palavras que serão desconsideradas para preencher a tabela ArrayList<String> palavras = StopWords.getPalavrasRejeitadas(); int qtdPalavras = palavras.size(); //preenche a tabela com as palavras que estão adicionadas até o momento DefaultTableModel modelo = (DefaultTableModel) getTabela().getModel(); for(int i=0; i<qtdPalavras; i++){ modelo.addRow(new String[]{palavras.get(i)}); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTablePalavras = new javax.swing.JTable(); jTextPalavra = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jButtonInserir = new javax.swing.JButton(); jButtonAplicar = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jButtonCancelar = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenuArquivo = new javax.swing.JMenu(); jMenuItemAbrir = new javax.swing.JMenuItem(); jMenuItemSalvar = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); jTablePalavras.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Lista de palavras que serão desconsideradas" } ) { boolean[] canEdit = new boolean [] { false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTablePalavras.getTableHeader().setReorderingAllowed(false); jTablePalavras.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTablePalavrasKeyPressed(evt); } }); jScrollPane1.setViewportView(jTablePalavras); if (jTablePalavras.getColumnModel().getColumnCount() > 0) { jTablePalavras.getColumnModel().getColumn(0).setResizable(false); } jTextPalavra.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextPalavraKeyPressed(evt); } }); jLabel1.setText("Palavra:"); jButtonInserir.setText("Inserir"); jButtonInserir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonInserirActionPerformed(evt); } }); jButtonAplicar.setText("Aplicar"); jButtonAplicar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAplicarActionPerformed(evt); } }); jButton1.setText("Limpar Lista"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButtonCancelar.setText("Cancelar"); jButtonCancelar.setMaximumSize(new java.awt.Dimension(54, 25)); jButtonCancelar.setMinimumSize(new java.awt.Dimension(54, 25)); jButtonCancelar.setPreferredSize(new java.awt.Dimension(54, 25)); jButtonCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCancelarActionPerformed(evt); } }); jMenuArquivo.setText("Arquivo"); jMenuItemAbrir.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK)); jMenuItemAbrir.setText("Abrir (.txt)"); jMenuItemAbrir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemAbrirActionPerformed(evt); } }); jMenuArquivo.add(jMenuItemAbrir); jMenuItemSalvar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK)); jMenuItemSalvar.setText("Salvar (.txt)"); jMenuItemSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemSalvarActionPerformed(evt); } }); jMenuArquivo.add(jMenuItemSalvar); jMenuBar1.add(jMenuArquivo); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(2, 2, 2) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jTextPalavra) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonAplicar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonInserir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(4, 4, 4) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextPalavra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonInserir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonAplicar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTablePalavrasKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTablePalavrasKeyPressed //verifica se foi pressionado o botão "del" para excluir uma linha if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DELETE){ //verifica qual linha está com o foco int linha = getTabela().getSelectedRow(); //caso não esteja selecionada nenhuma linha o método retorna "-1" if(linha != -1){ //remove a linha selecionada DefaultTableModel modelo = (DefaultTableModel) getTabela().getModel(); modelo.removeRow(linha); } } }//GEN-LAST:event_jTablePalavrasKeyPressed private void jButtonInserirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInserirActionPerformed inserirElemento(); }//GEN-LAST:event_jButtonInserirActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed limparLinhas(); }//GEN-LAST:event_jButton1ActionPerformed private void jButtonAplicarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAplicarActionPerformed //armazena a qtd de linhas da tabela int qtdLinhas = getTabela().getRowCount(); //array que irá armazenar os elementos da linha ArrayList<String> palavras = new ArrayList<>(); //adiciona todos os elementos das linhas no array DefaultTableModel modelo = (DefaultTableModel) getTabela().getModel(); for(int i=0; i<qtdLinhas; i++){ palavras.add(modelo.getValueAt(i, 0).toString().toLowerCase()); } //seta em "StopWords" nova lista de palavras que devem ser rejeitadas StopWords.setPalavrasRejeitadas(palavras); //fecha a janela dispose(); }//GEN-LAST:event_jButtonAplicarActionPerformed private void jTextPalavraKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextPalavraKeyPressed //verifica se foi pressionado o botão "enter" para inserir um elemento if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER){ inserirElemento(); } }//GEN-LAST:event_jTextPalavraKeyPressed private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed dispose(); }//GEN-LAST:event_jButtonCancelarActionPerformed private void jMenuItemSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSalvarActionPerformed salvarArquivoTexto(); }//GEN-LAST:event_jMenuItemSalvarActionPerformed private void jMenuItemAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemAbrirActionPerformed selecionarArquivoTexto(); }//GEN-LAST:event_jMenuItemAbrirActionPerformed public void salvarArquivoTexto(){ FileWriter arq; if(getTabela().getRowCount() > 0){ //abrir/salvar arquivos JFileChooser jfc = new JFileChooser(); //somente arquivos .txt final FileNameExtensionFilter filter = new FileNameExtensionFilter("Somente arquivos TXT","txt"); //aplica o filtro .txt jfc.setFileFilter(filter); //somente abre arquivos jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); //remove a opção de exibir outros formatos de arquivos jfc.setAcceptAllFileFilterUsed(false); if(jfc.showSaveDialog(jMenuArquivo) == JFileChooser.APPROVE_OPTION){ File f = jfc.getSelectedFile(); try { if(f.getAbsolutePath().endsWith(".txt")){ //abre o arquivo pra gravação arq = new FileWriter(f.getAbsolutePath()); PrintWriter gravarArq = new PrintWriter(arq); //armazena a quandidade de linhas que a tabela possui int qtdLinhas = getTabela().getRowCount(); //adiciona todos os elementos das linhas no arquivo DefaultTableModel modelo = (DefaultTableModel) getTabela().getModel(); for(int i=0; i<qtdLinhas; i++){ gravarArq.printf(modelo.getValueAt(i, 0).toString()+"\n"); } //fechar arquivo arq.close(); JOptionPane.showMessageDialog(null,"Arquivo de Remoção salvo em: "+f.getAbsolutePath(),"Alerta",JOptionPane.INFORMATION_MESSAGE); } else{ //abre o arquivo pra gravação arq = new FileWriter(f.getAbsolutePath()+".txt"); PrintWriter gravarArq = new PrintWriter(arq); //armazena a quandidade de linhas que a tabela possui int qtdLinhas = getTabela().getRowCount(); //adiciona todos os elementos das linhas no arquivo DefaultTableModel modelo = (DefaultTableModel) getTabela().getModel(); for(int i=0; i<qtdLinhas; i++){ gravarArq.printf(modelo.getValueAt(i, 0).toString()+"\n"); } //fechar arquivo arq.close(); JOptionPane.showMessageDialog(null,"Arquivo de Remoção salvo em: "+f.getAbsolutePath()+".txt","Alerta",JOptionPane.INFORMATION_MESSAGE); } }catch (IOException ex) { Logger.getLogger(JanelaPalavrasRem.class.getName()).log(Level.SEVERE, null, ex); } } } else JOptionPane.showMessageDialog(rootPane, "Não há nenhuma palavra inserida na lista","Erro", JOptionPane.ERROR_MESSAGE); } public void selecionarArquivoTexto(){ String local; String texto = "", token; //abrir arquivos JFileChooser jfc = new JFileChooser(); //habilida a seleção de vários arquivos jfc.setMultiSelectionEnabled(true); //somente arquivos .txt final FileNameExtensionFilter filter = new FileNameExtensionFilter("Somente arquivos TXT","txt"); //aplica o filtro .txt jfc.setFileFilter(filter); //somente abre arquivos jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); //remove a opção de exibir outros formatos de arquivos jfc.setAcceptAllFileFilterUsed(false); if(jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){ //armazenar o arquivo selecionado File f = jfc.getSelectedFile(); //armazena o local do arquivo local = f.getAbsolutePath(); //ler o arquivo texto try { texto = readFile(local, StandardCharsets.UTF_8); } catch (IOException ex) { System.err.printf("Arquivo não localizado: %s.\n", ex.getMessage()); } //separa em tokens todo o texto StringTokenizer st = new StringTokenizer(texto); if(st.hasMoreTokens()){ while(st.hasMoreTokens()){ //lê a pŕoxima palavra do texto token = st.nextToken(); //adiciona mais uma linha DefaultTableModel modelo = (DefaultTableModel) getTabela().getModel(); modelo.addRow(new String[]{token}); } } else JOptionPane.showMessageDialog(rootPane, "Não há nenhuma palavra no arquivo selecionado","Erro", JOptionPane.ERROR_MESSAGE); } } private static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return encoding.decode(ByteBuffer.wrap(encoded)).toString(); } public void inserirElemento(){ //verifica se existe algum texto na caixa de inserção de texto if(jTextPalavra.getText().trim().equals("")){ JOptionPane.showMessageDialog(rootPane, "Insira uma palavra na caixa de texto","Erro", JOptionPane.ERROR_MESSAGE); } else{ //insere o texto e remove o que está na caixa de inserção de texto DefaultTableModel modelo = (DefaultTableModel) getTabela().getModel(); modelo.addRow(new String[]{jTextPalavra.getText().trim()}); jTextPalavra.setText(""); } } public final JTable getTabela() { return jTablePalavras; } private void limparLinhas() { //remove todas as linhas da tabela DefaultTableModel modelo = (DefaultTableModel) getTabela().getModel(); int qtdLinhas = getTabela().getRowCount(); for(int i=0; i < qtdLinhas; i++) modelo.removeRow(0); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButtonAplicar; private javax.swing.JButton jButtonCancelar; private javax.swing.JButton jButtonInserir; private javax.swing.JLabel jLabel1; private javax.swing.JMenu jMenuArquivo; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItemAbrir; private javax.swing.JMenuItem jMenuItemSalvar; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTablePalavras; private javax.swing.JTextField jTextPalavra; // End of variables declaration//GEN-END:variables } <file_sep>package andreotticloud; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.TreeSet; import javax.swing.JFrame; import javax.swing.JOptionPane; import openCloud.OpenCloud; import wordCram.TagCloud; /** * * @author <NAME> */ public class Processamento { public static ArrayList<Texto> documentos; private static File shape; private static int tamMinTxt = 8, tamMaxTxt = 38, quantidadeMaxTermos = 0; private int docsPreProcess = 0; private boolean executarBiblio = false; private static volatile int qtdDoc = -1; public static Processamento getInstance(){ return ProcessamentoHolder.INSTANCE; } private static class ProcessamentoHolder{ private static final Processamento INSTANCE = new Processamento(); } public synchronized boolean execute(int idFile, String texto, boolean remvNum, boolean removPP, boolean removPI, int opCaractere, boolean wordCram, boolean openCloud, boolean uniaoHifen) throws IOException, InterruptedException{ boolean remvStop = true; //adicionar as stopWords if (removPP && removPI){ StopWords.setStop(new ArrayList<>()); StopWords.iniciarStopWords("portuguese"); StopWords.iniciarStopWords("english"); } else if(removPP){ StopWords st = new StopWords(); StopWords.setStop(new ArrayList<>()); StopWords.iniciarStopWords("portuguese"); } else if(removPI){ StopWords.setStop(new ArrayList<>()); StopWords.iniciarStopWords("english"); } else{ remvStop = false; StopWords.setStop(new ArrayList<>()); } if(documentos == null){ documentos = new ArrayList<>(); } Texto t = new Texto(texto); if(uniaoHifen){ JanelaPrincipal.setTextSaida("Processando união em caso de hífen em quebra de linha..."); //une as palavras quebradas texto = t.unirPalavrasCortadas(texto); JanelaPrincipal.setTextSaida("Quantidade de palavras quebradas com hífen encontradas: "+t.getTotalPalavrasHifen()); } JanelaPrincipal.setTextSaida("Processando tokenizar..."); //faz a tokenização de acordo com a preferência de remoção do usuário t.tokenizar(texto, remvNum, remvStop, opCaractere); JanelaPrincipal.setTextSaida("Processando vetor de frequências..."); //criar vetor de freqências t.criarVetorDeFrenquencia(opCaractere); JanelaPrincipal.setTextSaida("Removendo termos com baixa frequência..."); JanelaPrincipal.setTextSaida("Quantidade de termos antes da remoção: "+t.getVetorFreq().size()); //remover palavras que possuem pouca frequência t.removerBaixaFrequencia(Processamento.getQuantidadeMaxTermos()); JanelaPrincipal.setTextSaida("Quantidade de termos depois da remoção: "+t.getVetorFreq().size()); //definir um "id" único para o documento t.setIdFile(idFile); //adiciona na estrutura que armazena todos os textos documentos.add(t); //incrementa a quantidade de arquivos já PRÉ-processados docsPreProcess++; if(!JanelaPrincipal.variosArq){ JanelaPrincipal.setTextSaida("Criando TagCloud..."); } //verifica se já fez todo o PRÉ-pocessamento if(JanelaPrincipal.qtdArquivosSelecionados == docsPreProcess){ executarBiblio = true; JanelaPrincipal.setTextSaida("Criando TagCloud..."); } //verifica se será gerada apenas para um arquivo if(!JanelaPrincipal.variosArq){ //gera a WordCram if(wordCram){ docsPreProcess = 0; TagCloud wc = new TagCloud(); Thread tr = new Thread(wc); tr.start(); tr.sleep(500); wc = null; System.gc(); Runtime.getRuntime().freeMemory(); } //gera a OpenCloud if(openCloud){ docsPreProcess = 0; OpenCloud op = new OpenCloud(opCaractere); op.initUI(); } } else{ //espera todo o pré-processamento antes de usar a API if(JanelaPrincipal.metodoVariosArq == 0 && executarBiblio){ executarBiblio = false; docsPreProcess = 0; //gera uma TagCloud para cada documento for(int i=0; i<JanelaPrincipal.qtdArquivosSelecionados; i++){ //gera a WordCram if(wordCram){ TagCloud wc = new TagCloud(); Thread tr = new Thread(wc); tr.start(); tr.sleep(500); wc = null; System.gc(); Runtime.getRuntime().freeMemory(); } else //gera a OpenCloud if(openCloud){ OpenCloud op = new OpenCloud(opCaractere); op.initUI(); } } } else if(JanelaPrincipal.metodoVariosArq == 1){ //gera a WordCram if(wordCram){ TagCloud wc = new TagCloud(); Thread tr = new Thread(wc); tr.start(); tr.sleep(500); wc = null; System.gc(); Runtime.getRuntime().freeMemory(); } //gera a OpenCloud else if(openCloud){ OpenCloud op = new OpenCloud(opCaractere); op.initUI(); } } } return true; } public static void gravarArq(Texto t, String local) throws IOException{ //abrindo arquivo para escrita try (FileWriter arq = new FileWriter(local)) { PrintWriter gravarArq = new PrintWriter(arq); TreeSet<Representacao> vetorFreq = t.getVetorFreq(); for (Representacao vetorFreql : vetorFreq) { gravarArq.println(vetorFreql.getPalavra() + ", " + vetorFreql.getFrequencia()); } } } public boolean exibirVetorFreq(){ int op; //verica a quantidade de documentos e insere como opção ArrayList<String> opcoes = new ArrayList<>(); for(int i=0; i<documentos.size(); i++){ opcoes.add(Integer.toString(i+1)); } Object res = JOptionPane.showInputDialog(null, "Escolha o Documento Processado:" , "Seleção de Documentos" , JOptionPane.PLAIN_MESSAGE , null ,opcoes.toArray(),""); //verifica se foi clicado em cancelar if(res != null){ op = Integer.parseInt(res.toString())-1; TreeSet<Representacao> vet = documentos.get(op).getVetorFreqBk(); java.awt.EventQueue.invokeLater(() -> { TabelaFreq tF = new TabelaFreq(vet); tF.setLocationRelativeTo(null); tF.setVisible(true); tF.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); tF.setTitle("Frequências"); }); return true; } return false; } public static String abrirArquivo(String local){ //criar a estrutura para salvar o texto Texto t = new Texto(); //ler arquivo texto t.lerArq(local); return t.getTexto(); } public String carregarDoc(){ int op; //verica a quantidade de documentos e insere como opção ArrayList<String> opcoes = new ArrayList<>(); for(int i=0; i<documentos.size(); i++){ opcoes.add(Integer.toString(i+1)); } Object res = JOptionPane.showInputDialog(null, "Escolha um Documento:" , "Seleção de Documentos" , JOptionPane.PLAIN_MESSAGE , null ,opcoes.toArray(),""); //verifica se foi clicado em cancelar if(res != null){ op = Integer.parseInt(res.toString())-1; return (documentos.get(op).getTexto()); } else return ""; } public static Texto getDoc(int id){ for(int i=0; i<documentos.size(); i++){ if(documentos.get(i).getIdFile() == id) return documentos.get(i); } return null; } public static synchronized Texto getDoc(){ return documentos.get(++qtdDoc); } public static File getShape() { return shape; } public static void setShape(File shape) { Processamento.shape = shape; } public static int getTamMinTxt() { return tamMinTxt; } public static void setTamMinTxt(int tamMinTxt) { Processamento.tamMinTxt = tamMinTxt; } public static int getTamMaxTxt() { return tamMaxTxt; } public static void setTamMaxTxt(int tamMaxTxt) { Processamento.tamMaxTxt = tamMaxTxt; } public static int getQuantidadeMaxTermos() { return quantidadeMaxTermos; } public static void setQuantidadeMaxTermos(int quantidadeMaxTermos) { Processamento.quantidadeMaxTermos = quantidadeMaxTermos; } } <file_sep>package andreotticloud; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.SwingConstants; import javax.swing.Timer; /** * * @author <NAME> */ public class JanelaBarraProgresso extends JFrame implements Runnable { private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JLabel lblSplash = null; private JProgressBar prbProgresso = null; private Timer timer = null; public static int step; public static int tempo = 0; public JanelaBarraProgresso() { super(); step = 0; initialize(); } private void initialize() { this.setSize(375, 100); this.setContentPane(getJContentPane()); this.setTitle("Barra de Progresso"); this.setLocationRelativeTo(null); this.setAlwaysOnTop(true); setCursor(Cursor.WAIT_CURSOR); //"tempo" define o tempo de execução timer = new Timer(tempo, (ActionEvent e) -> { step++; prbProgresso.setValue(step); if (step > 10000) { JanelaBarraProgresso.this.dispose(); timer.stop(); setCursor(Cursor.DEFAULT_CURSOR); } }); timer.start(); } private JPanel getJContentPane() { if (jContentPane == null) { lblSplash = new JLabel(); lblSplash.setText("Processando..."); lblSplash.setHorizontalAlignment(SwingConstants.CENTER); jContentPane = new JPanel(); jContentPane.setLayout(new BorderLayout()); jContentPane.add(lblSplash, BorderLayout.CENTER); jContentPane.add(getPrbProgresso(), BorderLayout.SOUTH); } return jContentPane; } private JProgressBar getPrbProgresso() { if (prbProgresso == null) { prbProgresso = new JProgressBar(); } return prbProgresso; } @Override public void run() { JanelaBarraProgresso thisClass = new JanelaBarraProgresso(); thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); thisClass.setVisible(true); this.repaint(); } } <file_sep>package wordCram; import processing.core.PApplet; /** * Simple application wrapper to run the TagCloudGenerator from command line. * Please provide a config.properties for configuration. */ public class TagCloud implements Runnable{ @Override public void run() { //PApplet.main(new String[]{"--full-screen", "wordCram.TagCloudGenerator"}); PApplet.main(new String[]{"--location=20,20","wordCram.TagCloudGenerator"}); } } <file_sep>package wordCram; import java.awt.Color; import java.awt.Rectangle; import java.awt.geom.Area; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import processing.core.PVector; import wordcram.Word; import wordcram.WordNudger; import wordcram.WordPlacer; /** * Places and nudges words in the TagCloud basing on a shape image. * <p/> * Main parts from the comment section of: http://wordcram.org/2013/02/13/shapes-for-wordcram/ */ class TagCloudPlacer implements WordPlacer, WordNudger { public static int TOLERANCE = 5; private Area area; private float minX, minY, maxX, maxY; private Random random; private BufferedImage image; private TagCloudPlacer(BufferedImage image) { this.image = image; } private TagCloudPlacer init() { random = new Random(); Rectangle2D areaBounds = area.getBounds2D(); this.minX = (float) areaBounds.getMinX(); this.minY = (float) areaBounds.getMinY(); this.maxX = (float) areaBounds.getMaxX(); this.maxY = (float) areaBounds.getMaxY(); return this; } /** * Build a place with bases on an image load from a File * @param path Path to load the file from. * @param color Color to use as foreground * @param precise Shell the used shape be precise as the image information. Seems to be better with false * @return a placer instance bound to the image */ public static TagCloudPlacer fromFile(String path, Color color, boolean precise) { BufferedImage image = null; try { image = ImageIO.read(new File(path)); } catch (IOException e) { e.printStackTrace(); } return fromImage(image, color, precise); } /** * Build a place with bases on an image * @param image The shape image * @param color Color to use as foreground * @param precise Shell the used shape be precise as the image information. Seems to be better with false * @return a placer instance bound to the image */ public static TagCloudPlacer fromImage(BufferedImage image, Color color, boolean precise){ TagCloudPlacer result = new TagCloudPlacer(image); if (precise) { result.fromImagePrecise(color); } else { result.fromImageSloppy(color); } return result.init(); } private void fromImagePrecise(Color color) { Area area = new Area(); for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { Color pixel = new Color(image.getRGB(x, y)); if (isIncluded(color, pixel)) { Rectangle r = new Rectangle(x, y, 1, 1); area.add(new Area(r)); } } } this.area = area; } private void fromImageSloppy(Color color) { Area area = new Area(); Rectangle r; int y1, y2; for (int x = 0; x < image.getWidth(); x++) { y1 = 99; y2 = -1; for (int y = 0; y < image.getHeight(); y++) { Color pixel = new Color(image.getRGB(x, y)); if (isIncluded(color, pixel)) { if (y1 == 99) { y1 = y; y2 = y; } if (y > (y2 + 1)) { r = new Rectangle(x, y1, 1, y2 - y1); area.add(new Area(r)); y1 = y; } y2 = y; } } if ((y2 - y1) >= 0) { r = new Rectangle(x, y1, 1, y2 - y1); area.add(new Area(r)); } } this.area = area; } @Override public PVector place(Word w, int rank, int count, int ww, int wh, int fw, int fh) { w.setProperty("width", ww); w.setProperty("height", wh); for (int i = 0; i < 1000; i++) { float newX = randomBetween(minX, maxX); float newY = randomBetween(minY, maxY); if (area.contains(newX, newY, ww, wh)) { return new PVector(newX, newY); } } return new PVector(-1, -1); } @Override public PVector nudgeFor(Word word, int attempt) { PVector target = word.getTargetPlace(); float wx = target.x; float wy = target.y; float ww = (Integer) word.getProperty("width"); float wh = (Integer) word.getProperty("height"); for (int i = 0; i < 1000; i++) { float newX = randomBetween(minX, maxX); float newY = randomBetween(minY, maxY); if (area.contains(newX, newY, ww, wh)) { return new PVector(newX - wx, newY - wy); } } return new PVector(-1, -1); } private float randomBetween(float a, float b) { return a + random.nextFloat() * (b - a); } private boolean isIncluded(Color target, Color pixel) { int rT = target.getRed(); int gT = target.getGreen(); int bT = target.getBlue(); int rP = pixel.getRed(); int gP = pixel.getGreen(); int bP = pixel.getBlue(); return ((rP - TOLERANCE <= rT) && (rT <= rP + TOLERANCE) && (gP - TOLERANCE <= gT) && (gT <= gP + TOLERANCE) && (bP - TOLERANCE <= bT) && (bT <= bP + TOLERANCE)); } } <file_sep>package openCloud; import andreotticloud.JanelaBarraProgresso; import andreotticloud.JanelaCor; import andreotticloud.JanelaPrincipal; import andreotticloud.JanelaTag; import andreotticloud.Processamento; import andreotticloud.Representacao; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.mcavallo.opencloud.Cloud; import org.mcavallo.opencloud.Tag; import wordCram.TagCloudGenerator; /** * * @author <NAME> */ public class OpenCloud { private int idDocumento; private final int opCaractere; private static int quantidadeDocsProcessados = 0; public static int qtdDocsProcess = 0; private BufferedImage img; public static boolean msgFim = false; public OpenCloud(int opCaractere) { this.opCaractere = opCaractere; } public void initUI() throws IOException { String diretorio, nomeArq = "", diretorioSaida = "", nomeCompleto; //controla qual documento está sendo processado quantidadeDocsProcessados++; //busca um "id" de documento, esta função retorna apenas uma vez cada documento //como estamos trabalhando com thread este controle é necessário para não pegarmos //documentos repetidos idDocumento = Processamento.getDoc().getIdFile(); JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBackground(java.awt.Color.decode(JanelaCor.getCorFundo())); //API OpenCloud Cloud cloud = new Cloud(); //busca o documento pelo ID TreeSet<Representacao> vetFreq = Processamento.getDoc(idDocumento).getVetorFreq(); //percorre todo o vetor de frequência Iterator<Representacao> it = vetFreq.iterator(); Representacao rp; while(it.hasNext()){ rp = it.next(); //verifica a frequência do termo for(int i=0; i<rp.getFrequencia(); i++) //adiciona utilizando a API cloud.addTag(rp.getPalavra()); } JLabel label; for (Tag tag : cloud.tags()) { //verifica se é para deixar as palavras maiúsculas if(opCaractere == 2) //cria uma label com o nome do termo label = new JLabel(tag.getName().toUpperCase()); else //cria uma label com o nome do termo label = new JLabel(tag.getName()); //defina a cor do termo label.setForeground(java.awt.Color.decode(JanelaCor.getCor1())); label.setOpaque(false); //defini a posição que o termo ficará na imagem utilizando a API label.setFont(label.getFont().deriveFont((float) tag.getWeight() * Processamento.getTamMaxTxt())); //adiciona o termo panel.add(label); } frame.add(panel); frame.setSize(800, 600); frame.setVisible(true); //criar a imagem para ser salva como PNG img = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g = img.createGraphics(); panel.paint(g); g.dispose(); //se foi selecionado para processar vários arquivos, não serão exibidas as tags if (JanelaPrincipal.variosArq){ int incrementoNovoArq = 0, i; //verifica se o usuário tem preferência de diretório de saída if(JanelaPrincipal.diretorioDeSaidaSelecionado){ //armazena o diretório que o usuário adicionou diretorioSaida = JanelaPrincipal.diretorioDeSaida; diretorioSaida = diretorioSaida.concat("/"); } else{ //armazena o diretório onde o arquivo se encontra diretorioSaida = JanelaPrincipal.caminhoTodosFiles.get(idDocumento).getParent(); diretorioSaida = diretorioSaida.concat("/"); } //verifica o metodo de gerar a TagCloud que foi selecionada para vários arquivos //"0" significa que é pra gerar uma TagCloud para cada arquivo if(JanelaPrincipal.metodoVariosArq == 0){ //pega o nome do arquivo, pois vai salvar cada imagem com o nome do respectivo arquivo nomeCompleto = JanelaPrincipal.caminhoTodosFiles.get(idDocumento).getName(); //remove a extensão do nome nomeArq = JanelaPrincipal.caminhoTodosFiles.get(idDocumento).getName().substring(0, nomeCompleto.length()-4); } //"1" significa que é pra gerar uma única TagCloud para todos os arquivos selecionados else if(JanelaPrincipal.metodoVariosArq == 1){ //armazena o diretorio do arquivo diretorio = JanelaPrincipal.caminhoTodosFiles.get(idDocumento).getParent(); //pega a posição do último "/" para pegar somente o nome da pasta i = diretorio.lastIndexOf("/"); //armazena somente o nome da pasta, o arquivo será salvo com este nome nomeArq = diretorio.substring(i, diretorio.length()); } //verifica se não existe uma imagem de um processamento anterior (evitar sobrescrever) if(!new File(diretorioSaida+nomeArq+".png").exists()){ //salva a imagem no diretório do arquivo processado ou escolhido pelo usuário ImageIO.write(img,"png", new File(diretorioSaida+nomeArq+".png")); //fecha o frame frame.setVisible(false); } //se já existe uma imagem de outro processamento else{ //incrementa o nome que ela receberá incrementoNovoArq++; //enquanto houver imagens com nomes ainda iguais while((new File(diretorioSaida+nomeArq+"("+incrementoNovoArq+")"+".png").exists())) //incremeta o nome que ela receberá incrementoNovoArq++; //salva a imagem no diretório do arquivo processado ImageIO.write(img,"png", new File(diretorioSaida+nomeArq+"("+incrementoNovoArq+")"+".png")); //fecha o frame frame.setVisible(false); } //se chegou no último arquivo a ser processado if((quantidadeDocsProcessados == JanelaPrincipal.qtdArquivosSelecionados || JanelaPrincipal.metodoVariosArq == 1) && !msgFim){ msgFim = true; quantidadeDocsProcessados = 0; //parar barra de progresso JanelaBarraProgresso.step=10000; JOptionPane.showMessageDialog(null, "Processamento finalizado. Arquivos salvos em: "+diretorioSaida, "Sucesso", JOptionPane.INFORMATION_MESSAGE); } } else{ //salva a imagem na própria pasta do projeto nomeArq = Integer.toString(idDocumento); ImageIO.write(img,"png", new File(diretorioSaida+nomeArq+".png")); //fecha o frame frame.setVisible(false); //parar a barra de progresso JanelaBarraProgresso.step = 10000; //exibir a Tag Cloud java.awt.EventQueue.invokeLater(() -> { try { JanelaTag j = new JanelaTag(); j.setVisible(true); j.setLocationRelativeTo(null); j.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } catch (IOException ex) { Logger.getLogger(TagCloudGenerator.class.getName()).log(Level.SEVERE, null, ex); } }); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package andreotticloud; import javax.swing.JOptionPane; /** * * @author AndreAndreotti */ public class JanelaQuantidadeTermos extends javax.swing.JFrame { private final String numeroValido = "^\\d+$"; /* * Creates new form JanelaQuantidadeTermos */ public JanelaQuantidadeTermos() { initComponents(); jTextFieldQuantidade.setText(String.valueOf(Processamento.getQuantidadeMaxTermos())); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabelQuantidade = new javax.swing.JLabel(); jTextFieldQuantidade = new javax.swing.JTextField(); jButtonConfirmar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); jLabelQuantidade.setText("Quantidade máxima de termos:"); jTextFieldQuantidade.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldQuantidadeActionPerformed(evt); } }); jButtonConfirmar.setText("Confirmar"); jButtonConfirmar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonConfirmarActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabelQuantidade) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextFieldQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButtonConfirmar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelQuantidade) .addComponent(jTextFieldQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonConfirmar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConfirmarActionPerformed if(isNumero(jTextFieldQuantidade.getText())) { Processamento.setQuantidadeMaxTermos(new Integer(jTextFieldQuantidade.getText())); dispose(); } else { JOptionPane.showMessageDialog(rootPane, "Preencha com um número válido.","Erro", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButtonConfirmarActionPerformed private void jTextFieldQuantidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldQuantidadeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldQuantidadeActionPerformed public boolean isNumero(String numero){ return numero.matches(numeroValido); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonConfirmar; private javax.swing.JLabel jLabelQuantidade; private javax.swing.JTextField jTextFieldQuantidade; // End of variables declaration//GEN-END:variables } <file_sep>package andreotticloud; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import wordCram.TagCloudGenerator; import openCloud.OpenCloud; /** * * @author <NAME> */ public class JanelaPrincipal extends javax.swing.JFrame { public static boolean variosArq = false, diretorioDeSaidaSelecionado; public static File[] filesSelecionados = null; public static ArrayList<File> caminhoTodosFiles = null; public static int qtdArquivosSelecionados, metodoVariosArq, idFile = -1, qtdDocs = 0; public static String diretorioDeSaida = ""; /** * Creates new form Interface */ public JanelaPrincipal() { initComponents(); jTextAreaSaida.setLineWrap(true); jTextAreaSaida.setWrapStyleWord(true); jTextAreaEstatisticas.setLineWrap(true); jTextAreaEstatisticas.setWrapStyleWord(true); caminhoTodosFiles = new ArrayList<>(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); buttonGroup2 = new javax.swing.ButtonGroup(); jSplitPane = new javax.swing.JSplitPane(); jTabbedSaidaEstatist = new javax.swing.JTabbedPane(); jScrollPaneSaida = new javax.swing.JScrollPane(); jTextAreaSaida = new javax.swing.JTextArea(); jScrollPaneEstatisticas = new javax.swing.JScrollPane(); jTextAreaEstatisticas = new javax.swing.JTextArea(); jTabbedPaneTexto = new javax.swing.JTabbedPane(); jScrollPaneTextAreaPrincipal = new javax.swing.JScrollPane(); jTextAreaPrincipal = new javax.swing.JTextArea(); jButtonGerarTag = new javax.swing.JButton(); jButtonAbrirArqTxt = new javax.swing.JButton(); jButtonLimparAreaTxt = new javax.swing.JButton(); jSeparatorIcons = new javax.swing.JSeparator(); jButtonImagem = new javax.swing.JButton(); jButtonFrequencia = new javax.swing.JButton(); jButtonFonte = new javax.swing.JButton(); jButtonCor = new javax.swing.JButton(); jButtonDiretorioSaida = new javax.swing.JButton(); jMenuBarPrincipal = new javax.swing.JMenuBar(); jMenuArquivo = new javax.swing.JMenu(); jMenuAbrir = new javax.swing.JMenu(); jMenuItemAbrir = new javax.swing.JMenuItem(); jMenuSelecVariosArq = new javax.swing.JMenu(); jMenuGerarUmaTagParaCadaDoc = new javax.swing.JMenuItem(); jMenuGerarUmaUnicaTagParaVariosDocs = new javax.swing.JMenuItem(); jMenuDocs = new javax.swing.JMenuItem(); jSeparatorMenu = new javax.swing.JPopupMenu.Separator(); jMenuSair = new javax.swing.JMenuItem(); jMenuDiretorio = new javax.swing.JMenu(); jCheckBoxMesmoDir = new javax.swing.JCheckBoxMenuItem(); jMenuDefDir = new javax.swing.JMenuItem(); jLinguagem = new javax.swing.JMenu(); jCheckBoxMenuRemvNum = new javax.swing.JCheckBoxMenuItem(); jCheckBoxMenuRemovPP = new javax.swing.JCheckBoxMenuItem(); jCheckBoxMenuRemovPI = new javax.swing.JCheckBoxMenuItem(); jCheckBoxMenuTrataHifen = new javax.swing.JCheckBoxMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); jRadioButtonMenuComoDig = new javax.swing.JRadioButtonMenuItem(); jRadioButtonMenuMinuscula = new javax.swing.JRadioButtonMenuItem(); jRadioButtonMenuMaiuscula = new javax.swing.JRadioButtonMenuItem(); jRadioButtonMenuIguais = new javax.swing.JRadioButtonMenuItem(); jSeparator3 = new javax.swing.JPopupMenu.Separator(); jMenuAddRemocao = new javax.swing.JMenuItem(); jMenuDefinarQtdTermos = new javax.swing.JMenuItem(); jMenuCor = new javax.swing.JMenu(); jMenuItemDefCor = new javax.swing.JMenuItem(); jMenuFonte = new javax.swing.JMenu(); jMenuItemTamanho = new javax.swing.JMenuItem(); jMenuImagem = new javax.swing.JMenu(); jMenuItemSelecionarImg = new javax.swing.JMenuItem(); jMenuFrequencia = new javax.swing.JMenu(); jMenuItemFreqVis = new javax.swing.JMenuItem(); jMenuTecnica = new javax.swing.JMenu(); jRadioButtonWordCram = new javax.swing.JRadioButtonMenuItem(); jRadioButtonOpenCloud = new javax.swing.JRadioButtonMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setMinimumSize(new java.awt.Dimension(450, 200)); jSplitPane.setMinimumSize(new java.awt.Dimension(400, 100)); jTabbedSaidaEstatist.setMinimumSize(new java.awt.Dimension(100, 75)); jTextAreaSaida.setEditable(false); jTextAreaSaida.setColumns(20); jTextAreaSaida.setRows(5); jTextAreaSaida.setMinimumSize(new java.awt.Dimension(0, 0)); jScrollPaneSaida.setViewportView(jTextAreaSaida); jTabbedSaidaEstatist.addTab("Saída", jScrollPaneSaida); jTextAreaEstatisticas.setEditable(false); jTextAreaEstatisticas.setColumns(20); jTextAreaEstatisticas.setRows(5); jTextAreaEstatisticas.setMinimumSize(new java.awt.Dimension(0, 0)); jScrollPaneEstatisticas.setViewportView(jTextAreaEstatisticas); jTabbedSaidaEstatist.addTab("Estatísticas", jScrollPaneEstatisticas); jSplitPane.setLeftComponent(jTabbedSaidaEstatist); jTabbedPaneTexto.setMinimumSize(new java.awt.Dimension(200, 49)); jTextAreaPrincipal.setColumns(20); jTextAreaPrincipal.setRows(5); jTextAreaPrincipal.setMinimumSize(new java.awt.Dimension(0, 0)); jScrollPaneTextAreaPrincipal.setViewportView(jTextAreaPrincipal); jTabbedPaneTexto.addTab("Texto", jScrollPaneTextAreaPrincipal); jSplitPane.setRightComponent(jTabbedPaneTexto); jButtonGerarTag.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/execute20x20.png"))); // NOI18N jButtonGerarTag.setMnemonic('g'); jButtonGerarTag.setToolTipText("Gerar TagCloud (Alt+G)"); jButtonGerarTag.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonGerarTagActionPerformed(evt); } }); jButtonAbrirArqTxt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/open20x20.png"))); // NOI18N jButtonAbrirArqTxt.setToolTipText("Abrir Arquivo Texto (Ctrl+Shifit+T)"); jButtonAbrirArqTxt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAbrirArqTxtActionPerformed(evt); } }); jButtonLimparAreaTxt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/clear20x20.png"))); // NOI18N jButtonLimparAreaTxt.setMnemonic('l'); jButtonLimparAreaTxt.setToolTipText("Limpar Área de Texto (Alt+L)"); jButtonLimparAreaTxt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonLimparAreaTxtActionPerformed(evt); } }); jButtonImagem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/cam20x20.png"))); // NOI18N jButtonImagem.setToolTipText("Selecionar Imagem de Formato (Ctrl+Shift+I)"); jButtonImagem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonImagemActionPerformed(evt); } }); jButtonFrequencia.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/graph20x20.png"))); // NOI18N jButtonFrequencia.setToolTipText("Exibir Vetor de Frequência (Ctrl+Shift+R)"); jButtonFrequencia.setEnabled(false); jButtonFrequencia.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonFrequenciaActionPerformed(evt); } }); jButtonFonte.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/font20x20.png"))); // NOI18N jButtonFonte.setToolTipText("Definir Tamanho das Palavras (Ctrl+Shift+F)"); jButtonFonte.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonFonteActionPerformed(evt); } }); jButtonCor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/colors20x20.png"))); // NOI18N jButtonCor.setToolTipText("Definir Cores (Ctrl+Shift+C)"); jButtonCor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCorActionPerformed(evt); } }); jButtonDiretorioSaida.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/out20x20.png"))); // NOI18N jButtonDiretorioSaida.setToolTipText("Definir Diretório de Saída (Ctrl+Shift+O)"); jButtonDiretorioSaida.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonDiretorioSaidaActionPerformed(evt); } }); jMenuArquivo.setMnemonic('a'); jMenuArquivo.setText("Arquivo"); jMenuAbrir.setText("Abrir"); jMenuItemAbrir.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuItemAbrir.setText("Selecionar um arquivo .txt"); jMenuItemAbrir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemAbrirActionPerformed(evt); } }); jMenuAbrir.add(jMenuItemAbrir); jMenuSelecVariosArq.setText("Selecionar vários arquivos.txt"); jMenuGerarUmaTagParaCadaDoc.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuGerarUmaTagParaCadaDoc.setText("Gerar uma TagCloud para cada arquivo selecionado"); jMenuGerarUmaTagParaCadaDoc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuGerarUmaTagParaCadaDocActionPerformed(evt); } }); jMenuSelecVariosArq.add(jMenuGerarUmaTagParaCadaDoc); jMenuGerarUmaUnicaTagParaVariosDocs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuGerarUmaUnicaTagParaVariosDocs.setText("Gerar uma única TagCloud para todos os arquivos selecionados"); jMenuGerarUmaUnicaTagParaVariosDocs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuGerarUmaUnicaTagParaVariosDocsActionPerformed(evt); } }); jMenuSelecVariosArq.add(jMenuGerarUmaUnicaTagParaVariosDocs); jMenuAbrir.add(jMenuSelecVariosArq); jMenuDocs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.ALT_MASK)); jMenuDocs.setText("Documentos Processados"); jMenuDocs.setEnabled(false); jMenuDocs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuDocsActionPerformed(evt); } }); jMenuAbrir.add(jMenuDocs); jMenuArquivo.add(jMenuAbrir); jMenuArquivo.add(jSeparatorMenu); jMenuSair.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuSair.setText("Sair"); jMenuSair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuSairActionPerformed(evt); } }); jMenuArquivo.add(jMenuSair); jMenuBarPrincipal.add(jMenuArquivo); jMenuDiretorio.setMnemonic('d'); jMenuDiretorio.setText("Diretório"); jCheckBoxMesmoDir.setSelected(true); jCheckBoxMesmoDir.setText("Salvar saídas no mesmo diretório dos arquivos processados"); jCheckBoxMesmoDir.addMenuKeyListener(new javax.swing.event.MenuKeyListener() { public void menuKeyPressed(javax.swing.event.MenuKeyEvent evt) { jCheckBoxMesmoDirMenuKeyPressed(evt); } public void menuKeyReleased(javax.swing.event.MenuKeyEvent evt) { } public void menuKeyTyped(javax.swing.event.MenuKeyEvent evt) { } }); jCheckBoxMesmoDir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxMesmoDirActionPerformed(evt); } }); jMenuDiretorio.add(jCheckBoxMesmoDir); jMenuDefDir.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuDefDir.setText("Definir diretório de saída"); jMenuDefDir.setEnabled(false); jMenuDefDir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuDefDirActionPerformed(evt); } }); jMenuDiretorio.add(jMenuDefDir); jMenuBarPrincipal.add(jMenuDiretorio); jLinguagem.setMnemonic('i'); jLinguagem.setText("Linguagem"); jCheckBoxMenuRemvNum.setSelected(true); jCheckBoxMenuRemvNum.setText("Remover Números"); jLinguagem.add(jCheckBoxMenuRemvNum); jCheckBoxMenuRemovPP.setText("Remover palavras comuns Português"); jLinguagem.add(jCheckBoxMenuRemovPP); jCheckBoxMenuRemovPI.setText("Remover palavras comuns Inglês"); jLinguagem.add(jCheckBoxMenuRemovPI); jCheckBoxMenuTrataHifen.setText("Tratar quebra de palavra"); jCheckBoxMenuTrataHifen.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jCheckBoxMenuTrataHifenItemStateChanged(evt); } }); jLinguagem.add(jCheckBoxMenuTrataHifen); jLinguagem.add(jSeparator1); buttonGroup1.add(jRadioButtonMenuComoDig); jRadioButtonMenuComoDig.setSelected(true); jRadioButtonMenuComoDig.setText("Deixar as palavras como digitado"); jLinguagem.add(jRadioButtonMenuComoDig); buttonGroup1.add(jRadioButtonMenuMinuscula); jRadioButtonMenuMinuscula.setText("Todas palavras em minúscula"); jLinguagem.add(jRadioButtonMenuMinuscula); buttonGroup1.add(jRadioButtonMenuMaiuscula); jRadioButtonMenuMaiuscula.setText("Todas palavras em MAIÚSCULA"); jLinguagem.add(jRadioButtonMenuMaiuscula); buttonGroup1.add(jRadioButtonMenuIguais); jRadioButtonMenuIguais.setText("Unir palavras iguais"); jLinguagem.add(jRadioButtonMenuIguais); jLinguagem.add(jSeparator3); jMenuAddRemocao.setText("Adicionar palavras a lista de remoção"); jMenuAddRemocao.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuAddRemocaoActionPerformed(evt); } }); jLinguagem.add(jMenuAddRemocao); jMenuDefinarQtdTermos.setText("Definir limite máximo de termos"); jMenuDefinarQtdTermos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuDefinarQtdTermosActionPerformed(evt); } }); jLinguagem.add(jMenuDefinarQtdTermos); jMenuBarPrincipal.add(jLinguagem); jMenuCor.setMnemonic('c'); jMenuCor.setText("Cor"); jMenuItemDefCor.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuItemDefCor.setText("Definir cores"); jMenuItemDefCor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemDefCorActionPerformed(evt); } }); jMenuCor.add(jMenuItemDefCor); jMenuBarPrincipal.add(jMenuCor); jMenuFonte.setMnemonic('f'); jMenuFonte.setText("Fonte"); jMenuItemTamanho.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuItemTamanho.setText("Definir Tamanho das Palavras"); jMenuItemTamanho.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemTamanhoActionPerformed(evt); } }); jMenuFonte.add(jMenuItemTamanho); jMenuBarPrincipal.add(jMenuFonte); jMenuImagem.setMnemonic('i'); jMenuImagem.setText("Imagem"); jMenuItemSelecionarImg.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuItemSelecionarImg.setText("Selecionar imagem de formato"); jMenuItemSelecionarImg.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemSelecionarImgActionPerformed(evt); } }); jMenuImagem.add(jMenuItemSelecionarImg); jMenuBarPrincipal.add(jMenuImagem); jMenuFrequencia.setMnemonic('r'); jMenuFrequencia.setText("Frequência"); jMenuItemFreqVis.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuItemFreqVis.setText("Exibir Vetor de Frequência"); jMenuItemFreqVis.setEnabled(false); jMenuItemFreqVis.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemFreqVisActionPerformed(evt); } }); jMenuFrequencia.add(jMenuItemFreqVis); jMenuBarPrincipal.add(jMenuFrequencia); jMenuTecnica.setMnemonic('t'); jMenuTecnica.setText("Técnica"); jRadioButtonWordCram.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); buttonGroup2.add(jRadioButtonWordCram); jRadioButtonWordCram.setSelected(true); jRadioButtonWordCram.setText("WordCram"); jRadioButtonWordCram.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonWordCramActionPerformed(evt); } }); jMenuTecnica.add(jRadioButtonWordCram); jRadioButtonOpenCloud.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); buttonGroup2.add(jRadioButtonOpenCloud); jRadioButtonOpenCloud.setText("OpenCloud"); jRadioButtonOpenCloud.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonOpenCloudActionPerformed(evt); } }); jMenuTecnica.add(jRadioButtonOpenCloud); jMenuBarPrincipal.add(jMenuTecnica); setJMenuBar(jMenuBarPrincipal); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(4, 4, 4) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE) .addGap(4, 4, 4)) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jButtonAbrirArqTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonLimparAreaTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonDiretorioSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonCor, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonFonte, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonImagem, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonFrequencia, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonGerarTag, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addComponent(jSeparatorIcons) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(4, 4, 4) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jButtonAbrirArqTxt, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonLimparAreaTxt, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonDiretorioSaida, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonFonte, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonImagem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonFrequencia, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonCor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jButtonGerarTag, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparatorIcons, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE) .addGap(4, 4, 4)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jMenuItemAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemAbrirActionPerformed selecionarArquivoTexto(); }//GEN-LAST:event_jMenuItemAbrirActionPerformed private void jMenuItemFreqVisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemFreqVisActionPerformed //exibe vetor de frequências Processamento.getInstance().exibirVetorFreq(); }//GEN-LAST:event_jMenuItemFreqVisActionPerformed private void jMenuDocsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuDocsActionPerformed //abre um documento que já foi processado String result = Processamento.getInstance().carregarDoc(); if(!result.equals("")) jTextAreaPrincipal.setText(result); }//GEN-LAST:event_jMenuDocsActionPerformed private void jMenuSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuSairActionPerformed System.exit(0); }//GEN-LAST:event_jMenuSairActionPerformed private void jMenuAddRemocaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuAddRemocaoActionPerformed java.awt.EventQueue.invokeLater(() -> { JanelaPalavrasRem pr = new JanelaPalavrasRem(); pr.setLocationRelativeTo(null); pr.setVisible(true); pr.setDefaultCloseOperation(DISPOSE_ON_CLOSE); pr.setTitle("Palavras Desconsideradas"); }); }//GEN-LAST:event_jMenuAddRemocaoActionPerformed private void jMenuItemDefCorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDefCorActionPerformed definirCor(); }//GEN-LAST:event_jMenuItemDefCorActionPerformed private void jMenuItemTamanhoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemTamanhoActionPerformed definirFonte(); }//GEN-LAST:event_jMenuItemTamanhoActionPerformed private void jMenuItemSelecionarImgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSelecionarImgActionPerformed selecionarImagem(); }//GEN-LAST:event_jMenuItemSelecionarImgActionPerformed private void jRadioButtonOpenCloudActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonOpenCloudActionPerformed //desabilitar menus aceitos pela WordCram jRadioButtonMenuComoDig.setVisible(false); jRadioButtonMenuIguais.setVisible(false); jRadioButtonMenuMinuscula.setSelected(true); jMenuImagem.setEnabled(false); jButtonImagem.setEnabled(false); JanelaCor.zerarInterface = true; //seta tamanho de fonte default Processamento.setTamMaxTxt(10); }//GEN-LAST:event_jRadioButtonOpenCloudActionPerformed private void jRadioButtonWordCramActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonWordCramActionPerformed //habilitar menus aceitos pela WordCram jRadioButtonMenuComoDig.setVisible(true); jRadioButtonMenuIguais.setVisible(true); jMenuImagem.setEnabled(true); jButtonImagem.setEnabled(true); JanelaCor.zerarInterface = true; //seta tamanho de fonte default Processamento.setTamMaxTxt(38); }//GEN-LAST:event_jRadioButtonWordCramActionPerformed private void jMenuGerarUmaTagParaCadaDocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuGerarUmaTagParaCadaDocActionPerformed metodoVariosArq = 0; jTextAreaSaida.setText(""); jTextAreaEstatisticas.setText(""); TagCloudGenerator.msgFim = false; OpenCloud.msgFim = false; execVariosArquivos(); }//GEN-LAST:event_jMenuGerarUmaTagParaCadaDocActionPerformed private void jMenuGerarUmaUnicaTagParaVariosDocsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuGerarUmaUnicaTagParaVariosDocsActionPerformed metodoVariosArq = 1; jTextAreaSaida.setText(""); jTextAreaEstatisticas.setText(""); TagCloudGenerator.msgFim = false; OpenCloud.msgFim = false; execVariosArquivos(); }//GEN-LAST:event_jMenuGerarUmaUnicaTagParaVariosDocsActionPerformed private void jMenuDefDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuDefDirActionPerformed defDiretorio(); }//GEN-LAST:event_jMenuDefDirActionPerformed private void jButtonGerarTagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGerarTagActionPerformed JanelaPrincipal.variosArq = false; String texto = jTextAreaPrincipal.getText(); jTextAreaSaida.setText(""); jTextAreaEstatisticas.setText(""); TagCloudGenerator.msgFim = false; OpenCloud.msgFim = false; //adiciona apenas para incrementar pois o caminho dele não será necessário File f = new File(""); caminhoTodosFiles.add(f); idFile++; exec(texto, idFile); }//GEN-LAST:event_jButtonGerarTagActionPerformed private void jButtonAbrirArqTxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAbrirArqTxtActionPerformed selecionarArquivoTexto(); }//GEN-LAST:event_jButtonAbrirArqTxtActionPerformed private void jButtonLimparAreaTxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimparAreaTxtActionPerformed jTextAreaPrincipal.setText(""); }//GEN-LAST:event_jButtonLimparAreaTxtActionPerformed private void jButtonImagemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImagemActionPerformed selecionarImagem(); }//GEN-LAST:event_jButtonImagemActionPerformed private void jButtonFrequenciaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFrequenciaActionPerformed Processamento.getInstance().exibirVetorFreq(); }//GEN-LAST:event_jButtonFrequenciaActionPerformed private void jButtonFonteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFonteActionPerformed definirFonte(); }//GEN-LAST:event_jButtonFonteActionPerformed private void jButtonDiretorioSaidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDiretorioSaidaActionPerformed if(defDiretorio()){ jMenuDefDir.setEnabled(true); jCheckBoxMesmoDir.setSelected(false); } }//GEN-LAST:event_jButtonDiretorioSaidaActionPerformed private void jCheckBoxMesmoDirMenuKeyPressed(javax.swing.event.MenuKeyEvent evt) {//GEN-FIRST:event_jCheckBoxMesmoDirMenuKeyPressed }//GEN-LAST:event_jCheckBoxMesmoDirMenuKeyPressed private void jCheckBoxMesmoDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMesmoDirActionPerformed //se for selecionado para salvar no mesmo diretório dos arquivos processados if(jCheckBoxMesmoDir.isSelected()){ //desativa a opção de selecionar um diretório de saída jMenuDefDir.setEnabled(false); diretorioDeSaidaSelecionado = false; diretorioDeSaida = ""; } else{ if(defDiretorio()) jMenuDefDir.setEnabled(true); else jCheckBoxMesmoDir.setSelected(true); } }//GEN-LAST:event_jCheckBoxMesmoDirActionPerformed private void jButtonCorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCorActionPerformed definirCor(); }//GEN-LAST:event_jButtonCorActionPerformed private void jCheckBoxMenuTrataHifenItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBoxMenuTrataHifenItemStateChanged if(jCheckBoxMenuTrataHifen.isSelected()){ if(JOptionPane.showConfirmDialog(rootPane, "Esta opção pode dobrar o tempo de processamento para textos muito grandes.\nUtilize somente se for necessário.\nDeseja mesmo utilizar?", "União de palavras quebradas por hífen em uma quebra de linha", JOptionPane.YES_NO_OPTION) != 0){ jCheckBoxMenuTrataHifen.setSelected(false); } } }//GEN-LAST:event_jCheckBoxMenuTrataHifenItemStateChanged private void jMenuDefinarQtdTermosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuDefinarQtdTermosActionPerformed java.awt.EventQueue.invokeLater(() -> { JanelaQuantidadeTermos jqt = new JanelaQuantidadeTermos(); jqt.setLocationRelativeTo(null); jqt.setVisible(true); jqt.setDefaultCloseOperation(DISPOSE_ON_CLOSE); jqt.setTitle("Quantidade de termos"); }); }//GEN-LAST:event_jMenuDefinarQtdTermosActionPerformed public void definirCor(){ java.awt.EventQueue.invokeLater(() -> { JanelaCor c = new JanelaCor(jRadioButtonOpenCloud.isSelected(), jRadioButtonWordCram.isSelected()); c.setLocationRelativeTo(null); c.setVisible(true); c.setDefaultCloseOperation(DISPOSE_ON_CLOSE); c.setTitle("Cores"); }); } public void definirFonte(){ java.awt.EventQueue.invokeLater(() -> { JanelaFonte ft = new JanelaFonte(jRadioButtonOpenCloud.isSelected()); ft.setLocationRelativeTo(null); ft.setVisible(true); ft.setDefaultCloseOperation(DISPOSE_ON_CLOSE); ft.setTitle("Fonte"); }); } public void selecionarImagem(){ //criar instância JanelaShape java.awt.EventQueue.invokeLater(() -> { JanelaShape js = new JanelaShape(); js.setVisible(true); js.setLocationRelativeTo(null); js.setDefaultCloseOperation(DISPOSE_ON_CLOSE); js.setTitle("Imagem Formato"); }); } public void selecionarArquivoTexto(){ JanelaPrincipal.variosArq = false; String local; //abrir arquivos JFileChooser jfc = new JFileChooser(); //habilida a seleção de vários arquivos jfc.setMultiSelectionEnabled(true); //somente arquivos .txt final FileNameExtensionFilter filter = new FileNameExtensionFilter("Somente arquivos TXT","txt"); //aplica o filtro .txt jfc.setFileFilter(filter); //somente abre arquivos jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); //remove a opção de exibir outros formatos de arquivos jfc.setAcceptAllFileFilterUsed(false); if(jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){ //armazenar o arquivo selecionado File f = jfc.getSelectedFile(); //armazena o local do arquivo local = f.getAbsolutePath(); //limpar o texto jTextAreaPrincipal.setText(""); //adicionar o texto lido do arquivo na JtextArea String texto = Processamento.abrirArquivo(local); jTextAreaPrincipal.setText(texto); } } public boolean defDiretorio(){ String local; //abrir arquivos JFileChooser jfc = new JFileChooser(); //somente seleciona diretórios jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //mudar o texto do botão confirmar jfc.setApproveButtonText("Selecionar"); //mudar o título jfc.setDialogTitle("Seleção de Diretório"); if(jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){ //armazenar o arquivo selecionado File f = jfc.getSelectedFile(); //armazena o local do arquivo local = f.getAbsolutePath(); JOptionPane.showMessageDialog(rootPane, "Ao processar vários arquivos, as saídas serão salvas em: "+local, "Diretório de saída", JOptionPane.INFORMATION_MESSAGE); diretorioDeSaidaSelecionado = true; diretorioDeSaida = local; return true; } return false; } public static void setTextSaida(String texto){ jTextAreaSaida.setText(jTextAreaSaida.getText().concat(texto+"\n")); } public static void setTextEstatisticas(String texto){ jTextAreaEstatisticas.setText(jTextAreaEstatisticas.getText().concat(texto+"\n")); } public void execVariosArquivos(){ String local; String texto = ""; //verifica se já foi selecionada a imagem shape if(Processamento.getShape() == null && jRadioButtonWordCram.isSelected()){ JOptionPane.showMessageDialog(rootPane, "Selecione uma imagem que dará o formato da TagCloud. \n\nImagem->Selecionar imagem de formato","Imagem não selecionada", JOptionPane.ERROR_MESSAGE); } else{ JOptionPane.showMessageDialog(rootPane, "Selecione os arquivos \".txt\" que deseja gerar a \"TagCloud\".\n\nObs: Após a execução as imagens serão salvas no mesmo diretório,\nou no diretório de saída escolhido no menu \"Diretório\".", "Informações", JOptionPane.INFORMATION_MESSAGE); JanelaPrincipal.variosArq = true; //abrir arquivos JFileChooser jfc = new JFileChooser(); //habilida a seleção de vários arquivos jfc.setMultiSelectionEnabled(true); //somente arquivos .txt final FileNameExtensionFilter filter = new FileNameExtensionFilter("Somente arquivos TXT","txt"); //aplica o filtro .txt jfc.setFileFilter(filter); //somente abre arquivos jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); //remove a opção de exibir outros formatos de arquivos jfc.setAcceptAllFileFilterUsed(false); if(jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){ //guardar todos os arquivos selecionados filesSelecionados = jfc.getSelectedFiles(); //guardar a quantidade de arquivos selecionados qtdArquivosSelecionados = filesSelecionados.length; //se o método selecionado é gerar uma TagCloud para cada arquivo (0) if(metodoVariosArq == 0){ texto = ""; for (File file : filesSelecionados) { caminhoTodosFiles.add(file); idFile++; local = file.getAbsolutePath(); //adicionar o texto lido do arquivo texto = Processamento.abrirArquivo(local); //limpar o texto jTextAreaPrincipal.setText(" "); //executa varias vezes exec(texto, idFile); } } //se o método selecionado é gerar uma única TagCloud para todos os arquivo (1) else if(metodoVariosArq == 1){ texto = ""; idFile++; caminhoTodosFiles.add(filesSelecionados[0]); for (File file : filesSelecionados) { //armazenar o local local = file.getAbsolutePath(); //concatena todos os textos dos arquivos para gerar uma única TagCloud texto = texto.concat(Processamento.abrirArquivo(local)); //limpar o texto jTextAreaPrincipal.setText(" "); } //executa uma única vez exec(texto, idFile); } //verifica qual técnica será utilizada e define o tempo da barra de progresso if(jRadioButtonOpenCloud.isSelected() && metodoVariosArq == 0) JanelaBarraProgresso.tempo = qtdArquivosSelecionados*10; else if(jRadioButtonWordCram.isSelected() && metodoVariosArq == 0) JanelaBarraProgresso.tempo = qtdArquivosSelecionados*20; else{ JanelaBarraProgresso.tempo = (int) (texto.length()/3000); } JanelaBarraProgresso ex = new JanelaBarraProgresso(); new Thread(ex).start(); } } } public void exec(String texto, int idFile){ //verifica se já está inserido um texto if(!texto.trim().equals("")){ //verifica se já foi selecionada a imagem shape if(Processamento.getShape() == null && jRadioButtonWordCram.isSelected()){ JOptionPane.showMessageDialog(rootPane, "Selecione uma imagem que dará o formato da TagCloud. \n\nMenu->Imagem (Ctrl+Shift+I)","Imagem não selecionada", JOptionPane.ERROR_MESSAGE); } else{ if(!variosArq){ JanelaBarraProgresso.tempo = (int) (texto.length()/7000); JanelaBarraProgresso bp = new JanelaBarraProgresso(); new Thread(bp).start(); } //verifica as opções de preferência selecionadas int opCaractere; if(jRadioButtonMenuComoDig.isSelected()){ opCaractere = 0; } else if(jRadioButtonMenuMinuscula.isSelected()){ opCaractere = 1; } else if(jRadioButtonMenuMaiuscula.isSelected()){ opCaractere = 2; } else{ opCaractere = 3; } //variável que controla a quantidade de tags geradas numa instância do programa qtdDocs++; // criar uma thread para que seja possível atualizar a "saída" na JtexArea na interface e a barra de carregamento // caso contrário o processamento rodará na thread do Swing e o JtexArea não será atualizado // até que está thread fique livre new Thread(() -> { try { //executar processamento if (Processamento.getInstance().execute(idFile, texto, jCheckBoxMenuRemvNum.isSelected(), jCheckBoxMenuRemovPP.isSelected(), jCheckBoxMenuRemovPI.isSelected(), opCaractere, jRadioButtonWordCram.isSelected(), jRadioButtonOpenCloud.isSelected(), jCheckBoxMenuTrataHifen.isSelected())){ //ativar o menu de visualização do vetor de frequências jButtonFrequencia.setEnabled(true); jMenuItemFreqVis.setEnabled(true); jMenuDocs.setEnabled(true); } } catch (IOException ex) { Logger.getLogger(JanelaPrincipal.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(JanelaPrincipal.class.getName()).log(Level.SEVERE, null, ex); } }).start(); } } else JOptionPane.showMessageDialog(rootPane, "Área de texto vazia. Digite um texto ou carregue um arquivo.","Janela de Aviso", JOptionPane.ERROR_MESSAGE); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.ButtonGroup buttonGroup2; private javax.swing.JButton jButtonAbrirArqTxt; private javax.swing.JButton jButtonCor; private javax.swing.JButton jButtonDiretorioSaida; private javax.swing.JButton jButtonFonte; private javax.swing.JButton jButtonFrequencia; private javax.swing.JButton jButtonGerarTag; private javax.swing.JButton jButtonImagem; private javax.swing.JButton jButtonLimparAreaTxt; private javax.swing.JCheckBoxMenuItem jCheckBoxMenuRemovPI; private javax.swing.JCheckBoxMenuItem jCheckBoxMenuRemovPP; private javax.swing.JCheckBoxMenuItem jCheckBoxMenuRemvNum; private javax.swing.JCheckBoxMenuItem jCheckBoxMenuTrataHifen; private javax.swing.JCheckBoxMenuItem jCheckBoxMesmoDir; private javax.swing.JMenu jLinguagem; private javax.swing.JMenu jMenuAbrir; private javax.swing.JMenuItem jMenuAddRemocao; private javax.swing.JMenu jMenuArquivo; private javax.swing.JMenuBar jMenuBarPrincipal; private javax.swing.JMenu jMenuCor; private javax.swing.JMenuItem jMenuDefDir; private javax.swing.JMenuItem jMenuDefinarQtdTermos; private javax.swing.JMenu jMenuDiretorio; private javax.swing.JMenuItem jMenuDocs; private javax.swing.JMenu jMenuFonte; private javax.swing.JMenu jMenuFrequencia; private javax.swing.JMenuItem jMenuGerarUmaTagParaCadaDoc; private javax.swing.JMenuItem jMenuGerarUmaUnicaTagParaVariosDocs; private javax.swing.JMenu jMenuImagem; private javax.swing.JMenuItem jMenuItemAbrir; private javax.swing.JMenuItem jMenuItemDefCor; private javax.swing.JMenuItem jMenuItemFreqVis; private javax.swing.JMenuItem jMenuItemSelecionarImg; private javax.swing.JMenuItem jMenuItemTamanho; private javax.swing.JMenuItem jMenuSair; private javax.swing.JMenu jMenuSelecVariosArq; private javax.swing.JMenu jMenuTecnica; private javax.swing.JRadioButtonMenuItem jRadioButtonMenuComoDig; private javax.swing.JRadioButtonMenuItem jRadioButtonMenuIguais; private javax.swing.JRadioButtonMenuItem jRadioButtonMenuMaiuscula; private javax.swing.JRadioButtonMenuItem jRadioButtonMenuMinuscula; private javax.swing.JRadioButtonMenuItem jRadioButtonOpenCloud; private javax.swing.JRadioButtonMenuItem jRadioButtonWordCram; private javax.swing.JScrollPane jScrollPaneEstatisticas; private javax.swing.JScrollPane jScrollPaneSaida; private javax.swing.JScrollPane jScrollPaneTextAreaPrincipal; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparator3; private javax.swing.JSeparator jSeparatorIcons; private javax.swing.JPopupMenu.Separator jSeparatorMenu; private javax.swing.JSplitPane jSplitPane; private javax.swing.JTabbedPane jTabbedPaneTexto; private javax.swing.JTabbedPane jTabbedSaidaEstatist; private static javax.swing.JTextArea jTextAreaEstatisticas; private javax.swing.JTextArea jTextAreaPrincipal; private static javax.swing.JTextArea jTextAreaSaida; // End of variables declaration//GEN-END:variables }
383a235f5cd37b118e8e6c3fb051c5f65fac3903
[ "Java" ]
11
Java
AndreAndreotti/AndreottiCloud
91a19944ddbba9cedfb429445f8d5fbbc4f8b13c
7fe8aa34e6aba7fb3f4c3c0cfce4b5e0219c065e
refs/heads/master
<file_sep>var testApp = angular.module('testApp', []); var host = "http://" + window.location.host; testApp.controller('studentanlegenCtrl', function($scope,$http){ var name; var mnr; var email; var gdatum; var note; $scope.abschicken = function() { var daten = {}; name = $scope.name; mnr = $scope.mnr; email = $scope.email; gdatum = JSON.stringify($scope.gdatum); note = $scope.note; daten["name"] = name; daten["mnr"] = mnr; daten["email"] = email; daten["gdatum"] = substrGdatum(gdatum); daten["note"] = note; $http.post(host + "/studentanlegen", daten).then(function(data) { console.log(data); }); } $scope.holen = function() { console.log("war hier"); $http.get(host + "/studentholen").then(function(data) { $scope.besterStudent = data.data.name; console.log(data.data); }); } }); function substrGdatum(gdatum) { var neuDatum; neuDatum = gdatum.substr(1,10); return neuDatum; }<file_sep>var express = require('express'); var app = express(); var MongoClient = require('mongodb').MongoClient; var assert = require('assert'); var ObjectId = require('mongodb').ObjectID; var url = 'mongodb://localhost:27017/test'; var bodyParser = require('body-parser'); app.use(express.static(__dirname + '/app')); app.use(express.static(__dirname + '/app/views')); app.use(bodyParser.json()); var pfad = __dirname + '/app/views'; app.get("/", function(req, res) { res.sendFile(pfad + '/main.html'); }); app.post("/studentanlegen", function(req, res) { console.log("Body: " + JSON.stringify(req.body)); MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to server."); insertDocument(db, function() { db.close(); }); }); var json = req.body; var insertDocument = function(db, callback) { db.collection('studenten').insertOne(json, function(err, result) { assert.equal(err, null); console.log("Inserted a document into the restaurants collection."); callback(result); }); }; res.send("OK"); }); app.get("/studentholen", function(req, res) { var ergebnis = {}; MongoClient.connect(url, function(err, db) { assert.equal(null, err); getBestStudent(db, function() { db.close(); res.send(ergebnis[0]); }); }); var getBestStudent = function(db, callback) { var cursor = db.collection('studenten').find().sort({ "note": 1 }); var index = 0; cursor.each(function(err, doc) { assert.equal(err, null); if (doc != null) { console.dir(doc); ergebnis[index] = doc; console.dir("Ergebnis: " + JSON.stringify(ergebnis)); } else { callback(); } index++; }); }; }); app.listen(3131, function() { console.log("Test App läuft auf 3131"); });
2726d64076e61ab4649f4c8bb892149aa3f4c722
[ "JavaScript" ]
2
JavaScript
Kerem193/NodeJsMongo
95e5c11f7e4175e4e224c33db15c494ace3248ac
1458f482e1f0fd2a3aab68b15181173ada29675a
refs/heads/master
<repo_name>addagiri/SortNumbersLatest<file_sep>/SortNumbers/src/main/java/com/sortNumbers/dao/Sortdao.java package com.sortNumbers.dao; import java.util.ArrayList; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sortNumbers.entity.sortEntity; @Service public class Sortdao { @Autowired SortRepository sortRepo; /** * Retrieve All Values from database * * @return */ @Transactional public List<sortEntity> getAllSortNumbers() { List<sortEntity> entityResult = new ArrayList<sortEntity>(); sortRepo.findAll(). forEach(resultRow -> entityResult .add(resultRow)); return entityResult; } @Transactional public void saveOrUpdate(sortEntity sortNumber) { sortRepo.save(sortNumber); } } <file_sep>/SortNumbers/target/classes/application.properties server.port=8443 spring.h2.console.enabled=true spring.h2.console.path=/h2-console spring.datasource.url=jdbc:h2:file:~/test spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.datasource.driverClassName=org.h2.Driver spring.datasource.username= spring.datasource.password= <file_sep>/SortNumbers/src/main/java/com/sortNumbers/service/SortService.java package com.sortNumbers.service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sortNumbers.dao.Sortdao; import com.sortNumbers.entity.sortEntity; import com.sortNumbers.model.SortedResult; @Service public class SortService { @Autowired static Sortdao dao; public static SortedResult sort(String randomNumbers) { sortEntity result = new sortEntity(); int [] arrayOfNumbers = null; try { arrayOfNumbers = getArrayofNumbers(randomNumbers); } catch(NumberFormatException e) { result.setUnSortedNumbers(randomNumbers); result.setStatus("Sort Failed: "); //dao.saveOrUpdate(result); return new SortedResult(randomNumbers, "", 0, 0, ("Sort Failed" + " Given Numbers are:" + randomNumbers + " are invalid")); } String unSortedNumbers = Arrays.toString(arrayOfNumbers); long startTime = System.nanoTime(); int swapCount = getSwapCount(arrayOfNumbers); long endTime = System.nanoTime(); result.setUnSortedNumbers(unSortedNumbers); result.setSortedNumbers(Arrays.toString(arrayOfNumbers)); result.setDuration(endTime-startTime); result.setSwapCount(swapCount); result.setStatus("success"); //dao.saveOrUpdate(result); return new SortedResult(Arrays.toString(arrayOfNumbers), unSortedNumbers, swapCount, endTime-startTime, "success"); } public static int getSwapCount(int[] arrayOfNumbers) { int swapcount = 0; int n = arrayOfNumbers.length; for (int i=1; i<n; ++i) { int key = arrayOfNumbers[i]; int j = i-1; while (j>=0 && arrayOfNumbers[j] > key) { arrayOfNumbers[j+1] = arrayOfNumbers[j]; j = j-1; swapcount++; } arrayOfNumbers[j+1] = key; } return swapcount; } private static int[] getArrayofNumbers(String randomNumbers) { return Arrays.stream(randomNumbers.split(",")) .map(String::trim) .mapToInt(Integer::parseInt) .toArray(); } /** * Retrieve All the Values by connecting to database * * @return List<SortResult> */ public List<SortedResult> getAllResults() { List<SortedResult> results = new ArrayList<>(); List<sortEntity> sortedNumber = dao.getAllSortNumbers(); sortedNumber.forEach(resultRow -> { SortedResult result = new SortedResult(resultRow.getSortedNumbers(), resultRow.getUnSortedNumbers(), resultRow.getSwapCount(), resultRow.getDuration(), resultRow.getStatus()); results.add(result); }); return results; } } <file_sep>/SortNumbers/src/main/java/com/sortNumbers/model/UserInput.java package com.sortNumbers.model; public class UserInput { private static String userInput; public static String getUserInput() { return userInput; } public void setUserInput(String userInput) { this.userInput = userInput; } }<file_sep>/SortNumbers/src/main/java/com/sortNumbers/model/SortedResult.java package com.sortNumbers.model; public class SortedResult { private String SortedNumbers; private String UnSortedNumbers; private int SwapCount; private long duration; private String status; public SortedResult(String sortedNumbers, String unSortedNumbers, int swapCount, long duration, String status) { super(); SortedNumbers = sortedNumbers; UnSortedNumbers = unSortedNumbers; SwapCount = swapCount; this.duration = duration; this.status = status; } public String getSortedNumbers() { return SortedNumbers; } public void setSortedNumbers(String sortedNumbers) { SortedNumbers = sortedNumbers; } public String getUnSortedNumbers() { return UnSortedNumbers; } public void setUnSortedNumbers(String unSortedNumbers) { UnSortedNumbers = unSortedNumbers; } public int getSwapCount() { return SwapCount; } public void setSwapCount(int swapCount) { SwapCount = swapCount; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } <file_sep>/SortNumbers/src/main/java/com/sortNumbers/controller/SortController.java package com.sortNumbers.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.sortNumbers.model.SortedResult; import com.sortNumbers.service.SortService; @Controller public class SortController { @Autowired private SortService SortService; @RequestMapping("/sort") @GetMapping public String home(@ModelAttribute("randomNumbers") String randomNumbers,ModelMap map) { SortedResult resultOfSorting = SortService.sort(randomNumbers); map.put("sorted", resultOfSorting.getSortedNumbers()); map.put("Unsorted", resultOfSorting.getUnSortedNumbers()); map.put("time", resultOfSorting.getDuration()); map.put("swapCount", resultOfSorting.getSwapCount()); map.put("status", resultOfSorting.getStatus()); return "view.jsp"; } @RequestMapping("/") public String home() { return "home.jsp"; } } <file_sep>/SortNumbers/src/main/java/com/sortNumbers/entity/sortEntity.java package com.sortNumbers.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="Result") public class sortEntity { @Id @GeneratedValue private long id; private String SortedNumbers; private String UnSortedNumbers; private int SwapCount; private long duration; private String status; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getSortedNumbers() { return SortedNumbers; } public void setSortedNumbers(String sortedNumbers) { SortedNumbers = sortedNumbers; } public String getUnSortedNumbers() { return UnSortedNumbers; } public void setUnSortedNumbers(String unSortedNumbers) { UnSortedNumbers = unSortedNumbers; } public int getSwapCount() { return SwapCount; } public void setSwapCount(int swapCount) { SwapCount = swapCount; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
9f3ae2045bc6af806d2db84a8aadcd9e326312a3
[ "Java", "INI" ]
7
Java
addagiri/SortNumbersLatest
8df7282d6e0d8980fa1d013f0267a2dfc109ca04
e9cdafd3da91c26f26858b0331cd701e32c079d8
refs/heads/master
<repo_name>dlartigue/file_sorter<file_sep>/file_sorter.py #!/anaconda/bin/python import os import re import shutil class file_sorter(object): def __init__(self, main_dir): self.main_dir = main_dir self.files = [] files = os.listdir(main_dir) for f in files: if '.' in f: self.files.append(f) else: pass self.extensions = (r'\.([pdf]|[jpg]|[csv]|[dmg]|[iso]|[app]|' '[tar]|[xip])+$') self.exceptions = r'([\$recycle\.bin]|[\.ds_store]|[\.localized])+' self.filetypes = [] def create_dir(self, file_type): new_dir = self.main_dir + file_type.replace(".", "") + "/" if os.path.exists(new_dir): return(new_dir) else: os.makedirs(new_dir) print("%s directory created" % new_dir) return(new_dir) def sort(self): for f in self.files: try: file = f.lower() search = re.search(self.extensions, file) temp = search.group(0) destination = self.create_dir(temp) current = self.main_dir + file shutil.move(current, destination) print("moved %s to %s" % (file, destination)) except (TypeError, AttributeError) as e: if re.match(self.exceptions, file) is not None: pass else: print("There was an issue with %s" % file) print(e) pass if __name__ == "__main__": main_dir = "/Users/dustin/Downloads/" sorter = file_sorter(main_dir) sorter.sort()
dd79fb08d4989343745d6c6cbd0fc500ac71132b
[ "Python" ]
1
Python
dlartigue/file_sorter
b8e43d2540af899b48fd45329bed4b90ed62729f
6c8d04bbb257f0c5e5fa3a3fd21bb1d192eeedf3
refs/heads/master
<repo_name>ChristieDesnoyer30/WarGames<file_sep>/src/com/company/HumanPlayer.java package com.company; public class HumanPlayer implements PlayerHand { private Deck deck; public Deck getDeck() { return deck; } public void setDeck(Deck deck) { this.deck = deck; } public HumanPlayer(){ this.deck = new Deck(); } public void hand(){ deck.makeFirstHand(); } public int getHumanPlayerHandSize(){ return deck.handOne.size(); } public String getOneCard(){ return deck.getP1FirstCard().getRank(); } public int getCardNumberAtFirstIndexValue(String card){ card = getOneCard(); int cardNum = deck.getCardNumericalValueAtFirstIndexValue(card); return cardNum; } }
6625b9680a592074ccb1c888f716e108ed50bcde
[ "Java" ]
1
Java
ChristieDesnoyer30/WarGames
ed058f5de316b548b18f195741381e4a495883f3
6df3190b3a713dbfd106d708ef6999a29b9ac579
refs/heads/master
<file_sep>// // Created by manolo on Mar 11, 2014. // Copyright (c) 2014 manolo. All rights reserved. // package flappysub; /** * * @author manolo */ import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedList; import java.util.Scanner; import javax.swing.JFrame; /** * * @author manolo */ public class FlappySub extends JFrame implements Runnable, KeyListener, MouseListener { private static final long serialVersionUID = 1L; // Se declaran las variables. private Image dbImage; // Imagen a proyectar private Image background; // Imagen de fondo private Graphics dbg; // Objeto grafico private Base sub; // Objeto sub private int gravity; private int push; private LinkedList<Mine> mines; // Objeto minas private int nMines; private int minesV; private int minesGap; // Separacion entre minas arriba/abajo private SoundClip choque; // Sonido de choque con minas private SoundClip sonar; // Sonido de sonar private long tiempoActual; // el tiempo actual que esta corriendo el jar private long tiempoInicial; // el tiempo inicial private boolean sound; // si el sonido esta activado private int score; // el puntaje private int level; private boolean changeLvl; // checar si se necesitan private Base pausa; // Objeto que pinta el pausa private Base instruc; // Objeto que pinta las instrucciones private Base gameo; // Objeto que pinta el Game over private Base gamew; // Objeto que pinta el Game over win private int highestscore; // El puntuaje mas alto private int estado; // el estado actual del juego (0 = corriendo, 1 = pausa, 2 = informacion,3 = creditos) private boolean cargar; // variable que carga el archivo private String nombre; //guarda el nombre y el score public FlappySub() { init(); start(); } public void init() { // Inicializacion de variables setSize(1200,720); score = 0; level = 0; changeLvl = true; estado = 2; sound = true; cargar = false; choque = new SoundClip("resources/explosion.wav"); // choque con minas choque.setLooping(false); sonar = new SoundClip("resources/sonar.wav"); sonar.setLooping(false); background = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/background.jpg")); // Se cargan las imágenes para la animación Image sub0 = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/sub0.png")); Image sub1 = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/sub1.png")); Image iT = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/mineT.png")); Image iB = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/mineB.png")); Image instru= Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/instrucciones.png")); Image pausa1 = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/pause.jpg")); Image gameo1 = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/gameover.jpg")); // Image gameo2 = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/gameover2.png")); // Se crea la animación Animacion animS = new Animacion(), animT = new Animacion(), animB = new Animacion(); Animacion animI = new Animacion(), animGo = new Animacion(), animP=new Animacion(); int subTime = 200, mineTime = 0; animS.sumaCuadro(sub0, subTime); animS.sumaCuadro(sub1, subTime); animT.sumaCuadro(iT, mineTime); animB.sumaCuadro(iB, mineTime); animI.sumaCuadro(instru,0); animGo.sumaCuadro(gameo1,0); animP.sumaCuadro(pausa1,0); gravity = 5; push = 0; sub = new Base(563,400,1,animS); gameo = new Base(0,20,0,animGo); pausa = new Base(0,20,0,animP); nMines = 4; minesV = -3; minesGap = 128; mines = new LinkedList(); for (int i=0; i<nMines; i++) { Base top = new Base(0,0,0,animT); Base bottom = new Base(0,0,0,animB); mines.add(new Mine(0, 0, minesGap, top, bottom)); int r = (int)(Math.random()*100)+350; mines.get(i).setY(r); mines.get(i).setX(1250+i*300); } instruc = new Base(0,20,0,animI); setResizable(false); setBackground(new Color(43, 48, 51)); addKeyListener(this); addMouseListener(this); } /** * Metodo <I>start</I> sobrescrito de la clase <code>Applet</code>.<P> * En este metodo se crea e inicializa el hilo * para la animacion este metodo es llamado despues del init o * cuando el usuario visita otra pagina y luego regresa a la pagina * en donde esta este <code>Applet</code> * */ public void start () { // Declaras un hilo Thread th = new Thread(this); // Empieza el hilo th.start(); } /** * Metodo <I>run</I> sobrescrito de la clase <code>Thread</code>.<P> * En este metodo se ejecuta el hilo, es un ciclo indefinido donde se incrementa * la posicion en x o y dependiendo de la direccion, finalmente * se repinta el <code>Applet</code> y luego manda a dormir el hilo. * */ @Override @SuppressWarnings("SleepWhileInLoop") public void run () { while (true) { actualiza(); checaColision(); // Se actualiza el <code>Applet</code> repintando el contenido. repaint(); try { // El thread se duerme. Thread.sleep (20); } catch (InterruptedException ex) { System.out.println("Error en " + ex.toString()); } } } /** * Metodo usado para actualizar la posicion de objetos * */ public void actualiza() { if (estado == 0) { // Determina el tiempo que ha transcurrido desde que el Applet inicio su ejecución long tiempoTranscurrido = System.currentTimeMillis() - tiempoActual; // Guarda el tiempo actual tiempoActual += tiempoTranscurrido; // Actualiza la posicion y la animación en base al tiempo transcurrido int y = gravity+push; if (push<0) { push++; } sub.addY(y); sub.actualiza(tiempoActual); for (int i=0; i<nMines; i++) { Mine mine = mines.get(i); mine.addX(minesV); if (mine.getX() == 558 || mine.getX() == 559 || mine.getX() == 560) { score++; changeLvl = false; if (sound) { sonar.play(); } } else if (mine.getX() < -34) { mine.setX(1250); minesV = -3-((level+1)/2); int r = (int)(Math.random()*(100+50*level))+350-50*level; mine.setY(r); } } } if (sub.getLives() <= 0) { estado = 3; Scanner scanner= new Scanner(System.in); System.out.print("Pon tu nombre"); String nombre = scanner.nextLine(); try { grabaArchivo(); } catch(IOException e) { System.out.println("Error en guardar"); } } if (!changeLvl && (score%10)==0) { level++; changeLvl = true; } /* if (cargar) { cargar = false; try { leeArchivo(); } catch(IOException e) { System.out.println("Error en cargar"); } }*/ } /** * Metodo usado para checar las colisiones del objeto elefante y asteroid * con las orillas del <code>Applet</code>. */ public void checaColision() { if (sub.getY()<0 || sub.getY()>668) { sub.addLives(-1); if (sound) { choque.play(); } } for (int i=0; i<nMines; i++) { if (mines.get(i).intersecta(sub)) { sub.addLives(-1); if (sound) { choque.play(); } } } } /** * Metodo <I>keyPressed</I> sobrescrito de la interface <code>KeyListener</code>.<P> * En este metodo maneja el evento que se genera al presionar cualquier la tecla. * @param e es el <code>evento</code> generado al presionar las teclas. */ @Override public void keyPressed(KeyEvent e) { if (e.getKeyChar() == 's') { //Presiono tecla s para quitar sonido sound = !sound; } else if (e.getKeyChar() == 'i') { // Mostrar/Quitar las instrucciones del juego if (estado == 2) { estado = 0; } else { estado = 2; // cargar=true; } } else if (e.getKeyChar() == 'p') { //Presiono tecla p para parar el juego en ejecuccion if (estado == 1) { estado = 0; } else { estado = 1; } } else if (e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_UP) { push -= 10; } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { push += 10; } else if (e.getKeyCode()== KeyEvent.VK_R) { if (estado!=0) { score = 0; level = 0; gravity = 4; push = 0; minesV = -3; sub.setX(563); sub.setY(400); sub.setLives(1); for (int i=0; i<nMines; i++) { int r = (int)(Math.random()*300)+150; mines.get(i).setY(r); mines.get(i).setX(1250+i*300); mines.get(i).setGap(128); } estado = 0; } } } @Override public void keyReleased(KeyEvent e){} @Override public void keyTyped(KeyEvent e){} /** * Metodo <I>mousePressed</I> sobrescrito de la interface <code>MouseListener</code>.<P> * En este metodo maneja el evento que se genera al empezar un click. * @param e es el <code>evento</code> que se genera al empezar un click. */ @Override public void mousePressed(MouseEvent e) { // Para a link si se le da click/vuelve a moverse if (estado == 0) { push -= 10; } } @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e){} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} public void grabaArchivo() throws IOException { // Grabar las variables necesarias para reiniciar el juego de donde se quedo el usuario en un txt llamado Guardado PrintWriter fileOut = new PrintWriter(new FileWriter("Guardado")); fileOut.println(String.valueOf(nombre)); fileOut.println(String.valueOf(score)); fileOut.close(); } @Override public void paint(Graphics g) { // Inicializan el DoubleBuffer dbImage = createImage (this.getSize().width, this.getSize().height); dbg = dbImage.getGraphics (); // Actualiza la imagen de fondo. dbg.setColor(getBackground ()); dbg.fillRect(0, 0, this.getSize().width, this.getSize().height); // Actualiza el Foreground. dbg.setColor(getForeground()); paint1(dbg); // Dibuja la imagen actualizada g.drawImage (dbImage, 0, 0, this); } /** * Metodo <I>paint1</I> sobrescrito de la clase <code>Applet</code>, * heredado de la clase Container.<P> * En este metodo se dibuja la imagen con la posicion actualizada, * ademas que cuando la imagen es cargada te despliega una advertencia. * @param g es el <code>objeto grafico</code> usado para dibujar. */ public void paint1(Graphics g) { g.setFont(new Font("Helvetica", Font.PLAIN, 20)); // plain font size 20 g.setColor(Color.white); // black font if (sub != null) { // Dibuja la imagen en la posicion actualizada g.drawImage(background, 0, 20, this); for (int i=0; i<nMines; i++) { Mine m = mines.get(i); g.drawImage(m.getTop().getImage(), m.getX(), m.getTop().getY(), this); g.drawImage(m.getBottom().getImage(), m.getX(), m.getBottom().getY(), this); } if (estado == 0) { // Dibuja el estado corriendo del juego g.drawImage(sub.getImage(), sub.getX(), sub.getY(), this); g.drawString("Score: " + score,1000, 75); // draw score at (1000,25) // g.drawString("Vidas: " + String.valueOf(hank.getLives()), 1000, 75); // draw score at (1000,25) } else if (estado == 1) { // Dibuja el estado de pausa en el jframe g.drawImage(pausa.getImage(),pausa.getX(),pausa.getY(),this); } else if (estado == 2) { // Dibuja el estado de informacion para el usuario en el jframe g.drawImage(instruc.getImage(),instruc.getX(),instruc.getY(),this); } else if (estado ==3 ){ // Dibuja el estado de game over para el usuario en el jframe g.drawImage(gameo.getImage(),gameo.getX(),gameo.getY(),this); } } else { // Da un mensaje mientras se carga el dibujo g.drawString("No se cargo la imagen..", 20, 20); } } /** * @param args the command line arguments */ public static void main(String[] args) { FlappySub examen2 = new FlappySub(); examen2.setVisible(true); examen2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
2393be8f704b261165a053234c5561caa422c2b7
[ "Java" ]
1
Java
manolosavi/FlappySub
ae617182cc4176744f74d0601be42e2a9cfecd23
1ed4eea085b72f1a03ec3e0097ad197a1ccfba4b
refs/heads/master
<file_sep># hdr10plus_parser [![Tests](https://github.com/quietvoid/hdr10plus_parser/workflows/Tests/badge.svg)](https://github.com/quietvoid/hdr10plus_parser/actions?query=workflow%3ATests) [![Artifacts](https://github.com/quietvoid/hdr10plus_parser/workflows/Artifacts/badge.svg)](https://github.com/quietvoid/hdr10plus_parser/actions?query=workflow%3AArtifacts) Tool to check if a HEVC file contains SMPTE 2094-40 metadata in SEI messages. If dynamic metadata is found, the whole file is parsed through and a metadata JSON file is generated for use with x265/other encoders. ## Supported HDR10+ LLC Versions Up to Version 1.2 Version 1.3 of the specification released in September 2019 might not be supported. ## Usage, in CLI: * `hdr10plus_parser.exe "path/to/file.hevc" -o metadata.json` * `ffmpeg -i "input.mkv" -map 0:v:0 -c copy -vbsf hevc_mp4toannexb -f hevc - | hdr10plus_parser.exe -o metadata.json -` * `cargo run -- "path/to/file.hevc" -o metadata.json` options: * `-i`, `--input <INPUT>` Sets the input file to use. * `-o`, `--output <OUTPUT>` Sets the output JSON file to use. * `--verify` Checks if input file contains dynamic metadata. * `--force-single-profile` Force only one metadata profile, avoiding mixing different profiles (fix for x265 segfault). ### Piping with ffmpeg using Powershell is not supported because of memory leaking issues. ## Sample files Tears of Steel samples encoded with x265 using `--dhdr10-info` for tests. Sample JSON metadata available here: https://bitbucket.org/multicoreware/x265_git/downloads/ <file_sep>[package] name = "hdr10plus_parser" version = "0.4.1" authors = ["quietvoid"] edition = "2018" license = "MIT" [dependencies] structopt = "0.3.21" serde = "1.0.125" serde_json = "1.0.64" indicatif = "0.15.0" regex = "1.4.6" ansi_term = "0.12.1" deku = "0.9.2" hevc_parser = "0.1.4"<file_sep>use std::path::PathBuf; use super::metadata::DistributionMaxRgb; use super::parser::Parser; use super::Format; // x265 Tool_Verification_new_hdr10plus_llc.json 1st frame #[test] fn sample1() { let input_file = PathBuf::from("./assets/ToS-s1.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 400); assert_eq!(result.average_maxrgb, 1037); assert_eq!(result.maxscl, vec![17830, 16895, 14252]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![3, 14024, 43, 56, 219, 1036, 2714, 4668, 14445] ); assert_eq!(result.knee_point_x, 17); assert_eq!(result.knee_point_y, 64); assert_eq!( result.bezier_curve_anchors, vec![265, 666, 741, 800, 848, 887, 920, 945, 957] ); } // All 0 values except arrays #[test] fn sample2() { let input_file = PathBuf::from("./assets/ToS-s2.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 0); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![3, 14024, 43, 56, 219, 1036, 2714, 4668, 14445] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![265, 666, 741, 800, 848, 887, 920, 945, 957] ); } // Some small values #[test] fn sample3() { let input_file = PathBuf::from("./assets/ToS-s3.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 12); assert_eq!(result.maxscl, vec![0, 1, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![3, 14024, 43, 56, 219, 1036, 2714, 4668, 14445] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![265, 666, 741, 800, 848, 887, 920, 945, 957] ); } // More random values #[test] fn sample4() { let input_file = PathBuf::from("./assets/ToS-s4.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 10); assert_eq!(result.average_maxrgb, 1); assert_eq!(result.maxscl, vec![0, 1, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 14024, 43, 56, 219, 0, 2714, 4668, 14445] ); assert_eq!(result.knee_point_x, 1); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![0, 666, 741, 0, 848, 887, 920, 945, 957] ); } // Some 0 values except targeted display maximum luminance #[test] fn sample5() { let input_file = PathBuf::from("./assets/ToS-s5.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 500); assert_eq!(result.average_maxrgb, 0); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 3, 4, 5, 6, 7, 8] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } // More random values #[test] fn sample6() { let input_file = PathBuf::from("./assets/ToS-s6.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 500); assert_eq!(result.average_maxrgb, 1); assert_eq!(result.maxscl, vec![1, 3, 6]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 3, 4, 5, 6, 7, 8] ); assert_eq!(result.knee_point_x, 2048); assert_eq!(result.knee_point_y, 85); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } // Edge case with averageRGB #[test] fn sample7() { let input_file = PathBuf::from("./assets/ToS-s7.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 400); assert_eq!(result.average_maxrgb, 12); assert_eq!(result.maxscl, vec![3790, 5508, 3584]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 572, 100, 1, 1, 2, 12, 35, 491] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } // Low averageRGB and MaxScl 0s #[test] fn sample8() { let input_file = PathBuf::from("./assets/ToS-s8.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 400); assert_eq!(result.average_maxrgb, 3); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 572, 100, 1, 1, 2, 12, 35, 491] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } // Low averageRGB, MaxScl 0s and TargetedSystemDisplayMaximumLuminance 0 #[test] fn sample9() { let input_file = PathBuf::from("./assets/ToS-s9.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 3); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 572, 100, 1, 1, 2, 12, 35, 491] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } #[test] fn sample10() { let input_file = PathBuf::from("./assets/ToS-s10.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 13); assert_eq!(result.maxscl, vec![1, 3, 6]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 572, 100, 1, 1, 2, 12, 35, 491] ); assert_eq!(result.knee_point_x, 1); assert_eq!(result.knee_point_y, 1); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } #[test] fn sample11() { let input_file = PathBuf::from("./assets/ToS-s11.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 0); assert_eq!(result.maxscl, vec![69700, 67280, 89012]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 572, 100, 1, 1, 2, 12, 35, 491] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } #[test] fn sample12() { let input_file = PathBuf::from("./assets/ToS-s12.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 0); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 572, 100, 1, 1, 2, 12, 35, 491] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } #[test] fn sample13() { let input_file = PathBuf::from("./assets/ToS-s13.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 78023); assert_eq!(result.maxscl, vec![69700, 67280, 89012]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 572, 100, 1, 1, 2, 12, 35, 491] ); assert_eq!(result.knee_point_x, 2305); assert_eq!(result.knee_point_y, 1203); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } #[test] fn sample14() { let input_file = PathBuf::from("./assets/ToS-s14.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 9998); assert_eq!(result.average_maxrgb, 78023); assert_eq!(result.maxscl, vec![69700, 67280, 89012]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 572, 100, 1, 1, 2, 12, 35, 491] ); assert_eq!(result.knee_point_x, 2305); assert_eq!(result.knee_point_y, 1203); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } #[test] fn sample15() { let input_file = PathBuf::from("./assets/ToS-s15.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 9998); assert_eq!(result.average_maxrgb, 0); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 0, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample16() { let input_file = PathBuf::from("./assets/ToS-s16.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 400); assert_eq!(result.average_maxrgb, 1); assert_eq!(result.maxscl, vec![450, 26, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 9791, 100, 0, 1, 9, 32, 56, 9740] ); assert_eq!(result.knee_point_x, 35); assert_eq!(result.knee_point_y, 86); assert_eq!( result.bezier_curve_anchors, vec![203, 411, 624, 721, 773, 821, 875, 924, 953] ); } #[test] fn sample17() { let input_file = PathBuf::from("./assets/ToS-s17.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 400); assert_eq!(result.average_maxrgb, 11); assert_eq!(result.maxscl, vec![0, 0, 3584]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 9791, 100, 0, 1, 9, 32, 56, 9740] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } #[test] fn sample18() { let input_file = PathBuf::from("./assets/ToS-s18.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 3584); assert_eq!(result.maxscl, vec![0, 0, 8]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 9791, 100, 0, 1, 9, 32, 56, 9740] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } #[test] fn sample19() { let input_file = PathBuf::from("./assets/ToS-s19.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 4096); assert_eq!(result.average_maxrgb, 0); assert_eq!(result.maxscl, vec![4096, 8192, 16384]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 9791, 100, 0, 1, 9, 32, 56, 9740] ); assert_eq!(result.knee_point_x, 3823); assert_eq!(result.knee_point_y, 1490); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } #[test] fn sample20() { let input_file = PathBuf::from("./assets/ToS-s20.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 0); assert_eq!(result.maxscl, vec![0, 5582, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample21() { let input_file = PathBuf::from("./assets/ToS-s21.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 9); assert_eq!(result.maxscl, vec![0, 0, 3584]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample22() { let input_file = PathBuf::from("./assets/ToS-s22.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 12); assert_eq!(result.maxscl, vec![7, 0, 3584]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample23() { let input_file = PathBuf::from("./assets/ToS-s23.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 12); assert_eq!(result.maxscl, vec![1, 0, 6]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample24() { let input_file = PathBuf::from("./assets/ToS-s24.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 1); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![0, 5582, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample25() { let input_file = PathBuf::from("./assets/ToS-s25.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![3584, 0, 3584]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample26() { let input_file = PathBuf::from("./assets/ToS-s26.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 10000); assert_eq!(result.average_maxrgb, 100000); assert_eq!(result.maxscl, vec![2048, 2048, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample27() { let input_file = PathBuf::from("./assets/ToS-s27.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 10000); assert_eq!(result.average_maxrgb, 12); assert_eq!(result.maxscl, vec![2048, 2048, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample28() { let input_file = PathBuf::from("./assets/ToS-s28.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 10000); assert_eq!(result.average_maxrgb, 12); assert_eq!(result.maxscl, vec![2048, 2048, 2048]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample29() { let input_file = PathBuf::from("./assets/ToS-s29.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 10000); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![2049, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample30() { let input_file = PathBuf::from("./assets/ToS-s30.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![12, 3, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample31() { let input_file = PathBuf::from("./assets/ToS-s31.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![1, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample32() { let input_file = PathBuf::from("./assets/ToS-s32.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 11); assert_eq!(result.maxscl, vec![1152, 2, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample33() { let input_file = PathBuf::from("./assets/ToS-s33.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![32768, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample34() { let input_file = PathBuf::from("./assets/ToS-s34.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![1, 2304, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample35() { let input_file = PathBuf::from("./assets/ToS-s35.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 8192); assert_eq!(result.average_maxrgb, 11); assert_eq!(result.maxscl, vec![158, 1, 1]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample36() { let input_file = PathBuf::from("./assets/ToS-s36.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 8192); assert_eq!(result.average_maxrgb, 11); assert_eq!(result.maxscl, vec![4096, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample37() { let input_file = PathBuf::from("./assets/ToS-s37.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 8192); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample38() { let input_file = PathBuf::from("./assets/ToS-s38.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 8192); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![0, 2048, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample39() { let input_file = PathBuf::from("./assets/ToS-s39.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 8192); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![0, 98304, 98304]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample40() { let input_file = PathBuf::from("./assets/ToS-s40.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 8192); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![0, 70000, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample41() { let input_file = PathBuf::from("./assets/ToS-s41.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 1); assert_eq!(result.average_maxrgb, 12); assert_eq!(result.maxscl, vec![32768, 98304, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample42() { let input_file = PathBuf::from("./assets/ToS-s42.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 0); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![98304, 98304, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample43() { let input_file = PathBuf::from("./assets/ToS-s43.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 1); assert_eq!(result.average_maxrgb, 1024); assert_eq!(result.maxscl, vec![65536, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample44() { let input_file = PathBuf::from("./assets/ToS-s44.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 10000); assert_eq!(result.average_maxrgb, 65535); assert_eq!(result.maxscl, vec![0, 4097, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample45() { let input_file = PathBuf::from("./assets/ToS-s45.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 4096); assert_eq!(result.average_maxrgb, 1); assert_eq!(result.maxscl, vec![0, 65536, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample46() { let input_file = PathBuf::from("./assets/ToS-s46.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 4096); assert_eq!(result.average_maxrgb, 65536); assert_eq!(result.maxscl, vec![0, 65536, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample47() { let input_file = PathBuf::from("./assets/ToS-s47.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 8192); assert_eq!(result.average_maxrgb, 65536); assert_eq!(result.maxscl, vec![32768, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample48() { let input_file = PathBuf::from("./assets/ToS-s48.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 8192); assert_eq!(result.average_maxrgb, 65536); assert_eq!(result.maxscl, vec![0, 65536, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample49() { let input_file = PathBuf::from("./assets/ToS-s49.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 8192); assert_eq!(result.average_maxrgb, 12); assert_eq!(result.maxscl, vec![99000, 98304, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample50() { let input_file = PathBuf::from("./assets/ToS-s50.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 8192); assert_eq!(result.average_maxrgb, 99999); assert_eq!(result.maxscl, vec![99000, 98304, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample51() { let input_file = PathBuf::from("./assets/ToS-s51.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 400); assert_eq!(result.average_maxrgb, 32847); assert_eq!(result.maxscl, vec![32768, 32768, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample52() { let input_file = PathBuf::from("./assets/ToS-s52.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 400); assert_eq!(result.average_maxrgb, 0); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample53() { let input_file = PathBuf::from("./assets/ToS-s53.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 400); assert_eq!(result.average_maxrgb, 100000); assert_eq!(result.maxscl, vec![0, 99999, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample54() { let input_file = PathBuf::from("./assets/ToS-s54.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 10000); assert_eq!(result.average_maxrgb, 100000); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, Vec::<u16>::new()); } #[test] fn sample55() { let input_file = PathBuf::from("./assets/ToS-s55.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 350); assert_eq!(result.average_maxrgb, 1); assert_eq!(result.maxscl, vec![4425, 3984, 3292]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 98, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 0, 0, 0, 0, 0, 1, 5, 2756] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, vec![256, 512, 767]); } #[test] fn sample56() { let input_file = PathBuf::from("./assets/ToS-s56.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 350); assert_eq!(result.average_maxrgb, 1); assert_eq!(result.maxscl, vec![0, 65536, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 98, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 0, 0, 0, 0, 0, 1, 5, 2756] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, vec![256, 512, 767]); } #[test] fn sample57() { let input_file = PathBuf::from("./assets/ToS-s57.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 9998); assert_eq!(result.average_maxrgb, 0); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 0, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!(result.bezier_curve_anchors, vec![0, 0, 0]); } #[test] fn sample58() { let input_file = PathBuf::from("./assets/ToS-s58.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 10000); assert_eq!(result.average_maxrgb, 100000); assert_eq!(result.maxscl, vec![100000, 100000, 100000]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 98, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000] ); assert_eq!(result.knee_point_x, 4095); assert_eq!(result.knee_point_y, 4095); assert_eq!( result.bezier_curve_anchors, vec![1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023] ); } #[test] fn sample59() { let input_file = PathBuf::from("./assets/ToS-s59.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 10000); assert_eq!(result.average_maxrgb, 100000); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 98, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000] ); assert_eq!(result.knee_point_x, 4095); assert_eq!(result.knee_point_y, 4095); assert_eq!( result.bezier_curve_anchors, vec![1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023] ); } #[test] fn sample60() { let input_file = PathBuf::from("./assets/ToS-s60.h265"); let parser = Parser::new(Format::Raw, input_file, None, false, false); let result = parser._test().unwrap(); assert_eq!(result.num_windows, 1); assert_eq!(result.targeted_system_display_maximum_luminance, 400); assert_eq!(result.average_maxrgb, 0); assert_eq!(result.maxscl, vec![0, 0, 0]); assert_eq!( DistributionMaxRgb::distribution_index(&result.distribution_maxrgb), vec![1, 5, 10, 25, 50, 75, 90, 95, 99] ); assert_eq!( DistributionMaxRgb::distribution_values(&result.distribution_maxrgb), vec![0, 0, 100, 0, 0, 0, 0, 0, 0] ); assert_eq!(result.knee_point_x, 0); assert_eq!(result.knee_point_y, 0); assert_eq!( result.bezier_curve_anchors, vec![102, 205, 307, 410, 512, 614, 717, 819, 922] ); } <file_sep>use indicatif::{ProgressBar, ProgressStyle}; use std::{fs::File, path::Path}; pub mod metadata; pub mod parser; #[cfg(test)] mod tests; #[derive(Debug, PartialEq)] pub enum Format { Raw, RawStdin, Matroska, } #[derive(Debug)] pub struct RpuOptions { pub mode: Option<u8>, pub crop: bool, } pub fn initialize_progress_bar(format: &Format, input: &Path) -> ProgressBar { let pb: ProgressBar; let bytes_count; if let Format::RawStdin = format { pb = ProgressBar::hidden(); } else { let file = File::open(input).expect("No file found"); //Info for indicatif ProgressBar let file_meta = file.metadata(); bytes_count = file_meta.unwrap().len() / 100_000_000; pb = ProgressBar::new(bytes_count); pb.set_style( ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:60.cyan} {percent}%"), ); } pb } impl std::fmt::Display for Format { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { Format::Matroska => write!(f, "Matroska file"), Format::Raw => write!(f, "HEVC file"), Format::RawStdin => write!(f, "HEVC pipe"), } } } <file_sep>use regex::Regex; use std::path::{Path, PathBuf}; use structopt::StructOpt; mod hdr10plus; use hdr10plus::parser::Parser; use hdr10plus::Format; #[derive(StructOpt, Debug)] #[structopt( name = "hdr10plus_parser", about = "Parses HDR10+ dynamic metadata in HEVC video files" )] struct Opt { #[structopt( name = "input", short = "i", long, help = "Sets the input file to use", long, conflicts_with = "stdin", parse(from_os_str) )] input: Option<PathBuf>, #[structopt( help = "Uses stdin as input data", conflicts_with = "input", parse(from_os_str) )] stdin: Option<PathBuf>, #[structopt( short = "o", long, help = "Sets the output JSON file to use", parse(from_os_str) )] output: Option<PathBuf>, #[structopt(long, help = "Checks if input file contains dynamic metadata")] verify: bool, #[structopt( long, help = "Force only one metadata profile, avoiding mixing different profiles (fix for x265 segfault)" )] force_single_profile: bool, } fn main() { let opt = Opt::from_args(); let input = match opt.input { Some(input) => input, None => match opt.stdin { Some(stdin) => stdin, None => PathBuf::new(), }, }; let verify = opt.verify || opt.output.is_none(); match input_format(&input) { Ok(format) => { let parser = Parser::new(format, input, opt.output, verify, opt.force_single_profile); parser.process_input(); } Err(msg) => println!("{}", msg), } } fn input_format(input: &Path) -> Result<Format, &str> { let regex = Regex::new(r"\.(hevc|.?265|mkv)").unwrap(); let file_name = match input.file_name() { Some(file_name) => file_name.to_str().unwrap(), None => "", }; if file_name == "-" { Ok(Format::RawStdin) } else if regex.is_match(file_name) && input.is_file() { if file_name.contains("mkv") { Ok(Format::Matroska) } else { Ok(Format::Raw) } } else if file_name.is_empty() { Err("Missing input.") } else if !input.is_file() { Err("Input file doesn't exist.") } else { Err("Invalid input file type.") } } <file_sep>use ansi_term::Colour::Yellow; use deku::prelude::*; use serde_json::{json, Value}; use super::parser::MetadataFrame; const DISTRIBUTION_INDEXES_9: &[u8] = &[1, 5, 10, 25, 50, 75, 90, 95, 99]; const DISTRIBUTION_INDEXES_10: &[u8] = &[1, 5, 10, 25, 50, 75, 90, 95, 98, 99]; #[derive(Debug, DekuRead, Clone)] #[deku(endian = "big")] pub struct Metadata { #[deku(bits = "8")] pub country_code: u8, #[deku(bits = "16")] pub terminal_provider_code: u16, #[deku(bits = "16")] pub terminal_provider_oriented_code: u16, #[deku(bits = "8")] pub application_identifier: u8, #[deku(bits = "8")] pub application_version: u8, #[deku(bits = "2")] pub num_windows: u8, #[deku(bits = "27")] pub targeted_system_display_maximum_luminance: u32, #[deku(bits = "1")] pub targeted_system_display_actual_peak_luminance_flag: u8, #[deku(count = "3", bits = "17")] pub maxscl: Vec<u32>, #[deku(bits = "17")] pub average_maxrgb: u32, #[deku(bits = "4")] pub num_distribution_maxrgb_percentiles: u8, #[deku(count = "num_distribution_maxrgb_percentiles")] pub distribution_maxrgb: Vec<DistributionMaxRgb>, #[deku(bits = "10")] pub fraction_bright_pixels: u16, #[deku(bits = "1")] pub mastering_display_actual_peak_luminance_flag: u8, #[deku(bits = "1")] pub tone_mapping_flag: u8, #[deku(bits = "12", cond = "*tone_mapping_flag == 1")] pub knee_point_x: u16, #[deku(bits = "12", cond = "*tone_mapping_flag == 1")] pub knee_point_y: u16, #[deku(bits = "4", cond = "*tone_mapping_flag == 1")] pub num_bezier_curve_anchors: u8, #[deku( count = "num_bezier_curve_anchors", bits = "10", cond = "*tone_mapping_flag == 1" )] pub bezier_curve_anchors: Vec<u16>, #[deku(bits = "1")] pub color_saturation_mapping_flag: u8, } #[derive(Debug, PartialEq, DekuRead, Clone)] #[deku(endian = "endian", ctx = "endian: deku::ctx::Endian")] pub struct DistributionMaxRgb { #[deku(bits = "7")] percentage: u8, #[deku(bits = "17")] percentile: u32, } impl Metadata { pub fn validate(&self) { // SMPTE ST-2094 Application 4, Version 1 assert_eq!(self.application_identifier, 4); assert_eq!(self.application_version, 1); // The value of targeted_system_display_maximum_luminance shall be in the range of 0 to 10000, inclusive assert!(self.targeted_system_display_maximum_luminance <= 10000); // Shall be under 100000, inclusive self.maxscl.iter().for_each(|&v| assert!(v <= 100_000)); // Shall be under 100000, inclusive assert!(self.average_maxrgb <= 100_000); // Shall be under 100000, inclusive DistributionMaxRgb::validate( &self.distribution_maxrgb, self.num_distribution_maxrgb_percentiles, ); // The value of knee_point_x shall be in the range of 0 to 1, and in multiples of 1/4095 assert!(self.knee_point_x < 4096); assert!(self.knee_point_y < 4096); // THe maximum value shall be 9 assert!(self.num_bezier_curve_anchors <= 9); // Shall be under 1024 self.bezier_curve_anchors .iter() .for_each(|&v| assert!(v < 1024)); } pub fn json_list( list: &[MetadataFrame], force_single_profile: bool, ) -> (&str, Vec<Value>, Option<String>) { // Get highest number of anchors (should be constant across frames other than empty) let num_bezier_curve_anchors = if let Some(max) = list .iter() .map(|m| m.metadata.bezier_curve_anchors.len()) .max() { max } else { 0 }; // Use max with 0s instead of empty let replacement_curve_data = vec![0; num_bezier_curve_anchors]; let mut warning = None; let mut profile = "A"; let metadata_json_array = list .iter() .map(|mf| &mf.metadata) .map(|m| { // Profile A, no bezier curve data if m.targeted_system_display_maximum_luminance == 0 && m.bezier_curve_anchors.is_empty() && num_bezier_curve_anchors == 0 { json!({ "LuminanceParameters": { "AverageRGB": m.average_maxrgb, "LuminanceDistributions": DistributionMaxRgb::separate_json(&m.distribution_maxrgb), "MaxScl": m.maxscl }, "NumberOfWindows": m.num_windows, "TargetedSystemDisplayMaximumLuminance": m.targeted_system_display_maximum_luminance }) } else { // Profile B if profile != "B" { profile = "B"; } // Don't insert empty vec when profile B and forcing single profile let bezier_curve_anchors = if force_single_profile && m.bezier_curve_anchors.is_empty() && num_bezier_curve_anchors != 0 { if warning.is_none() { warning = Some(format!("{}", Yellow.paint("Forced profile B."))); } &replacement_curve_data } else { if warning.is_none() && m.bezier_curve_anchors.is_empty() && num_bezier_curve_anchors != 0 { warning = Some(format!("{} Different profiles appear to be present in the metadata, this can cause errors when used with x265.\nUse {} to \"fix\".", Yellow.paint("Warning:"), Yellow.paint("--force-single-profile"))); } &m.bezier_curve_anchors }; json!({ "BezierCurveData": { "Anchors": bezier_curve_anchors, "KneePointX": m.knee_point_x, "KneePointY": m.knee_point_y }, "LuminanceParameters": { "AverageRGB": m.average_maxrgb, "LuminanceDistributions": DistributionMaxRgb::separate_json(&m.distribution_maxrgb), "MaxScl": m.maxscl }, "NumberOfWindows": m.num_windows, "TargetedSystemDisplayMaximumLuminance": m.targeted_system_display_maximum_luminance }) } }) .collect::<Vec<Value>>(); (profile, metadata_json_array, warning) } } impl DistributionMaxRgb { pub fn distribution_index(list: &[Self]) -> Vec<u8> { list.iter().map(|v| v.percentage).collect::<Vec<u8>>() } pub fn distribution_values(list: &[Self]) -> Vec<u32> { list.iter().map(|v| v.percentile).collect::<Vec<u32>>() } fn separate_json(list: &[Self]) -> Value { json!({ "DistributionIndex": Self::distribution_index(list), "DistributionValues": Self::distribution_values(list), }) } pub fn validate(list: &[Self], num_distribution_maxrgb_percentiles: u8) { // The value of num_distribution_maxrgb_percentiles shall be 9 or 10 (for all we know) let correct_indexes = match num_distribution_maxrgb_percentiles { 9 => DISTRIBUTION_INDEXES_9, 10 => DISTRIBUTION_INDEXES_10, _ => panic!( "Invalid number of percentiles: {}", num_distribution_maxrgb_percentiles ), }; // Distribution indexes should be equal to: // 9 indexes: [1, 5, 10, 25, 50, 75, 90, 95, 99] // 10 indexes: [1, 5, 10, 25, 50, 75, 90, 95, 98, 99] assert_eq!(Self::distribution_index(list), correct_indexes); Self::distribution_values(list) .iter() .for_each(|&v| assert!(v <= 100_000)); } }
23aac215ca7d560f5da23328ea21cb4a5b08d044
[ "Markdown", "TOML", "Rust" ]
6
Markdown
allenk/hdr10plus_parser
98b8152da44da2b4a37482780005411c731f1f48
bd94b1c55daea60ea32f444840654f3c5c6d3f32
refs/heads/master
<file_sep>class MoviesController < ApplicationController # route: GET /movies(.:format) def index @movies = Movie.all # binding.pry respond_to do |format| format.html format.json { render :json => Movie.all } format.xml { render :xml => Movie.all.to_xml } end end # route: # GET /movies/:id(.:format) def show # @movie = Movie.find do |m| # m["imdbID"] == params[:id] # end /movies/:id "/movies/4" id = params[:id] @movie = Movie.find(id) if @movie.nil? flash.now[:message] = "Movie not found" @movie = {} end end def search @results = JSON.parse(Typhoeus.get("www.omdbapi.com/", :params => {:s => params[:search]}).body) end # route: GET /movies/new(.:format) def new end # route: GET /movies/:id/edit(.:format) def edit show end #route: # POST /movies(.:format) def create # create new movie object from params movie = params.require(:movie).permit(:title, :year) # movie["imdbID"] = rand(10000..100000000).to_s # add object to movie db Movie.create(movie) # show movie page # render :index redirect_to action: :index end def add results = params[:checked] results.each do |title| title_year = title.split(",") new_movie = {"title" => title_year[0], "year" => title_year[1]} # Movie.create(new_movie) # Movie.create(title: new_movie["title"], year: new_movie["year"], imdbID: new_movie["imdbID"]) Movie.create(new_movie) end redirect_to action: :index end # route: PATCH /movies/:id(.:format) def update #implement id = params[:id] changes = params.require(:movie).permit(:title, :year) # changes = {:title => params[:movie][:title], :year => params[:movie][:year]} movie = Movie.find(id) movie.update_attributes(changes) redirect_to "/movies/#{id}" end # route: DELETE /movies/:id(.:format) def destroy #implement id = params[:id] movie = Movie.find(id) Movie.destroy(movie) redirect_to "/" end def next # params[:id].nil? ? id = 0 : id = params[:id].to_1 + 1 # # redirect_to "movies/#{id+1}" # @movie = nil # while @movie.nil? # @movie = Movie.find(id) # i += 1 # end # redirect_to action: :show id = params[:id] @movie = nil while @movie == nil @movie = Movie.find(id) id += 1 end show end def prev movies = Movies.all params[:id].nil? ? id = movie.size.to_i : id = params[:id].to_i - 1 # redirect_to "movies/#{id-1}" @movie = Movie.find(id) redirect_to action: :show end end
d871ada193ad7ee0c6a5df949f392584b1ca49d7
[ "Ruby" ]
1
Ruby
melodicodyssey/wdi_rails_movie_views
587aef47022dea8b812bc3170f7617c1d68f7ff5
f3f14989b246547300059500f04fdd8b90e2e885
refs/heads/master
<file_sep>package com.example.devik.firstlib import android.content.Context import android.widget.Toast import java.lang.ref.WeakReference object SingleToast { var ref: WeakReference<Toast>? = null fun show(context: Context, messageResId: Int) { show(context, context.getString(messageResId)) } fun show(context: Context, message: String) { ref?.get()?.let { it.cancel() } val toast = Toast.makeText(context, message, Toast.LENGTH_SHORT) ref = WeakReference(toast) toast.show() } }
d5b50cdd726a4a0888243ff13c02aa6b674233a8
[ "Kotlin" ]
1
Kotlin
Devik0213/test_library
0108d3dbbc7210e3325e3440c223c98cde527156
0c0ef119fe8fd1e16262e90d92af1e6929d1d6c5
refs/heads/main
<repo_name>chintanrparmar/Naturist<file_sep>/app/src/main/java/app/chintan/naturist/MainActivity.kt package app.chintan.naturist import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import app.chintan.naturist.databinding.ActivityMainBinding import com.google.android.material.bottomnavigation.BottomNavigationView import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navView: BottomNavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_activity_main) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. val appBarConfiguration = AppBarConfiguration(setOf( R.id.navigation_post_list, R.id.navigation_favourite, R.id.navigation_profile)) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) navController.addOnDestinationChangedListener { _, destination, _ -> when (destination.id) { R.id.postDetailFragment -> hideBottomNav() else -> showBottomNav() } } } private fun hideBottomNav() { binding.navView.visibility = View.GONE } private fun showBottomNav() { binding.navView.visibility = View.VISIBLE } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment_activity_main) return navController.navigateUp() || super.onSupportNavigateUp() } }<file_sep>/app/src/main/java/app/chintan/naturist/NaturistApp.kt package app.chintan.naturist import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class NaturistApp : Application() { }<file_sep>/app/src/main/java/app/chintan/naturist/ui/blog/PostDetailFragment.kt package app.chintan.naturist.ui.blog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Observer import app.chintan.naturist.databinding.FragmentPostDetailBinding import app.chintan.naturist.model.Post import app.chintan.naturist.util.FirebaseUserManager import app.chintan.naturist.util.State import coil.load import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class PostDetailFragment : Fragment() { private val postViewModel: PostViewModel by activityViewModels() private var _binding: FragmentPostDetailBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! private var selectedPostId = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { _binding = FragmentPostDetailBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpOnClick() loadPostDetail() } private fun loadPostDetail() { postViewModel.selectedPostLiveData.observe(viewLifecycleOwner, Observer { when (it) { is State.Success -> { updatePostDetailUI(it.data) binding.progressBar.visibility = GONE } is State.Error -> { Toast.makeText(activity, it.message, Toast.LENGTH_SHORT).show() binding.progressBar.visibility = GONE } is State.Loading -> binding.progressBar.visibility = VISIBLE } }) } private fun updatePostDetailUI(data: Post) { binding.postImage.load(data.imageUrl) binding.postTitle.text = data.title binding.postDesc.text = data.description selectedPostId = data.id.toString() } private fun setUpOnClick() { binding.likeBt.setOnClickListener { FirebaseUserManager.getUserId()?.let { uid -> postViewModel.likePost(selectedPostId, uid ) } } } }<file_sep>/app/src/main/java/app/chintan/naturist/ui/login/LoginActivity.kt package app.chintan.naturist.ui.login import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import android.view.View.GONE import android.view.View.VISIBLE import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import app.chintan.naturist.MainActivity import app.chintan.naturist.R import app.chintan.naturist.databinding.ActivityLoginBinding import app.chintan.naturist.model.UserRole import app.chintan.naturist.util.Constants.ROLE_KEY import app.chintan.naturist.util.FirebaseUserManager import app.chintan.naturist.util.State import app.chintan.naturist.util.UserSessionManager import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.common.api.ApiException import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @AndroidEntryPoint class LoginActivity : AppCompatActivity() { @Inject lateinit var prefDataStore: DataStore<Preferences> private lateinit var binding: ActivityLoginBinding private val loginViewModel: LoginViewModel by viewModels() private lateinit var userSessionManager: UserSessionManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) setContentView(binding.root) userSessionManager = UserSessionManager(this) setUpOnClick() setUpObserver() } private fun setUpOnClick() { binding.googleSignInBt.setOnClickListener { checkRoleAndSignIn() } } private fun setUpObserver() { loginViewModel.firebaseAuthLiveData.observe(this, Observer { when (it) { is State.Success -> updateUserRole() is State.Error -> Toast.makeText(applicationContext, "Login Failed", Toast.LENGTH_SHORT).show() is State.Loading -> binding.progressBar.visibility = VISIBLE } }) loginViewModel.updateUserRoleLiveData.observe(this, Observer { when (it) { is State.Success -> { goToHomeUI() binding.progressBar.visibility = GONE } is State.Error -> { Toast.makeText(applicationContext, "Login Failed", Toast.LENGTH_SHORT).show() binding.progressBar.visibility = GONE } is State.Loading -> binding.progressBar.visibility = VISIBLE } }) } private fun saveRoleLocally(role: UserRole) { lifecycleScope.launch(Dispatchers.IO) { prefDataStore.edit { userDetails -> userDetails[ROLE_KEY] = role.name } } } private fun checkRoleAndSignIn() { if (binding.userRoleRg.checkedRadioButtonId == -1) { Toast.makeText(applicationContext, "Please select a role", Toast.LENGTH_SHORT).show() return } signIn() } private val signInLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { res -> this.onSignInResult(res) } private fun signIn() { //signIn Intent val signInIntent = userSessionManager.googleSignInClient.signInIntent signInLauncher.launch(signInIntent) } private fun onSignInResult(res: ActivityResult) { // Result returned from launching the Intent if (res.resultCode == Activity.RESULT_OK) { val task = GoogleSignIn.getSignedInAccountFromIntent(res.data) try { // Google Sign In was successful, authenticate with Firebase val account = task.getResult(ApiException::class.java)!! Log.d(TAG, "firebaseAuthWithGoogle:" + account.id) loginViewModel.firebaseAuthWithGoogle(account.idToken!!) } catch (e: ApiException) { // Google Sign In failed, update UI appropriately Log.w(TAG, "Google sign in failed", e) } } } override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. FirebaseUserManager.getCurrentUser()?.let { goToHomeUI() } } private fun updateUserRole() { when (binding.userRoleRg.checkedRadioButtonId) { R.id.adminRb -> { loginViewModel.updateUserRole(UserRole.ADMIN) saveRoleLocally(UserRole.ADMIN) } R.id.userRb -> { loginViewModel.updateUserRole(UserRole.USER) saveRoleLocally(UserRole.USER) } } } private fun goToHomeUI() { startActivity(Intent(this@LoginActivity, MainActivity::class.java)) finish() } companion object { private const val TAG = "LoginActivity" } }<file_sep>/app/src/main/java/app/chintan/naturist/util/FirebaseUserManager.kt package app.chintan.naturist.util import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase object FirebaseUserManager { private var auth: FirebaseAuth = Firebase.auth fun getAuth() = auth fun getCurrentUser() = auth.currentUser fun getUserId() = auth.uid }<file_sep>/app/src/main/java/app/chintan/naturist/ui/profile/ProfileViewModel.kt package app.chintan.naturist.ui.profile import androidx.lifecycle.ViewModel class ProfileViewModel : ViewModel() { }<file_sep>/app/src/main/java/app/chintan/naturist/ui/blog/PostListFragment.kt package app.chintan.naturist.ui.blog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import android.widget.Toast import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import app.chintan.naturist.R import app.chintan.naturist.databinding.FragmentPostListBinding import app.chintan.naturist.model.Post import app.chintan.naturist.model.UserRole import app.chintan.naturist.ui.adapter.PostListAdapter import app.chintan.naturist.util.Constants.ROLE_KEY import app.chintan.naturist.util.State import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import javax.inject.Inject @AndroidEntryPoint class PostListFragment : Fragment() { private val postViewModel: PostViewModel by activityViewModels() private var _binding: FragmentPostListBinding? = null @Inject lateinit var prefDataStore: DataStore<Preferences> // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { _binding = FragmentPostListBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpOnClick() setUpObserver() loadPosts() checkUserRole() } private fun setUpObserver() { postViewModel.postList.observe(viewLifecycleOwner, Observer { when (it) { is State.Success -> { updateBlogListUI(it.data) binding.progressBar.visibility = GONE } is State.Error -> { Toast.makeText(activity, it.message, Toast.LENGTH_SHORT).show() binding.progressBar.visibility = GONE } is State.Loading -> binding.progressBar.visibility = VISIBLE } }) } private fun updateBlogListUI(data: List<Post>) { val adapter = PostListAdapter(data) { val clickedPost = it as Post postViewModel.setSelectedPost(clickedPost) findNavController().navigate(R.id.action_navigation_post_list_to_postDetailFragment) } binding.postRcv.adapter = adapter } private fun loadPosts() { postViewModel.getPosts() } private fun setUpOnClick() { binding.createPostFab.setOnClickListener { findNavController().navigate(R.id.action_navigation_post_list_to_createPostFragment) } } private fun checkUserRole() { lifecycleScope.launch { readUserRole().collect { if (it == UserRole.ADMIN.name) { binding.createPostFab.visibility = VISIBLE } else { binding.createPostFab.visibility = GONE } } } } private fun readUserRole(): Flow<String> = prefDataStore.data .map { currentPreferences -> // Lets fetch the data from our DataStore by using the same key which we used earlier for storing the data. val name = currentPreferences[ROLE_KEY] ?: "" name } }<file_sep>/app/src/main/java/app/chintan/naturist/repository/PostRepository.kt package app.chintan.naturist.repository import android.graphics.Bitmap import app.chintan.naturist.model.Post import app.chintan.naturist.util.Constants.POST_COLLECTION import app.chintan.naturist.util.State import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.ktx.Firebase import com.google.firebase.storage.ktx.storage import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.onFailure import kotlinx.coroutines.channels.trySendBlocking import kotlinx.coroutines.flow.* import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.tasks.await import java.io.ByteArrayOutputStream import kotlin.coroutines.resumeWithException class PostRepository { private val postCollectionRef = FirebaseFirestore.getInstance().collection(POST_COLLECTION) @ExperimentalCoroutinesApi fun getPosts(): Flow<State<List<Post>>> = callbackFlow { // Registers callback to firestore, which will be called on new events val subscription = postCollectionRef?.addSnapshotListener { snapshot, _ -> if (snapshot == null) { return@addSnapshotListener } // Sends events to the flow! Consumers will get the new events trySendBlocking(State.success(snapshot.toObjects(Post::class.java))) .onFailure { throwable -> throwable?.message?.let { State.error<String>(it) } } } // The callback inside awaitClose will be executed when the flow is // either closed or cancelled. // In this case, remove the callback from Firestore awaitClose { subscription.remove() } } fun addPost(post: Post) = flow<State<String>> { emit(State.loading()) post.id = System.currentTimeMillis() val userRef = postCollectionRef.document(post.id.toString()).set(post).await() emit(State.success("Post Added")) }.catch { emit(State.error(it.message.toString())) }.flowOn(Dispatchers.IO) fun likePost(postId: String, uid: String) = flow<State<DocumentReference>> { emit(State.loading()) val washingtonRef = postCollectionRef.document(postId) washingtonRef.update("favourite", FieldValue.arrayUnion(uid)) emit(State.success(washingtonRef)) }.catch { emit(State.error(it.message.toString())) }.flowOn(Dispatchers.IO) @ExperimentalCoroutinesApi suspend fun uploadImage(bitmap: Bitmap) = suspendCancellableCoroutine<State<String>> { continuation -> val storage = Firebase.storage val storageRef = storage.reference val ref = storageRef.child("images/mountains${System.currentTimeMillis()}.jpg") val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos) val data = baos.toByteArray() val uploadTask = ref.putBytes(data) uploadTask.continueWithTask { task -> if (!task.isSuccessful) { task.exception?.let { continuation.resumeWithException(it) } } ref.downloadUrl }.addOnCompleteListener { task -> if (task.isSuccessful) { val downloadUri = task.result continuation.resume(State.success(downloadUri.toString()), null) } else { continuation.resume(State.error("Uploading Failed"), null) } } } }<file_sep>/app/src/main/java/app/chintan/naturist/ui/blog/CreatePostFragment.kt package app.chintan.naturist.ui.blog import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.launch import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import app.chintan.naturist.databinding.FragmentPostCreateBinding import app.chintan.naturist.model.Post import app.chintan.naturist.util.State import coil.load import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class CreatePostFragment : Fragment() { private val postViewModel: PostViewModel by viewModels() private var _binding: FragmentPostCreateBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { _binding = FragmentPostCreateBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpOnClick() setUpObserver() } private fun setUpObserver() { postViewModel.selectedImageBitmap.observe(viewLifecycleOwner, { when (it) { is State.Success -> binding.thumbnailIv.load(it.data) is State.Error -> Log.e(TAG, it.message) } }) postViewModel.uploadImageLiveData.observe(viewLifecycleOwner, { when (it) { is State.Success -> createPost(it.data) is State.Error -> Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT) .show() is State.Loading -> binding.progressBar.visibility = View.VISIBLE } }) postViewModel.addPostLiveData.observe(viewLifecycleOwner, { when (it) { is State.Success -> { binding.progressBar.visibility = View.GONE findNavController().popBackStack() Toast.makeText(requireContext(), it.data, Toast.LENGTH_SHORT).show() } is State.Error -> { binding.progressBar.visibility = View.GONE Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } is State.Loading -> binding.progressBar.visibility = View.VISIBLE } }) } private fun createPost(url: String) { postViewModel.addPost(Post(imageUrl = url, title = binding.titleTil.editText?.text.toString(), description = binding.descTil.editText?.text.toString())) } private fun setUpOnClick() { binding.thumbnailIv.setOnClickListener { openCamera() } binding.submitBt.setOnClickListener { validateDataAndSubmit() } } private fun validateDataAndSubmit() { if (postViewModel.selectedImageBitmap.value == null || postViewModel.selectedImageBitmap.value is State.Error || postViewModel.getImageBitmap() == null) { Toast.makeText(requireContext(), "Select Valid Image", Toast.LENGTH_SHORT).show() return } if (binding.titleTil.editText?.text.toString().length < 2) { binding.titleTil.error = "Enter Valid Title" return } if (binding.descTil.editText?.text.toString().length < 10) { binding.descTil.error = "Enter Valid Description" return } postViewModel.getImageBitmap()?.let { postViewModel.uploadImage(it) } } private val takePhoto = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) { postViewModel.setImageBitmap(it) } private fun openCamera() { takePhoto.launch() } companion object { const val TAG = "CreatePostFragment" } }<file_sep>/app/src/main/java/app/chintan/naturist/model/Post.kt package app.chintan.naturist.model import java.util.ArrayList data class Post( var id: Long = 0, var imageUrl: String? = null, var title: String? = null, var description: String? = null, var favourite: ArrayList<String>? = null, ) <file_sep>/app/src/main/java/app/chintan/naturist/util/Constants.kt package app.chintan.naturist.util import androidx.datastore.preferences.core.stringPreferencesKey object Constants { const val USER_COLLECTION = "users" const val POST_COLLECTION = "posts" val ROLE_KEY = stringPreferencesKey("ROLE") }<file_sep>/app/src/main/java/app/chintan/naturist/model/UserProfile.kt package app.chintan.naturist.model data class UserProfile(var uid: String? = null, var role: UserRole? = null) enum class UserRole { ADMIN, USER }<file_sep>/app/src/main/java/app/chintan/naturist/repository/UserRepository.kt package app.chintan.naturist.repository import app.chintan.naturist.model.UserProfile import app.chintan.naturist.util.Constants.POST_COLLECTION import app.chintan.naturist.util.Constants.USER_COLLECTION import app.chintan.naturist.util.State import com.google.firebase.firestore.FirebaseFirestore import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.tasks.await class UserRepository { private val userCollectionRef = FirebaseFirestore.getInstance().collection(USER_COLLECTION) fun addUser(user: UserProfile) = flow<State<String>> { emit(State.loading()) val userRef = userCollectionRef.document(user.uid.toString()).set(user).await() emit(State.success("User Updated")) }.catch { emit(State.error(it.message.toString())) }.flowOn(Dispatchers.IO) }<file_sep>/app/src/main/java/app/chintan/naturist/ui/adapter/PostListAdapter.kt package app.chintan.naturist.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import app.chintan.naturist.databinding.PostItemBinding import app.chintan.naturist.model.Post import coil.load class PostListAdapter(private val list: List<Post>, val adapterOnClick: (Any) -> Unit) : RecyclerView.Adapter<PostListAdapter.BlogItemView>() { inner class BlogItemView(private val binding: PostItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(post: Post) { binding.postTitle.text = post.title binding.postDesc.text = post.description binding.postImage.load(post.imageUrl) binding.root.setOnClickListener { adapterOnClick(post) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BlogItemView = BlogItemView( PostItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override fun getItemCount(): Int = list.size override fun onBindViewHolder(holder: BlogItemView, position: Int) = holder.bind(list[position]) }<file_sep>/app/src/main/java/app/chintan/naturist/di/RepositoryModule.kt package app.chintan.naturist.di import app.chintan.naturist.repository.PostRepository import app.chintan.naturist.repository.UserRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object RepositoryModule { @Provides @Singleton fun provideUserRepository() = UserRepository() @Provides @Singleton fun providePostRepository() = PostRepository() }<file_sep>/app/src/main/java/app/chintan/naturist/ui/profile/ProfileFragment.kt package app.chintan.naturist.ui.profile import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import app.chintan.naturist.databinding.FragmentProfileBinding import app.chintan.naturist.ui.login.LoginActivity import app.chintan.naturist.util.FirebaseUserManager import app.chintan.naturist.util.UserSessionManager import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ProfileFragment : Fragment() { private var _binding: FragmentProfileBinding? = null private lateinit var userSessionManager: UserSessionManager // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { _binding = FragmentProfileBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) userSessionManager = UserSessionManager(requireActivity()) setUpOnClick() } private fun setUpOnClick() { binding.logoutBt.setOnClickListener { signOut() } } private fun signOut() { // Firebase sign out FirebaseUserManager.getAuth().signOut() // Google sign out userSessionManager.googleSignInClient.signOut() startActivity(Intent(requireActivity(), LoginActivity::class.java)) requireActivity().finish() } }<file_sep>/app/src/main/java/app/chintan/naturist/ui/login/LoginViewModel.kt package app.chintan.naturist.ui.login import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.chintan.naturist.model.UserProfile import app.chintan.naturist.model.UserRole import app.chintan.naturist.repository.UserRepository import app.chintan.naturist.util.FirebaseUserManager import app.chintan.naturist.util.State import com.google.firebase.auth.GoogleAuthProvider import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor(private val userRepository: UserRepository) : ViewModel() { private val _firebaseAuthLiveData = MutableLiveData<State<String>>() val firebaseAuthLiveData: LiveData<State<String>> = _firebaseAuthLiveData private val _updateUserRoleLiveData = MutableLiveData<State<String>>() val updateUserRoleLiveData: LiveData<State<String>> = _updateUserRoleLiveData fun firebaseAuthWithGoogle(idToken: String) { _firebaseAuthLiveData.postValue(State.loading()) val credential = GoogleAuthProvider.getCredential(idToken, null) FirebaseUserManager.getAuth().signInWithCredential(credential) .addOnCompleteListener() { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success") _firebaseAuthLiveData.postValue(State.success("Account Verified")) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.exception) _firebaseAuthLiveData.postValue(State.error(task.exception?.message.toString())) } } } fun updateUserRole(userRole: UserRole) { _updateUserRoleLiveData.postValue(State.loading()) FirebaseUserManager.getCurrentUser().let { val userProfile = UserProfile() userProfile.uid = it?.uid userProfile.role = userRole viewModelScope.launch(Dispatchers.IO) { userRepository.addUser(userProfile).collect { addUserState -> when (addUserState) { is State.Success -> { if (addUserState.data.isEmpty()) { _updateUserRoleLiveData.postValue(State.error("Something went wrong")) } else { _updateUserRoleLiveData.postValue(State.success(addUserState.data)) } } is State.Error -> _updateUserRoleLiveData.postValue(State.error(addUserState.message)) is State.Loading -> _updateUserRoleLiveData.postValue(State.loading()) } } } } } companion object { private const val TAG = "LoginViewModel" } }<file_sep>/README.md # Naturist ***You can Install the Sample app by clicking below 👇*** [![Naturist App](https://img.shields.io/badge/Naturist-APK-green)](https://github.com/chintanrparmar/Naturist/blob/main/sample-app.apk?raw=true) ## About A Blogging app where you can take click the picture and write about it and post in simple steps. ## Built With - [Kotlin](https://kotlinlang.org/) - First class and official programming language for Android development. - [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html) - For asynchronous and more.. that sequentially emits values and completes normally or with an exception. - [Kotlin Flow](https://kotlinlang.org/docs/flow.html) - To return multiple asynchronously computed values.. - [Android Architecture Components](https://developer.android.com/topic/libraries/architecture) - Collection of libraries that help you design robust, testable, and maintainable apps. - [LiveData](https://developer.android.com/topic/libraries/architecture/livedata) - Data objects that notify views when the underlying database changes. - [ViewModel](https://developer.android.com/topic/libraries/architecture/viewmodel) - Stores UI-related data that isn't destroyed on UI changes. - [ViewBinding](https://developer.android.com/topic/libraries/view-binding) - Generates a binding class for each XML layout file present in that module and allows you to more easily write code that interacts with views. - [Jetpack Navigation Component](https://developer.android.com/guide/navigation) - Android Jetpack's Navigation component helps you implement navigation easily. - [Cloud Firestore](https://firebase.google.com/products/firestore/) - Cloud Firestore is a NoSQL document database that lets you easily store, sync, and query data. - [Firebase Authentication](https://firebase.google.com/products/auth) - Firebase Authentication aims to make building secure authentication systems easy. - [Firebase Storage](https://firebase.google.com/products/storage) - Cloud Storage is designed to help you quickly and easily store photos. - [Coil-kt](https://coil-kt.github.io/coil/) - An image loading library for Android backed by Kotlin Coroutines. - [Jetpack Datastore](https://developer.android.com/topic/libraries/architecture/datastore) - DataStore uses Kotlin coroutines and Flow to store data asynchronously, consistently, and transactionally. - [Material Components for Android](https://github.com/material-components/material-components-android) - Modular and customizable Material Design UI components for Android.## Switch to another file ## Contact If you need any help, feel free to connect. [Dev Profile](https://chintanparmar.com) <file_sep>/app/src/main/java/app/chintan/naturist/ui/blog/PostViewModel.kt package app.chintan.naturist.ui.blog import android.graphics.Bitmap import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.chintan.naturist.model.Post import app.chintan.naturist.repository.PostRepository import app.chintan.naturist.util.FirebaseUserManager import app.chintan.naturist.util.State import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class PostViewModel @Inject constructor(private val postRepository: PostRepository) : ViewModel() { private val _postList = MutableLiveData<State<List<Post>>>() val postList: LiveData<State<List<Post>>> = _postList private val _favouritePostList = MutableLiveData<State<List<Post>>>() val favouritePostList: LiveData<State<List<Post>>> = _favouritePostList private val _addPostLiveData = MutableLiveData<State<String>>() val addPostLiveData: LiveData<State<String>> = _addPostLiveData private val _likePostLiveData = MutableLiveData<State<String>>() val likePostLiveData: LiveData<State<String>> = _likePostLiveData private val _selectedPostLiveData = MutableLiveData<State<Post>>() val selectedPostLiveData: LiveData<State<Post>> = _selectedPostLiveData private val _uploadImageLiveData = MutableLiveData<State<String>>() val uploadImageLiveData: LiveData<State<String>> = _uploadImageLiveData private val _selectedImageBitmap = MutableLiveData<State<Bitmap>>() val selectedImageBitmap: LiveData<State<Bitmap>> = _selectedImageBitmap fun uploadImage(bitmap: Bitmap) { viewModelScope.launch(Dispatchers.IO) { _uploadImageLiveData.postValue(State.loading()) val uploadImageState = postRepository.uploadImage(bitmap) _uploadImageLiveData.postValue(uploadImageState) } } fun addPost(post: Post) { viewModelScope.launch(Dispatchers.IO) { postRepository.addPost(post).collect { when (it) { is State.Success -> { if (it.data != null) { _addPostLiveData.postValue(State.success("Added Successfully")) } else { _addPostLiveData.postValue(State.success("Something went wrong")) } } is State.Error -> _addPostLiveData.postValue(State.error(it.message)) is State.Loading -> _addPostLiveData.postValue(State.loading()) } } } } fun likePost(postId: String, uid: String) { viewModelScope.launch(Dispatchers.IO) { postRepository.likePost(postId, uid).collect { when (it) { is State.Success -> { if (it.data != null) { _likePostLiveData.postValue(State.success("Added Successfully")) } else { _likePostLiveData.postValue(State.success("Something went wrong")) } } is State.Error -> _likePostLiveData.postValue(State.error(it.message)) is State.Loading -> _likePostLiveData.postValue(State.loading()) } } } } fun getPosts() { viewModelScope.launch(Dispatchers.IO) { postRepository.getPosts().collect { when (it) { is State.Success -> { if (it.data.isNullOrEmpty()) { _postList.postValue(State.error("No Data Found")) } else { _postList.postValue(State.success(it.data)) } } is State.Error -> _postList.postValue(State.error(it.message)) is State.Loading -> _postList.postValue(State.loading()) } } } } fun getFavouritePosts() { viewModelScope.launch(Dispatchers.IO) { postRepository.getPosts().collect { when (it) { is State.Success -> { if (it.data.isNullOrEmpty()) { _favouritePostList.postValue(State.error("No Data Found")) } else { val filterList= it.data.filter { post -> post.favourite?.contains(FirebaseUserManager.getUserId()) == true } _favouritePostList.postValue(State.success(filterList)) } } is State.Error -> _favouritePostList.postValue(State.error(it.message)) is State.Loading -> _favouritePostList.postValue(State.loading()) } } } } fun setSelectedPost(post: Post?) { if (post != null) { _selectedPostLiveData.postValue(State.success(post)) } else { _selectedPostLiveData.postValue(State.error("Invalid Post Data")) } } fun setImageBitmap(bitmap: Bitmap?) { if (bitmap == null) { _selectedImageBitmap.postValue(State.error("Invalid Image")) return } _selectedImageBitmap.postValue(State.success(bitmap)) } fun getImageBitmap(): Bitmap? = when (selectedImageBitmap.value) { is State.Success -> (selectedImageBitmap.value as State.Success<Bitmap>).data else -> null } }<file_sep>/app/src/main/java/app/chintan/naturist/di/DataStoreModule.kt package app.chintan.naturist.di import android.app.Application import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStore import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class PrefDataStoreModule { @Provides @Singleton fun getDataStore(app: Application) = getDataStoreInstance(app) } val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "naturistDB") fun getDataStoreInstance(androidApplication: Application): DataStore<Preferences> = androidApplication.dataStore <file_sep>/app/src/main/java/app/chintan/naturist/util/UserSessionManager.kt package app.chintan.naturist.util import android.app.Activity import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions class UserSessionManager(activity: Activity) { // Configure Google Sign In private val gso: GoogleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken("<PASSWORD>") .requestEmail() .build() val googleSignInClient: GoogleSignInClient = GoogleSignIn.getClient(activity, gso) }
08a44f2604a97cd04668a79a9c9938f097c17fc7
[ "Markdown", "Kotlin" ]
21
Kotlin
chintanrparmar/Naturist
86519839299b012a51cca61069ecb4fee542e414
b56e20a401715cdd4ec25e7601c4ac6af454c966
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { StyleSheet, View, Dimensions, Image } from 'react-native'; var { height, width } = Dimensions.get('window'); export default class Light extends Component { render() { const { color } = this.props; let light; if (color === 'red') { light = ( <Image style={styles.light} source={require('../../assets/led-circle-red.png')} /> ); } else { light = ( <Image style={styles.light} source={require('../../assets/led-circle-green.png')} /> ); } return <View style={styles.container}>{light}</View>; } } const styles = StyleSheet.create({ container: { paddingLeft: 10, paddingRight: 10 }, light: { width: width / 13, height: width / 13 } }); <file_sep>import React, { Component } from 'react'; import { StyleSheet, View, Text } from 'react-native'; export default class Command extends Component { render() { return ( <View style={styles.container}> <Text style={styles.text}>{this.props.command}</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 4, backgroundColor: '#000000', borderTopRightRadius: 19, borderTopLeftRadius: 19, alignItems: 'center', justifyContent: 'center' }, text: { color: '#FFF', fontSize: 22 } }); <file_sep>import React, { Component } from 'react'; import { StyleSheet, Text, View, Dimensions, Image } from 'react-native'; import * as Progress from 'react-native-progress'; import AwesomeButton from 'react-native-really-awesome-button'; import TopScrews from './TopScrews'; import BottomScrews from './BottomScrews'; import Command from './Command'; import ActionButton from '../Actions/ActionButton'; import Light from './Light'; var { height, width } = Dimensions.get('window'); export default class DashBoard extends Component { constructor(props) { super(props); this.state = { command: 'Waiting...', gameStatus: '', progress: 1, error: 0, components: [], level: 2 }; const socket = this.props.navigation.getParam('socket'); const gameStarter = this.props.navigation.getParam('gameStarter'); if (gameStarter == true) { console.log('game begonnen'); socket.emit('startGame', 1, this.props.navigation.getParam('room')); } else { console.log('game niet begonnen'); } socket.on('win', () => { this.setState({ gameStatus: 'win' }); }); socket.on('nextLevel', () => { this.setState({ command: 'Waiting...', gameStatus: '', progress: 1, error: 0, components: [], level: this.state.level + 1 }); this.animate(); }); socket.on('time', err => { this.setState( { error: err }, () => { if (this.state.error == 3) { socket.emit( 'lose', this.props.navigation.getParam('room') ); } } ); }); socket.on('lose', () => { this.setState({ gameStatus: 'lost' }); }); socket.on('components', components => { this.setState({ components }); }); socket.on('command', command => { this.setState({ command, progress: 1 }); }); } componentDidMount() { this.animate(); } animate() { const interval = setInterval(() => { progress = this.state.progress - Math.random() / 50; if (progress <= 0) { socket.emit( 'time', this.state.error, this.props.navigation.getParam('room') ); progress = 1; } this.setState({ progress }); if ( this.state.gameStatus === 'win' || this.state.gameStatus === 'lost' || this.state.gameStatus === 'victory' || this.state.command == '' ) { console.log('clearing interval'); clearInterval(interval); } }, 100); } render() { let components = []; const room = this.props.navigation.getParam('room'); this.state.components.forEach(component => { let c = ( <ActionButton name={component.name} buttonName={component.buttonCommand} socket={socket} room={room} /> ); components.push(c); }); if (this.state.gameStatus === 'win' && this.state.level != 5) { return ( <View style={styles.center}> <AwesomeButton backgroundColor={'#ee0000'} backgroundDarker={'#bb0000'} backgroundShadow={'#C0C0C0'} textColor={'#F7F7F7'} width={150} onPress={() => { socket.emit('nextLevel', room); socket.emit('startGame', this.state.level, room); }} > Next level! </AwesomeButton> <Image style={styles.image} source={require('../../assets/ufo.png')} /> </View> ); } else if (this.state.gameStatus === 'win' && this.state.level == 5) { return ( <View style={styles.center}> <Text> You arrived at your home planet! Congratulations! </Text> <Image style={styles.image} source={require('../../assets/planet.png')} /> </View> ); } else if (this.state.gameStatus === 'lost') { return ( <View style={styles.center}> <Text> Game over! Time ran out and your spaceship has crashed! </Text> <Image style={styles.image} source={require('../../assets/crash.png')} /> </View> ); } else { return ( <View style={styles.container}> <TopScrews /> <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center', paddingBottom: 5 }} > {this.state.error > 2 ? ( <Light color="red" /> ) : ( <Light /> )} {this.state.error > 1 ? ( <Light color="red" /> ) : ( <Light /> )} {this.state.error > 0 ? ( <Light color="red" /> ) : ( <Light /> )} </View> <View style={styles.content}> <Command command={this.state.command} /> <Progress.Bar progress={this.state.progress} width={null} height={15} borderRadius={0} animated={true} /> <View style={{ flex: 20, backgroundColor: '#eeeeee', borderBottomRightRadius: 19, borderBottomLeftRadius: 19 }} > {components} </View> </View> <BottomScrews /> </View> ); } } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', justifyContent: 'space-between', backgroundColor: '#cccccc' }, center: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#cccccc' }, content: { flex: 18, backgroundColor: '#ffffff', marginLeft: width / 13, marginRight: width / 13, borderRadius: 25, borderWidth: 6, borderColor: '#7f7f7f', elevation: 4 }, image: { width: width / 3, height: width / 3, marginTop: 35 } });
be5d10ae91589e934d72bebbc0de9f8a8ac611b4
[ "JavaScript" ]
3
JavaScript
MichielTondeur/1819-WMD-Project
c241433f8f21e1a2f0b521f7a8d934423cc6bd03
bc4ced98d8e6aa6eb906ec256c60f694831c3c59
refs/heads/master
<repo_name>EvanGreaney/MobileAppProjectV2<file_sep>/README.md # MobileAppProjectV2 My app is a simple YuGiOh duel assister that keeps track of the players like points and can roll dice and flip coins depending the users needs Coin flip The coin flip generates a random between 0 and 1 that deping on the result prints out heads or tails Dice Roll The dice roll generates a random number between 1 and 6 and depending on the result, prints out a dice image of 1-6 Calculator Both playes start with 8000 life ponts and the users decide whether to add or subtract certain values based on the cards they play Each button with a number represents the number being able to ve subtracted or added to the life point total the equals button calculates the result so far when pressed and the new game button resets the game back to 8000 <file_sep>/MobileAppProjectV2/MobileAppProjectV2/DicePage.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace MobileAppProjectV2 { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class DicePage : ContentPage { public DicePage () { InitializeComponent (); } //Dice Roll method that when called generates a random number //and depending on the number displays a certain image of a dice private void DiceRoller_Clicked(object sender, EventArgs e) { //random number generator Random r = new Random(); int NumSelect = r.Next(0, 6); if (NumSelect == 1) { DiceImage.Source = ImageSource.FromResource("MobileAppProjectV2.Images.inverted_dice_1.png"); Result.Text = "One"; } else if (NumSelect == 2) { DiceImage.Source = ImageSource.FromResource("MobileAppProjectV2.Images.inverted_dice_2.png"); Result.Text = "Two"; } else if (NumSelect == 3) { DiceImage.Source = ImageSource.FromResource("MobileAppProjectV2.Images.inverted_dice_3.png"); Result.Text = "Three"; } else if (NumSelect == 4) { DiceImage.Source = ImageSource.FromResource("MobileAppProjectV2.Images.inverted_dice_4.png"); Result.Text = "Four"; } else if (NumSelect == 5) { DiceImage.Source = ImageSource.FromResource("MobileAppProjectV2.Images.inverted_dice_5.png"); Result.Text = "Five"; } else if (NumSelect == 6) { DiceImage.Source = ImageSource.FromResource("MobileAppProjectV2.Images.inverted_dice_6.png"); Result.Text = "Six"; } else { DiceImage.Source = ImageSource.FromResource("MobileAppProjectV2.Images.inverted_dice_6.png"); Result.Text = "Six"; } } } }<file_sep>/MobileAppProjectV2/MobileAppProjectV2/CalcPage.xaml.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace MobileAppProjectV2 { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CalcPage : ContentPage { //variables string myoperator = " "; int mainNumber1 = 0, mainNumber2 = 0; int resultNumber1 = 0, resultNumber2 = 0; public CalcPage() { InitializeComponent(); //setting the values to 8000 at the beginning of each new game resultText.Text = "8000"; resultText2.Text = "8000"; //converting the .text values of resultText to ints resultNumber1 = Convert.ToInt32(resultText.Text); resultNumber2 = Convert.ToInt32(resultText2.Text); } //method that sets up the grid private void setUpGrid() { var Grid = new Grid(); GridSetUp.ColumnDefinitions = new ColumnDefinitionCollection(); // rows GridSetUp.RowDefinitions = new RowDefinitionCollection(); } //method that when called sets the number for the red side based on the text value of the button pressed void OnSelectNumberRed(object sender, EventArgs e) { Button button = (Button)sender; int numberPressed = 0; numberPressed = Convert.ToInt32(button.Text); mainNumber1 = numberPressed; } //method that when called sets the number for the blue side based on the text value of the button pressed void OnSelectNumberBlue(object sender, EventArgs e) { Button button = (Button)sender; int numberPressed = 0; numberPressed = Convert.ToInt32(button.Text); mainNumber2 = numberPressed; } //method that when called sets the operator for the red side based on the text value of the button pressed void OnSelectOperaterRed(object sender, EventArgs e) { Button button = (Button)sender; string pressed = button.Text; myoperator = pressed; } //method that when called sets the number for the blue side based on the text value of the button pressed void OnSelectOperaterBlue(object sender, EventArgs e) { Button button = (Button)sender; string pressed = button.Text; myoperator = pressed; } //method that when called sets the result numbers for both sides when the new game button is pressed private void OnSelectNewGame(object sender, EventArgs e) { resultText.Text = "8000"; resultText2.Text = "8000"; resultNumber1 = 8000; resultNumber2 = 8000; } //method that calculates the result currently to the blue side void OnCalculateBlue(object sender, EventArgs e) { var result = 0; result = OperatorHelper.Calculate(mainNumber2, resultNumber2, myoperator); String stringresult = Convert.ToString(result); resultNumber2 = Convert.ToInt32(stringresult); resultText.Text = stringresult; } //method that calculates the result currently to the blue side void OnCalculateRed(object sender, EventArgs e) { var result = 0; result = OperatorHelper.Calculate(mainNumber1, resultNumber1, myoperator); String stringresult = Convert.ToString(result); resultNumber1 = Convert.ToInt32(stringresult); resultText2.Text = stringresult; } } }<file_sep>/MobileAppProjectV2/MobileAppProjectV2/OperatorHelper.cs using System; using System.Collections.Generic; using System.Text; namespace MobileAppProjectV2 { //a class that when called has one method called calculate that based on the values entered will return the result class OperatorHelper { public static int Calculate(int value1, int value2, string myoperator) { int result = value2; switch (myoperator) { case "+": result += value1; break; case "-": result -= value1; break; } return result; } } } <file_sep>/MobileAppProjectV2/MobileAppProjectV2/CoinPage.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace MobileAppProjectV2 { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CoinPage : ContentPage { public CoinPage() { InitializeComponent(); } //coin Flip method that when called generates a random number //and depending on the number displays a certain image of a coin private void CoinFlipper_Clicked(object sender, EventArgs e) { //random number generator Random r = new Random(); int NumSelect = r.Next(0,2); if (NumSelect == 1) { CoinImage.Source = ImageSource.FromResource("MobileAppProjectV2.Images.coin_tex_head.png"); Result.Text = "Heads"; } else { CoinImage.Source = ImageSource.FromResource("MobileAppProjectV2.Images.coin_tex_tail.png"); Result.Text = "Tails"; } } } }
93b2c044e27db1e75eda7f86e903886c650ff643
[ "Markdown", "C#" ]
5
Markdown
EvanGreaney/MobileAppProjectV2
97547f113a5add22db80b4e0fcbb6d9c713b9812
6bc61f44ef72651f8207dc555c943daa2fa0082b
refs/heads/master
<file_sep>module LootStatusWidgets class LineWidget < AllodsWidget build do |options| unless options.nil? AdminLineWidget if options[:user] && options[:user].admin? end end def display setup! render end private def setup! super @loot_status = LootStatus.find options[:loot_status_id] @loot_machine = @loot_status.loot_machine @no_js = options[:no_js] end end class AdminLineWidget < LineWidget end end <file_sep>LootMachine.blueprint do title { Faker::Lorem.sentence 10 } description { Faker::Lorem.paragraph 2 } end <file_sep># An admin has special rights to create, update and destroy resources. He may # have users' characters join or leave group. # class Admin < ActiveRecord::Base devise :database_authenticatable, :registerable, :timeoutable, :validatable, :timeout_in => 20.minutes end <file_sep>$:.unshift(File.expand_path('./lib', ENV['rvm_path'])) require 'rvm/capistrano' require File.expand_path './config/capistrano_database_yml.rb' set :rvm_ruby_string, 'ruby-1.9.2-p290@allods' set :rvm_type, :user set :user, 'jd' set :use_sudo, false set :scm, :git set :scm_username, :git set :deploy_via, :remote_cache #set :default_environment, { #'PATH' => '/home/jd/.rvm/gems/ruby-1.9.2-p180@allods/bin:/home/jd/.rvm/gems/ruby-1.9.2-p180@global/bin:/home/jd/.rvm/rubies/ruby-1.9.2-p180/bin:$PATH', #'RUBY_VERSION' => 'ruby 1.9.2', #'GEM_HOME' => '/home/jd/.rvm/gems/ruby-1.9.2-p180@allods', #'GEM_PATH' => '/home/jd/.rvm/gems/ruby-1.9.2-p180@allods', #'BUNDLE_PATH' => '/home/jd/.rvm/gems/ruby-1.9.2-p180@allods' #} set :application, 'hugr.fr' set :repository, 'git://github.com/chikamichi/allods.git' set :branch, 'master' set :deploy_to, '/home/jd/allods/webapp' set :server_type, 'thin' set :application_type, 'development' set :rails_env, 'corvus' set :default_environment, {'RAILS_ENV' => 'corvus'} server "#{user}@#{application}", :app, :web, :db, :primary => true # Tasks to perform. namespace :deploy do task :start, :depends => [:restart] do if server_type == 'thin' run "RAILS_ENV=#{rails_env} thin start -C #{shared_path}/config/thin.yml -A rack" end end task :stop do if server_type == 'thin' run "RAILS_ENV=#{rails_env} thin stop -C #{shared_path}/config/thin.yml -A rack" end end task :restart, :roles => :app, :except => { :no_release => true } do if server_type == 'thin' run "RAILS_ENV=#{rails_env} thin restart -C #{shared_path}/config/thin.yml -A rack" end end end namespace :thin do desc 'Copy thin config' task :copy do run "cd #{release_path} && cp config/thin/#{rails_env}.yml #{shared_path}/config/thin.yml" end end namespace :db do desc "Database create" task :create do run "cd #{current_path} && RAILS_ENV=#{rails_env} rake db:create:all" end task :migrate do run "cd #{current_path} && RAILS_ENV=#{rails_env} rake db:migrate" end end namespace :fs do desc 'Create filesystem required folders' task :create do run "test -d #{shared_path}/log || mkdir #{shared_path}/log" run "test -d #{shared_path}/config || mkdir #{shared_path}/config" run "test -d #{shared_path}/public || mkdir #{shared_path}/public" run "test -d #{shared_path}/public/media || mkdir #{shared_path}/public/media" run "cd #{release_path}/public && ln -s #{shared_path}/public/media media" end end namespace :bundle do desc 'Install required gems' task :install do run "cd #{current_path} && bundle install" end end # Let's proceed! after 'deploy:update_code', 'fs:create' after 'deploy:symlink', 'bundle:install' #after 'bundle:install', 'db:create' after 'bundle:install', 'db:migrate' after 'deploy:symlink', 'deploy:cleanup' before 'deploy:restart', 'thin:copy' <file_sep>require File.expand_path('../boot', __FILE__) require 'rails/all' require 'pp' # If you have a Gemfile, require the gems listed there, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) if defined?(Bundler) module Allods class Application < Rails::Application config.encoding = "utf-8" config.i18n.default_locale = :fr config.filter_parameters += [:password, :password_confirmation] config.generators do |g| g.template_engine :haml g.test_framework :rspec end config.action_view.javascript_expansions[:defaults] = %w(rails underscore) config.action_view.javascript_expansions[:jquery_plugins] = %w(jquery.livequery.js jquery.dataTables.js jquery.jeditable.js jquery.typewatch.js) config.after_initialize do unless Rails.env.production? || Rails.env.corvus? require "#{Rails.root}/spec/spec_helper" end $stderr.puts 'Using default locale ' + I18n.locale.inspect end end end <file_sep>class LootStatus < ActiveRecord::Base belongs_to :character belongs_to :loot_machine has_paper_trail :only => :bump, :meta => { :bump => Proc.new { |loot_status| loot_status.bump } } # Loot actions. Given its current score and the score of the other # member of a group, the character has a loot status enforced by the # group looting strategy/scheme. STATUS = [:need, :greed] #scope :archetype, lambda { |archetype| #includes(:character).where('characters.archetype=?', archetype) #} # Compute a dependent meta. # # @param [Symbol] what :score, :status # @param [Hash] options # @option options [true, false] :force (false) whether to force the computation # def compute(what, options = {}) self.send :"compute_#{what}", options end # Number of wins, that is, sum of needs and greeds. # This value is not stored as a metada, as it is just # an addition. # # @return [Integer] # def wins need + greed end private # Personnal score computation rule: # # * score = 0 if no wins # * score = [-(2*need + greed) + loyalty] / (wins + 1) # # @param [Hash] options # @return the computed value # def compute_score(options) merge_computation_options! options score = apply_rules_for :score update_attribute(:score, score) return self.class.type_cast!(score, :as => :score) end # Status computation rule: # # if the score is greater or equal to the max of the scores of all related # LootStatus records, then the status is 'need'; otherwise, it is 'greed'. # # @param [Hash] options # @return the computed value # def compute_status(options) merge_computation_options! options status = apply_rules_for :status update_attribute(:status, status) return self.class.type_cast!(status, :as => :status) end # Default options for the computations helpers. # # @param [Hash] options # @option options [true, false] :force (false) # and refresh the value # @return [Hash] # def merge_computation_options!(options) { :force => false }.merge(options) end # Defines and applies the rules. # # @param [Symbol] what :score, :status # @raise [ArgumentError] if no rules are matched # def apply_rules_for(what) case what when :score ( -2 * need - greed + loyalty ) when :status score >= loot_machine.loot_statuses.map(&:score).max ? 'need' : 'greed' else raise ArgumentError, "Computation rules for #{what} are not defined." end end # Type cast a value, given an attribute type # # @example # # type_cast!(1, :as => :score) # => 1.0 for :score is a Float # # @param [Object] value # @param [Hash] options # @option options [Symbol] :as # @return [Object] the type casted value # def self.type_cast!(value, options) self.columns_hash[options[:as].to_s].type_cast(value) end end <file_sep>User.create(:email => '<EMAIL>', :password => '<PASSWORD>') <file_sep>// Place your application-specific JavaScript functions and classes here // This file is automatically included by javascript_include_tag :defaults (function($) { $(document).ready(function() { /** * Fade flash messages out. */ $('.flash') .effect('slide', function() { $(this).delay(5000).fadeOut('slow', function() { $(this).remove(); }); }); /** * Allods namespace. Provides helpers and the like. Here's the sh*t. */ Allods = (function() { var _conf = { colors: { maxScore: '#446EFF', max: '#87CBFF', wait: '#C5D2FF' }, dataTable: { // inspect http://www.datatables.net/usage/ and related submenus bRetrieve: true, bInfo: false, bLengthChange: false, bPaginate: false, oLanguage: { sSearch: '', sZeroRecords: 'Aucun résultat.' } }, typeWatch: { wait: 350, captureLength: 1 } }; this.pad = function(number, length) { var str = '' + number; while (str.length < length) { str = '0' + str; } return str; }; this.randInteger = function(max, pad) { return this.pad(Math.floor(Math.random() * max), pad); }; return { setBackground: function() { $('body').css('background', 'url(../images/bg' + randInteger(1, 2) + '.jpg) no-repeat center center fixed'); }, /** * Turn a static table into a LootMachine console. */ LMConsole: function(elt) { $(elt).dataTable(_conf.dataTable); }, /** * On Character edit pages, dynamically display appropriate roles checkboxes * matching the current archetype. */ display_roles_radios_for: function(archetype) { $('.roles_for').fadeOut('fast', function() { $('.roles_for[data-archetype=' + archetype + ']').fadeIn('fast'); }); }, /** * Dynamic filtering should trigger some status computation, based on * the scores of the filtered elements. This will outline the line(s) * with the highest score. */ compute_status: function() { var scores = $('td.score'); if (!scores.length) { return null; } scores = _(scores).map(function(score) { return $(score).data('score'); }); max = _.max(scores); min = _.min(scores); $('td.score').animate({ backgroundColor: _conf.colors.wait }, 100); $('td.score[data-score=' + max + ']').animate({ backgroundColor: _conf.colors.max }, 200); $('td:not(.editable)', 'tr.loot_status_line[data-score=' + max + ']').animate({ backgroundColor: _conf.colors.max }, 200); }, /** * Reset styles which were set by compute_status() */ resetFilteringStyle: function() { $('td:not(.editable)', 'tr.loot_status_line').css('background', 'none'); $('td.score').css('background', 'none'); }, /** * When filtering is on, display a cross icon to reset filtering. */ appendCloseConsoleFilter: function(lm_console) { if (!$('#closeConsoleFilter').length) { elt = '<span id="closeConsoleFilter"><img src="/images/close.svg" /></span>'; $('input', '.dataTables_filter').after(elt); $('#closeConsoleFilter img').live('click', function() { Allods.removeCloseConsoleFilter(lm_console); }); } }, /** * Actions to be taken when reseting filtering. */ removeCloseConsoleFilter: function(lm_console) { $('input', '.dataTables_filter').val(''); $('#closeConsoleFilter').fadeOut('fast', function() { $(this).remove(); }); // don't forget to reset filtering lm_console.dataTable().fnFilter(''); this.resetFilteringStyle(); } }; })(); // I'll keep using a static bg for the moment, no good pics in stock //Allods.setBackground(); /** * Raise LootMachine consoles to live. */ $('.loot_machine_console').livequery(function(){ var that = $(this); Allods.LMConsole(that); }); /** * If necessary, make LootStatus lines editable (for admin, that is). * * Separated from the previous livequery, so that a LootStatus line * can be rendered on its own. */ $('td.editable', '.loot_machine_console[data-admin=true]').livequery(function() { var that = $(this) , ls_line = that.parents('.loot_status_line') , lm_console = ls_line.parents('.loot_machine_console') , content = lm_console.children('tbody'); that.editable(that.data('url_for_event'), { callback: function( sValue, y ) { var lm_console = $(this).parents('.loot_machine_console') , grid = lm_console.dataTable(); // I don't understand why, but at this point, the dataTable // features are lost, yet the object remains… // @todo: try not to set bRetrieve, and call dataTable here (it // should recreate it). Try to call fnDraw() as well… grid.fnDestroy(); content.replaceWith(sValue); Allods.LMConsole(lm_console); }, submitdata: function ( value, settings ) { // @todo: add a nice loader while processing the table return { loot_status_id: ls_line.data('id'), loot_machine_id: ls_line.data('machine_id'), loot_status_metadata: that.data('type') }; }, cssclass: 'editable', height: "12px" }); }); /** * Raise Character's edit pages to live. */ $('.archetype') .livequery(function() { var that = $(this) , selected = $(':selected', that); if (selected.length) { Allods.display_roles_radios_for(selected.val()); } }) .livequery('change', function(e) { var that = $(this) , archetype = that.val(); Allods.display_roles_radios_for(archetype); }); /** * Monitor what's been typed into a LootMachine console's filtering * input and behave. */ $('.dataTables_filter input[type=text]').livequery('keyup', function() { var that = $(this) , lm_console = $(that.parent().siblings('.loot_machine_console')); if (that.val().length > 0) { Allods.appendCloseConsoleFilter(lm_console); } else { Allods.removeCloseConsoleFilter(lm_console); } Allods.resetFilteringStyle(); }).livequery(function() { $(this).typeWatch($.extend(Allods.conf, { callback: Allods.compute_status })); }); /** * Raise plusOne links to live. * * They will trigger a request to increment selected LootStatus lines * counters. */ $('a.plusOne').livequery('click', function(e) { e.preventDefault(); var that = $(this) , lm_console = that.parents('.loot_machine_console') , content = lm_console.children('tbody') , grid = lm_console.dataTable() , ids = _.map($('input[type=checkbox]:checked.' + that.data('type')), function(cb) { return $(cb).parents('.loot_status_line').data('id'); }); $.post( that.attr('href'), { 'ids[]': ids, loot_status_metadata: that.data('type'), loot_machine_id: lm_console.data('id') }, function(data) { grid.fnDestroy(); content.replaceWith(data); Allods.LMConsole(lm_console); } ); }); }); })(jQuery); <file_sep>class Bootstrap < ActiveRecord::Migration def self.up # Users own characters create_table :characters do |t| t.string :nickname, :null => false t.integer :level, :null => false t.integer :user_id t.timestamps end # A loot machine is a raid, an event… which gathers # characters for several runs, and keep tracks of their loots create_table :loot_machines do |t| t.string :title, :null => false t.text :description t.string :metadata end # Actually, loots are monitored through a joined model create_table :loot_statuses do |t| t.references :character t.references :loot_machine t.string :status, :null => false, :default => "need" t.integer :need, :null => false, :default => 0 t.integer :greed, :null => false, :default => 0 t.integer :loyalty, :null => false, :default => 0 t.decimal :score, :null => false, :default => 0 t.timestamps end add_index :users, :email, :unique => true add_index :users, :reset_password_token, :unique => true add_index :characters, :user_id add_index :loot_statuses, :character_id add_index :loot_statuses, :loot_machine_id end def self.down drop_table :characters drop_table :loot_machines drop_table :loot_statuses end end <file_sep>class LootStatusScoreIsAFloat < ActiveRecord::Migration def self.up change_column :loot_statuses, :score, :float, :default => 0 end def self.down change_column :loot_statuses, :score, :string end end <file_sep>class LootMachinesController < ApplicationController before_filter :authenticate_user!, :except => [:index, :show] before_filter :require_adminship, :except => [:index, :show] has_widgets do |root| if current_loot_machine root << widget('loot_machine_widgets/console', "loot_machine_console_#{current_loot_machine.id}", :loot_machine_id => current_loot_machine.id, :user => current_user) end end # @get # def index @loot_machines = LootMachine.all end # @get # def new @loot_machine = LootMachine.new @characters = Character.all end # @post # def create @loot_machine = LootMachine.new(params[:loot_machine]) respond_to do |format| if @loot_machine.save format.html { redirect_to loot_machines_url, :notice => :created! } format.json { render :json => @loot_machine, :status => :created, :location => loot_machine_url(@loot_machine) } else render_errors(format, @loot_machine.errors) end end end # @get # def show @loot_machine = current_loot_machine title! :group_title => @loot_machine.title hint! :count => @loot_machine.characters.count respond_to do |format| format.html format.json { render :json => @loot_machine } end end # @get # def edit @loot_machine = current_loot_machine @characters = Character.all end # @put # def update @loot_machine = current_loot_machine respond_to do |format| if @loot_machine.update_attributes(params[:loot_machine]) format.html { redirect_to loot_machine_url(@loot_machine), :notice => updated! } format.json { rende :json => @loot_machine, :status => :ok } else render_errors(format, @loot_machine.errors) end end end private def current_loot_machine @loot_machine = LootMachine.find(params[:loot_machine_id] || params[:id]) end end <file_sep># A LootMachine is basically a dynamic group of characters. As they take part to events # the group is involved into, like a recurring raid, the may earn loots, hence the name. class LootMachine < ActiveRecord::Base has_many :loot_statuses has_many :characters, :through => :loot_statuses, :validate => false has_paper_trail :only => :bump, :meta => { :bump => Proc.new { |loot_machine| loot_machine.bump } } validates_presence_of :title accepts_nested_attributes_for :loot_statuses, :characters, :allow_destroy => true expose_attributes :public => [:title, :rendered_description], :show => [:rendered_description], :editable => [:title, :description] markdownize! :description # Save a new version of the LootMachine. This will save versions # for each associated LootStatus as well. # # Use the #bump attribute, which value is synchronized, to match # versions between the two models. The bump attribute store the date # the bump operation is performed as a string representation of the # timestamped datetime (eg. "1298833981"). # # @example # # lm = LootMachine.last # lm.udpate_attribute # make some modifs # lm.save # # # create a new version # lm.bump! # # # ensure matching versions # lm.versions.last.bump == lm.bump # => true # lm.loot_statuses.last.versions.bump == lm.bump # => true # # @param [Hash] params ({}) # @return [Bignum] the bump timestamp # def bump!(params = {}) time = Time.now.to_i.to_s # bump the LootMachine update_attribute(:bump, time) # create versions for each LootStatus record loot_statuses.each do |loot_status| loot_status.update_attribute(:bump, time) end return time end def version_at obj = super # fetch all matching LootStatus obj.loot_statuses = Version.where(:item_type => 'LootStatus', :bump => obj.bump).map(&:reify) return obj end end <file_sep># A user is a player, who may create characters. # class User < ActiveRecord::Base devise :database_authenticatable, :lockable, :recoverable, :rememberable, :registerable, :trackable, :timeoutable, :validatable, :token_authenticatable, :timeout_in => 2.hours has_many :characters attr_accessible :email, :password, :password_confirmation # Really simple state machine so that I, Master of Puppets, can # grant special rights to the favored. # state_machine :access_level, :initial => :member do event :adminship do transition any => :admin end event :membership do transition any => :member end around_transition do |user, transition, block| if transition.from == transition.to user.log_event :invalid_access_level_change, :level => transition.event else block.call user.log_event :access_level_change, :level => transition.event end end end state_machine :status, :initial => :inactive do event :activate do transition any => :active end event :deactivate do transition any => :inactive end end private def log_message(event, metadata = nil, object = nil) case event when :access_level_change "#{email} (##{id}) has been granted #{metadata[:level]}" when :invalid_access_level_change "#{email} (##{id}) has already been granted #{metadata[:level]}, event ignored" else return nil end end end <file_sep>class ApplicationController < ActionController::Base helper :all protect_from_forgery # Ensure a user is signed-in and has an activated account before proceeding. # User activation is done by admins, user being inactive by default. # # Otherwise, redirect to the index page with a error message. # def require_active_user unless current_user.active? flash[:error] = must_be_active! redirect_to root_url end end # Ensure a user is signed-in and has adminship before proceeding. # Otherwise, redirect to the index page with a error message. # def require_adminship unless user_signed_in? && current_user.admin? flash[:error] = forbidden! redirect_to root_url end end # Defines the locales to be processed while bootstraping the page # before rendering. PAGE_KEYS = [:title, :hint] # Act like a before_render filter. Simple, efficient, robust. # No need to hack Rails internals for that matter! # # Used to boostrap the rendered page config. # def render(*args) bootstrap_page super end # Default, shared URL options, like the server's hostname. # def default_url_options(options = {}) { :host => MY_DOMAIN } end # @todo: document these ^^ # [:created!, :updated!, :deleted!].each do |method| define_method method do I18n.t(method.to_s, :scope => [controller_name, :flash]) end end def forbidden! I18n.t('errors.forbidden') end # Bootstraps a page, fetching its title and hint. These will not # be displayed if their value is missing or set to an empty string # # To provide a title and/or a hint for a given page, define the locale # keys +title+ and +hint+ under the appropriate locale master key, # based on the controller/action hierarchy as usual. # # One may provide interpolation locals by calling +bootstrap_page_with+ # with the action. # # @example # def my_action Use-case # # Allow to use locales like: # # fr.my_controller.my_action.title = "Foo (%{count} items)" # # fr.my_controller.my_action.hint = "?%{secret_advise}" # # # bootstrap_page_with :title => { # :count => Foo.count, # }, # :hint => { # :secret_advise => " The password is actually #{get_password!}" # } # end # # @example Useful shortcuts # def my_action # page_title_with :count => Foo.count # page_hint_with :hint => " The password is actually #{get_password!}" # end # def bootstrap_page in_current_i18n_scope do PAGE_KEYS.each do |key| instance_variable_set :"@#{key}", I18n.t(".#{key}", i18n_options_for_page_key(key)) end end end # Allow to define the interpolations for the current page. Keys should match # the PAGE_KEYS, values must be hashes with the interpolations. # # One may call this method several times in a row, as the interpolations are # appended, not erased. Conflicting keys get replaced as one would expect. # # @param [Hash<Hash>] interpolations # # @todo: in fact the name sucks. Bootstraping may not be all about handling # interpolations! Gotta find a better DSL. # def bootstrap_page_with(interpolations) interpolations.each do |key, locals| page_key_with(key, locals) end end # Dev-friendly shortcut to set title interpolations. # def title!(locals) bootstrap_page_with(:title => locals) end # Dev-friendly shortcut to set hint interpolations. # def hint!(locals) bootstrap_page_with(:hint => locals) end # Render a 403 page. # # @return [File] with status 403 Forbidden # def render_403 render :file => "#{Rails.root}/public/403.html", :status => 403 and return end # Render errors, responding to HTML or JSON. HTTP status is set to 406. # def render_errors(format, errors) format.html { render :template => "shared/errors", :locals => {:errors => errors}, :status => :unprocessable_entity } format.json { render :json => errors, :status => :unprocessable_entity } end private # Perform something in a specific I18n scope, enforced by the # current controller / action tuple. # # @yield if a valid scope can be inferred from the current route. # def in_current_i18n_scope if controller_name && action_name @@scope = "#{controller_name}.#{action_name}" yield else logger.error "Failed to bootstrap the page given " + "controller: #{controller_name.inspect}, action: #{action_name.inspect}" end end # Compiles the I18n options hash required for a page locale, with # sensible defaults. # # @param [Symbol] key # @param [Symbol] scope (I18n.locale) # # @todo: add config.default # def i18n_options_for_page_key(key, scope = @@scope) page_interpolations_for(key).merge!({:scope => scope, :default => ''}) end # Fetch the interpolations for a tuple controller / action / I18n key. # # @param [Symbol] key # @return [Hash] # def page_interpolations_for(key) init_page_interpolations cname = controller_name.to_sym aname = action_name.to_sym if @@page_interpolations.has_key?(cname) && @@page_interpolations[cname].has_key?(aname) @@page_interpolations[cname][aname][key] || {} else {} end end def init_page_interpolations @@page_interpolations ||= {} end def page_key_with(key, locals) init_page_interpolations cname = controller_name.to_sym aname = action_name.to_sym return if !locals.is_a?(Hash) || locals.empty? # init if needed @@page_interpolations.store(cname, {}) unless @@page_interpolations.has_key?(cname) @@page_interpolations[cname].store(aname, {}) unless @@page_interpolations[cname].has_key?(aname) # then store it @@page_interpolations[cname][aname][key] ||= {} @@page_interpolations[cname][aname][key].merge!(locals) end end <file_sep>class Admin::UsersController < ApplicationController before_filter :authenticate_user! before_filter :require_adminship def new @user = User.new end def create @user = User.new(params[:user]) respond_to do |format| if @user.save format.html { redirect_to root_path, notice: I18n.t('.admin.user_account_created', email: @user.email) } format.json { render :json => @user, :status => :created, :location => root_path } else render_errors(format, @user.errors) end end end end <file_sep>Allods::Application.routes.draw do devise_for :users, :admin resources :home, :only => :index resources :admins, :only => :index namespace :admin do resources :users, only: [:new, :create] end resources :personnages, :controller => :characters, :as => :characters resources :groupes, :controller => :loot_machines, :as => :loot_machines root :to => 'home#index' end <file_sep>require 'acceptance/acceptance_helper' feature "LootMachines, aka. Groups", %q{ In order to follow the evolution of a group of players As a player myself I want to be able to display a group } do background do # FIXME: in fact, the factories defined with blueprint cannot handle # custom attributes, so implement that using the default syntax lm = Factory.create :loot_machine, :title => 'Raid' ch = Factory.create :character, :nickname => 'Joe' ls = Factory.create :loot_status, { :loot_machine_id => lm.id, :character_id => ch.id } end scenario "Groups index" do visit '/loot_machines' page.should have_content('Raid') page.should have_content('Joe') end end <file_sep>class Character < ActiveRecord::Base belongs_to :user has_many :loot_statuses has_many :loot_machines, :through => :loot_statuses accepts_nested_attributes_for :loot_statuses, :loot_machines validates_presence_of :nickname validates_presence_of :archetype # @todo: maybe build a LevelValidator validates_presence_of :level validates_numericality_of :level, :only_integer => true validates_inclusion_of :level, :in => configatron.character.levels.min..configatron.character.levels.max expose_attributes :public => [:nickname, :level, :archetype, :role, :created_at], :show => [:level, :archetype, :role] scope :for, lambda { |user| { :conditions => { :user_id => user.id } } } scope :for_everyone_but, lambda { |user| { :conditions => ["user_id <> ?", user.id] } } end <file_sep>module CharacterHelper # Display a character's nickname, and if required and available, # its LootStatus' status for a given set of conditions. # # If no conditions are provided or if conditions lead to no record being # found or if applying conditions raises an error, the character's nickname # is returned. Otherwise, the character's loot status is appended. # # @param [Character] character # @param [Hash] any number of `:key => value` conditions to be applied to # `character.loot_statuses`. Some special keys are interpreted and will # not make it to the WHERE clause, see options. # @option [true, false] :to_link (false) whether to render a link # @return [String] # # @example # # display_nickname_and_loot_status Character.last, :loot_machine_id => 10 # def display_nickname_and_loot_status(character, *args) parameters = args.first options = { :link_to => false } options[:link_to] = !!parameters.delete(:link_to) return character.nickname if parameters.empty? ls = character.loot_statuses.where(args.first) if ls.empty? character.nickname else nickname = character.nickname nickname = link_to character.nickname, character_url(character), :class => class_for(character) if options[:link_to] I18n.t('characters.display_nickname_and_loot_status', :nickname => nickname, :status => I18n.t("loot_statuses.statuses.#{ls.first.status}")).html_safe end rescue ActiveRecord::ActiveRecordError => e character.nickname end end <file_sep>class AddBumpToLootMachine < ActiveRecord::Migration def self.up add_column :loot_machines, :bump, :string end def self.down remove_column :loot_machines, :bump end end <file_sep>source 'http://rubygems.org' gem 'rails', '~>3.1.1' #gem 'apotomo', '~>1.1', :git => 'git://github.com/chikamichi/apotomo.git', :branch => 'builders' gem 'apotomo', '~>1.2.1' gem 'capistrano', '~>2.5' gem 'compass', '~>0.10' gem 'configatron', '~>2.7' gem 'devise', '~>1.1' gem 'haml', '~>3.0' gem 'kaminari', '~>0.10' gem 'markdownizer', '~>0.3' gem 'mysql2', '~>0.2' gem 'paper_trail', '~>2.0' gem 'passenger', '~>3.0' gem 'simple_form', '~>1.3' gem 'sqlite3-ruby', '~>1.3', :require => 'sqlite3' gem 'state_machine', '~>0.9' group :development, :test do gem 'yard' gem 'rspec-rails', '~>2.5' gem 'factory_girl', '~>1.3' gem 'faker', '~>0.3' # until the v1.0 is released, so I can use acceptance test within RSpec #gem 'capybara' gem 'capybara', :git => 'git://github.com/jnicklas/capybara.git' end group :production do gem 'thin' end <file_sep># Each widget must subclass AllodsWidget, which defines shared methods # and mixins useful modules, helpers… # class AllodsWidget < Apotomo::Widget helper ApplicationHelper attr_reader :_action_name before_filter :setup! private def setup! @state = _action_name @user = options[:user] end end # FIXME: this is mandatory for Apotomo to find the classes # Investigate on this matter asap. Maybe it's due to me, subclassing # Apotomo::Widget? Try with a simpler setup. # May add this recursively in the (auto)load_paths? Dir["#{Rails.root}/app/widgets/**/*.rb"].each { |f| load(f) } <file_sep># This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'rack/test' require 'factory_girl/syntax/blueprint' require 'faker' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} Dir[Rails.root.join("spec/factories/**/*.rb")].each {|f| require f} # Ensure a collection is made of objects of a certain type. # # @example # # response.should be_an Array of User # RSpec::Matchers.define :of do |expected| match do |collection| collection.all? do |item| item.is_a? expected end end end RSpec.configure do |config| config.run_all_when_everything_filtered = true config.mock_with :rspec config.fixture_path = "#{::Rails.root}/spec/fixtures" config.use_transactional_fixtures = true end <file_sep>module LootStatusWidgets class ContainerWidget < AllodsWidget has_widgets do |me| setup! @loot_statuses.each do |loot_status| me << widget('loot_status_widgets/line', "loot_status_line_#{loot_status.id}", :loot_status_id => loot_status.id) end end def display setup! render end private def setup! super @loot_statuses = LootStatus.where(:character_id => options[:character_id]) end end end <file_sep>* close.png: http://commons.wikimedia.org/wiki/File:Gnome-process-stop.svg <file_sep>class Version < ActiveRecord::Base #markdownize! :description alias :legacy_reify :reify def reify case item_type.to_s when 'LootMachine' then # TODO: maybe add support for Character versioning? obj = legacy_reify # One must clone the record, for overriding the association will erase # the record's data. loot_machine = obj.clone # fetch all matching LootStatus and restore the has_many association loot_statuses = Version.where(:item_type => 'LootStatus', :bump => bump) loot_statuses.map!(&:legacy_reify) loot_statuses.map do |loot_status| loot_status.loot_machine = loot_machine end loot_machine.loot_statuses = loot_statuses return loot_machine else legacy_reify end end end <file_sep>class CharactersController < ApplicationController has_widgets do |root| root << widget('loot_status_widgets/container', "loot_status_container_#{@character.id}", :character_id => @character.id) end before_filter :authenticate_user!, :except => [:index, :show] # @get # def index if user_signed_in? @own_characters = Character.for current_user @characters = Character.for_everyone_but current_user else @own_characters = [] @characters = Character.all end end # @get # def new @character = Character.new end # @post # def create @character = Character.new(params[:character]) @character.user = current_user respond_to do |format| if @character.save format.html { redirect_to character_url(@character.reload), :notice => :created! } format.json { render :json => @character, :status => :created, :location => character_url(@character) } else render_errors(format, @character.errors) end end end # @get # def show @character = Character.find(params[:id]) title! :nickname => @character.nickname respond_to do |format| format.html format.json { render :json => @character } end end # @get # def edit @character = Character.find(params[:id]) title! :nickname => @character.nickname end # @put # def update @character = Character.find(params[:id]) # smart JS require to extract the role from the proper radio buttons values set params[:character][:role] = params.find { |k,v| k =~ /roles_group_for_#{params[:character][:archetype]}/ }.last respond_to do |format| if @character.update_attributes(params[:character]) format.html { redirect_to character_url(@character), :notice => updated! } format.json { rende :json => @character, :status => :ok } else render_errors(format, @character.errors) end end end #def current_loot_statuses #return nil unless user_signed_in? #if params[:loot_machine_id] #[ LootStatus.where(:user_id => current_user.id, :loot_machine_id => params[:loot_machine_id]) ] #elsif params[:loot_status_id] #[ LootStatus.find(params[:loot_status_id]) ] #elsif @character #LootStatus.where(:user_id => @character.id) #end #end end <file_sep>LootStatus.blueprint do association :character association :loot_machine status { LootStatus::STATUS.sort_by{rand}.first } need { |ls| ls.status == :need ? 1 : 0 } greed { |ls| ls.status == :greed ? 1 : 0 } loyalty { 5 } score { rand(10) - 5 } end <file_sep>module LootMachineWidgets class ConsoleWidget < AllodsWidget responds_to_event :change responds_to_event :plusOne build do |options| AdminConsoleWidget if options[:user] and options[:user].admin? end has_widgets do |console| setup! unless @loot_machine.loot_statuses.empty? @loot_machine.loot_statuses.each do |loot_status| console << widget('loot_status_widgets/line', "loot_status_line_#{loot_status.id}", :loot_status_id => loot_status.id, :user => @user) end end end # @group States def display(opts = {}) setup! render :locals => opts end def inner_content setup! render end # @group Events def change(event) setup! unless @user.nil? || !@user.admin? ls = LootStatus.find(event[:loot_status_id]) # update the edited metadata with the new value ls.update_attribute(event[:loot_status_metadata].to_sym, event[:value]) # update the score ls.compute :score # status is to be computed on client-side as a result of dynamic filtering, # there's nothing left to do end render :view => :inner_content end def plusOne(event) setup! event['ids'].map(&:to_i).each do |ls_id| ls = LootStatus.find(ls_id.to_i) ls.increment event['loot_status_metadata'] ls.compute :score end render :view => :inner_content end # @endgroup private # Retrieve the proper LootMachine, using either the id set within # a controller or sent back with a request in the params hash # (options is merged to params). # def setup! super @loot_machine = LootMachine.find options[:loot_machine_id] end end class AdminConsoleWidget < ConsoleWidget end end <file_sep>class ActiveRecord::Base # Filter out attributes based on explicit, simple rules. This # defines helper *_attributes methods on model objects. # # @param [Hash] the filters, see example for details # # @example # # # in app/model/foo.rb # class Foo < ActiveRecord::Base # expose_attributes :public => [:login, :address, :description], # :editable => [:address, :description, :password] # end # # # now one can make use of: # Foo.first.public_attributes # Foo.first.editable_attributes # useful to iterate over in _form partials, for instance # Foo.first.editable_attribute? :description # => true # Foo.editable_attributes # => [:address, :description, :password] in order # # @todo: turn this into a little gem, and add support for simple options (prefix [String, nil], # maybe the ability to define a proc to be used as the method implementation!). # Change a little bit the DSL to ease things out: # # @example TODO # expose_attributes :public, :suffix => 'keys', :login, :address, :description # expose_attributes :public, :suffix => nil, :login, :address, :description # expose_attributes :private, :do => proc { |model| model.attributes.keep_if { |a| a.to_s.match? /_private$/ } } # expose_attributes :private, :do => :filter_private_attributes # call this method, cleaner # def self.expose_attributes(*args) args.first.each do |name, exposed| define_method :"#{name}_attributes" do attributes.keep_if { |a| exposed.include?(a.to_sym) } end define_method :"#{name}_attribute?" do |attribute| !!self.send(:"#{name}_attributes").include?(attribute.to_s) end self.metaclass.send :define_method, :"#{name}_attributes" do exposed end end end # @todo: use my Logg gem once published! :D # def log_event(event, metadata = nil, object = nil) message = log_message(event, metadata, object) logger.debug "#{Time.now} | #{message}" unless message.nil? end end <file_sep>User.blueprint do email { Faker::Internet.email } password { '<PASSWORD>' } end <file_sep># Allods An application tailored at managing groups in Allods MMORPG. Created by and for <NAME>, Vlad, France. This makes use of Apotomo, yeah! ## License WTFPL (http://sam.zoy.org/wtfpl/) ## Bugs, contributions Either: * Fork, patch, and make a pull request. * Send me a message. Use your brain. <file_sep>Character.blueprint do association :user nickname { Faker::Name.name } level { rand(42) } end <file_sep>namespace :db do MODELS = [ # LootStatus factory triggers creation of users, characters and loot machines # through associations. #:user, #:character, #:loot_machine, :loot_status ] desc "initialize" task :init => [:environment] do require 'factory_girl/syntax/blueprint' require 'faker' Dir.glob("spec/factories/*.rb") do |file_require| load file_require end # Don't send emails. ActionMailer::Base.delivery_method = :test def print_more print '.' STDOUT.flush end def nb (ENV['NB'] || 1).to_i end def generate model, attributes = {} 10.times do Factory.create model.to_sym, attributes print_more end puts "" end end desc "perform all populate tasks" task :populate => [:init] do Rake::Task['db:populate:default'].invoke end namespace :populate do desc 'default: perform all populate tasks' task :default => MODELS MODELS.each do |model| class_eval do desc "Create 10 #{model.to_s.camelize} records" task model => :init do print "Creating 10 #{model.to_s.camelize} records " generate model end end end end end <file_sep># encoding: UTF-8 module ApplicationHelper def admin?(user = current_user) $stderr.puts user.inspect return false if user.nil? user.admin? end def class_for(resource) if owns? resource if resource.is_a?(User) || resource.is_a?(Character) return 'myself' end end return '' end # Determines whether the current user owns the specified # resource. # # @param [Object] resource # @return [true, false] # def owns?(resource) return false unless user_signed_in? if resource.is_a? Character return false if resource.user.nil? resource.user.id == current_user.id end end # Display some resource's attributes as a list. # # @overload display(method, resource, *args) # the provided method will be applied to the resource to get a list # of attributes. # @param [#to_sym] method # @overload display(list, resource, *args) # @param [Array<Symbol>] list # # @param [Object] resource ActiveModel resource # @param [Hash] args # @option args [Array<Symbol>] :except ([]) a list of attributes to discard # @return [String] the formatted attributes in a <ul> tag # def display(type, resource, *args) opts = { :except => [] }.merge(args.extract_options!) model = resource.class attributes = if type.is_a?(Symbol) || type.responds_to?(:to_sym) model.send(type.to_sym) else type end unless attributes.nil? || attributes.empty? str = '' str += '<ul>' unless opts[:nowrap] attributes.each do |attr| value = resource.send(attr) unless value.blank? || opts[:except].include?(attr) str += "<li class='#{attr}'>" str += "<span class='attribute #{attr}'>" str += t("#{model.to_s.downcase}.attributes.#{attr}") str += "</span> : <span>" str += format(value, attr, model) str += "</span>" end end str += '</ul>' unless opts[:nowrap] return str.html_safe else return '' end end def display_armours(character) return nil if character.archetype.blank? configatron.character.armours.for.send(character.archetype).map do |a| I18n.t("characters.armours.#{a}").downcase end.join(', ') end # Format an attribute. If the key is provided, the attribute # type may be infered for a better guess. In case no smart guess # can be made, the value is returned as is. # # @example With a date # # format User.last.created_at, 'created_at' # # @param [Object] value # @param [#to_s] key (nil) key name # @param [#to_s] model (nil) model constant # @return [String] a formatted version of value # @todo add support for a type option to enforce formatting? # def format(value, key = nil, model = nil) if !key.nil? if key.to_s.ends_with?('_at') l(value.to_date) elsif !model.nil? t("#{model.to_s.downcase}.#{key}.#{value}", :default => value.to_s) else value.to_s end else value.to_s end end # def sign_up_in_links(message = nil) I18n.translate('.sign_up_in', { :sign_up_link => link_to('créer un compte', new_user_registration_url), :sign_in_link => link_to('vous connecter', new_user_session_url), :message => message.nil? ? '' : " #{message}" }).html_safe end end <file_sep>require 'yaml' require 'erb' # Load configuration files in /config/initializers/ # # Each configuration file can be a plain YAML (*.yml) # or an ERB template for a YAML document (*.yml.erb) # # The root YAML key *must be a symbol*. Allowed values are : # # * :all for default settings applicable all hosts and environments # # * #{RAILS_ENV} when you want to override the global settings with # settings specific to the development, cdp, production… # environment # # * `hostname` when you want to customize your configuration down to # host-specific settings # # * You can also provide a :"`hostname -f`-RAILS_ENV" key for very specific # settings # # # @see http://github.com/markbates/configatron/ for more info on configatron # if Rails.root.join("config/initializers/config.rb").exist? $stdout.puts "Loading config sets" Dir["#{Rails.root}/config/set/**/*.{yml,yml.erb}"].sort.each do |f| values = YAML.load ERB.new(File.read(f), 0, '<>%-').result # Reads a global config configatron.configure_from_hash values[:all] # Reads a "per env" config configatron.configure_from_hash values[Rails.env.to_sym] # Reads a "per host" config configatron.configure_from_hash values[`hostname -f`.chomp.to_sym] # Read a "per host/env" config configatron.configure_from_hash values["#{`hostname -f`.chomp}-#{Rails.env}".to_sym] end end
956173ea9e96feb35130b072dcf257e4f7760e9d
[ "JavaScript", "Ruby", "Markdown" ]
36
Ruby
nexustheru/allods
7508e542fe637be0956d4d0510721c2c50ac4428
9a3d07549af5412bb42b39fca157927a6748d9ed
refs/heads/main
<repo_name>jb0403/youtube-clone-react-native<file_sep>/src/redux/sagas/YTdataSaga.js import { call, put, takeLatest } from "redux-saga/effects"; const apiURL = " https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=10&q=songs&type=video&key=<KEY>"; <file_sep>/src/redux/index.js export { change_theme } from "./theme/ThemeActions"; export { addData } from "./YTdata/YTdataActions"; <file_sep>/src/redux/rootReducer.js import { combineReducers } from "redux"; import ThemeReducer from "./theme/ThemeReducer"; import YTReducer from "./YTdata/YTdataReducer"; const rootReducer = combineReducers({ YTdata: YTReducer, Theme: ThemeReducer, }); export default rootReducer; <file_sep>/src/redux/YTdata/YTdataReducer.js import { AddData } from "./YTdataType"; const initialState = []; const YTReducer = (state = initialState, action) => { switch (action.type) { case AddData: return { ...state, YTdata: action.payload, }; default: return state; } }; export default YTReducer; <file_sep>/src/redux/theme/ThemeReducer.js import { CHANGE_THEME } from "./ThemeType"; const initialState = false; const ThemeReducer = (state = initialState, action) => { switch (action.type) { case CHANGE_THEME: return { state: action.payload, }; default: return state; } }; export default ThemeReducer; <file_sep>/src/components/Header.js import React from "react"; import { StyleSheet, Text, View } from "react-native"; import { AntDesign, Ionicons, MaterialIcons } from "@expo/vector-icons"; import Constant from "expo-constants"; import { useNavigation, useTheme } from "@react-navigation/native"; import { useDispatch, useSelector } from "react-redux"; import { change_theme } from "../redux"; const Header = () => { const navigation = useNavigation(); const { colors, iconColor } = useTheme(); const dispatch = useDispatch(); const currentTheme = useSelector((state) => { return state.Theme.state; }); const secondary_clr = colors.iconColor; return ( <View style={[ styles.header, { backgroundColor: colors.headerColor, }, ]} > <View style={styles.header__left}> <AntDesign name="youtube" size={32} color="red" /> <Text style={[styles.header__left_text, { color: secondary_clr }]}> YouTube </Text> </View> <View style={styles.header__right}> <View style={styles.header__right_icons}> <Ionicons name="md-videocam" style={styles.header__right_icon} size={32} color={secondary_clr} /> <Ionicons name="md-search" style={styles.header__right_icon} size={30} color={secondary_clr} onPress={() => { navigation.navigate("search"); }} /> <MaterialIcons name="account-circle" style={styles.header__right_icon} size={32} color={secondary_clr} onPress={() => dispatch(change_theme(!currentTheme))} /> </View> </View> </View> ); }; export default Header; const styles = StyleSheet.create({ header: { height: 45, flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginTop: Constant.statusBarHeight, padding: 10, elevation: 4, marginBottom: 3, //for IOS // shadowOffset: { width: 10, height: 10 }, // shadowColor: "black", // shadowOpacity: 1.0, }, header__left: { flexDirection: "row", alignItems: "center", justifyContent: "flex-start", marginLeft: 10, }, header__left_text: { marginLeft: 10, fontSize: 21, fontWeight: "bold", }, header__right: { alignItems: "center", justifyContent: "flex-end", marginRight: 10, }, header__right_icons: { flexDirection: "row", alignItems: "center", width: 150, justifyContent: "space-around", }, });
d189701cff89de424671e777a0b94f43fd35c1d8
[ "JavaScript" ]
6
JavaScript
jb0403/youtube-clone-react-native
2d88311fd7f24e276b2b8711304967dd3c695d18
895438ff8d462c669a56b86418fb40fa062f770f
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class NewHouseItem(scrapy.Item): """新房item""" _id = scrapy.Field() # ID province = scrapy.Field() # 省份 city = scrapy.Field() # 城市 name = scrapy.Field() # 小区名字 price = scrapy.Field() # 价格 # house_type = scrapy.Field() # 房型 # area = scrapy.Field() # 面积 address = scrapy.Field() # 地址 district = scrapy.Field() # 行政区 sale = scrapy.Field() # 是否在售 origin_url = scrapy.Field() # 详情页链接 wylb = scrapy.Field() zxdh = scrapy.Field() jzlb = scrapy.Field() zxzk = scrapy.Field() cqnx = scrapy.Field() hxwz = scrapy.Field() kfs = scrapy.Field() xszt = scrapy.Field() lpyh = scrapy.Field() kpsj = scrapy.Field() jfsj = scrapy.Field() zlhx = scrapy.Field() ysxkz = scrapy.Field() xmts = scrapy.Field() zdmj = scrapy.Field() jzmj = scrapy.Field() rjl = scrapy.Field() lhl = scrapy.Field() tcw = scrapy.Field() ldzs = scrapy.Field() wygs = scrapy.Field() wyfms = scrapy.Field() lczk = scrapy.Field() zhs = scrapy.Field() wyf = scrapy.Field() class ESFHouseItem(scrapy.Item): """二手房item""" _id = scrapy.Field() # ID province = scrapy.Field() # 省份 city = scrapy.Field() # 城市 name = scrapy.Field() # 小区名字 intro_name = scrapy.Field() # 房名 house_type = scrapy.Field() # 房型 floor = scrapy.Field() # 楼层 towards = scrapy.Field() # 朝向 year = scrapy.Field() # 年代 area = scrapy.Field() # 面积 address = scrapy.Field() # 地址 price = scrapy.Field() # 总价 unit = scrapy.Field() # 单价 origin_url = scrapy.Field() # 详情页链接 gather_time = scrapy.Field() # 采集时间 # update_time = scrapy.Field() # 入库时间<file_sep>from scrapy import cmdline cmdline.execute('scrapy crawl ftx'.split())<file_sep># -*- coding: utf-8 -*- import re from datetime import datetime import scrapy from fangtianxia.items import NewHouseItem, ESFHouseItem class FtxSpider(scrapy.Spider): name = 'ftx' allowed_domains = ['fang.com'] start_urls = ['https://www.fang.com/SoufunFamily.htm'] def parse(self, response): """从官网下的所有城市入手,获取各城市url,并构建各城市新房和二手房链接""" trs = response.xpath('//div[@class="outCont"]//tr')[:-1] # 过滤掉海外城市 province = None for tr in trs: tds = tr.xpath('.//td[not(@class)]') # 获取省份并装入meta传入下一个函数 province_text = re.sub(r'\s', '', tds[0].xpath('.//text()').get()) # 某省城市多的话第二行没有省份信息,故而使用上一次的省份信息 if province_text: province = province_text # 获取城市信息 city_links = tds[1].xpath('.//a') for city_link in city_links: city = city_link.xpath('.//text()').get() city_url = city_link.xpath('.//@href').get() # 构建新房、二手房的url链接 url_module = city_url.split('//') if 'bj.' in url_module[1]: newhouse_url = 'https://newhouse.fang.com/house/s/' esf_url = 'https://esf.fang.com/' else: url_city = url_module[1].split('.')[0] newhouse_url = 'https://' + url_city + '.newhouse.fang.com/house/s/' esf_url = 'https://' + url_city + '.esf.fang.com' # 新房链接 yield scrapy.Request(url=newhouse_url, callback=self.parse_newhouse_list, meta={'info': (province, city)}, dont_filter=True) # 二手房链接 # yield scrapy.Request(url=esf_url, callback=self.parse_esf, meta={'info': (province, city)}, dont_filter=True) def parse_newhouse(self, response): province, city, _id, name, price, url = response.meta.get('info') # 实例化新房item item = NewHouseItem() lis = response.xpath('//div[contains(@class,"main-item")]/ul[contains(@class, "list")]/li') v = {} for li in lis: divs = li.xpath('./div') tmp_k = '' for i in range(0, 2): txt = ''.join([t.strip() for t in divs[i].xpath('.//text()').getall()]) if i == 0: tmp_k = txt else: v[tmp_k] = txt if tmp_k == '项目特色:': tmp_lis = divs[i].xpath('./li') for tmp_li in tmp_lis: tmp_divs = tmp_li.xpath('./div') tmp_k = '' for ii in range(0, 2): txt = ''.join([t.strip() for t in tmp_divs[ii].xpath('.//text()').getall()]) if ii == 0: tmp_k = txt else: v[tmp_k] = txt # print(tmp_k, txt) # print(v) item['_id'] = _id item['origin_url'] = url item['province'] = province item['city'] = city item['name'] = name item['price'] = price item['address'] = v.get('售楼地址:', '') item['wylb'] = v.get('物业类别:', '') # item['xmts'] = v.get('项目特色:', '') item['jzlb'] = v.get('建筑类别:', '') item['zxzk'] = v.get('装修状况:', '') item['cqnx'] = v.get('产权年限:', '') item['hxwz'] = v.get('环线位置:', '') item['kfs'] = v.get('开发商:', '') item['xszt'] = v.get('销售状态:', '') item['lpyh'] = v.get('楼盘优惠:', '') item['kpsj'] = v.get('开盘时间:', '') item['jfsj'] = v.get('交房时间:', '') item['zxdh'] = v.get('咨询电话:', '') item['zlhx'] = v.get('主力户型:', '') item['ysxkz'] = v.get('预售许可证:', '') item['zdmj'] = v.get('占地面积:', '') item['jzmj'] = v.get('建筑面积:', '') item['rjl'] = v.get('容积率:', '') item['lhl'] = v.get('绿化率:', '') item['tcw'] = v.get('停车位:', '') item['ldzs'] = v.get('楼栋总数:', '') item['zhs'] = v.get('总户数:', '') item['wygs'] = v.get('物业公司:', '') item['wyf'] = v.get('物业费:', '') item['wyfms'] = v.get('物业费描述:', '') item['lczk'] = v.get('楼层状况:', '') yield item def parse_newhouse_list(self, response): """新房列表解析函数""" # 获取上一步得到的省份和城市信息 province, city = response.meta.get('info') lis = response.xpath('//div[contains(@class,"nl_con")]/ul/li[contains(@id,"lp_")]') for li in lis: _id = int(li.xpath('./@id').get().replace("lp_", "")) name = li.xpath('.//div[@class="nlcd_name"]/a/text()').get().strip() url = response.urljoin(li.xpath('.//div[@class="nlcd_name"]/a/@href').get()) price = re.sub(r'\s|广告', '',''.join(li.xpath('.//div[@class="nhouse_price"]//text()').getall())).strip() if str(url).find('?') != -1: url = url[:str(url).find('?')] url = '{}house/{}/housedetail.htm'.format(url, _id) print(url) yield scrapy.Request(url=url, callback=self.parse_newhouse, meta={'info': (province, city, _id, name, price, url)}, dont_filter=True) # 自动获取下一页 next_page = response.xpath('//div[@class="page"]//a[@class="next"]/@href').get() if next_page: next_url = response.urljoin(next_page) yield scrapy.Request(url=next_url, callback=self.parse_newhouse, meta={'info': (province, city)}) def parse_esf(self, response): """二手房网页解析函数""" # 实例化二手房item item = ESFHouseItem() # 获取上一步得到的省份和城市信息 item['province'], item['city'] = response.meta.get('info') dls = response.xpath('//div[contains(@class,"shop_list")]/dl[@dataflag="bg"]') for dl in dls: href = dl.xpath('.//dd/h4/a/@href').get() # 商品ID item['_id'] = int(href.split('_')[-1].split('.')[0]) # 介绍名,就是那一行唬人的一长串 item['intro_name'] = dl.xpath('.//dd/h4/a/span/text()').get().strip() # 小区名称 item['name'] = dl.xpath('.//dd/p[@class="add_shop"]/a/text()').get().strip() # 详情页链接 item['origin_url'] = response.urljoin(href) # 获取房屋信息 house_infos = re.sub(r'[\s]', '', ''.join(dl.xpath('.//dd/p[@class="tel_shop"]//text()').getall())).split('|') for house_info in house_infos: # 户型 if '室' in house_info: item['house_type'] = house_info # 面积 elif '㎡' in house_info: item['area'] = float(house_info.replace("㎡", "")) # 香港澳门面积 elif '呎' in house_info: item['area'] = house_info # 楼层 elif '层' in house_info: item['floor'] = house_info # 朝向 elif '向' in house_info: item['towards'] = house_info # 建造时间 elif '年建' in house_info: item['year'] = int(house_info[:-2]) # 详细地址 item['address'] = dl.xpath('.//dd/p[@class="add_shop"]/span/text()').get() # 总价 price = ''.join(dl.xpath('.//dd[@class="price_right"]/span[1]//text()').getall()).strip() if '$' in price: # 港澳价格 item['price'] = price else: # 国内价格 item['price'] = float(price.replace("万", "").replace("$", "")) # 单价 unit = dl.xpath('.//dd[@class="price_right"]/span[2]/text()').get().strip() if '$' in unit: # 港澳价格 item['unit'] = unit else: # 国内价格 item['unit'] = float(unit.replace("元/㎡", "").replace("$", "")) # 采集时间 item['gather_time'] = datetime.now() yield item # 自动获取下一页 next_page = response.xpath('//div[@class="page_al"]/p[last()-2]') next_text = next_page.xpath('.//a/text()').get() if next_text and next_text == '下一页': next_url = response.urljoin(next_page.xpath('.//a/@href').get()) yield scrapy.Request(url=next_url, callback=self.parse_esf, meta={'info': (item['province'], item['city'])}) <file_sep># -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # import pymongo import codecs import csv class FangtianxiaPipeline(object): def process_item(self, item, spider): return item # 保存到CSV文件中 class CsvPipeline(object): def __init__(self): self.file = codecs.open('data.csv', 'w', encoding='utf_8_sig') def process_item(self, item, spider): fieldnames = ['_id', 'province', 'city', 'name', 'price', 'house_type', 'area', 'address', 'district', 'sale', 'origin_url', 'jzmj', 'lpyh', 'kpsj', 'xszt', 'jfsj', 'xmts', 'zxdh', 'tcw', 'ldzs', 'rjl', 'zxzk', 'lczk', 'wylb', 'hxwz', 'zdmj', 'jzlb', 'cqnx', 'zlhx', 'ysxkz', 'wyf', 'kfs', 'wygs', 'wyfms', 'lhl', 'zhs'] w = csv.DictWriter(self.file, fieldnames=fieldnames, quotechar='"', quoting=csv.QUOTE_ALL) # w.writeheader() w.writerow(item) return item def close_spider(self, spider): self.file.close() ''' class MongoPipeline(object): """MongoDB管道""" def __init__(self, mongo_uri, mongo_db): self.mongo_uri = mongo_uri self.mongo_db = mongo_db @classmethod def from_crawler(cls, crawler): return cls( mongo_uri=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DB') ) def open_spider(self, spider): self.client = pymongo.MongoClient(self.mongo_uri) self.db = self.client[self.mongo_db] def process_item(self, item, spider): name = item.__class__.__name__ data = dict(item) self.db[name].update_one({"_id": data['_id']}, {"$set": data}, upsert=True) return item def close_spider(self, spider): self.client.close() ''' <file_sep>scrapy==1.5.0 pymongo==3.9.0 requests==2.24.0 twisted==20.3.0 setuptools==45.2.0<file_sep># 某天下爬虫 某天下658城新房、二手房信息爬取 # 声明 1. 本次采集某天下全国658城新房、二手房信息,其中所涉及的仅用于学习交流,不得用作除此之外其余任何用途 2. 658城中缺失雷州、蒙城、广德及台湾等地数据,是因为某天下没有或者并未展示相关数据,无其他任何原因 # 环境 ``` pip install scrapy ``` # 使用 ``` python start.py ``` # 没了
80b303d4725a76c8edaf3788ac125a3f5f689632
[ "Markdown", "Python", "Text" ]
6
Python
xiaolu11bnb/fangtianxia
c100e8446fd2bff1a71a7a0e054f7c1bc7413095
481434caa89d558ed03cacacf57b402a7db2f733
refs/heads/master
<repo_name>alyssue/cmps112<file_sep>/perl/asg4/hello.h /* $Id: hello.h,v 1.1 2011-03-24 17:24:59-07 - - $ */ #ifndef __HELLO_H__ #define __HELLO_H__ void hello (void); #endif <file_sep>/README.md # cmps112 Covers several programming languages and compares styles, philosophy, and design principles. Principles underlying declarative, functional, and object-oriented programming styles are studied. Students write programs emphasizing each of these techniques. <file_sep>/ocaml/testing/.mk.dcout #!/bin/sh # $Id: .mk.dcout,v 1.1 2018-10-16 14:28:38-07 - - $ for test in *.in do echo $0: $test starting. base=`echo $test | sed 's/\.in$//'` dc <$test >$base.dcout 2>&1 echo $0: $test finished. done <file_sep>/ocaml/asg2/Makefile # $Id: Makefile,v 1.19 2018-04-19 14:58:55-07 - - $ DEPSFILE = Makefile.deps NOINCLUDE = ci clean spotless NEEDINCL = ${filter ${NOINCLUDE}, ${MAKECMDGOALS}} SOURCE = bigint.mli bigint.ml maindc.ml scanner.mll ALLSRC = ${SOURCE} dc.ml Makefile OBJCMI = bigint.cmi scanner.cmi MAINCMI = maindc.cmi OBJCMO = ${OBJCMI:.cmi=.cmo} maindc.cmo CAMLRUN = ocamldc LISTING = Listing.ps all : ${CAMLRUN} ${CAMLRUN} : ${OBJCMI} ${OBJCMO} ocamlc ${OBJCMO} -o ${CAMLRUN} %.cmi : %.mli - checksource $< ocamlc -c $< %.cmo : %.ml - checksource $< ocamlc -c $< scanner.cmi scanner.cmo scanner.ml : scanner.mll - checksource $< ocamllex $< ocamlc -c scanner.ml clean : - rm ${OBJCMO} ${OBJCMI} ${MAINCMI} ${DEPSFILE} scanner.ml spotless : clean - rm ${CAMLRUN} ${LISTING} ${LISTING:.ps=.pdf} ci : ${RCSFILES} - checksource ${ALLSRC} cid + ${ALLSRC} deps : ${SOURCE} ocamldep ${SOURCE} >${DEPSFILE} ${DEPSFILE} : @ touch ${DEPSFILE} make --no-print-directory deps lis : ${ALLSRC} mkpspdf ${LISTING} ${ALLSRC} ${DEPSFILE} again : make --no-print-directory spotless ci deps all lis ifeq (${NEEDINCL}, ) include ${DEPSFILE} endif <file_sep>/ocaml/testing/mk.build #!/bin/sh # $Id: mk.build,v 1.3 2018-10-25 14:00:00-07 - - $ checksource R* M* *.m* >check.log 2>&1 gmake >gmake.log 2>&1 <file_sep>/scheme/.bash_history 8: (7, -1820.5) (8, 4961.3) (9, -5398.500000000001) 9: (10, -2108.5) 10: (4, 9159.8) A-A = Transpose(A) = 1: (1, 8596.3) (3, -3013.9) (5, -1114.8) 4: (1, 5830.3) (2, -6315.9) (6, 5568.6) 5: (4, -9229.6) (6, -3604.1) 7: (4, -2402.8) (5, -9982.4) (6, 8095.4) (8, 1820.5) 8: (8, -4961.3) 9: (7, -644.5) (8, 9063.2) A*B = 1: (2, 7177910.499999999) (8, 3.9564415800000004E7) 2: (8, -4.28596974E7) 3: (2, -2516606.5) 4: (1, 2.0464887880000003E7) (2, -7538737.28) (3, -6975568.680000001) 5: (1, 8.502109904E7) (2, -930858.0) (3, -2.8979905439999998E7) 6: (1, -6.894933134E7) (2, -2943828.88) (3, 2.350175574E7) (8, 3.77885196E7) 7: (10, 1358928.25) 8: (1, -1.550538055E7) (3, 5285093.55) (9, -1.818167611E7) (10, -1.9109757200000003E7) B*B = 1: (10, -728537.5) 2: (4, -7991925.499999999) 3: (2, -4441676.72) (9, 3.396847077E7) 4: (9, 2.48686542E7) 5: (10, -712658.0) 6: (5, -4615145.7299999995) (8, 7866685.170000001) 7: (2, -7111778.5) (5, -1.5786767489999998E7) (8, 2.690912421E7) 8: (10, -7727019.949999999) 9: (4, -1.9313438299999997E7) 10: (8, 6.21584028E7) clear ./pa3.sh clear make Sparse in1 out make makemake make Sparse in1 out make Sparse in1 out make Sparse in1 out make Sparse in1 out ./pa3.sh make ./pa3.sh j1015525J clear cd cs101 cd pa3 ./pa3.sh make ./pa3.sh make mkae make ./pa3.sh submit cmps101-pt.s18 pa3 Matrix.java List.java MatrixTest.java ListTest.java Sparse.java README Makefile cd ls cd cs101 mkdir pa4 cd pa4 curl https://raw.githubusercontent.com/legendddhgf/cmps101-pt.s18.grading/master/pa4/pa4.sh > pa4.sh chmod +x pa4.sh ./pa4.sh clear make clearmake clear make clear make clear make clear make clear make clear make clear make clear make clear make clear make clear maek clear make clear make clear make ./pa4.sh clear make clean clear make clear make clear make make clean clear make clear make make clean clear make ./pa4.sh clear make clean ./pa4.sh clear ./pa4.sh cd cs101 cd pa4 ./pa4.sh cd cs101 cd pa4 ./pa4.sh make ./pa4.sh clear make FindPath FindPath in1 out cd cs101 cd pa4 ls ./pa4.sh make ./pa4.sh make FindPath in1 out vim in1 vim out FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out FindPath in2 out vim out make vim out FindPath in2 out vim out make FindPath in2 out make vim out make FindPath in2 out vim out ./pa4.sh clear make FindPath in2 out vim out make FindPath in2 out vim out:q! vim out make FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out ./pa4.sh clear mkae make clear make clear make clean clear make Find Path in2 out FindPath in2 out vim out make clear make clear make clear make clear make FindPath in2 out vim out make clear make clean make FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out make FindPath in2 out vim out ./pa4.sh clear make ./pa4.sh make ./pa4.sh make ./pa4.sh submit cmps101-pt.s18 pa4 Graph.h Graph.c Makefile README FindPath.c List.c List.h GraphTest.c rm -f *.txt *.sh ls submit cmps101-pt.s18 pa4 Graph.h Graph.c Makefile README FindPath.c List.c List.h GraphTest.c cd cs101 mkdir pa5 cd pa5 curl https://raw.githubusercontent.com/legendddhgf/cmps101-pt.s18.grading/master/pa5/pa5.sh > pa5.sh chmod +x pa5.sh ./pa4.sh ./pa5.sh make clear mkae clear mkae clear make mkae make clear make clear make ./pa5.sh clear make clear make clear make make clean clear make clear make clean make clear ./pa5.sh make clean clear ./pa5.sh make clear make maek make clear make clear make clean clear make clear ./pa4.sh ./pa5.sh clear make clear make clear make clear make clear make clear make make clean clear make clear make clean make clear mkae make clear make clear make clear make clear make make lcean clea make clean clear make clear make ake make mkae clean make clean make clear ./pa5.sh cd cs101 cd pa5 ./pa5.sh cd cs101 cd pa5 ./pa5.sh make clear make FindComponents GraphClient out mkae clean make clean make GraphClient clear ls clear mkae make clear make clean ./pa5.sh GraphClient gcc GraphClient.c -o GraphClient gcc GraphClient.c -o gcc GraphClient.c clear gcc GraphClient.c gcc GraphClient.c -o GraphClient GraphClient.c cd cs101 cd pa5 ls make GraphClient gcc GraphClient.c -i GraphClient gcc GraphClient.c -o GraphClient ./pa5.sh clear mkae make cd cs101 cd pa5 ./pa5.sh make FindComponents in1 out vim out cd cs101 cd pa5 ./pa5.sh ls ./pa5.sh ls ./pa5.sh logout ls cd cs101 ls cd pa5 ls ./pa5 ./pa5.sh cd cs101 cd pa5 ./pa5.sh cd cs101 cd pa5 ./pa5.sh make FindComponents FindComponents in out FindComponents in1 out vim out make FindComponents in1 out vim out make FindComponents in1 out vim out make FindComponents in1 out vim out make FindComponents in1 out vim out make FindComponents in1 out vim out make FindComponents in1 out make FindComponents in1 out make FindComponents in1 out make mkae make FindComponents in1 out make FindComponents in1 out make FindComponents in1 out vim out make FindComponents in1 out clear FindComponents in1 out FindComponents in1 system make FindComponents in1 system vim in1 make FindComponents in1 system clear make FindComponents in1 system clear maek make FindComponents in1 system vim out make FindComponents in1 system make FindComponents in1 system vim out make FindComponents in1 system vim system make FindComponents in1 system vim system maek make FindComponents in1 test vim test make FindComponents in1 test vim test make vim test FindComponents in1 test vim test make FindComponents in1 test vim test make FindComponents in1 test vim test ./pa5.sh make ./pa5.sh vim test make FindComponents in1 test vim test make FindComponents in1 test vim test ./pa5.sh vim test clear make clear ./pa5.sh make ./pa5.sh FindComponents in1 test make FindComponents in1 test vim test make FindComponents in1 test vim test mkae make FindComponents in1 test vim test make FindComponents in1 test vim test ./pa5.sh make FindComponents in1 test vim test make FindComponents in1 test vim test make FindComponents in1 test vim test ./pa5.sh make FindComponents in1 test vim test make FindComponents in1 test vim test make FindComponents in1 test vim test ./pa5.sh clear vim test make vim test FindComponent in1 test FindComponents in1 test vim test clear make clean ./pa5.sh make ./pa5.sh clear make FindComponents in1 out vim out clear make FindComponents in1 out vim out make FindComponents in1 out vim out vim test make ./pa5.sh make ./pa5.sh make ./pa5.sh make ./pa5.sh clear make ./pa5.sh clear maek make FindComponents in1 out vim out make FindComponents in1 out vim out make ./pa5.sh make ./pa5.sh make FindComponents in1 out vim out make mae mkae mkaemk mkae clear make FindComponents in1 out vim out make FindComponents in1 out vim out make mkae make clear make clear make FindComponents in1 out vim out make clear make FindComponents in1 out clear make FindComponents in1 out make FindComponents in1 out make FindComponents in1 out make FindComponents in1 out vim out make FindComponents in1 out vim out make FindComponents in1 out vim out make FindComponents in1 out vim out make clear make FindComponents in1 out clear make FindComponents in1 out vim out make FindComponents in1 out make FindComponents in1 out vim out make clear make FindComponents in1 out vim out make clear make clear make clean clear make clear make clean clea rclear clear maek clear maek clear make FindComponents in1 out vim out ./pa5.sh submit cmps101-pt.s18 pa5 README Makefile FindComponents.c Graph.c GraphTest.c Graph.h List.c List.h clear rm -f *.txt *.sh rm -f *.txt *.shrm -f *.txt *.sh rm -f *.txt *.sh ls rm system rm test ls rm in1 in2 ls rm out ls clear exit hostname write gjspangl writwrite gjspangl raalston write gjspangl raalston can can you kajdf sldjf write write gjspangl write raalston msg n who write bji ls cd public_html cd ls cd /afs/cats.ucsc.edu/courses/cmps012b-wm/Labs-cmps012m ls cd cs112 mkdir scheme cd scheme vi helloworld.scm ls echo > helloworld.scm ls echo Makefile ls cd cs112 ls cd scheme ls ls /a ls ls -a more .bash_profile vim .bash_profiel vim .bash_profile more .bash_profile ls cd cs112 cd scheme ls -a more more .bash more .bash_profile chsh vi echo "export PATH=$PATH:/afs/cats.ucsc.edu/users/a/amelton/programs/" >> ~/.bash_profile; more more .bash_profile echo "export cmps112=$courses/cmps112-wm" >> ~/.bash_profile; echo "export PATH=$PATH:$cmps112/usr/racket/bin" >> ~/.bash_profile; mzscheme ./mzscheme ls cd cs112 more .bash_profile cd .. more .bash_profile vim .bash_profile rm .bash_profile vim .bash_profile mzscheme ls mzscheme ls more more .bash_profile vim .bash_profile mzscheme pwd ls mzscheme (define (cube n)(* n n n)) mzscheme clear mzscheme clear ls cd cs112 ls cd scheme ls mzscheme readwords.scm which mzscheme which mzscheme readwords.scm sbi.scm ./sbi.scm ls ./helloworld.scm ./readwords.scm chmod chmod helloworld.scm chmod help chmod --help clear ./helloworld.scm chmod chmod helloworld.scm chmod --help chmod -c chmod -c helloworld.scm man chmod q qq clear ssh <EMAIL> fs fs --help fs listacl fs listacl ~/private fs listacl ~/cs112 echo $0 fs listacl clear ls cd perl5 ls ~ cd ~ ls rm perl5 chmod cs112 chmod -r permissionsettings cs112 man chmod chmod -c cs112 chmod cs112 -c clear cd cs112 ls cd scheme ls helloworld.sc helloworld.scm chmod +x helloworld.scm chmod +w helloworld.scm helloworld.scm cd~ chmod +x cs112 ls cd ~ ls chmod +x cs112 chmod +w cs112 chmod --help clear ls cd cs112 ls cd scheme ls readwords.scm chmod x chmod x readwords.scm chmod -x readwords.scm readwords.scm chmod +x readwords.scm readwords.scm clear cd ~ clear ls chmod +x cs101 chmod +x cs112 chmod +x cs12b clear cd cs112 cd scheme ls helloworld.scm vim helloworld.scm clear chmod +x ~ chmod +x clear cd cs112b cd cs112 cd scheme ls vim helloworld.scm vim readwords.scm vim sbi.scm ls clear ls clear ls clear cd ~ ls clear cd cs112b cd cs112 ls clear cd scheme ls clear cd assignment1 ls sbi.scm 02-exprs.sbir chmod +x sbi.scm sbi.scm 02-exprs.sbir ls clear sbi.scm 02-exprs.sbir vim 02-exprs.sbir ls clear ls sbi.scm ls clear vim sbi.scm ls clear cd .. ls helloworld.scm cd cs112 ls cd scheme ls vim helloworld.scm helloworld.scm rm readwords.scm ls clear cd assignment1 ls sci.scm sbi.scm ls clear sbi.scm clear sbi.scm sbi.scm 02-exprs.sbir clear sbi.scm 02-exprs.sbir ls clear cd cd .. ls cd ls ls cd cmps112 cd CMPS112 ls cd Scheme ls helloworld.scm ls cd cs112 cd scheme ls cd ls cd clear ls cd cs112 ls cd scheme ls clear ls sbi.scm 02-exprs.sbir chmod +x sbi.scm ls clear sbi.scm 02-exprs.sbir helloworld.scm ssh <EMAIL> cd cs112 cd scheme ls chmod+ helloworld.scm chmod +x helloworld.scm helloworld.scm clear ls helloworld.scm ls sbi.scm chmod +x sbi.scm ls chmod.scm 02-exprs.sbir chmod +x 02-exprs.sbir ls sbi.scm 02-exprs.sbir mzscheme cd cs112 ls cd scheme ls chmod +x hello.scm hello.scm mzscheme <file_sep>/perl/asg4/bad.c /* $Id: bad.c,v 1.1 2011-03-24 17:25:20-07 - - $ */ This is a bad file. cc won't compile it. <file_sep>/perl/asg4/hello.c /* $Id: hello.c,v 1.1 2011-03-24 17:24:59-07 - - $ */ #include "hello.h" void hello (void) { printf ("Hello, world.\n"); } <file_sep>/perl/asg4/Makefile # $Id: Makefile,v 1.1 2011-03-24 17:24:59-07 - - $ all : hello hello : main.o hello.o gcc main.o hello.o -o hello main.o : main.c hello.h gcc -c main.c hello.o : hello.c hello.h gcc -c hello.c ci : Makefile main.c hello.c hello.h cid Makefile main.c hello.c hello.h test : hello ./hello clean : - rm hello.o main.o spotless : clean - rm hello <file_sep>/perl/asg4/main.c /* $Id: main.c,v 1.1 2011-03-24 17:24:59-07 - - $ */ #include "hello.h" int main (void) { hello (); return 0; }
9a603ba8862090d004047ec0100b4a689b10f117
[ "Markdown", "C", "Makefile", "Shell" ]
10
C
alyssue/cmps112
1a4c885321d50a4a965f9f748703824750903a16
1db5ac57695a85772db6304ebb415165a5d45eff
refs/heads/master
<repo_name>pogrammist/SkillboxAndroidKotlinPart1<file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/Weapons.kt package com.example.kotlin410objectorientedprogramming import com.example.kotlin410objectorientedprogramming.Ammo.* import com.example.kotlin410objectorientedprogramming.FireType.* object Weapons { val machineGun = object : AbstractWeapon( maxAmmo = 100, fireType = BurstsShooting(ammo = BULLET, repeat = 10) ) { override fun makeShell(): Ammo { return fireType.ammo } } val grenadeLauncher = object : AbstractWeapon( maxAmmo = 1, fireType = SingleShooting(ammo = GRENADE) ) { override fun makeShell(): Ammo { return fireType.ammo } } val crossbow = object : AbstractWeapon( maxAmmo = 1, fireType = SingleShooting(ammo = ARROW) ) { override fun makeShell(): Ammo { return fireType.ammo } } val arm = object : AbstractWeapon( maxAmmo = 1, fireType = SingleShooting(ammo = DART) ) { override fun makeShell(): Ammo { return fireType.ammo } } val catapult = object : AbstractWeapon( maxAmmo = 9, fireType = BurstsShooting(ammo = CAT, repeat = 9) ) { override fun makeShell(): Ammo { return fireType.ammo } } }<file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/NoAmmoException.kt package com.example.kotlin410objectorientedprogramming class NoAmmoException(message: String) : Exception(message)<file_sep>/kotlin78Toolbar/settings.gradle rootProject.name='kotlin.7.8.Toolbar' include ':app' <file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/Team.kt package com.example.kotlin410objectorientedprogramming import com.example.kotlin410objectorientedprogramming.Weapons.arm import com.example.kotlin410objectorientedprogramming.Weapons.catapult import com.example.kotlin410objectorientedprogramming.Weapons.crossbow import com.example.kotlin410objectorientedprogramming.Weapons.grenadeLauncher import com.example.kotlin410objectorientedprogramming.Weapons.machineGun import kotlin.random.Random class Team(private val countOfWarrior: Int) { private var warriorList: MutableList<Warrior> = mutableListOf() init { makeTeam(countOfWarrior) } private fun makeTeam(countOfWarrior: Int) { while (warriorList.size < countOfWarrior) { when (Random.nextInt(100)) { in 1..20 -> warriorList.add( Shooter( health = 100, chanceOfDodging = 90, accuracy = 90, weapon = arm ) ) in 21..40 -> warriorList.add( Shooter( health = 100, chanceOfDodging = 50, accuracy = 90, weapon = crossbow ) ) in 41..60 -> warriorList.add( Gunner( health = 500, chanceOfDodging = 10, accuracy = 20, weapon = catapult ) ) in 61..80 -> warriorList.add( Juggernaut( health = 1500, chanceOfDodging = 30, accuracy = 60, weapon = machineGun ) ) in 81..100 -> warriorList.add( Juggernaut( health = 1500, chanceOfDodging = 30, accuracy = 30, weapon = grenadeLauncher ) ) } } } fun shuffleWarriorList() { warriorList.shuffle() } fun getWarriorList(): MutableList<Warrior> { return warriorList } }<file_sep>/kotlin.5.7.HigherOrderFunctions/src/Main.kt fun main() { val first = Queue<Any?>() first.enqueue(1) first.enqueue("second") first.enqueue('3') first.enqueue(null) first.enqueue(5) val second = first.filter { it is Int } val three = second::filter { it is Int } println(three.dequeue()) println(three.dequeue()) val ff = Queue<Int>() ff.enqueue(1) ff.enqueue(2) ff.enqueue(3) ff.enqueue(4) val foo = ff.filter(::predict) println(foo.dequeue()) println(foo.dequeue()) } fun predict(it: Int): Boolean { return it % 2 == 0 }<file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/Battle.kt package com.example.kotlin410objectorientedprogramming import com.example.kotlin410objectorientedprogramming.BattleState.* import kotlin.random.Random class Battle(private val countOfWarrior: Int) { private var arrayTeams = Array(2) { Team(countOfWarrior) } private var battleFinished: Boolean = false private var turnFirst: Int = Random.nextInt(2) private val firstTeamHealth: Int get() = arrayTeams[0].getWarriorList().sumBy { it.getCurrentHealth() } private val secondTeamHealth: Int get() = arrayTeams[1].getWarriorList().sumBy { it.getCurrentHealth() } fun startBattle() { if (turnFirst == 1) { arrayTeams.reverse() } println("Начало битвы") while (!battleFinished) { shuffled() when (val battleState = getState()) { is CurrentState -> { battleState.printInConsole() } is FirstTeamWin -> { battleFinished = true battleState.printInConsole() } is SecondTeamWin -> { battleFinished = true battleState.printInConsole() } is Debuxar -> { battleFinished = true battleState.printInConsole() } } } } private fun getState(): BattleState { return if (firstTeamHealth == 0) { SecondTeamWin("Победила вторая команда") } else if (secondTeamHealth == 0) { FirstTeamWin("Победила первая команда") } else if (firstTeamHealth != 0 && secondTeamHealth != 0) { CurrentState("Progress(commandAHealth=$firstTeamHealth, commandBHealth=$secondTeamHealth)") } else { Debuxar("Ничья") } } private fun shuffled() { println("Совершаем ход") arrayTeams.forEach { it.shuffleWarriorList() } arrayTeams.forEach { team -> team.getWarriorList().forEach { warrior -> if (!warrior.isKilled) { val targetWarrior: Warrior? = if (team == arrayTeams[0]) { arrayTeams[1].getWarriorList().lastOrNull { !it.isKilled } } else { arrayTeams[0].getWarriorList().lastOrNull { !it.isKilled } } if (targetWarrior != null) { warrior.attack(targetWarrior) } } } } } }<file_sep>/kotlin.3.9.Kotlin/settings.gradle include ':app' rootProject.name='kotlin.3.9.Kotlin' <file_sep>/kotlin.5.3.Generics/src/Tutorial.kt fun main(args: Array<String>) { val lootBoxOne: LootBox<Fedora> = LootBox( Fedora( "a generic-looking fedora", 15 ) ) val lootBoxTwo: LootBox<Coin> = LootBox(Coin(15)) lootBoxOne.open = true lootBoxOne.fetch()?.run { println("You retrieve a $name from the box!") } val coin = lootBoxOne.fetch() { Coin(it.value * 3) } coin?.let { println(it.value) } } class LootBox<T>(item: T) { var open = false private var loot: T = item fun fetch(): T? { return loot.takeIf { open } } fun <R> fetch(lootModFunction: (T) -> R): R? { return lootModFunction(loot).takeIf { open } } } class Fedora(val name: String, val value: Int) class Coin(val value: Int) <file_sep>/kotlin.6.8.Views/settings.gradle rootProject.name='kotlin.6.8.Views' include ':app' <file_sep>/kotlin.4.5.Collections/app/src/main/java/ru/example/kotlin45collections/Map.kt package ru.example.kotlin79extensionsobjectsenums fun main() { while (true) { val map: MutableMap<String, String> = mutableMapOf() for (item in 1..3) { print("Введите имя человека с номером телефона ") val card = readLine() ?: continue map[card.substringBefore(':')] = card.substringAfterLast(": ") } map.forEach { (k, v) -> println("Человек: $v. Номер телефона: $k") } } }<file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/Warrior.kt package com.example.kotlin410objectorientedprogramming interface Warrior { val isKilled: Boolean val chanceOfDodging: Int fun attack(warrior: Warrior) fun takeDamage(damage: Int) fun getCurrentHealth(): Int }<file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/BattleState.kt package com.example.kotlin410objectorientedprogramming sealed class BattleState(private val state: String) { data class CurrentState(val state: String) : BattleState(state) data class FirstTeamWin(val state: String) : BattleState(state) data class SecondTeamWin(val state: String) : BattleState(state) data class Debuxar(val state: String) : BattleState(state) fun printInConsole() { println(state) } } <file_sep>/kotlin.5.3.Generics/src/Queue.kt class Queue<T> { private val queue: MutableList<T> = mutableListOf() fun enqueue(item: T) { queue.add(item) } fun dequeue(): T? { if (queue.isEmpty()) { return null } val first = queue.first() queue.removeAt(0) return first } }<file_sep>/kotlin.2.14.Gradle/app/src/main/java/com/example/kotlin214gradle/MainActivity.kt package com.example.kotlin214gradle import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView = findViewById<TextView>(R.id.textView) textView.text = """ Flavor=${BuildConfig.FLAVOR} BuildType=${BuildConfig.BUILD_TYPE} VersionCode=${BuildConfig.VERSION_CODE} VersionName=${BuildConfig.VERSION_NAME} ApplicationID=${BuildConfig.APPLICATION_ID} """.trimIndent() } } <file_sep>/kotlin.4.5.Collections/app/src/main/java/ru/example/kotlin45collections/Collections.kt package ru.example.kotlin79extensionsobjectsenums fun main() { while (true) { println("Введите число: ") val listLength = readLine()?.toIntOrNull() ?: continue val list = makePhoneNumberList(listLength) println("Вы ввели список телефонных номеров: $list") if (countOfRussianNumbers(list).isNotEmpty()) { println("Российские телефонные номера: ${countOfRussianNumbers(list)}") } else { "Российские телефонные номера отсутствуют" } println( "Уникальных номеров: ${setOfNumbers(list)}" ) println("Сумма длин всех номеров: ${sumOfNumbers(list)}") } } fun makePhoneNumberList(items: Int): List<String> { val list: MutableList<String> = mutableListOf() for (item in 1..items) { println("Введите $item телефонный номер (+01234567890):") val number = readLine() ?: continue val matchResult = Regex("""\+\d{11}""").find(number) ?: continue list.add(matchResult.value) } return list } fun countOfRussianNumbers(list: List<String>) = list.filter { it.startsWith("+7") } fun setOfNumbers(list: List<String>) = list.toSet().size fun sumOfNumbers(list: List<String>) = list.sumBy { it.substring(1).length } <file_sep>/kotlin.5.7.HigherOrderFunctions/src/Queue.kt class Queue<T> { private var queue: MutableList<T> = mutableListOf() fun enqueue(item: T) { queue.add(item) } fun dequeue(): T? { if (queue.isEmpty()) { return null } val first = queue.first() queue.removeAt(0) return first } fun filter(predicate: (T) -> Boolean): Queue<T> { val newQueue = Queue<T>() queue.filter { predicate(it) }.forEach { newQueue.enqueue(it) } // second variant // newQueue.queue = queue.filter { predicate(it) } as MutableList<T> return newQueue } }<file_sep>/kotlin.6.8.Views/app/src/main/java/com/example/kotlin68views/MainActivity.kt package com.example.kotlin68views import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.PersistableBundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.View import android.widget.* import androidx.constraintlayout.widget.ConstraintSet import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { companion object { private const val FORM_STATE = "Form state" } private val tag = "MainActivity" private var state: FormState? = FormState(true, "") override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(FORM_STATE, state) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) state = savedInstanceState.getParcelable(FORM_STATE) stateTextView.text = state?.message ?: "" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.v(tag, "onCreate was called") Log.d(tag, "onCreate was called") Log.i(tag, "onCreate was called") Log.w(tag, "onCreate was called") Log.e(tag, "onCreate was called") // val progressBar = ProgressBar(this).apply { // id = View.generateViewId() // layoutParams = ConstraintLayout.LayoutParams( // ConstraintLayout.LayoutParams.WRAP_CONTENT, // ConstraintLayout.LayoutParams.MATCH_PARENT // ).apply { // endToEnd = ConstraintLayout.LayoutParams.PARENT_ID // startToStart = ConstraintLayout.LayoutParams.PARENT_ID // } // } // container.addView(progressBar) // val progressBar = ProgressBar(this).apply { // id = View.generateViewId() // } // container.addView(progressBar) // ConstraintSet().apply { // constrainHeight(progressBar.id, ConstraintSet.WRAP_CONTENT) // constrainWidth(progressBar.id, ConstraintSet.WRAP_CONTENT) // connect(progressBar.id,ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.LEFT) // connect(progressBar.id,ConstraintSet.RIGHT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT) // connect(progressBar.id,ConstraintSet.TOP,ConstraintSet.PARENT_ID,ConstraintSet.TOP) // connect(progressBar.id,ConstraintSet.BOTTOM,ConstraintSet.PARENT_ID,ConstraintSet.BOTTOM) // setMargin(progressBar.id, ConstraintSet.LEFT, 110) // applyTo(container) // } val imageLink = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" Glide.with(this).load(imageLink).into(imageView) emailEditText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { if (!emailEditText.isEmailValid()) emailEditText.error = "Please Enter Email Address" } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { loginButton.isEnabled = isAuthValid() } }) passEditText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { if (passEditText.text.isBlank()) passEditText.error = "Please Enter Password" } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { loginButton.isEnabled = isAuthValid() } }) checkBox.setOnCheckedChangeListener { _, _ -> loginButton.isEnabled = isAuthValid() } loginButton.setOnClickListener { if (emailEditText.text.toString().substringAfter('@') != "gmail.com") { emailEditText.error = "Email must be gmail.com" stateTextView.text = getString(R.string.form_not_true) state = FormState(false, getString(R.string.form_not_true)) } if (passEditText.text.length < 10) { passEditText.error = "Password must be 10 characters" stateTextView.text = getString(R.string.form_not_true) state = FormState(false, getString(R.string.form_not_true)) } else { stateTextView.text = "" state = FormState(true, "") makeLongBar() } } imageView.setOnClickListener { Thread.sleep(6000) } } override fun onStart() { super.onStart() Log.v(tag, "onStart was called") Log.d(tag, "onStart was called") Log.i(tag, "onStart was called") Log.w(tag, "onStart was called") Log.e(tag, "onStart was called") } override fun onResume() { super.onResume() Log.v(tag, "onResume was called") Log.d(tag, "onResume was called") Log.i(tag, "onResume was called") Log.w(tag, "onResume was called") Log.e(tag, "onResume was called") } override fun onPause() { super.onPause() Log.v(tag, "onPause was called") Log.d(tag, "onPause was called") Log.i(tag, "onPause was called") Log.w(tag, "onPause was called") Log.e(tag, "onPause was called") } override fun onStop() { super.onStop() Log.v(tag, "onStop was called") Log.d(tag, "onStop was called") Log.i(tag, "onStop was called") Log.w(tag, "onStop was called") Log.e(tag, "onStop was called") } override fun onDestroy() { super.onDestroy() Log.v(tag, "onDestroy was called") Log.d(tag, "onDestroy was called") Log.i(tag, "onDestroy was called") Log.w(tag, "onDestroy was called") Log.e(tag, "onDestroy was called") } private fun EditText.isEmailValid(): Boolean { return android.util.Patterns.EMAIL_ADDRESS.matcher(this.text.toString()).matches() } private fun isAuthValid(): Boolean { return emailEditText.isEmailValid() && passEditText.text.isNotBlank() && checkBox.isChecked } private fun makeLongBar() { emailEditText.isEnabled = false passEditText.isEnabled = false checkBox.isEnabled = false loginButton.isEnabled = false val progressBar = ProgressBar(this).apply { id = View.generateViewId() } container.addView(progressBar) val set = ConstraintSet().apply { constrainHeight(progressBar.id, ConstraintSet.WRAP_CONTENT) constrainWidth(progressBar.id, ConstraintSet.WRAP_CONTENT) connect(progressBar.id, ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT) connect( progressBar.id, ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT ) connect(progressBar.id, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP) connect( progressBar.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM ) applyTo(container) } Handler().postDelayed({ emailEditText.text.clear() emailEditText.isEnabled = true passEditText.text.clear() passEditText.isEnabled = true checkBox.isEnabled = true checkBox.isChecked = false loginButton.isEnabled = true container.removeView(progressBar) Toast.makeText(this, "No connection", Toast.LENGTH_SHORT).show() }, 2000) } } <file_sep>/kotlin.3.9.Kotlin/app/src/main/java/com/example/kotlin39kotlin/Kt.kt package com.example.kotlin39kotlin fun main() { while (true) { println("Введите число чисел: ") val listLength = readLine()?.toIntOrNull() ?: continue val list = makeIntList(listLength) println("Вы ввели список чисел: $list") println("Количество натуральных чисел в массиве: ${countOfNaturalNumbers( list )}") println("Количество четных чисел в массиве: ${countOfEvenNumbers( list )}") println("Четные числа в массиве: ${evenNumbers(list)}") println("Количество уникальных чисел в массиве: ${uniqueNumbers( list ).count()}") val sumNumbers = list.sum() println("Сумма чисел в массиве: $sumNumbers") list.forEach { println( "Число $it, сумма $sumNumbers, НОД ${greatestCommonFactor( it, uniqueNumbers(list).sum() )}" ) } } } fun makeIntList(items: Int): List<Int> { val list: MutableList<Int> = mutableListOf() for (item in 1..items) { println("Введите $item число:") val number = readLine()?.toIntOrNull() ?: continue list.add(number) } return list } fun countOfNaturalNumbers(list: List<Int>) = list.filter { it > 0 }.size fun countOfEvenNumbers(list: List<Int>) = list.filter { it % 2 == 0 }.size fun evenNumbers(list: List<Int>): List<Int> = list.filter { it % 2 == 0 }.map { it } fun uniqueNumbers(list: List<Int>): MutableSet<Int> { val set: MutableSet<Int> = mutableSetOf() list.forEach { set += it } return set } tailrec fun greatestCommonFactor(a: Int, b: Int): Int { if (b == 0) { return a } return greatestCommonFactor(b, a % b) } <file_sep>/kotlin.9.11.Intent/settings.gradle rootProject.name='kotlin.9.11.Intent' include ':app' <file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/FireType.kt package com.example.kotlin410objectorientedprogramming sealed class FireType( open val ammo: Ammo, open val repeat: Int ) { data class SingleShooting( override val ammo: Ammo, override val repeat: Int = 1 ) : FireType(ammo, repeat) data class BurstsShooting( override val ammo: Ammo, override val repeat: Int ) : FireType(ammo, repeat) }<file_sep>/kotlin.5.3.Generics/src/Generics.kt fun main() { val listInt = listOf<Int>(1, 2, 3, 4, 5, 6, 7) println(evenList(listInt)) val listDouble = listOf<Double>(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7) println(evenList(listDouble)) val listFloat = listOf<Float>(1.11f, 2.22f, 3.33f, 4.44f, 5.55f, 6.66f, 7.77f) println(evenList(listFloat)) val listLong = listOf<Long>( 1111111111111111111, 2222222222222222222, 3333333333333333333, 4444444444444444444, 5555555555555555555, 6666666666666666666, 7777777777777777777, 122.2.toLong(), 122.0.toLong() ) println(evenList(listLong)) val queue = Queue<String>() queue.enqueue("first") queue.enqueue("second") println(queue.dequeue()) println(queue.dequeue()) println(queue.dequeue()) //true val first: Result<Int, String>? = getResult(1) val second: Result<Any, String>? = getResult(0) println(first.toString()) println(second.toString()) // false // val three: Result<Int, CharSequence>? = getResult(1) // val four: Result<Int, Any>? = getResult(0) // println(three.toString()) // println(four.toString()) }<file_sep>/kotlin.2.5.KotlinBasics/app/src/main/java/ru/example/kotlin25kotlinbasics/KotlinBasics.kt package ru.example.kotlin25kotlinbasics fun main() { foo() } fun foo() { var age: Int = 23 println(age) age = 56 println(age) val firstName: String = "Василий" val lastName: String = "Пупкин" var height: Int = 160 var weight: Float = 50F val isChild: Boolean = height < 150 || weight < 40F var isChildren: Boolean = height < 150 || weight < 40F println(isChild) println(isChildren) var info: String = "name: $firstName, lastname: $lastName, " + "height: $height, weight: $weight, isChild: $isChild, isChildren: $isChildren, ${height < 150 || weight < 40F}" println("Summary info: $info") val info2: String = "name: $firstName, lastname: $lastName, " + "height: $height, weight: $weight, isChild: $isChild, isChildren: $isChildren, ${height < 150 || weight < 40F}" println("Summary info: $info2") height = 50 println(height) weight = 30F println(weight) println(isChild) println(isChildren) println(height < 150 || weight < 40F) println("Updated summary info: $info") println("Updated summary info: $info2") println( "Updated summary info: name: $firstName, lastname: $lastName, \" +\n" + " \"height: $height, weight: $weight, isChild: $isChild, isChildren: $isChildren, ${height < 150 || weight < 40F}" ) }<file_sep>/kotlin.5.3.Generics/src/Result.kt sealed class Result<out T, R> data class Success<T, R>(val t: T) : Result<T, R>() data class Error<T, R>(val r: R) : Result<T, R>() fun getResult(request: Int): Result<Int, String>? { return when (request) { 1 -> { Success(1) } 0 -> { Error("Error") } else -> null } }<file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/AbstractWarrior.kt package com.example.kotlin410objectorientedprogramming abstract class AbstractWarrior( var health: Int, override val chanceOfDodging: Int, val accuracy: Int, private val weapon: AbstractWeapon ) : Warrior { override val isKilled: Boolean get() = health == 0 init { println("Рекрутирован $this") weapon.reload() } override fun attack(warrior: Warrior) { try { val damage = weapon.getShell().sumBy { it.getDamage() } println("$this атакует $warrior") warrior.takeDamage(damage) } catch (ex: NoAmmoException) { println(ex.message) println("Требуется перезарядка") weapon.reload() } } override fun takeDamage(damage: Int) { health = if (health - damage < 0) 0 else health - damage if (isKilled) { println("$this понес урон $damage и погиб") } else { println("$this понес урон $damage") } } override fun getCurrentHealth(): Int { return health } override fun toString(): String { return health.toString() } }<file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/AbstractWeapon.kt package com.example.kotlin410objectorientedprogramming abstract class AbstractWeapon( val maxAmmo: Int, val fireType: FireType ) { private var ammoList: MutableList<Ammo> = mutableListOf() private var shells: MutableList<Ammo> = mutableListOf() private val ammoIsEmpty: Boolean get() = ammoList.isEmpty() init { // println("Инициализировано оружие ${this.fireType}, магазин пуст") } abstract fun makeShell(): Ammo fun reload() { for (shell in 1..maxAmmo) { ammoList.add(makeShell()) } println("Заряжен ${ammoList.size} заряд ${fireType.ammo}") } // fun getShell(): List<Ammo> { // if (ammoIsEmpty) { // reload() // } else { // var count = fireType.repeat // while (!ammoIsEmpty && count > 0) { // shells.add(ammoList.last()) // ammoList.removeAt(ammoList.lastIndex) // count-- // } // } // return shells // } fun getShell(): List<Ammo> { var count = fireType.repeat while (count > 0) { if (ammoIsEmpty) throw NoAmmoException("Боекомплект пуст") shells.add(ammoList.last()) ammoList.removeAt(ammoList.lastIndex) count-- } return shells } }<file_sep>/kotlin.9.11.Intent/app/src/main/java/com/example/kotlin911intent/EnabledActivity.kt package com.example.kotlin911intent import android.os.Bundle import android.util.Patterns import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_enabled.* class EnabledActivity : AppCompatActivity() { companion object { private const val DIAL_REQUEST_CODE = 100 } //Do not work with alpha05, do not have dial method private val dialLauncher = prepareCall(ActivityResultContracts.Dial()) { result -> // Did not answer with "We called" if (result) { println(result.toString()) toast("We did call") } else { println(result.toString()) toast("We did not call") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_enabled) callButton.setOnClickListener { val phoneNumber = phoneNumberEditText.text.toString() val isPhoneNumberValid = Patterns.PHONE.matcher(phoneNumber).matches() if (!isPhoneNumberValid) { toast("Type valid phone number") } else { dialLauncher.launch(phoneNumber) // val phoneIntent = Intent(Intent.ACTION_DIAL).apply { // data = Uri.parse("tel:$phoneNumber") // } // if (phoneIntent.resolveActivity(packageManager) != null) { // startActivityForResult(phoneIntent, DIAL_REQUEST_CODE) // } } } } // Did not answer with "We called" // override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { // if (requestCode == DIAL_REQUEST_CODE) { // if (resultCode == Activity.RESULT_OK) { // toast("We did call") // } else { // toast("We did not call") // } // } else { // super.onActivityResult(requestCode, resultCode, data) // } // } private fun toast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } }<file_sep>/kotlin.9.11.Intent/app/src/main/java/com/example/kotlin911intent/DeeplinkActivity.kt package com.example.kotlin911intent import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activitu_deeplink.* class DeeplinkActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activitu_deeplink) handleIntentData() } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) handleIntentData() } private fun handleIntentData() { intent.data?.let { data -> urlTextView.text = data.host + data.path } } }<file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/TestAmmo.kt package com.example.kotlin410objectorientedprogramming fun main() { println("Пуля нанесла урон ${Ammo.BULLET.getDamage()} единиц") println("Граната нанесла урон ${Ammo.GRENADE.getDamage()} единиц") println("Стрела нанесла урон ${Ammo.ARROW.getDamage()} единиц") println("Дротик нанес урон ${Ammo.DART.getDamage()} единиц") println("Котик нанес урон ${Ammo.CAT.getDamage()} единиц") val bullet = Ammo.BULLET val dart = Ammo.DART println("Пуля нанесла урон ${bullet.getDamage()} единиц") println("Дротик нанес урон ${dart.getDamage()} единиц") println("Пуля нанесла больше урона на ${bullet.compareDamage(dart)} единиц чем дротик") val bullet2 = Ammo.BULLET val dart2 = Ammo.DART println("Пуля нанесла урон ${bullet2.getDamage()} единиц") println("Дротик нанес урон ${dart2.getDamage()} единиц") println("Пуля нанесла больше урона на ${bullet2.compareDamage(dart2)} единиц чем дротик") println(Ammo.valueOf("DART")) Ammo.values().forEach { println(it) println(it.name) println(it.ordinal) } var team = Team(5) println(team.getWarriorList()[1].takeDamage(10000)) println(team.getWarriorList()[2].takeDamage(10000)) println(team.getWarriorList()[4].takeDamage(10000)) println(team.getWarriorList().lastOrNull { !it.isKilled }?.getCurrentHealth()) }<file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/Ammo.kt package com.example.kotlin410objectorientedprogramming import kotlin.random.Random enum class Ammo( damage: Int, chanceOfMaxDamage: Int, ratioOfMaxDamage: Int ) { BULLET(damage = 30, chanceOfMaxDamage = 50, ratioOfMaxDamage = 25), GRENADE(damage = 80, chanceOfMaxDamage = 70, ratioOfMaxDamage = 50), ARROW(damage = 50, chanceOfMaxDamage = 30, ratioOfMaxDamage = 75), DART(damage = 20, chanceOfMaxDamage = 10, ratioOfMaxDamage = 75), CAT(damage = 100, chanceOfMaxDamage = 90, ratioOfMaxDamage = 100); private var currentDamage: Int init { val chance = Random.nextInt(100) > chanceOfMaxDamage val maxDamage = if (chance) 0 else (0..ratioOfMaxDamage).shuffled().last() currentDamage = damage + maxDamage } fun getDamage(): Int { return currentDamage } fun compareDamage(ammo: Ammo): Int { return currentDamage - ammo.currentDamage } } <file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/Main.kt package com.example.kotlin410objectorientedprogramming fun main() { while (true) { print("Введите количество воинов: ") val teamCount = readLine()?.toIntOrNull() ?: continue val battle = Battle(teamCount) battle.startBattle() } }<file_sep>/kotlin.5.3.Generics/src/evenList.kt fun evenList(list: List<Number>): List<Number> { return list.filter { it.toLong() % 2 == 0L } } fun <T : Number> evenListWithoutMaxLong(list: List<T>): List<T> { return list.filter { kotlin.math.round(it.toDouble()) == it.toDouble() }.filter { it.toLong() % 2 == 0L } } fun <T : Number> evenListWithMaxLong(list: List<T>): List<T> { val evenList: MutableList<T> = mutableListOf() for (x in list) { if (x is Long && (x == Long.MAX_VALUE)) { continue } val l = x.toLong() if (l < Long.MAX_VALUE) { if (kotlin.math.round(x.toDouble()) == x.toDouble() && l % 2 == 0L) { evenList.add(x) } } else { evenList.add(x) } } return evenList }<file_sep>/kotlin78Toolbar/app/src/main/java/com/example/kotlin78toolbar/ToolbarActivity.kt package com.example.kotlin78toolbar import android.os.Bundle import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import kotlinx.android.synthetic.main.activity_toolbar.* class ToolbarActivity : AppCompatActivity() { private val users = listOf( "User1", "User2", "Unknown" ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_toolbar) initToolbar() } private fun toast(text: String) { Toast.makeText(this, text, Toast.LENGTH_SHORT).show() } private fun initToolbar() { toolbar.setNavigationOnClickListener { toast("Navigation clicked") } toolbar.setOnMenuItemClickListener { menuItem -> when (menuItem.itemId) { R.id.action_1 -> { toast("action 1 clicked") true } R.id.action_2 -> { toast("action 2 clicked") true } R.id.action_3 -> { toast("action 3 clicked") true } R.id.action_4 -> { toast("action 4 clicked") true } R.id.action_5 -> { toast("action 5 clicked") true } R.id.action_6 -> { toast("action 6 clicked") true } R.id.action_search -> { toast("search clicked") true } else -> false } } val searchItem = toolbar.menu.findItem(R.id.action_search) searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { override fun onMenuItemActionExpand(item: MenuItem?): Boolean { expandTextView.text = getString(R.string.search_expanded) toast("search expanded") return true } override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { expandTextView.text = getString(R.string.search_collapse) toast("search collapse") return true } }) (searchItem.actionView as SearchView).setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { return true } override fun onQueryTextChange(newText: String?): Boolean { users.filter { it.contains(newText ?: "", ignoreCase = true) } .joinToString() .let { searchResultTextView.text = it } return true } }) } }<file_sep>/kotlin.9.11.Intent/app/src/main/java/com/example/kotlin911intent/MainActivity.kt package com.example.kotlin911intent import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Patterns import android.widget.* import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { companion object { private const val FORM_STATE = "Form state" } private var state: FormState? = FormState(true, "") override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(FORM_STATE, state) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) state = savedInstanceState.getParcelable(FORM_STATE) stateTextView.text = state?.message ?: "" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val imageLink = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" Glide.with(this).load(imageLink).into(imageView) emailEditText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) {} override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { loginButton.isEnabled = isAuthValid() } }) passEditText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) {} override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { loginButton.isEnabled = isAuthValid() } }) checkBox.setOnCheckedChangeListener { _, _ -> loginButton.isEnabled = isAuthValid() } loginButton.setOnClickListener { val enabledActivityIntent = Intent(this, EnabledActivity::class.java) startActivity(enabledActivityIntent) } } private fun EditText.isEmailValid(): Boolean { return Patterns.EMAIL_ADDRESS.matcher(this.text.toString()).matches() } private fun isAuthValid(): Boolean { return emailEditText.isEmailValid() && emailEditText.text.toString().substringAfter('@') == "gmail.com" && passEditText.text.isNotBlank() && checkBox.isChecked } } <file_sep>/kotlin.2.14.Gradle/settings.gradle include ':app' rootProject.name='kotlin.2.14.Gradle' <file_sep>/kotlin.4.10.ObjectOrientedProgramming/src/Gunner.kt package com.example.kotlin410objectorientedprogramming class Gunner( health: Int, chanceOfDodging: Int, accuracy: Int, weapon: AbstractWeapon ) : AbstractWarrior(health, chanceOfDodging, accuracy, weapon) { override fun toString(): String { return "Gunner[${super.toString()}]" } }
0ff668454e0f3930ad7bef50953dc86d4f58ab77
[ "Kotlin", "Gradle" ]
35
Kotlin
pogrammist/SkillboxAndroidKotlinPart1
c1045a9b682876b3ec6a5339faa994605d3cb38b
aa96e50c575761bb6f699a573afdf68717a362d2
refs/heads/main
<file_sep>import mongoose from 'mongoose'; const User = mongoose.model( 'User', new mongoose.Schema( { first_name: String, last_name: String, email: String, username: String, password: String, user_id: String, }, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at', }, } ) ); export {User as default};<file_sep>import gql from 'graphql-tag'; const loginMutation = gql` mutation login($username: String!, $password: String!) { login(username: $username, password: $password) } `; export default loginMutation;<file_sep>import { createApp } from "vue"; import { createRouter, createWebHistory } from "vue-router"; import store from "./store"; import routes from "./routes"; import App from "./App.vue"; import "./assets/tailwind.css"; const router = createRouter({ history: createWebHistory(), routes, }); router.beforeEach((to, from, next) => { const isLoggedIn = store.getters.isLoggedIn; if (to.matched.some((entry) => entry.meta?.requiresAuth)) { if (isLoggedIn) { store.dispatch("getCurrentUser"); next(); } else { store.dispatch("logout"); next({ path: "/login" }); } } else { store.dispatch("getCurrentUser"); next(); } }); createApp(App) .use(router) .use(store) .mount("#app"); <file_sep>// import {gql} from 'apollo-server'; // const Mutation = ` // type Mutation { // register(username: String!, password: String!): String // login(username: String!, password: String!): String // } // `; // const typeDefs = gql` // ${Mutation} // `; // export default typeDefs;<file_sep>import gql from 'graphql-tag'; const projects = gql` query projectsQuery { projects { edges { node { id name description created_by } } } } `; export {projects as default};<file_sep>import jwt from 'jsonwebtoken'; import mongoose from 'mongoose'; import {Project, User} from '../models'; const createProject = async (parent, args, context) => { const token = context.authorization.split(' ')[1]; const decoded = jwt.verify(token, process.env.JWT_SECRET); const user = await User.findById(mongoose.Types.ObjectId(decoded.userId)); const project = new Project({ name: args.name, description: args.description, created_by: user.username, }); await project.save(); return project; }; export {createProject as default}; <file_sep>import { createStore } from "vuex"; import actions from "./actions"; import mutations from "./mutations"; const store = createStore({ state: { jwtToken: localStorage.getItem("jwtToken"), currentUser: null, projects: [], }, getters: { isLoggedIn: (state) => !!state.jwtToken, currentUser: (state) => state.currentUser, }, mutations, actions, }); export default store; <file_sep>import gql from 'graphql-tag'; const getCurrentUser = gql` query getCurrentUserQuery { getCurrentUser { id username } } `; export default getCurrentUser;<file_sep>import apolloClient from "../../apollo-client"; import { loginMutation } from "../../graphql/mutations"; import { getCurrentUser } from "../../graphql/queries"; const authActions = { async login({ dispatch }, { username, password }) { // https://blog.logrocket.com/handling-authentication-in-your-graphql-powered-vue-app/ const { data } = await apolloClient.mutate({ mutation: loginMutation, variables: { username, password }, }); localStorage.setItem("jwtToken", data.login); dispatch("getCurrentUser"); }, logout({ commit }) { commit("LOGOUT_USER"); }, async getCurrentUser({ commit }) { const { data } = await apolloClient.query({ query: getCurrentUser, }); commit("SET_CURRENT_USER", data.getCurrentUser); }, }; export default authActions; <file_sep>import {HttpLink} from 'apollo-link-http'; import {ApolloClient, InMemoryCache} from '@apollo/client'; const getHeaders = () => { const headers = {}; const jwtToken = localStorage.getItem('jwtToken'); if (jwtToken) { headers.Authorization = `Bearer ${jwtToken}`; } return headers; }; const Link = new HttpLink({ uri: 'http://localhost:4000/graphql', headers: getHeaders(), }); // https://github.com/learnwithjason/vue-3-and-apollo-client-3/blob/main/src/main.js const apolloClient = new ApolloClient({ link: Link, cache: new InMemoryCache(), }); export default apolloClient; <file_sep>export { default as registerMutation } from "./register"; export { default as loginMutation } from "./login"; export { default as createProjectMutation } from "./create-project"; export { default as updateProjectMutation } from "./update-project"; <file_sep>import bcrypt from 'bcrypt'; import jwt from 'jsonwebtoken'; import {User} from '../models'; const login = async (parent, args) => { const user = await User.findOne({username: args.username}); if (!user) { throw new Error("User not found"); } if (!bcrypt.compareSync(args.password, user.password)) { throw new Error("Invalid password"); } const token = jwt.sign({userId: user.id}, process.env.JWT_SECRET); return token; }; export default login; <file_sep>import {ApolloServer} from 'apollo-server-express'; import express from 'express'; import {readFileSync} from 'fs'; import mongoose from 'mongoose' import resolvers from './resolvers'; require('dotenv').config(); mongoose.connect(process.env.MONGO_URL, {useUnifiedTopology: true}); const app = express(); const typeDefs = readFileSync('./schema/schema.graphql').toString('utf-8'); const server = new ApolloServer({ resolvers, typeDefs, // https://www.apollographql.com/docs/apollo-server/data/resolvers/ context: ({req}) => ({ authorization: req.headers.authorization, }), }); server.applyMiddleware({app}); app.listen({port: 4000}, () => { console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`) });<file_sep>import Register from './components/Register.vue'; import Login from './components/Login.vue'; import Projects from './components/Projects.vue'; import NewProject from './components/NewProject.vue'; import EditProject from './components/EditProject.vue'; import ViewProject from './components/ViewProject.vue'; const routes = [ {path: '/', name: 'Root', component: Projects, meta: {requiresAuth: true}}, {path: '/projects', name: 'Projects', component: Projects, meta: {requiresAuth: true}}, {path: '/projects/new', name: 'New Project', component: NewProject, meta: {requiresAuth: true}}, {path: '/project/:id', name: 'viewProject', component: ViewProject, meta: {requiresAuth: true}}, {path: '/project/:id/edit', name: 'editProject', component: EditProject, meta: {requiresAuth: true}}, {path: '/register', name: 'Register', component: Register}, {path: '/login', name: 'Login', component: Login}, ]; export default routes;<file_sep>import {Project} from '../models'; import mongoose from 'mongoose'; const project = async (parent, args) => { const project = await Project.findById(mongoose.Types.ObjectId(args.id)); return project; }; export {project as default};<file_sep>import {Project} from '../models'; const projects = async () => { const allProjects = await Project.find(); return {edges: allProjects.map((project) => ({node: project}))}; }; export {projects as default};<file_sep>import gql from "graphql-tag"; const updateProjectMutation = gql` mutation updateProject( $projectId: ID! $name: String! $description: String ) { updateProject( projectId: $projectId name: $name description: $description ) { id name description } } `; export { updateProjectMutation as default }; <file_sep>import { map } from "lodash"; import apolloClient from "../../apollo-client"; import { projectsQuery } from "../../graphql/queries"; const projectsActions = { async fetchProjects({ commit }) { const { data } = await apolloClient.query({ query: projectsQuery, }); commit("setProjects", map(data.projects.edges, "node")); }, }; export default projectsActions; <file_sep>import mongoose from 'mongoose'; const Project = mongoose.model( 'Project', new mongoose.Schema( { name: String, description: String, created_by: String }, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at', }, } ) ); export {Project as default}; <file_sep>export {default as getCurrentUser} from './get-current-user'; export {default as projectQuery} from './project'; export {default as projectsQuery} from './projects';<file_sep>import authActions from "./auth"; import projectsActions from "./projects"; const actions = { ...authActions, ...projectsActions, }; export default actions; <file_sep>import mongoose from "mongoose"; import { Project } from "../models"; const updateProject = async (parent, args) => { const project = await Project.findById( mongoose.Types.ObjectId(args.projectId) ); await project.updateOne({ name: args.name, description: args.description, }); return project; }; export { updateProject as default };
4e0735468eda717c5be440242ae200c02eb1bc11
[ "JavaScript" ]
22
JavaScript
trivektor/vue-ticket-tracking
1a738781a950942a5a680674e76e8007f6d7f632
b5bee0e3a759f3b4bde379ee20e14d5d7867414a
refs/heads/master
<repo_name>novakvova/TCPCHAT<file_sep>/TCPClientCon/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace TCPClientCon { class Program { static void Main(string[] args) { //Connect("10.7.180.103", "Kovbasa"); Connect("127.0.0.1", "Kovbasa"); } static void Connect(string server, string message) { try { int port = 9999; TcpClient client = new TcpClient(server, port); Byte[] data = Encoding.Unicode.GetBytes(message); NetworkStream stream = client.GetStream(); stream.Write(data, 0, data.Length); Console.WriteLine($"Send: {message}"); data = new byte[256]; string resposeData = string.Empty; int bytes = stream.Read(data, 0, data.Length); resposeData = Encoding.Unicode.GetString(data, 0, bytes); Console.WriteLine($"Received: {resposeData}"); stream.Close(); client.Close(); } catch (Exception ex) { ; } } } } <file_sep>/TCPServer/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace TCPServer { class Program { static void Main(string[] args) { TcpListener server = null; try { int maxThreadCount = Environment.ProcessorCount * 4; Console.WriteLine($"Максиальна кількість потоків {maxThreadCount}"); ThreadPool.SetMaxThreads(maxThreadCount, maxThreadCount); ThreadPool.SetMinThreads(2, 2); int port = 9999; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); //IPAddress localAddr = IPAddress.Parse("10.7.180.103"); int counter = 0; server = new TcpListener(localAddr, port); server.Start(); while(true) { Console.WriteLine("Server for connection ..."); ThreadPool.QueueUserWorkItem(ObrabotkaCleint, server.AcceptTcpClient()); counter++; Console.WriteLine($"\n Connection #{counter}"); } } catch (Exception) { ; } } private static void ObrabotkaCleint(object client_obj) { Byte[] bytes = new Byte[256]; String data = null; Thread.Sleep(1000); TcpClient client = client_obj as TcpClient; NetworkStream stream = client.GetStream(); Int32 i = 0; while ((i=stream.Read(bytes, 0, bytes.Length))!=0) { data = System.Text.Encoding.Unicode.GetString(bytes, 0, i); Console.WriteLine(data); data = data.ToUpper(); Byte[] message = Encoding.Unicode.GetBytes(data); stream.Write(message, 0, message.Length); } stream.Close(); client.Close(); } } }
b6a204ca9e269fcb3c186a48c50d266e94edeb67
[ "C#" ]
2
C#
novakvova/TCPCHAT
4e7f465733e3c88b28c74838feb33d3dbf0d755c
57fde22ee8b2fb61978adcf21b78be8c057a83db
refs/heads/master
<file_sep>#include <string> #include <vector> #include <algorithm> #include <queue> #include <iostream> using namespace std; int solution(vector<int> scoville, int K) { int answer = 0; priority_queue<int,vector<int>,greater<int> > dq; int k = K; for (int i = 0; i < scoville.size(); i++) { dq.push(scoville[i]); } int one = 0; int two = 0; while (dq.top()<k&&dq.size()>1) { one = dq.top(); dq.pop(); two = dq.top(); dq.pop(); dq.push(one + 2 * two); answer++; } if (dq.top()<k) {//끝내 k를 넘지 못함 answer = -1; } return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); vector<int> v; int k; cin >> k; for (int i = 0; i < 6; i++) { int n; cin >> n; v.push_back(n); } int ans = solution(v,k); cout << ans << '\n'; return 0; }<file_sep>#include <iostream> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int arr[9]; for (int i = 0; i < 9; i++) cin >> arr[i]; int Max = 0; int idx = 0; for (int i = 0; i < 9; i++) { if (Max < arr[i]) { Max = arr[i]; idx = i; } } cout << Max << '\n' << idx+1 << '\n'; return 0; }<file_sep>#include <iostream> #include <cstdlib> #include <vector> #include <algorithm> #include <cstring> using namespace std; vector<int> arr; int n, s; vector<int> output; bool check[21]; vector<int> ans; void get_part(int start,int end_num,int m) { if (end_num == m+1) { int sum = 0; for (unsigned int i = 0; i < output.size(); i++) { sum += output[i]; } ans.push_back(sum); return; } for (int i = start; i <n; i++) { if (check[i]) continue; check[i] = true; output.push_back(arr[i]); get_part(i, end_num+1,m); check[i] = false; output.pop_back(); } } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> s; for (int i = 0; i < n; i++) { int num; cin >> num; arr.push_back(num); } int cnt = 0; sort(arr.begin(), arr.end()); for (unsigned int i = 0; i < n; i++) { if (arr[i] == s) cnt++; } int m = 1; for(int i=m;i<n;i++) get_part(0,0,i); for (unsigned int i = 0; i < ans.size(); i++) { if (ans[i] == s) cnt++; } cout << cnt << '\n'; return 0; }<file_sep>#include <string> #include <vector> #include <queue> #include <iostream> using namespace std; int solution(int bridge_length, int weight, vector<int> truck_weights) { int answer = 0;//รส queue<int> q; int max_size = 0; int siz = 0; int len = truck_weights.size(); for (int i = 0; i < len; i++) { siz = truck_weights[i]; while (true) { if (q.empty()) { q.push(siz); max_size += siz; answer++; break; } if (q.size() == bridge_length) { max_size -= q.front(); q.pop(); } else { if (siz + max_size > weight) { q.push(0); answer++; } else { q.push(siz); max_size += siz; answer++; break; } } } } answer += bridge_length; return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int len, weight; cin >> len >> weight; vector<int> v; for (int i = 0; i < 1; i++) { int num; cin >> num; v.push_back(num); } int ans = solution(len, weight, v); cout << ans << '\n'; return 0; }<file_sep>#include <iostream> #include <queue> #include<string.h> using namespace std; int map[1001][1001] = { 0, }; int visit[1001][1001] = { 0, }; int dx[] = { -1,0,1,0 }; int dy[] = { 0,1,0,-1 }; int m, n; queue<pair<int, int>> q; int bfs() { int nowX, nowY, nextX, nextY; while (!q.empty()) { nowX = q.front().first; nowY = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { nextX = nowX + dx[i]; nextY = nowY + dy[i]; if (0 <= nextX && nextX < n && 0 <= nextY && nextY < m) { if (map[nextX][nextY] == 0 && visit[nextX][nextY] == -1) { q.push({ nextX,nextY }); visit[nextX][nextY] = visit[nowX][nowY] + 1; map[nextX][nextY] = 1; } } } } return visit[nowX][nowY]; } int main(void) { memset(visit, -1, sizeof(visit)); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> m >> n; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int num; cin >> num; map[i][j] = num; if (num == 1) { q.push({ i,j }); visit[i][j] = 0; } } } int day = bfs(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == 0) { cout << -1 << '\n'; return 0; } } } cout << day << '\n'; return 0; }<file_sep>#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; int solution(vector<int> citations) { int answer = 0; vector<int> h_idx; //1.오름 차순으로 2~3가지의 경우 테스트 //2.내림 차순으로 2~3가지의 경우 테스트 sort(citations.begin(), citations.end(), greater<int>()); for (int i = 0; i < citations.size(); i++) { h_idx.push_back(i); } for (int i = 0; i < citations.size(); i++) { if (h_idx[i] + 1 > citations[i]) { return i; } } answer = citations.size(); return answer; }<file_sep>#include <iostream> #include <algorithm> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int total = 0; int cost[4] = { 0, }; for (int i = 1; i <= 3; i++) { cin >> cost[i]; cost[i] = i * cost[i]; } int time[101] = { 0, }; for (int i = 0; i < 3; i++) { int arrival, leave; cin >> arrival >> leave; for (int j = arrival; j < leave; j++) time[j]++; } int len = sizeof(time) / sizeof(int); for (int i = 1; i<len; i++) { total += cost[time[i]]; } cout << total << '\n'; return 0; }<file_sep>#include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; vector<int> solution(vector<int> array, vector<vector<int>> commands) { vector<int> answer; //벡터는 0번부터 시작하기 때문에 맨 앞에 0을 추가합니다. array.insert(array.begin(), 0); //커멘드 사이즈 만큼 돌고(가로) for (int i = 0; i < commands.size(); i++) { vector<int> tmp; for (int j = commands[i][0]; j <= commands[i][1]; j++) {//커맨드 첫번째 적힌수 부터 두번째 적힌수까지 자릅니다. //ex) [2,5,3]이면 2번째 부터 5번째까지 array원소를 잘라서 tmp넣습니다. tmp.push_back(array[j]); } sort(tmp.begin(), tmp.end());//정렬 answer.push_back(tmp[commands[i][2] - 1]);//벡터에서 3번째는 인덱스2를 의미합니다. } return answer; }<file_sep>#include <iostream> #include <algorithm> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); while (true) { int a, b, c; cin >> a >> b >> c; if (a == 0 && b == 0 && c == 0) break; if (a >= b) swap(a, b); if (a >= c) swap(a, c); if (b >= c) swap(b, c); if (c * c == a * a + b * b) cout << "right" << '\n'; else cout << "wrong" << '\n'; } return 0; }<file_sep>#include <iostream> using namespace std; int n; bool c[15][15]; int ans; bool check(int row,int col) { // -(row) for (int i = 0; i < n; i++) { if (i == col) continue; if (c[row][i])//지나가지 x하는 경우 return false; } // |(col) for (int i = 0; i < n; i++) { if (i == row) continue; if (c[i][col])//지나가지 x하는 경우 return false; } // \(왼쪽 대각선) int x = row - 1; int y = col - 1; while (x >= 0 && y >= 0) { if (c[x][y])//지나가지 x하는 경우 return false; x--; y--; } x = row - 1; y = col + 1; while (x >= 0 && y < n) { if (c[x][y])//지나가지 x하는 경우 return false; x--; y++; } return true; } void queen(int row) { if (row == n) { ans += 1; return; } for (int i = 0; i < n; i++) { c[row][i] = true; if (check(row,i)) queen(row + 1); c[row][i] = false; } } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; queen(0); cout << ans << '\n'; return 0; } <file_sep>#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); double m, n; cin >> m >> n; vector<double> ans; for (double i = m; i <= n; i++) { if (int(sqrt(i)) == pow(i,0.5)) { ans.push_back(i); } } double Min = 987654321; int len = ans.size(); double total = 0; if (len != 0) { for (int i = 0; i < len; i++) { if (Min > ans[i]) Min = ans[i]; total += ans[i]; } cout << total << '\n' << Min << '\n'; } else cout << -1 << '\n'; return 0; }<file_sep>#include <iostream> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int m; cin >> m; int cup[4] = { 0,1,2,3 }; for (int i = 1; i <= m; i++) { int x, y; cin >> x >> y; if (x == y) continue; for (int k = 1; k <= m; k++) { int tmp = 0; if (x == cup[k]) { cup[k] = y; }else if (y == cup[k]) { cup[k] = x; } } } cout << cup[1] << '\n'; return 0; }<file_sep>#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; /*string solution(vector<int> numbers) { string answer = ""; string temp = ""; for (int i = 0; i < numbers.size(); i++) { temp += to_string(numbers[i]); } int zero = 0;//zero갯수 for (int i = 0; i < temp.size(); i++) { if (temp[i] == '0') zero++; } vector<int> counter; for (int i = 0; i < numbers.size(); i++) { int cnt = 0; int pre = numbers[i]; while (pre != 0) { pre /= 10; cnt++; } counter.push_back(cnt); } int maxCnt = 0; for (int i = 0; i < counter.size(); i++) { maxCnt = max(counter[i], maxCnt); } vector<int> copys;//numbers조작 않기 위해 복사본 만듦 for (int i = 0; i < numbers.size(); i++) { copys.push_back(numbers[i]); } for (int i = 0; i < counter.size(); i++) { if (counter[i] != maxCnt) { int cnt = counter[i]; while (cnt != maxCnt) { copys[i] *= 10; cnt++; } } } sort(copys.begin(), copys.end(), greater<int>()); for (int i = 0; i < copys.size(); i++) { answer += to_string(copys[i]); } int copy_zero = 0; for (int i = 0; i < answer.size(); i++) { if (answer[i] == '0') copy_zero++; } cout << copy_zero << '\n'; for (int i = 0; i < answer.size(); i++) { if (copy_zero == zero) break; if (answer[i] == '0') { answer[i] = '\0'; } copy_zero--; } return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); vector<int> num; for (int i = 0; i < 5; i++) { int n; cin >> n; num.push_back(n); } string ans = solution(num); cout << ans << '\n'; return 0; }*/ bool cmp(const string& a, const string& b) { if (a + b > b + a) return true; else return false; } string solution(vector<int> numbers) { string answer = ""; vector<string> str_arr; for (int i = 0; i < numbers.size(); i++) str_arr.push_back(to_string(numbers[i])); sort(str_arr.begin(), str_arr.end(), cmp); for (int i = 0; i < str_arr.size();i++) { answer += str_arr[i]; } if (answer[0] == '0')//예외처리 return "0"; return answer; } int main(void) { cin.tie(0); vector<int> num; for (int i = 0; i < 5; i++) { int n; cin >> n; num.push_back(n); } string ans = solution(num); cout << ans << '\n'; return 0; }<file_sep>#include <iostream> #include <string> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); string s; cin >> s; for (int i = 0; i < s.length(); i++) { if (s[i] >= 65 && s[i] < 97) { cout << s[i]; } } return 0; } <file_sep># AllAlgorithmExercises 백준+프로그래머스 <file_sep>#include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; vector<int> solution(vector<int> answers) { vector<int> answer; int st1[5] = { 1,2,3,4,5 }; int st2[8] = { 2,1,2,3,2,4,2,5 }; int st3[10] = { 3,3,1,1,2,2,4,4,5,5 }; int st1_cnt = 0; int st2_cnt = 0; int st3_cnt = 0; for (int i = 0; i < answers.size(); i++) { if (st1[i % 5] == answers[i]) st1_cnt++; if (st2[i % 8] == answers[i]) st2_cnt++; if (st3[i % 10] == answers[i]) st3_cnt++; } cout << st1_cnt << ' ' << st2_cnt << ' ' << st3_cnt << '\n'; int MaxVal = 0; int tmp[3]; tmp[0] = st1_cnt; tmp[1] = st2_cnt; tmp[2] = st3_cnt; for (int i = 0; i < 3; i++) { if (MaxVal < tmp[i]) MaxVal = tmp[i]; } if (MaxVal == st1_cnt) { answer.push_back(1); } if (MaxVal == st2_cnt) { answer.push_back(2); } if (MaxVal == st3_cnt) { answer.push_back(3); } sort(answer.begin(), answer.end()); return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); vector<int> input; for (int i = 0; i < 5; i++) { int num; cin >> num; input.push_back(num); } vector<int> output = solution(input); for (int i : output) { cout << i << '\n'; } return 0; }<file_sep>#include <iostream> using namespace std; void alarm_control(int hr, int min) { if (min < 45) { hr -= 1; min += 60; } else { min -= 45; } cout << hr << ' ' << min << '\n'; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int hour, minute; cin >> hour >> minute; alarm_control(hour, minute); return 0; }<file_sep>#include <iostream> #include <queue> #include <cstring> using namespace std; int dx[4] = { -1,0,1,0 }; int dy[4] = { 0,1,0,-1 }; int map[9][9]; int visit[9][9]; int visit2[9][9]; int n, m; queue<pair<int, int>> q; void bfs() { int nowX, nowY, nextX, nextY; int wall = 0; while (!q.empty()) { nowX = q.front().first; nowY = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { nextX = nowX + dx[i]; nextY = nowY + dy[i]; if (0 <= nextX && nextX < n && 0 <= nextY && nextY < m) { if (map[nextX][nextY] == 0 && visit[nextX][nextY] == 0) { visit[nextX][nextY] = 1; map[nextX][nextY] = 1; wall++; if (wall == 3) { return; } } } } } } void spread() { for (int x = 1; x < n; x++) { for (int y = 1; y < m; y++) { if (map[x][y] == 2) { if (map[x - 1][y] == 0) { map[x - 1][y] = 2; } if (map[x][y + 1] == 0) { map[x][y + 1] = 2; } if (map[x + 1][y] == 0) { map[x + 1][y] = 2; } if (map[x][y - 1] == 0) { map[x][y - 1] = 2; } } } } } int main(void) { memset(visit, 0, sizeof(visit)); memset(visit2, 0, sizeof(visit2)); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> map[i][j]; if (map[i][j] == 2) { visit[i][j] = 1; q.push(make_pair(i, j)); } } } bfs(); spread(); int cnt = 0; cout << '\n' << '\n'; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << map[i][j] << ' '; } cout << '\n'; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == 0) cnt++; } } cout << cnt << '\n'; return 0; }<file_sep>#include <string> #include <vector> #include <deque> #include <iostream> using namespace std; int solution(vector<int> priorities, int location) { int answer = 0;//pop 마다 count deque<int> dq; bool check = true;//1번 2번 구분 int m = location; int len = priorities.size(); for (int i = 0; i < len; i++) { dq.push_back(priorities[i]); } while (!dq.empty()) { check = true; for (int h = 1; h < dq.size(); h++) { if (dq.front() < dq[h]) { check = false; break; } }//h if (check) { dq.pop_front(); answer++; if (m == 0) { return answer; } if (m > 0) m--; else m = dq.size() - 1; } else if (!check) { int n = dq.front(); dq.pop_front(); dq.push_back(n); if (m > 0) m--; else m = dq.size() - 1; } }//dq empty return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int loc; cin >> loc; vector<int> input; for (int i = 0; i < 4; i++) { int n; cin >> n; input.push_back(n); } int ans = solution(input, loc); cout << ans << '\n'; return 0; }<file_sep>#include <iostream> #include <stack> using namespace std; int arr[1000]; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; for (int i = 0; i < n; i++) cin >> arr[i]; int Min = 1000; int idx = 0; for (int i = 0; i < 10; i++) { if (Min > arr[i]) { Min = arr[i]; idx = i; } } stack<int> st; for (int i = idx; i < n; i++) { if (st.top() < arr[i]) { st.push(arr[i]); } else st.pop(); } cout << st.size() << '\n'; return 0; } <file_sep>#include <iostream> using namespace std; void pick(int idx, int cnt) { if (cnt == n / 2) { } } int main(void) { ios_base::sy }<file_sep>#include <string> #include <vector> #include <iostream> using namespace std; vector<int> solution(vector<int> progresses, vector<int> speeds) { vector<int> answer; vector<int> f; int arr[100] = { 0, }; for (int i = 0; i < progresses.size(); i++) { int day = 0; while (progresses[i] < 100) { progresses[i] += speeds[i]; day++; } f.push_back(day); } for (int i = 0; i < f.size() - 1; i++) { if (f[i] > f[i + 1]) { f[i + 1] = f[i]; } } for (int i = 0; i < f.size(); i++) { arr[f[i]]++; //cout << f[i] << ' '; } int tmp = 0; for (int i = 0; i < f.size(); i++) { if(tmp!=arr[f[i]]) answer.push_back(arr[f[i]]); tmp = arr[f[i]]; } return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); vector<int> pr;//진행 vector<int> sp;//스피드 for (int i = 0; i < 6; i++) { int n1, n2; cin >> n1 >> n2; pr.push_back(n1); sp.push_back(n2); } vector<int> out = solution(pr, sp); for (int i : out) { cout << i << '\n'; } return 0; }<file_sep>#include <iostream> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int H, M; cin >> H >> M; if (M - 45 < 0) { M = 45 - M; H--; } else M -= 45; if (H < 0) H = 23; cout << H << ' ' << M << '\n'; return 0; }<file_sep>#include <iostream> #include <cmath> #include <vector> using namespace std; int cnt; vector<pair<int, int> > v; void move(int from, int to) { //cout << from << ' ' << to << '\n'; v.push_back(make_pair(from, to)); } void hanoi(int n, int from, int by, int to) { if (n==1) { move(from, to); } else { hanoi(n - 1, from, to, by); move(from, to); hanoi(n - 1, by, from, to); } cnt++; return; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; hanoi(n, 1,2,3); cout << cnt << '\n'; for (int i = 0; i < v.size(); i++) { cout << v[i].first << ' ' << v[i].second << '\n'; } return 0; }<file_sep>#include <iostream> using namespace std; bool check_row[10][10];//왼쪽인덱스는 index, 오른쪽은 숫자(1~9) bool check_col[10][10]; bool check_three[10][10]; int Map[10][10]; int square(int x, int y) { return (x / 3) * 3 + y / 3; } void sudoku() { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { cout << Map[i][j] << ' '; } cout << '\n'; } } bool check(int n) { if (n == 81) { sudoku(); return true; } int x = n / 9;//행 int y = n % 9; if (Map[x][y] != 0) { return check(n + 1); } else { for (int i = 1; i <= 9; i++) { if (check_row[x][i] == false && check_col[y][i] == false && check_three[square(x, y)][i] == false) { check_row[x][i] = true; check_col[y][i] = true; check_three[square(x, y)][i] = true; Map[x][y] = i; if (check(n + 1)) { return true; } Map[x][y] = 0; check_row[x][i] = false; check_col[y][i] = false; check_three[square(x, y)][i] = false; } } } return false; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { cin >> Map[i][j]; if (Map[i][j] != 0) { check_row[i][Map[i][j]] = true; check_col[j][Map[i][j]] = true; check_three[square(i, j)][Map[i][j]] = true; } } } check(0); return 0; }<file_sep>#include <iostream> #include <algorithm> using namespace std; int arr[1000000]; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; for (int i = 0; i < n; i++) cin >> arr[i]; int Max = -987654321; int Min = 987654321; for (int i = 0; i < n; i++) { Max = max(Max, arr[i]); Min = min(Min, arr[i]); } cout << Min << ' ' << Max << '\n'; return 0; }<file_sep>#include <vector> #include <iostream> using namespace std; int check[1000001] = { 0, }; vector<int> solution(vector<int> arr) { vector<int> answer; for (int i = 0; i < arr.size() - 1; i++) { if (arr[i] == arr[i + 1]) { check[i+1] = i+1; } } for (int i = 0; i < arr.size(); i++) { if (check[i] == 0) answer.push_back(arr[i]); } return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); vector<int> input; for (int i = 0; i < 7; i++) { int num; cin >> num; input.push_back(num); } vector<int> output = solution(input); for (int i : output) { cout << i << ' '; } cout << '\n'; return 0; }<file_sep>#include <iostream> #include <algorithm> #include <vector> using namespace std; char board[51][51]; int visited[51][51]; int dx[2] = { 0,1 }; int dy[2] = { 1,0 }; int n; int sol() { vector<int> v; int result = 1; int len = 1; for (int x = 0; x < n; x++) { for (int y = 0; y < n; y++) { if (board[x][y] == board[x][y + 1]) len++; else { result = max(result, len); len = 1; } } result = max(result, len); len = 1; for (int y = 0; y < n; y++) { if (board[y][x] == board[y + 1][x]) len++; else { result = max(result, len); len = 1; } } result = max(result, len); len = 1; } return result; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> board[i][j]; } } int MaxVal = 1; for (int x = 0; x < n; x++) { for (int y = 0; y < n; y++) { for (int d = 0; d < 2; d++) { int nx = x + dx[d]; int ny = y + dy[d]; if (0 <= nx && nx < n && 0 <= ny && ny < n) { if (!board[x][y]) continue; swap(board[x][y], board[nx][ny]); MaxVal = max(MaxVal, sol()); swap(board[x][y], board[nx][ny]); } } } } cout << MaxVal << '\n'; return 0; }<file_sep>#include <iostream> #include <algorithm> #include <vector> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int> a(n); vector<int> b(n); vector<int> c(n); vector<int> d(n); for (int i = 0; i < n; i++) { cin >> a[i] >> b[i] >> c[i] >> d[i]; } vector<int> first, second; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { first.push_back(a[i] + b[j]); second.push_back(c[i] + d[j]); } } sort(second.begin(), second.end()); long long int ans = 0; for (int number : first) { auto range = equal_range(second.begin(), second.end(), -number);//a+b=-(c+d)되는지 검사해주는 것 ans += range.second - range.first; } cout << ans << '\n'; return 0; }<file_sep>#include <iostream> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); char chess[8][8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { cin >> chess[i][j]; } } int cnt = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (chess[i][j] == 'F') { if (i % 2 == 0 && j % 2 == 0) { cnt++; } else if (i % 2 == 1) { if (j % 2 == 1) { cnt++; } } } } } cout << cnt << '\n'; return 0; }<file_sep>#include <iostream> using namespace std; int dp[101][10]; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long int sum = 0; int n; cin >> n; for (int i = 1; i < 10; i++)//startnum: 1~9 dp[1][i] = 1; for (int i = 2; i <=n; i++) { for (int j = 0; j < 10; j++) { if (j == 0) { dp[i][0] = (dp[i-1][1]) % 1000000000; } else if (j == 9) { dp[i][9] = (dp[i-1][8]) % 1000000000; } else { dp[i][j] = (dp[i - 1][j-1] + dp[i - 1][j+1]) % 1000000000; } } }//n까지 모든 경우의 수(개수) for (int i = 0; i < 10; i++) { sum =(sum+dp[n][i])%1000000000; } cout << sum << '\n'; return 0; }<file_sep>#include <iostream> #include <queue> using namespace std; queue<int> q; int visit[100000]; int dx[] = { -1,0,1,0 }; int n, k; void bfs() { int now, next; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); } <file_sep>#include <iostream> #include <cstring> #include <queue> #include <algorithm> using namespace std; int dx[4] = {0,1,0,-1}; int dy[4] = {-1,0,1,0}; int map[101][101]; int visit[101][101]; int ex, ey;//끝점 int m, n, k; queue<pair<int, int>> q; vector<int> ans; int area=0; void bfs(int sx,int sy) { int total = 0; int x, y; map[sx][sy] = 1; q.push(make_pair(sx, sy)); while (!q.empty()) { x = q.front().first; y = q.front().second; q.pop(); total++; for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (0 <= nx && nx < m && 0 <= ny && ny < n) { if (map[nx][ny] == -1) { map[nx][ny] = 1; q.push(make_pair(nx, ny)); } } } } ans.push_back(total); area++; } int main(void) { memset(map, -1, sizeof(map)); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> m >> n >> k; for (int i = 0; i < k; i++) { int sx, sy;//시작점 cin >> sx >> sy >> ex >> ey; for (int k = ey - 1; k >= sy; k--) { for (int j = ex - 1; j >= sx; j--) { map[k][j] = 0; } }//음영부분은 0으로+ 컴퓨터의 배열 접근 순서가 반대로 있을때 반복문 돌리는 방법(즉 우리가 일반적으로 쓰는 좌표평면일때) } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (map[i][j] == -1) { bfs(i, j); } } } sort(ans.begin(), ans.end()); cout << area << '\n'; for (unsigned int i = 0; i < ans.size(); i++) cout << ans[i] << ' '; return 0; }<file_sep>#include <iostream> #include <queue> using namespace std; char adj[21][21]; int visit[21][21]; int n, m; queue<pair<int, int>> q; int dx[4] = { -1,0,1,0 }; int dy[4] = { 0,1,0,-1 }; int cnt = 0; int bfs(){ int nowX, nowY, nextX, nextY; while (!q.empty()) { nowX = q.front().first; nowY = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { nextX = nowX + dx[i]; nextY = nowY + dy[i]; if (0 <= nextX && nextX < n && 0 <= nextY && nextY < m) { if (adj[nextX][nextY] == '.' && visit[nextX][nextY] == 0) { q.push({ nextX,nextY }); visit[nextX][nextY] = visit[nowX][nowY] + 1; cnt++; } } } } return visit[nowX][nowY]; } int main(void) { memset(visit, 0, sizeof(visit)); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> adj[i][j]; if (adj[i][j] == 'o') { visit[i][j] = 1; q.push({ i,j }); } } } int ans = bfs(); if (ans == -1 || cnt > 10) cout << -1 << '\n'; else cout << ans << '\n'; return 0; }<file_sep>#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; void borrow_cloth(int arr[], int n) { if (arr[n - 1] == 2 || arr[n + 1] == 2) { if (arr[n] == 0 && arr[n + 1] == 2) { arr[n] = 1; arr[n + 1] = 1; }else if (arr[n] == 0 && arr[n - 1] == 2) { arr[n] = 1; arr[n - 1] = 1; } } } int solution(int n, vector<int> lost, vector<int> reserve) { int answer = 0; int lost_counter = 0; int* arr = new int[n + 2]; arr[0] = 0; arr[n + 1] = 0; for (int i = 1; i <= n; i++) arr[i] = 1; for (int i = 0;i<lost.size(); i++) { arr[lost[i]] -= 1; } for (int i = 0; i < reserve.size(); i++) { arr[reserve[i]] += 1; } for (int i = 1; i <= n; i++) { if (arr[i] == 0) borrow_cloth(arr, i); } for (int i = 1; i <= n; i++) { if (arr[i] == 0) lost_counter++; } answer = n - lost_counter; return answer; }<file_sep> #include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; vector<int> solution(vector<int> array, vector<vector<int>> commands) { vector<int> answer; //벡터의 start는 0부터인데 문제에서 인덱스의 첫번째는 1번째이므로 0번째에 임의의 숫자 0을 추가 하였습니다. array.insert(array.begin(), 0); //각줄의 원소갯수 i for (int i = 0; i < commands.size(); i++) { vector<int> tmp; for (int j = commands[i][0]; j <= commands[i][1]; j++) {// 각 commands 0번째 숫자부터 1번째숫자까지 array에서 잘라서 //[2,5,3]이면 2번째~5번째까지 array에서 자르겠죠 //임의의 벡터 tmp에 추가합니다. tmp.push_back(array[j]); } sort(tmp.begin(), tmp.end());//정렬 O(nlogn) #include <algorithm> answer.push_back(tmp[commands[i][2] - 1]);//위에서 설명 했다시피 벡터는 0부터 시작하기때문에 //문제에서 의미하는 3번째는 벡터에서 2번째를 의미합니다. } return answer; } <file_sep>#include <iostream> #include <vector> #include <cstring> using namespace std; bool prime[123456 * 2 + 1]; int main(void) { memset(prime, false, sizeof(prime)); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); for (int i = 2; i * i <= 123456*2; i++) { if (prime[i] == false) { for (int j = i * i; j <= 123456 * 2; j+=i) { prime[j] = true; } } } while (true) { int n; cin >> n; if (n == 0) break; int cnt = 0; for (int i = n + 1; i <= 2 * n; i++) { if (prime[i]==false) { cnt++; } } cout << cnt << '\n'; } return 0; }<file_sep>bool cmp(const string& a, const string& b) { if (a + b > b + a) return true; else return false; } string solution(vector<int> numbers) { string answer = ""; vector<string> str_arr; for (int i = 0; i < numbers.size(); i++) str_arr.push_back(to_string(numbers[i])); sort(str_arr.begin(), str_arr.end(), cmp); for (int i = 0; i < str_arr.size(); i++) { answer += str_arr[i]; } if (answer[0] == '0')//¿¹¿Üó¸® return "0"; return answer; }<file_sep>#include <string> #include <vector> #include <algorithm> #include <iostream> #include <stack> using namespace std; /*string solution(string number, int k) { string answer = ""; vector<int> ind; vector<string> ans; string tmp = number; int m = number.length() - k; for (int i = 0; i < m; i++) { ind.push_back(1); } for (int i = 0; i < k; i++) { ind.push_back(0); } sort(ind.begin(), ind.end()); do { string str = ""; for (int i = 0; i < ind.size(); i++) { if (ind[i] == 1) { str += tmp[i]; } } ans.push_back(str); } while (next_permutation(ind.begin(),ind.end())); sort(ans.begin(), ans.end()); answer = ans[ans.size() - 1]; return answer; }*/ string solution(string number, int k) { string answer = ""; stack<char> stk; int siz = number.length() - k; for (int i = 0; i < number.length(); i++) { char ch = number[i]; while (!stk.empty() && k > 0) { if (stk.top() >= ch) break; stk.pop(); k--; } stk.push(ch); } while (stk.size() != siz) stk.pop(); while (!stk.empty()) { char x = stk.top(); answer += x; stk.pop(); } reverse(answer.begin(), answer.end()); return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int k; cin >> k; string input; cin >> input; string out = solution(input, k); cout << out << '\n'; return 0; }<file_sep>#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int index[101] = { 0, }; string word; getline(cin, word); sort(word.begin(), word.end()); for (int i = 0; i < word.size(); i++) { index[word[i] - 'a']++; } for (int i = 0; i < 26; i++) { cout << index[i] << ' '; } return 0; } <file_sep>#include <iostream> using namespace std; void alarm_control(int hr, int min) { if (hr == 0) { hr = 24; } if (min < 45) { hr -= 1; min += 60; min -= 45; } else { min -= 45; } cout << hr << ' ' << min << '\n'; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int hour, minute; cin >> hour >> minute; alarm_control(hour, minute); return 0; }<file_sep>/* */ #include <iostream> #include <queue> #include <algorithm> #include <string> #include <cstring> using namespace std; queue<int> q; int visit[10001]; int dist[10001];//거리 현재는 필요 x char ch[10001];//다음 int from[10001]; string bfs(int a,int b) { visit[a] = 1; q.push(a); string res = ""; while (!q.empty()) { int num = q.front(); q.pop(); int next = (2 * num) % 10000; if (!visit[next]) { visit[next] = 1; q.push(next); dist[next] = dist[num] + 1; from[next] = num; ch[next] = 'D'; } next = num - 1; if (next == -1) next = 9999; if (!visit[next]) { visit[next] = 1; q.push(next); dist[next] = dist[num] + 1; from[next] = num; ch[next] = 'S'; } next = (num % 1000) * 10 + num / 1000; if (!visit[next]) { visit[next] = 1; q.push(next); dist[next] = dist[num] + 1; from[next] = num; ch[next] = 'L'; } next = (num / 10) + (num % 10) * 1000; if (!visit[next]) { visit[next] = 1; q.push(next); dist[next] = dist[num] + 1; from[next] = num; ch[next] = 'R'; } } string ans = ""; while (a != b) { ans += ch[b]; b = from[b]; } reverse(ans.begin(), ans.end()); return ans; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { int a, b;//a 시작 b 끝 cin >> a >> b; string answer= bfs(a, b); cout << answer << '\n'; memset(visit, 0, sizeof(visit)); memset(dist, 0, sizeof(dist)); memset(ch, 0, sizeof(ch)); memset(from, 0, sizeof(from)); } return 0; }<file_sep>#include <string> #include <vector> #include <map> #include <string> #include <vector> #include <map> #include <iostream> #include <algorithm> using namespace std; string solution(vector<string> participant, vector<string> completion) { string answer = ""; completion.push_back(""); sort(participant.begin(), participant.end()); sort(completion.begin(), completion.end()); map<string, string> par; for (int i = 0; i < completion.size(); i++) { par.insert(make_pair(participant[i], completion[i])); } map<string, string>::iterator it; for (it = par.begin(); it != par.end(); it++) { cout << it->first << ' ' << it->second << '\n'; if (it->first != it->second) answer = it->first; } return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); vector<string> p; vector<string> c; int n; cin >> n; for (int i = 0; i < n; i++) { string name; cin >> name; p.push_back(name); } for (int i = 0; i < n - 1; i++) { string name; cin >> name; c.push_back(name); } cout << solution(p, c) << '\n'; return 0; }<file_sep>#include <string> #include <vector> #include <queue> #include <iostream> using namespace std; int solution(int stock, vector<int> dates, vector<int> supplies, int k) { int answer = 0; int Lstock = stock; int idx = 0; priority_queue<int> pq; for (int i = 0; i < k; i++) { if (idx < dates.size() && dates[idx] == i) { pq.push(supplies[idx]); idx++; } if (Lstock == 0) { Lstock += pq.top(); pq.pop(); answer++; } Lstock--; } return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int stock; cin >> stock; vector<int> day(3); vector<int> supply(3); for (int i = 0; i < 3; i++) { cin >> day[i]; } for (int i = 0; i < 3; i++) { cin >> supply[i]; } int k; cin >> k; int ans = solution(stock, day, supply, k); cout << ans << '\n'; return 0; }<file_sep>#include <iostream> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int num; cin >> num; int one = num / 10; int two = num % 10; int cnt = 0; int r = 0; while (true) { int tmp = one + two; r = two * 10 + tmp % 10; cnt++; if (num == r) break; one = r / 10; two = r % 10; } cout << cnt << '\n'; return 0; }<file_sep>#include <iostream> #include <algorithm> #include <string> #include <cstring> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); bool check[1000]; memset(check, true, sizeof(check)); for (int i = 123; i < 1000; i++) { int x = i / 100; int y = (i % 100) / 10; int z = (i % 100) % 10; if (x == y || x == z || y == z) check[i] = false; if (x == 0 || y == 0 || z == 0) check[i] = false; } int n; cin >> n; for (int i = 0; i < n; i++) { int num, s, b;//s strike b ball cin >> num >> s >> b; if (s == 3) { cout << 1 << '\n'; return 0; } string n = to_string(num); int x = num / 100; int y = (num % 100) / 10; int z=(num % 100) % 10; for (int j = 123; j < 1000; j++) { if (check[j] == true) { int strike = 0; int ball = 0; int jx = j / 100; int jy = (j % 100) / 10; int jz = (j % 100) % 10; if (x == jx) strike++; if (y == jy) strike++; if (z == jz) strike++; if (x == jy||x==jz) ball++; if (y == jx||y==jz) ball++; if (z == jx||z==jy) ball++; if (strike != s || ball != b) { check[j] = false; } } } } int cnt = 0; for (int i = 123; i < 1000; i++) { if (check[i] == true) cnt++; } cout << cnt << '\n'; return 0; }<file_sep>#include <iostream> #include <cstring> #include <algorithm> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); string a, b; cin >> a >> b;// 공백으로 구분 int ans = 51;//max 길이 50 //알파벳추가는 최대한같게 비교한다음 a의 빈자리는 b의 빈자리에 해당하는 알파벳으로 채운다.(가정) for (int dis = 0; dis <= b.length() - a.length(); dis++) { int cnt = 0;//다른거 세기 for (int i = 0; i < a.length(); i++) { if (a[i] != b[dis + i]) cnt++; } ans = min(ans, cnt); } cout << ans << '\n'; return 0; }<file_sep>#include <iostream> #include <string> #include <cstring> #include <cstdlib> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; int ans = 0; int num = 666; int cnt = 0; while (true) { string s = to_string(num); if (s.find("666") != string::npos) { cnt++; } if (cnt == n) break; num ++; } cout << num << '\n'; return 0; }<file_sep>#include <iostream> #include <queue> #include <cstring> using namespace std; bool visited[31][31][31]; char graph[31][31][31]; /* 3차원 bfs에서는 queue<pair<pair<int, int>, pair<int, int>> > q; 를 이용해서 횟수, l,r,c를 묶어서 계산하자 2차원에서는 횟수 , r,c 묶어서 계산하자 queue<pair<int,pair<int,int> >q; */ int l, r, c; int dx[6] = { 0,0,1,-1,0,0 }; int dy[6] = { 1,-1,0,0,0,0 }; int dh[6] = { 0,0,0,0,-1,1 }; int l_exit; int x_exit; int y_exit; struct building { int cnt, high, x, y; }; int bfs(int floor, int a, int b) { //struct building build; queue<building> q;//마지막 에 한칸 띄우기 중요!!! int cnt = 0; visited[floor][a][b] = true; q.push({ cnt,floor,a,b }); while (!q.empty()) { int x = q.front().x; int y = q.front().y; int f = q.front().high; cnt = q.front().cnt; q.pop(); if (f == l_exit && x == x_exit && y == y_exit) { return cnt; } for (int i = 0; i < 6; i++) { int nx = x + dx[i]; int ny = y + dy[i]; int high = f + dh[i]; if (1 <= nx && nx <= r && 1 <= ny && ny <= c) { if (1 <= high && high <= l) { if (graph[high][nx][ny] == '#') { //visited[high][nx][ny] = true; continue; } if (graph[high][nx][ny] == '.' ||graph[high][nx][ny] == 'E') { if (!visited[high][nx][ny]) { visited[high][nx][ny] = true; //make_pair(make_pair(cnt+1,high), make_pair(nx, ny)) q.push({ cnt + 1,high,nx,ny }); } } } } }//i } return -1;//0은 답에 포함되므로 } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); while (true) { memset(visited, false, sizeof(visited)); memset(graph, 0, sizeof(graph)); cin >> l >> r >> c; if (l == 0 && r == 0 && c == 0)// l층 r 가로 c 세로 break; //초기화 l_exit = 0; x_exit = 0; y_exit = 0; //i j k for (int i = 1; i <= l; i++) { for (int j = 1; j <= r; j++) { for (int k = 1; k <= c; k++) { cin >> graph[i][j][k]; } } }//i //bool isS = false; int s1 = 0; int s2 = 0; int s3 = 0; for (int i = 1; i <= l; i++) { for (int j = 1; j <= r; j++) { for (int k = 1; k <= c; k++) { if (graph[i][j][k] == 'S') { s1 = i; s2 = j; s3 = k; } else if (graph[i][j][k] == 'E') { l_exit = i; x_exit = j; y_exit = k; } }//k }//j }//i int ans=bfs(s1, s2, s3);//s1 s2 s3 시작점 if (ans==-1) { cout << "Trapped!" << '\n'; } else { cout << "Escaped in" << ' ' << ans << ' ' << "minute(s)." << '\n'; } } return 0; }<file_sep>#include <iostream> #include <vector> #include <algorithm> using namespace std; bool is_eureca(int num,vector<int> output) { for (int a = 0; a * (a + 1) / 2 <= num; a++) { for (int b = 0; b * (b + 1) / 2 <= num; b++) { for (int c = 0; c * (c + 1) / 2 <= num; c++) { if (output[a] + output[b] + output[c] == num) { return true; } } } } return false; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; vector<int> k; for (int i = 0; i < t; i++) { int num; cin >> num; k.push_back(num); } int maxVal = 0; for (int i = 0; i < k.size(); i++) { maxVal = max(maxVal, k[i]); } vector<int> output; for (int i = 1; i<= 45; i++) { output.push_back(i*(i + 1) / 2); } for (int i = 0; i < k.size(); i++) { if (is_eureca(k[i], output)) { cout << 1 << '\n'; } else cout << 0 << '\n'; } return 0; } <file_sep>#include <iostream> #include <cstring> using namespace std; //처음에 라인 바이 라인으로 규칙을 찾으려 했으나 이것은 잘못된 접근방식이란것을 알게됨 //분할정복 //27*27->9*9 이런식으로 쪼개서 다시 합하자 //쪼개서 보자 규칙이 나온다. 같은 형태가 여러개 합쳐서 하나의 형태가 됨 char matrix[2200][2200]; void Star(int a,int b,int end) { if (end == 1) { matrix[a][b] = '*'; return; } int num = end / 3; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) continue;//가운데 else { //matrix[i][j] = '*'; Star(a + i * num, b + j * num, end/3); } } } } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; memset(matrix, ' ', sizeof(matrix)); Star(0,0,n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << matrix[i][j]; } cout << '\n'; } return 0; }<file_sep>#include <iostream> #include <string> using namespace std; int word_length(string s) { int len = 0; for (int i = 0; i < s.length(); i++) len++; return len; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); string str; getline(cin, str); int ans = word_length(str); cout << ans << '\n'; return 0; }<file_sep>#include <string> #include <vector> #include <algorithm> using namespace std; int check[10000000]; int solution(string numbers) { int answer = 0; int len = numbers.length(); sort(numbers.begin(), numbers.end()); for (int i = 2; i <= len; i++) { int ans = select(numbers,0,i); } return answer; } int select(string numbers, int cnt,int m) { vector<int> v; vector<int> output; if (cnt == m) { int num = 0; int mul = 1; for (int i = output.size()-1; i >0; i--) { num = output[i] * mul; mul = } } for (int i = 0; i < numbers.length(); i++) { int num = numbers[i] - '0'; v.push_back(num); } int len = v.size(); for (int i = 0; i < len; i++) { if (check[v[i]]) continue; check[v[i]] = true; output.push_back(v[i]); select(numbers, cnt + 1, m); output.pop_back(); check[v[i]] = false; } }<file_sep>#include <iostream> #include <queue> #include <algorithm> #include <cstring> using namespace std; int cnt; queue<pair<int, int> > q; char board[13][7]; bool visit[13][7] = { false, }; int dx[4] = {-1,0,1,0}; int dy[4] = {0,1,0,-1}; //연속확인시에는 q를 하나더 생성해서 요구하는 크기만큼이 담겨있는지 확인을 해줍니다. int bfs() { while (1) { vector<pair<int, int> > v; memset(visit, false, sizeof(visit)); for (int x = 0; x < 11; x++) { for (int y = 0; y < 6; y++) { if (board[x][y] == '.') { continue; } queue<pair<int, int> > popped_color;//같은 색깔의 puyo가 상하좌우에 4개있는지 확인 char color = board[x][y]; visit[x][y] = true; q.push(make_pair(x, y)); while (!q.empty()) { int CurX = q.front().first; int CurY = q.front().second; popped_color.push(make_pair(CurX, CurY)); q.pop(); for (int i = 0; i < 4; i++) { int nx = CurX + dx[i]; int ny = CurY + dy[i]; if (0 <= nx && nx < 12 && 0 <= ny && ny < 6) { if (board[nx][ny] == color && !visit[nx][ny]) { visit[nx][ny] = true; q.push(make_pair(nx, ny)); } } }//i 방향회전 }//not empty if (popped_color.size() >= 4) { while (!popped_color.empty()) { v.push_back(make_pair(popped_color.front().first, popped_color.front().second)); popped_color.pop(); } }//연속 확인 } } if (v.size() > 0) { sort(v.begin(), v.end()); for (int i = 0; i < v.size(); i++) { for (int j = v[i].first; j > 0; j--) { board[j][v[i].second] = board[j - 1][v[i].second]; } board[0][v[i].second] = '.'; } cnt++; } else break; } return cnt; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); for (int i = 0; i < 12; i++) { for (int j = 0; j < 6; j++) { cin >> board[i][j]; } } int ans = bfs(); cout << ans << '\n'; return 0; }<file_sep>#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; struct sorting { int age; string word; int cnt; }; bool cmp(const sorting s1, const sorting s2) { if (s1.age < s2.age) { return true; } else if (s1.age == s2.age) { return s1.cnt < s2.cnt; } else return false; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; vector<sorting> v; for (int i = 0; i < n; i++) { int age; string word; cin >> age >> word; v.push_back({ age,word,i }); } sort(v.begin(), v.end(),cmp); for (int i = 0; i < v.size()-1; i++) { if (v[i].age == v[i + 1].age) { if (v[i].cnt > v[i + 1].cnt) { swap(v[i].age, v[i + 1].age); swap(v[i].word, v[i + 1].word); swap(v[i].cnt, v[i + 1].cnt); } } } for (int i = 0; i < v.size(); i++) { cout << v[i].age << ' ' << v[i].word << '\n'; } return 0; }<file_sep>#include <iostream> #include <queue> #include <algorithm> using namespace std; int dx[4] = { -1,0,1,0 }; int dy[4] = { 0,1,0,-1 }; int map[9][9]; int visit[9][9]; int n, m, ans; void bfs() { int after[9][9] = { 0, }; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { after[i][j] = map[i][j]; } } queue<pair<int, int>> q; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (after[i][j] == 2) { q.push(make_pair(i, j)); } } } while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { int nextX = x + dx[i]; int nextY = y + dy[i]; if (0 <= nextX && nextX < n && 0 <= nextY && nextY < m) { if (after[nextX][nextY] == 0) { after[nextX][nextY] = 2; q.push(make_pair(nextX, nextY)); } } } } int cnt = 0;//최종 0갯수 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (after[i][j] == 0) cnt++; } } ans = max(cnt, ans); } void wall_make(int cnt) { if (cnt == 3) {//최대 벽의 개수 3개 bfs(); return; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == 0) { map[i][j] = 1; wall_make(cnt + 1); map[i][j] = 0; } } } } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> map[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == 0) {//빈칸발견!! map[i][j] = 1; wall_make(1); map[i][j] = 0; } } } cout << ans << '\n'; return 0; }<file_sep>#include <iostream> #include <string> #include <vector> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); vector<char> v; vector<char> ch;// ) ] while (true) { bool check = true; string s; getline(cin, s); if (s == ".") { break; } for (unsigned int i = 0; i < s.size(); i++) { if (s[i] == '[') { v.push_back('['); }if (s[i] == '(') { v.push_back('('); }if (s[i] == ']') { ch.push_back(']'); if (!v.empty()) { char c = v.back(); if (c == '[') { v.pop_back(); ch.pop_back(); } } }if (s[i] == ')') { ch.push_back(')'); if (!v.empty()) { char c = v.back(); if (c == '(') { v.pop_back(); ch.pop_back(); } } } } if (v.empty()&&ch.empty()) { cout << "yes" << '\n'; } else cout << "no" << '\n'; v.clear(); ch.clear(); } return 0; }<file_sep>#include <iostream> #include <cstring> #include <vector> #include <algorithm> using namespace std; int dx[4] = { -1,0,1,0 }; int dy[4] = { 0,1,0,-1 }; char map[21][21]; int visited[21][21]; int check[21][21];//중복체크 2차원배열 int r, c;//세로 r, 가로 c int cnt = -1; int ans = 0; void dfs(int x, int y) { visited[0][0] = 1; for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (0 <= nx && nx < r && 0 <= ny && ny < c) { if (map[nx][ny] != map[x][y] && visited[nx][ny] == 0) { visited[nx][ny] = 1; cnt++; dfs(nx, ny); } } } ans = max(ans, cnt); } int main(void) { memset(visited, 0, sizeof(visited)); memset(check, 0, sizeof(check)); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> r >> c; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cin >> map[i][j]; } } dfs(0, 0); cout << ans << '\n'; return 0; }<file_sep>#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; /*int solution(vector<int> citations) { int answer = 0; if (citations.size() == 1) { answer = 1; return answer; } vector<int> h_idx; for (int i = 0; i < citations.size(); i++) { h_idx.push_back(i); } //1.오름 차순으로 2~3가지의 경우 테스트 //2.내림 차순으로 2~3가지의 경우 테스트 sort(citations.begin(), citations.end(),greater<int>()); int cnt = 0; for (int i = 0; i < citations.size(); i++) { if (h_idx[i] >= citations[i]) { break; } cnt++; } answer = cnt; return answer; }*/ int solution(vector<int> citations) { int answer = 0; vector<int> h_idx; //1.오름 차순으로 2~3가지의 경우 테스트 //2.내림 차순으로 2~3가지의 경우 테스트 sort(citations.begin(), citations.end(), greater<int>()); for (int i = 0; i < citations.size(); i++) { h_idx.push_back(i); } for (int i = 0; i < citations.size(); i++) { if (h_idx[i] + 1 > citations[i]) { return i; } } answer = citations.size(); return answer; } int main(void) { cin.tie(0); int n; cin >> n; vector<int> num; for (int i = 0; i < n; i++) { int n; cin >> n; num.push_back(n); } int ans = solution(num); cout << ans << '\n'; return 0; }<file_sep>#include <iostream> #include <vector> using namespace std; int arr[10001]; void solution() { for (int i = 1; i <= 10000; i++) { int sum = i; int num = i; while (num != 0) { sum += num % 10; num /= 10; } arr[sum]++; } for (int i = 1; i <= 10000; i++) { if (arr[i] == 0) { cout << i << '\n'; } } } int main(void) { solution(); return 0; }<file_sep>#include <iostream> using namespace std; int n; bool check_row[15]; bool check_col[15]; bool check_dig1[30]; bool check_dig2[30]; int ans; bool check(int row, int col) { if (check_row[row]) return false; if (check_col[col]) return false; if (check_dig1[row + col]) return false; if (check_dig2[row - col + n]) return false; return true; } void queen(int row) { if (row == n) { ans += 1; return; } for (int i = 0; i < n; i++) { if (check(row, i)) { check_row[row] = true; check_col[i] = true; check_dig1[row + i] = true; check_dig2[row - i + n] = true; queen(row + 1); check_row[row] = false; check_col[i] = false; check_dig1[row + i] = false; check_dig2[row - i + n] = false; } } } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; queen(0); cout << ans << '\n'; return 0; } <file_sep>#include <iostream> using namespace std; int solution(int n) { if (n == 0) return 0; if (n == 1) return 1; else return solution(n - 1) + solution(n - 2); } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; int ans = solution(n); cout << ans << '\n'; return 0; }<file_sep>#include <iostream> #include <cmath> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int red, brown; cin >> red >> brown; int total = red + brown; //int mul = total;//가로*세로 //int tmp = brown+5; //int plus = tmp;//가로+세로 int L=0, W=0; int w = 0; for (int i = 1;i<=sqrt(total) ; i++) { if (brown % i == 0) { w = brown / i; if (2 * w + 2 * i + 4 == red) { L = i + 2; W = w + 2; break; } } } cout << W << ' ' << L << '\n'; return 0; }<file_sep>#include <iostream> #include <cstring> #include <queue> using namespace std; int prime[10000]; int visit[10000]; queue<pair<int,int> > q;// prime과 cnt int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { memset(prime, 0, sizeof(prime)); int Start, End; cin >> Start >> End; for (int i = Start; i<= End; i++) { prime[i] = i; } for (int i = Start; i * i <= End; i++) { if (prime[i] == 0) continue; for (int j = i + i; j <= End; j += i) { prime[j] = 0; } }//에라토스테네스의 체 int pre = Start; int cnt = 0; int num = 1;//자리수 for (int i = pre; i <= End;) { if (prime[i] == i && !visit[i]) { cout << i << '\n'; q.push(make_pair(i, cnt + 1)); cnt++; visit[i] = 1; } if (num == 1) { i += 1000; if (i / 1000 == 9) { i = pre; num = 2; } }//첫째자리수 변경 else if (num == 2) { i += 100; if ((i % 1000) / 100 == 0) { i = pre; num = 3; } }//둘째 자리 변경 else if (num == 3) { i += 10; if ((i % 100) / 10 == 0) { i = pre; num = 4; } } else if (num == 4) { i++; if (i % 10 == 0) { break; } } } if (Start == End) { cout << 0 << '\n'; } else if (Start != End) { cout << cnt << '\n'; while (!q.empty()) { q.pop(); } } } return 0; } <file_sep>#include <iostream> #include <cmath> using namespace std; int solution(int n) { int cnt = 0; for (int i = 1; i <= n; i++) { if (i < 100) cnt++; else if (i < 1000) { int x = i / 100; int y = (i % 100) / 10; int z = (i % 100) % 10; if (x - y == y-z) { cnt++; } } } return cnt; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int num; cin >> num; int ans = solution(num); cout << ans << '\n'; return 0; }<file_sep>#include <string> #include <vector> #include <iostream> using namespace std; vector<int> solution(vector<int> prices) { vector<int> answer; vector<int> tmp = prices; int len = tmp.size(); for (int i = 0; i < len; i++) { int count = 0; for (int j = i; j < len; j++) { if (tmp[i] > tmp[j] || j == len - 1) { answer.push_back(count); break; } else { count++; } } } return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); vector<int> price(5); for (int i = 0; i < 5; i++) { cin >> price[i]; } vector<int> ans = solution(price); for (int i = 0; i < ans.size(); i++) { cout << ans[i] << ' '; } cout << '\n'; return 0; }<file_sep>#include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; int solution(int n, vector<int> lost, vector<int> reserve) { int answer = 0; sort(lost.begin(), lost.end());//도난당한학생 vector<int> student; for (int i = 0; i < lost.size(); i++) { student.push_back(lost[i]); } sort(reserve.begin(), reserve.end());//여벌이 있는 학생 vector<int> result; int notVal= 0; for (int i = 0; i < student.size(); i++) { for (int j = i; j < reserve.size(); j++) { if (student[i] == reserve[j]) continue; if (reserve[j] - 1 == student[i] || reserve[j] + 1 == student[i]) { result.push_back(student[i]); break; } } } for (int i = 0; i < reserve.size(); i++) result.push_back(reserve[i]); answer = result.size()+answer; return answer; } int main(void) { int n; cin >> n; vector<int> lost; vector<int> reserve; for (int i = 0; i < 2; i++) { int num; cin >> num; lost.push_back(num); } for (int i = 0; i < 3; i++) { int num; cin >> num; reserve.push_back(num); } int ans=solution(n, lost, reserve); cout << ans; return 0; }<file_sep>#include <iostream> #include <algorithm> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int l, a, b, c, d; //a 국어 b 수학 c 국어 최대 d 수학 최대 cin >> l; cin >> a; cin >> b; cin >> c; cin >> d; int korea_day = a / c; int math_day = b / d; if (a % c != 0) { korea_day++; }if (b % d != 0) { math_day++; } int ans = max(korea_day, math_day); ans = l - ans; cout << ans << '\n'; return 0; }<file_sep>#include <cstdio> using namespace std; int main(void) { int n = 0x00111111; char* c = (char*)& n; if (c[0]) printf("little endian"); else printf("big endian"); return 0; }<file_sep>#include <iostream> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int money; cin >> money; int remain = 1000 - money; int hun_five = remain / 500; int hun = (remain - hun_five * 500)/100; int ten_five = (remain % 100) / 50; int ten = (remain % 100) / 10-(ten_five*5); int five = (remain % 100) % 10 / 5; int one = (remain % 100) % 10 - (five * 5); int sum = hun_five + hun + ten_five + ten + five + one; cout << sum << '\n'; return 0; }<file_sep>#include <iostream> #include <string> #include <stack> using namespace std; int solution(string assignment) { int answer = 0; int len = assignment.length(); stack<char> Stack; for (int i = 0; i < len; i++) { if (assignment[i] == '(') { Stack.push('('); } else if (assignment[i] == ')') { Stack.pop(); if (assignment[i - 1] == '(') {//·¹ÀÌÀú answer += Stack.size(); } else if (assignment[i - 1] == ')') { answer++; } } } return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); string input; cin >> input; int ans = solution(input); cout << ans << '\n'; return 0; }<file_sep>#include <iostream> using namespace std; int n, m; string a[21]; int dx[] = { -1,0,1,0 }; int dy[] = { 0,-1,0,1 }; int two_coin(int stage, int x1, int y1, int x2, int y2) { if (stage > 10) { return -1; } bool fall1 = false; bool fall2 = false; if (x1 < 0 || x1 >= n || y1 < 0 || y1 >= m) fall1 = true; if (x2 < 0 || x2 >= n || y2 < 0 || y2 >= m) fall2 = true; if (fall1 && fall2) return -1; if (fall1 || fall2) return stage; int ans = -1; for (int i = 0; i < 4; i++) { int nx1 = x1 + dx[i]; int ny1 = y1 + dy[i]; int nx2 = x2 + dx[i]; int ny2 = y2 + dy[i]; if (0 <= nx1 && nx1 < n && 0 <= ny1 && ny1 < m && a[nx1][ny1] == '#') { nx1 = x1; ny1 = y1; } if (0 <= nx2 && nx2 < n && 0 <= ny2 && ny2 < m && a[nx2][ny2] == '#') { nx2 = x2; ny2 = y2; } int temp = two_coin(stage + 1, nx1, ny1, nx2, ny2); if (temp == -1) continue; if (ans == -1 || ans > temp) { ans = temp; } } return ans; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; int x1, y1, x2, y2; x1 = y1 = x2 = y2 = -1; for (int i = 0; i < n; i++) { cin >> a[i]; for (int j = 0; j < m; j++) { if (a[i][j] == 'o') { if (x1 == -1) { x1 = i; y1 = j; } else { x2 = i; y2 = j; } a[i][j] = '.'; } } } int ans= two_coin(0, x1, y1, x2, y2); cout << ans << '\n'; return 0; }
9f60f4cdb14d66dfcb6ec88780070ba9b07a172c
[ "Markdown", "C++" ]
72
C++
kdh123456/AllAlgorithmExercises
3add5d081a09b569c6c3a1d55e4a02ab73c1931a
8b0dd6926b3d517ae6404c1da9022fcc22c0796a
refs/heads/master
<repo_name>joelpt/freedom<file_sep>/Assets/RigidbodyFPSWalker.js // TODO when releasing the skiing key, wait a few hundred ms before switching physic materials // and/or grounded state: we don't want to do ground-based deceleration when jetpacking var speed = 10.0; var gravity = 10.0; var maxVelocityChange = 10.0; var canJump = true; var jumpHeight = 1.5; private var grounded = false; var walkingMaterial : UnityEngine.PhysicMaterial; var skiingMaterial : UnityEngine.PhysicMaterial; var skiingBoostPercent = 0.05; var skiingBoostBelowVelocity = 1.0; var skiingDampeningFactor = 0.02; var fuelAirControlFactor = 0.5; var fuelAirControlPenaltyFactor = 0.5; var freeAirControlFactor = 0.2; var airDrag = 0.1; var groundBrakingFactor = 10; @script RequireComponent(Rigidbody, CapsuleCollider) function Awake () { rigidbody.freezeRotation = true; rigidbody.useGravity = false; } function GetGroundNormal() { var dist = 1; var dir : Vector3 = Vector3(0,-1,0); var hit : UnityEngine.RaycastHit; //edit: to draw ray also// //end edit// if (Physics.Raycast(transform.position, dir, hit, dist)) { //Debug.DrawRay(hit.point, hit.normal, Color.red); return hit.normal; } else { return null; } // if(Physics.Raycast(transform.position,dir,hit,dist)) { // //the ray collided with something, you can interact // // with the hit object now by using hit.collider.gameObject // return hit.collider.gameObject; // } // else { // //nothing was below your gameObject within 10m. // return null; // } return null; } function FixedUpdate () { if (Input.GetMouseButton(0)) { Screen.lockCursor = true; // collider.material = walkingMaterial; } //if (grounded) //{ var groundNormal = GetGroundNormal(); //grounded = (groundNormal != null); // Calculate how fast we should be moving var targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); targetVelocity = transform.TransformDirection(targetVelocity); targetVelocity *= speed; var skiing = Input.GetButton("Jump"); var jetpacking = Input.GetMouseButton(1); if (skiing || !grounded || jetpacking) { if (collider.material != skiingMaterial) { collider.material = skiingMaterial; } } else { if (collider.material != walkingMaterial) { collider.material = walkingMaterial; } } if (!grounded) { rigidbody.drag = airDrag; } else { rigidbody.drag = 0; } //grounded = true; //Debug.Log(grounded); if (grounded && !skiing && !jetpacking) { if (rigidbody.velocity.magnitude > speed) { // Decelerate us rigidbody.AddForce(-rigidbody.velocity * groundBrakingFactor); } else if (targetVelocity.magnitude > 0) { // Apply a force that attempts to reach our target velocity var velocity = rigidbody.velocity; var velocityChange = (targetVelocity - velocity); velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange); velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange); velocityChange.y = 0; if (groundNormal != null) { velocityChange = AdjustGroundVelocityToNormal(velocityChange, groundNormal); } rigidbody.AddForce(velocityChange, ForceMode.VelocityChange); } } // else if (!grounded) { // // Apply a force that attempts to accelerate in the desired direction // rigidbody.AddForce(targetVelocity * airControlFactor, ForceMode.Acceleration); // } else if (skiing && grounded) { // Amplify skiing speed slightly when we start out if (rigidbody.velocity.magnitude < skiingBoostBelowVelocity) { rigidbody.AddForce(rigidbody.velocity * skiingBoostPercent, ForceMode.Impulse); } // TODO change our PhysicMaterial instead rigidbody.AddForce(-rigidbody.velocity.normalized * skiingDampeningFactor, ForceMode.Impulse); } if (jetpacking) { //if (grounded) { // rigidbody.velocity = Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z); //} //else { if (targetVelocity.magnitude == 0) { rigidbody.AddForce(Physics.gravity * -jumpHeight); } else { rigidbody.AddForce(Physics.gravity * (1 - fuelAirControlPenaltyFactor) * -jumpHeight); rigidbody.AddForce(targetVelocity * fuelAirControlFactor); } //} } else if (!grounded) { // free air control (takes no fuel) rigidbody.AddForce(targetVelocity * freeAirControlFactor); } // Jump //if (canJump && Input.GetButton("Jump")) //if (Input.GetMouseButton(1)) //{ // rigidbody.velocity = Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z); //} //} //else { // if (Input.GetMouseButton(1)) { // rigidbody.AddForce(Physics.gravity * -10); // } //} // We apply gravity manually for more tuning control rigidbody.AddForce(Vector3 (0, -gravity * rigidbody.mass, 0)); grounded = false; } function OnCollisionStay () { //Debug.Log("ON COLLISION STAY"); grounded = true; } function CalculateJumpVerticalSpeed () { // From the jump height and gravity we deduce the upwards speed // for the character to reach at the apex. return Mathf.Sqrt(2 * jumpHeight * gravity); } function AdjustGroundVelocityToNormal (hVelocity : Vector3, groundNormal : Vector3) : Vector3 { var sideways : Vector3 = Vector3.Cross(Vector3.up, hVelocity); return Vector3.Cross(sideways, groundNormal).normalized * hVelocity.magnitude; } <file_sep>/README.md This is a very early prototype of a racing game focused around freedom of movement and retaining your momentum. The game engine is Unity Free. Read the [design document](https://github.com/joelpt/freedom/wiki/Design-document) for more.
25df01ab99ace4a915623be093292bd363f42aec
[ "JavaScript", "Markdown" ]
2
JavaScript
joelpt/freedom
4beb59376d19cf796b1144b0badf0cbeaec16ef7
d1ad7893cb39b3f1367f74badbda7d822bebb6bc
refs/heads/master
<repo_name>Atul9/repo1<file_sep>/prime_nos.rb require 'prime' Prime.each(100){|prime| puts prime}
5732d74efdc19eac8ce8bb89eb47a04ec5e8fd3c
[ "Ruby" ]
1
Ruby
Atul9/repo1
84856e5a12abbef7278c78de3c1b046ee757cc0f
19b41da69441e249dc5539490fb4cf2d27c8a7e2
refs/heads/master
<repo_name>nosarabs/Analysis-Techniques<file_sep>/main.cpp #include "Datos.h" #include "Parque.h" #include <iostream> #include<time.h> using namespace std; int main() { Datos d; Parque p; clock_t timer; vector<int> s((d.m)/2, 0); timer = clock(); s = p.busquedaExhaustiva(d.espera,13,8,d.disfrute,d.traslado); timer = (clock()-timer); for(int i=0; i<18;++i){ if(s[i]!= 0){ cout<< s[i]<<" "; } } cout<<"\nTomo un tiempo de: "<<((float)timer)/CLOCKS_PER_SEC<<endl; return 0; } <file_sep>/Parque.h #ifndef PARQUE #define PARQUE #include "Datos.h" #include <vector> #include <iostream> using namespace std; class Parque { public: Parque(); ~Parque(); vector<int> busquedaExhaustiva(const int** espera, int m, int n, const int* disfrute, const int** traslado); vector<int> programacionDinamica(const int** espera, int m, int n, const int* disfrute, const int** traslado); vector<int> algoritmoAvido(const int** espera, int m, int n, const int* disfrute, const int** traslado); private: int fase(const int** espera, int m, int n, const int* disfrute, const int** traslado, int Sacum, int nvisitados, vector<int> sigma, int i, vector<int> &solucion); void oraculo(const int** espera, const int* disfrute, const int** traslado); Datos d; int nMax = -1; }; #endif <file_sep>/Parque.cpp #include "Parque.h" using namespace std; Parque::Parque() { } Parque::~Parque() { } vector<int> Parque::busquedaExhaustiva(const int** espera, int m, int n, const int* disfrute, const int** traslado) { vector<int> solucion((d.m)/2, 0); vector<int> sigma((d.m)/2, 0); int cont = 0; m = m-1; nMax = fase(espera,m,n,disfrute,traslado, 0, 0, sigma, 1,solucion); return solucion; } vector<int> Parque::programacionDinamica(const int** espera, int m, int n, const int* disfrute, const int** traslado) { } vector<int> Parque::algoritmoAvido(const int** espera, int m, int n, const int* disfrute, const int** traslado) { } int Parque::fase(const int** espera, int m, int n, const int* disfrute,const int** traslado, int Sacum, int nvisitados, vector<int> sigma, int i, vector<int> &solucion) { vector<bool> visitados(n, false); if(Sacum >= m || (Sacum + traslado[sigma[i-1]][n]) >= m){ return nvisitados; }else{ for(int j=1; j<=n; ++j){ Sacum += traslado[sigma[i-1]][j]; if(visitados[j] == false && (Sacum + espera[Sacum][j-1]+disfrute[j-1]) < m && sigma[i-1]!=j){ visitados[j] = true; sigma[i] = j; ++nvisitados; int nAct = fase(espera,m,n,disfrute,traslado,Sacum + espera[Sacum][j-1]+disfrute[j-1],nvisitados,sigma,i+1,solucion); if(nAct > nMax){ nMax = nAct; solucion = sigma; } visitados[j] = false; } Sacum -= traslado[sigma[i-1]][j]; } sigma = solucion; } return nMax; //return nvisitados; } /* void Parque::oraculo (const int** espera, const int* disfrute, const int** traslado) { int maxDis = 0; int maxAct = 0; for (int i = tFinal-1; i >= 0 ; i--) { for(int j = 0; j < cantAtracciones; j++) { if(i + traslado[j+1][cantAtracciones] == tFinal) oraculoD[i][j] = 1; else if( i + traslado[j+1][cantAtracciones] > tFinal || i < traslado[0][j] + espera[traslado[0][j]][j] + disfrute[j]) oraculoD[i][j] = 0; else { maxAct = 0; maxDis = 0; oraculoD[i][j] = 1; for (int k = 0; k < cantAtracciones; k++) { if(traslado[j+1][k] + i < tFinal && j != k)// si el traslado mas el tiempo i y si no se ha visitado esa atraccion { if(i + traslado[j+1][k] + espera[traslado[j+1][k] + i][k] + disfrute[k] < tFinal)// si el tiempo i mas el traslado mas la espera mas el disfrute no se han pasado del tiempo que dispone para estar en el parque { maxDis = oraculoD [ i + traslado[j+1][k] + espera[traslado[j+1][k] + i] [k] + disfrute[k]][k]; if(maxDis > maxAct) { maxAct = maxDis; horaD[i][j] = i + traslado[j+1][k] + espera[traslado[j+1][k] + i][k] + disfrute[k]; atraccionesD [i][j]= k; } } } } oraculoD[i][j] = oraculoD[i][j] + maxAct; } } } } */ <file_sep>/README.md # Analysis-Techniques Universidad de Costa Rica CI-1210 Data Structures and Algorithm Analysis Advanced Design and Analysis Techniques: - Exhaustive Search (Brute-force Search) - Dynamic Programming - Greedy Algorithms
b932738c062b1673701908a88da0d20f7f9f35ff
[ "Markdown", "C++" ]
4
C++
nosarabs/Analysis-Techniques
3497331d25fc6eafcde4b06f2b4e64faa565e113
4cf52d18387d02f01e7894c697b9fdbf8abd07d8
refs/heads/main
<repo_name>mrsmamasia/backsvsp<file_sep>/index.js const express = require('express') const bodyParser = require('body-parser') const mongoose = require('mongoose') const http = require('http') // подключение к БД mongoose.connect( 'mongodb://mongodb:27017/mevnsvsp', { useCreateIndex: true, useNewUrlParser: true, } ) //инициализация приложения const app = express() app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true})); // роуты const PORT = 3000; http.createServer({},app).listen(PORT); console.log('Server running at $(PORT)');
3e8c56b04132b73af85a06aa396f8072dddd4a8a
[ "JavaScript" ]
1
JavaScript
mrsmamasia/backsvsp
0960da429859625799f927bcc14a78a59ff895a6
306b92f87cfaf8a5f9c06c77ed75156ca3956bcc
refs/heads/master
<repo_name>SAllegre/elementarygames<file_sep>/CatchtheWord/wr/w_4294/js/resource_use.js var movieWidth; var movieHeight; var scalePercentagew; var scalePercentageh; var lcap; var finished = "notdone"; var finishedarray; var finalScore = 0; window.quizscope = 0; var width var height var no_of_attempts; var no_of_tries; var m_movieProps var catchRoot; var catchStage; var VarFScore var variableSpeed; var gameMainBgSel, gameMainBgColor var gameInstructionTitle, gameInstructions; var gameMainName,gameMainNameColor,gamePlayBtnText,gamePlayBtnTextColor,gamePlayBtnBaseColor var gameLifeLineColor, gameScoreTimeSel, gameScoreTimeText,gameScoreTimeColor,gameTopBannerSel, gameTopBannerColor, gameStartQuestionTextColor, gameNextQuestionText1, gameNextQuestionText2, gameNextQuestionTextColor, gameCartColor, gameShapeSelected, gameShapeBaseSelected, gameShapeBaseColor,gameShapeBorderSelected, gameShapeBorderColor, gameShapeTextColor, gameQuestionColor, gameAnswerBaseColor,gameAnswerTextColor var gameCrctFeedbackTxt, gameCrctFeedbackTxtColor, gameWrngFeedbackTxt, gameWrngFeedbackTxtColor, gameYourScoreTxt, yourScoreTxtHex, gamefinalScoreTxtColor var getAllPanelInformationArray var alphaMixList = new Array(); var alphaMixListDefault = ["A", "a", "B", "b", "C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "H", "h", "I", "i", "J", "j", "K", "k", "L", "l", "M", "m", "N", "n", "O", "o", "P", "p", "Q", "q", "R", "r", "S", "s", "T", "t", "U", "u", "V", "v", "W", "w", "X", "x", "Y", "y", "Z", "z"]; var alphaMixWordListDefault = ["Green", "Yellow", "Red"]; var numMixList = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-", "/", "(", ")", "*"]; var ID_Whatisthecolorofthesky, ID_Blue, ID_AlphaSetFull var totalQuestions = 0; var currentScore = 0; var totalScore = 0; var totalGameTime; var qNum = 0; var ranCount; var charArrayToRemove; var isDevice; var parentDeviceMotion; var parentOrientation; var lastOrientation; var activateCart = false; var gameSelLifeline =0;; var cartMc; var isResponsiveProject = false; var mainCPNamespace; var evtHandle; isDevice = { Android: function() { return navigator.userAgent.match(/Android/i) ? true : false; }, BlackBerry: function() { return navigator.userAgent.match(/BlackBerry/i) ? true : false; }, IOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false; }, Windows: function() { return navigator.userAgent.match(/IEMobile/i) ? true : false; }, any: function() { return (isDevice.Android() || isDevice.BlackBerry() || isDevice.IOS() || isDevice.Windows()); } }; resourceUse = { onLoad: function() { if (!this.captivate) return; lcap = this.captivate; handle = this.captivate.CPMovieHandle; //if (handle.isWidgetVisible() == true) { var lInteractiveWidgetHandle = this.captivate.CPMovieHandle.getInteractiveWidgetHandle(); if (lInteractiveWidgetHandle) { if (lInteractiveWidgetHandle.shouldDisable()) this.disable(); } try { no_of_attempts = this.captivate.CPMovieHandle.getCPQuestionData().maxAttempts if (no_of_attempts == -1) { no_of_attempts = 1 } no_of_tries = this.captivate.CPMovieHandle.getCPQuestionData().numTries } catch (err) { no_of_attempts = 0; no_of_tries = 0; } this.movieProps = this.captivate.CPMovieHandle.getMovieProps(); if (!this.movieProps) return; m_movieProps = this.movieProps; this.varHandle = this.movieProps.variablesHandle; m_VariableHandle = this.varHandle; //this.eventDisp = this.movieProps.eventDispatcher; evtHandle = this.movieProps.eventDispatcher; mainCPNamespace = this.movieProps.getCpHandle(); isResponsiveProject = mainCPNamespace.responsive; this.xmlStr = this.captivate.CPMovieHandle.widgetParams(); var size = this.OpenAjax.getSize(); width = size.width; height = size.height; this.externalImage = ''; this.description = ''; this.myVar = ''; this.myVar1 = ''; movieWidth = parseInt(size.width.split("px")[0]); movieHeight = parseInt(size.height.split("px")[0]); //Captivate Event listener evtHandle.addEventListener(mainCPNamespace.WINDOWRESIZECOMPLETEDEVENT,updateSizeNPositionOnResizeComplete, false ); evtHandle.addEventListener(mainCPNamespace.ORIENTATIONCHANGECOMPLETEDEVENT,updateSizeNPositionOnResizeComplete, false ); this.updateData(); this.doUpdate(); if (parent.cpInQuizScope == true) { id = setInterval(checkval, 100) window.quizscope = 1 } else { id = setInterval(checkval, 100) } //} }, //To be implemented by a QUESTION WIDGET to be part of Captivate's Quizzing framework enable: function() { //var btnElement = document.getElementById('feedbackCanvas'); //btnElement.disabled = false; }, //To be implemented by a QUESTION WIDGET to be part of Captivate's Quizzing framework disable: function() { //var btnElement = document.getElementById('feedbackCanvas'); //btnElement.disabled = 'disabled'; }, //Captivate App will not recognize a Question Widget unless this function is implemented and returns true getInteractionQuestionState: function() { var lResult_Str = finished + ":quiz"; //Append with score lResult_Str = lResult_Str + ":" + finalScore; //Implements this to return Widget State as String return lResult_Str; }, setInteractionQuestionState: function(aVal) { //Implements this to set Widget State from input String(aVal) var lArray = []; lArray = aVal.split(","); if (lArray[0] != "") { finished = lArray[0]; } else { finished = "notdone" } valueset = 1; if (lArray.length < 2) return; }, getCorrectAnswerAsArray: function() { //Return correct answer as string return ["1"]; }, getCurrentAnswerAsString: function() { //Return current answer as string }, //Handle Click, if Clicked Outside Widget ( will be called from captivate internally) onClickExternal: function(e) { var lMsg = 'On Click Received in Widget'; if (e) { lMsg += "x=" + e.pageX + "y=" + e.pageY; } if (!this.captivate) return; //Call set Failure var lInteractiveWidgetHandle = this.captivate.CPMovieHandle.getInteractiveWidgetHandle(); }, updateData: function() { var allWidgets = window.parent.document.getElementsByClassName("cp-widget"); var myFrameName = window.name; var myWidgetiFrame = window.parent.document.getElementById(window.name); if (myWidgetiFrame) { myWidgetiFrame.style.height = movieHeight + "px"; myWidgetiFrame.style.width = movieWidth + "px"; } var id = 0; var result = jQuery.parseXML(this.xmlStr); var resultDoc = jQuery(result); var strProp = resultDoc.find('string').text(); //BREAKING UP THE XML FROM CAPTIVATE //VARIABLE //Game Variable var varFscr = resultDoc.find('#gameVariable'); if (varFscr){ if (varFscr.find('string')){ VarFScore = varFscr.find('string').text(); } } //BACKGROUND //Game bg selected var gamebgsel = resultDoc.find('#bgSelected'); if (gamebgsel) { if (gamebgsel.find('string')) { gameMainBgSel = gamebgsel.find('string').text(); } } //Get Bg Color var gamebghex = resultDoc.find('#bgColorHex'); if (gamebghex) { if (gamebghex.find('string')) { gameMainBgColor = '#' + gamebghex.find('string').text(); } } //INSTRUCTIONS //Get instruction title var gamedesctitle = resultDoc.find('#instTitleText'); if (gamedesctitle) { if (gamedesctitle.find('string')) { gameInstructionTitle = gamedesctitle.find('string').text(); } } //Get instructions for the game var gamedesc = resultDoc.find('#instText'); if (gamedesc) { if (gamedesc.find('string')) { gameInstructions = gamedesc.find('string').text(); } } //START SCREEN //Game Name var gamename = resultDoc.find('#gameNameText'); if (gamename) { if (gamename.find('string')) { gameMainName = gamename.find('string').text(); } } //Game name color var gamenamecolor = resultDoc.find('#gameNameColorHex'); if (gamenamecolor) { if (gamenamecolor.find('string')) { gameMainNameColor = '#' + gamenamecolor.find('string').text(); } } //Play Button text var gameplaybtn = resultDoc.find('#playButtonText'); if (gameplaybtn) { if (gameplaybtn.find('string')) { gamePlayBtnText = gameplaybtn.find('string').text(); } } //Play Button Text Color var gameplaybtnhex = resultDoc.find('#playButtonColorHex'); if (gameplaybtnhex) { if (gameplaybtnhex.find('string')) { gamePlayBtnTextColor = '#' + gameplaybtnhex.find('string').text(); } } //Play Button Base Color var gameplaybtnbasehex = resultDoc.find('#playButtonBaseColorHex'); if (gameplaybtnbasehex) { if (gameplaybtnbasehex.find('string')) { gamePlayBtnBaseColor = '#' + gameplaybtnbasehex.find('string').text(); } } //GAME SCREEN //LifeLine color var lifeLineColorHex = resultDoc.find('#lifeLineColorHex'); if (lifeLineColorHex) { if (lifeLineColorHex.find('string')) { gameLifeLineColor = '#' + lifeLineColorHex.find('string').text(); } } //Lifeline choosen var selLifeline = resultDoc.find('#selLifeline'); if (selLifeline) { if (selLifeline.find('number')) { gameSelLifeline = parseInt(selLifeline.find('number').text()); } } //Score Time Color var scoretimesel = resultDoc.find('#scoreTimeSel'); if (scoretimesel) { if (scoretimesel.find('string')) { gameScoreTimeSel = scoretimesel.find('string').text(); } } //Score Time Color var scoretimetext = resultDoc.find('#scoreTimeText'); if (scoretimetext) { if (scoretimetext.find('string')) { gameScoreTimeText = scoretimetext.find('string').text(); } } //Score Time Color var scoretimehex = resultDoc.find('#scoreTimeColorHex'); if (scoretimehex) { if (scoretimehex.find('string')) { gameScoreTimeColor = '#' + scoretimehex.find('string').text(); } } //Top banner sel var topbannersel = resultDoc.find('#topBannerSelected'); if (topbannersel) { if (topbannersel.find('string')) { gameTopBannerSel = topbannersel.find('string').text(); } } //Top banner color var topbannerHex = resultDoc.find('#topBannerColorHex'); if (topbannerHex) { if (topbannerHex.find('string')) { gameTopBannerColor = '#' + topbannerHex.find('string').text(); } } //Start Question color var startQuestionTexthex = resultDoc.find('#startQuestionColorHex'); if (startQuestionTexthex) { if (startQuestionTexthex.find('string')) { gameStartQuestionTextColor = '#' + startQuestionTexthex.find('string').text(); } } //Next Question Panel text 1 var nextQuestionText1 = resultDoc.find('#nextQuestionText1'); if (nextQuestionText1) { if (nextQuestionText1.find('string')) { gameNextQuestionText1 = nextQuestionText1.find('string').text(); } } //Next Question Panel text2 var nextQuestionText2 = resultDoc.find('#nextQuestionText2'); if (nextQuestionText2) { if (nextQuestionText2.find('string')) { gameNextQuestionText2 = nextQuestionText2.find('string').text(); } } //Next Question Panel text2 var nextQuestionTexthex = resultDoc.find('#nextQuestionColorHex'); if (nextQuestionTexthex) { if (nextQuestionTexthex.find('string')) { gameNextQuestionTextColor = '#' + nextQuestionTexthex.find('string').text(); } } //Cart color var cartColorHex = resultDoc.find('#cartColorHex'); if (cartColorHex) { if (cartColorHex.find('string')) { gameCartColor = '#' + cartColorHex.find('string').text(); } } //Shape details //Shape selected var shapeSelected = resultDoc.find('#shapeSelected'); if (shapeSelected) { if (shapeSelected.find('number')) { gameShapeSelected = parseInt(shapeSelected.find('number').text()); } } //Shape shapeBaseSelected var shapeBaseSelected = resultDoc.find('#shapeBaseSelected'); if (shapeBaseSelected) { if (shapeBaseSelected.find('string')) { gameShapeBaseSelected = shapeBaseSelected.find('string').text(); } } //Shape shapeBaseSelected color var shapeBaseColorHex = resultDoc.find('#shapeBaseColorHex'); if (shapeBaseColorHex) { if (shapeBaseColorHex.find('string')) { gameShapeBaseColor = '#' +shapeBaseColorHex.find('string').text(); } } //Shape shapeBorderSelected var shapeBorderSelected = resultDoc.find('#shapeBorderSelected'); if (shapeBorderSelected) { if (shapeBorderSelected.find('string')) { gameShapeBorderSelected = shapeBorderSelected.find('string').text(); } } //Shape shapeBorderSelected color var shapeBorderColorHex = resultDoc.find('#shapeBorderColorHex'); if (shapeBorderColorHex) { if (shapeBorderColorHex.find('string')) { gameShapeBorderColor = '#' +shapeBorderColorHex.find('string').text(); } } //Shape text color var shapeTextColorHex = resultDoc.find('#shapeTextColorHex'); if (shapeTextColorHex) { if (shapeTextColorHex.find('string')) { gameShapeTextColor = '#' +shapeTextColorHex.find('string').text(); } } //Bottom banner color var bottomBannerColorHex = resultDoc.find('#bottomBannerColorHex'); if (bottomBannerColorHex) { if (bottomBannerColorHex.find('string')) { gameBottomBannerColor = '#' +bottomBannerColorHex.find('string').text(); } } //Question color var questionColorHex = resultDoc.find('#questionColorHex'); if (questionColorHex) { if (questionColorHex.find('string')) { gameQuestionColor = '#' +questionColorHex.find('string').text(); } } //Answer base color var answerBaseColorHex = resultDoc.find('#answerBaseColorHex'); if (answerBaseColorHex) { if (answerBaseColorHex.find('string')) { gameAnswerBaseColor = '#' +answerBaseColorHex.find('string').text(); } } //Answer text color var answerTextColorHex = resultDoc.find('#answerTextColorHex'); if (answerTextColorHex) { if (answerTextColorHex.find('string')) { gameAnswerTextColor = '#' +answerTextColorHex.find('string').text(); } } //END SCREEN //Correct feedback text var crctFeedbackTxt = resultDoc.find('#crctFeedbackText'); if (crctFeedbackTxt) { if (crctFeedbackTxt.find('string')) { gameCrctFeedbackTxt = crctFeedbackTxt.find('string').text(); } } //Correct feedback text color var crctFeedbackTxtHex = resultDoc.find('#crctFeedbackColorHex'); if (crctFeedbackTxtHex) { if (crctFeedbackTxtHex.find('string')) { gameCrctFeedbackTxtColor = '#' + crctFeedbackTxtHex.find('string').text(); } } //InCorrect feedback text var wrngFeedbackTxt = resultDoc.find('#wrngFeedbackText'); if (wrngFeedbackTxt) { if (wrngFeedbackTxt.find('string')) { gameWrngFeedbackTxt = wrngFeedbackTxt.find('string').text(); } } //InCorrect feedback text color var wrngFeedbackTxtHex = resultDoc.find('#wrngFeedbackColorHex'); if (wrngFeedbackTxtHex) { if (wrngFeedbackTxtHex.find('string')) { gameWrngFeedbackTxtColor = '#' + wrngFeedbackTxtHex.find('string').text(); } } //Your score text var yourScoreTxt = resultDoc.find('#yourScoreText'); if (yourScoreTxt) { if (yourScoreTxt.find('string')) { gameYourScoreTxt = yourScoreTxt.find('string').text(); } } //Your score text color var yourScoreTxtHex = resultDoc.find('#yourScoreColorHex'); if (yourScoreTxtHex) { if (yourScoreTxtHex.find('string')) { gameYourScoreTxtColor = '#' + yourScoreTxtHex.find('string').text(); } } //Finalscore color var finalScoreTxtHex = resultDoc.find('#finalScoreColorHex'); if (finalScoreTxtHex) { if (finalScoreTxtHex.find('string')) { gamefinalScoreTxtColor = '#' + finalScoreTxtHex.find('string').text(); } } //ADDITION FOR LOCALIZATION //Finalscore color var ID_Whatisthecoloroftheskytxt = resultDoc.find('#ID_Whatisthecolorofthesky'); if (ID_Whatisthecoloroftheskytxt) { if (ID_Whatisthecoloroftheskytxt.find('string')) { ID_Whatisthecolorofthesky = ID_Whatisthecoloroftheskytxt.find('string').text(); } } var ID_Bluetxt = resultDoc.find('#ID_Blue'); if (ID_Bluetxt) { if (ID_Bluetxt.find('string')) { ID_Blue = ID_Bluetxt.find('string').text(); } } var ID_AlphaSetFulltxt = resultDoc.find('#ID_AlphaSetFull'); if (ID_AlphaSetFulltxt) { if (ID_AlphaSetFulltxt.find('string')) { ID_AlphaSetFull = ID_AlphaSetFulltxt.find('string').text(); } } alphaMixListDefault = ID_AlphaSetFull.split(",") //Get All Questions Information var getAllPanelInformation = resultDoc.find('#allPanelInformation'); getAllPanelInformationArray = new Array(); if (getAllPanelInformation){ totalQuestions = getAllPanelInformation.children().children().children().length; if(totalQuestions>0){ for (i=0; i<totalQuestions; i++) { var questionObj = new Object(); var questionList = $(getAllPanelInformation.find('array').children()[i]); questionObj.type = ($($($(questionList).find('#0'))[0]).find('string').text()); if (questionObj.type == "word") { questionObj.num = ($($($(questionList).find('#1'))[0]).find('string').text()); questionObj.qTxt = ($($($(questionList).find('#2'))[0]).find('string').text()); questionObj.aTxt = ($($($(questionList).find('#3'))[0]).find('string').text()); questionObj.scoreTxt = ($($($(questionList).find('#4'))[0]).find('string').text()); questionObj.removeATxt = ($($($(questionList).find('#5'))[0]).find('string').text()); questionObj.lifeLines = ($($($(questionList).find('#6'))[0]).find('number').text()); questionObj.cTxt = ($($($(questionList).find('#7'))[0]).find('string').text()); questionObj.isWord = ($($($(questionList).find('#9'))[0]).find('string').text()); questionObj.hideRandom = ($($($(questionList).find('#10'))[0]).find('string').text()); questionObj.removeHideListDpString = ($($($(questionList).find('#13'))[0]).find('string').text()); } else if (questionObj.type == "number") { questionObj.num = ($($($(questionList).find('#1'))[0]).find('string').text()); questionObj.aTxt = ($($($(questionList).find('#2'))[0]).find('string').text()); questionObj.scoreTxt = ($($($(questionList).find('#3'))[0]).find('string').text()); questionObj.removeNTxt = ($($($(questionList).find('#4'))[0]).find('string').text()); questionObj.removeSTxt = ($($($(questionList).find('#5'))[0]).find('string').text()); questionObj.lifeLines = ($($($(questionList).find('#6'))[0]).find('number').text()); questionObj.hideRandom = ($($($(questionList).find('#7'))[0]).find('string').text()); questionObj.removeHideListDpString = ($($($(questionList).find('#10'))[0]).find('string').text()); } getAllPanelInformationArray.push(questionObj); } }else{ //Prepare dummy question var questionObjD = new Object(); questionObjD.type = "word" questionObjD.num = 1; questionObjD.qTxt = ID_Whatisthecolorofthesky; questionObjD.aTxt = ID_Blue; questionObjD.scoreTxt = "10"; questionObjD.removeATxt = "1"; questionObjD.lifeLines = "5"; questionObjD.cTxt = ""; getAllPanelInformationArray.push(questionObjD); } } }, doUpdate: function() { resizeInteraction(width, height); }, }; resource_use = function() { //Check if the browser is Safari on Mac only to toggle the YES NO Button Positions //SystemIsMac = ( navigator.platform.match(/(iPad|iPhone|Mac)/g) ? true : false ); return resourceUse; } function resizeInteraction(thewidth, theheight) { var scale = 0; thewidth = String(thewidth).replace("px", ""); theheight = String(theheight).replace("px", ""); if (thewidth < theheight){ scale = thewidth / (movieWidth); } else{ scale = theheight / (movieHeight); } var holdScale = scale var margins = Math.round(25 * scale); margins += "px" scale = "scale(" + scale + ")"; $('#gamedesc').css('-webkit-transform', scale); $('#gamedesc').css('-moz-transform', scale); $('#gamedesc').css('-o-transform', scale); $('#gamedesc').css('-ms-transform', scale); $('#gamedesc').css('-webkit-transform-origin', '0 0'); $('#gamedesc').css('-moz-transform-origin', '0 0'); $('#gamedesc').css('-o-transform-origin', '0 0'); $('#gamedesc').css('-ms-transform-origin', '0 0'); $('#gamedesc').css('-webkit-tap-highlight-color', 'rgba(0,0,0,0)'); $('#gamedesc').css({ left: (75*holdScale) + "px", top: (160*holdScale) + "px", }); $('#catchCanvas').css('-webkit-transform', scale); $('#catchCanvas').css('-moz-transform', scale); $('#catchCanvas').css('-o-transform', scale); $('#catchCanvas').css('-ms-transform', scale); $('#catchCanvas').css('-webkit-transform-origin', '0 0'); $('#catchCanvas').css('-moz-transform-origin', '0 0'); $('#catchCanvas').css('-o-transform-origin', '0 0'); $('#catchCanvas').css('-ms-transform-origin', '0 0'); $('#catchCanvas').css('-webkit-tap-highlight-color', 'rgba(0,0,0,0)'); } var scaleDiffw; var scaleDiffh; function checkval() { clearInterval(id); catchTheAlphaNumsInit(); } function catchTheAlphaNumsInit() { catchCanvas = document.getElementById("catchCanvas"); catchCanvas.width = movieWidth; catchCanvas.height = movieHeight; //Apply text and Color features // ONLY Instructions will be set from her catchRoot = new lib.runtime(); catchRoot.scaleX = movieWidth / 640; catchRoot.scaleY = movieHeight / 480; catchStage = new createjs.Stage(catchCanvas); catchStage.addChild(catchRoot); catchStage.enableMouseOver(); //Enabling Touch createjs.Touch.enable(catchStage); createjs.Ticker.setFPS(lib.properties.fps); createjs.Ticker.addEventListener("tick", catchStage); scalePercentagew = movieWidth / 640; scalePercentageh = movieHeight / 480; scaleDiffw = movieWidth - 640; scaleDiffh = movieHeight - 480; catchRoot.runTime_mc.instScreen.visible = false; catchRoot.runTime_mc.startScreen.visible = false; catchRoot.runTime_mc.gameScreen.visible = false; catchRoot.runTime_mc.endScreen.visible = false; catchRoot.runTime_mc.bg.visible = false; //Set up Background setupBg(); //Set up instructions setupInstructions(); //Set up start screen setupStartScreen(); //Set up game screen setupGameScreen(); catchStage.update(); //hide all html elements finishedarray = finished.split(":") if (finishedarray[2] != undefined) { finalScore = parseInt(finishedarray[2]); } if (m_VariableHandle != null) { m_VariableHandle[VarFScore] = finalScore; } var lInteractiveWidgetHandle = lcap.CPMovieHandle.getInteractiveWidgetHandle(); if (parent.cpInQuizScope == true) { if (lcap.CPMovieHandle.getQuizController().m_QuizzingData.isInReviewMode == true) { if (finishedarray[0] == "complete") { setReviewMode("success"); } else { setReviewMode("fail") } } else if (no_of_tries < no_of_attempts) { if (finishedarray[0] == "notdone") { setnotdonemode(); } else if (finishedarray[0] == "complete") { setReviewMode("success"); } else { setReviewMode("fail"); } } else if (no_of_tries >= no_of_attempts) { if (finishedarray[0] == "notdone") { setnotdonemode(); } else if (finishedarray[0] == "complete") { setReviewMode("success"); } else { setReviewMode("fail") } } } else { if (lcap.CPMovieHandle.getQuizController().m_QuizzingData != null) { if (lcap.CPMovieHandle.getQuizController().m_QuizzingData.isInReviewMode == true) { if (finishedarray[0] == "notdone") { if (finishedarray[1] == "quiz") { setReviewMode("fail") } else { setnotdonemode(); } } else if (finishedarray[0] == "complete") { setReviewMode("success"); } else { setReviewMode("fail") } } else if (no_of_tries < no_of_attempts) { if (finishedarray[0] == "notdone") { setnotdonemode(); } else if (finishedarray[0] == "complete") { setReviewMode("success"); } } else if (no_of_tries >= no_of_attempts) { if (finishedarray[0] == "notdone") { setnotdonemode(); } else if (finishedarray[0] == "complete") { setReviewMode("success"); } else { setReviewMode("fail") } } } else { if (finishedarray[0] == "notdone") { if (finishedarray[1] == "quiz") { setReviewMode("fail") } else { setnotdonemode(); } } else if (finishedarray[0] == "success") { setReviewMode("success"); } else if (finishedarray[0] == "fail") { setReviewMode("fail") } } } //Checking device orientation if(isDevice.any()){ if(window.DeviceMotionEvent){ lastOrientation = {} window.addEventListener('devicemotion', deviceMotionTest, false); } if (window.DeviceOrientationEvent) { lastOrientation = {} window.addEventListener('deviceorientation', deviceOrientationTest, false); }else{ //console.log("Not avalable") } } } function setupBg(){ if(gameMainBgSel == "true"){ catchRoot.runTime_mc.bg.visible = true; }else{ catchRoot.runTime_mc.bg.visible = false; } } function setupInstructions(){ catchRoot.runTime_mc.instScreen.instMc.instTitleMc.instTitle.text = gameInstructionTitle catchRoot.runTime_mc.instScreen.instMc.instTxtMcShow.instTxt.visible = false; catchRoot.runTime_mc.instScreen.instMc.close_btn.addEventListener("mouseover", handleMouseOver); catchRoot.runTime_mc.instScreen.instMc.close_btn.addEventListener("mouseout", handleMouseOut); catchRoot.runTime_mc.instScreen.instMc.close_btn.addEventListener("click", hideInstructions); catchRoot.runTime_mc.instScreen.help_btn.addEventListener("mouseover", handleMouseOver); catchRoot.runTime_mc.instScreen.help_btn.addEventListener("mouseout", handleMouseOut); catchRoot.runTime_mc.instScreen.help_btn.addEventListener("click", showHideInstructions); //Game instructions $('#gamedesc').attr('rows', 8) $('#gamedesc').attr('cols', 37) $('#gamedesc').css({ zIndex: 25, left: (75*scalePercentagew) + "px", top: (160*scalePercentageh) + "px", width: 470 + "px", height: 182 + "px", backgroundColor: 'transparent', textAlign: 'Left', lineHeight: '160%', overflow: 'auto', "overflow-x": 'hidden', }); $('#gamedesc').html(gameInstructions); $('#gamedesc').disableTextSelect(); $('#gamedesc').mouseover(function(e) { e.target.style.cursor = "default"; }); $('#gamedesc').show(); catchRoot.runTime_mc.instScreen.visible = true; hideInstructions(); } function showHideInstructions(){ if(catchRoot.runTime_mc.instScreen.instMc.visible){ hideInstructions(); }else{ catchRoot.runTime_mc.startScreen.visible = false; catchRoot.runTime_mc.instScreen.instMc.visible = true; $('#gamedesc').show(); } } function hideInstructions(){ $('#gamedesc').hide(); catchRoot.runTime_mc.instScreen.instMc.visible = false; catchRoot.runTime_mc.startScreen.visible = true; } function setupStartScreen(){ catchRoot.runTime_mc.startScreen.visible = true; catchRoot.runTime_mc.startScreen.playBtn.addEventListener("mouseover", handleMouseOver); catchRoot.runTime_mc.startScreen.playBtn.addEventListener("mouseout", handleMouseOut); catchRoot.runTime_mc.startScreen.playBtn.addEventListener("click", startGameScreen); } function startGameScreen(){ catchRoot.runTime_mc.startScreen.visible = false; catchRoot.runTime_mc.instScreen.visible = false; catchRoot.runTime_mc.gameScreen.visible = true; prepareQuestion(); } var alNumYArray; function setupGameScreen(){ //Score if(gameScoreTimeSel == "true"){ catchRoot.runTime_mc.gameScreen.scoreMc.visible =true; }else{ catchRoot.runTime_mc.gameScreen.scoreMc.visible =false; } //Lifelines for(i =1;i<=5;i++){ //catchRoot.runTime_mc.gameScreen["heart"+i].heart.gotoAndStop(0) catchRoot.runTime_mc.gameScreen["heart"+i].heart.base_1.gotoAndStop(0); catchRoot.runTime_mc.gameScreen["heart"+i].heart.base.gotoAndStop(0); if(gameSelLifeline==2){ catchRoot.runTime_mc.gameScreen["heart"+i].heart.base_1.visible=true; catchRoot.runTime_mc.gameScreen["heart"+i].heart.base.visible=false; }else{ catchRoot.runTime_mc.gameScreen["heart"+i].heart.base_1.visible=false; catchRoot.runTime_mc.gameScreen["heart"+i].heart.base.visible=true; } } //Top Banner if(gameTopBannerSel =="true"){ catchRoot.runTime_mc.gameScreen.topBannerMc.visible =true; }else{ catchRoot.runTime_mc.gameScreen.topBannerMc.visible =false; } //Start Question Panel catchRoot.runTime_mc.gameScreen.startQuestion.visible =false; //Next Question Panel catchRoot.runTime_mc.gameScreen.nextQuestion.visible =false; catchRoot.runTime_mc.gameScreen.nextQuestion.crctmc.visible =false; catchRoot.runTime_mc.gameScreen.nextQuestion.wrngmc.visible =false; catchRoot.runTime_mc.gameScreen.nextQuestion.base.gotoAndStop(0) //Cart features cartMc = catchRoot.runTime_mc.gameScreen.cartMc; cartMc.mc.base.bordermc.gotoAndStop(gameShapeSelected-1); cartMc.mc.base.shapemc.gotoAndStop(gameShapeSelected-1); if(gameShapeBorderSelected == "true"){ cartMc.mc.base.bordermc.visible=true; }else{ cartMc.mc.base.bordermc.visible=false; } if(gameShapeBaseSelected == "true"){ cartMc.mc.base.shapemc.visible=true; }else{ cartMc.mc.base.shapemc.visible=false; } //cartMc.mc.txt.text = "M" cartMc.mc.alpha =0; //Shape Features alNumYArray = new Array(); for(i=1;i<=7;i++){ alNumYArray.push(catchRoot.runTime_mc.gameScreen["alnum"+i].y) catchRoot.runTime_mc.gameScreen["alnum"+i].base.bordermc.gotoAndStop(gameShapeSelected-1); catchRoot.runTime_mc.gameScreen["alnum"+i].base.shapemc.gotoAndStop(gameShapeSelected-1); if(gameShapeBorderSelected == "true"){ catchRoot.runTime_mc.gameScreen["alnum"+i].base.bordermc.visible=true; }else{ catchRoot.runTime_mc.gameScreen["alnum"+i].base.bordermc.visible=false; } if(gameShapeBaseSelected == "true"){ catchRoot.runTime_mc.gameScreen["alnum"+i].base.shapemc.visible=true; }else{ catchRoot.runTime_mc.gameScreen["alnum"+i].base.shapemc.visible=false; } } //Get the total score for this game totalScore = 0; for (var i = 0; i < getAllPanelInformationArray.length; i++) { totalScore = totalScore + parseInt(getAllPanelInformationArray[i].scoreTxt) } catchRoot.runTime_mc.gameScreen.scoreMc.score.text = currentScore + "/" + totalScore; //Button features for correct and incorrect feedback catchRoot.runTime_mc.gameScreen.nextQuestion.addEventListener("mouseover", handleMouseOverNextQues); catchRoot.runTime_mc.gameScreen.nextQuestion.addEventListener("mouseout", handleMouseOutNextQues); catchRoot.runTime_mc.gameScreen.nextQuestion.addEventListener("click", removeAllChars); } function handleMouseOverNextQues(evt) { catchCanvas.style.cursor = "pointer"; catchRoot.runTime_mc.gameScreen.nextQuestion.base.gotoAndStop(1); } function handleMouseOutNextQues(evt) { catchCanvas.style.cursor = "default"; catchRoot.runTime_mc.gameScreen.nextQuestion.base.gotoAndStop(0); } var gameOverCheck function removeAllChars() { for (i = 0; i < charArrayToRemove.length; i++) { var charBox = catchRoot.runTime_mc.gameScreen.getChildByName(charArrayToRemove[i]); catchRoot.runTime_mc.gameScreen.removeChild(charBox); } //Clear all intervals clearInterval(moveAlphaShapeid1) clearInterval(moveAlphaShapeid2) clearInterval(moveAlphaShapeid3) clearInterval(moveAlphaShapeid4) clearInterval(moveAlphaShapeid5) clearInterval(moveAlphaShapeid6) clearInterval(moveAlphaShapeid7) //resetting Alnums for(i=1;i<=7;i++){ catchRoot.runTime_mc.gameScreen["alnum"+i].y = alNumYArray[i-1] } //Enable Lifelines enableAllLifelines(); //Check next question checkForNextQuestion(); } function checkForNextQuestion() { qNum++; if (qNum < totalQuestions) { catchRoot.runTime_mc.gameScreen.nextQuestion.visible = false; prepareQuestion() } else { catchRoot.runTime_mc.gameScreen.visible = false; catchRoot.runTime_mc.endScreen.crctFeedback.visible = false catchRoot.runTime_mc.endScreen.wrngFeedback.visible = false; finalScore = currentScore; if (currentScore == totalScore) { catchRoot.runTime_mc.endScreen.crctFeedback.visible = true; finished = "complete"; setSuccess(); } else { catchRoot.runTime_mc.endScreen.wrngFeedback.visible = true; finished = "failed"; setFailure(); } updateVariable(); catchRoot.runTime_mc.endScreen.finalScore.finalScoreTxt.text = currentScore; catchRoot.runTime_mc.endScreen.visible = true; } } function updateVariable(){ if (m_VariableHandle != null) { m_VariableHandle[VarFScore] = finalScore; } } var mainCharListLength; var questionDisplayString =""; function prepareQuestion(){ var qType = getAllPanelInformationArray[qNum].type; setQuestionComplete = false; ansCalCounter =0; if(qType == "word"){ //ShowQuestion if(getAllPanelInformationArray[qNum].qTxt == ""){ catchRoot.runTime_mc.gameScreen.quesTxt.text = ID_Whatisthecolorofthesky; }else{ catchRoot.runTime_mc.gameScreen.quesTxt.text = getAllPanelInformationArray[qNum].qTxt } questionDisplayString = catchRoot.runTime_mc.gameScreen.quesTxt.text; //Answer var ansSet; if(getAllPanelInformationArray[qNum].aTxt == ""){ ansSet = createAlphabetSet(ID_Blue); }else{ ansSet = createAlphabetSet(String(getAllPanelInformationArray[qNum].aTxt)) } var ansWords = ansSet[0]; var ansCharacters = ansSet[1]; //isWord var isWord = String(getAllPanelInformationArray[qNum].isWord); var alphaList = new Array(); if (isWord == "true") { alphaList = ansWords; } else { for (i = 0; i < ansCharacters.length; i++) { for (k = 0; k < ansCharacters[i].length; k++) { alphaList.push(ansCharacters[i][k]) } } } //Score for this question var questionScore = parseInt(getAllPanelInformationArray[qNum].scoreTxt) //Number of alphabets to remove var questionAlpaRemove; if (parseInt(getAllPanelInformationArray[qNum].removeATxt) > alphaList.length) { questionAlpaRemove = alphaList.length; } else { questionAlpaRemove = parseInt(getAllPanelInformationArray[qNum].removeATxt); } //Lifelines var questionLifeLine = parseInt(getAllPanelInformationArray[qNum].lifeLines); //Character set var charQuestionList = String(getAllPanelInformationArray[qNum].cTxt); var charListArray = charQuestionList.split(","); //isRandom var isRandom = getAllPanelInformationArray[qNum].hideRandom; //hideCharsArray var hideCharsArray = null; if(getAllPanelInformationArray[qNum].removeHideListDpString){ hideCharsArray = getAllPanelInformationArray[qNum].removeHideListDpString.split(";"); } //Char set var TempArray = new Array(); ranCount = 0; var ranArray; if(isRandom=="false"){ if (hideCharsArray != null && hideCharsArray.length > 0 && hideCharsArray[0]!="") { ranArray = hideCharsArray; }else{ ranArray = getRandNumInRange(0, alphaList.length, questionAlpaRemove, TempArray) } }else{ ranArray = getRandNumInRange(0, alphaList.length, questionAlpaRemove, TempArray) } var charBoxCount = 0; charArrayToRemove = new Array(); var totalWidthtoOccupy; if (isWord == "true") { totalWidthtoOccupy = 0; for (s = 0; s < alphaList.length; s++) { if(alphaList[s].length>=2){ boxW= 10 }else{ boxW= 25.6 } var charBoxWord = new lib.ansCharBoxWord(alphaList[s].length); charBoxWord.type = "fullword" charBoxWord.count = ansCharacters[s].length; charBoxWord.num = charBoxCount; charBoxWord.name = "ansCharBox" + charBoxCount; charBoxWord.txt.text = alphaList[s]; //charBoxWord.base.gotoAndStop(0); charBoxWord.width = ansCharacters[s].length*boxW; charBoxWord.txt.visible =false; charBoxWord.y = 453; charArrayToRemove.push(charBoxWord.name); totalWidthtoOccupy += charBoxWord.width; totalWidthtoOccupy += boxW; charBoxCount++; catchRoot.runTime_mc.gameScreen.addChild(charBoxWord); } //console.log(totalWidthtoOccupy) for (t = 0; t < alphaList.length; t++) { var charBoxWord1 = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + t) if (t == 0) { charBoxWord1.x = (325-(totalWidthtoOccupy / 2)) } else { if(alphaList[t-1].length>=2){ spaceW= 16 }else{ spaceW= 0 } var prevCharBoxWord1 = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + (t - 1)) charBoxWord1.x = (prevCharBoxWord1.x + prevCharBoxWord1.width) + spaceW; } } } else { totalWidthtoOccupy = 25 * (alphaList.length) + ((ansCharacters.length) * 10); for (j = 0; j < ansCharacters.length; j++) { for (m = 0; m < ansCharacters[j].length; m++) { var ansCharBox = new lib.ansCharBoxes(); ansCharBox.type = "normal" ansCharBox.num = charBoxCount ansCharBox.count = 1; ansCharBox.name = "ansCharBox" + charBoxCount; ansCharBox.txt.text = ansCharacters[j][m]; ansCharBox.base.gotoAndStop(0); ansCharBox.y = 453; charArrayToRemove.push(ansCharBox.name); if (charBoxCount == 0) { ansCharBox.x = 320 - (totalWidthtoOccupy / 2) } else { prevCharBox = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + (charBoxCount - 1)); if (m == 0) { ansCharBox.x = (prevCharBox.x + 25.6) + 10; } else { ansCharBox.x = (prevCharBox.x + 25.6) + 2; } } charBoxCount++; catchRoot.runTime_mc.gameScreen.addChild(ansCharBox) } } } //Hide chars var sendThisArray = new Array(); mainCharListLength = alphaList.length; if (isWord == "true") { sendThisArray = alphaList; } else { for (r = 0; r < alphaList.length; r++) { for (u = 0; u < ranArray.length; u++) { if (r == ranArray[u]) { var tempCharBox = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + r); tempCharBox.txt.visible = false; //console.log(tempCharBox.txt.text, "tempCharBox") sendThisArray.push(tempCharBox.txt.text); } } } } setUpAnswer(qType, sendThisArray, questionLifeLine, questionScore, charListArray, isWord) }else{ //ShowQuestion catchRoot.runTime_mc.gameScreen.quesTxt.text = ""; //Answer var ansSet; if(getAllPanelInformationArray[qNum].aTxt == ""){ ansSet = createEquationSet("(5+5)*3=30"); }else{ ansSet = createEquationSet(String(getAllPanelInformationArray[qNum].aTxt)) } var ansNumbers = ansSet[0]; var ansSymbols = ansSet[1]; var ansCharacters = ansSet[2]; var alphaList = new Array(); for (i = 0; i < ansCharacters.length; i++) { for (k = 0; k < ansCharacters[i].length; k++) { alphaList.push(ansCharacters[i][k]) } } //Score for this question var questionScore = parseInt(getAllPanelInformationArray[qNum].scoreTxt) //Number of alphabets to remove var questionAlpaRemove; if (parseInt(getAllPanelInformationArray[qNum].removeATxt) > alphaList.length) { questionAlpaRemove = alphaList.length; } else { questionAlpaRemove = parseInt(getAllPanelInformationArray[qNum].removeATxt); } //Lifelines var questionLifeLine = parseInt(getAllPanelInformationArray[qNum].lifeLines); var charQuestionList = String(getAllPanelInformationArray[qNum].cTxt); var removeNumber = 0; var removeSymbol = 0; if(getAllPanelInformationArray[qNum].removeNTxt){ removeNumber = parseInt(getAllPanelInformationArray[qNum].removeNTxt); } if(getAllPanelInformationArray[qNum].removeSTxt){ removeSymbol = parseInt(getAllPanelInformationArray[qNum].removeSTxt); } if(removeNumber == 0 && removeSymbol == 0){ removeNumber = 1; } //console.log(getAllPanelInformationArray[qNum].removeNTxt,removeSymbol) var ranNumArray = new Array(); var ranSymArray = new Array(); if (removeNumber > 0) { ranCount = 0; var TempNumArray = new Array(); ranNumArray = getRandNumInRange(0, ansNumbers.length, removeNumber, TempNumArray); } if (removeSymbol > 0) { ranCount = 0; var TempSymArray = new Array(); ranSymArray = getRandNumInRange(0, ansSymbols.length, removeSymbol, TempSymArray); } mainCharListLength = alphaList.length; var charBoxCount = 0; var totalWidthtoOccupy = 25 * (alphaList.length); charArrayToRemove = new Array(); for (var m = 0; m < alphaList.length; m++) { var charBox = new lib.ansCharBoxes(); charBox.num = charBoxCount charBox.name = "ansCharBox" + charBoxCount; charBox.txt.text = alphaList[m]; charBox.y = 443; charBox.base.gotoAndStop(0); charArrayToRemove.push(charBox.name); if (charBoxCount == 0) { charBox.x = 320 - (totalWidthtoOccupy / 2) } else { var prevCharBox = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + (charBoxCount - 1)); charBox.x = (prevCharBox.x + + 25.6) + 2; } charBoxCount++; catchRoot.runTime_mc.gameScreen.addChild(charBox); } //isRandom var isRandom = getAllPanelInformationArray[qNum].hideRandom; //hideCharsArray var hideCharsArray = null; if(getAllPanelInformationArray[qNum].removeHideListDpString){ hideCharsArray = getAllPanelInformationArray[qNum].removeHideListDpString.split(";"); } //Hide chars var sendThisArray = new Array(); if (isRandom == "false" && hideCharsArray != null && hideCharsArray.length>0 && hideCharsArray[0]!="") { for (q = 0; q < hideCharsArray.length; q++) { var tempCharBox3 = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + hideCharsArray[q]); tempCharBox3.txt.visible = false; sendThisArray.push(tempCharBox3.txt.text); } } else { for (var r = 0; r < alphaList.length; r++) { if (ranNumArray.length > 0) { for (var u = 0; u < ranNumArray.length; u++) { if (r == ansNumbers[ranNumArray[u]]) { var tempCharBox1 = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + r); tempCharBox1.txt.visible = false; sendThisArray.push(tempCharBox1.txt.text); } } } if (ranSymArray.length > 0) { for (var v = 0; v < ranSymArray.length; v++) { if (r == ansSymbols[ranSymArray[v]]) { var tempCharBox2 = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + r); tempCharBox2.txt.visible = false; sendThisArray.push(tempCharBox2.txt.text); } } } } } //For display as question var tempQuesString = ""; for (var s = 0; s < alphaList.length; s++) { var tempCharBoxDum = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + s); if (tempCharBoxDum.txt.visible) { tempQuesString = tempQuesString + tempCharBoxDum.txt.text; } else { tempQuesString = tempQuesString + " _ " } } questionDisplayString = tempQuesString; var dummyArray = [] setUpAnswer(qType, sendThisArray, questionLifeLine, questionScore, dummyArray,"false") } } var moveCartid var speed = 4; var rightArrow; var leftArrow; var spaceBar; var dropSpeed1,dropSpeed2,dropSpeed3,dropSpeed4,dropSpeed5,dropSpeed6,dropSpeed7 var yValArray; var speedRangeVal1 = 1; var speedRangeVal2 = 6; var scoreForThisQuest; var moveAlphaShapeid1,moveAlphaShapeid2,moveAlphaShapeid3,moveAlphaShapeid4,moveAlphaShapeid5,moveAlphaShapeid6,moveAlphaShapeid7 var globalIsWord = false; function setUpAnswer(qType, alphaList, lifLiCount, thisScore, charListArray,isWord) { catchRoot.runTime_mc.gameScreen.nextQuestion.visible = false; counter = 0; assurance = 0; charList = new Array(); charList = alphaList; lifeLineCounter = lifLiCount; scoreForThisQuest = thisScore; quesType = qType; setScore = false; questionPassed = false; alphaMixList = new Array(); globalIsWord = isWord; if (charListArray.length > 1) { alphaMixList = charListArray; } else { if (isWord == "true") { alphaMixList = alphaMixWordListDefault; }else{ alphaMixList = alphaMixListDefault; } } yValArray = new Array(); for (i = 1; i <= 7; i++) { yValArray.push(catchRoot.runTime_mc.gameScreen["alnum" + i].y) if (quesType == "word") { var randAlphaAns = alphaMixList[randRange(0, (alphaMixList.length - 1))]; if(globalIsWord=="true"){ catchRoot.runTime_mc.gameScreen["alnum" + i].resetAttr(14,1.3) catchRoot.runTime_mc.gameScreen["alnum" + i].setText(randAlphaAns,true) }else{ catchRoot.runTime_mc.gameScreen["alnum" + i].resetAttr(24,0.909) catchRoot.runTime_mc.gameScreen["alnum" + i].setText(randAlphaAns,false) } catchRoot.runTime_mc.gameScreen["alnum" + i].ansText = randAlphaAns; } else { var randNumAns = numMixList[randRange(0, (numMixList.length - 1))]; //catchRoot.runTime_mc.gameScreen.fontSize = 24; //catchRoot.runTime_mc.gameScreen.scaleSize = 0.909 catchRoot.runTime_mc.gameScreen["alnum" + i].resetAttr(24,0.909) catchRoot.runTime_mc.gameScreen["alnum" + i].setText(randNumAns,false) catchRoot.runTime_mc.gameScreen["alnum" + i].ansText = randNumAns; } catchRoot.runTime_mc.gameScreen["alnum" + i].alpha = 100; } //SetUp lifelines clearAllLifeLines(); for (i = 1; i <= lifeLineCounter; i++) { catchRoot.runTime_mc.gameScreen["heart"+i].alpha = 1; } //Show Question before droping alphabets catchRoot.runTime_mc.gameScreen.startQuestion.qnumtxt.text = "Q: " + (qNum + 1) + " of " + totalQuestions; catchRoot.runTime_mc.gameScreen.startQuestion.txt1.text=questionDisplayString; catchRoot.runTime_mc.gameScreen.startQuestion.visible = true; catchRoot.runTime_mc.gameScreen.startQuestion.alpha= 1; //Show Question for 3 seconds clearInterval(moveCartid);//Disable jkey board focus on cart activateCart = false;// Disable accelerometer features on the cart var startshowQuestionid = setInterval(startfadeQuestionOut, 3000); function startfadeQuestionOut(){ clearInterval(startshowQuestionid); var quesfadeCounter = 1 var fadeQuestionid = setInterval(fadeQuestionOut, 30) function fadeQuestionOut(){ quesfadeCounter-=0.1 catchRoot.runTime_mc.gameScreen.startQuestion.alpha = quesfadeCounter; if(catchRoot.runTime_mc.gameScreen.startQuestion.alpha<=0.1){ clearInterval(fadeQuestionid); //Alphabet drop begins dropSpeed1 = randRange(1, 3) dropSpeed2 = randRange(5, 6) dropSpeed3 = randRange(2, 4) dropSpeed4 = randRange(4, 6) dropSpeed5 = randRange(1, 2) dropSpeed6 = randRange(3, 5) dropSpeed7 = randRange(2, 3) moveAlphaShapeid1 = setInterval(moveDown1, 20) moveAlphaShapeid2 = setInterval(moveDown2, 20) moveAlphaShapeid3 = setInterval(moveDown3, 20) moveAlphaShapeid4 = setInterval(moveDown4, 20) moveAlphaShapeid5 = setInterval(moveDown5, 20) moveAlphaShapeid6 = setInterval(moveDown6, 20) moveAlphaShapeid7 = setInterval(moveDown7, 20) if(!isDevice.any()){ variableSpeed = 0 window.addEventListener("keydown", keyPressed, true); window.addEventListener("keyup", keyReleased, true); moveCartid = setInterval(moveCart, 20) }else{ activateCart = true; variableSpeed = 6 } } } } } function clearAllLifeLines(){ for (i = 1; i <= 5; i++) { catchRoot.runTime_mc.gameScreen["heart"+i].alpha = 0; } } $( window ).on( "focus", function(e){ if(!isDevice.any()){ clearInterval(moveCartid); if(catchRoot.runTime_mc.gameScreen.visible == true){ window.addEventListener("keydown", keyPressed, true); window.addEventListener("keyup", keyReleased, true); moveCartid = setInterval(moveCart, 10) } } }); function keyPressed(evt){ var KeyID = (window.event) ? event.keyCode : evt.keyCode; switch(KeyID){ // left arrow key case 37: leftArrow = true; break; // right arrow key case 39: rightArrow = true; break; // right arrow key case 32: spaceBar = true; break; } } function keyReleased(evt){ var KeyID = (window.event) ? event.keyCode : evt.keyCode; switch(KeyID){ // left arrow key case 37: leftArrow = false; break; // right arrow key case 39: rightArrow = false; break; // right arrow key case 32: spaceBar = false; break; } } function moveCart() { if (spaceBar) { speed = 10; } else { speed = 4; } if (rightArrow) { if (cartMc.x < 596) { cartMc.x += speed; } else { cartMc.x = 597; } } if (leftArrow) { if (cartMc.x > 47) { cartMc.x -= speed; } else { cartMc.x = 46; } } } //Folowing code is for Accelerometer support // Does the gyroscope or accelerometer actually work? function deviceMotionTest(event) { window.removeEventListener('devicemotion', deviceMotionTest); window.parent.addEventListener('devicemotion', onDeviceMotionChange, false); animationId = setInterval(onRenderUpdate, 10); } function deviceOrientationTest(event) { window.removeEventListener('deviceorientation', deviceOrientationTest); // Listen for orientation changes window.parent.addEventListener('deviceorientation', onDeviceOrientationChange, false); } function onDeviceOrientationChange(event) { lastOrientation.gamma = event.gamma; lastOrientation.beta = event.beta; } function onDeviceMotionChange(event){ lastOrientation.gamma = event.accelerationIncludingGravity.x; lastOrientation.beta = event.accelerationIncludingGravity.y; } var acceleroSpeed = 2 function onRenderUpdate(event) { var xDelta, yDelta; var moveSpeed; switch (window.parent.orientation) { case 0: moveSpeed = lastOrientation.gamma*acceleroSpeed xDelta = moveSpeed; break; case 180: moveSpeed = (lastOrientation.gamma * -1)*acceleroSpeed xDelta = moveSpeed; break; case 90: moveSpeed = lastOrientation.beta*acceleroSpeed xDelta = moveSpeed; break; case -90: moveSpeed = (lastOrientation.beta * -1)*acceleroSpeed xDelta = moveSpeed; break; default: moveSpeed = lastOrientation.gamma*acceleroSpeed xDelta = moveSpeed; } moveAcceleratCart(Number(xDelta), Number(yDelta)); } function moveAcceleratCart(xDelta, yDelta) { if(xDelta && activateCart){ cartMc.x += (xDelta); if(cartMc.x<47){ cartMc.x=47 } if(cartMc.x>596){ cartMc.x=596 } catchStage.update(); } } var fadecartAlnumId; var ansCalCounter = 0 var assurance =0 var setQuestionComplete = false; var lifelineCounterId; function moveDown1() { validateAnswers(1) } function moveDown2() { validateAnswers(2) } function moveDown3() { validateAnswers(3) } function moveDown4() { validateAnswers(4) } function moveDown5() { validateAnswers(5) } function moveDown6() { validateAnswers(6) } function moveDown7() { validateAnswers(7) } var pauseCatch = false; var cartFadeComplete = true; var lifelinefadeCounter = 1; var beginfadecartAlnumId var templifeLineCounter function validateAnswers(VarId){ var tempMovie = catchRoot.runTime_mc.gameScreen["alnum"+VarId] tempMovie.y += (this["dropSpeed"+VarId]+variableSpeed); if(!setQuestionComplete && !pauseCatch){ if(tempMovie.x >= (cartMc.x-40) && tempMovie.x <= (cartMc.x+40)){ if(tempMovie.y >= (cartMc.y-40) && tempMovie.y <= cartMc.y){ var ansMatch = false; console.log(tempMovie.ansText,"tempMovie.ansText") var caughtChar = String(tempMovie.ansText).toLowerCase(); this["dropSpeed"+VarId] = randRange(speedRangeVal1, speedRangeVal2) tempMovie.y = yValArray[0]; ansCalCounter++; //Show cart anim if (quesType == "word") { if(globalIsWord=="true"){ cartMc.mc.resetAttr(14,1.3) cartMc.mc.setText(tempMovie.txt.text,true) }else{ cartMc.mc.resetAttr(24,0.909) cartMc.mc.setText(tempMovie.txt.text,false) } } else { cartMc.mc.resetAttr(24,0.909) cartMc.mc.setText(tempMovie.txt.text,false) } cartMc.mc.alpha = 1; beginfadecartAlnumId = setInterval(beginfadecartAlnum, 100) //Validating answer for (k = 0; k < mainCharListLength; k++) { var getCharBox = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + k); var tempCharString = String(getCharBox.txt.text).toLowerCase(); console.log (caughtChar, "==" ,tempCharString) if (caughtChar == tempCharString) { if (getCharBox.txt.visible == false) { getCharBox.txt.visible = true; if(getCharBox.type=="fullword"){ for(g = 0;g<getCharBox.count;g++){ getCharBox["base"+g].gotoAndStop(1) } }else{ getCharBox.base.gotoAndStop(1) } } } } var ansFound = false; var charFound; for (j = 0; j < charList.length; j++) { var matchChar = String(charList[j]).toLowerCase(); if (caughtChar == matchChar) { ansFound = true; charFound = j; break; } } if (ansFound) { //console.log("correct answer") resetArray(charList[charFound]) ansMatch = true; }else{ //console.log("incorrect answer") //liferline Checks pauseCatch = true; clearInterval(lifelineCounterId); lifelinefadeCounter = 1 lifelineCounterId = setInterval(fadeLifeLine, 30) templifeLineCounter = lifeLineCounter; lifeLineCounter--; if (lifeLineCounter == 0) { charList = []; setQuestionComplete = true; questionPassed = false; showMissedChars(); setQuestionCompleteFunc(); clearInterval(this["moveAlphaShapeid"+VarId]); } else if (lifeLineCounter <= 2) { showDistress(lifeLineCounter); } } if(!setQuestionComplete){ if (charList.length > 0) { if (ansCalCounter >= 2) { ansCalCounter = 0; if (assurance >= (charList.length - 1)) { assurance = 0 } else { assurance++; } if (quesType == "word") { if(globalIsWord=="true"){ tempMovie.resetAttr(14,1.3) tempMovie.setText(charList[assurance],true) }else{ tempMovie.resetAttr(24,0.909) tempMovie.setText(charList[assurance],false) } } else { tempMovie.txt.text = charList[assurance]; } tempMovie.ansText = charList[assurance]; } else { if (quesType == "word") { var randAlphaAns = alphaMixList[randRange(0, (alphaMixList.length - 1))]; if(globalIsWord=="true"){ tempMovie.resetAttr(14,1.3) tempMovie.setText(randAlphaAns,true) }else{ tempMovie.resetAttr(24,0.909) tempMovie.setText(randAlphaAns,false) } tempMovie.ansText = randAlphaAns; } else { var randNumAns = numMixList[randRange(0, (numMixList.length - 1))] tempMovie.resetAttr(24,0.909) tempMovie.setText(randNumAns,false) tempMovie.ansText = randNumAns; } } }else{ setQuestionComplete = true; questionPassed = true; setQuestionCompleteFunc(); clearInterval(this["moveAlphaShapeid"+VarId]) } } } } } if(tempMovie.y >=500){ if (charList.length > 0) { if (ansCalCounter >= 2) { ansCalCounter = 0; if (assurance >= (charList.length - 1)) { assurance = 0 } else { assurance++; } if (quesType == "word") { if(globalIsWord=="true"){ tempMovie.resetAttr(14,1.3) tempMovie.setText(charList[assurance],true) }else{ tempMovie.resetAttr(24,0.909) tempMovie.setText(charList[assurance],false) } }else{ tempMovie.txt.text = charList[assurance]; } tempMovie.ansText = charList[assurance]; } else { if (quesType == "word") { var randAlphaAns = alphaMixList[randRange(0, (alphaMixList.length - 1))]; if(globalIsWord=="true"){ tempMovie.resetAttr(14,1.3) tempMovie.setText(randAlphaAns,true) }else{ tempMovie.resetAttr(24,0.909) tempMovie.setText(randAlphaAns,false) } tempMovie.ansText = randAlphaAns } else { var randNumAns = numMixList[randRange(0, (numMixList.length - 1))] tempMovie.resetAttr(24,0.909) tempMovie.setText(randNumAns,false) tempMovie.ansText = randNumAns; } } }else{ if(!setQuestionComplete){ questionPassed = false; setQuestionComplete = true; setQuestionCompleteFunc(); } clearInterval(this["moveAlphaShapeid"+VarId]) } this["dropSpeed"+VarId] = randRange(speedRangeVal1, speedRangeVal2) tempMovie.y = yValArray[0]; ansCalCounter++; } } var fadealpcounter = 1; var myInterval function fadeOuAlphaNums() { myInterval = setInterval(fadeoutnums, 30); } function fadeoutnums() { fadealpcounter -= 0.2 if (fadealpcounter <= 0) { clearInterval(myInterval); } else { for (i= 1; i <= 7; i++) { catchRoot.runTime_mc.gameScreen["alnum" + i].alpha = fadealpcounter; } } } var fadeCounter = 1 function fadecartAlnum(){ fadeCounter-=0.2 cartMc.mc.alpha = fadeCounter; if(fadeCounter<=0){ clearInterval(fadecartAlnumId); fadeCounter=1 } } function beginfadecartAlnum(){ clearInterval(beginfadecartAlnumId); clearInterval(fadecartAlnumId); fadecartAlnumId = setInterval(fadecartAlnum, 30) } function fadeLifeLine(){ lifelinefadeCounter-=0.1 catchRoot.runTime_mc.gameScreen["heart"+templifeLineCounter].alpha = lifelinefadeCounter; if(catchRoot.runTime_mc.gameScreen["heart"+templifeLineCounter].alpha<=0.1){ pauseCatch = false; catchRoot.runTime_mc.gameScreen["heart"+templifeLineCounter].alpha=0.1; clearInterval(lifelineCounterId); } } function showMissedChars(){ for (k = 0; k < mainCharListLength; k++) { var getCharBox = catchRoot.runTime_mc.gameScreen.getChildByName("ansCharBox" + k); if (getCharBox.txt.visible == false) { getCharBox.txt.visible = true; if(getCharBox.type=="fullword"){ for(g = 0;g<getCharBox.count;g++){ getCharBox["base"+g].gotoAndStop(2) } }else{ getCharBox.base.gotoAndStop(2) } } } } function setQuestionCompleteFunc(){ clearAllLifelines(); if(catchRoot.runTime_mc.gameScreen.nextQuestion.visible == false){ catchRoot.runTime_mc.gameScreen.nextQuestion.visible =true; gameOverCheck = questionPassed; if(questionPassed){ //questionPassed = false; updateScore(); catchRoot.runTime_mc.gameScreen.nextQuestion.crctmc.visible =true; catchRoot.runTime_mc.gameScreen.nextQuestion.wrngmc.visible =false; }else{ //questionPassed = true; catchRoot.runTime_mc.gameScreen.nextQuestion.crctmc.visible =false; catchRoot.runTime_mc.gameScreen.nextQuestion.wrngmc.visible =true; } } fadealpcounter = 1; fadeOuAlphaNums(); } function showDistress(varStat) { var i; var j; for (j = 1; j <= 5; j++) { catchRoot.runTime_mc.gameScreen["heart" + j].heart.base.gotoAndStop(0); catchRoot.runTime_mc.gameScreen["heart" + j].heart.base_1.gotoAndStop(0); } for (i = 1; i <= varStat; i++) { catchRoot.runTime_mc.gameScreen["heart" + i].heart.base.gotoAndStop(1); catchRoot.runTime_mc.gameScreen["heart" + i].heart.base_1.play(); } } function clearAllLifelines(){ for (j = 1; j <= 5; j++) { catchRoot.runTime_mc.gameScreen["heart" + j].heart.base.gotoAndStop(0); catchRoot.runTime_mc.gameScreen["heart" + j].heart.base_1.gotoAndStop(0); } } function enableAllLifelines(){ for (j = 1; j <= 5; j++) { catchRoot.runTime_mc.gameScreen["heart" + j].heart.base.gotoAndStop(0); catchRoot.runTime_mc.gameScreen["heart" + j].heart.base_1.gotoAndStop(0); catchRoot.runTime_mc.gameScreen["heart" + j].alpha =1; } } function resetArray(varStat) { var i; var varStatToLower = String(varStat).toLowerCase(); for (i = 0; i < charList.length; i++) { var tempToLower = String(charList[i]).toLowerCase(); if (varStatToLower == tempToLower) { charList.splice(i, 1); resetArray(varStat); return; } } } function createAlphabetSet(varString) { var wordArray = varString.split(" "); var combinedArray = new Array(); var wordCount = new Array(); //Remove extra spaces function removeExtraSpaces() { for (var j = 0; j < wordArray.length; j++) { if (wordArray[j].length == 0) { wordArray.splice(j, 1) removeExtraSpaces(); } } } removeExtraSpaces(); //Extract all words for (var i = 0; i < wordArray.length; i++) { var wordAlphabetsArray = new Array(); wordAlphabetsArray = wordArray[i].split(""); wordCount.push(wordAlphabetsArray); } combinedArray.push(wordArray, wordCount); //Extract Alphabets for each word return combinedArray; } function createEquationSet(varString) { var equationArray = new Array(); var numbersArray = new Array(); var symbolArray = new Array(); var combinedArray = new Array(); var extractedNumber = ""; var arr = new Array(); //Remove all spaces from the equation var space = new RegExp(/\s/g); var string = varString.replace(space, ""); var stringArray = string.split(""); //Extract Numbers and symbols separately for (var i = 0; i < stringArray.length; i++) { var char = parseInt(stringArray[i]); if (!isNaN(char)) { //extractedNumber += stringArray[i]; numbersArray.push(i); } else { symbolArray.push(i) //combinedArray.push(stringArray[i]); /*if (extractedNumber) { numbersArray.push(i); combinedArray.push(parseInt(extractedNumber)); extractedNumber = ""; }*/ } } equationArray.push(numbersArray, symbolArray, stringArray) return equationArray; } function setnotdonemode() { //Hide EventThing } function startGame() { FastClick.attach(document.body); } var instClickCount = 0; function showFeedBack(varStat) { catchRoot.runTime_mc.endScreen.crctFeedback.visible = false; catchRoot.runTime_mc.endScreen.wrngFeedback.visible = true; catchRoot.runTime_mc.endScreen.yourScore.visible = true; catchRoot.runTime_mc.endScreen.finalScore.visible = true; catchRoot.runTime_mc.endScreen.visible = true; } function setReviewMode(varStat) { } function updateScore() { currentScore = currentScore+scoreForThisQuest; catchRoot.runTime_mc.gameScreen.scoreMc.score.text = currentScore + "/" + totalScore; }; function handleMouseOver(evt) { catchCanvas.style.cursor = "pointer"; } function handleMouseOut(evt) { catchCanvas.style.cursor = "default"; } function setSuccess() { var lInteractiveWidgetHandle = lcap.CPMovieHandle.getInteractiveWidgetHandle(); lInteractiveWidgetHandle.setSuccess(true); } function setFailure() { var lInteractiveWidgetHandle = lcap.CPMovieHandle.getInteractiveWidgetHandle(); lInteractiveWidgetHandle.setSuccess(false); } //Function for randomizing var ranCardNum; function getRandNumInRange(startNum, EndNum, MaxOut, pushToArray) { if (pushToArray.length == 0) { ranCardNum = randRange(startNum, EndNum); pushToArray.push(ranCardNum); getRandNumInRange(startNum, EndNum, MaxOut, pushToArray); } else { ranCount = 0; ranCardNum = randRange(startNum, EndNum); if (pushToArray.length < MaxOut) { for (i = 0; i < pushToArray.length; i++) { if (ranCardNum == pushToArray[i]) { ranCount++; } } if (ranCount == 0) { pushToArray.push(ranCardNum); } getRandNumInRange(startNum, EndNum, MaxOut, pushToArray); } } return pushToArray; } //Randomizeize within a range of numbers function randRange(minNum, maxNum) { var randNum = Math.floor(Math.random() * (maxNum - minNum)) + minNum; return randNum; } function updateSizeNPositionOnResizeComplete(){ resizeInteraction(width,height); }
ab71b5cdd2a31fe8799c1f914a8dde40cfc25457
[ "JavaScript" ]
1
JavaScript
SAllegre/elementarygames
6a20fa9ef2df63e146f6a0851209035dcc8915bd
8c966bccef5f58f498223769507b805bdb15ff17
refs/heads/master
<file_sep># googlehashcode2019 Our Google Hash Code 2019 Challenge Solution! With it, we were able to end in the **top 13.3%** ([885th/6640](https://codingcompetitions.withgoogle.com/hashcode/archive/2019)), not bad for our first coding competition! Regarding the developed algorithm, we first join the vertical photos in slides based on the least amount of tags in common they have, in order to have more matching posibilities with the horizontal slides. We then go over all the horizontal photos and calculate the minimum interest factor, following the optimisation [problem statement](https://github.com/izadiegizabal/googlehashcode2019/blob/master/photo_slideshow.pdf), until we find the one with whom it will have the biggest interest factor. Once we do that, we add them to the final ordered slides list and then repeat the process until we get the final ordered slides. As you can imagine, this is not the most efficient way of solving the problem, but this simple method proved to be quite reliable! Thanks to this we were able to finish first of our Hub, 24th in Spain and 885th Worldwide, top 6.2% in Spain and 13.3% globally, where more than 6640 teams competed! Taking into account it was our first code challenge, we are really happy with the results! We had a really good time and we hope to repeat the experience! For the Extended Round the results improved and we ended up 7th in Spain (top 1.8%) and 115th globally (**top 1.7%**)! With this code we were able to achieve over 700K Points in the Online Qualification Round. ![700K points proof](https://i.imgur.com/WJGTtM2.png) And over 1M Points in the Extended Round thanks to extra time time to run the program and compile de answers. ![1M points proof](https://i.imgur.com/LChP0yx.png) ![1st of torre juana](https://i.imgur.com/LvCJdo4.png) ![24th of Spain](https://i.imgur.com/iUN5U4j.png) ![885th worldwide](https://i.imgur.com/CLiBUC9.png) ![7th in Spain](https://i.imgur.com/gRd7Fiq.png) ![115th globally](https://i.imgur.com/js3e2KS.png) <file_sep>import java.util.ArrayList; public class Photo { private Integer index; private Boolean vertical; private ArrayList<String> tags; public Photo(Integer index, Boolean vertical, ArrayList<String> tags) { this.index = index; this.vertical = vertical; this.tags = new ArrayList<>(tags); } @Override public String toString() { return "Index: " + this.index + "\nOrientation: " + (vertical ? "Vertical" : "Horizontal") + "\nTags: " + tags.toString() + "\n"; } public Boolean getVertical() { return vertical; } public Integer getIndex() { return index; } public ArrayList<String> getTags() { return tags; } public void setIndex(Integer index) { this.index = index; } public void setTags(ArrayList<String> tags) { this.tags = tags; } public void setVertical(Boolean vertical) { this.vertical = vertical; } } <file_sep>import java.util.ArrayList; public class Slide { private ArrayList<Photo> photos; private ArrayList<String> tags; public Slide(ArrayList<Photo> photos) { this.photos = new ArrayList<>(photos); tags = new ArrayList<>(); this.photos.forEach(photo -> photo.getTags().forEach(tag -> { if (!tags.contains(tag)) { tags.add(tag); } })); } public ArrayList<Photo> getPhotos() { return photos; } public ArrayList<String> getTags() { return tags; } public void setPhotos(ArrayList<Photo> photos) { this.photos = photos; } @Override public String toString() { String indexes = ""; for (Photo photo : this.photos) { indexes += photo.getIndex() + " "; } return "Indexes: " + indexes + "Tags: " + this.tags; } }
a97d76a75366620fa23a840ac953f59bb94914cd
[ "Markdown", "Java" ]
3
Markdown
izadiegizabal/googlehashcode2019
f65852ba6d25c529c2f4aad26f4aef14d70e71de
b7ad951bcf819b77221d12f6f32cdd67a2fdf6d0
refs/heads/master
<repo_name>LaloEspino/asipro<file_sep>/src/pages/QuienesSomos.jsx import React, { Component, Fragment } from 'react' import '../styles/pages/QuienesSomos.css' class QuienesSomos extends Component { componentDidMount() { window.scrollTo(0, 0) } constructor(props) { super(props) this.state = { especialidades: [ { heading: 'headingOne', colapse: 'collapseOne', titulo: 'Sistemas de Detección de Incendio', texto: 'Independientemente de que hoy en día la prevención de incendio es una norma prevista por la Secretaría del Trabajo y Previsión Social (STPS), consideramos de vital importancia el analizar junto con el cliente cuales sería el sistema óptimo de detección rápida en caso de incendio, determinando el mínimo de detectores que el local y las zonas a proteger requieran. Esto se lleva a cabo cubriendo los requisitos mínimos establecidos por la guía de códigos locales o nacionales para la aplicación de sistemas de detección de incendio así como los requisitos de las autoridades gubernamentales.' }, { heading: 'headingTwo', colapse: 'collapseTwo', titulo: 'Circuito Cerrado de Televisión (CCTV)', texto: 'La necesidad de sentir y mantener la seguridad en nuestro entorno que pueda contemplar la grabación de los eventos solo es posible con un sistema de Circuito Cerrado de TV(CCTV), ya que por medio de una o varias cámaras, monitores, grabador analógico o digital que permite ver lo que acontece incluso vía remota(Internet) y hasta una impresora de video, podemos obtener un registro minucioso de la actividad en diferentes sitios.' }, { heading: 'headingThree', colapse: 'collapseThree', titulo: 'Sistemas de Control de Acceso ', texto: 'Un sistema integral de control de acceso permite contar con el registro de entrada y salida del personal mediante al uso de: tarjetas de proximidad, banda magnética, teclado, registro biométrico. Los sistemas de control de acceso que proponemos tienen un diseño modular, completo e independiente y pueden conectarse a configuraciones de puertas múltiples que se adaptan a las necesidades de los clientes y si se requiere, permite tener un registro histórico de todas las transacciones o eventos.' }, { heading: 'headingFour', colapse: 'collapseFour', titulo: 'Sistemas de Alarmas Contra Robo y Asalto ', texto: 'Al activarse un sistema de alarma nulifica el propósito del intruso o bien previene la sustracción de mercancía u otros objetos. Un sistema de alarma proporciona tranquilidad al propietario y reduce costos por robos o daños a equipo o material confidencial.' }, { heading: 'headingFive', colapse: 'collapseFive', titulo: 'Detectores de armas y metales ', texto: 'Utilizado hoy día en muchos lugares de acceso público y privado en la revisión de la persona. Un sistema de detección de armas y metales proporcionar seguridad y evitar cualquier intento de atento a la seguridad en el interior del local.' }, { heading: 'headingSix', colapse: 'collapseSix', titulo: 'Detectores de narcóticos y explosivos ', texto: 'Una realidad hoy en día ha motivado la supervisión de las personas y cosas para evitar la introducción y portación de narcóticos y explosivos a recintos públicos o privados. Existen sistemas y máquinas orientadas al control de estos aspectos.' } ] } } render() { const especialidades = this.state.especialidades.map((especialidad) => <Fragment key={especialidad.heading}> <div className='card'> <div className='card-header bg-dark' id={especialidad.heading}> <h5 className='mb-0'> <button className='btn btn-link text-light' data-toggle='collapse' data-target={'#' + especialidad.colapse} aria-expanded='true' aria-controls={especialidad.colapse}> {especialidad.titulo} </button> </h5> </div> <div id={especialidad.colapse} className='collapse' aria-labelledby={especialidad.heading} data-parent='#accordion'> <div className='card-body'> {especialidad.texto} </div> </div> </div> </Fragment> ) return ( <Fragment> <div className='container'> <h1 className='mt-5'>Quiénes Somos</h1> <p> Una Empresa que nace con la finalidad de satisfacer las demandas de Seguridad Patrimonial. </p> <p> Iniciamos nuestras actividades el primero de Junio de 1989 con el objeto de prestar servicios en el ramo de la asesoría, venta e instalación de equipos y sistemas de seguridad con la finalidad de atender la creciente demanda para la protección del patrimonio. </p> <p> En la actualidad nos hemos consolidado como empresa líder en el mercado de la seguridad lo que nos ha permitido diversificar nuestras líneas de servicio abarcando toda la república. Nuestra preparación y experiencia nos avala para atender las necesidades del cliente en todas las áreas de la seguridad. </p> <h3 className='mt-5 mb-3'>Objetivos</h3> <p> Nuestro propósito inicial es definir en forma integral las necesidades específicas de cada cliente y nuestro objetivo, el proporcionarle la mejor solución técnica utilizando productos de la mejor calidad y precio adecuado, complementado con mano de obra altamente calificada, buscando ante todo, su satisfacción. </p> <h3 className='mt-5 mb-3'>Nuestras Especialidades</h3> <p> Contamos con las siguientes áreas: </p> <div id='accordion'> {especialidades} </div> <h3 className='mt-5 mb-3'>Nuestros Recursos</h3> <p> Nuestros recursos humanos son la base de nuestro servicio. Nuestro personal se capacita continuamente de tal forma que nuestros clientes siempre podrán estar seguros de recibir un trabajo profesional. </p> </div> </Fragment> ) } } export default QuienesSomos <file_sep>/src/pages/Contacto.jsx import React, { Component, Fragment } from 'react' class Contacto extends Component { constructor(props) { super(props) this.state = { nombre: '' } } componentDidMount() { window.scrollTo(0, 0) } handleChange = (event) => { this.setState({ [event.target.name]: event.target.value }) } // handleSubmit = (event) => { // event.preventDefault() // window.addEventListener('load', function () { // // Fetch all the forms we want to apply custom Bootstrap validation styles to // var forms = document.getElementsByClassName('needs-validation'); // // Loop over them and prevent submission // var validation = Array.prototype.filter.call(forms, function (form) { // form.addEventListener('submit', function (event) { // if (form.checkValidity() === false) { // event.preventDefault(); // event.stopPropagation(); // } // form.classList.add('was-validated'); // }, false); // }); // }, false); // } render() { return ( <Fragment> <div className='container'> <h1 className='mt-5'>Contacto</h1> {/* <form className='needs-validation' novalidate> <div className='form-row'> <div className='col-md-4 mb-3'> <label for='validationCustom01'>Nombre</label> <input type='text' className='form-control' id='validationCustom01' placeholder='Nombre' name='nombre' value={this.state.nombre} onChange={this.handleChange} required /> <div className='valid-feedback'> Looks good! </div> </div> <div className='col-md-4 mb-3'> <label for='validationCustom02'>Last name</label> <input type='text' className='form-control' id='validationCustom02' placeholder='Last name' value='Otto' required /> <div className='valid-feedback'> Looks good! </div> </div> <div className='col-md-4 mb-3'> <label for='validationCustomUsername'>Username</label> <div className='input-group'> <div className='input-group-prepend'> <span className='input-group-text' id='inputGroupPrepend'>@</span> </div> <input type='text' className='form-control' id='validationCustomUsername' placeholder='Username' aria-describedby='inputGroupPrepend' required /> <div className='invalid-feedback'> Please choose a username. </div> </div> </div> </div> <div className='form-row'> <div className='col-md-6 mb-3'> <label for='validationCustom03'>City</label> <input type='text' className='form-control' id='validationCustom03' placeholder='City' required /> <div className='invalid-feedback'> Please provide a valid city. </div> </div> <div className='col-md-3 mb-3'> <label for='validationCustom04'>State</label> <input type='text' className='form-control' id='validationCustom04' placeholder='State' required /> <div className='invalid-feedback'> Please provide a valid state. </div> </div> <div className='col-md-3 mb-3'> <label for='validationCustom05'>Zip</label> <input type='text' className='form-control' id='validationCustom05' placeholder='Zip' required /> <div className='invalid-feedback'> Please provide a valid zip. </div> </div> </div> <div className='form-group'> <div className='form-check'> <input className='form-check-input' type='checkbox' value='' id='invalidCheck' required /> <label className='form-check-label' for='invalidCheck'> Agree to terms and conditions </label> <div className='invalid-feedback'> You must agree before submitting. </div> </div> </div> <button className='btn btn-primary' type='submit'>Submit form</button> </form> */} </div> </Fragment> ) } } export default Contacto <file_sep>/src/components/Footer.jsx import React, { Fragment } from 'react' import '../styles/components/Footer.css' class Footer extends React.Component { render() { return ( <Fragment> <footer className='footer mt-auto py-3'> <div className='container mt-5 mb-5 text-center'> <span className='text-muted'> Bonampak No. 52-1 Col. <NAME>. <NAME> C.P. 03600 México, CDMX </span> <br /> <span className='text-muted'> Tel. Conmutador: <a href='tel:5674 3274'>5674 3274</a>, email: <a href='mailto:<EMAIL>'><EMAIL></a> </span> <br /> <span className='text-muted'> Asipro S.A. de C.V Derechos Reservados 2007 </span> </div> </footer> </Fragment> ) } } export default Footer<file_sep>/src/components/Modal.jsx import React, { Fragment } from 'react' import '../styles/components/Modal.css' class Modal extends React.Component { handleClick = (documento) => { window.open(documento) } render() { const producto = this.props.producto return ( <Fragment> <div className='modal fade' id={producto.clave} tabIndex='-1' role='dialog' aria-labelledby='exampleModalCenterTitle' aria-hidden='true'> <div className='modal-dialog modal-dialog-centered' role='document'> <div className='modal-content'> <div className='modal-header'> <h5 className='modal-title' id='exampleModalCenterTitle'> {producto.titulo} </h5> <button type='button' className='close' data-dismiss='modal' aria-label='Close'> <span aria-hidden='true'>&times;</span> </button> </div> <div className='modal-body text-left'> <div className='text-center'> <img src={producto.imagen} className='img-fluid Modal__image' alt={producto.clave} /> </div> {producto.texto.map((texto, index) => <p key={index}>* {texto}</p> )} </div> <div className='modal-footer'> <button type='button' className='btn btn-secondary' data-dismiss='modal'>Cerrar</button> <button type='button' className='btn btn-primary' onClick={() => this.handleClick(producto.documento)}>Descargar ficha técnica</button> </div> </div> </div> </div> </Fragment> ) } } export default Modal<file_sep>/src/pages/Alarma.jsx import React, { Component, Fragment } from 'react' import { alarmas } from '../productos/alarma.js' import '../styles/pages/Alarma.css' import Modal from '../components/Modal.jsx'; class Alarma extends Component { componentDidMount() { window.scrollTo(0, 0) } render() { const alarmasMapping = alarmas.map((alarma, index) => <div key={index} className='col-lg-4 col-md-6 col-sm-6'> <div className='card Alarma__card text-center'> <img src={alarma.imagen} className='card-img-top' alt={alarma.titulo} /> <div className='card-body'> <h5 className='card-title'>{alarma.titulo}</h5> <button type='button' className='btn btn-primary' data-toggle='modal' data-target={'#' + alarma.clave}> Ver especificaciones </button> <Modal producto={alarma} /> </div> </div> </div> ) return ( <Fragment> <div className='container'> <h1 className='mt-5'>Alarma</h1> <p> Los actuales sistemas de alarma no sólo cubren cada vez mayor tipo de incidencias, sino que permiten disfrutar de un sistema a la medida para cada necesidad de la oficina, industria o del hogar. Pueden ser aplicables a eventos como robo, incendio, etc. </p> <p> Un sistema de alarma digital permite que se le integren diversos tipos de componentes como: detector de ruptura de cristal, detector de movimiento, sirena, luz estrobo, contactos magnéticos para puertas, ventanas, foto celdas (protección exterior). </p> <div className='container'> <div className='row'> {alarmasMapping} </div> </div> </div> </Fragment> ) } } export default Alarma <file_sep>/src/pages/NotFound.jsx import React, { Component, Fragment } from 'react' import { Link } from 'react-router-dom' import bug from '../images/bug.svg' import '../styles/pages/NotFound.css' class NotFound extends Component { componentDidMount() { window.scrollTo(0, 0) } render() { return ( <Fragment> <div className='jumbotron'> <h1 className='display-4'>ERROR 404!</h1> <p className='lead'>La página no existe.</p> <hr className='my-4' /> <Link className='btn btn-primary' to='/'>Regresar</Link> <div className='text-center'> <img className='NotFound__image mx-auto' src={bug} alt='Bug' /> </div> </div> </Fragment> ) } } export default NotFound
054c57898487cade2221e75f61a737dcbc0008dc
[ "JavaScript" ]
6
JavaScript
LaloEspino/asipro
192b1e1ef731057d440789552af6aea96bc819c6
b5e22dc4e5672b2c2b0c4ed2142977d4f8cd3835
refs/heads/master
<repo_name>cavo789/sql_formatter<file_sep>/README.md # SQL Formatter ![php 8.2](https://img.shields.io/badge/php-8.2-brightgreen?style=flat) ![Banner](./banner.svg) Very straight-forward script for formatting SQL statement. Format string like, f.i., ```sql SELECT LAT_N, CITY, TEMP_F FROM STATS, STATION WHERE MONTH = 7 AND STATS.ID = STATION.ID ORDER BY TEMP_F ``` into ```sql SELECT LAT_N, CITY, TEMP_F FROM STATS, STATION WHERE MONTH = 7 AND STATS.ID = STATION.ID ORDER BY TEMP_F ``` ## How to use Just copy/paste your SQL statement into the text box as illustrated here below and click on the `Format` button. ![sql_formatter](images/demo.gif) ## Source The `SqlFormatter` has been written by `<NAME>` and available on GitHub: https://github.com/jdorn/sql-formatter. <file_sep>/index.php <?php declare(strict_types=1); /* * AUTHOR : <NAME> * * Written date : 9 october 2018 * * Interface allowing to copy a non formatted SQL statement (in one line) and * get a SQL statement that is formatted (on multiple lines) and using color * syntaxing. * * * @see SQL-Formatter on https://github.com/jdorn/sql-formatter */ define('REPO', 'https://github.com/cavo789/sql_formatter'); $task = filter_input(INPUT_POST, 'task', FILTER_SANITIZE_FULL_SPECIAL_CHARS); if ('format' == $task) { // Retrieve the SQL statement $SQL = base64_decode(filter_input(INPUT_POST, 'sql', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); // Include the library require_once __DIR__ . '/lib/SqlFormatter.php'; // Return the formatted SQL header('Content-Type: text/html'); echo SqlFormatter::format($SQL); die(); } // Sample values $SQL = 'SELECT LAT_N, CITY, TEMP_F FROM STATS, STATION ' . 'WHERE MONTH = 7 AND STATS.ID = STATION.ID ORDER BY TEMP_F'; // Get the GitHub corner $github = ''; if (is_file($cat = __DIR__ . DIRECTORY_SEPARATOR . 'octocat.tmpl')) { $github = str_replace('%REPO%', REPO, file_get_contents($cat)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="author" content="<NAME>" /> <meta name="robots" content="noindex, nofollow" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8;" /> <title>SQL Formatter</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> </head> <body> <?php echo $github; ?> <div class="container"> <div class="page-header"> <h1>SQL Formatter</h1> </div> <div class="container"> <details> <summary>How to use?</summary> <div class="container-fluid"> <div class="row"> <div class="col-sm"> <ol> <li>Copy/Paste your SQL statement in the textbox</li> <li>Click on the Format button</li> </ol> </div> <div class="col-sm"> <img height="300px" src="https://raw.githubusercontent.com/cavo789/sql_formatter/master/images/demo.gif" alt="Demo"> </div> </div> </div> </details> <div class="form-group"> <label for="SQL">Copy/Paste your SQL statement in the textbox below then click on the Format button:</label> <textarea class="form-control" rows="5" id="SQL" name="SQL"><?php echo $SQL; ?></textarea> </div> <button type="button" id="btnFormat" class="btn btn-primary">Format</button> <hr /> <pre id="Result"></pre> <i style="display:block;font-size:0.6em;"> <a href="https://github.com/jdorn/sql-formatter"> SQL Formatter written by <NAME> </a> </i> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <script type="text/javascript"> $('#btnFormat').click(function(e) { e.stopImmediatePropagation(); var $data = new Object; $data.task = "format"; $data.sql = window.btoa($('#SQL').val()); $.ajax({ beforeSend: function() { $('#Result').html('<div><span class="ajax_loading">&nbsp;</span><span style="font-style:italic;font-size:1.5em;">Formatting...</span></div>'); $('#btnFormat').prop("disabled", true); }, async: true, type: "POST", url: "<?php echo basename(__FILE__); ?>", data: $data, datatype: "html", success: function(data) { $('#btnFormat').prop("disabled", false); $('#Result').html(data); } }); // $.ajax() }); </script> </body> </html>
490ac5ba9a535d107b7318c896f709fff710c9d8
[ "Markdown", "PHP" ]
2
Markdown
cavo789/sql_formatter
0653c3b7622ac26ffd5725a053cee40e195f8e9a
c7930fb3ee199b8ed137754c45f208bf6141c2cd
refs/heads/master
<file_sep># Webtech-LAB-performance-<file_sep><?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "examdata"; $conn = new mysqli($answer1,$answer2,$answer3,$answer4,$answer5,$answer6,$answer7,$answer8,$answer9,$answer10); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $answer1 = $_POST['answer1']; $answer2 = $_POST['answer2']; $answer3 = $_POST['answer3']; $answer4 = $_POST['answer4']; $answer5 = $_POST['answer5']; $answer6 = $_POST['answer6']; $answer7 = $_POST['answer7']; $answer8 = $_POST['answer8']; $answer9 = $_POST['answer9']; $answer10 = $_POST['answer10']; $sql = "INSERT INTO examdata (answer1,answer2,answer3,answer4,answer5,answer6,answer7,answer8,answer9,answer10) VALUES ('$answer1','$answer2','$answer3','$answer4','$answer5','$answer6','$answer7','$answer8','$answer9','$answer10') if ($conn->query($sql) === TRUE) { echo "NEW record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
451ac9f044e4cd53a29a9292c17688f04ce6cb33
[ "Markdown", "PHP" ]
2
Markdown
mdashikuzzaman/Webtech-LAB-performance-
475b2f21f23ae8e5f0cac0948e891c15fd1b44e6
64fcaec478f0276128ba6e29ff96d8fea3b49b0c
refs/heads/master
<repo_name>RomaOnyshkiv/teamCityConfig<file_sep>/src/test/java/SimpleTest.java import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertTrue; public class SimpleTest extends BaseTest{ private final String URL = "https://www.google.com"; private String searchQuery = ""; @Test public void simpleTest() { SearchWithGoogle search = PageFactory.initElements(driver, SearchWithGoogle.class); assertTrue(search .openPage(URL) .searchFor("test") .getResult() .contains("dTest")); } } <file_sep>/src/main/java/SearchWithGoogle.java import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class SearchWithGoogle extends AbstractPage { public SearchWithGoogle(WebDriver driver) { super(driver); } private By searchField = By.name("q"); private By searchBtn = By.className("lsb"); private By result = By.partialLinkText("dTest"); SearchWithGoogle openPage(String url) { openURL(url); return this; } String getResult() { return getText(result); } SearchWithGoogle searchFor(String text) { typeTest(searchField, text); clickOn(searchBtn); return this; } }
a1ad1e847678cbe8c57cc161420af5a4f9abcc6d
[ "Java" ]
2
Java
RomaOnyshkiv/teamCityConfig
950bc12b754a34669945a3e7326fb80a2db86fb5
047fc2840a8b0281f6be6c79207dd78cf83b007a
refs/heads/master
<file_sep>package com.noujnouj.ocr.nouj.trackernouj; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; public class Prefs { private static Prefs instance; private static String PREFS = "PREFS"; private static String INSTALLATIONS = "INSTALLATIONS"; private SharedPreferences prefs; private Prefs(Context context) { prefs = context.getSharedPreferences(PREFS, Activity.MODE_PRIVATE); } public static Prefs getInstance(Context context) { if (instance == null) instance = new Prefs(context); return instance; } public void storeUserMoods(ArrayList<Mood> moods) { //start writing (open the file) SharedPreferences.Editor editor = prefs.edit(); //put the data Gson gson = new Gson(); String json = gson.toJson(moods); editor.putString(INSTALLATIONS, json); //close the file editor.apply(); } public ArrayList<Mood> getUserMoods() { Gson gson = new Gson(); String json = prefs.getString(INSTALLATIONS, ""); ArrayList<Mood> mood; if (json.length() < 1) { mood = new ArrayList<>(); } else { Type type = new TypeToken<ArrayList<Mood>>() { }.getType(); mood = gson.fromJson(json, type); } return mood; } }<file_sep>package com.noujnouj.ocr.nouj.trackernouj; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import java.util.ArrayList; import java.util.Calendar; import static android.app.AlarmManager.INTERVAL_DAY; import static android.app.AlarmManager.RTC_WAKEUP; public class MainActivity extends AppCompatActivity { Context c = this; public static final String TAG = MainActivity.class.getSimpleName(); private ViewGroup mMainLayout; private ImageView mCurrentBackground; private ImageView mCurrentSmiley; protected int mCurrentMoodIndex; private String mMoodComment; private ArrayList<Mood> mMoodList; @SuppressLint("ClickableViewAccessibility") @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* set the default mood index to Happy (3) */ mCurrentMoodIndex = 3; setTheTimeToUpdateTables(); //mMainLayout = (ViewGroup) ((ViewGroup) this .findViewById(android.R.id.content)).getChildAt(0); mCurrentBackground = findViewById(R.id.activity_main_current_background); mCurrentSmiley = findViewById(R.id.activity_main_current_smiley); Button messageBtn = findViewById(R.id.activity_main_message_btn); Button historyBtn = findViewById(R.id.activity_main_history_btn); initMoodList(); mCurrentBackground.setBackgroundColor(getResources().getColor(mMoodList.get(mCurrentMoodIndex).getMoodColor())); // Display XML elements related to the latest mood index (default or selected by the user) mCurrentSmiley.setImageDrawable(getResources().getDrawable(mMoodList.get(mCurrentMoodIndex).getMoodSmiley())); // mMainLayout.setBackground(getResources().getDrawable(mMoodList.get(mCurrentMoodIndex).getMoodSmiley())); /* On swipe implementation */ mCurrentBackground.setOnTouchListener(new OnSwipeTouchListener(this) { SoundsUtil soundsUtil = new SoundsUtil(c); public void onSwipeTop() { incrementMoodIndex(); soundsUtil.playSound(mCurrentMoodIndex); mCurrentBackground.setBackgroundColor(getResources().getColor(mMoodList.get(mCurrentMoodIndex).getMoodColor())); mCurrentSmiley.setImageDrawable(getResources().getDrawable(mMoodList.get(mCurrentMoodIndex).getMoodSmiley())); } public void onSwipeRight() { } public void onSwipeLeft() { } public void onSwipeBottom() { decrementMoodIndex(); soundsUtil.playSound(mCurrentMoodIndex); mCurrentBackground.setBackgroundColor(getResources().getColor(mMoodList.get(mCurrentMoodIndex).getMoodColor())); mCurrentSmiley.setImageDrawable(getResources().getDrawable(mMoodList.get(mCurrentMoodIndex).getMoodSmiley())); } }); /* On click listener for optional daily comments - Dialog box */ messageBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showCommentDialog(); } }); /* On click listener for History activity with display of previous moods (Recycler View) */ historyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, HistoryActivity.class); startActivity(intent); } }); } @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onStop() { super.onStop(); mMoodList.get(mCurrentMoodIndex).setMoodComment(mMoodComment); SaveMoodHelper smh = new SaveMoodHelper(Prefs.getInstance(this), mMoodList.get(mCurrentMoodIndex)); smh.saveMood(); mMoodComment = null; } /* Create 5 moods @param moodIndex The mood index number @param moodColor The mood color @param moodSmiley The mood smiley */ public void initMoodList() { Mood mood1 = new Mood(0, R.color.disappointed_faded_red, R.drawable.smiley_disappointed); Mood mood2 = new Mood(1, R.color.sad_warm_grey, R.drawable.smiley_sad); Mood mood3 = new Mood(2, R.color.normal_cornflower_blue_65, R.drawable.smiley_normal); Mood mood4 = new Mood(3, R.color.happy_light_sage, R.drawable.smiley_happy); Mood mood5 = new Mood(4, R.color.super_happy_banana_yellow, R.drawable.smiley_super_happy); mMoodList = new ArrayList<>(); mMoodList.add(mood1); mMoodList.add(mood2); mMoodList.add(mood3); mMoodList.add(mood4); mMoodList.add(mood5); } /* OnSwipeUp Increment mood index until 4 @param mCurrentMoodIndex The current mood index */ private void incrementMoodIndex() { if (mCurrentMoodIndex < 4) { ++mCurrentMoodIndex; } } /* OnSwipeDown Decrement mood index until -1 @param mCurrentMoodIndex The current mood index */ private void decrementMoodIndex() { if (mCurrentMoodIndex > 0) { --mCurrentMoodIndex; } } /* Display the dialog box for optional daily comments */ public void showCommentDialog () { final EditText taskEditText = new EditText(this); AlertDialog dialog = new AlertDialog.Builder(this) .setTitle("Commentaire") .setView(taskEditText) .setPositiveButton("Valider", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mMoodComment = taskEditText.getText().toString(); } }) .setNegativeButton("Annuler", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //cancel } }) .create(); dialog.show(); } /* Alarm Manager - Store default mood at midnight */ private void setTheTimeToUpdateTables() { Log.i("Update table function", "Yes"); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Intent alarmIntent = new Intent(this, RecurringTasks.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.cancel(pendingIntent); Calendar alarmStartTime = Calendar.getInstance(); alarmStartTime.set(Calendar.HOUR_OF_DAY, 0); alarmStartTime.set(Calendar.MINUTE, 0); alarmStartTime.set(Calendar.SECOND, 0); alarmManager.setRepeating(RTC_WAKEUP, alarmStartTime.getTimeInMillis(), INTERVAL_DAY, pendingIntent); Log.d("Alarm", "Set for midnight"); } } <file_sep>package com.noujnouj.ocr.nouj.trackernouj; import android.annotation.TargetApi; import android.os.Build; import android.support.annotation.RequiresApi; import java.time.LocalDate; import java.time.Period; import java.time.format.DateTimeFormatter; public class DatesUtil { public DatesUtil() { } /* Get today's date - LocalDate format */ @TargetApi(Build.VERSION_CODES.O) public LocalDate getTodayDate() { LocalDate date; date = LocalDate.now(); return date; } /* Convert today's date in a String format */ public String getTodayStr() { return getTodayDate().toString(); } /* Check if 2 dates are identical - String format @param date1, date2 The 2 dates to compare in String format */ public boolean compareDates (String date1, String date2) { if (date1.equals(date2)) { return true; } else { return false; } } /* Convert a String date to a LocalDate date @param dateStr The date in String format */ @RequiresApi(api = Build.VERSION_CODES.O) public LocalDate convertDateStrToLocalDate(String dateStr) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate localDate = LocalDate.parse(dateStr, formatter); return localDate; } /* Calculates the number of days between 2 dates - LocalDate format @param date1, date2 The 2 dates to compare in LocalDate format */ @RequiresApi(api = Build.VERSION_CODES.O) public int daysBetweenDates(LocalDate date1, LocalDate date2) { Period period = Period.between(date1, date2); int diff = period.getDays(); return diff; } } <file_sep>package com.noujnouj.ocr.nouj.trackernouj; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.Button; import java.util.ArrayList; public class HistoryActivity extends AppCompatActivity { public RecyclerView mRecyclerView; public UserMoodsAdapter mUserMoodsAdapter; public ArrayList<Mood> mHistoryMoods; public Button mCommentButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); mRecyclerView = findViewById(R.id.history_activity_recycler_view); mCommentButton = findViewById(R.id.buttonViewMessage); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); Prefs prefs = Prefs.getInstance(this); mHistoryMoods = prefs.getUserMoods(); mUserMoodsAdapter = new UserMoodsAdapter(this, mHistoryMoods); mRecyclerView.setAdapter(mUserMoodsAdapter); } }
fac7ed99e19e82bde9415c6994a85f9d56d07301
[ "Java" ]
4
Java
PhilNouj/MoodTracker
80640b1483e3ccb0ccfa5d47f6c5e7f75b835391
074c26632fc5a5b097ac26effff9cdb77debe661