language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
1,699
2.59375
3
[]
no_license
# Java小專題-網路投保系統 DEMO 模擬一個網路投保平台(未串接金流),提供三種保險商品試算保費、投保及查詢保單等服務。 DEMO(Youtube) [影片連結](https://youtu.be/8HXu-Y0e3ho "Java小專題-網路投保系統 DEMO") #主要架構與`package`說明如下: **`controller`**: 3種保險各一個:`Accident`、`Life`、`Tour` 簽發保單:`Underwriter` 會員管理:`MemberServlet` **`model`**:分為 (1)`model.premium`:計算保費 定期壽險`LifeCalculator`及旅遊平安險`TourCalculator`,意外險由後述`calculateAccident.js`計算 (2)`model.policy`:簽發保單 3種保險各一個:`AccidentUnderwriter`、`LifeUnderwriter`、`TourUnderwriter`;產生保單號碼:`PolicyNumber` (3)`model.member`: 會員相關邏輯:`MemberService`;檢查身分證字號:`CheckID` **`beans`**:專案所用到的java bean 保單`Policy` 3種保險各一個:`PolicyAccident`、`PolicyLife`、`PolicyTour`,並繼承`Policy` 會員`Member` **`api`**:專案共用的類別 `BCrypt`&`CheckPasswd`:密碼加解密 `ConnectionPool`:資料庫連線池 JNDI Data Source名稱 **`view`**(jsp) 試算保費:`calculate`、`calculate_accident`、`calculate_life`、`calculate_tour` 保單投保:`apply`、`applyAccident`、`applyLife`、`applyTour` 保單預覽:`previewAccident`、`previewLife`、`previewTour` 會員相關:`member`、`myPolicy`、`myPolicyDetail`、`register`、`edit`、`forget` **`vendor/js`**(javascript) 試算保費相關:`calculateAccident`、`calculateLife`、`calculateTour` 旅平險自動調整出發時間:`selectTime` 註冊會員身分證字號檢查:`checkID`
Python
UTF-8
1,656
2.5625
3
[]
no_license
import scipy import sklearn import sklearn.cluster import pickle from enum import Enum from sklearn.decomposition import PCA import numpy as np from sklearn.preprocessing import StandardScaler import csv class Objects(Enum): banana=1 bulldozer=2 chair=3 eyeglasses=4 flashlight=5 foot=6 hand=7 harp=8 hat=9 keyboard=10 laptop=11 nose=12 parrot=13 penguin=14 pig=15 skyscraper=16 snowman=17 spider=18 trombone=19 violin=20 def create_train(): lengths=[] filename="/home/cse/btech/cs1150251/scratch/train/"+Objects(1).name+ ".npy" obj_np=np.load(filename) obj_np=np.array(obj_np/255) lengths.append(len(obj_np)) for i in range(1,20): filename="/home/cse/btech/cs1150251/scratch/train/"+Objects(i+1).name+ ".npy" temp=np.load(filename) temp=np.array(temp/255) lengths.append(len(temp)) obj_np=np.vstack((obj_np,temp)) # print(lengths) return obj_np, lengths # def csv_writer(test_answers): # with open('/home/cse/btech/cs1150251/scratch/answers.csv', 'w') as csvfile: # mywriter = csv.writer(csvfile, delimiter=',') # mywriter.writerow(["ID", "CATEGORY"]) # for i in range(len(test_answers)): # mywriter.writerow([i, Objects(test_answers[i]+1).name]) def csv_reader(): main_arr=np.zeros((100000,20)) for i in range(6): with open((i+1).str()+".csv", 'r') as csvfile: myreader = csv.reader(csvfile, delimiter=',') for row in myreader: print(row) break csv_reader()
Python
UTF-8
3,820
2.890625
3
[]
no_license
import scipy from sklearn.feature_selection import mutual_info_classif, SelectKBest, RFE from sklearn.discriminant_analysis import LinearDiscriminantAnalysis import sklearn.model_selection from sklearn.metrics import roc_auc_score from sklearn.neighbors.kde import KernelDensity from sklearn.svm import SVR import numpy as np def kruskal_wallis(data, n_features=16, seed=None): """ preforms feature selection using kruskal wallis Recieves: data -> data frame n_features -> number of remaining features Returns: keep_features -> list with the naime of the choosen features """ rank = [] for i in data['x'].columns: setX = data['x'][i].values rank.append((i, scipy.stats.kruskal(setX, data['y'])[0])) rank = sorted(rank, key=lambda x: x[1]) keep_features = [] for i in range(n_features): keep_features.append(rank[i][0]) return keep_features def select_k_best(data, n_features=16, seed=None): """ Preforms feature selection using the select_k_best with mutual_info_classif Recieves: data -> data frame n_features -> number of remaining features Returns: keep_features -> list with the naime of the choosen features """ clf = SelectKBest(mutual_info_classif, k=n_features) new_data = clf.fit_transform(data['x'], data['y'].ravel()) mask = clf.get_support() keep_features = data['x'].columns[mask] return keep_features def ROC(data, n_features=16, seed=None): """ Preforms feature selection using the ROC with LDA classifier Recieves: data -> data frame n_features -> number of remaining features Returns: keep_features -> list with the naime of the choosen features """ rank = [] classifier = LinearDiscriminantAnalysis() X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(data['x'], data['y'], test_size=0.25, random_state=seed, shuffle=False) for i in X_train.columns: x_train_2d_array = X_train[i].to_frame() y_score = classifier.fit(x_train_2d_array, y_train) x_test_2d_array = X_test[i].to_frame() y_score = y_score.decision_function(x_test_2d_array) rank.append([i, roc_auc_score(y_test, y_score)]) rank = sorted(rank, key=lambda x: x[1]) keep_features = [] for i in range(n_features): keep_features.append(rank[i][0]) return keep_features def kernel_density_fs(data, n_features=16, seed=None): """ Preforms feature selection using the KernelDensity with gaussian kernel Recieves: data -> data frame n_features -> number of remaining features Returns: keep_features -> list with the naime of the choosen features """ rank = [] for column in data['x']: df = data['x'][column].values.reshape(-1, 1) kde = KernelDensity(kernel='gaussian', bandwidth=0.2).fit(df) values = kde.score(df, data['y']) rank.append((column, values)) rank = sorted(rank, key=lambda x: x[1], reverse=True) keep_features = [] for i in range(n_features): keep_features.append(rank[i][0]) return keep_features def RFE_fs(data, n_features=16, seed=None): """ Preforms feature selection using the RFE with LDA Recieves: data -> data frame n_features -> number of remaining features Returns: keep_features -> list with the naime of the choosen features """ estimator = LinearDiscriminantAnalysis() selector = RFE(estimator, n_features) selector = selector.fit(data['x'], data['y']) mask = selector.get_support() keep_features = data['x'].columns[mask] return keep_features
C++
UTF-8
2,251
3.90625
4
[]
no_license
// // Created by m43 on 22. 04. 2020.. // #include <iostream> #include <string> #include <vector> #include <set> using namespace std; template<typename Iterator, typename Predicate> Iterator mymax( Iterator first, Iterator last, Predicate pred) { Iterator max_iterator = first; while (first != last) { if (pred(*max_iterator, *first) != 1) { max_iterator = first; } first++; } return max_iterator; } int arr_int[] = {1, 3, 5, 7, 4, 6, 9, 2, 72}; const string arr_str[] = { "Gle", "malu", "vocku", "poslije", "kise", "Puna", "je", "kapi", "pa", "ih", "njise" }; vector<string> str_vector(arr_str, arr_str + sizeof(arr_str) / sizeof(char *)); set<string> str_set(arr_str, arr_str + sizeof(arr_str) / sizeof(char *)); int main() { // C++ is smart so "mymax<int *, int (*)(int&,int&)>(...)" becomes "mymax(...)" const int *maxint = mymax( &arr_int[0], &arr_int[sizeof(arr_int) / sizeof(*arr_int)], [](int &x, int &y) { return x > y ? 1 : 0; } ); cout << "Max integer is " << *maxint << "\n"; auto max_arr = mymax( &arr_str[0], &arr_str[sizeof(arr_str) / sizeof(*arr_str)], [](const string &x, const string &y) { return x.compare(y) > 0 ? 1 : 0; } ); cout << "Max string in array is " << *max_arr << "\n"; auto max_vec = mymax( str_vector.begin(), str_vector.end(), [](auto &x, auto &y) { return x.compare(y) > 0 ? 1 : 0; } ); cout << "Max string in vector is " << *max_vec << "\n"; auto max_set = mymax( str_set.begin(), str_set.end(), [](auto x, auto y) { return x.compare(y) > 0 ? 1 : 0; } ); cout << "Max string in set is " << *max_set << "\n"; return 0; } /* "Comment on the advantages and disadvantages of this implementation over the implementation from the previous task" In the previous task the solution was not as flexible as it is here. In this solution, mymax can accept any data structure for which some kind of iterator can be defined: bare arrays (though one needs to construct the iterator manually), std::vector, std::set etc. */
Java
UTF-8
208
1.546875
2
[]
no_license
package d3; public interface setup{ final public static class env{ public world wld; public window win; public player[]plrs; } public void do_setup(final applet app,final env ret)throws Throwable; }
C
WINDOWS-1251
2,923
3.640625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> int main() { int i, n=1; // , . char mas[100]; printf("\nput string\n"); scanf("%s",mas);/* // N , . for (i=0;i<n; i++) { puts(mas); } // . . for (i=0;i<strlen(mas);i++) { if((mas[i]>='a')&&(mas[i]<='z')) { mas[i]=toupper(mas[i]); continue; } if((mas[i]>='A')&&(mas[i]<='Z')) { mas[i]=tolower(mas[i]); continue; } } puts(mas); // . int num=0; for (i=0;i<strlen(mas);i++) { if((mas[i]>='0')&&(mas[i]<='9')) num++; } printf("\nnum=%i",num); // . int sum=0; for (i=0;i<strlen(mas);i++) { if((mas[i]>='0')&&(mas[i]<='9')) sum+=mas[i]-'0'; } printf("\nsum=%i",sum); // N, (N < ). int N=5; for (i=N;i<strlen(mas);i++){ mas[i]=' ';} puts(mas); // . . printf("\nput char\n"); char mat; _flushall(); mat=getchar(); int c = 0; for (i=0;i<strlen(mas);i++){ if(mas[i]==mat) {printf("YEAH"); break; } else { c++; } } if (c==(strlen(mas))) printf("NO!"); */ // 2 . ( ) . char mas2[100]; char *istr; printf("\nput string2\n"); scanf("%s",mas2);/* istr = strstr (mas,mas2); if ( istr == NULL) printf("NO!"); else printf("YEAH"); */ // int count=0; char *p=&mas; int a=0; int d=0; int axe=0; int t=1; /* do{ if(d==0) { axe=0; d++; } istr = strstr (mas+axe,mas2); axe=strlen(mas2); if ( istr == NULL) { break; } count++; } while (( istr != NULL)); */ while (t) { if(d==0) { axe=0; d++; } istr = strstr (mas+axe,mas2); axe=strlen(mas2); if ( istr == NULL) { t=0; } count++; } printf("\nCOunt=%d",count); return 0; }
C++
UTF-8
2,049
2.65625
3
[]
no_license
#include "ExhaustivePatchMatch.h" #include <boost/progress.hpp> #include "boost/iostreams/stream.hpp" using cv::Mat; using cv::matchTemplate; using cv::minMaxLoc; using cv::Point; using cv::Rect; using cv::Scalar; using cv::Vec3f; using std::shared_ptr; ExhaustivePatchMatch::ExhaustivePatchMatch(const Mat &source, const Mat &target, int patch_size, bool show_progress_bar) : _source(source), _target(target), _patch_size(patch_size), _show_progress_bar(show_progress_bar) { _temp.create(source.rows - _patch_size + 1, source.cols - _patch_size + 1, CV_32FC1); } shared_ptr<OffsetMap> ExhaustivePatchMatch::match() { auto offset_map = shared_ptr<OffsetMap>(new OffsetMap(_target.cols - _patch_size + 1, _target.rows - _patch_size + 1)); const unsigned long matched_pixels = static_cast<unsigned long>(offset_map->_width * offset_map->_height); boost::iostreams::stream<boost::iostreams::null_sink> nullout { boost::iostreams::null_sink{} }; std::ostream& out = _show_progress_bar ? std::cout : nullout; boost::progress_display show_progress(matched_pixels, out); for (int x = 0; x < offset_map->_width; x++) { for (int y = 0; y < offset_map->_height; y++) { Rect rect(x, y, _patch_size, _patch_size); Mat patch = _target(rect); OffsetMapEntry *entry = offset_map->ptr(y, x); double minVal; Point min_loc; matchSinglePatch(patch, &minVal, &min_loc); entry->distance = static_cast<float>(minVal); entry->offset = Point(min_loc.x - x, min_loc.y - y); } show_progress += offset_map->_width; } return offset_map; } void ExhaustivePatchMatch::matchSinglePatch(const Mat &patch, double *minVal, Point *minLoc) const { // Do the Matching matchTemplate(_source, patch, _temp, cv::TM_SQDIFF); // Localizing the best match with minMaxLoc minMaxLoc(_temp, minVal, nullptr, minLoc, nullptr); }
Python
UTF-8
544
3.71875
4
[]
no_license
from threading import Thread i = 0 def Thread1(): for j in range(1000000): i=i+1 def Thread1(): for j in range(1000000): i=i-1 # Potentially useful thing: # In Python you "import" a global variable, instead of "export"ing it when you declare it # (This is probably an effort to make you feel bad about typing the word "global") global i def main(): thread1 = Thread(target = Thread1, args = (),) thread2 = Thread(target = Thread1, args = (),) thread1.start() thread2.start() thread1.join() thread2.join() print(i) main()
JavaScript
UTF-8
1,758
4.3125
4
[]
no_license
//Function that returns an object which gives the total amount of change to give back following a purchase. const calculateChange = function(total, cash) { const currencyNames = ['twentyDollar', 'tenDollar', 'fiveDollar', 'twoDollar', 'oneDollar', 'quarter', 'dime', 'nickle', 'penny'] //Holder for currency names. const currencyValues = [2000, 1000, 500, 200, 100, 25, 10, 5, 1] //Holder for currency values let changeObject = {}; //Array to hold final change object. let changeLeft = cash - total; //Equation to calculate change. for (let i = 0; i < currencyValues.length; i++) { //Loop through calculateChange values. if (changeLeft >= currencyValues[i]) { //If change left (cash - total) is greater than the currency value index, proceed with code in block. //Use >= to include exact change (ex change 100 = oneDollar: 1 vs quarters: 4). changeObject [currencyNames[i]] = Math.floor(changeLeft / currencyValues[i]); //Assign currency name to changeObject key and assign the value to the change divided by the currency value to determine how many of that currency are needed (ex: fiveDollar: 2). // Math floor is used to round down to the nearest whole number, as you cannot give partial denominations back (ex. fiveDollar: 2.5). changeLeft = changeLeft % currencyValues[i]; //Assign change left following each subtraction of currency. (start with 600 change, subtract 500 following fiveDollars to give you 100. then subtract 100 following oneDollar to give you 0 - until no change is left). } } return changeObject; //Return final object. }; console.log(calculateChange(1787, 2000)); console.log(calculateChange(2623, 4000)); console.log(calculateChange(501, 1000));
Go
UTF-8
5,934
2.515625
3
[]
no_license
package ui import ( "image" "image/color" "image/draw" "log" "golang.org/x/image/font" "github.com/jmigpin/editor/imageutil" "github.com/jmigpin/editor/ui/tautil" "github.com/jmigpin/editor/xgbutil/evreg" "github.com/jmigpin/editor/xgbutil/xcursors" "github.com/BurntSushi/xgb/xproto" ) const ( SeparatorWidth = 1 ) var ( ScrollbarWidth = 10 SquareWidth = 10 ScrollbarLeft = false ) func SetScrollbarAndSquareWidth(v int) { ScrollbarWidth = v SquareWidth = v } type UI struct { win *Window Layout *Layout fface1 font.Face CursorMan *CursorMan EvReg *evreg.Register Events2 chan interface{} incompleteDraws int } func NewUI(fface font.Face) (*UI, error) { ui := &UI{ fface1: fface, Events2: make(chan interface{}, 256), } ui.EvReg = evreg.NewRegister() ui.EvReg.Events = ui.Events2 win, err := NewWindow(ui.EvReg) if err != nil { return nil, err } ui.win = win ui.CursorMan = NewCursorMan(ui) ui.Layout = NewLayout(ui) ui.EvReg.Add(xproto.Expose, &evreg.Callback{ui.onExpose}) ui.EvReg.Add(evreg.ShmCompletionEventId, &evreg.Callback{ui.onShmCompletion}) ui.EvReg.Add(UITextAreaAppendAsyncEventId, &evreg.Callback{ui.onTextAreaAppendAsync}) ui.EvReg.Add(UITextAreaInsertStringAsyncEventId, &evreg.Callback{ui.onTextAreaInsertStringAsync}) return ui, nil } func (ui *UI) Close() { ui.win.Close() close(ui.Events2) } func (ui *UI) onExpose(ev0 interface{}) { ui.UpdateImageSize() ui.Layout.C.NeedPaint() } func (ui *UI) UpdateImageSize() { err := ui.win.UpdateImageSize() if err != nil { log.Println(err) } else { ib := ui.win.Image().Bounds() if !ui.Layout.C.Bounds.Eq(ib) { ui.Layout.C.Bounds = ib ui.Layout.C.CalcChildsBounds() ui.Layout.C.NeedPaint() } } } func (ui *UI) PaintIfNeeded() (painted bool) { if ui.incompleteDraws == 0 { ui.Layout.C.PaintIfNeeded(func(r *image.Rectangle) { painted = true ui.incompleteDraws++ ui.win.PutImage(r) }) } return painted } func (ui *UI) onShmCompletion(_ interface{}) { ui.incompleteDraws-- } func (ui *UI) RequestPaint() { ui.EvReg.Enqueue(evreg.NoOpEventId, nil) } func (ui *UI) Image() draw.Image { return ui.win.Image() } func (ui *UI) FillRectangle(r *image.Rectangle, c color.Color) { imageutil.FillRectangle(ui.Image(), r, c) } // Default fontface (used by textarea) func (ui *UI) FontFace() font.Face { return ui.fface1 } func (ui *UI) QueryPointer() (*image.Point, bool) { return ui.win.QueryPointer() } func (ui *UI) WarpPointer(p *image.Point) { ui.win.WarpPointer(p) //ui.animatedWarpPointer(p) } //func (ui *UI) animatedWarpPointer(p *image.Point) { // p0, ok := ui.QueryPointer() // if !ok { // ui.win.WarpPointer(p) // return // } // //jump := 50 // //jumpTime := time.Duration(20 * time.Millisecond) // //dx := p.X - p0.X // //dy := p.Y - p0.Y // //dist := math.Sqrt(float64(dx*dx + dy*dy)) // //jx := int(float64(jump) * float64(dx) / dist) // //jy := int(float64(jump) * float64(dy) / dist) // //x, y := p0.X, p0.Y // //for u := 0.0; u < dist; u += float64(jump) { // // x, y = x+jx, y+jy // // p2 := image.Point{x, y} // // ui.win.WarpPointer(&p2) // // time.Sleep(jumpTime) // //} // //ui.win.WarpPointer(p) // //return // fps := 30 // frameDur := time.Second / time.Duration(fps) // dur := time.Duration(400 * time.Millisecond) // now := time.Now() // end := now.Add(dur) // for ; !now.After(end); now = time.Now() { // step := dur - end.Sub(now) // step2 := float64(step) / float64(dur) // dx := p.X - p0.X // x := p0.X + int(float64(dx)*step2) // dy := p.Y - p0.Y // y := p0.Y + int(float64(dy)*step2) // p2 := &image.Point{x, y} // ui.win.WarpPointer(p2) // time.Sleep(frameDur) // } // // ensure final position at p // ui.win.WarpPointer(p) //} func (ui *UI) WarpPointerToRectanglePad(r0 *image.Rectangle) { p, ok := ui.QueryPointer() if !ok { return } // pad rectangle pad := 25 r := *r0 if r.Dx() < pad*2 { r.Min.X = r.Min.X + r.Dx()/2 r.Max.X = r.Min.X } else { r.Min.X += pad r.Max.X -= pad } if r.Dy() < pad*2 { r.Min.Y = r.Min.Y + r.Dy()/2 r.Max.Y = r.Min.Y } else { r.Min.Y += pad r.Max.Y -= pad } // put p inside if p.Y < r.Min.Y { p.Y = r.Min.Y } else if p.Y >= r.Max.Y { p.Y = r.Max.Y } if p.X < r.Min.X { p.X = r.Min.X } else if p.X >= r.Max.X { p.X = r.Max.X } ui.WarpPointer(p) } func (ui *UI) SetCursor(c xcursors.Cursor) { ui.win.Cursors.SetCursor(c) } func (ui *UI) RequestPrimaryPaste() (string, error) { return ui.win.Paste.RequestPrimary() } func (ui *UI) RequestClipboardPaste() (string, error) { return ui.win.Paste.RequestClipboard() } func (ui *UI) SetClipboardCopy(v string) { ui.win.Copy.SetClipboard(v) } func (ui *UI) SetPrimaryCopy(v string) { ui.win.Copy.SetPrimary(v) } func (ui *UI) TextAreaAppendAsync(ta *TextArea, str string) { ev := &UITextAreaAppendAsyncEvent{ta, str} ui.EvReg.Enqueue(UITextAreaAppendAsyncEventId, ev) } func (ui *UI) onTextAreaAppendAsync(ev0 interface{}) { ev := ev0.(*UITextAreaAppendAsyncEvent) ta := ev.TextArea str := ev.Str // max size for appends maxSize := 5 * 1024 * 1024 str2 := ta.Str() + str if len(str2) > maxSize { d := len(str2) - maxSize str2 = str2[d:] } // false,true = keep pos, but clear undo for massive savings ta.SetStrClear(str2, false, true) } func (ui *UI) TextAreaInsertStringAsync(ta *TextArea, str string) { ev := &UITextAreaInsertStringAsyncEvent{ta, str} ui.EvReg.Enqueue(UITextAreaInsertStringAsyncEventId, ev) } func (ui *UI) onTextAreaInsertStringAsync(ev0 interface{}) { ev := ev0.(*UITextAreaInsertStringAsyncEvent) tautil.InsertString(ev.TextArea, ev.Str) } const ( UITextAreaAppendAsyncEventId = evreg.UIEventIdStart + iota UITextAreaInsertStringAsyncEventId ) type UITextAreaAppendAsyncEvent struct { TextArea *TextArea Str string } type UITextAreaInsertStringAsyncEvent struct { TextArea *TextArea Str string }
JavaScript
UTF-8
352
2.71875
3
[ "MIT" ]
permissive
var Fiber = require('fibers'); function sleep(ms) { var fiber = Fiber.current; setTimeout(function() { fiber.run(); }, ms*1000); Fiber.yield(); } this.getParticipants = function () { return []; }; // the body this.body = function () { console.log('heijaa begin'); sleep(3); console.log('heijaa end'); };
Java
UTF-8
1,136
2.65625
3
[]
no_license
package user; import util.UserNameConverter; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Embeddable; /** * Created by oradchykova on 11/7/17. */ @Embeddable public class Credentials { @Column(nullable = false, unique = true, updatable = false) private String login; @Convert(converter = UserNameConverter.class) @Column(name = "user_name", nullable = false) private UserName name; protected Credentials() { } public Credentials(String login, UserName userName) { this.login = login; this.name = userName; } public String getLogin() { return login; } public UserName getName() { return name; } void setName(UserName name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Credentials that = (Credentials) o; return login.equals(that.login); } @Override public int hashCode() { return login.hashCode(); } }
C#
UTF-8
3,850
2.515625
3
[]
no_license
using Alexa.NET.Request.Type; using Alexa.NET.Response; using Alexa.NET.Response.Directive; using GameMaker.Implementations; using GameMaker.Interfaces; using GameMaker.Utils; using NLog; using System; using System.Collections.Generic; using System.Text; namespace GameMaker.IntentHandlers { class AddScoreIntent : IIntentHandler { public SkillResponse HandleIntent(IGameController gameMaker, IntentRequest intentRequest, string userId, string sessionId, Logger logger) { SkillResponse response = new SkillResponse(); response.Version = "1.0"; try { List<Player> players = gameMaker.GetGameScore(userId, null); if (players == null) { response.Response = Helpers.GetPlainTextResponseBody("Sorry, no active game found. Please create a game first", true, "Sorry, no active game found"); response.Response.ShouldEndSession = true; //say no game active } else { //if a score is passed if (intentRequest.Intent.Slots["score"].Value != null) { foreach (var p in players) { if (p.PlayerBookmark == 'P') { //save it p.PlayerScoreUncommited = Int32.Parse(intentRequest.Intent.Slots["score"].Value); p.PlayerBookmark = 'C';//completed gameMaker.SetGameScore(new List<Player>() { p }, userId, sessionId); } } } Player playerToSetScore = null; //find next player to name foreach (var p in players) { if (p.PlayerState == PlayerState.Active && (p.PlayerBookmark== char.MinValue||p.PlayerBookmark=='P' )) // handle pending from last session { playerToSetScore = p; p.PlayerBookmark = 'P';//picked gameMaker.SetGameScore(new List<Player>() { p }, userId, sessionId); // just update the flag break; } } if (playerToSetScore != null) { response.Response = Helpers.GetPlainTextResponseBody("Tell me the score for " + playerToSetScore.PlayerAlias, true, "Add scores"); response.Response.Directives.Add(new DialogElicitSlot("score")); response.Response.ShouldEndSession = false; } else { //no more players to get score of now update scores response.Response = Helpers.GetPlainTextResponseBody("Player scores added.", true, "Add scores"); foreach(var p in players) { p.PlayerScore += p.PlayerScoreUncommited; p.PlayerBookmark = char.MinValue; } gameMaker.SetGameScore(players, userId, sessionId); response.Response.ShouldEndSession = true; } } } catch (Exception e) { logger.Debug(e.StackTrace); response.Response = Helpers.GetPlainTextResponseBody("Sorry I encountered an error! Please try again", true, "Please try again"); } return response; } } }
Markdown
UTF-8
2,589
3
3
[ "MIT" ]
permissive
--- layout: post title: "Super simple BDD with Buildout" excerpt: "Behaviour-Driven Development without the overhead" category: blog tags: - bdd - tdd - buildout - python published: true --- I've been doing BDD for years. I've never used Lettuce, or behave, or Cucumber, or in fact any BDD framework. I've never really needed to, as I can achieve a similar result with the tools I'm already using: Python and Buildout. *** To get started, we add the following additions to our Buildout config: [buildout] parts = ... specs ... [specs] recipe = pbp.recipe.noserunner eggs = unittest2 pbp.recipe.noserunner pinocchio working-directory = ${buildout:directory} defaults = --where specs --exe --include ^(it|ensure|must|should|specs?|examples?) --include (specs?(.py)?|examples?(.py)?)$ --with-spec --spec-color As you can see we're using `nose` to aggregate and run our tests, but we're tweaking the way it works and specifying that it should look in a "specs" directory. The "BDD" magic is in the 2 `--include` lines. Here we tell `nose` to include files and classes that end with either `Spec(s)` or `Example(s)`, and tests that start with the BDD keywords: `it`, `ensure`, `must`, and `should`. However, the real star of the show is Pinocchio. By specifying `--with-spec` and `--spec-color` we get nicely laid-out, colourised test results. Here's an example of the sort of spec file we'd create in our project, `./specs/foo_spec.py`: import unittest from foo import foo class FooSpec(unittest.TestCase): def it_should_return_true_for_true_values(self): raise SkipTest('Not implemented') def it_should_return_false_for_false_values(self): self.assertFalse(foo()) def it_should_return_true_for_None_values(self): self.assertTrue(foo(None)) The nice thing about this is that we're writing simple unittest classes & methods. We can skip writing the plain-English "feature" files and go straight to writing Python. We're also not using any quirky decorators to tie things together, instead we're following a simple naming convention. We can also embellish our output with the use of docstrings on the classes and methods -- these will be used in place of the class/function name to give us more control over what we see in the results. Additionally, there's nothing that could get in the way when using standard nose plugins. So we can add plugins for coverage.
Markdown
UTF-8
5,253
3.0625
3
[]
no_license
# Run_Analysis ## Project Background The purpose of this project is to demonstrate an ability to collect, work with, and clean a data set. It is a requirement for completion of the Coursera Getting and Cleaning data course. It uses data compiled during a Human Activity Recognition experiment that built recordings of 30 subjects performing activities of daily living (ADL) while carrying a waist-mounted smartphone with embedded inertial sensors. ## Experiment Background From the UCI Machine Learning Repository website describing the experiment: The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years. Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope, we captured 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz. The experiments have been video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets, where 70% of the volunteers was selected for generating the training data and 30% the test data. The sensor signals (accelerometer and gyroscope) were pre-processed by applying noise filters and then sampled in fixed-width sliding windows of 2.56 sec and 50% overlap (128 readings/window). The sensor acceleration signal, which has gravitational and body motion components, was separated using a Butterworth low-pass filter into body acceleration and gravity. The gravitational force is assumed to have only low frequency components, therefore a filter with 0.3 Hz cutoff frequency was used. From each window, a vector of features was obtained by calculating variables from the time and frequency domain. ## Experiment Data Several text data files were provided from the experiment. Not all files were pertinent to the analysis. Specifically, the data files used include: * 'features_info.txt': Shows information about the variables used on the feature vector * 'features.txt': Lists the titles of all 561 features found in the test and training feature data sets. * 'activity_labels.txt': Lists the six activity class labels (1, 2, ...,6) and links them with with their activity name. * 'X_train.txt': Training set containing the feature data for 7,352 observations. * 'y_train.txt': Contains the activity labels associated with the 7,352 feature observations in the 'X_train.txt' file. * 'subject_train.txt': Contains the subject ID associated with the 7,352 feature observations in the 'X_train.txt' file. * 'X_test.txt': Test set containing the feature data for 2,947 observations * 'y_test.txt': Contains the activity labels associated with the 2,947 feature observations in the 'X_test.txt' file. * 'subject_test.txt': Contains the subject ID associated with the 2,947 feature observations in the 'X_test.txt' file. ## Goals of the analysis As specified in the project assignment instructions, these are the project objectives: * Merge the training and the test sets to create one data set. * Extract only the measurements on the mean and standard deviation for each measurement. * Use descriptive activity names to name the activities in the data set * Appropriately label the data set with descriptive variable names. * From the data set in the previous step, create a second, independent tidy data set with the average of each variable for each activity and each subject. ## Analysis Plan and Procedures The analysis plan includes the following steps: 1. Create data frames in R for all of the above text data files using the read.table() function 2. Add the appropriate column header titles to all resulting data frames 3. For the data frames containing the test and training features data, subset only the columns ending in "mean()" or "std()" in order to meet the above requirement "Extract only the measurements on the mean and standard deviation for each measurement." 4. Bind the test data (X_test, subject_test, and y_test) into a single test data frame using the cbind() function 5. Bind the training data (X_train, subject_train, and y_train) into a single training data frame using the cbind() function 6. Bind the test and training data frames into a single data frame using the rbind() function 7. Merge the resulting single data frame with the activity_labels data frame to include the activity titles 8. Remove the activityCode column from the data frame as it is no longer required 9. Change the feature column titles to more meaningful names 10. Melt the data frame and compute means for each feature column for each subject and activity The R commands to complete these steps are found in the Run_Analysis.R script file along with comments to provide details for each. ## Repository Contents This repository contains files that make up the solution to the Run Analysis project. Specifically, you will find: * Run_Analysis.R - an R script file containing all commands used to transform the data * Codebook.md - a markdown file that lists and describes all variables contained within the final run analysis data file * This Readme.md file that describes the experiment and the steps to create a resulting tidy data file.
Java
UTF-8
6,071
2.671875
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2013 the original author or authors. * * 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.brekka.logtools.stash; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * Dispatches event messages to logstash using the specified client. Messages will be queued for sending in case * the server is temporarily unavailable. A sensible limit is set on the number of messages that can be buffered. If * that limit is exceeded, new messages will start being dropped. * * @author Andrew Taylor (andrew@brekka.org) */ class Dispatcher { private static final boolean DEBUG_ENABLED = "true".equals(System.getProperty("logtools.dispatcher.debug")); private final ExecutorService executorService; private final Client client; private final AtomicLong counter = new AtomicLong(); /** * Maximum time to block the JVM shutdown to clear events. */ private int shutdownDelaySeconds = 10; public Dispatcher(final Client client) { this(client, 1000, 4); } public Dispatcher(final Client client, final int eventBufferSize, final int priority) { this.client = client; ThreadFactory tf = new ThreadFactory() { @Override public Thread newThread(final Runnable r) { Thread t = new Thread(r, "LogStashDispatcher"); t.setDaemon(true); // Slightly below normal t.setPriority(priority); return t; } }; // Just one daemon thread. executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(eventBufferSize), tf); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { // JVM is going down, try to flush as many messages as possible. close(true); } }); } /** * Close this dispatcher without blocking. Any subsequent call to dispatchMessage will be rejected. */ public void close() { close(false); } protected void close(final boolean wait) { if (!executorService.isShutdown()) { try { executorService.submit(new Runnable() { @Override public void run() { client.close(); } }); } catch (RejectedExecutionException e){ // Leave the socket open and hope the finalizer gets it if (DEBUG_ENABLED) { System.err.printf("Dispatcher to '%s' close rejected, must already have been called.%n", client); } } executorService.shutdown(); } if (wait && !executorService.isTerminated()) { // The JVM is shutting down. We want to flush as many events as possible before giving up. try { if (executorService.awaitTermination(shutdownDelaySeconds, TimeUnit.SECONDS)) { if (DEBUG_ENABLED) { System.err.printf("Shutdown of dispatcher to '%s' failed to process all events%n", client); } } } catch (InterruptedException e) { if (DEBUG_ENABLED) { System.err.printf("Dispatcher to '%s' failed to process all events due to interruption%n", client); } } } } public void dispatchMessage(final String message) { try { executorService.submit(new Runnable() { @Override public void run() { while (true) { try { client.writeEvent(message); // Written successfully counter.incrementAndGet(); return; } catch (Exception e) { client.close(); // Make sure to have some kind of delay between attempts. There are situations // where connection failures will be very quick so this avoids thrashing try { Thread.sleep(1000); } catch (InterruptedException e1) { return; } } if (Thread.currentThread().isInterrupted()) { // Thread is interrupted. Exit now return; } } } }); } catch (RejectedExecutionException e) { if (DEBUG_ENABLED) { System.err.printf("Dispatch to '%s' failed for event %s%n", client, message); e.printStackTrace(); } } } /** * @param shutdownDelaySeconds the shutdownDelaySeconds to set */ public void setShutdownDelaySeconds(final int shutdownDelaySeconds) { if (shutdownDelaySeconds > 0) { this.shutdownDelaySeconds = shutdownDelaySeconds; } } }
Python
UTF-8
294
3
3
[]
no_license
import cv2 # 이미지 읽기 img = cv2.imread('bts.jpg', 1) print(img) print("shape:", img.shape) # 이미지 화면에 표시 cv2.imshow('Image', img) cv2.waitKey() # 이미지 윈도우 삭제 cv2.destroyAllWindows() # 이미지 다른 파일로 저장 # cv2.imwrite('test2.png', img)
C#
UTF-8
2,139
3.109375
3
[]
no_license
using CollectionViewChallenge.Models; using System.Collections.ObjectModel; namespace CollectionViewChallenge.ViewModels { public class WorldViewModel { private ObservableCollection<Country> countries; public ObservableCollection<Country> Countries { get => countries; set { countries = value; } } public WorldViewModel() { countries = new ObservableCollection<Country>() { new Country(){Name = "Pakistan", ISO="pk", Capital="Islamabad" }, new Country(){Name = "Spain", ISO="es", Capital="Madrid" }, new Country(){Name = "Afghanistan", ISO="af", Capital="Kabul" }, new Country(){Name = "Bangladesh", ISO="bd", Capital="Dhaka" }, new Country(){Name = "Austria", ISO="at", Capital="Viena" }, new Country(){Name = "Belgium", ISO="be", Capital="Brussels" }, new Country(){Name = "Germany", ISO="de", Capital="Berlin" }, new Country(){Name = "Ghana", ISO="gh", Capital="Accra" }, new Country(){Name = "Kenya", ISO="ke" , Capital="Nairobi" }, new Country(){Name = "Nigeria", ISO="bg", Capital="Abuja" }, new Country(){Name = "Mali", ISO="ml", Capital="Bamako" }, new Country(){Name = "Malaysia", ISO="my", Capital="Kuala Lumpur" }, new Country(){Name = "Egypt", ISO="eg", Capital="Cairo" }, new Country(){Name = "New Zealand", ISO="nz", Capital="Wellington" }, new Country(){Name = "Hong Kong", ISO="hk", Capital="Central" }, new Country(){Name = "China", ISO="cn", Capital="Beijing" }, new Country(){Name = "USA ", ISO="us", Capital="Washington, D.C" }, new Country(){Name = "United Kingdom", ISO="gb", Capital="London" } }; } } }
Java
UTF-8
2,304
2.859375
3
[]
no_license
package demo; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import theater.systemusers.Client; import theater.systemusers.SystemCheck; import theater.systemusers.User; import theater.Admin; import theater.Cinema; import theater.Movie; public class Demo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //creating Cinema: Cinema cinema = Cinema.getInstance(); // admin signIn with username: admin, password: admin Admin admin = Admin.getInstance(); System.out.println("Admin signIn, please enter admin username: "); String adminUsername = sc.nextLine(); System.out.println("Admin signIn, please enter admin password: "); String adminPass = sc.nextLine(); admin.signIn(adminUsername, adminPass); // Add movies in the cinema admin.addMovieToCinema(new Movie("The Avengers", "Action")); admin.addMovieToCinema(new Movie("Scary Movie", "Comedy")); admin.addMovieToCinema(new Movie("SAW", "Triller")); admin.addMovieToCinema(new Movie("Stargate", "Sci-Fi")); System.out.println("\nALL MOVIES IN: " + cinema.getName()); cinema.showAllMovies(); // set the broadcasts and print the movies for the week admin.addBroadcasts(); cinema.printBroadcasts(); System.out.println(" For the demo lets register some clients "); System.out.println(" Lets begin the registrations: "); //Make some people (10 Clients and one admin) ArrayList<Client> clients = new ArrayList(); for(int i = 1; i <= 3;i++) { Client client = new Client("Client" + i, "client" + i + "@abv.bg", "0875154510"); clients.add(client); if(client != null) { client.registration(); } } //Make reservations for(Client c : clients) { c.makeReservation(cinema, SystemCheck.getRandomNum(1, 10)); } clients.get(0).profileChanges(); clients.get(1).profileChanges(); //3 clients to cancel reservations clients.get(SystemCheck.getRandomNum(clients.size()-1)).cancelLastReservation(); clients.get(SystemCheck.getRandomNum(clients.size()-1)).cancelLastReservation(); clients.get(SystemCheck.getRandomNum(clients.size()-1)).cancelLastReservation(); admin.removeUser(clients.get(1)); cinema.showAllUsers(); } }
Java
UTF-8
641
2.578125
3
[]
no_license
package edu.chl.tda367.booleancircuits.common; import java.beans.PropertyChangeListener; /** * Interface for classes that wants to be observable by PropertyChangeListener. * * @author Kaufmann * */ public interface IObservable { /** * Adds an observer to this observable class. * * @param listener * the observer */ public void addPropertyChangeListener(PropertyChangeListener listener); /** * Removes an observer from this observable class. * * @param listener * to remove */ public void removePropertyChangeListener(PropertyChangeListener listener); }
Java
UTF-8
664
3.4375
3
[]
no_license
package encapsulation; public class EncapsulationIntro { public static void main(String[] args) { Laptop lap = new Laptop(); lap.setPrice(10); lap.setRam(20); System.out.println(lap.getRam()); } public void doWork() { System.out.println("i am working"); } } class Laptop{ private int ram; private int price; public void setRam(int ram) { this.ram = ram; } public int getRam() { return ram; } public int getPrice() { return price; } public void setPrice(int price) { boolean isAdmin = true; if(!isAdmin) { System.out.println("you cannot change price"); }else { this.price = price; System.out.println(price); } } }
Java
UTF-8
511
1.789063
2
[]
no_license
package com.huatu.tiku.match.service.v1.report; import com.huatu.ztk.commons.exception.BizException; /** * 描述:我的报告接口 * * @author biguodong * Create time 2018-12-27 下午5:36 **/ public interface ReportService { /** * 查询模考大赛报告列表 * * @param userId * @param tagId * @param subject * @return * @throws BizException */ Object myReportList(int userId, int tagId, int subject,String cv,int terminal) throws BizException; }
Markdown
UTF-8
2,641
2.890625
3
[ "MIT" ]
permissive
--- layout: post title: "Labelled network subgraphs reveal stylistic subtleties in written texts" date: 2017-11-08 02:16:49 categories: arXiv_CL tags: arXiv_CL Relation author: Vanessa Q. Marinho, Graeme Hirst, Diego R. Amancio mathjax: true --- * content {:toc} ##### Abstract The vast amount of data and increase of computational capacity have allowed the analysis of texts from several perspectives, including the representation of texts as complex networks. Nodes of the network represent the words, and edges represent some relationship, usually word co-occurrence. Even though networked representations have been applied to study some tasks, such approaches are not usually combined with traditional models relying upon statistical paradigms. Because networked models are able to grasp textual patterns, we devised a hybrid classifier, called labelled subgraphs, that combines the frequency of common words with small structures found in the topology of the network, known as motifs. Our approach is illustrated in two contexts, authorship attribution and translationese identification. In the former, a set of novels written by different authors is analyzed. To identify translationese, texts from the Canadian Hansard and the European parliament were classified as to original and translated instances. Our results suggest that labelled subgraphs are able to represent texts and it should be further explored in other tasks, such as the analysis of text complexity, language proficiency, and machine translation. ##### Abstract (translated by Google) 大量数据和计算能力的增加使得从多个角度分析文本,包括将文本表示成复杂的网络。网络的节点代表单词,边代表一些关系,通常是单词同现。尽管网络化表征已被用于研究某些任务,但这种方法通常不会与依赖于统计范式的传统模型相结合。由于网络模型能够掌握文本模式,我们设计了一个称为标记子图的混合分类器,它将常见词的频率与在网络拓扑中发现的小型结构(称为基元)相结合。我们的方法在两种情况下进行说明,即作者归属和翻译识别。前者分析了不同作者写的一套小说。为了识别翻译文本,加拿大国会议事录和欧洲议会的文本被归类为原始和翻译的实例。我们的研究结果表明,有标签的子图能够代表文本,还应该在其他任务中进一步探索,如分析文本复杂性,语言熟练程度和机器翻译。 ##### URL [https://arxiv.org/abs/1705.00545](https://arxiv.org/abs/1705.00545) ##### PDF [https://arxiv.org/pdf/1705.00545](https://arxiv.org/pdf/1705.00545)
Java
UTF-8
2,274
2.125
2
[ "MIT" ]
permissive
package br.uff.ic.gems.peixeespadacliente.symptom; import br.uff.ic.gems.peixeespadacliente.exception.RefactoringException; import java.util.List; import br.uff.ic.gems.peixeespadacliente.model.agent.LocalManagerAgent; import br.uff.ic.gems.peixeespadacliente.resolution.ExtractInterfaceResolution; import br.uff.ic.gems.peixeespadacliente.tool.ExtractInterfaces; import br.uff.ic.gems.peixeespadacliente.tool.RefactoringTool; import java.util.ArrayList; import java.util.Arrays; import net.sf.refactorit.classmodel.BinCIType; /** * * @author João Felipe */ public class ExtractInterfaceSymptom extends Symptom { private String classQualifiedName; private String className; public ExtractInterfaceSymptom(BinCIType cls, ExtractInterfaces refactoringTool) { super(refactoringTool); classQualifiedName = cls.getQualifiedName(); if (refactoringTool.getProject().getTypeRefForSourceName(classQualifiedName) == null) { classQualifiedName = cls.getParentType().getQualifiedName() + "." + cls.getName(); } className = cls.getName(); } @Override public RefactoringTool getRefactoringTool() { return this.refactoringTool; } public ExtractInterfaces getExtractInterfacesRefactoringTool() { return (ExtractInterfaces) this.refactoringTool; } @Override public List<ExtractInterfaceResolution> generateResolutions(LocalManagerAgent agentPeixeEspada, boolean verify) throws RefactoringException { List<ExtractInterfaceResolution> result = new ArrayList(Arrays.asList(new ExtractInterfaceResolution(this, className))); if (verify && !result.get(0).applyWorking(null)){ return new ArrayList<ExtractInterfaceResolution>(); } return result; } @Override public String toString() { return "Extract " + getInterfaceName() + " from " + getClassQualifiedName(); } public String getClassQualifiedName() { return classQualifiedName; } public String getInterfaceName() { return className+"Interface"; } public String getClassName() { return className; } @Override public String getDescription() { return " " + this.toString(); } }
Java
UTF-8
152
2.171875
2
[]
no_license
public class ProjectBWorkerV1 { public void run(){ new ProjectAWorkerV1().run(); System.out.println("project b worker v1"); } }
Swift
UTF-8
1,973
3.125
3
[]
no_license
// // CardView.swift // Memorize // // Created by Martin Dimitrov on 19.11.20. // import SwiftUI struct CardView: View { //MARK: - Constants private enum Constants { static let cornerRadius:CGFloat = 10.0 static let fontSizeMultiplier: CGFloat = 0.75 static let strokeWidth: CGFloat = 3.0 } private let card: MemoryGame<String>.Card private let theme: Theme init(card: MemoryGame<String>.Card, theme: Theme) { self.card = card self.theme = theme } var body: some View { GeometryReader { geometry in ZStack { PieChartView(startAngle: Angle.degrees(0 - 90), endAngle: Angle.degrees(110 - 90), clockwise: true) .foregroundColor(theme.cardBackColor) .padding(15) .opacity(0.4) Text("\(card.content)") // if card.isFaceUp { // RoundedRectangle(cornerRadius: Constants.cornerRadius).fill(Color.white) // RoundedRectangle(cornerRadius: Constants.cornerRadius) // .strokeBorder(theme.cardBackColor, lineWidth: 5) // } else { // if !card.isMatched { // RoundedRectangle(cornerRadius: Constants.cornerRadius).fill(theme.cardBackColor) // } // } } .font(Font.system(size: getFontSize(for: min(geometry.size.width, geometry.size.height)))) } } private func getFontSize(for size: CGFloat) -> CGFloat { return size * Constants.fontSizeMultiplier } } struct CardView_Previews: PreviewProvider { private static var card: MemoryGame<String>.Card = MemoryGame<String>.Card(id: 0, content: "😕") static var previews: some View { card.isFaceUp = true return CardView(card: card, theme: .halloween) } }
Python
UTF-8
608
2.546875
3
[]
no_license
import tkinter, os from tkinter.messagebox import askokcancel, showinfo # import TestDire import windnd def drag_files(urls): print(b'\n'.join(urls).decode()) showinfo('确认路径', b'\n'.join(urls).decode()) if __name__ == '__main__': top = tkinter.Tk() top.title('测试工具') # top.geometry("350x200") ent = tkinter.Entry(top, width=100).grid(row=0) label = tkinter.Label(top, text='请拖拽文件夹至软件内上传', font=15, width=80, height=40) label.grid(row=1) # windnd.hook_dropfiles(top, func=drag_files) # 进入消息循环 top.mainloop()
C#
UTF-8
985
2.53125
3
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
using BrightIdeasSoftware; namespace FreyrViewer.Ui.Grids { internal class FormatRowArgs { public FormatRowArgs( OLVListItem item, int rowIndex, int displayIndex, bool useCellFormatEvents) { Item = item; RowIndex = rowIndex; DisplayIndex = displayIndex; UseCellFormatEvents = useCellFormatEvents; } /// <summary> /// Gets the item of the cell /// </summary> public OLVListItem Item { get; } /// <summary> /// Gets the row index of the cell /// </summary> public int RowIndex { get; } /// <summary> /// Gets the display index of the row /// </summary> public int DisplayIndex { get; } /// <summary> /// Should events be triggered for each cell in this row? /// </summary> public bool UseCellFormatEvents { get; set; } } }
Java
UTF-8
162
2.078125
2
[]
no_license
package pieces; public class Lieutenant extends AbstractMovable implements Movable { public Lieutenant(Team team){ super(team,5,"./images/5.png"); } }
Python
UTF-8
1,391
3.765625
4
[]
no_license
class HotBeverages: def __init__(self): self.price = 0.30 self.name = "hot beverage" def description(self): return "Just some hot water in a cup." def __str__(self): des = self.description() n = self.name p = '%.2f' % self.price s = "name : " + n + "\nprice : " + p + "\ndescription : " + des return s class Coffee(HotBeverages): def __init__(self): super().__init__() self.name = "coffee" self.price = 0.40 def description(self): return "A coffee, to stay awake." class Tea(HotBeverages): def __init__(self): super().__init__() self.name = "tea" class Chocolate(HotBeverages): def __init__(self): super().__init__() self.name = "chocolate" self.price = 0.50 def description(self): return "Chocolate, sweet chocolate..." class Cappuccino(HotBeverages): def __init__(self): super().__init__() self.name = "cappuccino" self.price = 0.45 def description(self): return "Un po' di Italia nella sua tazza!" if __name__ == '__main__': hot = HotBeverages() print(hot.__str__()) coffee = Coffee() print(coffee.__str__()) tea = Tea() print(tea.__str__()) choco = Chocolate() print(choco.__str__()) capu = Cappuccino() print(capu.__str__())
PHP
UTF-8
6,562
2.546875
3
[]
no_license
<?php /** * @package modules\roles * @subpackage roles * @category Xaraya Web Applications Framework * @version 2.4.0 * @copyright see the html/credits.html file in this release * @license GPL {@link http://www.gnu.org/licenses/gpl.html} * @link http://xaraya.info/index.php/release/27.html */ /** * Search * * @author Marc Lutolf <marcinmilan@xaraya.com> * @return array|void data for the template display */ function roles_user_search() { if (!xarVar::fetch('startnum', 'isset', $startnum, NULL, xarVar::DONT_SET)) {return;} if (!xarVar::fetch('email', 'isset', $email, NULL, xarVar::DONT_SET)) {return;} if (!xarVar::fetch('uname', 'isset', $uname, NULL, xarVar::DONT_SET)) {return;} if (!xarVar::fetch('name', 'isset', $name, NULL, xarVar::DONT_SET)) {return;} if (!xarVar::fetch('q', 'isset', $q, NULL, xarVar::DONT_SET)) {return;} if (!xarVar::fetch('bool', 'isset', $bool, NULL, xarVar::DONT_SET)) {return;} if (!xarVar::fetch('sort', 'isset', $sort, NULL, xarVar::DONT_SET)) {return;} if (!xarVar::fetch('author', 'isset', $author, NULL, xarVar::DONT_SET)) {return;} $data = array(); $data['users'] = array(); // show the search form if (!isset($q)) { if (xarModHooks::isHooked('dynamicdata','roles')) { // get the DataObject defined for this module /** @var DataObject $object */ $object = xarMod::apiFunc('dynamicdata','user','getobject', array('module' => 'roles')); if (isset($object) && !empty($object->objectid)) { // get the Dynamic Properties of this object $data['properties'] =& $object->getProperties(); } } return $data; } // execute the search // Default parameters if (!isset($startnum)) { $startnum = 1; } if (!isset($numitems)) { $numitems = 20; } // Need the database connection for quoting strings. $dbconn = xarDB::getConn(); // TODO: support wild cards / boolean / quotes / ... (cfr. articles) ? // remember what we selected before $data['checked'] = array(); if (xarModHooks::isHooked('dynamicdata','roles')) { // make sure the DD classes are loaded if (!xarMod::apiLoad('dynamicdata','user')) return $data; // @todo load the right object for roles here // get a new object list for roles $descriptor = new DataObjectDescriptor(array('moduleid' => xarMod::getRegID('roles'))); $object = new DataObjectList($descriptor); if (isset($object) && !empty($object->objectid)) { // save the properties for the search form $data['properties'] =& $object->getProperties(); // quote the search string (in different variations here) $quotedlike = $dbconn->qstr('%'.$q.'%'); $quotedupper = $dbconn->qstr('%'.strtoupper($q).'%'); $quotedlower = $dbconn->qstr('%'.strtolower($q).'%'); $quotedfirst = $dbconn->qstr('%'.ucfirst($q).'%'); $quotedwords = $dbconn->qstr('%'.ucwords($q).'%'); // run the search query $where = array(); // see which properties we're supposed to search in foreach (array_keys($object->properties) as $field) { if (!xarVar::fetch($field, 'checkbox', $checkfield, NULL, xarVar::NOT_REQUIRED)) {return;} if ($checkfield) { $where[] = $field . " LIKE " . $quotedlike; $where[] = $field . " LIKE " . $quotedupper; $where[] = $field . " LIKE " . $quotedlower; $where[] = $field . " LIKE " . $quotedfirst; $where[] = $field . " LIKE " . $quotedwords; // remember what we selected before $data['checked'][$field] = 1; } // reset the checkfield value $checkfield = NULL; } if (count($where) > 0) { // TODO: refresh fieldlist of datastore(s) before getting items $items =& $object->getItems(array('where' => join(' or ', $where))); if (isset($items) && count($items) > 0) { // TODO: combine retrieval of roles info above foreach (array_keys($items) as $id) { if (isset($data['users'][$id])) { continue; } // Get user information $data['users'][$id] = xarMod::apiFunc('roles', 'user', 'get', array('id' => $id)); } } } } } // quote the search string $quotedlike = $dbconn->qstr('%'.$q.'%'); $selection = " AND ("; $selection .= "(name LIKE " . $quotedlike . ")"; $selection .= " OR (uname LIKE " . $quotedlike . ")"; if (xarModVars::get('roles', 'searchbyemail')) { $selection .= " OR (email LIKE " . $quotedlike . ")"; } $selection .= ")"; $data['total'] = xarMod::apiFunc('roles', 'user', 'countall', array('selection' => $selection, 'include_anonymous' => false)); if (!$data['total']){ if (count($data['users']) == 0){ $data['status'] = xarML('No Users Found Matching Search Criteria'); } $data['total'] = count($data['users']); return $data; } $users = xarMod::apiFunc('roles', 'user', 'getall', array('startnum' => $startnum, 'selection' => $selection, 'include_anonymous' => false, 'numitems' => (int)xarModVars::get('roles', 'items_per_page'))); // combine search results with DD if (!empty($users) && count($data['users']) > 0) { foreach ($users as $user) { $id = $user['id']; if (isset($data['users'][$id])) { continue; } $data['users'][$id] = $user; } } else { $data['users'] = $users; } if (count($data['users']) == 0){ $data['status'] = xarML('No Users Found Matching Search Criteria'); } return $data; }
Java
UTF-8
479
2.765625
3
[]
no_license
public class Director { private DressBuilder dbuilder; public DressList Construct(DressBuilder dressBuilder , int type , int wallet , int watch) { dbuilder = dressBuilder; if(type == 1 || type == 2) { dbuilder.addDress(type); } else { System.out.println("Invalid Type"); } dbuilder.addWallet(wallet); dbuilder.addSmartWatch(watch); return dbuilder.getDress(); } }
C++
UTF-8
1,545
3.9375
4
[]
no_license
#include <iostream> #include <forward_list> /* * NOTE: This solution fails to imagine the possibility that the heads * of two linked lists merge into single linked list. This isn't possible * with forward_lists, but is possible with a more basic linked list. * */ using namespace std; /* * Runs O(n) * */ bool intersect( forward_list<int>::const_iterator node1, const forward_list<int>::const_iterator end1, forward_list<int>::const_iterator node2, const forward_list<int>::const_iterator end2) { auto node1_copy = node1; while (node1_copy != end1) { if (node1_copy == node2) { return true; } node1_copy++; } auto node2_copy = node2; while (node2_copy != end2) { if (node1 == node2_copy) { return true; } node2_copy++; } return false; } int main() { forward_list<int> list1 {1, 2, 3, 4}; forward_list<int> list2 {1, 2, 3, 4}; cout << "Test 1: " << intersect(list1.begin(), list1.end(), list1.begin(), list1.end()) << endl; cout << "Test 2: " << intersect(list1.begin(), list1.end(), list2.begin(), list2.end()) << endl; cout << "Test 3: " << intersect( list1.begin(), list1.end(), next(list1.begin(), 2), list1.end()) << endl; cout << "Test 3: " << intersect( next(list1.begin(), 1), list1.end(), next(list1.begin(), 2), list1.end()) << endl; }
Markdown
UTF-8
39,913
3.046875
3
[]
no_license
# Spring注解驱动开发 ### Configuration ```java //表名这是一个配置类 @Configuration ``` ###Bean ```java /** * 方法名可以作为bean的id 也可以使用 @Bean的value属性 * @return */ @Bean public Person person(){ return new Person(1,"卡卡西"); } ``` ###CompontScan ```java //bean扫描注解 @ComponentScan( value = "com.able.springannocation", //指定扫描的时候按照什么规则排除那些组件 // excludeFilters = { // @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, Service.class}) // }, //指定扫描的时候只包含那些组件 注意 useDefaultFilters要设置为false includeFilters = { // @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class}), @ComponentScan.Filter(type = FilterType.CUSTOM,classes = {MyTypeFilter.class}) },useDefaultFilters = false ) ``` java8中可以重复标注 @ComponentScan 低于jdk8可以使用 @ComponentScans注解 里面包含@ComponentScan数组 FilterType ```java public enum FilterType { /** 按照注解 * Filter candidates marked with a given annotation. * @see org.springframework.core.type.filter.AnnotationTypeFilter */ ANNOTATION, /**按照给定的类型 * Filter candidates assignable to a given type. * @see org.springframework.core.type.filter.AssignableTypeFilter */ ASSIGNABLE_TYPE, /**使用 ASPECTJ * Filter candidates matching a given AspectJ type pattern expression. * @see org.springframework.core.type.filter.AspectJTypeFilter */ ASPECTJ, /**使用正则表达式 * Filter candidates matching a given regex pattern. * @see org.springframework.core.type.filter.RegexPatternTypeFilter */ REGEX, /**使用自定义规则 Filter candidates using a given custom * {@link org.springframework.core.type.filter.TypeFilter} implementation. */ CUSTOM } ``` 自定义过滤规则实现类 ```java public class MyTypeFilter implements TypeFilter { /** * * @param metadataReader 读取到当前正在扫描的类的信息 * @param metadataReaderFactory 可以获取到其他任何类信息的 * @return * @throws IOException */ @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { //获取正在扫描类的注解信息 AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); //获取正在扫描类的类信息 ClassMetadata classMetadata = metadataReader.getClassMetadata(); //获取正在扫描类的资源(类的路径。。。) Resource resource = metadataReader.getResource(); String className = classMetadata.getClassName(); System.out.println("className="+ className); if (className.contains("er")) { return true; } return false; } } ``` ### Scope ```java /** * Specifies the name of the scope to use for the annotated component/bean. * <p>Defaults to an empty string ({@code ""}) which implies * {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}. * @since 4.2 * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE 多实例 调用的时候创建对象 获取几次调用几次 * @see ConfigurableBeanFactory#SCOPE_SINGLETON 单实例 ioc容器启动启动的时候会创建对象并把对象放到容器中去 * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST 同一次请求创建一个实例 * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION 同一个session创建一个实例 * @see #value */ ``` ### Lazy ```java 懒加载 /** * 方法名可以作为bean的id 也可以使用 @Bean的value属性 * @return */ @Bean @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Lazy public Person person(){ return new Person(1,"卡卡西"); } ``` ###Conditional 按照一定的条件判断 进行判断 满足条件给容器中注册bean 可以放在类上 放在类上 只有满足条件 类中的组件才会注册 也可以放在方法上 ```java @Bean("bill") @Conditional(WindowsCondition.class) public Person person1(){ return new Person(2,"Bill Gates"); } @Bean("linus") @Conditional(LinuxCondition.class) public Person person2(){ return new Person(3,"linus"); } public class LinuxCondition implements Condition { /** * * @param context 判断条件上下文环境 * @param metadata 注解信息 * @return */ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { //获取当前的系统环境 Environment environment = context.getEnvironment(); String property = environment.getProperty("os.name"); System.out.println("LinuxCondition="+property); //获取beanRegistry bean定义的注册类 可以判断容器中bean的注册情况 也可以给容器中注册bean BeanDefinitionRegistry registry = context.getRegistry(); //获取BeanFactory ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); //获取类加载器 ClassLoader classLoader = context.getClassLoader(); if (property.contains("lin")) { return true; } return false; } } public class WindowsCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String property = context.getEnvironment().getProperty("os.name"); System.out.println("WindowsCondition="+property); if (property.toLowerCase().contains("win")) { return true; } return false; } } ``` ###Import 给容器中注册组件: 1. 包扫描+组件标注注解(@Controller @Service @Repository @Component (通常自己写的组件) 2. @Bean【导入第三方包里的组件】 3. @Import [快速给容器中导入组件] 1. @import(要导入到容器中的组件):容器中就会自动注册这个组件 id默认是全类名 2. ImportSelector:返回需要导入的组件全类名数组 3. ImportBeanDefinitionRegistrar:手工注册bean到容器中 2. 使用Spring提供的FactoryBean 1. 默认获取到的工厂bean调用getObject创建对象 2. 要获取工厂Bean本身 我们需要给id前面添加一个& ​```java //@Import导入组件 id默认是组件的全类名 @Import({Color.class, Red.class, MyImportSelector.class}) ​``` ​```java public class MyImportSelector implements ImportSelector { /** * * @param importingClassMetadata 当前标注@Import注解的类的所有注解信息 * @return */ @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[]{Green.class.getName(), Bule.class.getName()}; } } ​``` ​```java @Slf4j public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { /** * * @param importingClassMetadata 当前类的注解信息 * @param registry bean定义的注册类 */ @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { RootBeanDefinition beanDefinition=new RootBeanDefinition(RainBow.class); MutablePropertyValues propertyValues=new MutablePropertyValues(); propertyValues.add("number",88); beanDefinition.setPropertyValues(propertyValues); registry.registerBeanDefinition("rainBow",beanDefinition); } } ​``` ### ```java * bean的生命周期: * bean创建--初始化--消耗过程 * 容器管理bean的生命周期: * 我们可以自定义初始化和消耗方法:容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法 * 1 指定初始化和销毁的方法: * 指定 init-method 和destory-method * 2 bean实现 InitializingBean DisposableBean 接口 * 3 可以使用Jsr250的注解 PostConstruct PreDestroy * 4 BeanPostProcessor:bean的后置处理器 * 构造:创建对象 * 单实例:在容器启动的时候创建对象 * 多实例:在每次获取的时候创建对象 * BeanPostProcessor.postProcessBeforeInitialization * 初始化: * 对象完成 并赋值好 调用初始化方 * BeanPostProcessor.postProcessAfterInitialization * 销毁: * 单实例:容器关闭的时候 * 多实例:容器不会管理这个bean 不会调用销毁方法 ``` ```java public class Car implements InitializingBean, DisposableBean { public Car() { System.out.println("car================constructor"); } //对象创建并赋值之后调用 @PostConstruct public void postConstrctor(){ System.out.println("car========postConstructor========"); } @PreDestroy public void preDestory(){ System.out.println("car======preDestory========"); } public void init(){ System.out.println("car===================init======="); } public void destory(){ System.out.println("car====================destory"); } @Override public void destroy() throws Exception { System.out.println("car====================destroy"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("car=================afterPropertiesSet"); } } @Configuration @ComponentScan(basePackages = { "com.able.springannocation.processor" }) public class BeanCycleConfig { @Bean(initMethod ="init",destroyMethod = "destory") public Car car(){ return new Car(); } } @Component public class MyBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println(beanName+"================postProcessBeforeInitialization"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println(beanName+"================postProcessAfterInitialization"); return bean; } } ``` ### Value ​ propertySource ​ propertySources ```java @Configuration @PropertySource({ "classpath:application.properties" }) public class PropertyConfig { @Bean public Person person(){ return new Person(); } } @Data public class Person { /** * 使用@Value 赋值 * 1 基本数值 * 2 可以使用Spel:#{} * 3 可以使用${},使用配置文件中的值 * */ @Value("#{20-2}") private Integer id; /** * */ @Value("张三") private String name; @Value("${nike.name}") private String nikeName; public Person() { } public Person(Integer id, String name) { this.id = id; this.name = name; //System.out.println("person创建"); } } ``` ### 自动注入 ```java /* * spring利用DI 完成对IOC容器中的各个组件的依赖关系赋值 * 1 @Autowired * 1 默认按照类型取容器中找对应的组件 * 2 如果找到多个相同的组件 在将属性的名称作为组件的id去容器中查找 * 3 使用@Qualifier()指定要装配的组件id 而不是使用属性名 * 4 自动装配 默认一定要将属性赋值好 没有则会报错 * 可以使用 @Autowired(required=false) 来装配 有就装配 没有也不报错 * 5 @Primary :让Spring进行装配的时候默认使用首选的bean * 也可以继续使用@Qualifier 指定需要装配的bean的名字 * * 2 @Resource(Jsr250) [java规范注解] * 可以和@Autowired一样事项自动装配功能 默认是按照组件名称进行装配的 * 没有能支持@Primary功能 * 没有能支持@Autowired(required=false)的功能 * @Resource(name="xxx") * 3 @Inject(Jsr 330) [java规范注解] * 需要导入javax.inject的包 和autowired功能一样 不同的是不支持required属性 **/ ``` ```java *@Autowired : * 标注在方法上 * 标注在构造器上:如果组件只有一个有参构造器 @Autowired可以省略 * 标注在参数上 @Component public class Boss { Car car; @Autowired public Boss(@Autowired Car car) { this.car = car; } public Car getCar() { return car; } @Autowired public void setCar(Car car) { this.car = car; } @Override public String toString() { return "Boss{" + "car=" + car + '}'; } } ``` 自定义组件 想要使用Spring容器底层的一些组件(ApplicationContext BeanFactory xxx) ​ 自定义组件实现xxxAware: 在创建对象的时候 会调用接口规定的方法注入相关组件:Aware ​ 把Spring底层的一些组件注入到自定义组件中 ​ xxxAware:功能使用xxxProcessor ​ applicationConextAware===>ApplicationContextAwareProcessor ### Profile Spring为我们提供可以根据当前环境 动态激活和切换一些列组件的功能: 指定组件在哪个环境的情况下才能被注册到容器中 不指定 任何环境都能注册到这个组件 加了环境标识的bean 只有这个环境被激活的时候才能注册到容器中 默认是default 写在配置类上 只有指定环境的时候 整个配置类里面的所有配置才能开始生效 @Profile("dev") @Profile("prod") ```java @Configuration public class ProfileConfig { @Bean @Profile("default") public Car car(){ return new Car(); } @Bean @Profile("dev") public Bule bule(){ return new Bule(); } } ``` 使用命令行动态参数: -Dspring.profiles.active=dev 使用代码 ```java @Before public void init(){ // applicationContext=new AnnotationConfigApplicationContext(ProfileConfig.class); //创建 applicationContext applicationContext=new AnnotationConfigApplicationContext(); //设置需要激活的环境 applicationContext.getEnvironment().setActiveProfiles("dev"); //注册主配置类 applicationContext.register(ProfileConfig.class); //刷新启动容器 applicationContext.refresh(); } ``` ### AOP ​ 动态代理 指在程序运行期间动态的将某段代码切入到指定方法的指定位置进行运行的编程方式 ​ 1.导入aop模块:spring-aop:(spring-aspect) ​ 2.定义一个业务逻辑类(MatchCalculaotr):在业务逻辑运行的时候将日志进行打印(方法之前 方法运行结束 方法出现异常) ```java public class MathCalculator { } ``` ​ 3 定义一个日志切面类 切面里的方法需要动态感知业务运行到哪里 然后执行 ​ 通知方法: >前置通知:@Before 目标方法运行之前执行 > >后置通知:@After 目标方法运行之后运行 > >返回通知:@AfterRetuining 目标方法正常返回之后运行 > >异常通知:@AfterThrowing在目标方法运行异常之后运行 > >环绕通知:@Around 动态代理,手动推进目标方法运行(joinPoint.process()) 4 给切面类的目标方法标注何时何地运行(通知注解) ```java @Aspect public class LogAspects { /** * 抽取公共切入点表达式 * 1 本类引用:只要方法名 * 2 其他切面引用:需要指定全类名 */ @Pointcut("execution(* com.able.springannocation.aop.*.*(..))") public void pointCut(){ } @Before("pointCut()") public void logStart(){ } @After("pointCut()") public void logEnd(){ } @AfterReturning("pointCut()") public void logReturn(){ } @AfterThrowing("pointCut()") public void logException(){ } } ``` 5 将切面类和业务逻辑类(目标方法所在类)都加入到容器中 ```java @Configuration public class AOPConfig { @Bean public MathCalculator mathCalculator(){ return new MathCalculator(); } @Bean public LogAspects logAspects(){ return new LogAspects(); } } ``` 6 告诉Spring那个是切面类: ```java @Aspect public class LogAspects { } ``` 7 给配置类中加 @EnableAspectJAutoProxy 开启基于注解的aop模式 ```java //开启切面功能 @EnableAspectJAutoProxy @Configuration public class AOPConfig { @Bean public MathCalculator mathCalculator(){ return new MathCalculator(); } @Bean public LogAspects logAspects(){ return new LogAspects(); } } ``` ```java @Aspect @Slf4j public class LogAspects { /** * 抽取公共切入点表达式 * 1 本类引用:只要方法名 * 2 其他切面引用:需要指定全类名 */ @Pointcut("execution(* com.able.springannocation.aop.*.*(..))") public void pointCut(){ } @Before("pointCut()") public void logStart(JoinPoint joinPoint){ String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName(); String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); log.info("logStart=================,类名为:{}方法名为:{},参数为:{}",declaringTypeName,methodName, Arrays.asList(args)); } @After("pointCut()") public void logAfter(JoinPoint joinPoint){ log.info("logAfter================="); } @AfterReturning(value = "pointCut()",returning = "result") public void logReturn(Object result){ log.info("接收到的返回值为:{}",result); log.info("logReturn======================="); } //JoinPoint 一定要出现在参数表的第一位 @AfterThrowing(value = "pointCut()",throwing = "exception") public void logException(JoinPoint joinPoint,Exception exception){ log.info("exception=",exception); log.info("logException==================================="); } } ``` 三步: ​ 将业务逻辑与切面类都加入到容器中:告诉Spring 哪个是切面类(@Aspect) ​ 在切面类上的每一个通知方法上标注通知注解 告诉Spring何时何地运行(切入点表达式) ​ 开启基于注解的apo模式 ​ ### AOP原理 【看给容器中注册了什么组件 这个组件什么时候工作 组件的功能是什么 】 @EnableAspectJAutoProxy: ```java @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(AspectJAutoProxyRegistrar.class) public @interface EnableAspectJAutoProxy { /** * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed * to standard Java interface-based proxies. The default is {@code false}. */ boolean proxyTargetClass() default false; /** * Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal} * for retrieval via the {@link org.springframework.aop.framework.AopContext} class. * Off by default, i.e. no guarantees that {@code AopContext} access will work. * @since 4.3.1 */ boolean exposeProxy() default false; } ``` ​ 通过注解EnableAspectJAutoProxy 给容器中导入AspectJAutoProxyRegistrar这个组件 利用 AspectJAutoProxyRegistrar自定义给容器中注册bean ​ org.springframework.aop.config.internalAutoProxyCreator :org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator ```java @Nullable private static BeanDefinition registerOrEscalateApcAsRequired( Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); if (!cls.getName().equals(apcDefinition.getBeanClassName())) { int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName()); int requiredPriority = findPriorityForClass(cls); if (currentPriority < requiredPriority) { apcDefinition.setBeanClassName(cls.getName()); } } return null; } RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); beanDefinition.setSource(source); beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition); return beanDefinition; } ``` ```java AnnotationAwareAspectJAutoProxyCreator ->AspectJAwareAdvisorAutoProxyCreator ->AbstractAdvisorAutoProxyCreator ->AbstractAutoProxyCreator implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware 关注后置处理器(在bean初始化完成前后做的事情) 自动注入beanFactory AbstractAutoProxyCreator.setBeanFactory AbstractAutoProxyCreator.有后置处理器的逻辑 AbstractAdvisorAutoProxyCreator.setBeanFactory-->initBeanFactory AnnotationAwareAspectJAutoProxyCreator.initBeanFactory ``` 流程: ​ 1 传入配置类 创建IOC容器 ​ 2 注册配置类 调用refresh()刷新容器 ​ 3 registerBeanPostProcessors(beanFactory) 注册bean 的后置处理器来方便拦截bean的创建 ​ 1 先获取ioc容器中已经定义了的需要创建对象的所有BeanPostProcessor ​ 2 给容器中添加别的BeanPostProcessor ​ 3 优先注册实现了 PriorityOrdered接口的BeanPostProcessor ​ 4 再给容器中注册实现了Ordered接口的BeanPostProcessor ​ 5 注册没有实现上面两个接口BeanPostProcesor ​ 6 注册BeanPostProcessor 实际上就是创建BeanPostProcessor对象 保存在容器中 ​ 1 创建bean实例 ​ 2 populateBean(beanName, mbd, instanceWrapper);给bean的属性赋值 ​ 3 initializeBean 初始化bean : ​ 1.invokeAwareMethods:处理Aware接口的回调 ​ 2 applyBeanPostProcessorsBeforeInitialization:应用后置处理器的postProcessBeforeInitialization方法 ​ 3invokeInitMethods :执行初始化方法 ​ 4 applyBeanPostProcessorsAfterInitialization():执行后置处理器的postProcessAfterInitialization方法 ​ 4 this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory); ​ this.aspectJAdvisorsBuilder = new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory); ​ 7 把BeanPostProcessor 注册到BeanFactory中 ​ 4 finishBeanFactoryInitialization(beanFactory) 完成benaFactory初始化工作 完成剩下的单实例bean ​ 1 遍历容器中所有的bean 依次创建对象:getBean(beanName) ​ getBean-->doGetBean-->getSingleton ​ 2 创建Bean ​ AnnotationAwareAspectJAutoProxyCreator在所有bean创建之前会有一个拦截:InstantiationAwareBeanPostProcessor ​ 1 先从缓存中获取当前bean 如果能获取到 说明bean之前被创建过 直接使用 否则再创建 只要创建好的bean都会被缓存起来 ​ 2 createBean 创建bean ​ BeanPostProcessor是bean对象创建完成初始化前后调用的 ​ InstantiationAwareBeanPostProcessor 是在创建bean实例之前先尝试用后置处理器返回对象的 ​ 1.resolveBeforeInstantiation //希望后置处理器在此能返回一个代理对象 如果能返回对象就使用 如果不能就继续。 ​ bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); ​ bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); ​ Object beanInstance = doCreateBean(beanName, mbdToUse, args);真正去创建一个bean实例 AnnotationAwareAspectJAutoProxyCreator的【InstantiationAwareBeanPostProcessor 】作用 ​ 1 每个bean创建之前 调用postProcessBeforeInstantiation(): ​ 关心MathCalculator 和LogAspect的创建 ​ 1 判断当前bean是否在adviseBeans中(保存了所有需要增强bean) ​ 2 判断当前bean是否是基础类型: ​ boolean retVal = Advice Pointcut Advisor AopInfrastructureBean ​ 或者是否是切面(Aspect) ​ 3 是否需要跳过 ​ 获取候选的增强器(切面里的通知方法) List<Advisor> candidateAdvisors ​ I。每一个封装的通知方法的增强器为:InstantiationModelAwarePointcutAdvisor ​ 判断每个增强器的类型是否为AspectJPointcutAdvisor 返回true ​ 2 。永远返回false ​ 创建对象 ​ postProcessAfterInitialization ​ return wrapIfNecessary(bean, beanName, cacheKey); ​ 1 获取当前bean的所有增强器 :Object[] specificInterceptors ​ 1 获取当前bean 的所有增强器(通知方法) ​ 2 找到能在当前bean使用的增强器(找到那些通知方法是需要切入当前bean方法的) ​ 3 给增强器排序 ​ 2 保存当前bean 在advisedBeans 中 ​ 3.Object proxy = createProxy( bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); 为当前bean的代理对象 ​ 1 获取所有增强器(通知方法) ​ 2 保存到proxyFactory ​ 3 创建代理对象 ​ JdkDynamicAopProxy jdk的动态代理 ​ ObjenesisCglibAopProxy cglib动态代理 ​ 4 给容器中返回当前组件使用cglib增强了的代理对象 ​ 5 以后容器获取到的就是这个组件的代理对象 代理对象就会执行通知方法的流程 ``` * BeanPostProcessor:bean的后置处理器 bean 创建对象初始化前后进行拦截工作的 * BeanFactoryPostProcessor:beanFactory的后置处理器 : * 在beanFactory标准初始化之后调用 * 所有的bean定义已经保存加载到beanFactory中 但是bean的实例还未创建 * 流程: * IOC容器创建 * 执行invokeBeanFactoryPostProcessors * 如何知道所有的BeanFactoryPostProcessor并执行他们的方法: * 1.String[] postProcessorNames = * beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); * 直接在beanFactory中找到所有的类型为 BeanFactoryPostProcessor的组件 并执行他们的方法 * 2 在初始创建其他组件前面执行 *BeanDefinitionRegistryPostProcessor:bean定义注册后置处理器 * BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor * 在所有的bean定义信息将要被加载 bean实例还没有创建 可以利用他给容器中额外添加组件 * 优先于BeanFactoryPostProcessor 的执行 * 流程 : * IOC容器创建 * refresh();方法调用 * invokeBeanFactoryPostProcessors(beanFactory);的方法调用 * postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); * 从容器中获取BeanDefinitionRegistryPostProcessor类型的所有组件 * 1 依次循环触发BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry的方法 * 2 在来循环触发BeanFactoryPostProcessor的postProcessBeanFactory方法 * * 在从文档中找到 BeanFactoryPostProcessor * String[] postProcessorNames = * beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); * 然后触发 postProcessBeanFactory方法 * * * * ApplicationListener:监听容器中法的时间。事件驱动模型开发 * ApplicationListener<E extends ApplicationEvent> extends EventListener * 监听ApplicationEvent及其下面的子事件 * 步骤: * 写一个监听器来监(ApplicationListener的实现类)听某个事件(ApplicationEvent及其子类) * @EventListener * @EventListener(classes = {ApplicationEvent.class}) * public void listener(ApplicationEvent applicationEvent){ * * } * 原理: * EventListenerMethodProcessor * SmartInitializingSingleton原理: * 1 ioc容器创建对象并refresh() * 2 初始化所有剩下的单实例bean finishBeanFactoryInitialization(beanFactory); * 1 先创建所有的单实例bean * 2 获取所有创建好的单实例bean 判断是否实现了 SmartInitializingSingleton这个接口 * 如果是 则调用afterSingletonsInstantiated这个方法 * * 把监听器加入到容器 * 只要容器中有相应的事件发布 我们就能监听到这个事件 * 1 ContextRefreshedEvent:容器刷新完成(所有bean都完全创建)会发布这个事件 * * 2 自己发布事件 * 3 容器关闭会发布事件 ContextClosedEvent * * * 发布一个事件 * 原理: 1 容器创建对象:refresh(); * 2 容器刷新完成:finishRefresh(); * 发布事件 容器刷新完成:publishEvent(new ContextRefreshedEvent(this)); * * * 事件发布流程: * getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType); * 获取事件的多播器(派发器) * multicastEvent 派发事件 * getApplicationListeners(event, type)获取所有的指定事件监听器 * 如果有executor 则可以进行异步派发 否则同步的方式直接执行 * invokeListener(listener, event) 拿到listener回调onApplicationEvent方法 * applicationEventMulticaster【事件派发器】 * initApplicationEventMulticaster();初始化applicationEventMulticaster * 先去容器中寻找id为applicationEventMulticaster的组件 * 如果没有 则创建并添加到容器中取 * this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); * beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); * 容器中有哪些监听器 * 1 容器创建对象:refresh(); * 2 registerListeners(); * 从容器中拿到所有的监听器 吧他们添加到ApplicationEventMulticaster中去 * String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); * for (String listenerBeanName : listenerBeanNames) { * getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); * } ``` ​ ### Spring容器的refresh() 创建刷新 ​ 1 prepareRefresh();//Prepare this context for refreshing. 容器刷新前的预处理 ​ 1 initPropertySources(); 初始化属性设置 子类自定义个性化的属性设置方法 ​ 2 getEnvironment().validateRequiredProperties() 属性的合法性检测 ​ 3 this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); 保存容器的一些早期的事件 ​ 2 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 获取刷新bean工厂 ​ 1 refreshBeanFactory(); ​ GenericApplicationContext 构造函数中 this.beanFactory = new DefaultListableBeanFactory(); ​ 创建 beanFactory 并设置id ​ 2 getBeanFactory() 获取BeanFactory ​ 3 将创建的beanFactory【DefaultListableBeanFactory】返回 ​ 3 prepareBeanFactory(beanFactory); BeanFactory的预处理工作(BeanFactory进行一些设置) ​ 1 设置BeanFactory的类加载器 支持表达式解析器。。。 ​ 2 添加部分BeanPostProcessor(ApplicationContextAwareProcessor) ​ 3 设置回来的自动装配的接口EnvironmentAware EmbeddedValueResolverAware。。。 ​ 4 注册可以解析的自动装配 ​ 5 添加后置处理器 BeanPostProcessor(ApplicationListenerDetector) ​ 6 添加编译时的AspectJ ​ 7 给BeanFactory中添加 environment【ConfigurableEnvironment】 ​ systemProperties 【Map<String, Object>】 ​ systemEnvironment【Map<String, Object>】等组件 ​ 4 postProcessBeanFactory(beanFactory);(一个空方法) beanFactory准备工作完成后的后置处理工作 ​ 1 子类可以通过重写这个方法 在beanFactory创建并预准备完成后 做进一步设置 ​ ==================beanFactory创建以及预准备工作================================= ​ 5 invokeBeanFactoryPostProcessors(beanFactory)执行beanFactory的postProcess ​ 在BeanFactory标准初始化之后执行的 ​ 两个接口:BeanFactoryPostProcessor BeanDefinitionRegistryPostProcessor ​ 1 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); 执行postProcessBeanDefinitionRegistry ​ 1.String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); 获取所有的BeanDefinitionRegistryPostProcessor的名称 ​ 2 看优先级排序 PriorityOrdered ​ 执行 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); ​ 3 再执行实现了Ordered 顺序接口的 BeanDefinitionRegistryPostProcessor ​ 执行 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); ​ 4 最后执行没有实现任何接口的BeanDefinitionRegistryPostProcessor ​ 执行 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); ​ 5 执行BeanDefinitionRegistryPostProcessor的PostProcessor方法 ​ invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); ​ invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); ​ 2String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);获取所有的 BeanFactoryPostProcessor的方法 ​ 1 获取所有的BeanFactoryPostProcessor ​ 2 先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor ​ postProcessor.postProcessBeanFactory ​ 2 再执行实现了Ordered接口的BeanFactoryPostProcessor ​ postProcessor.postProcessBeanFactory ​ 3 最后执行没有实现PriorityOrdered 或者Ordered接口的BeanFactoryPostProcessor ​ postProcessor.postProcessBeanFactory ​ 6 registerBeanPostProcessors(beanFactory); 注册BeanPostProcessor【bean的后置处理器】 ​ //// Register bean processors that intercept bean creation. 用于拦截bean的创建 ​ ​ 不同类型的BeanPostProcessor 在Bean创建的前后的执行时机不同 ​ BeanPostProcessor ​ DestructionAwareBeanPostProcessor ​ SmartInstantiationAwareBeanPostProcessor ​ InstantiationAwareBeanPostProcessor ​ MergedBeanDefinitionPostProcessor 1.String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);获取所有的BeanPostProcessor ​ 1 获取所有的BeanPostProcessor 货值处理器默认可以通过 PriorityOrdered Ordered接口等分到不同的list中 ​ 1 对实现了PriorityOrdered 接口的BeanPostProcessor进行排序然后注册(所谓注册 就是将beanPostProcessor添加到 beanFactory中) ​ private static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) { for (BeanPostProcessor postProcessor : postProcessors) { beanFactory.addBeanPostProcessor(postProcessor); }} ​ 2 对实现了Ordered 接口的BeanPostProcessor进行排序然后注册 ​ 3 对没有实现任何接口的BeanPostProcessor进行排序 然后注册 ​ 4 最终注册实现了MergedBeanDefinitionPostProcessor接口的BeanPostProcessor ​ 5 最后注册一个 ApplicationListenerDetector(applicationContext)来在Bean创建完成后检查是否是ApplicationListener 如果是 则添加到容器中去 7 initMessageSource(); 初始化MessageSource组件(做国际化功能 消息绑定 消息解析) ​ 1 获取beanFactory ​ 2 判断容器中是否存在messageSource的这个bean 有则赋值给messageSources ​ 没有则创建一个默认的new DelegatingMessageSource()给messageSources 属性 ​ MessageSource 取出国际化配置文件中的某个key的值 按照区域信息获取 ​ 3 把创建好的messageSources注册到容器中 以后获取国际化配置文件值的时候 可以自动注入 ​ beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); 8 initApplicationEventMulticaster(); 初始化事件派发器 ​ 1 获取beanFactory ​ 2 判断容器中是否存在 applicationEventMulticaster 存在则将其赋值给属性applicationEventMulticaster ​ 不存在则创建默认的派发器 new SimpleApplicationEventMulticaster(beanFactory) 将其赋值给applicationEventMulticaster 并将其添加到容器中去 9 onRefresh(); 留给子类重写 ​ 1 在容器刷新的时候自定义逻辑 10 registerListeners(); 给容器中注册监听器 ​ 1 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); ​ 2 从容器中获取所有的ApplicationListener的名字 将其添加到事件派发器中 ​ getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); ​ 3 派发之前步骤产生的事件 11 finishBeanFactoryInitialization(beanFactory); 初始化所有剩下单例的bean =======================================总结================================== 1 spring容器在启动的时候 会先保存所有的注册进来的bean的定义信息 ​ xml注册 注解注册 2 spring容器会在何时的时机创建这些bean ​ 1 用到bean的时候 利用getBean创建 ;创建好之后保存在容器中 ​ 2 统一创建剩下所有bean的时候finishBeanFactoryInitialization ​ 3 后置处理器:BeanPostProcessor ​ 每一个bean创建完成 都会使用各种后置处理器进行处理 用来增强bean的功能 ​ 4 事件驱动模型 ​ ApplicationListener 事件监听 @WebServlet @WebListener @Webfilter 1 Servlet容器启动 会扫描当前应用的每一个jar包的ServletContainerInitializer的实现 2 提供ServletContainerInitializer的实现类 ​ 必须绑定在META-INF/services/javax.servlet.ServletContainerInitializer中 ​ 文件的内容就是ServletContainerInitializer实现类的全类名 总结:容器在启动应该的时候 会扫描当前应用每一个jar包里面META-INF/services/javax.servlet.ServletContainerInitializer指定的实现类 启动并运行这个实现类的方法 ```java //容器启动的时候会将@HandlesTypes指定的这个类型下面的子类 子接口传递过来 @HandlesTypes(BeanPostProcessor.class) @Slf4j public class MyServletContainerInntializer implements ServletContainerInitializer { /** * * @param set 感兴趣类型的所有子类型 * @param servletContext 代表当前web应用的ServletContext 一个web应用 一个servletContext * @throws ServletException */ @Override public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException { log.info("感兴趣的类型为:{}",set); } } ``` ​ ​ ​ ​ ​
Markdown
UTF-8
30,205
2.59375
3
[]
no_license
# IsoSeq™: PacBio® Isoform Sequencing. The Isoform Sequencing (Iso-Seq™) Anaylsis refers to [PacBio’s proprietary methods and software applications for transcriptome sequencing](http://www.pacb.com/applications/rna-sequencing/). The Iso-Seq application generates full-length cDNA sequences — from the 5’ end of transcripts to the poly-A tail — eliminating the need for transcriptome reconstruction using isoform-inference algorithms. The Iso-Seq method generates accurate information about alternatively spliced exons and transcriptional start sites. It also delivers information about poly-adenylation sites for transcripts up to 10 kb in length across the full complement of isoforms within targeted genes or the entire transcriptome. This document describes the Iso-Seq software in SMRT® Analysis v3.0 release, which includes SMRT Link v1.0. Previous Iso-Seq documents can be found in its [github wiki](https://github.com/PacificBiosciences/cDNA_primer/wiki). Table of contents ================= * [Overview](#overview) * [Manual](#manual) * [Running with SMRT Link](#running-with-smrt-link) * [Running on the Command-Line](#running-on-the-command-line) * [Running on the Command-Line with pbsmrtpipe](#running-on-the-command-line-with-pbsmrtpipe) * [Advanced Analysis Options](#advanced-analysis-options) * [SMRT Link/pbsmrtpipe IsoSeq Options](#smrt-linkpbsmrtpipe-iso-seq-options) * [Classify Options](#classify-options) * [Cluster Options](#cluster-options) * [Subset Options](#subset-options) * [Output Files](#output-files) * [Classify Output Files](#classify-output-files) * [Cluster Output Files](#cluster-output-files) * [Algorithm Modules](#algorithm-modules) * [Diff SMRT Analysis v3.0 vs v2.3](#diff-smrt-analysis-v30-vs-v23) * [Handling PacBio RS and PacBio RS II data](#handling-pacbio-rs-and-pacbio-rs-ii-data) * [Glossary](#glossary) ## Overview ![isoseq expanded](https://cloud.githubusercontent.com/assets/12494820/11380910/c9775812-92ad-11e5-97e3-5c3849ce6fea.png) Analyses are performed in three stages, CCS, Classify and Cluster. Cluster employs the Iterative Clustering and Error correction (ICE) algorithm. For analyses performed on the command-line, there is an optional tool, Subset, for subsetting the IsoSeq results. * __CCS__ * CCS is the first stage of an IsoSeq analysis. CCS builds circular consensus sequences (CCSs) from your subreads. More information about CCS is available [here](https://github.com/PacificBiosciences/pbccs/blob/master/README.md). * __Classify__ * Classify is the second stage of an IsoSeq analysis. The key output of Classify is a file of full-length non-chimeric reads, and a file of non-full length reads. The key input of Classify is the circular consensus sequences generated from CCS. Classify will identify and remove polyA/T tails, remove primers, and identify read strandedness. Classify also removes artificial concatemers, but does not remove PCR chimeras. * __Cluster__ * Cluster is the third stage of an IsoSeq analysis. The key outputs of Cluster is a file of polished, high-quality consensus sequences, and a file of polished, low-quality consensus sequences. The key input of clustering is the file of full-length non-chimeric reads, and a file of non-full length reads outputted by Classify. * __Subset__ * Subset is an optional program which can be used to subset the output files for particular classes of sequences, such as non-chimeric reads, or non-full-length reads. ##Manual There are three ways to run the Iso-Seq application: Using SMRT Link, on the command line, and on the command line using pbsmrtpipe so that you can run the whole Iso-Seq Analysis with one command given to pbsmrtpipe. ##Running with SMRT Link To run the Iso-Seq application using SMRT Link, follow the usual steps for analysing data on SMRT Link. TODO: Link to document explaining SMRT Link. ##Running on the Command Line On the command line, the analysis is performed in 3 steps: 1. Run CCS on your subreads, generating a CCS BAM file. Then generate an XML from the BAM file. 2. Run Classify on your CCSs with the XML as input, generating a FASTA of annotated sequences. 3. Run Cluster on the FASTA produced by Classify, generating polished isoforms. __Step 1. CCS__ First, convert your subreads to circular consensus sequences. You can do this with the command: ccs --noPolish --minLength=300 --minPasses=1 --minZScore=-999 --maxDropFraction=0.8 --minPredictedAccuracy=0.8 --minSnr=4 subreads.bam ccs.bam Where ccs.bam is where the CCSs will be output, and subreads.bam is the file containing your subreads. CCS options are described in [pbccs doc](https://github.com/PacificBiosciences/pbccs/blob/master/README.md). If you think that you have transcripts of interest that are less than 300 bp in length, be sure to adjust the `minLength` parameter. Next, you will generate an XML file from your CCSs. You can do this with the commmand: dataset create --type ConsensusReadSet ccs.xml ccs.bam Where `ccs.xml` is the name of the XML file you are generating and `ccs.bam` is the name of the BAM file you generated previously using the `ccs` command. __Step 2. Classify__ Classify can be run at the command line as follows: pbtranscript classify [OPTIONS] ccs.xml isoseq_draft.fasta --flnc=isoseq_flnc.fasta --nfl=isoseq_nfl.fasta Where `ccs.xml` is the XML file you generated in Step 1. Where `isoseq_flnc.fasta` contains only the full-length, non-chimeric reads. And where `isoseq_nfl.fasta` contains all non-full-length reads. Or you can run classify creating XML files instead of FASTA files as follows: pbtranscript classify [OPTIONS] ccs.xml isoseq_draft.fasta --flnc=isoseq_flnc.contigset.xml --nfl=isoseq_nfl.contigset.xml Where `ccs.xml` is the XML file you generated in Step 1. Where `isoseq_flnc.contigset.xml` contains only the full-length, non-chimeric reads. And where `isoseq_nfl.contigset.xml` contains all non-full-length reads. **Note**: One can always use `pbtranscript subset` to further subset `isoseq_draft.fasta` if `--flnc` and `--nfl` are not specified when you run `pbtranscript classify`. For example: pbtranscript subset isoseq_draft.fasta isoseq_flnc.fasta --FL --nonChimeric __Step 3. Cluster and Polish__ `cluster` can be run at the command line as follows: pbtranscript cluster [OPTIONS] isoseq_flnc.fasta polished_clustered.fasta --quiver --nfl=isoseq_nfl.fasta --bas_fofn=my.subreadset.xml Or pbtranscript cluster [OPTIONS] isoseq_flnc.contigset.xml polished_clustered.contigset.xml --quiver --nfl=isoseq_nfl.contigset.xml --bas_fofn=my.subreadset.xml **Note**: `--quiver --nfl=isoseq_nfl.fasta|contigset.xml` must be specified in order to get Quiver|Arrow polished consensus isoforms. Optionally, you may call the following command to run ICE and create unpolished consensus isoforms only. pbtranscript cluster [OPTIONS] isoseq_flnc.fasta unpolished_clustered.fasta ##Running on the Command-Line with pbsmrtpipe ###Install pbsmrtpipe pbsmrtpipe is a part of `smrtanalysis-3.0` package and will be installed if `smrtanalysis-3.0` has been installed on your system. Or you can [download pbsmrtpipe](https://github.com/PacificBiosciences/pbsmrtpipe) and [install](http://pbsmrtpipe.readthedocs.org/en/master/). You can verify that pbsmrtpipe is running OK by: pbsmrtpipe --help ### Create a dataset Now create an XML file from your subreads. ``` dataset create --type SubreadSet --generateIndices my.subreadset.xml subreads1.bam subreads2.bam ... ``` This will create a file called `my.subreadset.xml`. ### Create and edit Iso-Seq Analysis options and global options for `pbsmrtpipe`. Create a global options XML file which contains SGE related, job chunking and job distribution options that you may modify by: ``` pbsmrtpipe show-workflow-options -o global_options.xml ``` Create an Iso-Seq options XML file which contains Iso-Seq related options that you may modify by: ``` pbsmrtpipe show-template-details pbsmrtpipe.pipelines.sa3_ds_isoseq -o isoseq_options.xml ``` The entries in the options XML files have the format: ``` <option id="pbtranscript.task_options.min_seq_len"> <value>300</value> </option> ``` **Note**: If you only want to run Iso-Seq Classify without Cluster, please create an XML for Iso-Seq Classify Only. ``` pbsmrtpipe show-template-details pbsmrtpipe.pipelines.sa3_ds_isoseq_classify -o isoseq_classify_options.xml ``` And you can modify options using your favorite text editor, such as vim. ### Run the Iso-Seq application from pbsmrtpipe Once you have set your options, you are ready to run the Iso-Seq software application via pbsmrtpipe: ``` pbsmrtpipe pipeline-id pbsmrtpipe.pipelines.sa3_ds_isoseq -e eid_subread:my.subreadset.xml --preset-xml=isoseq_options.xml --preset-xml=global_options.xml --output-dir=my_run ``` Where `my_run` is where the results of your analysis will be stored. ## Advanced Analysis Options ## SMRT Link/pbsmrtpipe Iso-Seq Options You may modify Iso-Seq advanced analysis parameters for SMRT Link or pbsmrtpipe as follows. | Module | Parameter | pbsmrtpipe name | Default | Explanation | | ------ | -------------------------- | ------- | --------------------------- | ----------------- | | CCS | Max. dropped fraction | max_drop_fraction | 0.08 | Maximum fraction of subreads that can be dropped before giving up. | | CCS | Minimum length | min_length | 300 | Sets a minimum length requirement for the median size of insert reads in order to generate a consensus sequence. If the targeted template is known to be a particular size range, this can filter out alternative DNA templates. | | CCS | Minimum Number of Passes | min_passes | 1 | Sets a minimum number of passes for a ZMW to be emitted. This is the number of full passes. Full passes must have an adapter hit before and after the insert sequence and so does not include any partial passes at the start and end of the sequencing reaction. Additionally, the full pass count does not include any reads that were dropped by the Z-Filter. | | CCS | Minimum Predicted Accuracy | min_predicted_accuracy | 0.8 | The minimum predicted accuracy of a read. CCS generates an accuracy prediction for each read, defined as the expected percentage of matches in an alignment of the consensus sequence to the true read. A value of 0.99 indicates that only reads expected to be 99% accurate are emitted. | | CCS | Minimum read score | min_read_score | 0.75 | Minimum read score of input subreads. | | CCS | Minimum SNR | min_snr | 4 | This filter removes data that is likely to contain deletions. SNR is a measure of the strength of signal for all 4 channels (A, C, G, T) used to detect basepair incorporation. The SNR can vary depending on where in the ZMW a SMRTbell™ template stochastically lands when loading occurs. SMRTbell templates that land near the edge and away from the center of the ZMW have a less intense signal, and as a result can contain sequences with more "missed" basepairs. This value sets the threshold for minimum required SNR for any of the four channels. Data with SNR < 3.75 is typically considered lower quality. | | CCS | Minimum Z Score | min_zscore | -9999 | The minimum Z-Score for a subread to be included in the consensus generating process. | | Classify | Ignore polyA | ignore_polya | FALSE | Full-Length criteria does not require polyA tail. By default this is off, which means that polyA tails are required for a sequence to be considered full length. When it is turned on, sequences do not need polyA tails to be considered full length. | | Classify | Min. seq. length | min_seq_len | 300 | Minimum sequence length to output. | | Cluster | Minimum Quiver|Arrow Accuracy | hq_quiver_min_accuracy | 0.99 | Minimum allowed Quiver accuracy to classify an isoform as hiqh-quality. | | Cluster-Polish | Trim QVs 3' | qv_trim_3p | 30 | Ignore QV of n bases in the 3' end. | | Cluster-Polish | Trim QVs 5' | qv_trim_5p | 100 | Ignore QV of n bases in the 5' end. | | Maximum Length (max_length) | --maxLength=15000 | Maximum length of subreads to use for generating CCS. Default = 7000 | | No Polish (no_polish) | --noPolish | Only output the initial template derived from the POA (faster, less accurate). | **Note**: The Iso-Seq Classify Only protocol does not perform isoform-level clustering and only uses a subset of advanced analysis parameters. ## Classify Options In order to display Classify advanced options via command line: `pbtranscript classify --help`. | Type | Parameter | Example | Explanation | | --------------- | ---------- | ------------- | ----------------- | | positional | readsFN | ccs.bam,xml,fasta | First positional argument. It specifies input CCS reads in BAM, dataset XML, or FASTA format. | | positional | outReadsFN | isoseq_draft.fasta,contigset.xml | Second positional argument. Output file which contains all classified reads in FASTA or contigset XML format. | | optional | Help | -h, --help | This prints the help message. | | optional | Full-Length Non-Chimeric | --flnc FLNC_FA.fasta,contigset.xml | Outputs full-length non-chimeric reads in fasta or contigset XML format. | | optional | Output Non-Full-Length | --nfl NFL_FA.fasta | Outputs non-full-length reads in FASTA or contigset XML format. | | HMMER | HMMER Directory | -d OUTDIR, --outDir OUTDIR | Directory to store HMMER output (default: output/). | | HMMER | Summary | -summary out.classify_summary.txt | TXT file to output classify summary (default: out.classify_summary.txt). | | HMMER | Primers File | -p primers.fa, --primer primers.fa | Primer FASTA file (default: primers.fa). | | HMMER | Primers Report | --report out.primer_info.csv | CSV file of primer info. Contains the same info found in the description lines of the output FASTA (default: out.primer_info.csv). | | HMMER | CPUs | --cpus CPUS | Number of CPUs to run HMMER (default: 8). | | Chimera-detection | Minimum Sequence Length | --min_seq_len MIN_SEQ_LEN | Minimum CCS length to be analyzed. Fragments shorter than minimum sequence length are excluded from analysis (default: 300). | | Chimera-detection | Minimum PHMMER Score | --min_score MIN_SCORE | Minimum phmmer score for primer hit (default: 10). | | Chimera-detection | Non-Full-Length Chimeras | --detect_chimera_nfl | Detect chimeric reads among non-full-length reads. Non-full-length non-chimeric/chimeric reads will saved to outDir/nflnc.fasta and outDir/nflc.fasta. | | Read-Extraction | Ignore polyA | --ignore_polyA | Full-Length criteria does not require polyA tail. By default this is off, which means that polyA tails are required for a sequence to be considered full length. When it is turned on, sequences do not need polyA tails to be considered full length. | ## Cluster Options In order to show Iso-Seq Cluster advanced options via command line: `pbtranscript cluster`. | Type | Parameter | Example | Explanation | | ----- | ------------------ | ---------------- | ----------------- | | positional | Input Reads | isoseq_flnc.fasta,contigset.xml | Input full-length non-chimeric reads in FASTA or contigset XML format. Used for clustering consensus isoforms. | | positional | Output Isoforms | out.fasta,congitset.xml | Output predicted (unpolished) consensus isoforms in FASTA file. | | optional | Help | -h, --help | This prints the help message. | | optional | Input Non-Full-Length | --nfl_fa isoseq_nfl.fasta | Input non-full-length reads in FASTA format, used for polishing consensus isoforms. | | optional | CCS QVs FOFN | --ccs_fofn ccs.fofn | A ccs.fofn or ccs.bam or ccs.xml file. If not given, Cluster assumes there is no QV information available. | | optional | Reads QVs FOFN | --bas_fofn my.subreadset.xml | A file which provides quality values of raw reads and subreads. Can be either a FOFN of BAM or BAX files, or a dataset XML. | | optional | Output Directory | -d output/, --outDir output/ | Directory to store temporary and output cluster files (default: output/). | | optional | Temp Directory | --tmp_dir tmp/ | Directory to store temporary files (default: tmp/). | | optional | Summary | --summary my.cluster_summary.txt | TXT file to output cluster summary (default: my.cluster_summary.txt). | | optional | Report | --report report.csv | A CSV file, each line containing a cluster, an associated read of the cluster, and the read type. | | optional | Pickle | --pickle_fn PICKLE_FN | Developers' option from which all clusters can be reconstructed. | | ICE | cDNA | --cDNA_size {under1k,between1k2k,between2k3k,above3k} | Estimated cDNA size. | | ICE | Quiver | --quiver | Call Quiver or Arrow to polish consensus isoforms using non-full-length non-chimeric CCS reads. | | ICE | Finer Quiver or Arrow | --use_finer_qv | Use finer classes of QV information from CCS input instead of a single QV from FASTQ. This option is slower and consumes more memory. | | SGE | Run SGE | --use_sge | Instructs Cluster to use SGE. | | SGE | Maximum SGE Jobs | --max_sge_jobs MAX_SGE_JOBS | The maximum number of jobs that will be submitted to SGE concurrently. | | SGE | SGE Job ID | --unique_id UNIQUE_ID | Unique ID for submitting SGE jobs. | | SGE | BLASR Cores | --blasr_nproc BLASR_NPROC | Number of cores for each BLASR job. | | SGE | Quiver or Arrow CPUs | --quiver_nproc QUIVER_NPROC | Number of CPUs each quiver or Arrow job uses. | | IceQuiver High QV/Low QV | Minimum Quiver or Arrow Accuracy | --hq_quiver_min_accuracy HQ_QUIVER_MIN_ACCURACY | Minimum allowed quiver or Arrow accuracy to classify an isoform as hiqh-quality. | | IceQuiver High QV/Low QV | Trim QVs 5' | --qv_trim_5 QV_TRIM_5 | Ignore QV of n bases in the 5' end. | | IceQuiver High QV/Low QV | Trim QVs 3' | --qv_trim_3 QV_TRIM_3 | Ignore QV of n bases in the 3' end. | | IceQuiver High QV/Low QV | High-Quality Isoforms FASTA | --hq_isoforms_fa output/all_quivered_hq.fa | Quiver or Arrow polished, high-quality isoforms in FASTA (default: output/all_quivered_hq.fa). | | IceQuiver High QV/Low QV | High-Quality Isoforms FASTQ | --hq_isoforms_fq output/all_quivered_hq.fq | Quiver or Arrow polished, high-quality isoforms in FASTQ (default: output/all_quivered_hq.fq). | | IceQuiver High QV/Low QV | Low-Quality Isoforms FASTA | --lq_isoforms_fa output/all_quivered_lq.fa | Quiver or Arrow polished, low-quality isoforms in FASTA (default: output/all_quivered_lq.fa). | | IceQuiver High QV/Low QV | Low-Quality Isoforms FASTQ | --lq_isoforms_fq output/all_quivered_lq.fq | Quiver or Arrow polished, low-quality isoforms in FASTQ (default: output/all_quivered_lq.fq). | ## Subset Options In order to show pbtranscript Subset options via command line: `pbtranscript subset`. | Type | Parameter | Example | Explanation | | ----- | ------------------ | --------------------------- | ----------------- | | positional | Input Sequences | isoseq_draft.fasta | Input FASTA file. | | positional | Output Sequences | isoseq_subset.fasta | Output FASTA file. | | optional | Help | -h, --help | This prints the help message. | | optional | Output Full-length | --FL | Reads to output must be Full-Length, with 3' primer and 5' primer and polyA tail seen. | | optional | Output Non-Full-length | --nonFL | Reads to output must be Non-Full-Length reads. | | optional | Output Non-Chimeric | --nonChimeric | Reads to output must be non-chimeric reads. | | optional | Output Read-Length | --printReadLengthOnly | Only print read lengths, no read names and sequences. | | optional | Ignore polyA Tails | --ignore_polyA | Full-Length criteria does not require polyA tail. By default this is off, which means that polyA tails are required for a sequence to be considered full length. When it is turned on, sequences do not need polyA tails to be considered full length. | ## Output Files ## Classify Output Files __Classify FASTA Output (isoseq_*.fasta)__ `isoseq_flnc.fasta` contains all full-length, non-artificial-concatemer reads. `isoseq_nfl.fasta` contains all non-full-length reads. `isoseq_draft.fasta` is an intermediate file in order to get full-length reads, which you can ignore. Reads in these FASTA files look like the following: ``` >m140121_100730_42141_c100626750070000001823119808061462_s1_p0/119/30_1067_CCS strand=+;fiveseen=1;polyAseen=1;threeseen=1;fiveend=30;polyAend=1067;threeend=1096;primer=1;chimera=0 ATAAGACGACGCTATATG ``` These lines have the format: ``` <movie_name>/<ZMW>/<start>_<end>_CCS INFO ``` The info fields are: * strand: either + or -, whether a read is forward or reverse-complement cDNA, * fiveseen: whether or not 5' prime is seen in this read, 1 yes, 0 no * polyAseen: whether or not poly A tail is seen, 1 yes, 0 no * threeseen: whether or not 3' prime is seen, 1 yes, 0 no * fiveend: start position of 5' * threeend: start position of 3' in read * polyAend: start position of polyA in read * primer: index of primer seen in this read (remember primer fasta file >F0 xxxxx >R0 xxxxx >F1 xxxxx >R1 xxxx) * chimera: whether or not this read is classified as a chimeric cdna **Note**: Reads in `isoseq-flnc.fasta` are always **strand-specific**. That is, the 5' and 3' primer (and sometimes the polyA tail) are used to tell whether the read is in the right strand. If needed, the scripts described here reverse-complement the original read and produce the sequence that is supposed to be the transcript. Non-full-length reads in `isoseq_nfl.fasta` on the other hand, could be in either orientation. __Summary (classify_summary.txt)__ This file contains the following statistics: * Number of reads of insert * Number of five prime reads * Number of three prime reads * Number of poly-A reads * Number of filtered short reads * Number of non-full-length reads * Number of full-length reads * Number of full-length non-chimeric reads * Average full-length non-chimeric read length **Note**: By seeing that the number of full-length, non-chimeric (flnc) reads is only a little less than the number of full-length reads, we can confirm that the number of artificial concatemers is very low. This indicates a successful SMRTbell library prep. ##Cluster Output Files __Summary (cluster_summary.txt)__ This file contains the following statistics: * Number of consensus isoforms * Average read length of consensus isoforms __Report (cluster_report.csv)__ This is a csv file each line of which contains the following fields: * cluster_id: ID of a consensus isoforms from ICE. * read_id : ID of a read which supports the consensus isoform. * read_type : Type of the supportive read ## Algorithm Modules __CCS__ `pbccs` is a tool to create circular consensus sequences (CCS) sequence from raw subreads for PacBio sequences. See [pbccs doc](https://github.com/PacificBiosciences/pbccs/blob/master/README.md) for usage. __Classify__ Iso-Seq Classify classifies reads into full-length or non-full-length reads, artifical-concatemer chimeric or non-chimeric read. In order to classify a read as full-length or non-full-length, we search for primers and polyA within reads. If and only if both primers and polyAs are seen in a read, we classify it as a full-length read. Otherwise, we classify the read as non-full-length. We also remove primers and polyAs from reads and identify read strandedness based on this information. **Note**: The current version of the Iso-Seq application in SMRT Link 1.0 by default recognizes Clontech SMARTer primers. **Note**: In SMRT Link 1.0, custom primers are __NOT__ supported. In order to use custom primers, You must call pbtranscript from command line like ```pbtranscript classify --primer your_primer_fasta ...``` Where your_primer_fasta is a FASTA file with the following format: ``` >F0 5' sequence here >R0 3' sequence here (but in reverse complement) ``` Next, we further look into full-length reads and classify them into artificial-concatemer chimeric reads or non-chimeric reads by locating primer hits within reads. * __HMMER__: We use `phmmer` in __HMMER__ package to detect locations of primer hits within reads and classify reads which have primer hits in the middle of sequences as artificial-concatemer chimeric. __Cluster__ Iso-Seq Cluster performs isoform-level clustering using the Iterative Clustering and Error correction (ICE) algorithm, which iteratively classifies full-length non-chimeric CCS reads into clusters and builds consensus sequences of clusters using `pbdagcon`. ICE is customized to work well on alternative isoforms and alternative polyadenlynation sites, but not on SNP analysis and SNP based highly complex gene families. For a detailed explanation of ICE, please refer to the [Iso-Seq webinar recording and slides](https://github.com/PacificBiosciences/cDNA_primer/wiki/Understanding-PacBio-transcriptome-data#isoseq). * __pbdagcon__: [`pdagcon`](https://github.com/PacificBiosciences/pbdagcon) is a tool which builds consensus sequences using Directed Acyclic Graph Consensus. __Polish__ Iso-Seq Polish further polishes consensus sequenecs of clusters (i.e., `pbdagcon` output) taking into account all the QV information. We assign not only full-length non-chimeric CCS reads but also non-full-length CCS reads into clusters based on similarity. Then for each cluster, we align raw subreads of its assigned ZMWs towards its consensus sequence. Finally, we load quality values to these alignments and polish the consensus sequence using `Quiver` or `Arrow`. * __Quiver__: [`Quiver|Arrow`](https://github.com/PacificBiosciences/GenomicConsensus) is a consensus and variant-calling algorithm for PacBio reads. `Quiver` or `Arrow` finds the maximum likelihood template sequence given PacBio reads of the template. It is used by the Iso-Seq application to polish consensus isoforms. `Quiver|Arrow` uses quality values and creates higher-quality consensus sequence comapred with `pbdagcon`, but is more time-consuming. ## Diff SMRT Analysis v3.0 vs v2.3 The output of the Sequel™ instruments is [BAM](http://pacbiofileformats.readthedocs.org/en/3.0/BAM.html) format, while the output of the PacBio RS and PacBio RS II instruments is bax.h5. Major differences between Iso-Seq software in SMRT Analysis v3.0 and Iso-Seq software in SMRT Analysis v2.3 are listed in the table below. *Note*: Functions of Iso-Seq Analysis have NOT been changed since v2.3, and Iso-Seq Tofu has NOT been integrated. | Iso-Seq Application in SMRT Analysis v3.0 | Iso-Seq Application in SMRT Analysis v2.3 | | --------------------------- | ---------------------------- | | SMRT Analysis Web Server: SMRT Link | SMRT Analysis Web Server: SMRT Portal | | Works on data from Sequel instrument | Works on data from PacBio RS and RS II | | Input PacBio reads are stored in BAM | Input PacBio reads are stored in bax.h5 format | | Supports PacBio [DataSet](http://pbsmrtpipe.readthedocs.org/en/master/getting_started.html#appendix-b-working-with-datasets) | Does *NOT* support PacBio Dataset | | Uses new algorithm pbccs to create CCS reads | Uses `ConsensusTools.sh` to create CCS reads | | Does *NOT* support using customer primers from SMRT Link | Supports using customer primers from SMRT Portal | | Does *NOT* support using `GMAP` to align consensus isoforms to reference from SMRT Link | Supports using `GMAP` to align consensus isoforms to reference from SMRT Portal | | SMRT Link has two protocols: `IsoSeq Classify Only` and `IsoSeq`. The `IsoSeq Classify Only` protocol only classifies reads, while the `IsoSeq` protocol not only classifies reads but also generates consensus isoforms using ICE and polish them using `Quiver` or `Arrow`. | SMRT Portal has one protocol: RS_IsoSeq, which provides options such that users can calssify reads, or run ICE and generate unpolished consensus isoforms or polish consensus isoforms using `Quiver` or `Arrow`. | ##Handling PacBio RS and PacBio RS II data If you want to run the Iso-Seq application on existing PacBio RS or PacBio RS II data, you will need to convert reads in bax.h5 files to BAM files. __Converting PacBio RS and PacBio RS II data to BAM with SMRT Link__ TODO: points to SMRT Link Doc. __Converting PacBio RS and PacBio RS II data to BAM from command line__ ``` bax2bam -o mynewbam mydata.1.bax.h5 mydata.2.bax.h5 mydata.3.bax.h5 ``` ## Glossary * __Chimera__ * Iso-Seq Classify classifies reads as artificial-concatemer chimeric or non-chimeric based on whether or not primers are found in the middle of the sequence. * __High QV | Low QV__ * Iso-Seq Cluster generates polished consensus isoforms are classified into either high-quality or low-quality isoforms. We classify an isoform as high quality if its consensus accuracy is no less than a cut-off, otherwise low quality. The default cut-off is **0.99**. You may change this value from command line, or via SMRT Link Advanced Analysis Parameters when creating an Iso-Seq job. <sup>For Research Use Only. Not for use in diagnostic procedures. © Copyright 2015, Pacific Biosciences of California, Inc. All rights reserved. Information in this document is subject to change without notice. Pacific Biosciences assumes no responsibility for any errors or omissions in this document. Certain notices, terms, conditions and/or use restrictions may pertain to your use of Pacific Biosciences products and/or third party products. Please refer to the applicable Pacific Biosciences Terms and Conditions of Sale and the applicable license terms at http://www.pacificbiosciences.com/licenses.html. </sup> <sup> Visit the [PacBio Developer's Network Website](http://pacbiodevnet.com) for the most up-to-date links to downloads, documentation and more. </sup> <sup>[Terms of Use & Trademarks](http://www.pacb.com/legal-and-trademarks/site-usage/) | [Contact Us](mailto:devnet@pacificbiosciences.com) </sup>
C++
UTF-8
1,016
3.28125
3
[]
no_license
#ifndef MATHHELPER_H #define MATHHELPER_H #include <random> #include "Vector2.h" #include "Vector3.h" namespace MathHelper { inline int randomInt( int min, int max ) { int diff = max - min; int offset = rand() % diff; return min + offset; } inline int randomInt( int max ) { return rand() % max; } inline long randomColor() { return RGB( randomInt(256), randomInt(256), randomInt(256) ); } inline float randomFloat() { return (float) rand() / RAND_MAX; } inline float randomSignedFloat() { return 2 * (rand()-RAND_MAX/2.0f) / RAND_MAX; } const float TWO_PI = 2*3.1415926f; inline Vector2 randomUnitVector() { float angle = TWO_PI * randomFloat(); return Vector2( cos(angle), sin(angle) ); } inline Vector3 randomUnit3DVector() { float angle = TWO_PI * randomFloat(); float z = randomFloat()*2-1; float areaEqual = std::sqrt(1-z*z); return Vector3( areaEqual*cos(angle), areaEqual*sin(angle), z ); } } #endif
Java
UTF-8
1,513
2.328125
2
[]
no_license
package br.com.PersonalSpringMVC.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import br.com.PersonalSpringMVC.model.service.ProfessorService; import br.com.PersonalSpringMVC.negocio.Professor; @Controller public class ProfessorController { @Autowired private ProfessorService service; @RequestMapping(value = "/professores", method = RequestMethod.GET) public String showLista( Model model ) { model.addAttribute("professores", service.obterLista()); return "professor/lista"; } @RequestMapping(value = "/professor", method = RequestMethod.GET) public String showDetalhe() { return "professor/detalhe"; } @RequestMapping(value = "/professor", method = RequestMethod.POST) public String incluir( Model model, Professor professor ) { service.incluir(professor); return this.showLista(model); } @RequestMapping(value = "/professor/{id}", method = RequestMethod.GET) public String excluir( Model model, @PathVariable Integer id ) { service.excluir(id); return this.showLista(model); } public ProfessorService getService() { return service; } public void setService(ProfessorService service) { this.service = service; } }
Markdown
UTF-8
2,427
2.859375
3
[]
no_license
+++ categories = ["daily"] date = "2019-01-20T12:00:00-08:00" tags = ["today", "change"] title = "Gone for a swim" +++ ![](/uploads/Copy of IMG_8923.JPG) Annnd.. that's me. At first I wasn't planning on including any pictures of myself on here, but today is a milestone and I wanted some proof, so I decided to share that here as well for whoever eventually reads through this. The air temperature today was a balmy 3C, but we have had some frosty mornings recently, so I'd wager the water was quite cold. Two days ago I decided I wanted to challenge myself to a "polar bear swim". Solo though. I had already decided to do a real polar bear swim this next year whenever one was happening, but I felt like I wanted to mix up my daily activities a bit and did this. We drove out to prudhomme lake, which is a bit down the highway outside of town. There was a lot of fish surfacing at the time, there always is around this area. Can't seem to land a fish to save my life in this spot though so I wasn't too upset about not having my rod with me. I stripped down to some boxer shorts and just stood, and did some deep breathing for a couple minutes before heading in. I honestly expected it to be a lot colder. I have been doing strictly cold showers every day for a couple weeks now, in addition to the wim hof breathing technique, though I haven't been doing the breathing on a daily basis. In the past few days I started adding a cold dip in the bathtub after the showers, which is what prompted me to head to the lake. I got in, and sat down neck deep, and stayed that way breathing for about a minute, dunking my head once around 30 seconds in. After that I swam around a short bit, dunked my head again, and then got out. All in all, about 2-3 minutes in the water. After I got out the only part of me that felt seriously cold was the very tips of my fingers. They warmed up quite quickly after we were in the car. The only other thing that happened was 2 middle toes on my left foot stayed numb for about an hour after the dip. I eventually massaged them for a few minutes and after standing and walking around the numbness went away. I read that it is a response that the body has to cold, where it directs blood flow away from the extremities. Even so, I never felt too cold, I never shivered, or panicked in the water. I was able to be very calm. I'll definitely do it again. Maybe this will be a Sunday thing.
Java
UTF-8
19,704
1.929688
2
[]
no_license
package com.qcj.controller; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ModelAndView; import com.qcj.entity.Commodity; import com.qcj.entity.CommodityComment; import com.qcj.entity.Commoditypicture; import com.qcj.entity.Gategories; import com.qcj.entity.SalesVolume; import com.qcj.service.CommodityCommentService; import com.qcj.service.CommodityService; import com.qcj.service.CommoditypictureService; import com.qcj.service.GategoriesService; import com.qcj.service.PageService; import com.qcj.service.SalesVolumeService; @Controller public class GategoriesController { static Logger log = Logger.getLogger(GategoriesController.class); @Resource GategoriesService gategoriesService; @Resource CommodityService commodityService; @Resource CommoditypictureService commoditypictureService; @Resource CommodityCommentService commodityCommentService; @Resource SalesVolumeService salesVolumeService; @Resource PageService pageService; int pageOn = 2;// 每页多少条数据 @RequestMapping("/findGategoriesList") public ModelAndView findGategoriesList(HttpServletRequest request, HttpServletResponse response) { ModelAndView mv = new ModelAndView(); int pageNumber = 1; String pageNumberX = request.getParameter("pageNumberX"); if (pageNumberX != null && pageNumberX != "") { pageNumber = Integer.parseInt(pageNumberX); } int gategoriesPageAll = pageService.gategoriesAllPage(pageOn);// 返回一共多少页 if (pageNumber > gategoriesPageAll) { pageNumber = gategoriesPageAll; } if (pageNumber < 1) { pageNumber = 1; } log.info("how much page:" + gategoriesPageAll); List<Gategories> list = gategoriesService.selectPageGategories(pageOn, pageNumber);// 查询相关的那一页 log.info("list size:" + list.get(0).getGategoriesId()); mv.setViewName("shopWMS/view/findGategoriesList"); mv.addObject("pageAll", gategoriesPageAll); mv.addObject("pageNumberX", pageNumber);// 当前是第几页 mv.addObject("GategoriesList", list);// 查询到的结果集 return mv; } @RequestMapping("/updateGategories") public ModelAndView updateGategories(HttpServletRequest request, HttpServletResponse response) { ModelAndView mv = new ModelAndView(); int pageNumber = 1; String pageNumberX = request.getParameter("pageNumberX"); if (pageNumberX != null && pageNumberX != "") { pageNumber = Integer.parseInt(pageNumberX); } int gategoriesPageAll = pageService.gategoriesAllPage(pageOn);// 返回一共多少页 if (pageNumber > gategoriesPageAll) { pageNumber = gategoriesPageAll; } if (pageNumber < 1) { pageNumber = 1; } log.info("how much page:" + gategoriesPageAll); List<Gategories> list = gategoriesService.selectPageGategories(pageOn, pageNumber);// 查询相关的那一页 log.info("list size:" + list.get(0).getGategoriesId()); mv.setViewName("shopWMS/view/updateGategories"); mv.addObject("pageAll", gategoriesPageAll); mv.addObject("pageNumberX", pageNumber);// 当前是第几页 mv.addObject("GategoriesList", list);// 查询到的结果集 return mv; } @RequestMapping("/addGategories") public ModelAndView addGategories(HttpServletRequest request, HttpServletResponse response) { ModelAndView mv = new ModelAndView(); String gategoriesName = request.getParameter("gategoriesName"); String gategoriesMessage = request.getParameter("gategoriesMessage"); Gategories gategories = new Gategories(); gategories.setGategoriesName(gategoriesName); gategories.setGategoriesMessage(gategoriesMessage); log.info("参数gategories is :" + gategories); if (gategoriesService.addGategories(gategories) != 0) { /* mv.setViewName("shopWMS/view/findUserList"); */ mv.setViewName("forward:findGategoriesList"); return mv; } else { mv.setViewName("shopWMS/view/errorPage"); return mv; } } // 模糊查询 @RequestMapping("/updateGategoriesLike") public ModelAndView updateGategoriesLike(HttpServletRequest request, HttpServletResponse response) { ModelAndView mv = new ModelAndView(); int pageNumber = 1;// 初始化是第一页 String pageNumberX = request.getParameter("pageNumberX"); String gategoriesNameLike = request.getParameter("gategoriesNameLike");// 得到的模糊查询条件 System.out.println("模糊查询条件:" + gategoriesNameLike); if (pageNumberX != null) { pageNumber = Integer.parseInt(pageNumberX); } log.info("now pagenumber is:" + pageNumber); int gategoriesPageAll = pageService.gategoriesAllPage(pageOn, gategoriesNameLike);// 查询没页1条数据一共多少页面 System.out.println("模糊查询返回的gategoriesPageAll:" + gategoriesPageAll); if (pageNumber > gategoriesPageAll) { pageNumber = gategoriesPageAll; } if (pageNumber < 1) { pageNumber = 1; } log.info("模糊查询how much page:" + gategoriesPageAll); List<Gategories> list = gategoriesService.selectPageGategories(pageOn, pageNumber, gategoriesNameLike);// 查询相关的那一页 // log.info("模糊查询list size:" + list.get(0).getGategoriesId()); mv.setViewName("shopWMS/view/updateGategories"); mv.addObject("gategoriesNameLike", gategoriesNameLike); mv.addObject("pageAll", gategoriesPageAll); mv.addObject("pageNumberX", pageNumber);// 当前是第几页 mv.addObject("GategoriesList", list);// 查询到的结果集 return mv; } @RequestMapping("/gategoriesToUpdate") public ModelAndView gategoriesToUpdate(HttpServletRequest request, HttpServletResponse response) { ModelAndView mv = new ModelAndView(); String gategoriesId = request.getParameter("gategoriesId"); String gategoriesName = request.getParameter("gategoriesName"); String gategoriesMessage = request.getParameter("gategoriesMessage"); mv.addObject("gategoriesId", gategoriesId); mv.addObject("gategoriesName", gategoriesName); mv.addObject("gategoriesMessage", gategoriesMessage); System.out.println("gategoriestoupdate:--" + gategoriesId + ":" + gategoriesName); mv.setViewName("shopWMS/view/gategoriesUpdate"); return mv; } @RequestMapping("/deleteGategories") public ModelAndView deleteGategories(HttpServletRequest request, HttpServletResponse response) { ModelAndView mv = new ModelAndView(); String gategoriesId1 = request.getParameter("gategoriesId"); int gategoriesId = Integer.parseInt(gategoriesId1); List<Commodity> clist = commodityService.selectCommodityBycId(gategoriesId); if (null == clist) { if (gategoriesService.deleteGategories(gategoriesId) != 0) { mv.setViewName("shopWMS/view/updateGategories"); return mv; } else { String deleteGategoriesErr = "操作失败"; mv.addObject("deleteGategoriesErr", deleteGategoriesErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else { // 根据返回的cid挨个删除 for (Commodity commodity : clist) { int commodityId = commodity.getCommodityId(); // begin // 查询看看是否有图片有就执行下边 没有直接删除 List<Commoditypicture> cplist = commoditypictureService.selectCommoditypicture(commodityId); List<CommodityComment> cclist = commodityCommentService.selectCommodityCommentByCid(commodityId); List<SalesVolume> svlist = salesVolumeService.selectSalesVolumeBycId(commodityId); if (null == cplist && null == cclist && null == svlist) { if (commodityService.deleteCommodity(commodityId) != 0) { } else { String deleteCommoditypictureErr = "操作失败"; mv.addObject("deleteCommoditypictureErr", deleteCommoditypictureErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else if (null != cplist && null == cclist && null == svlist) { if (commoditypictureService.deleteCommoditypictures(commodityId) != 0) { System.out.println("商品所有图片删除成功"); if (commodityService.deleteCommodity(commodityId) != 0) { } else { String deleteCommoditypictureErr = "操作失败"; mv.addObject("deleteCommoditypictureErr", deleteCommoditypictureErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else { String deleteCommodityErr = "操作失败"; mv.addObject("deleteCommodityErr", deleteCommodityErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else if (null == cplist && null != cclist && null == svlist) { if (commodityCommentService.deleteCommodityCommentbycId(commodityId) != 0) { System.out.println("商品评论删除成功"); if (commodityService.deleteCommodity(commodityId) != 0) { } else { String deleteCommoditypictureErr = "操作失败"; mv.addObject("deleteCommoditypictureErr", deleteCommoditypictureErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else { String deleteCommodityErr = "操作失败"; mv.addObject("deleteCommodityErr", deleteCommodityErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else if (null == cplist && null == cclist && null != svlist) { if (salesVolumeService.deletesalesVolumebycId(commodityId) != 0) { System.out.println("商品销量表删除成功"); if (commodityService.deleteCommodity(commodityId) != 0) { } else { String deleteCommoditypictureErr = "操作失败"; mv.addObject("deleteCommoditypictureErr", deleteCommoditypictureErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else { String deleteCommodityErr = "操作失败"; mv.addObject("deleteCommodityErr", deleteCommodityErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else if (null != cplist && null != cclist && null != svlist) { if (commoditypictureService.deleteCommoditypictures(commodityId) != 0 && commodityCommentService.deleteCommodityCommentbycId(commodityId) != 0 && salesVolumeService.deletesalesVolumebycId(commodityId) != 0) { System.out.println("三个关联表删除成功"); if (commodityService.deleteCommodity(commodityId) != 0) { } else { String deleteCommoditypictureErr = "操作失败"; mv.addObject("deleteCommoditypictureErr", deleteCommoditypictureErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else { String deleteCommodityErr = "操作失败"; mv.addObject("deleteCommodityErr", deleteCommodityErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else if (null == cplist && null != cclist && null != svlist) { if (commodityCommentService.deleteCommodityCommentbycId(commodityId) != 0 && salesVolumeService.deletesalesVolumebycId(commodityId) != 0) { System.out.println("两个关联表删除成功"); if (commodityService.deleteCommodity(commodityId) != 0) { } else { String deleteCommoditypictureErr = "操作失败"; mv.addObject("deleteCommoditypictureErr", deleteCommoditypictureErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else { String deleteCommodityErr = "操作失败"; mv.addObject("deleteCommodityErr", deleteCommodityErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else if (null != cplist && null == cclist && null != svlist) { if (commoditypictureService.deleteCommoditypictures(commodityId) != 0 && salesVolumeService.deletesalesVolumebycId(commodityId) != 0) { System.out.println("两个关联表删除成功"); if (commodityService.deleteCommodity(commodityId) != 0) { } else { String deleteCommoditypictureErr = "操作失败"; mv.addObject("deleteCommoditypictureErr", deleteCommoditypictureErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else { String deleteCommodityErr = "操作失败"; mv.addObject("deleteCommodityErr", deleteCommodityErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else if (null != cplist && null != cclist && null == svlist) { if (commoditypictureService.deleteCommoditypictures(commodityId) != 0 && commodityCommentService.deleteCommodityCommentbycId(commodityId) != 0) { System.out.println("两个关联表删除成功"); if (commodityService.deleteCommodity(commodityId) != 0) { } else { String deleteCommoditypictureErr = "操作失败"; mv.addObject("deleteCommoditypictureErr", deleteCommoditypictureErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else { String deleteCommodityErr = "操作失败"; mv.addObject("deleteCommodityErr", deleteCommodityErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } else { String deleteCommodityErr = "操作失败"; mv.addObject("deleteCommodityErr", deleteCommodityErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } // end } System.out.println("商品类型所有关联表删除成功"); if (gategoriesService.deleteGategories(gategoriesId) != 0) { mv.setViewName("forward:updateGategories"); return mv; } else { String deleteGategoriesErr = "操作失败"; mv.addObject("deleteGategoriesErr", deleteGategoriesErr); mv.setViewName("shopWMS/view/errorPage"); return mv; } } } @RequestMapping("/gategoriesUpdate") public ModelAndView gategoriesUpdate(HttpServletRequest request, HttpServletResponse response) { ModelAndView mv = new ModelAndView(); String gategoriesId1 = request.getParameter("gategoriesId"); int gategoriesId = Integer.parseInt(gategoriesId1); String gategoriesName = request.getParameter("gategoriesName"); String gategoriesMessage = request.getParameter("gategoriesMessage"); if (gategoriesService.gategoriesUpdate(gategoriesId, gategoriesName, gategoriesMessage) != 0) { mv.setViewName("forward:updateGategories"); return mv; } else { mv.setViewName("shopWMS/view/errorPage"); return mv; } } @RequestMapping("/gategoriesAndCommodity") public ModelAndView gategoriesAndCommodity(HttpServletRequest request, HttpServletResponse response) { ModelAndView mv = new ModelAndView(); String gategoriesId1 = request.getParameter("gategoriesId"); String gategoriesName = request.getParameter("gategoriesName"); System.out.println("gategories 参数:--" + gategoriesId1 + ":" + gategoriesName); int gategoriesId = Integer.parseInt(gategoriesId1); Gategories gategories1 = new Gategories(); gategories1.setGategoriesId(gategoriesId); List<Map<String, Object>> clist = gategoriesService.queryCommodity(gategories1); System.out.println("gategories clist 返回:" + clist); mv.addObject("clist", clist); mv.addObject("gategoriesId", gategoriesId); mv.addObject("gategoriesName", gategoriesName); mv.setViewName("shopWMS/view/gategoriesAndCommodity"); return mv; } /** * 图片上传测试例子 * * @param request * @param response * @throws IOException */ @RequestMapping("/upPicture") public void upPicture(HttpServletRequest request, HttpServletResponse response) throws IOException { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); /* * if (multipartResolver.isMultipart(request)) { * System.out.println("ss"); } */ /* * String testpath = request.getServletPath(); String testpath2 = * request.getRequestURI(); String testpath3 = * request.getServletContext().getRealPath("/"); // 第一种:获取类加载的根路径 * D:\git\daotie\daotie\target\classes File f = new * File(this.getClass().getResource("/").getPath()); * System.out.println(f); // 获取当前类的所在工程路径; 如果不加“/” 获取当前类的加载目录 * D:\git\daotie\daotie\target\classes\my File f2 = new * File(this.getClass().getResource("").getPath()); * System.out.println(f2); // 第二种:获取项目路径 D:\git\daotie\daotie File * directory = new File("");// 参数为空 String courseFile = * directory.getCanonicalPath(); System.out.println(courseFile); // 第三种: * file:/D:/git/daotie/daotie/target/classes/ URL xmlpath = * this.getClass().getClassLoader().getResource(""); * System.out.println(xmlpath); // 第四种: D:\git\daotie\daotie * System.out.println(System.getProperty("user.dir")); * * 结果: C:\Documents and Settings\Administrator\workspace\projectName * 获取当前工程路径 * * // 第五种: 获取所有的类路径 包括jar包的路径 * System.out.println(System.getProperty("java.class.path")); * System.err.println("-----testpath路径地址为::"+testpath); * System.err.println("-----testpath2路径地址为::"+testpath2); * System.err.println("-----testpath3路径地址为::"+testpath3); */ // 获取支持文件上传的Request对象 MultipartHttpServletRequest MultipartHttpServletRequest mtpreq = (MultipartHttpServletRequest) request; // 通过 mtpreq 获取文件域中的文件 MultipartFile file = mtpreq.getFile("file"); // 通过MultipartFile 对象获取文件的原文件名 String fileName = file.getOriginalFilename(); // 生成一个uuid 的文件名 UUID randomUUID = UUID.randomUUID(); // 获取文件的后缀名 int i = fileName.lastIndexOf("."); String uuidName = randomUUID.toString() + fileName.substring(i); // 获取服务器的路径地址(被上传文件的保存地址) // String realPath = // request.getSession().getServletContext().getRealPath("/file"); String realPath = "C:/Users/Admin/git/Shop/WebContent/file"; // 将路径转化为文件夹 并 判断文件夹是否存在 File dir = new File(realPath); if (!dir.exists()) { dir.mkdir(); } // 获取一个文件的保存路径 String path = realPath + "/" + uuidName; System.err.println("-----realpath改了后路径地址为::" + realPath); // 为文件这服务器中开辟一给新的空间,*没有数据 // File newFile = new File(path); try { file.transferTo(new File(path)); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.err.println("-----服务器的路径地址为::" + realPath); System.err.println("-----图片名称为::" + fileName); System.err.println("-----图片新名称为::" + uuidName); System.err.println("-----图片新路径为::" + path); } }
Python
UTF-8
6,913
3.234375
3
[]
no_license
# Import routines import numpy as np import math import random from itertools import permutations # Defining hyperparameters m = 5 # number of cities, ranges from 1 ..... m t = 24 # number of hours, ranges from 0 .... t-1 d = 7 # number of days, ranges from 0 ... d-1 C = 5 # Per hour fuel and other costs R = 9 # per hour revenue from a passenger class CabDriver(): def __init__(self): """initialise your state and define your action space and state space""" self.action_space = [(0, 0)] + list(permutations([i for i in range(m)], 2)) self.action_space = [list(i) for i in self.action_space] self.state_space = [[x, y, z] for x in range(m) for y in range(t) for z in range(d)] self.state_init = random.choice(self.state_space) # Start the first round self.reset() ## Encoding state (or state-action) for NN input # Use this function if you are using architecture-1 def state_encod_arch1(self, state, action): """convert the (state-action) into a vector so that it can be fed to the NN. This method converts a given state-action pair into a vector format. Hint: The vector is of size m + t + d + m + m.""" state_encod = [0 for _ in range(m+t+d)] #location state_encod[state[0]] = 1 #time state_encod[m+state[1]] = 1 #day state_encod[m+t+state[2]] = 1 #set action vector if pickup loc is not 0 if(action[0] != 0): state_encod[m+t+d+action[0]] = 1 if(action[1] != 0): state_encod[m+t+d+m+action[1]] = 1 return state_encod # Use this function if you are using architecture-2 def state_encod_arch2(self, state): """convert the state into a vector so that it can be fed to the NN. This method converts a given state into a vector format. Hint: The vector is of size m + t + d.""" state_encod = [0 for _ in range(m+t+d)] #location state_encod[state[0]] = 1 #time state_encod[m+state[1]] = 1 #day state_encod[m+t+state[2]] = 1 return state_encod ## Getting number of requests def requests(self, state): """Determining the number of requests basis the location. Use the table specified in the MDP and complete for rest of the locations""" location = state[0] if location == 0: requests = np.random.poisson(2) if location == 1: requests = np.random.poisson(12) if location == 2: requests = np.random.poisson(4) if location == 3: requests = np.random.poisson(7) if location == 4: requests = np.random.poisson(8) if requests >15: requests =15 possible_actions_index = random.sample(range(1, (m-1)*m +1), requests) + [0] # [0,0] is not considered as customer request actions = [self.action_space[i] for i in possible_actions_index] return possible_actions_index,actions def reward_func(self, state, action, Time_matrix): """Takes in state, action and Time-matrix and returns the reward""" curr_loc = state[0] curr_time = state[1] curr_day = state[2] pickup_loc = action[0] drop_loc = action[1] if(action == [0,0]): #no booking accepted reward = -C #print("No ride") else: if curr_loc == pickup_loc: #pickup request is from present driver's location ride_time = Time_matrix[curr_loc][drop_loc][curr_time][curr_day] reward = (R-C)*ride_time #print("same loc ride") else: #current and pickup locs are different pickup_time = Time_matrix[curr_loc][pickup_loc][curr_time][curr_day] new_time,new_day = self.get_updt_time_day(curr_time, curr_day, pickup_time) ride_time = Time_matrix[pickup_loc][drop_loc][new_time][new_day] reward = (R-C)*ride_time - C*pickup_time #print("diff loc ride") #print("from env.py reward is: ",reward) return int(reward) def get_updt_time_day(self, time, day, ride_duration): """Takes present time, present day and ride duration to give end time and end day""" #ride duration is float ride_duration = int(ride_duration) #check if day overflow happens if time + ride_duration < 24: time = time + ride_duration else: #overflow num_days = (time + ride_duration) // 24 time = (time + ride_duration) % 24 #handle wraparound of day day = (day + num_days) % 7 return time,day def next_state_func(self, state, action, Time_matrix): """Takes state and action as input and returns next state""" curr_loc = state[0] curr_time = state[1] curr_day = state[2] pickup_loc = action[0] drop_loc = action[1] #required to decide episode end total_time = 0 #list copy next_state = [i for i in state] if action != [0,0]: next_state[0] = drop_loc if curr_loc == pickup_loc: #pickup request is from present driver's location ride_time = Time_matrix[curr_loc][drop_loc][curr_time][curr_day] new_time,new_day = self.get_updt_time_day(curr_time, curr_day, ride_time) total_time = ride_time else: #current and pickup locs are different pickup_time = Time_matrix[curr_loc][pickup_loc][curr_time][curr_day] new_time,new_day = self.get_updt_time_day(curr_time, curr_day, pickup_time) ride_time = Time_matrix[pickup_loc][drop_loc][new_time][new_day] new_time,new_day = self.get_updt_time_day(new_time, new_day, ride_time) total_time = ride_time + pickup_time else: #no ride accepted - increment by one time unit total_time = 1 new_time,new_day = self.get_updt_time_day(curr_time, curr_day, 1) next_state[1] = new_time next_state[2] = new_day return total_time, next_state def step(self, state, action, Time_matrix): """Environment step - returns next_state, reward and time taken for completion of action""" time_taken, next_state = self.next_state_func(state, action, Time_matrix) reward = self.reward_func(state, action, Time_matrix) return next_state, reward, time_taken def reset(self): return self.action_space, self.state_space, self.state_init
Java
UTF-8
419
3.015625
3
[]
no_license
package com.horcu.apps.interview.google.Math; /** * Created by ray on 6/12/16. */ //factorial of 5. How many combinations are there public class factorial { public static void main(String[] args) { int fact = 6, runningProduct = 0; for (int a = fact; a > 0; a--) { runningProduct = a== fact? fact: runningProduct*a; } System.out.println( runningProduct); } }
JavaScript
UTF-8
1,353
2.90625
3
[ "MIT" ]
permissive
const Table = require("../") const header = [ { value: "item" } ] // Example with arrays as rows const rows1 = [ [1] ] const rows2 = [ [{ value: 1 }] ] const footer = [ function (cellValue, columnIndex, rowIndex, rowData) { const total = rowData.reduce((prev, curr) => { return prev + (typeof curr[0] === "object") ? curr[0].value : curr[0] }, 0) return `${(total / rowData.length * 100).toFixed(2)}%` } ] const options = { borderColor: "green", width: "80%" } // header, rows, footer, and options const A1 = Table(header, rows1, footer, options).render() const A2 = Table(header, rows2, footer, options).render() // header, rows, footer const B1 = Table(header, rows1, footer).render() const B2 = Table(header, rows2, footer).render() // header, rows, options const C1 = Table(header, rows1, options).render() const C2 = Table(header, rows2, options).render() // header, rows (rows, footer is not an option) const D1 = Table(header, rows1).render() const D2 = Table(header, rows2).render() // rows, options const E1 = Table(rows1, options).render() const E2 = Table(rows2, options).render() // rows const F1 = Table(rows1).render() const F2 = Table(rows2).render() // adapter called: i.e. `require('tty-table')('automattic-cli')` console.log(A1, A2, B1, B2, C1, C2, D1, D2, E1, E2, F1, F2)
Java
UTF-8
690
2.234375
2
[]
no_license
package ru.itis; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import ru.itis.dao.UsersDaoJdbcImpl; import ru.itis.model.User; import java.util.List; /** * 06.05.2017 * Main * * @author Sidikov Marsel (First Software Engineering Platform) * @version v1.0 */ public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("ru.itis\\context.xml"); UsersDaoJdbcImpl usersDao = context.getBean(UsersDaoJdbcImpl.class); List<User> userList = usersDao.findUsersByAge(24); System.out.println(userList); } }
Python
UTF-8
871
3.4375
3
[]
no_license
class Stud: scount=0 def __init__(self,id,name,marks): self.sid = id self.sname = name self.smarks = marks Stud.scount += 1 def showstudentinfo(self): print('######################') print("Student id is",self.sid) print('Student name is',self.sname) print('Students mark is',self.smarks) id = int(input('Enter student id ')) name =input('Enter student name') marks = int(input('Enter students marks')) print('u enetred --',id,'--',name,'--',marks) st1=Stud(id,name,marks) id = int(input('Enter student id ')) name =input('Enter student name') marks = int(input('Enter students marks')) print('u enetred --',id,'--',name,'--',marks) st2=Stud(id,name,marks) print('Student 1 info') st1.showstudentinfo() print('Student 2 info') st2.showstudentinfo()
Shell
UTF-8
4,325
3.796875
4
[ "MIT" ]
permissive
archi=$(uname -m) if [ -z ${LD_LIBRARY_PATH+x} ] then export LD_LIBRARY_PATH=/usr/local/lib fi source dev_function.sh # Go language GO_VERSION=1.10.1 go_suffix='' case "$archi" in "armv6l") go_suffix=arm;; "i686") go_suffix=386;; "x86_64") go_suffix=amd64;; *);; esac if [ ! -z "$go_suffix" ] then e_header "Installing Go language go-$GO_VERSION" if [ -d $SOFT_DIR/go-$GO_VERSION ] then e_arrow "An existing Go directory exists [$SOFT_DIR/go-$GO_VERSION]" else go_dir=go${GO_VERSION}-linux-${go_suffix} go_filename=go${GO_VERSION}.linux-${go_suffix}.tar.gz go_url=https://dl.google.com/go/${go_filename} tmp_dir=$(mktemp -d) cd $tmp_dir && wget -q "$go_url" && tar xf $go_filename && \ mv -i go $SOFT_DIR/go-$GO_VERSION && \ cd $SOFT_DIR && ln -sf go-$GO_VERSION go && \ rm -fr "${tmp_dir}" e_arrow "Go installaton done" fi else e_warn "Unknwon architecture [$go_suffix]=> GO will not be installed" fi # End Go installation # Google-test installation GTEST_VERSION=1.8.0 e_header "Installing google-test library $GTEST_VERSION" if [ -f /usr/local/include/gtest/gtest.h -a -f /usr/local/lib/libgtest.a ] then e_arrow "Gtest is already installed" else gtest_filename=release-${GTEST_VERSION}.tar.gz gtest_url=https://github.com/google/googletest/archive/${gtest_filename} tmp_dir=$(mktemp -d) CXX_PATH=$(which g++) cd $tmp_dir && e_arrow downloading ... && \ wget -q "$gtest_url" && tar xf $gtest_filename && \ mkdir build && cd build && \ cmake ../googletest-release-${GTEST_VERSION} \ -DCMAKE_CXX_COMPILER=${CXX_PATH} > /tmp/gtest_cmake.log && \ e_arrow building ... && \ make -j 2 > /tmp/gtest_make.log && \ e_arrow installing ... && \ sudo make install > /tmp/gtest_install.log && \ rm -fr "${tmp_dir}" fi e_arrow "Gtest installaton done with error code $?" # End Google-test installation # Quickfix installation if [ -f /usr/local/include/quickfix/Message.h -a -f /usr/local/lib/libquickfix.so ] then e_arrow "Quickfix is already installed" else e_header "Installing quickfix library (master branch)" tmp_dir=$(mktemp -d) cd $tmp_dir && e_arrow downloading ... && \ git clone https://github.com/quickfix/quickfix.git && \ cd quickfix && \ e_arrow building ... && \ ./bootstrap > /tmp/quickfix_bootstrap.log 2>&1 && \ ./configure > /tmp/quickfix_configure.log 2>&1 && \ make -j 2 > /tmp/quickfix_make.log 2>&1 && \ e_arrow installing ... && \ sudo make install > /tmp/quickfix_install.log && rm -fr $tmp_dir res=$? if [ $res -ne 0 ] then e_error "quickfix installaton done with error code $res" e_arrow Check log files /tmp/quickfix_* else e_arrow "quickfix installaton done with error code $res" fi fi # End Quickfix installation # Google Benchmark library if [ -f /usr/local/include/benchmark/benchmark.h ] then e_arrow "Benchmark is already installed" else e_header "Installing benchmark library (master branch)" create_tmp_and_clone "benchmark" "https://github.com/google/benchmark.git" if [ $? -eq 0 ] then e_arrow building .. && \ cd benchmark && \ mkdir build && \ cd build && \ cmake .. -DCMAKE_BUILD_TYPE=RELEASE && \ make -j 2 > /tmp/benchmark_make.log 2>&1 && \ e_arrow installing ... && \ sudo make install > /tmp/benchmark_install.log && rm -fr $tmp_dir res=$? if [ $res -ne 0 ] then e_error "benchmark installaton done with error code $res" e_arrow Check log files /tmp/benchmark_* else e_arrow "benchmark installaton done with error code $res" fi fi fi # End Google Benchmark installation # Emscripten SDK if [ -f $SOFT_DIR/emsdk/emsdk ] then e_arrow "EMSDK is already installed" else create_tmp_and_clone "Emscripten SDK" "https://github.com/juj/emsdk.git" if [ $? -eq 0 ] then e_arrow installing .. && \ cd emsdk && \ ./emsdk install latest && \ e_arrow activating .. && \ ./emsdk activate latest res=$? if [ $res -ne 0 ] then e_error "Emscripten SDK installaton done with error code $res" else cd .. mv emsdk $SOFT_DIR/ e_success "Emscripten SDK installaton done with error code $res" fi else e_warn "Error when cloning git repository $?d " fi fi # End Emscripten SDK
JavaScript
UTF-8
1,588
3.59375
4
[]
no_license
$(function() { $("form").submit(function(event) { // Get the input text, remove punctuation, and split on newlines var inputText = $("#input-text").val().replace(/[^\w\s]/g, "").split(/\r|\n/); // Get other input values var wordCount = parseInt($("#word-count").val()); var vowelCount = parseInt($("#vowel-count").val()); var lineCount = parseInt($("#line-count").val()); // Send to get count parseText(inputText, wordCount, vowelCount, lineCount); event.preventDefault(); }); function parseText(inputText, wordCount, vowelCount, lineCount) { // Final output word and line counts var wordTotal = 0; var lineTotal = 0; // Loop through each line for (var x = lineCount - 1; x < inputText.length; x = x+lineCount) { // Split line into each word var splitLine = inputText[x].split(/[ ]+/); var wordFound = false; // Loop through each word for (var y = wordCount-1;y < splitLine.length; y = y+wordCount) { // If the word has required amount of vowels count it and flag line if (splitLine[y].match(/[aeiou]/gi).length >= vowelCount) { wordTotal++; wordFound = true; } } // If a word was found count the line if (wordFound) { lineTotal++; } } $("#output").html("Lines: " + lineTotal + ", Words: " + wordTotal); } });
C#
UTF-8
911
4.1875
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Task2ReadNumbersIntoStack { class Program { static void Main(string[] args) { // Task 2: Write a program that reads N integers from the console // and reverses them using a stack. Use the Stack<int> class. Console.WriteLine("N = "); Stack<int> stack = new Stack<int>(); int N = int.Parse(Console.ReadLine()); for (int counter = 0; counter < N; counter++) { int num = int.Parse(Console.ReadLine()); stack.Push(num); } Console.WriteLine("Your numbers:"); while (stack.Count > 0) { Console.WriteLine(stack.Peek()); stack.Pop(); } } } }
Rust
UTF-8
2,456
3.3125
3
[ "Apache-2.0", "MIT" ]
permissive
use std::cell::UnsafeCell; use std::mem; use super::INITIAL_CAPACITY; use super::job::Job; // a chain of vectors where jobs will be allocated in contiguous memory. struct BufChain { buf: Vec<Job>, _prev: Option<Box<BufChain>>, } impl BufChain { fn new(size: usize) -> Self { BufChain { buf: Vec::with_capacity(size), _prev: None, } } // try to allocate this job on the top-level vector. // returns an error if out of space. fn alloc(&mut self, job: Job) -> Result<*mut Job, Job> { let len = self.buf.len(); if len == self.buf.capacity() { Err(job) } else { self.buf.push(job); unsafe { Ok(self.buf.get_unchecked_mut(len) as *mut Job) } } } // create a new buffer with double the size of this one, while preserving // this one in the linked list. fn grow(self) -> Self { use std::cmp::max; let new_size = max(self.buf.len() * 2, 4); BufChain { buf: Vec::with_capacity(new_size), _prev: Some(Box::new(self)), } } } // A pool allocator for jobs. pub struct Arena { buf: UnsafeCell<BufChain>, } impl Arena { pub fn new() -> Self { Arena { buf: UnsafeCell::new(BufChain::new(INITIAL_CAPACITY)), } } // push a job onto the end of the pool and get a pointer to it. // this may only be called from the thread which logically owns this arenas. pub unsafe fn alloc(&self, job: Job) -> *mut Job { let mut buf = self.buf.get(); match (*buf).alloc(job) { Ok(job_ptr) => job_ptr, Err(job) => { // grow the buffer, replacing it with a temporary while we grow it. let new_link = mem::replace(&mut *buf, BufChain::new(0)).grow(); *buf = new_link; // we just grew the buffer, so we are guaranteed to have capacity. (*buf).alloc(job).ok().unwrap() } } } // gets the current top of the buffer. // this can only be called from the thread which logically owns this arena. pub unsafe fn top(&self) -> usize { (*self.buf.get()).buf.len() } // sets the top of the buffer. pub unsafe fn set_top(&self, top: usize) { (*self.buf.get()).buf.set_len(top); } } unsafe impl Send for Arena {} unsafe impl Sync for Arena {}
Python
UTF-8
567
3.3125
3
[]
no_license
#!/usr/bin/env python import numpy import scipy.stats import matplotlib.pyplot as pyplot ''' Generate a quantile-quantile plot, given an array of data. ''' def run(dataset): ''' ----------- Parameters: ----------- dataset: (numpy.ndarray) a 1-dimensional numpy array of data. ----------------- Function ----------------- Displays Q-Q plot, comparing normalized data to N(0,1) distribution ''' #Calculate quantile values scipy.stats.probplot(dataset, plot=pyplot) #Display plot pyplot.show() return
Java
UTF-8
2,315
2.484375
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.aviary.android.feather.widget; import it.sephiroth.android.library.imagezoom.ImageViewTouch; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ViewSwitcher; // TODO: Auto-generated Javadoc /** * The Class ImageSwitcher. */ public class ImageSwitcher extends ViewSwitcher { /** The m switch enabled. */ protected boolean mSwitchEnabled = true; /** * Instantiates a new image switcher. * * @param context * the context */ public ImageSwitcher( Context context ) { super( context ); } /** * Instantiates a new image switcher. * * @param context * the context * @param attrs * the attrs */ public ImageSwitcher( Context context, AttributeSet attrs ) { super( context, attrs ); } /** * Sets the image bitmap. * * @param bitmap * the bitmap * @param reset * the reset * @param matrix * the matrix * @param maxZoom * the max zoom */ public void setImageBitmap( Bitmap bitmap, boolean reset, Matrix matrix, float maxZoom ) { ImageViewTouch image = null; if ( mSwitchEnabled ) image = (ImageViewTouch) this.getNextView(); else image = (ImageViewTouch) this.getChildAt( 0 ); image.setImageBitmap( bitmap, reset, matrix, maxZoom ); if ( mSwitchEnabled ) showNext(); else setDisplayedChild( 0 ); } /** * Sets the image drawable. * * @param drawable * the drawable * @param reset * the reset * @param matrix * the matrix * @param maxZoom * the max zoom */ public void setImageDrawable( Drawable drawable, boolean reset, Matrix matrix, float maxZoom ) { ImageViewTouch image = null; if ( mSwitchEnabled ) image = (ImageViewTouch) this.getNextView(); else image = (ImageViewTouch) this.getChildAt( 0 ); image.setImageDrawable( drawable, reset, matrix, maxZoom ); if ( mSwitchEnabled ) showNext(); else setDisplayedChild( 0 ); } /** * Sets the switch enabled. * * @param enable * the new switch enabled */ public void setSwitchEnabled( boolean enable ) { mSwitchEnabled = enable; } }
JavaScript
UTF-8
593
2.546875
3
[]
no_license
function navbox() { var body = $('body'); var navbox = $('#navbox'); var navboxShow = $('#navboxShow'); var navboxClose = $('#navboxClose'); function showActions() { body.css('overflow','hidden'); navbox.addClass('open'); navbox.on('click', 'a', closeActions); } function closeActions() { body.css('overflow',''); navbox.removeClass('open'); navbox.off('click', 'a', closeActions); } navboxShow.click(function() { showActions(); }); navboxClose.click(function() { closeActions(); }); } $(document).ready(function(){ navbox(); });
JavaScript
UTF-8
521
3.625
4
[]
no_license
function countDown(num){ let timer = setInterval(function(){ if(num<=0){ clearInterval; console.log('Done!'); }else{ console.log(num); } num --; }, 1000); } countDown(4); function randomGame(){ let counter = 0; let counting = setInterval(function(){ let num = Math.random(); counter++; if(num>.75){ clearInterval(counting); console.log(num); } },1000)} randomGame();
C#
UTF-8
12,071
2.703125
3
[]
no_license
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 Inventory_Management_System { public partial class balancesheet : Form { SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-H8FALR0\SQLEXPRESS;Initial Catalog=finalproducts;Integrated Security=True"); public balancesheet() { InitializeComponent(); } private void button4_Click(object sender, EventArgs e) { try { SqlDataAdapter sda = new SqlDataAdapter("select * from balancesheet ", con); DataTable dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; } catch { MessageBox.Show("An unexpected error occured !\nPlease try again !","Error",MessageBoxButtons.OK,MessageBoxIcon.Error); } } private void button1_Click(object sender, EventArgs e) { try { if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "" && comboBox1.SelectedItem != null && dateTimePicker1.Text != null ) { SqlDataAdapter sda = new SqlDataAdapter("insert into balancesheet(Serial,Date,Account,Category) values ('" + textBox1.Text + "' , '" + dateTimePicker1.Text + "' ,'" + textBox2.Text + "', '" + comboBox1.SelectedItem.ToString() + "')", con); SqlDataAdapter sda2 = new SqlDataAdapter("insert into Approval(Amount,Name,[Source Name]) values ('" + textBox3.Text + "', '" + textBox2.Text + "', '" + label1.Text + "')", con); DataTable dt = new DataTable(); DataTable dt2 = new DataTable(); sda.Fill(dt); sda2.Fill(dt2); MessageBox.Show("Successfully inserted in database !\nPlease refresh database. ", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("You can't leave any fields empty.\nPlease try again !", "Stop", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } catch { MessageBox.Show("An error occurred while inserting data !\nPlease try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button2_Click(object sender, EventArgs e) { try { if (textBox2.Text == "" && textBox3.Text == "" && textBox1.Text != "") { SqlDataAdapter sda = new SqlDataAdapter("delete from balancesheet where Serial = '" + textBox1.Text + "' ", con); DataTable dt = new DataTable(); sda.Fill(dt); MessageBox.Show("Successfully deleted from database !\nPlease refresh database.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Please reset the text boxes and other inputs first if having any data in text boxes & put the serial number and try again to delete from database !", "Stop", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } catch { MessageBox.Show("An error occurred while deleting data !\nPlease try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button5_Click(object sender, EventArgs e) { textBox1.Clear(); comboBox1.SelectedItem = null ; dateTimePicker1.Text = null; textBox3.Clear(); textBox2.Clear(); } private void button3_Click(object sender, EventArgs e) { try { SqlDataAdapter sda = new SqlDataAdapter("update balancesheet set Date ='" + dateTimePicker1.Text + "' , Account = '" + textBox2.Text + "' , Category ='" + comboBox1.SelectedItem.ToString() + "' , Amount = '" + textBox3.Text + "' where Serial = '" + textBox1.Text + "' ", con); DataTable dt = new DataTable(); sda.Fill(dt); MessageBox.Show("Database updated successfully !\nPlease refresh database.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("An error occurred while updating data !\nPlease try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button8_Click(object sender, EventArgs e) { try { SqlDataAdapter sda = new SqlDataAdapter("select sum(Amount) from balancesheet", con); DataTable dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; } catch { MessageBox.Show("An error occurred !\nPlease try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button6_Click(object sender, EventArgs e) { this.Close(); } private void button7_Click(object sender, EventArgs e) { this.Hide(); Form1 bck = new Form1(); bck.Show(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Hide(); Form1 bck = new Form1(); bck.Show(); } private void loginPageToolStripMenuItem_Click(object sender, EventArgs e) { this.Hide(); logininfo bck = new logininfo(); bck.Show(); } private void updateToolStripMenuItem_Click(object sender, EventArgs e) { try { SqlDataAdapter sda = new SqlDataAdapter("update balancesheet set Date ='" + dateTimePicker1.Text + "' , Account = '" + textBox2.Text + "' , Category ='" + comboBox1.SelectedItem.ToString() + "' , Amount = '" + textBox3.Text + "' where Serial = '" + textBox1.Text + "' ", con); DataTable dt = new DataTable(); sda.Fill(dt); MessageBox.Show("Database updated successfully !\nPlease refresh database.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("An error occurred while updating data !\nPlease try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { try { if (textBox2.Text == "" && textBox3.Text == "" && comboBox1.SelectedItem != null) { SqlDataAdapter sda = new SqlDataAdapter("delete from balancesheet where Serial = '" + textBox1.Text + "' ", con); DataTable dt = new DataTable(); sda.Fill(dt); MessageBox.Show("Successfully deleted from database !\nPlease refresh database.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Please reset the text boxes first & put the serial number and try again to delete from database !", "Stop", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } catch { MessageBox.Show("An error occurred while deleting data !\nPlease try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void resetToolStripMenuItem_Click(object sender, EventArgs e) { textBox1.Clear(); comboBox1.SelectedItem = null; dateTimePicker1.Text = null; textBox3.Clear(); textBox2.Clear(); } private void exitToolStripMenuItem_Click_1(object sender, EventArgs e) { this.Hide(); Form1 bck = new Form1(); bck.Show(); } private void totalBalanceToolStripMenuItem_Click(object sender, EventArgs e) { try { SqlDataAdapter sda = new SqlDataAdapter("select sum(Amount) from balancesheet", con); DataTable dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; } catch { MessageBox.Show("An error occurred !\nPlease try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void databaseToolStripMenuItem_Click(object sender, EventArgs e) { try { SqlDataAdapter sda = new SqlDataAdapter("select * from balancesheet ", con); DataTable dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; } catch { MessageBox.Show("An unexpected error occured !\nPlease try again !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void insertToolStripMenuItem_Click(object sender, EventArgs e) { try { if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "" && comboBox1.SelectedItem != null && dateTimePicker1.Text != null) { SqlDataAdapter sda = new SqlDataAdapter("insert into balancesheet(Serial,Date,Account,Category,Amount) values ('" + textBox1.Text + "' , '" + dateTimePicker1.Text + "' , '" + textBox2.Text + "', '" + comboBox1.SelectedItem.ToString() + "', '" + textBox3.Text + "')", con); DataTable dt = new DataTable(); sda.Fill(dt); MessageBox.Show("Successfully inserted in database !\nPlease refresh database. ", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("You can't leave any fields empty.\nPlease try again !", "Stop", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } catch { MessageBox.Show("An error occurred while inserting data !\nPlease try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { try { var index = e.RowIndex; DataGridViewRow row = dataGridView1.Rows[index]; textBox1.Text = row.Cells[0].Value.ToString(); textBox2.Text = row.Cells[2].Value.ToString(); textBox3.Text = row.Cells[4].Value.ToString(); comboBox1.SelectedItem = row.Cells[3].Value.ToString(); dateTimePicker1.Text = row.Cells[1].Value.ToString(); } catch { } } private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { foreach(DataGridViewRow r in dataGridView1.Rows) { r.DefaultCellStyle.ForeColor = Color.Black; } } private void balancesheet_Load(object sender, EventArgs e) { // 3764 label3.ForeColor = Color.Black; label7.ForeColor = Color.Black; label6.ForeColor = Color.Black; label4.ForeColor = Color.Black; } } }
Java
UTF-8
645
1.875
2
[]
no_license
package com.hdc.service; import java.io.Serializable; import java.util.List; import com.hdc.entity.Page; import com.hdc.entity.Parameter; import com.hdc.entity.Role; public interface IRoleService { public List<Role> getRoleListPage(Parameter param, Page<Role> page) throws Exception; public List<Role> getRoleList() throws Exception; public Role getRoleById(String id) throws Exception; public Serializable doAdd(Role role) throws Exception; public void doUpdate(Role role) throws Exception; public void saveOrUpdate(Role role) throws Exception; public void doDelete(String id) throws Exception; }
Markdown
UTF-8
1,353
3.203125
3
[]
no_license
# pyqt_simple_memo ## 1. What is this <img src="./sample.jpg"></img><br/> This is a simple Memo App made using PyQt5. * * * ## 2. What can this app do Records the date of creation and modification of the memo, and displays a list of memos saved by the app itself.</br> This program manages memo data in xml standard.</br> Each memo is given a unique serial using uuid.</br> The schema of the saved memo is as follows.</br> ```xml <memos> <memo no="a38af062-6771-400c-83b3-ef13676272c5" title="new memo example 1" c_date="2021-02-03 16:38:06" m_date="2021-02-03 17:47:22"> <content>this is test memo example 1</content> </memo> <memo no="14096883-949a-4d88-8a70-46f007f68137" title="new memo example 2" c_date="2021-02-03 16:38:06" m_date="2021-02-03 17:47:28"> <content>this is test memo example 2</content> </memo> <memo no="cf271045-fe0b-40fa-95ad-eb3171aa03d3" title="new memo example 3" c_date="2021-02-03 17:27:34" m_date="2021-02-03 17:47:34"> <content>this is test memo example 3</content> </memo> </memos> ``` * * * ## 3. Install required packages - Python3+ (The version of Python used when making this program is 3.9) - PyQt (PyQt5) - Pyinstaller If you want to build this source, run this command in your project's directory. <pre><code>pyinstaller --onefile --windowed main.py</code></pre>
TypeScript
UTF-8
4,484
2.515625
3
[]
no_license
/* eslint-disable no-console */ import { useState, useEffect } from 'react'; import useReactRouter from 'use-react-router'; import { Post } from 'entity/entity/post'; import { SortType, SortTypes } from 'entity/union/sortType'; import { searchPostList } from 'api/posts/searchPostList'; import { SearchParam, SearchParams } from 'constants/searchParams'; import { COUNT_PER_PAGE } from 'constants/countPerPage'; import { INITIAL_SEARCH_PARAM } from 'constants/initialSearchParam'; export interface OrderInterface { id: number; name: string; } export const useEnhancer = () => { const [posts, setPosts] = useState<Post[]>([]); const [isLoading, setIsLoading] = useState<boolean>(true); const [isSorting, setIsSorting] = useState<boolean>(false); const { history, location } = useReactRouter(); const params = new URLSearchParams(location.search); const [isLastPage, setIsLastPage] = useState<boolean>(false); const [isMoreLoading, setIsMoreLoading] = useState<boolean>(false); const [postLength, setPostLength] = useState<number>(0); const [sortType, setSortType] = useState<SortType>(SortTypes.NEWEST); const [page, setPage] = useState<number>(1); const [searchWord, setWord] = useState<string>(''); const [searchCategoryIds, setSearchCategoryIds] = useState<number[]>([]); const [searchGameIds, setSearchGameIds] = useState<number[]>([]); const getParams = (): SearchParam => { const param: SearchParam = { ...INITIAL_SEARCH_PARAM }; const order = params.get(SearchParams.ORDER); if (order != null) { const orderNum: SortType = +order as SortType; setSortType(orderNum); param.order = orderNum; } const word = params.get(SearchParams.WORD); if (word != null) { setWord(word); param.word = word; } const category = params.get(SearchParams.CATEGORY); if (category != null) { setSearchCategoryIds([Number(category)]); param.category = [Number(category)]; } const game = params.get(SearchParams.GAME); if (game != null) { setSearchGameIds([Number(game)]); param.game = [Number(game)]; } // const order = params.get(SearchParams.ORDER); // if (order != null) { // const orderNum: SortType = +order as SortType; // searchParam.order = orderNum; // setSortType(SortTypeRelation[orderNum]); // } return param; }; const pushPostDetailPage = (postId: number) => { history.push({ pathname: `/post/${postId}`, }); }; useEffect(() => { (async () => { const param = getParams(); setIsSorting(true); try { await search(param); } finally { setIsLoading(false); setIsSorting(false); (async () => { })(); } })(); }, [location.search]); useEffect(() => { if (posts.length > 0) { let searchCondition = `order=${sortType}`; if (searchCategoryIds.length !== 0) searchCondition += `&category=${searchCategoryIds[0]}`; if (searchGameIds.length !== 0) searchCondition += `&game=${searchGameIds[0]}`; searchCondition += `&word=${searchWord}`; history.push({ pathname: 'search', search: `?${searchCondition}`, }); } }, [sortType]); const search = async (param: SearchParam) => { setPosts([]); try { const res = await searchPostList(1, param.per, param.game, param.category, param.order, param.word); setIsLastPage(false); setPosts(res.posts); setPostLength(res.posts.length); checkLastPage(res.posts); setPage(2); } catch (e) { console.debug(e); } }; const checkLastPage = (postList: Post[]) => { if (postList.length < COUNT_PER_PAGE) { setIsLastPage(true); } }; const loadMore = async () => { setIsMoreLoading(true); try { const param = getParams(); const res = await searchPostList(page, COUNT_PER_PAGE, param.game, param.category, param.order, param.word); setPosts([...posts, ...res.posts]); setPostLength((l) => l + res.posts.length); setIsLoading(false); setPage(page + 1); checkLastPage(res.posts); setIsMoreLoading(false); } catch (e) { console.debug(e); } finally { setIsLoading(false); } }; return { posts, isLoading, loadMore, isLastPage, isMoreLoading, postLength, setSortType, search, isSorting, sortType, pushPostDetailPage }; };
Java
UTF-8
3,742
2.15625
2
[]
no_license
package ie.hodmon.computing.service_manager.controller; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.Arrays; import java.util.List; import ie.hodmon.computing.service_manager.R; import ie.hodmon.computing.service_manager.connection.ConnectionAPI; import ie.hodmon.computing.service_manager.model.CustomerProduct; import ie.hodmon.computing.service_manager.model.Job; import ie.hodmon.computing.service_manager.model.Report; public class ProductHistory extends ClassForCommonAttributes implements AdapterView.OnItemClickListener { private ListView jobListView; private List<Job> jobs; private TextView title; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_history); Log.v("check email", "email: " + engineerEmail); title=(TextView)findViewById(R.id.jobHistoryTitle); title.setText("Previous Jobs for this Product"); jobListView =(ListView)findViewById(R.id.productHistoryListView); jobListView.setOnItemClickListener(this); Log.v("productHistory","getting jobs for "+getIntent().getStringExtra("customer_product_id")); new GetCustomerProduct(this).execute("/customer_products/"+getIntent().getStringExtra("customer_product_id")); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_callout_screen, menu); return true; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Job c=(Job)parent.getItemAtPosition(position); Intent intent = new Intent(this, ReportScreen.class); intent.putExtra("id",""+c.getId()); startActivity(intent); } @Override public void onDestroy() { super.onDestroy(); } private class GetCustomerProduct extends AsyncTask<String, Void, CustomerProduct> { protected ProgressDialog dialog; protected Context context; public GetCustomerProduct(Context context) { this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); this.dialog = new ProgressDialog(context, 1); this.dialog.setMessage("Retrieving History"); this.dialog.show(); } @Override protected CustomerProduct doInBackground(String... params) { try { Log.v("REST", "Getting Jobs"); return (CustomerProduct) ConnectionAPI.getCustomerProduct((String) params[0]); } catch (Exception e) { Log.v("REST", "ERROR : " + e); e.printStackTrace(); } return null; } @Override protected void onPostExecute(CustomerProduct result) { super.onPostExecute(result); jobs= Arrays.asList(result.getJobs()); ProductHistoryAdapter adapterForCalloutListView =new ProductHistoryAdapter(ProductHistory.this, jobs); jobListView.setAdapter(adapterForCalloutListView); if (dialog.isShowing()) { dialog.dismiss(); } } } }
C++
UTF-8
3,405
3.484375
3
[]
no_license
#include<iostream> #include<conio.h> #define col 3 using namespace std; bool getInputAndSetCell(char[][col], bool); void showBoard(char[][col]); bool rowAndColomnsame(char[][3]); bool ifDiagonalSame(char[][col]); void playGame(void); int main() { char ch; do { playGame(); cout << "\n\nDo you want to play again...." << "\nY-Yes" << "\nN-No"; ch = _getch(); } while (ch == 'Y' || ch == 'y'); return 0; } bool getInputAndSetCell(char board[][col], bool playerOne) { bool error = false; int row, colomn; if (playerOne) cout << "\nPlayer One Turn : " << endl; else cout << "\nPlayer Two Turn : " << endl; do { if (error) cout << "\nError : This position already marked or Invalid input..\n\n"; cout << "Enter row and colomn position seprated by space : "; cin >> row >> colomn; error = true; } while (row < 0 || colomn < 0 || board[row][colomn] != '*'); if (playerOne) { board[row][colomn] = 'X'; playerOne = false; } else { board[row][colomn] = 'O'; playerOne = true; } return playerOne; } void showBoard(char board[][col]) { cout << "\n\n"; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << board[i][j] << "\t"; } cout << endl << endl; } } bool rowAndColomnsame(char board[][col]) { if (board[0][0] == 'O' || board[0][0] == 'X') { if (board[0][0] == board[1][0] && board[0][0] == board[2][0]) //ist colomn return true; //else return false; } if (board[0][1] == 'O' || board[0][1] == 'X') { if (board[0][1] == board[1][1] && board[0][1] == board[2][1]) //2nd colomn return true; //else return false; } if ((board[0][2] == 'O') || (board[0][2] == 'X')) { //3rd colomn if ((board[0][2] == board[1][2]) && (board[0][2] == board[2][2])) return true; //else return false; } if (board[0][0] == 'O' || board[0][0] == 'X') { if (board[0][0] == board[0][1] && board[0][0] == board[0][2]) //ist row return true; //else return false; } if (board[1][0] == 'O' || board[1][0] == 'X') { if (board[1][0] == board[1][1] && board[1][0] == board[1][2]) //2nd row return true; //else return false; } if (board[2][0] == 'O' || board[2][0] == 'X') { if (board[2][0] == board[2][1] && board[2][0] == board[2][2]) //3rd row return true; //else return false; } else return false; } bool ifDiagonalSame(char board[][col]) { if (board[0][0] == 'O' || board[0][0] == 'X') { if (board[0][0] == board[1][1] && board[0][0] == board[2][2]) //primary diagonal return true; //else return false; } if (board[0][2] == 'O' || board[0][2] == 'X') { if (board[0][2] == board[1][1] && board[0][2] == board[2][0]) //secondary diagonal return true; //else return false; } else return false; } void playGame(void) { int count = 0; bool playerOne = true, winner = false; char board[col][col]; system("cls"); cout << "\t\t\tTic-Tac-Toe Game\n\n\n"; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) board[i][j] = '*'; showBoard(board); do { playerOne = getInputAndSetCell(board, playerOne); count++; showBoard(board); if (count > 4) { winner = ifDiagonalSame(board); if (!winner) winner = rowAndColomnsame(board); if (winner) { if (!playerOne) cout << "\nPlayer One Wins..\n"; else cout << "\nPlayer Two Wins..\n"; } } } while (!winner && count != 9); if (count == 9) cout << "\nGame Draw..."; }
Java
UTF-8
643
1.765625
2
[]
no_license
package com.cpone.platform.api.repository.traceplan; import com.cpone.platform.api.domain.bzb.TraceplanSku; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import javax.transaction.Transactional; /** * Created by Sitthi */ public interface TraceplanSkuRepo extends JpaRepository<TraceplanSku, Integer> { //List<TraceplanSku> findByTraceplan(Traceplan traceplan); @Modifying @Transactional @Query("delete from TraceplanSku w where w.traceId = ?1") void deleteByTraceId(Integer traceId); }
Python
UTF-8
9,114
3.21875
3
[]
no_license
# ------------------------------------------------------------------------------ # FOURIER OPTICS DEMONSTRATION # Language: Python 3 # ------------------------------------------------------------------------------ # Calculates the optical intensity on a screen due to aperture diffraction. # The complex scalar field u(x,y) in the source plane is a concave sperical # phasefront (ROC=0.5 m) passing through a circular aperture. The resulting # complex scalar field amplitude u'(x',y') in the "field plane" is calculated # via Fourier transform. # ------------------------------------------------------------------------------ import numpy as np import numpy.matlib as npm import matplotlib.pyplot as plt # -------------------- # Physical Parameters # -------------------- c = 3e8 # speed of light in m/s epsilon0 = 8.854e-12 # vacuum permittivity in F/m lam = 633e-9 # optical wavelength in m # ------------- # Source plane # ------------- xmax=0.002 # Src plane area: 4*xmax*ymax m^2 ymax=xmax Nx = int(2**np.ceil(np.log2(np.abs(512)))) # number of pixels in source plane grid is Nx*Ny Ny = int(2**np.ceil(np.log2(np.abs(512)))) # (2**... etc gives next power of two for speed) dxp = 2*xmax/(Nx-1); dyp=2*ymax/(Ny-1) # interpixel dist. in the src plane (m) xp = npm.repmat( ((np.arange(0,Nx))-np.floor(Nx/2)) *dxp, Ny,1) # x' values at which to calc. source field yp = np.transpose(npm.repmat( ((np.arange(0,Ny))-np.floor(Ny/2)) *dyp, Nx,1)); # and y' values # ----------------------- # ABCD Matrix Components # ----------------------- # Optical system consists of [ FREE SPACE : LENS : FREE SPACE ]. L1 = 0.035 ;#0.1e-3; # aperture-lens dist. in m L2 = 0.05; # lens-screen dist. in m f = -0.03; # f=Inf corresponds to no lens M = np.array([[1,L2],[0,1]]) \ @ np.array([[1,0],[-1/f,1]]) \ @ np.array([[1,L1],[0,1]]) # ABCD matrix of the system AA = M[0,0]; BB = M[0,1]; CC = M[1,0]; DD = M[1,1]; # The components A, B, C, D # --------- # Aperture # --------- # Field amplitude is non-zero at these values of x, y (i.e. where it passes # through the aperture). The apertures are defined as logical matrixes that # are used to index the source field distribution, i.e. Usource(~aperture)=0; # UIsource(aperture)= <something nonzero>. #a = 50*1e-6; # circular obstrution diam. (m) #b = 600e-6; # off-center scale factor #aperture = (xp+0.75*b)**2+(yp-0.35*b)**2 > (a/2)**2 # circular obstruction logical mask a = 3000*1e-6; # triangle side length (m) aperture = np.logical_and.reduce([(yp<np.sqrt(3)*xp+a/2/np.sqrt(3)), \ (yp<-np.sqrt(3)*xp+a/2/np.sqrt(3)), \ (yp>-a/2/np.sqrt(3))]) # equil. triangular aperture #a = 300e-6 # triangle side length (m) #b = 600e-6 # off-center scale factor #aperture = np.logical_not(np.logical_and.reduce(\ # [((yp-0.35*b)<np.sqrt(3)*(xp+0.75*b)+a/2/np.sqrt(3)), \ # ((yp-0.35*b)<-np.sqrt(3)*(xp+0.75*b)+a/2/np.sqrt(3)), \ # ((yp-0.35*b)>-a/2/np.sqrt(3))])) # equil. triangular aperture # equil. triangular obstruction # ------------- # Source Field # ------------- # Here, the incident field is assumed to be a Gaussian beam of width "w" # and radius of curvature "roc". The beam is clipped by the apeture. roc = 0.5; # R.O.C. of phasefront at src plane (m) w = 750e-6; # beam width of incident beam (m) I0 = 7617.5; # max src plane intensity (W/m^2) E0 = np.sqrt(2*I0/c/epsilon0); # m ax field ampl. in src plane (N/C) k = 2*np.pi/lam; # wave number r = np.sqrt(xp**2+yp**2); # src plane coordss dist from center usource = E0*np.exp(-r**2/w**2)*np.exp(1j*k*r**2/2/roc); # field ampl. in src plane usource[np.logical_not(aperture)]=0; # field is zero except in the aperture Isource = epsilon0*c/2*np.abs(usource)**2; # Intensity in the source plane (W/m^2) # ======================================================================================== # |+|+|+|+| THE COMPUTATION OCCURS BETWEEN THIS LINE AND THE ONE LIKE IT BELOW |+|+|+|+| # ======================================================================================== # h, below is a scale factor to change from the physical units (meters) to new units in # which all physical lengths are scaled by h=sqrt(B*lam). In the new units, the Fresnel # integral becomes a standard Fourier transform multiplied by a phase factor. We now scale # all physical lengths to the new units before performing the fourier tranform. Due to the # limitations placed on variable names, x' in the text is the variable f here, y' is g, # X' is F, and Y' is G. h = np.sqrt(BB*lam); # scaling factor dXp = dxp/h; dYp = dyp/h; # src interpixel dist in the new units Xp = xp/h; # src plane x-coords scaled to new units Yp = yp/h; # src plane y-coords scaled to new units dX = 1/dXp/Nx; dY = 1/dYp/Ny; # corresponding spatial sampling interval # in field plane after 2 dim. FFT (fft2). X=npm.repmat((np.arange(0,Nx)-np.floor(Nx/2)) *dX,Ny,1); # Field plane, x-domain (in scaled length) Y=np.transpose(npm.repmat((np.arange(0,Ny)-np.floor(Ny/2)) *dY,Nx,1)); # and y-domain dx=dX*h; dy=dY*h; # field plane sampling interval (in meters) x = X*h; y = Y*h; # Field plane, x and y-domains (in meters) # Perform 2D FFT on and scale correctly # ------------------------------------- ufield = \ -1j*np.exp(1j*np.pi*DD/BB/lam*((x)**2+(y)**2)) \ *np.fft.fftshift(np.fft.fft2(np.exp(1j*np.pi*AA*(Xp**2+Yp**2))*usource )*dXp*dYp ) # FT2 Ifield = epsilon0*c/2*np.abs(ufield)**2; # get the intensity # ======================================================================================== # |+|+|+|+| CODE BELOW CHECKS AND DISPLAYS THE RESULTS |+|+|+|+|+|+|+|+|+|+|+|+|+|+|+|+|+| # ======================================================================================== # Check energy conservation # ------------------------- inpow = np.trapz(np.trapz(Isource))*dxp*dxp; # integral of intensity in the src plane outpow = np.trapz(np.trapz(Ifield))*dx*dy; # (total power) should equal field plane print('Power in the source plane: Pin = '+"%8.4f" % ( inpow*1000)+' mW'); print('Power in the field plane: Pout = '+"%8.4f" % (outpow*1000)+' mW'); # Display source plane intensity (Fig. 1) # --------------------------------------- fig1 = plt.figure(1) # open figure 1 plt.clf() # clear it in case previously used ax1 = plt.axes() # define a set of axes c1 = ax1.pcolormesh(xp*1e3,yp*1e3,Isource/1000, cmap='copper') # plot the source plane irradiance ax1.set_aspect('equal', 'box') # set aspect ratio to be correct ax1.set_title('Source Plane Irradiance') # add a title plt.xlabel('x (mm)') # label x axis plt.ylabel('y (mm)') # label y axis c1bar = fig1.colorbar(c1) # add a colorbar c1bar.set_label('Irradiance (mW/mm$^2$)', rotation=90) # label the colorbar plt.show() # display the plot # Display field plane intensity (Fig. 2) # -------------------------------------- fig2 = plt.figure(2) # open figure 2 plt.clf() # clear it in case previously used ax2 = plt.axes() # define a set of axes c2 = ax2.pcolormesh(x*1e3,y*1e3,Ifield/1000, cmap='copper') # plot the field plane irradiance ax2.set_aspect('equal', 'box') # set aspect ratio to be correct ax2.set_title('Field Plane Irradiance') # add a title plt.xlabel('x (mm)') # label x axis plt.ylabel('y (mm)') # label y axis c2bar = fig2.colorbar(c2) # add a color bar c2bar.set_label('Irradiance (mW/mm$^2$)', rotation=90) # label the colorbar plt.show() # display the plot
Java
UTF-8
3,509
2.21875
2
[]
no_license
/* * The contents of this file are subject to the terms of the Common Development * and Distribution License (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at http://www.netbeans.org/cddl.html * or http://www.netbeans.org/cddl.txt. * * When distributing Covered Code, include this CDDL Header Notice in each file * and include the License file at http://www.netbeans.org/cddl.txt. * If applicable, add the following below the CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun * Microsystems, Inc. All Rights Reserved. */ package test.convolve; import java.awt.Point; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import org.netbeans.api.visual.action.ActionFactory; import org.netbeans.api.visual.layout.LayoutFactory; import org.netbeans.api.visual.widget.ConvolveWidget; import org.netbeans.api.visual.widget.ImageWidget; import org.netbeans.api.visual.widget.LabelWidget; import org.netbeans.api.visual.widget.LayerWidget; import org.netbeans.api.visual.widget.Scene; import org.netbeans.api.visual.widget.Widget; import org.openide.util.Utilities; import test.SceneSupport; /** * @author David Kaspar */ public class ConvolveTest extends Scene { Kernel blurKernel = new Kernel(5, 5, new float[] { 0.00f, 0.00f, 0.05f, 0.00f, 0.00f, 0.00f, 0.05f, 0.10f, 0.05f, 0.00f, 0.05f, 0.10f, 0.20f, 0.10f, 0.05f, 0.00f, 0.15f, 0.10f, 0.05f, 0.00f, 0.00f, 0.00f, 0.05f, 0.00f, 0.00f, }); Kernel dropShadowKernel = new Kernel(5, 5, new float[] { 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 1.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.30f, }); private LayerWidget layer; public ConvolveTest() { layer = new LayerWidget(this); addChild(layer); createNormalWidget(50, 50, "This is normal Widget - no effect"); createConvolveWidget(blurKernel, 100, 150, "This is ConvolveWidget - the image with label has to be blurred"); createConvolveWidget(dropShadowKernel, 150, 250, "This is ConvolveWidget - the image with label has to drop shadow"); } private void createNormalWidget(int x, int y, String text) { Widget widget = new Widget(this); widget.setLayout(LayoutFactory.createVerticalFlowLayout()); widget.setPreferredLocation(new Point(x, y)); widget.getActions().addAction(ActionFactory.createMoveAction()); layer.addChild(widget); widget.addChild(new ImageWidget(this, Utilities.loadImage("test/resources/displayable_64.png"))); // NOI18N widget.addChild(new LabelWidget(this, text)); } private void createConvolveWidget(Kernel kernel, int x, int y, String text) { ConvolveWidget convolve = new ConvolveWidget(this, new ConvolveOp(kernel)); convolve.setLayout(LayoutFactory.createVerticalFlowLayout()); convolve.setPreferredLocation(new Point(x, y)); convolve.getActions().addAction(ActionFactory.createMoveAction()); layer.addChild(convolve); convolve.addChild(new ImageWidget(this, Utilities.loadImage("test/resources/displayable_64.png"))); // NOI18N convolve.addChild(new LabelWidget(this, text)); } public static void main(String[] args) { SceneSupport.show(new ConvolveTest()); } }
C++
UTF-8
2,330
3.109375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef struct No { int val; struct No *dir; struct No *esq; } No; int N, i; No *pesquisa(No *r, int v) { if (!r) return r; if (r->val == v) return r; if (r->val > v) return pesquisa(r->esq, v); return pesquisa(r->dir, v); } void insere(No **r, int v) { if (!*r) { *r = (No *)malloc(sizeof(No)); (*r)->dir = NULL; (*r)->esq = NULL; (*r)->val = v; N++; return; } if (v > (*r)->val) insere(&(*r)->dir, v); else insere(&(*r)->esq, v); } void remover(No **r, int v) { if (!*r) return; if ((*r)->val != v) { if ((*r)->val > v) remover(&(*r)->esq, v); else remover(&(*r)->dir, v); return; } if (!(*r)->dir && !(*r)->esq) { free(*r); *r = NULL; N--; return; } No *aux; if (!(*r)->dir) { aux = (*r)->esq; free(*r); *r = aux; N--; } else if (!(*r)->esq) { aux = (*r)->dir; free(*r); *r = aux; N--; } else { No **m = &(*r)->esq; while ((*m)->dir) { m = &(*m)->dir; } (*r)->val = (*m)->val; remover(m, (*m)->val); } } void imprime(No *r) { i++; printf("%d", r->val); if (i != N) printf(" "); else printf("\n"); } void pre(No *r) { if (!r) return; imprime(r); pre(r->esq); pre(r->dir); } void pos(No *r) { if (!r) return; pos(r->esq); pos(r->dir); imprime(r); } void em(No *r) { if (!r) return; em(r->esq); imprime(r); em(r->dir); } int main() { int C; scanf(" %d", &C); for (int j = 1; j <= C; j++) { No *r = NULL; int n, aux; scanf(" %d", &n); N = 0; while (n--) { scanf(" %d", &aux); insere(&r, aux); } printf("Case %d:\n", j); printf("Pre.: "); i = 0; pre(r); printf("In..: "); i = 0; em(r); printf("Post: "); i = 0; pos(r); printf("\n"); } return 0; }
Markdown
UTF-8
1,055
2.75
3
[]
no_license
### 无用的 CSS 如何删除 - `purifyCss`: 遍历代码,识别已经用到的 CSS class - `uncss`: HTML 通过 jsdom 加载,所有的样式通过 PostCSS 解析,通过 document.querySelector 来识别在 html 文件里面不存在的选择器 #### 在 webpack 中如何使用 PurifyCSS - 使用 [purgecss-webpack-plugin](https://github.com/FullHuman/purgecss-webpack-plugin) - 加上 mini-css-extract-plugin 配合使用(必须和将css单独提取成文件的插件配合使用) 代码: ~~~ const PATHS = { src: path.join(__dirname, 'src') } module.exports = { module:{ rules: [ { test: /\.css$/, use: [ MiniCssWebpackPlugin.loader, 'css-loader' ] } ] }, plugins: [ new MinCssWebpackPlugin({ filename: '[name].css' }), new PurgecssPlugin({ path: glob.sync(`${PATHS.src}/**/*`, //path 必须是绝对路径 {nodir: true}) }) ] } ~~~
Java
UTF-8
1,009
3.578125
4
[]
no_license
import java.util.ArrayList; import java.util.Arrays; public class selectionSort { public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList(Arrays.asList(1, 32, 13, 56, 6)); System.out.println(selectionSort(arr)); } public static int findSmallest(ArrayList<Integer> arr) { int smallest = arr.get(0); Integer smallest_index = 0; for (int i=1; i<arr.size(); i++) { if (arr.get(i) < smallest) { smallest = arr.get(i); smallest_index = i; } } return smallest_index; } public static ArrayList<Integer> selectionSort(ArrayList<Integer> arr) { int smallest; ArrayList<Integer> newArr = new ArrayList<>(); int arraySize = arr.size(); for (int i=0; i<arraySize;i++) { smallest = findSmallest(arr); newArr.add(arr.get(smallest)); arr.remove(smallest); } return newArr; } }
Python
UTF-8
156
3.6875
4
[]
no_license
num1 = int(input("Enter the lower limit")) num2 = int(input("Enter the upper limit")) i = num1 while(i<=num2): if(i%2==0): print(i) i+=1
Go
UTF-8
403
2.96875
3
[]
no_license
package expression import "fmt" type Number struct { Value int64 } func (number Number) String() string { return fmt.Sprintf("%d", number.Value) } func (number Number) Inspect() string { return fmt.Sprintf("<%d>", number.Value) } func (number Number) Reduce(environment map[string]Expression) Expression { panic("don't reduce number") } func (number Number) Reducable() bool { return false }
JavaScript
UTF-8
3,558
2.875
3
[]
no_license
import React, { Component } from 'react'; import Cell from './Cell'; import presets from '../preset'; import '../styles/Board.css'; class Board extends Component { constructor(props) { super(props); this.state = { cells: [] } } componentDidMount() { this.setupBoard() } setupBoard = () => { var cells = []; for (let i=0; i<900; i++) {cells.push(0)} switch(this.props.template) { case 'glider': for (let i=0; i<presets.glider.length; i++) {cells[presets.glider[i]] = 1;} break; case 'small_exploder': for (let i=0; i<presets.small_exploder.length; i++) {cells[presets.small_exploder[i]] = 1;} break; case 'exploder': for (let i=0; i<presets.exploder.length; i++) {cells[presets.exploder[i]] = 1;} break; case 'spaceship': for (let i=0; i<presets.spaceship.length; i++) {cells[presets.spaceship[i]] = 1;} break; case 'random': for (let i=0; i<presets.random.length; i++) {cells[presets.random[i]] = 1;} break; default: break; } this.setState({ cells }); } // Calculates neighbors and returns next state updateCells = () => { const cells = this.state.cells.map((cell, index) => { let neighbors = 0 const length = Math.sqrt(this.state.cells.length) const row = Math.floor(index/length) const col = index-(row*length) // Calculate neighbors if (this.isAlive(row-1, col)) neighbors +=1 if (this.isAlive(row-1, col+1)) neighbors +=1 if (this.isAlive(row-1, col-1)) neighbors +=1 if (this.isAlive(row, col+1)) neighbors +=1 if (this.isAlive(row, col-1)) neighbors +=1 if (this.isAlive(row+1, col)) neighbors +=1 if (this.isAlive(row+1, col+1)) neighbors +=1 if (this.isAlive(row+1, col-1)) neighbors +=1 // Returns cells next state if (cell === 1) { if(neighbors < 2) return 0 if(neighbors > 3) return 0 if(neighbors === 3 || neighbors === 2) return 1 } else { if(neighbors === 3) return 1 } return cell }) this.setState({ cells }) // this.props.handleGen(); } // Used to check if a cell is alive isAlive = (row, col) => { const length = Math.sqrt(this.state.cells.length); if (row === -1) row = length - 1 if (row === length) row = 0 if (col === -1) col = length -1 if (col === length) col = 0 const cell = (row*length)+col return this.state.cells[cell] } // Changes a cell dead/alive when clicked handleClick = (id) => { const cells = this.state.cells; cells[id] = (cells[id]+1) & 1 this.setState({ cells }) } componentDidUpdate(previousProps) { // Checks if clear has been clicked if (this.props.clear === true && previousProps !== this.props) { this.setupBoard() this.props.handleClear() } if (this.props.template !== '' && previousProps !== this.props) { this.setupBoard(); this.props.handleStopTem(); } // Starts/stops the game from running(Invokes updateCells) let celInt = 0; if (this.props.running === true) {celInt = setTimeout(this.updateCells, this.props.speed) } if (this.props.running === false) {clearTimeout(celInt)} } // Creates cell components for render createCells = () => { return this.state.cells.map((cell, index) => ( <Cell key={index} id={index} value={cell} handleClick={this.handleClick} /> )) } render() { return ( <div className='board'> {this.createCells()} </div> ); } } export default Board;
C++
UTF-8
495
2.578125
3
[]
no_license
#ifndef GRIDPOINT_H_ #define GRIDPOINT_H_ #include "util.h" using namespace trimesh; class GridPoint { public: float opacity; vec3_d color; GridPoint(); GridPoint(float opacity, vec3_d color); bool isEmpty() const; }; inline GridPoint::GridPoint() : opacity(0.0f), color(vec3_d(0, 0, 0)) { } inline GridPoint::GridPoint(float opacity, vec3_d color) : opacity(opacity), color(color) { } inline bool GridPoint::isEmpty() const { return (opacity == 0.0f); } #endif /* DATAPOINT_H_ */
Markdown
UTF-8
2,590
2.796875
3
[ "MIT", "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
--- title: ChartGroups object (Excel) keywords: vbaxl10.chm569072 f1_keywords: - vbaxl10.chm569072 ms.prod: excel api_name: - Excel.ChartGroups ms.assetid: 991147bc-bbb5-9f7d-a7c9-55854aa50325 ms.date: 03/29/2019 ms.localizationpriority: medium --- # ChartGroups object (Excel) Represents one or more series plotted in a chart with the same format. ## Remarks A **ChartGroups** collection is a collection of all the **[ChartGroup](Excel.ChartGroup(object).md)** objects in the specified chart. A chart contains one or more chart groups, each chart group contains one or more **[Series](Excel.Series(object).md)** objects, and each series contains one or more **[Points](Excel.Point(object).md)** objects. For example, a single chart might contain both a line chart group, containing all the series plotted with the line chart format, and a bar chart group, containing all the series plotted with the bar chart format. Use the **[ChartGroups](excel.chart.chartgroups.md)** method of the **Chart** object to return the **ChartGroups** collection. The following example displays the number of chart groups on embedded chart 1 on worksheet 1. ```vb MsgBox Worksheets(1).ChartObjects(1).Chart.ChartGroups.Count ``` Use **ChartGroups** (_index_), where _index_ is the chart-group index number, to return a single **ChartGroup** object. The following example adds drop lines to chart group 1 on chart sheet 1. ```vb Charts(1).ChartGroups(1).HasDropLines = True ``` If the chart has been activated, you can use **ActiveChart**. ```vb Charts(1).Activate ActiveChart.ChartGroups(1).HasDropLines = True ``` Because the index number for a particular chart group can change if the chart format used for that group is changed, it may be easier to use one of the named chart group shortcut methods to return a particular chart group. The **[PieGroups](excel.piegroups.md)** method returns the collection of pie chart groups in a chart, the **[LineGroups](excel.linegroups.md)** method returns the collection of line chart groups, and so on. Each of these methods can be used with an index number to return a single **ChartGroup** object, or without an index number to return a **ChartGroups** collection. ## Methods - [Item](Excel.ChartGroups.Item.md) ## Properties - [Application](Excel.ChartGroups.Application.md) - [Count](Excel.ChartGroups.Count.md) - [Creator](Excel.ChartGroups.Creator.md) - [Parent](Excel.ChartGroups.Parent.md) ## See also - [Excel Object Model Reference](overview/Excel/object-model.md) [!include[Support and feedback](~/includes/feedback-boilerplate.md)]
C++
UTF-8
989
2.8125
3
[ "MIT" ]
permissive
#pragma once #include <mw/mmr/MMRInfo.h> #include <mw/interfaces/db_interface.h> // Forward Declarations class Database; class MMRInfoDB { public: MMRInfoDB(mw::DBWrapper* pDBWrapper, mw::DBBatch* pBatch = nullptr); ~MMRInfoDB(); /// <summary> /// Retrieves an MMRInfo by index. /// </summary> /// <param name="index">The index of the MMRInfo to retrieve.</param> /// <returns>The MMRInfo for the given index. nullptr if not found.</returns> std::unique_ptr<MMRInfo> GetByIndex(const uint32_t index) const; /// <summary> /// Retrieves the latest MMRInfo. /// </summary> /// <returns>The latest MMRInfo. nullptr if none are found.</returns> std::unique_ptr<MMRInfo> GetLatest() const; /// <summary> /// Saves by index and also saves the entry as the latest. /// </summary> /// <param name="info">The MMR info to save</param> void Save(const MMRInfo& info); private: std::unique_ptr<Database> m_pDatabase; };
Markdown
UTF-8
322
2.96875
3
[]
no_license
# MagicSquare # The program will take in a user input that should be a positive odd number # The code's output verifies that the 'magic square' calculation is correct or not, # while verifying if the user's input is correct as well # In the square format: each row, column and diagonals should add up to the same number
C++
UTF-8
249
2.78125
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; int main() { int x, n; cin >> x >> n; int y; int rest = x; for (int i = 0; i < n; i++) { cin >> y; if (rest + x > y) rest = rest + x - y; else rest = 0; } cout << rest << endl; }
Java
UTF-8
8,509
2.34375
2
[]
no_license
package cn.weili.love.biz.service.comply; import cn.weili.bridge.context.BridgeException; import cn.weili.love.biz.data.*; import cn.weili.love.biz.exception.LoveException; import cn.weili.love.biz.form.RegisterForm; import cn.weili.love.biz.service.support.BizService; import cn.weili.love.biz.service.UserService; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import static cn.weili.util.SecurityUtil.md5; /** * LocalUserService * * 本站用户的userServie实现类 * * Created with IntelliJ IDEA. * User: canden * Date: 5/3/13 * Time: 2:05 PM * * To change this template use File | Settings | File Templates. */ public class LocalUserService extends BizService implements UserService { private final Logger logger = LoggerFactory.getLogger(getClass()); /** * loadUserDO * <p/> * 根据userNick和userFrom加在单个用户基本信息 * * @param userNick * @param userFrom * @return UserDO * @throws cn.weili.love.biz.exception.LoveException * */ @Override public UserDO loadUserDO(String userNick, UserFrom userFrom) throws LoveException { if(StringUtils.isBlank(userNick) || userFrom==null) return null; Map<String,String> parameterMap = new HashMap<String, String>(2); parameterMap.put("userNick",userNick.toLowerCase()); parameterMap.put("userFrom",userFrom.toString()); try { return getDbService().loadData(NameSpace.user.toString(),"loadUserDOByNick",parameterMap); } catch (BridgeException e) { logger.error(e.getMessage(), e); throw new LoveException("根据userNick和userFrom加在单个用户基本信息异常",e); } } /** * loadUserDO * * @param userId * @return * @throws cn.weili.love.biz.exception.LoveException * */ @Override public UserDO loadUserDO(int userId) throws LoveException { try { return getDbService().loadData(NameSpace.user.toString(),"loadUserDOById",userId); } catch (BridgeException e) { logger.error(e.getMessage(),e); throw new LoveException("根据 userId:["+userId+"],加载用户基本信息异常",e); } } /** * validateLogin * * @param userNick * @param password * @param component * @return ResultDO<UserDO> * @throws cn.weili.love.biz.exception.LoveException * */ @Override public ResultDO<UserDO> validateLogin(String userNick, String password,Component component) throws LoveException { if(StringUtils.isBlank(userNick) || StringUtils.isBlank(password)) return BizContext.emptyResultDO(); //判断该帐户是否存在 ResultDO<UserDO> resultDO = new ResultDO<UserDO>(); UserDO userDO = loadUserDO(userNick,UserFrom.love); if(userDO==null){ resultDO.invokeFail("该帐号不存在,请检查后重新输入!"); return resultDO; } //判断密码是否正确 if(!userDO.getPassword().trim().equals(md5(password))){ resultDO.invokeFail("密码不正确,请重新输入!"); return resultDO; } //如果用户和密码都正确,那么需要判断该用户是否有登录boss系统的权限,只有admin或者waiter才可以登录boss if(component==Component.boss){ // if(!(userDO.getUserType()==UserType.admin || userDO.getUserType()==UserType.waiter // || userDO.getUserType()==UserType.sellers)){ //从0.4版本开始,只有买家不同登录boss系统 if(userDO.getUserType()==null || userDO.getUserType()==UserType.buyer){ resultDO.invokeFail("该帐户权限不够,不能登录boss系统,请使用其他帐户登录!"); return resultDO; } } resultDO.invoke(userDO); return resultDO; } /** * isLoveUser * * @param userNick * @param userFrom * @return * @throws cn.weili.love.biz.exception.LoveException * */ @Override public boolean isLoveUser(String userNick, UserFrom userFrom) throws LoveException { if(StringUtils.isBlank(userNick) || userFrom==null) return Boolean.FALSE; boolean isLoveUser = Boolean.FALSE; try { Map<String,String> map = new HashMap<String, String>(2); map.put("userNick",userNick.toLowerCase()); map.put("userFrom",userFrom.toString()); Integer id = getDbService().loadData(NameSpace.user.toString(),"loadIdByNickAndFrom",map); if(id!=null && id.intValue()>0) { isLoveUser = Boolean.TRUE; } } catch (BridgeException e) { logger.error(e.getMessage(),e); throw new LoveException("判断用户是否已经存在异常",e); } return isLoveUser; } /** * isLoveEmail * * @param email * @param userFrom * @return * @throws cn.weili.love.biz.exception.LoveException * */ @Override public boolean isLoveEmail(String email, UserFrom userFrom) throws LoveException { if(StringUtils.isBlank(email) || userFrom==null) return Boolean.FALSE; boolean isLoveEmail = Boolean.FALSE; try { Map<String,String> map = new HashMap<String, String>(2); map.put("email", email.toLowerCase()); map.put("userFrom",userFrom.toString()); Integer id = getDbService().loadData(NameSpace.user.toString(),"loadIdByEmailAndFrom",map); if(id!=null && id.intValue()>0) isLoveEmail = Boolean.TRUE; return isLoveEmail; } catch (BridgeException e) { logger.error(e.getMessage(),e); throw new LoveException("判断是否是唯一的电子邮件地址异常",e); } } /** * register * * @param registerForm * @return * @throws cn.weili.love.biz.exception.LoveException * */ @Override public ResultDO<UserDO> register(RegisterForm registerForm) throws LoveException { if(registerForm==null) return BizContext.emptyResultDO(); ResultDO<UserDO> resultDO = new ResultDO<UserDO>(); if(!registerForm.getConfirmPass().trim().equals(registerForm.getPassword().trim())){ resultDO.invokeFail("亲,两次输入的密码不一致,不能注册!"); return resultDO; } //TODO : 校验EMAIL,密码复杂程度 if(isLoveUser(registerForm.getUserNick(),UserFrom.love)){ resultDO.invokeFail("亲,该用户已经存在,不能注册!"); return resultDO; } //TODO 需要修改bridge,返回int而不是long,暂时采用重新查询一遍的方式来解决 insertUserDO(registerForm.createUserDO()); UserDO userDO = loadUserDO(registerForm.getUserNick(),UserFrom.love); resultDO.invoke(userDO); return resultDO; } /** * insertUserDO * * @param userDO * @return * @throws cn.weili.love.biz.exception.LoveException * */ @Override public void insertUserDO(UserDO userDO) throws LoveException { if(userDO==null) return; try { getDbService().insertData(NameSpace.user.toString(),"insertUserDO",userDO); } catch (BridgeException e) { logger.error(e.getMessage(),e); throw new LoveException("新增用户信息异常",e); } } /** * getUserList * * @param userTypes * @return * @throws cn.weili.love.biz.exception.LoveException * */ @Override public List<TinyUserDO> getUserList(UserType... userTypes) throws LoveException { if(userTypes==null || userTypes.length<=0) return Collections.emptyList(); try { List<String> userTypeList = new ArrayList<String>(userTypes.length); for(UserType userType : userTypes){ userTypeList.add(userType.toString()); } return getDbService().batchQueryData(NameSpace.user.toString(),"getUserListByTypes",userTypeList); } catch (BridgeException e) { logger.error(e.getMessage(),e); throw new LoveException("根据userTypes获取用户信息异常",e); } } }
Swift
UTF-8
1,064
2.75
3
[]
no_license
// // ContentView.swift // CoronaTrace // // Created by Sai Gurrapu on 3/29/20. // Copyright © 2020 Sai Gurrapu. All rights reserved. // import SwiftUI struct ContentView: View { @State private var selection = 0 var body: some View { TabView(selection: $selection){ Home() .tabItem { Image(systemName: "house.fill") Text("Home") } Image("home") .resizable() .resizable() .aspectRatio(contentMode: .fill) .padding(.top, -15) .tabItem { Image(systemName: "chart.bar.fill") Text("Trends") } Map() .tabItem { Image(systemName: "globe") Text("Live Map") } }.edgesIgnoringSafeArea(.top).font(.headline) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Python
UTF-8
834
4.0625
4
[]
no_license
""" 제목 : 시저 암호 아이디어 : 아스키 코드를 이용 - 아스키 코드의 특징 : a-z,A-Z까지 1씩 증가함 - a ~ z 사이에서 움직이는건 그냥 더해주면 됨 - z를 넘어서는 값은 나머지 연산 처리해주면 됨 - a = 53 z = 79 라고 하면, 79+1 -> 53이 되도록 구현 : 그냥 무식하게 하자 - for c in s: - c가 공백인 경우 - c가 소문자인 경우 - c가 대문자인 경우 """ def solution(s, n): answer = "" for c in s : if c == ' ': answer += c if c >= 'a' and c <= 'z': answer += chr(ord(c)+n) if chr(ord(c)+n) <= 'z' else chr(ord(c)+n-26) if c >= 'A' and c <= 'Z': answer += chr(ord(c) + n) if chr(ord(c) + n) <= 'Z' else chr(ord(c) + n - 26) return answer print(solution('z',3))
Python
UTF-8
7,333
2.65625
3
[]
no_license
# Created by: Jenny Trac # Created on: Dec 2017 # Created for: ICS3U # This scene shows the main menu. from scene import * import ui import config import sound from game_scene import * from settings_scene import * from instructions_scene import * from credits_scene import * class MainMenuScene(Scene): def setup(self): # this method is called, when user moves to this scene self.CENTRE_OF_SCREEN = self.size / 2 # add background color self.background = SpriteNode('./assets/sprites/space_background.PNG', position = self.CENTRE_OF_SCREEN, parent = self, size = self.size) # add logo to top of screen logo_position = self.CENTRE_OF_SCREEN logo_position.y = self.size.y - 170 self.space_ninja_logo = SpriteNode('./assets/sprites/space_ninja_logo.PNG', parent = self, position = logo_position, size = self.size / 1.5) # play label play_label_position = self.CENTRE_OF_SCREEN play_label_position.y = self.size.y - 300 self.play_label = LabelNode(text = "Play", font = ('ChalkboardSE-Light', 70), parent = self, position = play_label_position) # settings label settings_label_position = self.CENTRE_OF_SCREEN settings_label_position.y = self.size.y - 400 self.settings_label = LabelNode(text = "Settings", font = ('ChalkboardSE-Light', 70), parent = self, position = settings_label_position) # instructions label instructions_label_position = self.CENTRE_OF_SCREEN instructions_label_position.y = self.size.y - 500 self.instructions_label = LabelNode(text = "Instructions", font = ('ChalkboardSE-Light', 70), parent = self, position = instructions_label_position) # credits label credits_label_position = self.CENTRE_OF_SCREEN credits_label_position.y = self.size.y - 600 self.credits_label = LabelNode(text = "Credits", font = ('ChalkboardSE-Light', 70), parent = self, position = credits_label_position) # all 4 arrow buttons play_arrow_button_position = Vector2() play_arrow_button_position.x = 350 play_arrow_button_position.y = self.size.y - 300 self.play_arrow_button = SpriteNode('./assets/sprites/arrow_button.PNG', parent = self, position = play_arrow_button_position, scale = 0.15) settings_arrow_button_position = Vector2() settings_arrow_button_position.x = 285 settings_arrow_button_position.y = self.size.y - 400 self.settings_arrow_button = SpriteNode('./assets/sprites/arrow_button.PNG', parent = self, position = settings_arrow_button_position, scale = 0.15) instructions_arrow_button_position = Vector2() instructions_arrow_button_position.x = 220 instructions_arrow_button_position.y = self.size.y - 500 self.instructions_arrow_button = SpriteNode('./assets/sprites/arrow_button.PNG', parent = self, position = instructions_arrow_button_position, scale = 0.15) credits_arrow_button_position = Vector2() credits_arrow_button_position.x = 290 credits_arrow_button_position.y = self.size.y -600 self.credits_arrow_button = SpriteNode('./assets/sprites/arrow_button.PNG', parent = self, position = credits_arrow_button_position, scale = 0.15) # play background music config.background_music = sound.play_effect('./assets/sounds/backgroundMusic.mp3') self.music_start_time = time.time() def update(self): # this method is called, hopefully, 60 times a second #pass # check if sound was turned off if config.sound_setting == False: sound.stop_effect(config.background_music) # check if audio has stopped playing and play again if config.sound_setting == True and (time.time() - self.music_start_time >= 65): config.background_music = sound.play_effect('./assets/sounds/backgroundMusic.mp3') self.music_start_time = time.time() def touch_began(self, touch): # this method is called, when user touches the screen pass def touch_moved(self, touch): # this method is called, when user moves a finger around on the screen pass def touch_ended(self, touch): # this method is called, when user releases a finger from the screen # play button if self.play_arrow_button.frame.contains_point(touch.location) or self.play_label.frame.contains_point(touch.location): # make sure game status is not over and reset score config.game_over = False config.score = 0 self.present_modal_scene(GameScene()) # settings button if self.settings_arrow_button.frame.contains_point(touch.location) or self.settings_label.frame.contains_point(touch.location): self.present_modal_scene(SettingsScene()) # instructions button if self.instructions_arrow_button.frame.contains_point(touch.location) or self.instructions_label.frame.contains_point(touch.location): self.present_modal_scene(InstructionsScene()) # credits button if self.credits_arrow_button.frame.contains_point(touch.location) or self.credits_label.frame.contains_point(touch.location): self.present_modal_scene(CreditsScene()) # pass def did_change_size(self): # this method is called, when user changes the orientation of the screen # thus changing the size of each dimension pass def pause(self): # this method is called, when user touches the home button # save anything before app is put to background pass def resume(self): # this method is called, when user place app from background # back into use. Reload anything you might need. pass
Java
UTF-8
1,571
2.640625
3
[ "Apache-2.0" ]
permissive
package com.researchspace.protocolsio; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class DisplayOrderOfComponentsTest { @Test @DisplayName("PIOStepComponent.DisplayOrder puts title first") void displayOrder() { List<PIOStepComponent> parts = createComponentsList(); parts.sort(PIOStepComponent.DisplayOrder); assertEquals(TypeConstants.TITLE, parts.get(0).getTypeId().intValue()); } @Test @DisplayName("title component is always first after ordering protocol") void orderProtocols() { List<PIOStepComponent> parts = createComponentsList(); List<PIOStepComponent> part2 = createComponentsList(); Protocol p = new Protocol(); List<PIOStep> steps = new ArrayList<>(); PIOStep step1 = new PIOStep(); step1.setComponents(parts); PIOStep step2 = new PIOStep(); step2.setComponents(part2); steps.add(step1); steps.add(step2); p.setSteps(steps); p.orderComponents(PIOStepComponent.DisplayOrder); p.getSteps().forEach(step -> { assertEquals(TypeConstants.TITLE, step.getComponents().get(0).getTypeId().intValue()); }); } private List<PIOStepComponent> createComponentsList() { List<PIOStepComponent> parts = new ArrayList<>(); parts.add(new PIOSoftwareComponent()); parts.add(new PIOLinkComponent()); parts.add(new PIOTitleComponent()); return parts; } }
C++
UTF-8
823
2.953125
3
[ "MIT" ]
permissive
/* * author:tlming16 * email:tlming16@fudan.edu.cn * all wrong reserved */ class Solution { public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(),nums.end()); int diff=INT_MAX; int ans=0; for (int i=0;i<nums.size()-2;i++){ int j=i+1; int k= nums.size()-1; for ( ;j<k;) { int sum = nums[i] +nums[j]+nums[k]; if ( abs(sum -target)<diff) { diff = abs(sum-target); ans =sum; } if (sum== target) { return target; } else if (sum < target) { j++; }else { k--; } } } return ans; } };
C#
UTF-8
1,699
2.984375
3
[ "MIT" ]
permissive
using UnityEngine; using System.Collections; using System.Collections.Generic; sealed public class MeshUnoptimizer { public static Mesh Unoptimize(Mesh mesh) { List<Vector3> vertices = new List<Vector3>(mesh.vertices); List<Vector2> uvs = new List<Vector2>(mesh.uv); List<int> triangles = new List<int>(mesh.triangles); HashSet<int> allTrisSeen = new HashSet<int>(); HashSet<int> quadTrisSeen = new HashSet<int>(); var numAdded = 0; for (var i = 0; i < mesh.triangles.Length; i+= 6) { quadTrisSeen.Clear(); for (var j = 0; j < 6; j++) { var vi = mesh.triangles[i+j]; // If we've seen this vertex in the current quad, just skip it //if (quadTrisSeen.Contains(vi)) { // continue; //} // Otherwise, if we *haven't* seen this vertex in other quads, it's // unique (for now). Remember it for both and keep going. if (!allTrisSeen.Contains(vi)) { //quadTrisSeen.Add(vi); allTrisSeen.Add(vi); continue; } // Ok... This is a non-unique vertex. Let's make some copies. numAdded++; var vi2 = vertices.Count; vertices.Add(vertices[vi]); uvs.Add(uvs[vi]); triangles[i+j] = vi2; } } Debug.Log("Unoptimized " + numAdded + " vertices."); mesh.Clear(); mesh.vertices = vertices.ToArray(); mesh.uv = uvs.ToArray(); mesh.triangles = triangles.ToArray(); return mesh; } } abstract public class BaseMeshUnoptomizerBehavior { abstract protected Mesh getMesh(); abstract protected void setMesh(Mesh m); // Use this for initialization void Start () { var m = getMesh(); setMesh(MeshUnoptimizer.Unoptimize(m)); } // Update is called once per frame void Update () { } }
C
UTF-8
666
2.65625
3
[]
no_license
#include<stdio.h> int main(){ int l,i,j,flag=1,k=0; int map[100][100]; int tmap[100][100]; scanf("%d",&l); for(i=0;i<=l-1;i++) for(j=0;j<=l-1;j++){ scanf("%d",&map[i][j]); tmap[i][j]=map[i][j]; } while(1){ flag=1; for(i=0;i<=l-1;i++) for(j=0;j<=l-1;j++) if(map[i][j]==0){ flag=0; if((i>0&&map[i-1][j]==1)||(i<(l-1)&&map[i+1][j]==1)||(j>0&&map[i][j-1]==1)||(j<(l-1)&&map[i][j+1]==1)) tmap[i][j]=1; } if(flag==1)//no space for germ break; else //Update map from tmap for(i=0;i<=l-1;i++) for(j=0;j<=l-1;j++) map[i][j]=tmap[i][j]; k++; } printf("%d",k); return 0; }
Java
UTF-8
617
1.734375
2
[]
no_license
package com.zhanlu.custom.dm.service; import com.zhanlu.custom.dm.dao.BackupHistDao; import com.zhanlu.custom.dm.entity.BackupHist; import com.zhanlu.framework.common.service.CommonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; /** * 备份历史 */ @Service public class BackupHistService extends CommonService<BackupHist, Long> { @Autowired private BackupHistDao backupHistDao; @PostConstruct @Override public void initDao() { super.commonDao = backupHistDao; } }
Markdown
UTF-8
1,053
3.40625
3
[]
no_license
# Collinear Points **The problem**. Given a set of n distinct points in the plane, find every (maximal) line segment that connects a subset of 4 or more of the points. ## My Code The Point class has a method for computing the slope to another point and a Comparator which compares the argument points by the slope they make with the invoking point. BruteCollinear first generates all combinations of 4 points and then iterates through the groups, checking if they all have the same slope relative to one point in the group. Its runtime is n^4 because of the combination generation. FastCollinear iterates through each point but for each point sorts the other points using the slopeOrder comparator. It then iterates through the ordered points and creates segments from the adjacent sorted points that have equal slopes. It runs in n^2 log n time. It uses the built-in sort. ## Running 1. Download the jar files and inputExamples 2. java -jar fast.jar inputFile.txt brute.jar will fail for large input files because of its quartic runtime.
Java
UTF-8
1,087
2.25
2
[]
no_license
package com.revature.services; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.revature.models.Users; import com.revature.repositories.UserDao; @Service public class UserServiceImpl implements UserService { // to use Dao & with constructor injection private UserDao ud; @Autowired public UserServiceImpl(UserDao ud) { this.ud = ud; } @Override public List<Users> getAllUsers() { // TODO Auto-generated method stub return ud.findAll(); } @Override @Transactional public Users saveOneUser(Users u) { // TODO Auto-generated method stub return ud.save(u); } @Override public Users getByUsernameAndPassword(String username, String password) { // TODO Auto-generated method stub return ud.findByUsernameAndPassword(username, password); } @Override public Users findUserById(int id) { // TODO Auto-generated method stub return ud.getOne(id); } }
Java
UTF-8
443
1.6875
2
[]
no_license
package com.mahao.waterlayoutdemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class DashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dash); /* DashView dashView = (DashView) findViewById(R.id.dash_view); dashView.startAnim();*/ } }
C++
UTF-8
2,536
2.84375
3
[]
no_license
/* ----------------------------------------------------------------------- | | | Class: Profile | | Description: Profile entity class. | | | | | | | | | | Author: Syzgy | | Date: 11/27/2015 | | | | | ----------------------------------------------------------------------- */ #include "profile.h" Profile::Profile() { id = -1; } Profile::Profile(const Profile& other) { id = other.getId(); addAllAnswers(other.getAllAnswers()); } Profile::Profile(int id) { this->id = id; } int Profile::getId() const { return id; } void Profile::setId(int value) { id = value; } QuestionnaireAnswer*Profile::getAnswer(int questionNumber) const { if (!questionnaire.length()) { return NULL; } QList<QuestionnaireAnswer*>::const_iterator iter; QuestionnaireAnswer* a = NULL; for (iter = questionnaire.begin(); iter != questionnaire.end(); ++iter) { if ((*iter)->getQuestionNumber() == questionNumber) { a = *iter; break; } } return a; } QList<QuestionnaireAnswer*> Profile::getAllAnswers() const { QList<QuestionnaireAnswer*> copy(questionnaire); return copy; } bool Profile::addAnswer(QuestionnaireAnswer* answer) { questionnaire.append(answer); return true; } bool Profile::addAllAnswers(QList<QuestionnaireAnswer*> answers) { questionnaire.append(answers); return true; } QuestionnaireAnswer* Profile::removeAnswer(int questionNumber) { if (!questionnaire.length()) { return NULL; } QList<QuestionnaireAnswer*>::iterator iter; QuestionnaireAnswer* a = NULL; for (iter = questionnaire.begin(); iter != questionnaire.end(); ++iter) { if ((*iter)->getQuestionNumber() == questionNumber) { a = *iter; questionnaire.erase(iter); } } return a; } bool Profile::removeAnswer(QuestionnaireAnswer* answer) { return questionnaire.removeOne(answer); }
Java
UTF-8
2,168
2.234375
2
[]
no_license
/** * */ package br.edu.unitri.Rest; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.codehaus.jackson.map.ObjectMapper; import br.edu.unitri.ejb.EmailDao; import br.edu.unitri.model.Email; /** * @author marcos.fernando * */ @Path("/email") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class EmailService implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Inject private EmailDao emailDao; @GET @Path("/todos") public List<Email> listAll() { return emailDao.listAll(); } @GET @Path("/porId") public Email getById(Integer id) { return emailDao.getById(id); } @GET @Path("/porExemplo") public List<Email> listByEmail(Email email) { return emailDao.listByEntity(email); } @POST @Path("/salvar") public Response salvar(Email email) { try { if (email.getId() != null) { emailDao.update(email); } else { emailDao.insert(email); } return Response.ok().build(); } catch (Exception ex) { Map<String, String> responseObj = new HashMap<String, String>(); responseObj.put("erro", ex.getMessage()); return Response.status(Response.Status.BAD_REQUEST).entity(responseObj).build(); } } @DELETE @Path("/excluir/{entidade}") public Response excluir(@PathParam("entidade") String entidade) throws Exception{ try { Email email = new ObjectMapper().readValue(entidade, Email.class); emailDao.deleteByEntity(email); return Response.ok().build(); } catch (Exception e) { Map<String, String> responseObj = new HashMap<String, String>(); responseObj.put("msg", "endereço não existe"); return Response.ok().entity(responseObj).build(); } } }
Python
UTF-8
2,314
3.453125
3
[]
no_license
from textwrap import wrap def formatKeyFunc(text, key): # these lines format the key so it is repeated as many times as the text count, keyBuild = -1, "" for i in range(len(text)): count += 1 if count > (len(key) - 1): count = 0 keyBuild = keyBuild + key[count].upper() return keyBuild def formatTextFunc(text): # these lines format the text by removing all spaces and making letters capital textBuild = "" for letter in text: if letter.upper() != " ": textBuild = textBuild + letter.upper() return textBuild def encrypt(text, key): # these lines encrypt the given text using the given key text = formatTextFunc(text) key = formatKeyFunc(text, key) period, textFinal = 5, "" alphabet, matrix, textBuild = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"], [], "" count = -1 for i in range(26): # these lines create a matrix of the alphabet count += 1 matrix.append(alphabet[count:] + alphabet[:count]) for pl, letter in enumerate(text): # these lines carry out the encryption place = matrix[0].index(letter) for row in matrix: if row[place] == key[pl]: textBuild = textBuild + row[0] textBuild = wrap(textBuild, period) # these line format the output for i in textBuild: textFinal = textFinal + i + " " return textFinal[:-1] def decrypt(text, key): # these lines encrypt the given text using the given key text = formatTextFunc(text) key = formatKeyFunc(text, key) alphabet, matrix, textBuild = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"], [], "" count = -1 for i in range(26): # these lines create a matrix of the alphabet count += 1 matrix.append(alphabet[count:] + alphabet[:count]) for pl, letter in enumerate(text): # these lines carry out the encryption for row in matrix: if row[0] == letter: place = row.index(key[pl]) textBuild = textBuild + matrix[0][place] return textBuild
C++
UTF-8
507
2.859375
3
[]
no_license
#include <gtest/gtest.h> #include "projet/Vertex.hpp" TEST(Vertex, init){ } /* TEST(Vertex, init){ Vertex pt1; Vertex pt2(glm::vec3(0), glm::vec2(0), glm::vec3(0)); EXPECT_EQ(pt1, pt2); Vertex pt3(glm::vec3(1), glm::vec2(1,2), glm::vec3(0,1,0)); EXPECT_EQ(pt3, Vertex(glm::vec3(1), glm::vec2(1,2), glm::vec3(0,1,0))); } TEST(Vertex, copy_constructor){ Vertex pt1(glm::vec3(0,0,-5), glm::vec2(0,0), glm::vec3(1,1,1)); Vertex pt2 = pt1; EXPECT_EQ(pt1, pt2); } */
C++
UTF-8
263
2.578125
3
[]
no_license
#include <stdio.h> int main() { char a[501] = { 0 }; int i, j = 0; scanf("%s", a); for (i = 0; i < 501; i++) { if (a[i] != EOF) { j += a[i] - '0'; } else break; } if (j % 3 == 0) printf("1"); else printf("0"); }
PHP
UTF-8
5,461
2.6875
3
[ "MIT" ]
permissive
<?php defined('BASEPATH') or exit('No direct script access allowed'); class M_katalog extends CI_Model { public function getProdbyId($id) { $this->db->select('*'); $this->db->from('barang'); $this->db->join('kategori', 'tbl_barang.barang_kategori_id = kategori.kategori_id', 'left'); $this->db->order_by('barang_id', 'asc'); $this->db->where('barang_id', $id); $query = $this->db->get(); return $query->result_array(); } public function find($barang_id) { $query = $this->db->get_where('barang', array('barang_id' => $barang_id)); return $query->result(); } public function validate_add_cart_item() { $id = $this->input->post('barang_id'); // Assign posted product_id to $id $qty = $this->input->post('qty'); // Assign posted quantity to $cty $this->db->where('barang_id', $id); // Select where id matches the posted id $query = $this->db->get('tbl_barang', 1); // Select the products where a match is found and limit the query by 1 // Check if a row has matched our product id if ($query->num_rows > 0) { // We have a match! foreach ($query->result() as $row) { // Create an array with product information $data = array( 'id' => $id, 'qty' => $qty, 'price' => $row->price_total, 'name' => $row->name_products ); // Add the data to the cart using the insert function that is available because we loaded the cart library $this->cart->insert($data); return true; // Finally return TRUE } } else { // Nothing found! Return FALSE! return false; } } public function cartPrice() { $this->db->where('barang_id', $this->input->post('barang_id')); $this->db->where('c_cart_id', $this->input->post('c_cart_id')); $this->db->select('c_price'); $c = $this->db->get('tbl_cart_detail')->row_array(); $string = implode($c); return $string; } public function pStock() { $this->db->where('barang_id', $this->input->post('barang_id')); $this->db->select('barang_stok'); $c = $this->db->get('tbl_barang')->row_array(); $string = implode($c); return $string; } public function cartIduser() { $this->db->where('barang_id', $this->input->post('barang_id')); $this->db->where('c_cart_id', $this->input->post('c_cart_id')); $c = $this->db->get('tbl_cart_detail')->row_array(); $string = implode($c); return $string; } public function cartQty() { $this->db->where('barang_id', $this->input->post('barang_id')); $this->db->where('c_cart_id', $this->input->post('c_cart_id')); $this->db->select('qty'); $c = $this->db->get('tbl_cart_detail')->row_array(); $string = implode($c); return $string; } public function cartQty2() { $this->db->where('barang_id', $this->input->post('barang_id')); $this->db->where('c_cart_id', $this->input->post('c_cart_id')); $this->db->select('qty'); $c = $this->db->get('tbl_cart_detail')->row_array(); return $c; } public function cartIdproduct() { $this->db->where('barang_id', $this->input->post('barang_id')); $this->db->where('c_cart_id', $this->input->post('c_cart_id')); $this->db->select('barang_id'); $c = $this->db->get('tbl_cart_detail')->row_array(); $string = implode($c); return $string; } public function tssprice($idu) { $this->db->where('c_cart_id', $idu); $this->db->where('barang_id', $this->input->post('barang_id')); $this->db->from('tbl_cart_detail'); $anu = $this->db->get()->num_rows(); return $anu; } // tes pagination public function getpage($limit, $start, $keyword = null) { if ($keyword) { // jika ada keyword maka di lakukan query like $this->db->select('*'); $this->db->from('tbl_barang'); $this->db->join('kategori', 'tbl_barang.barang_kategori_id = kategori.kategori_id', 'left'); $this->db->order_by('barang_id', 'asc'); $this->db->like('barang_nama', $keyword); $this->db->limit($limit, $start); } else { // jika keyword tidak ada $this->db->select('*'); $this->db->from('tbl_barang'); $this->db->join('kategori', 'tbl_barang.barang_kategori_id = kategori.kategori_id', 'left'); $this->db->order_by('barang_id', 'asc'); $this->db->limit($limit, $start); } $query = $this->db->get(); return $query->result_array(); } public function getPbyIdcat($id) { $this->db->select('*'); $this->db->from('tbl_barang'); $this->db->join('kategori', 'tbl_barang.barang_kategori_id = kategori.kategori_id', 'left'); $this->db->order_by('barang_id', 'asc'); $this->db->where('tbl_barang.barang_kategori_id', $id); $query = $this->db->get(); return $query->result_array(); } } /* End of file Home_model.php */ /* Location: ./application/models/Home_model.php */
SQL
UTF-8
119
2.75
3
[]
no_license
SELECT deposit_group, SUM(deposit_amount) AS total_sum FROM wizzard_deposits GROUP BY deposit_group ORDER BY total_sum
Python
UTF-8
580
2.5625
3
[]
no_license
from data_structure.graph import Graph as GRAPH from web_parsers.href_parser import HrefParserThreadBoosted from pyvis.network import Network link = 'https://facebook.com' graph = GRAPH() network = Network(height='100%', width='100%', bgcolor='#000000', font_color='white') threaded_parser = HrefParserThreadBoosted(threads=5, max_links=100) threaded_parser.driver(link) graph.add_nodes(threaded_parser.links) graph.add_edges(threaded_parser.edges) network.barnes_hut() network.add_nodes(graph.get_all_nodes) network.add_edges(graph.get_all_edges) network.show(f'foo.html')
Java
UTF-8
236
1.507813
2
[]
no_license
package com.boot.service; import org.springframework.web.context.request.async.DeferredResult; /** * Created by XJX on 2017/6/8. */ public interface PushService { DeferredResult<String> getAsyncUpdate(); void refresh(); }
JavaScript
UTF-8
1,672
2.6875
3
[]
no_license
var http = require('http') , https = require('https') , cheerio = require('cheerio') , querystring = require('querystring') , siteUrl = 'http://nodejs.cn/api/' , fs = require('./fs.js'); function domFilter(html) { var $ = cheerio.load(html) , html = $('#column2').children("#intro").next("ul").children("li").children('a') , hrefArray = [] , href = '' html.each(function () { //href = this.attribs.href var currentAtag = $(this) //fetch the current cheerio? object, the commented line above does the same href = currentAtag.attr('href') hrefArray.push(href) }) return hrefArray } function loopWrite(html) { var hrefArray = domFilter(html) hrefArray.forEach(function (value, index, array) { var url = siteUrl + value , filePath = './data fetched/' + value http.get(url, function (res) { var html = '' , statusCode = res.statusCode res.on('data', function (data) { html += data }) res.on('end', function () { fs.writeTxt(filePath, html) }) }).on('error', function (err) { console.log(err) }) }) } function httpGetRequest(siteUrl) { http.get(siteUrl, function (res) { var html = '' , statusCode = res.statusCode res.on('data', function (data) { html += data }) res.on('end', function () { loopWrite(html) }) }).on('error', function (err) { console.log(err) }) } httpGetRequest(siteUrl)
C
UTF-8
3,126
2.90625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <png.h> #include <sys/times.h> #include <libpng16/png.h> #define SIZE 600 #define ITERATION_LIMIT 32000 void mandel (int buffer[SIZE][SIZE]) { clock_t delta = clock (); struct tms tmsbuf1, tmsbuf2; times (&tmsbuf1); float a = -2.0, b = .7, c = -1.35, d = 1.35; int width = SIZE, height = SIZE, iterationLimit = ITERATION_LIMIT; float dx = (b - a) / width; float dy = (d - c) / height; float reC, imC, reZ, imZ, newReZ, newImZ; int iteration = 0; for (int j = 0; j < height; ++j) { for (int k = 0; k < width; ++k) { reC = a + k * dx; imC = d - j * dy; reZ = 0; imZ = 0; iteration = 0; while (reZ * reZ + imZ * imZ < 4 && iteration < iterationLimit) { newReZ = reZ * reZ - imZ * imZ + reC; newImZ = 2 * reZ * imZ + imC; reZ = newReZ; imZ = newImZ; ++iteration; } buffer[j][k] = iteration; } } times (&tmsbuf2); printf("%ld\n",tmsbuf2.tms_utime - tmsbuf1.tms_utime + tmsbuf2.tms_stime - tmsbuf1.tms_stime); delta = clock () - delta; printf("%f sec\n",(float) delta / CLOCKS_PER_SEC); } int main (int argc, char *argv[]) { if (argc != 2) { printf("Hasznalat: ./mandelpng fajlnev\n"); return -1; } FILE *fp = fopen(argv[1], "wb"); if(!fp) return -1; png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL); if(!png_ptr) return -1; png_infop info_ptr = png_create_info_struct(png_ptr); if(!info_ptr) { png_destroy_write_struct(&png_ptr,(png_infopp)NULL); return -1; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); return -1; } png_init_io(png_ptr, fp); png_set_IHDR(png_ptr, info_ptr, SIZE, SIZE, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_text title_text; title_text.compression = PNG_TEXT_COMPRESSION_NONE; title_text.key = "Title"; title_text.text = "Mandelbrot halmaz"; png_set_text(png_ptr, info_ptr, &title_text, 1); png_write_info(png_ptr, info_ptr); png_bytep row = (png_bytep) malloc(3 * SIZE * sizeof(png_byte)); int buffer[SIZE][SIZE]; mandel(buffer); for (int j = 0; j < SIZE; ++j) { for (int k = 0; k < SIZE; ++k) { row[k*3] = (255 - (255 * buffer[j][k]) / ITERATION_LIMIT); row[k*3+1] = (255 - (255 * buffer[j][k]) / ITERATION_LIMIT); row[k*3+2] = (255 - (255 * buffer[j][k]) / ITERATION_LIMIT); row[k*3+3] = (255 - (255 * buffer[j][k]) / ITERATION_LIMIT); } png_write_row(png_ptr, row); } png_write_end(png_ptr, NULL); printf("%s mentve\n",argv[1]); }
Python
UTF-8
437
4.28125
4
[]
no_license
def read_int(prompt): s = "" while not isnumber(s): s = input(prompt) return int(s) def isnumber(s): try: int(s) return True except ValueError: return False a = read_int("Enter the first number: ") b = read_int("Enter the second number: ") print(f"{a} + {b} = {a + b}") print(f"{a} - {b} = {a - b}") print(f"{a} * {b} = {a * b}") print(f"{a} / {b} = {a / b}")
Java
UTF-8
251
1.820313
2
[]
no_license
package com.afei.bat.afeiplayandroid.biz; /** * Created by MrLiu on 2017/12/26. *2. 登录模块model接口和所需参数 */ public interface IHomeFragmentBannerModel { void banner(IHomeFragmentBannerListener iHomeFragmentBannerListener); }
PHP
UTF-8
691
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Actions\Tag; use App\Contracts\Actions\Tag\DeletesTag; use App\Models\Tag; class DeleteTagAction extends TagActionAbstract implements DeletesTag { /** * Delete the given tag. * * @param Tag $tag * @return int Remote tag ID. */ public function delete(Tag $tag): int { $this->authorize( 'delete', $this->tag = $tag->fresh() ); $id = $tag->id; $tag->delete(); return $id; } /** * Get the validation rules that apply to the action. * * @return array */ protected function rules(): array { return [ // ]; } }
C++
UTF-8
2,347
3.125
3
[]
no_license
#include "KeyboardControls.h" KeyboardControls::KeyboardControls() { ToggleFullscreenKey = Keyboard::F11; PauseKey = Keyboard::Escape; DisplayMapKey = Keyboard::Space; IncreaseSkillKey = Keyboard::Add; DecreaseSkillKey = Keyboard::Subtract; NextSkillKey = Keyboard::Numpad9; PreviousSkillKey = Keyboard::Numpad7; MovementHorizontalPositiveKey = Keyboard::D; MovementHorizontalNegativeKey = Keyboard::A; MovementVerticalPositiveKey = Keyboard::S; MovementVerticalNegativeKey = Keyboard::W; AimHorizontalPositiveKey = Keyboard::Right; AimHorizontalNegativeKey = Keyboard::Left; AimVerticalPositiveKey = Keyboard::Down; AimVerticalNegativeKey = Keyboard::Up; } bool KeyboardControls::isPressed(Uint32 button) { switch (button) { case Button::ToggleFullscreen: return Keyboard::isKeyPressed(ToggleFullscreenKey); case Button::Pause: return Keyboard::isKeyPressed(PauseKey); case Button::DisplayMap: return Keyboard::isKeyPressed(DisplayMapKey); case Button::IncreaseSkill: return Keyboard::isKeyPressed(IncreaseSkillKey); case Button::DecreaseSkill: return Keyboard::isKeyPressed(DecreaseSkillKey); case Button::NextSkill: return Keyboard::isKeyPressed(NextSkillKey); case Button:: PreviousSkill: return Keyboard::isKeyPressed(PreviousSkillKey); default: assert(false && "Nonexistant button!"); } } Vector2f KeyboardControls::getVector(Uint32 axisX, Uint32 axisY) { return Vector2f(getAxis(axisX), getAxis(axisY)); } float KeyboardControls::getAxis(Uint32 axis) { switch (axis) { case Axis::AimHorizontal: return getAxis(AimHorizontalPositiveKey, AimHorizontalNegativeKey); case Axis::AimVertical: return getAxis(AimVerticalPositiveKey, AimVerticalNegativeKey); case Axis::MovementHorizontal: return getAxis(MovementHorizontalPositiveKey, MovementHorizontalNegativeKey); case Axis::MovementVertical: return getAxis(MovementVerticalPositiveKey, MovementVerticalNegativeKey); default: assert(false && "Nonexistant Axis!"); } } float KeyboardControls::getAxis(Keyboard::Key positive, Keyboard::Key negative) { if(Keyboard::isKeyPressed(positive)) { return 100; } else if (Keyboard::isKeyPressed(negative)) { return -100; } else { return 0; } }
Java
UTF-8
622
1.507813
2
[]
no_license
package cn.cjf.gateway.vo.wx; import com.thoughtworks.xstream.annotations.XStreamAlias; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public abstract class WxPayBaseRequest { @XStreamAlias("appid") protected String appid; @XStreamAlias("mch_id") protected String mchId; @XStreamAlias("sub_appid") protected String subAppId; @XStreamAlias("sub_mch_id") protected String subMchId; @XStreamAlias("nonce_str") protected String nonceStr; @XStreamAlias("sign") protected String sign; @XStreamAlias("sign_type") private String signType; }