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
Java
UTF-8
2,654
2.140625
2
[]
no_license
package com.braintech.cmyco.utils; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.Color; import android.support.v7.internal.widget.DialogTitle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.braintech.cmyco.R; public class AlertDialogManager { public void showAlertDialog(Context context, String message) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); // Setting Dialog Message alertDialog.setMessage(message); // alertDialog.setTitle("Alert"); // Setting OK Button alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); try { // Showing Alert Message AlertDialog alert = alertDialog.show(); TextView messageText = (TextView) alert .findViewById(android.R.id.message); messageText.setTextColor(Color.parseColor("#000000")); Fonts.robotoRegular(context, messageText); messageText.setGravity(Gravity.CENTER); alert.show(); } catch (RuntimeException ex) { ex.printStackTrace(); } } public void showAlertForFinish(final Context context, String message) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); // Setting Dialog Message alertDialog.setMessage(message); // Setting OK Button alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ((Activity) context).finish(); } }); try { // Showing Alert Message AlertDialog alert = alertDialog.show(); TextView messageText = (TextView) alert .findViewById(android.R.id.message); Fonts.robotoRegular(context, messageText); messageText.setTextColor(Color.parseColor("#000000")); messageText.setGravity(Gravity.CENTER); alert.show(); } catch (RuntimeException ex) { ex.printStackTrace(); } } }
Python
UTF-8
6,805
2.734375
3
[]
no_license
import sys, os, re, math, copy def FarthestFirstTraversal(data, k): start = data[0] centers = [start] data.remove(start) while len(centers)<k: max_value = 0 max_point = [] for i in data: distance = [] for j in centers: tmp_distance = 0 for n in xrange(len(i)): tmp_distance += (i[n]-j[n])**2 distance.append(tmp_distance) if min(distance)>max_value: max_value = min(distance) max_point = i centers.append(max_point) data.remove(max_point) return centers def distortion(data, centers): total = 0 for i in data: min_dis = 1000000000 for j in centers: tmp_dis = 0 for k in xrange(len(j)): tmp_dis += (i[k]-j[k])**2 if tmp_dis < min_dis: min_dis = tmp_dis total += min_dis return total/len(data) def Lloyd(data, k): centers = data[0:k] total = 1000000000 while total > 1e-9: graph = {} for i in xrange(k): graph[i] = [] for i in data: min_dis = 1000000000 for j in centers: tmp_dis = 0 for n in xrange(len(data[0])): tmp_dis += (i[n]-j[n])**2 if tmp_dis < min_dis: min_dis = tmp_dis final_center = j graph[centers.index(final_center)].append(i) gravity = [] for i in xrange(k): gravity.append([]) for j in xrange(len(data[0])): tmp = 0 for n in xrange(len(graph[i])): tmp += graph[i][n][j] gravity[i].append(tmp/len(graph[i])) if len(graph[i])!=0 else gravity[i].append(0) total = 0 for i in xrange(len(centers)): for j in xrange(len(centers[0])): total += (centers[i][j]-gravity[i][j])**2 centers = gravity return centers def expectationMax(data, k, beta, times): centers = copy.deepcopy(data[0:k]) # centers = [[2.5],[-2.5]] n = 0 while n<times: n += 1 hiddenMatrix = [[0]*k for i in xrange(len(data))] for i in xrange(len(data)): dic = {} total = 0 for j in xrange(len(centers)): distance = 0 for m in xrange(len(data[i])): distance += (data[i][m]-centers[j][m])**2 dic[j] = math.sqrt(distance) total += math.exp(-beta*math.sqrt(distance)) for center in xrange(len(centers)): hiddenMatrix[i][center] = math.exp(-beta*dic[center])/total ########### update the centers for i in xrange(len(centers)): for j in xrange(len(centers[i])): numerator = 0 denominator = 0 for m in xrange(len(data)): numerator += hiddenMatrix[m][i]*data[m][j] denominator += hiddenMatrix[m][i] centers[i][j] = numerator/denominator return centers def hierachical(graph): times = len(graph) n = 1 new_key = times+1 cluster = {} for i in xrange(1,times+1): cluster[i] = {} cluster[i]['size'] = 1 cluster[i]['items'] = [i] while n<times: cluster[new_key] = {} n += 1 min_value = 1000000 start = 0 end = 0 graph[new_key] = {} for i in graph: for j in graph[i]: if graph[i][j]<min_value: min_value = graph[i][j] start = i end = j for i in graph: if i!=new_key: total = 0 if start in graph[i]: total += graph[i][start]*cluster[start]['size'] if i in graph[start]: total += graph[start][i]*cluster[start]['size'] if end in graph[i]: total += graph[i][end]*cluster[end]['size'] if i in graph[end]: total += graph[end][i]*cluster[end]['size'] size = cluster[start]['size']+cluster[end]['size'] cluster[new_key]['size'] = size cluster[new_key]['items'] = list(set(cluster[start]['items']+cluster[end]['items'])) graph[new_key][i] = 1.0*total/size for i in graph: if start in graph[i]: graph[i].pop(start, None) if end in graph[i]: graph[i].pop(end, None) graph.pop(start, None) graph.pop(end, None) for items in cluster[new_key]['items']: print items, print new_key += 1 if __name__ == '__main__': f = open('test', 'r') lines = f.readlines() n = int(lines[0].split()[0]) graph = {} key = 1 for line in lines[1:]: graph[key] = {} items = line.strip().split() for i in xrange(key,n): graph[key][i+1] = float(items[i]) key += 1 hierachical(graph) # f = open('test', 'r') # lines = f.readlines() # k = int(lines[0].split()[0]) # m = int(lines[0].split()[1]) # beta = float(lines[1]) # data = [] # for line in lines[2:]: # data.append([float(x) for x in line.split()]) # res = expectationMax(data, k, beta, 100) # for i in res: # for j in i: # print "%.3f" %j, # print # f = open('test', 'r') # lines = f.readlines() # k = int(lines[0].split()[0]) # m = int(lines[0].split()[1]) # data = [] # for line in lines[1:]: # data.append([float(x) for x in line.split()]) # res = Lloyd(data, k) # for i in res: # for j in i: # print "%.3f" %j, # print # f = open('test', 'r') # lines = f.readlines() # k = int(lines[0].split()[0]) # m = int(lines[0].split()[1]) # centers = [] # for line in lines[1:k+1]: # centers.append([float(x) for x in line.split()]) # data = [] # for line in lines[k+2:]: # data.append([float(x) for x in line.split()]) # res = distortion(data, centers) # print res # f = open('test', 'r') # lines = f.readlines() # k = int(lines[0].split()[0]) # m = int(lines[0].split()[1]) # data = [] # for line in lines[1:]: # data.append([float(x) for x in line.split()]) # res = FarthestFirstTraversal(data, k) # for i in res: # for j in i: # print j, # print
Java
UTF-8
2,612
2.4375
2
[]
no_license
package soup.movie.data.soup.model; import com.google.gson.annotations.SerializedName; import java.util.List; public class Movie { @SerializedName("id") private String id; @SerializedName("title") private String title; @SerializedName("thumbnail") private String thumbnailUrl; @SerializedName("poster") private String posterUrl; @SerializedName("age") private String age; @SerializedName("open_date") private String openDate; @SerializedName("egg") private String egg; @SerializedName("special_types") private List<String> specialTypeList; @SerializedName("trailers") private List<Trailer> trailers; public Movie() { } public String getId() { return id; } public String getTitle() { return title; } public String getThumbnailUrl() { return thumbnailUrl; } public String getPosterUrl() { return posterUrl; } public String getAge() { return age; } public String getOpenDate() { return openDate; } public String getEgg() { return egg; } public List<String> getSpecialTypeList() { return specialTypeList; } public List<Trailer> getTrailers() { return trailers; } public void setId(String id) { this.id = id; } public void setTitle(String title) { this.title = title; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } public void setPosterUrl(String posterUrl) { this.posterUrl = posterUrl; } public void setAge(String age) { this.age = age; } public void setOpenDate(String open_date) { this.openDate = open_date; } public void setEgg(String egg) { this.egg = egg; } public void setSpecialTypeList(List<String> specialTypeList) { this.specialTypeList = specialTypeList; } public void setTrailers(List<Trailer> trailers) { this.trailers = trailers; } @Override public String toString() { return "Movie{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", thumbnailUrl='" + thumbnailUrl + '\'' + ", posterUrl='" + posterUrl + '\'' + ", age='" + age + '\'' + ", openDate='" + openDate + '\'' + ", egg='" + egg + '\'' + ", specialTypeList=" + specialTypeList + ", trailers=" + trailers + '}'; } }
C
UTF-8
407
3.609375
4
[]
no_license
#include<stdio.h> int main() { int i, j, temp; int arr[9]={1, 5, 8, 12, 31, 42, 57, 65, 81}; printf("Ascending order;\n"); for(i=0;i<9;i++) { printf("%d ", arr[i]); } for(i=0, j=8;i<4, j>=5;i++, j--) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } printf("\nDescending order;\n"); for(i=0;i<9;i++) { printf("%d ", arr[i]); } printf("\n"); system("PAUSE"); return 0; }
Java
UTF-8
1,815
3
3
[]
no_license
package model; import IA.Gasolina.Distribucion; import representation.Global; import java.util.Iterator; import java.util.LinkedList; import java.util.Optional; public class Trip extends LinkedList<Petition> { public Trip() { } public Trip(Trip copy) { super(copy); } @Override public boolean add(Petition p) { throw new RuntimeException("Use addPetition instead"); } public void addPetition(Petition p, Truck truck) throws RestrictionViolationException { if (p == null) { throw new IllegalArgumentException("Petition is null"); } else if (isFull()) { throw new RestrictionViolationException("Trip assignations violation"); } super.add(p); if (truck.getTravelledDistance() > Global.MAX_KM_PER_DAY) { removeLast(); throw new RestrictionViolationException("Truck kilometers violation"); } } public boolean isFull() { return size() == Global.ASSIGNATIONS_PER_TRIP; } public int getTravelledDistance(Distribucion origin) { int km = 0; Iterator<Petition> iterator = iterator(); if (iterator.hasNext()) { Petition prev = iterator.next(); km += prev.getDistanceTo(origin); while (iterator.hasNext()) { Petition next = iterator.next(); km += prev.getDistanceTo(next); prev = next; } km += prev.getDistanceTo(origin); } return km; } Optional<Petition> findFirstPetitionWithDistinctStationThan(Petition petition) { return stream().filter(p -> !p.isSameStation(petition)).findFirst(); } @Override public String toString() { return "Trip " + super.toString(); } }
Python
UTF-8
743
2.625
3
[ "MIT" ]
permissive
# Copyright (c) 2019 Thomas Howe from problem_sets.environment import Environment from problem_sets.gen.manager import registered_gens, load_gens def gen_problem(set_id: str): """ Attempt to generate problem with generator id 'set_id' (generators have an infinite virtual "set") """ problem_id = None if ':' in set_id: set_id_split = set_id.split(':') problem_id = int(set_id_split[1]) set_id = set_id_split[0] if set_id not in registered_gens: return return registered_gens[set_id].fun(problem_id) def gen_sets(): """ List of names of all available problem generators """ return registered_gens.keys() def initialize_gen(env: Environment): load_gens(env)
Java
UTF-8
22,038
1.84375
2
[ "Apache-2.0" ]
permissive
package com.ieeton.agency.activity; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.RejectedExecutionException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.fortysevendeg.swipelistview.SwipeListView; import com.ieeton.agency.exception.PediatricsApiException; import com.ieeton.agency.exception.PediatricsIOException; import com.ieeton.agency.exception.PediatricsParseException; import com.ieeton.agency.models.City; import com.ieeton.agency.models.Doctor; import com.ieeton.agency.net.NetEngine; import com.ieeton.agency.utils.Constants; import com.ieeton.agency.utils.Utils; import com.ieeton.agency.view.CustomToast; import com.ieeton.agency.view.PatientListItemView; import com.ieeton.agency.view.SelectCityListItemView; import com.ieeton.agency.R; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.TextView.OnEditorActionListener; public class SearchDoctorActivity extends Activity { // private static final int REQUEST_SELECT_CITY = 1; // // private ImageView mChooseCityBtn; // private ImageView mSearchCityBtn; // private ImageView mCancelBtn; // private EditText mEditText; // private ListView mHistoryListView; // private LinearLayout mSearchHistory; // private ImageView mClearHistoryBtn; // private CustomToast mProgressDialog; // private SwipeListView mSearchDoctorListView; // private DoctorListAdapter mSearchDoctorListAdapter; // private List<Doctor> mSearchDoctorList; // private LoadDoctorListTask mLoadDoctorListTask; // private boolean mTaskFree = true; // private boolean mHotSearchTaskFree = true; // private int mPageCount = 1; // private HistoryListAdapter mHistoryListAdapter; // private LinkedHashSet<String> mSearchRecordSet; //历史搜索记录数据 // private List<String> mSearchRecordList; //历史搜索记录数据 // private String mKeywords; // private TextView mCurrentCity; // private String mCache; // public static final String NEW_SEARCHKEYWORDLISTPATH = "/searchkeywordlistcaches"; // private static final int MAX_NUM_RECORD = 5; // private LoadSearchHistoryTask mLoadHistoryTask; // // private ListView mHotSearchListView; // private LinearLayout mHotSearchLayout; // private HotSearchListAdapter mHotSearchListAdapter; // private List<String> mHotSearchList; // private boolean mShowSuggestion = true; // // /** // * save search history to local cache file // */ // private void saveSearchHistory(String key){ // if( (mSearchRecordSet != null && mSearchRecordSet.contains( key ) )){ // return; // } // // final String filePath = mCache + NEW_SEARCHKEYWORDLISTPATH +"/"+Utils.getPassport(SearchDoctorActivity.this)+"passport"; // // //make sure mSearchRecordSet not null // if( mSearchRecordSet == null ){ // Set<String> set = Utils.loadKeyWordList(filePath); // if( set == null ){ // mSearchRecordSet = new LinkedHashSet<String>(); // }else{ // //兼容3.2.0之前的搜索历史数据(3.2.0之前以HashSet存储) // if( set instanceof HashSet ){ // mSearchRecordSet = new LinkedHashSet<String>(set); // }else { // mSearchRecordSet = (LinkedHashSet<String>) set; // } // } // } // // Iterator<String> itelator = mSearchRecordSet.iterator(); // int size = mSearchRecordSet.size(); // while( ( size > MAX_NUM_RECORD - 1 ) && itelator.hasNext() ){ //// 在通过itelator遍历列表时,不能直接通过collection来remove元素,否则会发生ConcurrentModificationException //// mSearchRecordSet.remove( itelator.next() ); // itelator.next(); // itelator.remove(); // size = mSearchRecordSet.size(); // } // // mSearchRecordSet.add( key ); // // if( mSearchRecordList != null ){ // mSearchRecordList.clear(); // mSearchRecordList.addAll( mSearchRecordSet ); // }else{ // mSearchRecordList = new ArrayList<String>( mSearchRecordSet ); // } // Utils.saveKeyWordList(filePath, mSearchRecordSet); // } // // /** // * load search history from local cache file // */ // private List<String> loadSearchHistroy() { // final String filePath = mCache + NEW_SEARCHKEYWORDLISTPATH+"/"+Utils.getPassport(SearchDoctorActivity.this)+"passport"; // Set<String> set = Utils.loadKeyWordList( filePath ); // if( set == null ){ // return new ArrayList<String>( ); // } // // if( set instanceof HashSet ){ // mSearchRecordSet = new LinkedHashSet<String>(set); // }else { // mSearchRecordSet = (LinkedHashSet<String>) set; // } // if ( mSearchRecordSet != null ) { // ArrayList<String> list = new ArrayList<String>( mSearchRecordSet ); // Collections.reverse( list ); // return list; // }else { // return new ArrayList<String>( ); // } // } // // /** // *load Search History task // */ // private class LoadSearchHistoryTask extends AsyncTask<Void, Void, List<String>>{ // // @Override // protected List<String> doInBackground( Void... params ) { // if (mSearchRecordList != null && mSearchRecordList.size() != 0) { // return mSearchRecordList; // }else { // return loadSearchHistroy(); // } // } // // @Override // protected void onPreExecute() { // super.onPreExecute(); // if( mHistoryListAdapter != null ){ // mHistoryListAdapter.clear(); // } // ((BaseAdapter)mHistoryListView.getAdapter()).notifyDataSetChanged(); // } // // @Override // protected void onPostExecute( List<String> result ) { // super.onPostExecute(result); // mSearchRecordList = result ; // ((BaseAdapter)mHistoryListView.getAdapter()).notifyDataSetChanged(); // // if(mShowSuggestion){ // mSearchHistory.setVisibility(View.VISIBLE); // } // } // // } // // // @Override // protected void onCreate(Bundle savedInstanceState) { // // TODO Auto-generated method stub // super.onCreate(savedInstanceState); // setContentView(R.layout.search_doctor); // // mShowSuggestion = true; // // City city = Utils.getMyCity(SearchDoctorActivity.this); // mCurrentCity = (TextView)findViewById(R.id.tv_city); // mCurrentCity.setText(city.getCityName()); // // mChooseCityBtn = (ImageView)findViewById(R.id.iv_select_city); // mChooseCityBtn.setOnClickListener(this); // // mSearchCityBtn = (ImageView)findViewById(R.id.search_btn); // mSearchCityBtn.setOnClickListener(this); // // mCancelBtn = (ImageView)findViewById(R.id.cancel_btn); // mCancelBtn.setOnClickListener(this); // // mEditText = (EditText)findViewById(R.id.search_input_box); // mEditText.setOnClickListener(this); // mEditText.addTextChangedListener( this ); // mEditText.setImeOptions( EditorInfo.IME_ACTION_SEARCH ); // mEditText.setOnEditorActionListener( new OnEditorActionListener() { // @Override // public boolean onEditorAction( TextView v, int actionId, KeyEvent event ) { // switch (actionId) { // case EditorInfo.IME_ACTION_UNSPECIFIED: // case EditorInfo.IME_ACTION_SEARCH: // mKeywords = mEditText.getEditableText().toString(); // search(); // return true; // default: // return false; // } // } // } ); // // mSearchHistory = (LinearLayout)findViewById(R.id.search_history); // mSearchHistory.setVisibility(View.GONE); // // mHistoryListView = (ListView)findViewById(R.id.lv_search_history); // mHistoryListAdapter = new HistoryListAdapter(); // mHistoryListView.setAdapter( mHistoryListAdapter ); // // mHistoryListView.setOnItemClickListener(new OnItemClickListener() { // // @Override // public void onItemClick(AdapterView<?> parent, View view, int position, // long arg3) { // // TODO Auto-generated method stub // mKeywords = mSearchRecordList.get(position); // search(); // } // }); // // mHotSearchLayout = (LinearLayout)findViewById(R.id.ll_hot_search_keywords); // mHotSearchLayout.setVisibility(View.GONE); // // mHotSearchListView = (ListView)findViewById(R.id.lv_hot_search); // mHotSearchListAdapter = new HotSearchListAdapter(); // mHotSearchListView.setAdapter(mHotSearchListAdapter); // mHotSearchListView.setOnItemClickListener(new OnItemClickListener() { // // @Override // public void onItemClick(AdapterView<?> parent, View view, int position, // long arg3) { // // TODO Auto-generated method stub // mKeywords = mHotSearchList.get(position); // search(); // } // }); // // mClearHistoryBtn = (ImageView)findViewById(R.id.clear_search_history); // mClearHistoryBtn.setOnClickListener(this); // // mSearchDoctorListView = (SwipeListView)findViewById(R.id.lv_search_doctor_list); // mSearchDoctorListAdapter = new DoctorListAdapter(); // mSearchDoctorListView.setAdapter(mSearchDoctorListAdapter); // mSearchDoctorListView.setVisibility(View.GONE); // // mCache = getCacheDir().getAbsolutePath(); // try{ // mLoadHistoryTask = new LoadSearchHistoryTask(); // mLoadHistoryTask.execute(); // }catch(RejectedExecutionException e){ // e.printStackTrace(); // } // // // try{ // LoadHotSearchWordsTask task = new LoadHotSearchWordsTask(); // task.execute(); // }catch(RejectedExecutionException e){ // e.printStackTrace(); // } // } // // void search(){ // if(mKeywords == null || mKeywords.equals("")){ // Toast.makeText(SearchDoctorActivity.this, "请输入你要搜索的内容", Toast.LENGTH_SHORT).show(); // return; // } // if(mTaskFree){ // try{ // mLoadDoctorListTask = new LoadDoctorListTask(); // mLoadDoctorListTask.execute(); // }catch(RejectedExecutionException e){ // e.printStackTrace(); // } // } // } // // @Override // public void onClick(View v) { // if(v == mChooseCityBtn){ // Intent intent = new Intent(this, SelectCityActivity.class); // intent.putExtra(SelectCityActivity.MODE, SelectCityActivity.MODE_SEARCH); // startActivityForResult(intent, REQUEST_SELECT_CITY); // }else if(v == mSearchCityBtn){ // mKeywords = mEditText.getEditableText().toString(); // search(); // }else if(v == mCancelBtn){ // finish(); // }else if(v == mClearHistoryBtn){ // mSearchRecordList.clear(); // mHistoryListAdapter.notifyDataSetChanged(); // } // } // // class DoctorListAdapter extends BaseAdapter{ // // @Override // public int getCount() { // if(mSearchDoctorList != null){ // return mSearchDoctorList.size(); // } // return 0; // } // // @Override // public Object getItem(int position) { // return position; // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // PatientListItemView view = null; // if (convertView == null){ // view = new PatientListItemView(SearchDoctorActivity.this); // }else{ // view = (PatientListItemView)convertView; // } // // if(mSearchDoctorList != null && mSearchDoctorList.size() > 0 && position < mSearchDoctorList.size()){ // view.update(mSearchDoctorList.get(position)); // } // // return view; // } // // } // // class LoadDoctorListTask extends AsyncTask<Void, Void, List<Doctor>>{ // private Throwable mThr; // // @Override // protected void onPreExecute() { // // TODO Auto-generated method stub // super.onPreExecute(); // showProgress(); // mTaskFree = false; // } // // @Override // protected List<Doctor> doInBackground(Void... arg0) { // String result = ""; // // try { // //保存搜索关键字 // saveSearchHistory( mKeywords.trim() ); // // result = NetEngine.getInstance(SearchDoctorActivity.this) // .searchDoctor(Utils.getPassport(SearchDoctorActivity.this), // Utils.getMyCity(SearchDoctorActivity.this).getCityID(), // mKeywords, Constants.MAX_PAGE_SIZE, mPageCount); // } catch (PediatricsIOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // mThr = e; // } catch (PediatricsParseException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // mThr = e; // } catch (PediatricsApiException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // mThr = e; // } // // JSONObject object = null; // try { // object = new JSONObject(result); // if(!object.getBoolean("error")){ // JSONObject json_data = object.getJSONObject("messages").getJSONObject("data"); // JSONArray array = json_data.getJSONArray("docotors"); // // List<Doctor> list = new ArrayList<Doctor>(); // for(int i=0; i<array.length(); i++){ // Doctor item = new Doctor((JSONObject)array.get(i)); // list.add(item); // } // return list; // }else{ // return null; // } // } catch (JSONException e) { // e.printStackTrace(); // return null; // } // } // // @Override // protected void onCancelled() { // // TODO Auto-generated method stub // super.onCancelled(); // dismissProgress(); // } // // @Override // protected void onPostExecute(List<Doctor> result) { // mTaskFree = true; // dismissProgress(); // // if (result == null || result.equals("")){ // if(mThr != null){ // Utils.handleErrorEvent(mThr, SearchDoctorActivity.this); // }else{ // Utils.showToast(SearchDoctorActivity.this, R.string.PediatricsParseException, Toast.LENGTH_SHORT); // } // return; // } // if(mSearchDoctorList != null){ // mSearchDoctorList.clear(); // } // mSearchDoctorList = result; // if(mSearchDoctorListAdapter != null){ // mSearchDoctorListAdapter.notifyDataSetChanged(); // } // mSearchHistory.setVisibility(View.GONE); // mHotSearchLayout.setVisibility(View.GONE); // mSearchDoctorListView.setVisibility(View.VISIBLE); // } // // } // // public class HotSearchKeywords{ // String id; // String keywords; // // public HotSearchKeywords(JSONObject data){ // try{ // id = data.getString("id"); // keywords = data.getString("name"); // }catch(JSONException e){ // e.printStackTrace(); // } // } // // public String getKeyword(){ // return keywords; // } // } // // class LoadHotSearchWordsTask extends AsyncTask<Void, Void, List<String>>{ // private Throwable mThr; // // @Override // protected void onPreExecute() { // // TODO Auto-generated method stub // super.onPreExecute(); // showProgress(); // mHotSearchTaskFree = false; // } // // @Override // protected List<String> doInBackground(Void... arg0) { // String result = ""; // // try { // result = NetEngine.getInstance(SearchDoctorActivity.this).getHotSearchKeywords(); // } catch (PediatricsIOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // mThr = e; // } catch (PediatricsParseException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // mThr = e; // } catch (PediatricsApiException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // mThr = e; // } //Log.v("sereinli","Result:"+result); // JSONObject object = null; // try { // object = new JSONObject(result); // if(!object.getBoolean("error")){ // JSONObject json_data = object.getJSONObject("messages").getJSONObject("data"); // JSONArray array = json_data.getJSONArray("hots"); // // List<String> list = new ArrayList<String>(); // for(int i=0; i<array.length(); i++){ // HotSearchKeywords item = new HotSearchKeywords((JSONObject)array.get(i)); // list.add(item.getKeyword()); // } // return list; // }else{ // return null; // } // } catch (JSONException e) { // e.printStackTrace(); // return null; // } // } // // @Override // protected void onCancelled() { // super.onCancelled(); // dismissProgress(); // } // // @Override // protected void onPostExecute(List<String> result) { // mHotSearchTaskFree = true; // dismissProgress(); // // if (result == null || result.equals("")){ // if(mThr != null){ // Utils.handleErrorEvent(mThr, SearchDoctorActivity.this); // }else{ // Utils.showToast(SearchDoctorActivity.this, R.string.PediatricsParseException, Toast.LENGTH_SHORT); // } // return; // } // if(mHotSearchList != null){ // mHotSearchList.clear(); // } // mHotSearchList = result; // if(mHotSearchListAdapter != null){ // mHotSearchListAdapter.notifyDataSetChanged(); // } // // if(mShowSuggestion){ // mHotSearchLayout.setVisibility(View.VISIBLE); // } // } // // } // // private void showProgress(){ // if (mProgressDialog == null){ // mProgressDialog = Utils.createProgressCustomToast(R.string.loading, SearchDoctorActivity.this); // } // mProgressDialog.show(); // } // // private void dismissProgress(){ // if (mProgressDialog != null){ // mProgressDialog.cancel(); // } // } // // class HistoryListAdapter extends BaseAdapter{ // // @Override // public int getCount() { // if (mSearchRecordList != null && !mSearchRecordList.isEmpty()){ // return mSearchRecordList.size(); // } // return 0; // } // // public void clear(){ // if( mSearchRecordList != null ){ // mSearchRecordList.clear(); // } // } // // @Override // public Object getItem(int position) { // return position; // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // View view = null; // if (convertView == null){ // LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); // view = inflater.inflate(R.layout.select_city_list_item, null); // }else{ // view = convertView; // } // TextView record = (TextView)view.findViewById(R.id.tv_city); // record.setText(mSearchRecordList.get(position)); // // return view; // } // // } // // class HotSearchListAdapter extends BaseAdapter{ // // @Override // public int getCount() { // if (mHotSearchList != null && !mHotSearchList.isEmpty()){ // return mHotSearchList.size(); // } // return 0; // } // // public void clear(){ // if( mHotSearchList != null ){ // mHotSearchList.clear(); // } // } // // @Override // public Object getItem(int position) { // return position; // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // View view = null; // if (convertView == null){ // LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); // view = inflater.inflate(R.layout.select_city_list_item, null); // }else{ // view = convertView; // } // TextView record = (TextView)view.findViewById(R.id.tv_city); // record.setText(mHotSearchList.get(position)); // // return view; // } // // } // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // // TODO Auto-generated method stub // super.onActivityResult(requestCode, resultCode, data); // // if(resultCode != RESULT_OK){ // return; // } // // switch (requestCode) { // case REQUEST_SELECT_CITY: // City city = (City) data.getExtras().getSerializable("city"); // String name = city.getCityName(); // if(name != null && !name.equals("")){ // mCurrentCity.setText(city.getCityName()); // } // break; // // default: // break; // } // } // // @Override // public void afterTextChanged(Editable s) { // // TODO Auto-generated method stub // } // // @Override // public void beforeTextChanged(CharSequence s, int start, int count, // int after) { // // mShowSuggestion = true; // // if(mSearchRecordList != null && mSearchRecordList.size() > 0){ // mSearchHistory.setVisibility(View.VISIBLE); // } // if(mHotSearchList != null && mHotSearchList.size() > 0){ // mHotSearchLayout.setVisibility(View.VISIBLE); // } // // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // // TODO Auto-generated method stub // // } // }
Markdown
UTF-8
867
3.125
3
[]
no_license
# 穿越时空的深度网络架构 在本节中,我们将回顾从 LeNet5 开始在整个深度学习历史中出现的里程碑架构。 ## LeNet 5 在 1980 年代和 1990 年代,神经网络领域一直保持沉默。 尽管付出了一些努力,但是架构非常简单,并且需要大的(通常是不可用的)机器力量来尝试更复杂的方法。 1998 年左右,在 Bells 实验室中,在围绕手写校验数字分类的研究中,Ian LeCun 开始了一种新趋势,该趋势实现了所谓的“深度学习-卷积神经网络”的基础,我们已经在第 5 章,简单的前馈神经网络中对其进行了研究。 在那些年里,SVM 和其他更严格定义的技术被用来解决这类问题,但是有关 CNN 的基础论文表明,与当时的现有方法相比,神经网络的表现可以与之媲美或更好。
Python
UTF-8
1,670
4.25
4
[]
no_license
'''절댓값 힙은 다음과 같은 연산을 지원하는 자료구조이다. 배열에 정수 x (x ≠ 0)를 넣는다. 배열에서 절댓값이 가장 작은 값을 출력하고, 그 값을 배열에서 제거한다. 절댓값이 가장 작은 값이 여러개일 때는, 가장 작은 수를 출력하고, 그 값을 배열에서 제거한다. 프로그램은 처음에 비어있는 배열에서 시작하게 된다. 입력 첫째 줄에 연산의 개수 N(1≤N≤100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 0이 아니라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0이라면 배열에서 절댓값이 가장 작은 값을 출력하고 그 값을 배열에서 제거하는 경우이다. 입력되는 정수는 -231보다 크고, 231보다 작다. 출력 입력에서 0이 주어진 회수만큼 답을 출력한다. 만약 배열이 비어 있는 경우인데 절댓값이 가장 작은 값을 출력하라고 한 경우에는 0을 출력하면 된다.''' #힙 from heapq import * import sys N = int(sys.stdin.readline()) arr = [] heapify(arr) for _ in range(N): x = int(sys.stdin.readline()) if(x==0): if(len(arr)==0): print(0) else: print(heappop(arr)[1]) #정렬기준은 절댓값이고 출력하는 건 원래 값이므로 1번 인덱스를 출력 else: if(x<0): heappush(arr,(-x,x)) #튜블의 첫번째 원소를 기준으로 가기 때문에 절댓값을 첫번째 원소로 두고 원래값을 두번째 값으로 준다. else: heappush(arr,(x,x))
C
UTF-8
159
2.609375
3
[]
no_license
/* ** EPITECH PROJECT, 2019 ** CPool_rush1_2019 ** File description: ** main */ void rush(int x, int y); int main(void) { rush(15, 15); return (0); }
C++
UTF-8
5,373
2.6875
3
[]
no_license
/** * @file * @author Matthew Parkan <matthew.parkan@gmail.com> * @version 1.0 * * @section LICENSE * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details at * http://www.gnu.org/copyleft/gpl.html * * @section DESCRIPTION * * This class is a container for 3D points. * */ #ifndef POINTCOLLECTION_H #define POINTCOLLECTION_H #include <iostream> #include <vector> #include <array> #include "CircularBuffer.h" #include "CircularBufferCollection.h" class PointCollection { friend class SegmenterSNC; friend class FileIO; friend class CircularBufferCollection; friend class TreeCollection; public: /** * Sorts the Points in the PointCollection by z (height) in descending order. * */ void SortByZ(); /** * Computes the bounding box of the PointCollection. * */ void ComputeBoundingBox(); /** * Computes the linear index of each Point in the PointCollection. * */ void ComputePointIndexes(); /** * Computes a grid coordinate (col, row) for each Point in the PointCollection. * * @param scaling_factor The coordinate scaling factor (1 metric, 10 = decimetric). Defaults to 1, if different values than 1 or 10 are given. */ void ComputeGridCoordinates(); /** * Assigns each Point to a grid cell. * */ void AssignGridCells(); /** * Extracts all the Points located within the specified CircularBuffer centered at (col_0, row_0) to the specified PointCollection. * * @param circular_buffer A reference to the CircularBuffer used in the extraction. * @param sample A reference to a PointCollection where the extracted points will contained. * @param col_0 The column at which the CircularBuffer is centerer. * @param row_0 The row at which the CircularBuffer is centerer. * */ void ExtractPointsInBuffer(CircularBuffer& circular_buffer, PointCollection& sample, int& col_0, int& row_0); /** * Finds all local maxima in the PointCollection. A Point is considered a local maxima if it's z coordinates is larger than or equal * to all other point wihtin the CircularBuffer centered on it. * * @param circular_buffer A reference to the CircularBuffer used in the local maxima definition. * */ void FindLocalMaxima(CircularBuffer& circular_buffer); /** * Set the int16 RGB color triplet for each Point in the PointCollection based on its tree index (tree_idx member). * * @param hsv_colormap A colormap consisting of int16 RGB triplets. * */ void SetRGBColors(std::vector<std::array<unsigned int, 3>> hsv_colormap); /** * Accessor to the coordinate scaling factor used in gridding. * */ unsigned int GetScalingFactor(); /** * Filter Points in the PointCollection by their classification. * * @param keep_classes The classes which are kept. * */ PointCollection FilterPointsByClass(std::vector<unsigned int>& keep_classes); PointCollection(){coordinate_scaling_ = 1;}; // Constructor ~PointCollection(){}; // Destructor private: /** * 3D Point. * */ struct Point { double x; double y; double z; int row; int col; unsigned int classification; unsigned int point_idx; unsigned int tree_idx; unsigned int local_maxima_status; bool segmentation_status; std::array<unsigned int,3> rgb_color; }; /** * Bounding box representing the horizontal extent of a PointCollection. * */ struct BoundingBox { bool availability; double width; double height; double x_min; double x_max; double y_min; double y_max; unsigned int x_min_idx; unsigned int x_max_idx; unsigned int y_min_idx; unsigned int y_max_idx; }; /** * Points. * */ std::vector<Point> points_; /** * Bounding box. * */ BoundingBox bounding_box_; /** * Grid. * */ std::vector<std::vector<int>> idx_grid_; /** * Number of grid columns. * */ unsigned int n_cols_; /** * Number of grid rows. * */ unsigned int n_rows_; /** * Coordinate scaling factor (1 metric, 10 = decimetric, 100 = centimetric, etc...) used in gridding. * */ unsigned int coordinate_scaling_; /** * Number of segmented points. * */ unsigned int n_segmented_; /** * Converts a linear grid cell index to a subscript coordinate (row, col). * * @param ncols The number of columns in the grid. * @param nrows ncols The number of rows in the grid. * @param idx The linear grid cell index. * @return Returns a coordinate (row, col). */ std::array<unsigned int,2> IndexToSubscript(unsigned int ncols, unsigned int nrows, unsigned int idx); /** * Converts a subscript coordinate (row, col) to a linear grid cell index. * * @param ncols The number of columns in the grid. * @param row The row of the Point. * @param column The column of the Point. * @return Returns a linear cell index. */ unsigned int SubscriptToIndex(unsigned int ncols, unsigned int row, unsigned int column); }; #endif
Java
UTF-8
20,267
1.664063
2
[]
no_license
package com.example.kelys.Models; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.kelys.Adapters.RoomAdapter; import com.example.kelys.Helpers.ConfirmFinalOrderActivity; import com.example.kelys.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.datepicker.MaterialDatePicker; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Objects; public class RoomHotel extends AppCompatActivity { private Button addToCartButton; private ImageView productImage; private TextView productprice, productDescription, productName, categorieChambre; private String productPID = "", hotelPID, hotelName, defUser; private String productID = ""; private TextView saveUser, saveUserPhone, saveUserMail; private String saveCurrentDate1,saveCurrentDate2,saveCurrentDate,saveCurrentTime; private String ActivityCaller; Dialog myDialog; private TextView nDialogDate1,nDialogDate2; private DatePickerDialog.OnDateSetListener onDateSetListener1, onDateSetListener2; String user_name, user_email, user_phoneNo; // Les preferences partagees SharedPreferences sharedPreferences; public static final String fileName = "login"; public static final String UsernamePreference = "Username"; public static final String EmailPreference = "Email"; public static final String Passwordpreference = "Password"; public static final String IsAdminpreference = "IsAdmin"; private static final String Tag = "RoomHotel"; Date currentmaxDate = Calendar.getInstance().getTime(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_room_hotel); sharedPreferences = getSharedPreferences(fileName, Context.MODE_PRIVATE); myDialog = new Dialog(this); productPID = getIntent().getStringExtra("pid"); hotelPID = getIntent().getStringExtra("HotelPid"); hotelName = getIntent().getStringExtra("HotelName"); ActivityCaller = getIntent().getStringExtra("ActivityCaller"); //defUser = getIntent().getStringExtra("username"); defUser = getCurrentUsername(sharedPreferences); Log.d("defUser", defUser); productImage = (ImageView) findViewById(R.id.room_image_details); productName = (TextView) findViewById(R.id.room_name_details); productDescription = (TextView) findViewById(R.id.room_description_detail); productprice = (TextView) findViewById(R.id.room_price_details); addToCartButton = (Button) findViewById(R.id.pd_add_to_cart_button); categorieChambre = (TextView) findViewById(R.id.room_type_detail); getProductDetails(productPID); getUserDetails(defUser); addToCartButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //données popup final TextView txtclose; final Button btnFollow; myDialog.setContentView(R.layout.popup_room_reservation); txtclose =(TextView) myDialog.findViewById(R.id.txtclose); //txtclose.setText("M"); btnFollow = (Button) myDialog.findViewById(R.id.btn_reserv); final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(RoomHotel.this); builder.setTitle("Effectuer une Réservation"); builder.setMessage("Voulez-vous effectuer une réservation?"); builder.setPositiveButton("Oui", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { txtclose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myDialog.dismiss(); } }); myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); myDialog.show(); getDataPicker(); btnFollow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); SimpleDateFormat currentDate = new SimpleDateFormat("MMMM dd, yyyy"); saveCurrentDate = currentDate.format(calendar.getTime()); SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a"); saveCurrentTime = currentTime.format(calendar.getTime()); productID = saveCurrentDate + saveCurrentTime; saveDatainReservationTable(); saveDatainFirebase(); } }); } }); builder.setNegativeButton("Non", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.show(); } }); } private String getCurrentUsername(SharedPreferences shared) { String username = shared.getString(UsernamePreference,""); return username; } private void getDataPicker(){ //popup datepicker dialog nDialogDate1 = (TextView) myDialog.findViewById(R.id.choose_date1); nDialogDate2 = (TextView) myDialog.findViewById(R.id.choose_date2); // désactiver nDialogDate2 nDialogDate2.setEnabled(false); nDialogDate2.setClickable(false); nDialogDate1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); int day = calendar.get(Calendar.DAY_OF_MONTH); int month = calendar.get(Calendar.MONTH); int year = calendar.get(Calendar.YEAR); calendar.add(Calendar.YEAR, -2); // subtract 2 years from now final DatePickerDialog datePickerDialog = new DatePickerDialog( RoomHotel.this, R.style.MyDatePickerDialogTheme, onDateSetListener1, year,month,day); //datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE)); //datePickerDialog.getButton(DialogInterface.BUTTON_POSITIVE).setBackgroundColor(Color.rgb(16,1,100)); // datePickerDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setBackgroundColor(Color.argb(140,16,1,100)); // datePickerDialog.getButton(DialogInterface.BUTTON_NEUTRAL).setBackgroundColor(Color.argb(140,16,1,100)); /* * trouver la date maximum dans la BDD qui servira à définir le datepickerdialog * voir ci-dessus * */ final Query productRef = FirebaseDatabase.getInstance().getReference().child("Reservation Chambre").orderByChild("pid").equalTo(productPID); productRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { /* for (DataSnapshot sn : snapshot.getChildren()) { Date tempDate = null; Log.d("date1", sn.child("date1").getValue(String.class)); try { tempDate = new SimpleDateFormat("dd/MM/yyyy").parse(sn.child("date1").getValue(String.class)); if( tempDate.getTime() >= currentmaxDate.getTime()) { currentmaxDate = tempDate; } } catch (ParseException e) { Log.e("error",e.getMessage()); } } */ datePickerDialog.getDatePicker().setMinDate(currentmaxDate.getTime()); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); /* * trouver la date maximum dans la BDD qui servira à définir le datepickerdialog * voir ci-dessous * */ datePickerDialog.show(); } }); nDialogDate2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); int day = calendar.get(Calendar.DAY_OF_MONTH); int month = calendar.get(Calendar.MONTH); int year = calendar.get(Calendar.YEAR); calendar.add(Calendar.YEAR, -2); // subtract 2 years from now Log.d("ProductID",productID); DatePickerDialog datePickerDialog = new DatePickerDialog( RoomHotel.this, R.style.MyDatePickerDialogTheme, onDateSetListener2, year,month,day); datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE)); datePickerDialog.show(); //datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis()); Date tempDate = null; try { tempDate = new SimpleDateFormat("dd/MM/yyyy").parse(saveCurrentDate1); } catch (ParseException e) { e.printStackTrace(); } datePickerDialog.getDatePicker().setMinDate(tempDate.getTime()); } }); onDateSetListener1 =new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { month = month + 1; Log.d(Tag, "onDataSet : mm/dd/yyy: " + dayOfMonth + "/" + month + "/" + year); String date = dayOfMonth + "/" + month + "/" + year; nDialogDate1.setText(date); saveCurrentDate1 = date; // activer ndialog2 nDialogDate2.setEnabled(true); nDialogDate2.setClickable(true); } }; onDateSetListener2 =new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { month = month + 1; Log.d(Tag,"onDataSet : mm/dd/yyy: " + dayOfMonth + "/" + month + "/" + year); String date = dayOfMonth + "/" + month + "/" + year; nDialogDate2.setText(date); saveCurrentDate2 = date; } }; } private void getProductDetails(String productPID) { DatabaseReference productRef = FirebaseDatabase.getInstance().getReference().child("Chambre"); productRef.child(productPID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.exists()){ RoomAdapter room = snapshot.getValue(RoomAdapter.class); productName.setText(room.getPname()); productDescription.setText(room.getDescription()); productprice.setText(room.getPrice()); categorieChambre.setText(room.getDetail_room()); Picasso.get().load(room.getImage()).into(productImage); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } private void getUserDetails(String defUser){ DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("users").child(defUser); Log.d("reference",String.valueOf(reference)); saveUser = (TextView) findViewById(R.id.save_user); saveUserPhone = (TextView) findViewById(R.id.save_userphone); saveUserMail = (TextView) findViewById(R.id.save_usermail); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.exists()){ user_name = Objects.requireNonNull(snapshot.child("name").getValue()).toString(); user_email = Objects.requireNonNull(snapshot.child("email").getValue()).toString(); user_phoneNo = Objects.requireNonNull(snapshot.child("phoneNo").getValue()).toString(); saveUser.setText(user_name); saveUserMail.setText(user_email); saveUserPhone.setText(user_phoneNo); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } private void saveDatainFirebase(){ final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Reservation Chambre"); final HashMap<String, Object> cartMap = new HashMap<>(); cartMap.put("pid", productPID); cartMap.put("id", productID); cartMap.put("pname", productName.getText().toString()); cartMap.put("price", productprice.getText().toString()); cartMap.put("date1", saveCurrentDate1); cartMap.put("date2", saveCurrentDate2); cartMap.put("name user", saveUser.getText().toString()); cartMap.put("phone user", saveUserPhone.getText().toString()); cartMap.put("mail user", saveUserMail.getText().toString()); cartListRef.child(productID).updateChildren(cartMap) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Toast.makeText(RoomHotel.this,"Réservation en cours...",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RoomHotel.this,ConfirmFinalOrderActivity.class); if(ActivityCaller == null) { } else if(ActivityCaller.equals("HomeActivity")) { intent.putExtra("ActivityCaller","HomeActivity"); } startActivity(intent); } else { String message = task.getException().toString(); Toast.makeText(RoomHotel.this,"Error: " , Toast.LENGTH_SHORT).show(); } } }); } private void saveDatainReservationTable(){ final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Reservations"); final HashMap<String, Object> cartMap = new HashMap<>(); cartMap.put("pid", productPID); cartMap.put("id", productID); cartMap.put("Nom_produit", productName.getText().toString()); cartMap.put("price", productprice.getText().toString()); cartMap.put("date_debut", saveCurrentDate1); cartMap.put("date_fin", saveCurrentDate2); cartMap.put("name_user", saveUser.getText().toString()); cartMap.put("phone_user", saveUserPhone.getText().toString()); cartMap.put("mail_user", saveUserMail.getText().toString()); cartMap.put("categorie", "Chambre"); cartMap.put("statut", "En attente"); cartMap.put("mail_user_statut", saveUserMail.getText().toString()+"_En attente"); cartListRef.child(productID).updateChildren(cartMap) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ } else { } } }); } @Override public void onBackPressed() { super.onBackPressed(); if(ActivityCaller == null) { Intent intent = new Intent(RoomHotel.this,DetailHotel.class); intent.putExtra("pid", hotelPID); intent.putExtra("pname", hotelName); startActivity(intent); } else if(ActivityCaller.equals("HomeActivity")) { Intent intent = new Intent(RoomHotel.this,DetailHotel.class); intent.putExtra("pid", hotelPID); intent.putExtra("pname", hotelName); intent.putExtra("ActivityCaller", "HomeActivity"); startActivity(intent); } } private long getMaxDateForRoomReservation() { Query productRef = FirebaseDatabase.getInstance().getReference().child("Reservation Chambre").orderByChild("pid").equalTo(productPID); productRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot sn : snapshot.getChildren()) { Date tempDate = null; Log.d("date1", sn.child("date1").getValue(String.class)); try { tempDate = new SimpleDateFormat("dd/MM/yyyy").parse(sn.child("date1").getValue(String.class)); if( tempDate.getTime() >= currentmaxDate.getTime()) { currentmaxDate = tempDate; Log.d("currentmaxdate", String.valueOf(currentmaxDate)); } } catch (ParseException e) { Log.e("error",e.getMessage()); } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); return currentmaxDate.getTime(); } }
Java
UTF-8
769
2.703125
3
[]
no_license
package cn.pgyyd.mcg.singleton; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; //TODO: 重写此类,更改为 时间+机器ID+random 组合而成的ID public class JobIDGenerator { private static long nodeId; public static void init(int id) { nodeId = id % 100; } private static AtomicLong atomicLong = new AtomicLong(0); private static JobIDGenerator ourInstance = new JobIDGenerator(); public static JobIDGenerator getInstance() { return ourInstance; } private JobIDGenerator() { } public long generate() { long rand = atomicLong.incrementAndGet() % 10000; return System.currentTimeMillis() * 1000000 + nodeId * 10000 + rand; } }
Python
UTF-8
3,642
2.734375
3
[]
no_license
import markdown import re from fenced_code_plus import FencedCodePlusExtension import unittest import pytest unadorned_code_block_md = """\ ``` def foo(): bar = 4 return 8 ``` """ unadorned_code_block_html = """\ <pre><code>def foo(): bar = 4 return 8 </code></pre>""" only_language_md = """\ ``` python def foo(): bar = 4 return 8 ``` """ only_language_html = """\ <pre><code class="python"> def foo(): bar = 4 return 8 </code></pre>""" only_filename_md = """\ ``` path="arbitrary string here" def foo(): bar = 4 return 8 ``` """ only_filename_html = """\ <pre><code data-path="arbitrary string here"> def foo(): bar = 4 return 8 </code></pre>""" only_numbering_md = """\ ``` number=3 def foo(): bar = 4 return 8 ``` """ only_numbering_html = """\ <pre><code data-number="3"> def foo(): bar = 4 return 8 </code></pre>""" only_numbering_default_md = """\ ``` number def foo(): bar = 4 return 8 ``` """ only_numbering_default_html = """\ <pre><code data-number="0"> def foo(): bar = 4 return 8 </code></pre>""" language_hl_lines_md = """\ ``` python hl_lines="4 5" def foo(): bar = 4 return 8 ``` """ language_hl_lines_html = """\ <pre><code class="python" data-hl_lines="4 5"> def foo(): bar = 4 return 8 </code></pre>""" language_hl_lines_numbering_md = """\ ``` python number hl_lines="4 5" def foo(): bar = 4 return 8 ``` """ language_hl_lines_numbering_html = """\ <pre><code class="python" data-hl_lines="4 5" data-number="0"> def foo(): bar = 4 return 8 </code></pre>""" hl_lines_numbering_filename_md = """\ ``` number path="another arbitrary string" hl_lines="4 5" def foo(): bar = 4 return 8 ``` """ hl_lines_numbering_filename_html = """\ <pre><code data-hl_lines="4 5" data-number="0" data-path="another arbitrary string"> def foo(): bar = 4 return 8 </code></pre>""" language_hl_lines_numbering_filename_md = """\ ``` python number path="another arbitrary string" hl_lines="4 5" def foo(): bar = 4 return 8 ``` """ language_hl_lines_numbering_filename_html = """\ <pre><code class="python" data-hl_lines="4 5" data-number="0" data-path="another arbitrary string"> def foo(): bar = 4 return 8 </code></pre>""" class TestFencedCodePlus(unittest.TestCase): def test_unadorned_code_block(self): assert markdown.markdown(unadorned_code_block_md, extensions=[FencedCodePlusExtension()]) ==\ unadorned_code_block_html def test_only_language(self): assert markdown.markdown(only_language_md, extensions=[FencedCodePlusExtension()]) ==\ only_language_html def test_only_filename(self): assert markdown.markdown(only_filename_md, extensions=[FencedCodePlusExtension()]) ==\ only_filename_html def test_only_numbering(self): assert markdown.markdown(only_numbering_md, extensions=[FencedCodePlusExtension()]) ==\ only_numbering_html def test_only_numbering_default(self): assert markdown.markdown(only_numbering_default_md, extensions=[FencedCodePlusExtension()]) ==\ only_numbering_default_html def test_language_hl_lines(self): assert markdown.markdown(language_hl_lines_md, extensions=[FencedCodePlusExtension()]) ==\ language_hl_lines_html def test_language_hl_lines_numbering_filename(self): assert markdown.markdown(language_hl_lines_numbering_filename_md, extensions=[FencedCodePlusExtension()]) ==\ language_hl_lines_numbering_filename_html if __name__ == '__main__': pytest.main()
Java
UTF-8
2,620
3.640625
4
[]
no_license
package recursion_dc_dp.p120; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author :lennyz * @desc: 2020/11/12 11:04 PM * 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。 * 相邻的结点 在这里指的是 下标 与 上一层结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。 * 例如,给定三角形: * <p> * [ * [2], * [3,4], * [6,5,7], * [4,1,8,3] * ] * <p> * 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 * <p> * 如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。 */ public class P120Solution01 { // 错误 自底向上 public int minimumTotal(List<List<Integer>> triangle) { if (triangle.size() == 0) { return 0; } int n = triangle.size() - 1; return dp(triangle, n, -1); } public int dp(List<List<Integer>> triangle, int n, int last) { if (n == 0) return triangle.get(0).get(0); Integer min = null; if (last < 0) { min = triangle.get(n).get(0); for (int i = 0; i < triangle.get(n).size(); i++) { if (triangle.get(n).get(i) < min) { min = triangle.get(n).get(i); last = i; } } } else { List<Integer> subList = triangle.get(n); for (int i = last - 1; i <= last; i++) { if (i >= 0 && i < subList.size()) { if (min == null) { min = subList.get(i); } else if (subList.get(i) < min) { min = subList.get(i); last = i; } } } } System.out.println(last + " " + min); return dp(triangle, n - 1, last) + min; } @Test public void test() { List<List<Integer>> triangle = new ArrayList<>(); triangle.add(Arrays.asList(-1)); triangle.add(Arrays.asList(3, 2)); triangle.add(Arrays.asList(-3, 1, -1)); // triangle.add(Arrays.asList(4, 1, 8, 3)); // List<List<Integer>> triangle = new ArrayList<>(); // triangle.add(Arrays.asList(2)); // triangle.add(Arrays.asList(3, 4)); // triangle.add(Arrays.asList(6, 5, 7)); // triangle.add(Arrays.asList(4, 1, 8, 3)); System.out.println(minimumTotal(triangle)); } }
Python
UTF-8
3,824
3.5
4
[]
no_license
""" MontyHallProblem Description: """ import random import math # constants. NUM_DOORS = 3 # end constants. carDoor = None def generateCarDoor(): global carDoor carDoor = random.randint(1, NUM_DOORS) def getRemainingChoices(toExclude, lo, hi): uwu = [] for i in range(lo, hi): canAdd = True for j in toExclude: if i == j: canAdd = False if canAdd: uwu.append(i) return uwu def generateRandomGoatKnown(initChoice): uwu = getRemainingChoices([carDoor, initChoice], 1, NUM_DOORS + 1) return uwu[random.randint(0, len(uwu) - 1)] def takeNumericInput(): global running choice = input() if choice == "quit": print("Goodbye") raise SystemExit choiceInt = int(choice) return choiceInt def doManualSim(trials): trial = 0 remainPlayersWon = 0 remainPlayersTotal = 0 switchPlayersWon = 0 switchPlayersTotal = 0 while trial < trials: choicesInit = getRemainingChoices([-1], 1, NUM_DOORS+1) print("Choose a door. Choices: %s" % choicesInit) initChoice = takeNumericInput() generateCarDoor() goatInfo = generateRandomGoatKnown(initChoice) print("Door #%d is known to be a goat." % goatInfo) print("Please pick from the following choices: %s" % str(getRemainingChoices([goatInfo], 1, NUM_DOORS + 1))) remainChoice = takeNumericInput() if remainChoice == initChoice: remainPlayersTotal += 1 if remainChoice == carDoor: print("You got the car!") remainPlayersWon += 1 else: print("You did not get the car!") else: switchPlayersTotal += 1 if remainChoice == carDoor: print("You got the car!") switchPlayersWon += 1 else: print("You did not get the car!") print("-----------------------\n") trial += 1 print("SwitchWon (n=%d): %.4f%%" % (switchPlayersTotal, float(100.0 * switchPlayersWon / switchPlayersTotal))) print("RemainWon (n=%d): %.4f%%" % (remainPlayersTotal, float(100.0 * remainPlayersWon / remainPlayersTotal))) def doAutoSim(trials): trial = 0 half = trials / 2 remainPlayersWon = 0 remainPlayersTotal = 0 switchPlayersWon = 0 switchPlayersTotal = 0 while trial < trials: choicesInit = getRemainingChoices([-1], 1, NUM_DOORS+1) initChoice = random.randint(1, NUM_DOORS) generateCarDoor() goatInfo = generateRandomGoatKnown(initChoice) remainingChoices = getRemainingChoices([goatInfo], 1, NUM_DOORS + 1) remainChoice = None if trial < half: remainPlayersTotal += 1 remainChoice = initChoice if remainChoice == carDoor: remainPlayersWon += 1 else: switchPlayersTotal += 1 for i in remainingChoices: if i != initChoice: remainChoice = i break if remainChoice == carDoor: switchPlayersWon += 1 trial += 1 print("SwitchWon (n=%d): %.4f%%" % (switchPlayersTotal, float(100.0 * switchPlayersWon / switchPlayersTotal))) print("RemainWon (n=%d): %.4f%%" % (remainPlayersTotal, float(100.0 * remainPlayersWon / remainPlayersTotal))) print("Would you like to:") print("[1] Try the simulation yourself for a set number of trials?") print("[2] Run the simulation with an automated number of trials?") print("[3] Quit") choice = takeNumericInput() if choice != 3: print("How many trials would you like?") trials = takeNumericInput() if choice == 1: doManualSim(trials) elif choice == 2: doAutoSim(trials)
Java
UTF-8
430
2.140625
2
[]
no_license
package com.tae.letscook.Utils; import android.content.Context; import android.view.inputmethod.InputMethodManager; /** * Created by Eduardo on 02/01/2016. */ public class KeyboardUtils { public static void showKeyboard(Context context) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } }
SQL
UTF-8
4,825
3.15625
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 3.3.9.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Sep 21, 2012 at 02:16 PM -- Server version: 5.5.9 -- PHP Version: 5.2.17 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `IP` -- CREATE DATABASE `IP` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `IP`; -- -------------------------------------------------------- -- -- Table structure for table `doc` -- CREATE TABLE `doc` ( `DocID` int(3) NOT NULL, `DocName` varchar(100) DEFAULT NULL, `Department` varchar(100) DEFAULT NULL, `OPD_Days` char(3) DEFAULT NULL, PRIMARY KEY (`DocID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `doc` -- INSERT INTO `doc` VALUES(104, 'KK Sharma', 'paed', 'TTS'); INSERT INTO `doc` VALUES(201, 'CK Sharma', 'Ortho', 'MWF'); INSERT INTO `doc` VALUES(301, 'Mr. Rawat', 'ENT', 'TTS'); -- -------------------------------------------------------- -- -- Table structure for table `marks` -- CREATE TABLE `marks` ( `schno` int(4) NOT NULL, `Maths` decimal(6,2) NOT NULL, `Physics` decimal(6,2) NOT NULL, `Chemistry` decimal(6,2) NOT NULL, `IP` decimal(6,2) NOT NULL, `Average` decimal(6,2) NOT NULL, PRIMARY KEY (`schno`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `marks` -- INSERT INTO `marks` VALUES(111, 90.00, 76.00, 89.00, 69.00, 81.00); INSERT INTO `marks` VALUES(123, 50.00, 87.00, 87.00, 91.00, 78.75); INSERT INTO `marks` VALUES(323, 60.00, 78.00, 89.00, 92.00, 79.75); INSERT INTO `marks` VALUES(839, 80.00, 65.00, 70.00, 98.75, 78.44); INSERT INTO `marks` VALUES(2483, 85.00, 79.00, 81.00, 91.00, 84.00); INSERT INTO `marks` VALUES(2484, 80.00, 75.00, 69.00, 97.00, 80.25); -- -------------------------------------------------------- -- -- Table structure for table `parents` -- CREATE TABLE `parents` ( `schno` int(4) NOT NULL, `fname` varchar(200) NOT NULL, `mname` varchar(200) NOT NULL, `contact` varchar(10) NOT NULL, `occupation` varchar(200) NOT NULL, KEY `schno` (`schno`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `parents` -- INSERT INTO `parents` VALUES(839, 'Manoj Saraf', 'Sangita Saraf', '9630112361', 'Business'); INSERT INTO `parents` VALUES(2483, 'Puneet Godha', 'Shefali Godha', '968544503', 'Builder'); INSERT INTO `parents` VALUES(2484, 'Vineet Godha', 'Sangita Godha', '9685445204', 'Lawyer'); INSERT INTO `parents` VALUES(323, 'Mr. Sachdeva', 'Mrs. Sachdeva', '9845671209', 'Hotel'); INSERT INTO `parents` VALUES(123, 'Mr. Rajpal', 'Mrs. Rajpal', '9825705882', 'Business'); INSERT INTO `parents` VALUES(111, 'Mr. Saluja', 'Mrs. Saluja ', '8537783587', 'Autoparts'); -- -------------------------------------------------------- -- -- Table structure for table `pat` -- CREATE TABLE `pat` ( `PatNo` int(11) NOT NULL DEFAULT '0', `PatName` varchar(100) DEFAULT NULL, `DocID` int(3) DEFAULT NULL, PRIMARY KEY (`PatNo`), KEY `DocID` (`DocID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `pat` -- INSERT INTO `pat` VALUES(1, 'Neeraj', 301); INSERT INTO `pat` VALUES(4, 'Vijay', 104); INSERT INTO `pat` VALUES(5, 'Nandini', 201); -- -------------------------------------------------------- -- -- Table structure for table `students` -- CREATE TABLE `students` ( `schno` int(4) NOT NULL, `name` varchar(200) NOT NULL, `dob` date NOT NULL, `class` varchar(4) NOT NULL, `subject` varchar(20) NOT NULL, PRIMARY KEY (`schno`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `students` -- INSERT INTO `students` VALUES(111, 'Abhiroop Saluja', '1995-10-05', '12G', 'Commerce IP'); INSERT INTO `students` VALUES(123, 'Rahul Rajpal', '1995-12-30', '12G', 'Commerce IP'); INSERT INTO `students` VALUES(323, 'Amrit Sachdeva', '1994-10-19', '12G', 'Commerce PE'); INSERT INTO `students` VALUES(839, 'Ayush Saraf', '1996-02-29', '12B', 'PCMIP'); INSERT INTO `students` VALUES(2483, 'Surbhit Godha', '1995-07-19', '12B', 'PCMPE'); INSERT INTO `students` VALUES(2484, 'Harshit Godha', '1995-07-30', '12E', 'Commerce IP'); -- -- Constraints for dumped tables -- -- -- Constraints for table `marks` -- ALTER TABLE `marks` ADD CONSTRAINT `marks_ibfk_1` FOREIGN KEY (`schno`) REFERENCES `students` (`schno`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `parents` -- ALTER TABLE `parents` ADD CONSTRAINT `parents_ibfk_1` FOREIGN KEY (`schno`) REFERENCES `students` (`schno`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `pat` -- ALTER TABLE `pat` ADD CONSTRAINT `pat_ibfk_1` FOREIGN KEY (`DocID`) REFERENCES `doc` (`DocID`) ON DELETE CASCADE ON UPDATE CASCADE;
Java
WINDOWS-1252
499
2.9375
3
[]
no_license
package fcu.iecs.oop.password; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner keyboard = new Scanner(System.in); String in; while(true){ System.out.println("пJ@r : "); in = keyboard.next(); if(in.compareTo("exit") == 0) break; PasswordEncorder x = new PasswordEncorder(); String result = x.encode(in); System.out.println(result); } System.out.println("End"); keyboard.close(); } }
TypeScript
UTF-8
1,026
2.890625
3
[]
no_license
// throttleTime: lo contrario que debounceTime, emite el valor al llamar al obs y luego ignora las demas x segs import { asyncScheduler, fromEvent } from 'rxjs'; import { throttleTime, distinctUntilChanged, map, pluck } from 'rxjs/operators'; const click$ = fromEvent(document, 'click'); // Esto es útil para controlar observables que emiten una gran catidad // de mensajes muy rapidamente, con demasiados eventos que pueden bajar el rendimiento. click$.pipe( throttleTime(2000) ); const input = document.createElement('input'); document.body.append(input); const input$ = fromEvent(input, 'keyup').pipe( throttleTime(1000, asyncScheduler, { leading: true, // primer elemento trailing: true // ultimo elemento }), pluck('target','value'), // que imprima solo el valor del target distinctUntilChanged() // solo se llama cuando es diferente (si pongo pepsi llama, si borro rapidamente antes del x segs y pongo otra vez la i que he quitado no llama) ); input$.subscribe(console.log);
Python
UTF-8
1,634
2.859375
3
[]
no_license
# login attempts class User(): def __init__(self, first_name, last_name, age, city): self.first_name = first_name self.last_name = last_name self.age = age self.city = city self.login = 0 self.password = '' def greet(slef): print('Welcome %s %s, you registration is ready.' %(self.first_name.title(), self.last_name.title())) def skill(self): print('Please enter your bio %s' %self.first_name.tittle()) def user_info(self): print('\n*************************************************************\n') print('Your info \nFull name: %s %s\nAge: %s\nCity: %s' %(self.first_name.title(), self.last_name.title(), str(self.age), self.city.title())) print('\n*************************************************************\n') def login_att(self): psw = self.password active = True while active: psw = input("Please add your password: ") if psw == 'mimicom2433062fl': active = False self.login = 0 print ('Well Done') else: self.login = self.login + 1 print('This is your ', self.login,' try') print ('You have %s logs' %str(self.login), '!We did reset of your attempts!') acitve = True slavo_user = User('slavo', 'popovic', 35, 'fort lauderdale') # tamara_user = User('tamara', 'nakic', 33, 'pompano beach') # nenad_user = User('nenad', 'sotirovic', 37, 'Dobrec') # milos_user = User('milos', 'puric', 36, 'belgrade') slavo_user.login_att()
Java
UTF-8
2,624
2.796875
3
[]
no_license
package radar.scale.test; import radar.model.AnalysisResult; import radar.model.Model; import radar.model.ModelSolver; import radar.model.Parser; import radar.utilities.Helper; public class RADAR_Performance { public static void main(String[] args) { // TODO Auto-generated method stub try { String outputDir= "/Users/INTEGRALSABIOLA/Documents/JavaProject/RADAR/uk.ac.ucl.cs.examples/"; String [] models = new String [] {"CBA", "FDM", "BSPDM", "ECS", "SAS"}; Integer []simArray = new Integer [] {1000, 10000, 100000, 1000000}; for (String m : models ){ for (int i =0; i < 2; i++){ for (Integer sim : simArray){ String modelPath = outputDir + m +"/" + m + ".rdr"; new RADAR_Performance().analyseRadarModel (modelPath,sim,outputDir); } } } }catch (Exception e){ System.out.print("Error: "); System.out.println(e.getMessage()); } } Model loadModel (String modelPath, int nbr_sim, String infoObj,String subGraphObj) throws Exception{ //4. when parse is specified quickly parse and write a message that the model is parsed. Model semanticModel =null; try { semanticModel = new Parser().parseCommandLineModel(modelPath.trim(), nbr_sim, infoObj,subGraphObj); }catch (RuntimeException re){ throw new RuntimeException( "Error: "+ re.getMessage()); } return semanticModel; } void analyseRadarModel (String modelPath , int nbr_sim, String outputDir){ try { // get sematic model from model file Model semanticModel = loadModel (modelPath,nbr_sim, "", "" ); // analyse model AnalysisResult result = ModelSolver.solve(semanticModel); String analysisResult = result.analysisToString(); String modelResultPath = outputDir+ nbr_sim+ "/"+semanticModel.getModelName() + "/Performance/AnalysisResult/"; Helper.printResults (modelResultPath , analysisResult, semanticModel.getModelName() +".out", true); String referenceDecisions = result.getReferenceDecisions(); String referencePath = outputDir+ nbr_sim+ "/"; Helper.printResults (referencePath , referenceDecisions, semanticModel.getModelName() +".ref", true); long runtime = result.getRunTime(); String runTimePath = outputDir+ nbr_sim+ "/"; Helper.printResults (runTimePath , String.valueOf(runtime), semanticModel.getModelName() +".time", true); System.out.println("Finished with " +modelPath + " for simulaion run " + nbr_sim); }catch (Exception e){ System.out.print("Error: "); System.out.println(e.getMessage()); } } }
PHP
UTF-8
433
2.796875
3
[ "MIT" ]
permissive
<?php namespace App\Repositories\User; use App\Models\User; use App\Repositories\User\UserRepositoryInterface; class UserRepository implements UserRepositoryInterface { public $model; public function __construct(User $user) { $this->model = $user; } public function all() { return $this->model->all(); } public function find($id){ return $this->model->find($id); } }
C
UTF-8
1,594
2.984375
3
[]
no_license
/* * basics_header_init.h * * Created on: 10 de nov. de 2016 * Author: Pablo */ #ifndef BASICS_HEADER_INIT_H_ #define BASICS_HEADER_INIT_H_ #include "header.h" static inline void pin_set(uint8_t port, uint8_t pin, bool estado) { Chip_GPIO_SetPinState(LPC_GPIO, port, pin, estado); } static inline bool pin_get(uint8_t port, uint8_t pin) { return Chip_GPIO_GetPinState(LPC_GPIO, port, pin); } static inline void pin_gpio_init(uint8_t port, uint8_t pin, uint32_t mode, bool salida) { // if(DEBUG_MODE) // { // printf("[info] pin_init: \n"); // printf("\t puerto %hhu, pin %hhu, modo %hhu, salida %hhu \n", port, pin, mode, salida); // } Chip_IOCON_PinMux(LPC_IOCON, port, pin, mode, IOCON_FUNC0); // Setea modo (inactivo/pulldown/pullup/repeater) y funcion (gpio) del pin Chip_GPIO_SetDir(LPC_GPIO, port, pin, (uint8_t)salida); // Setea direccion del pin: entrada o salida if(salida) pin_set(port, pin, 0); // Inicializa pin en 0 (si es de salida) } static inline void pin_init(uint8_t port, uint8_t pin, uint32_t mode, uint8_t func) { if(DEBUG_MODE) { if(func == 0) { printf("[error] pin_init:\n"); printf("\t Quiso inicializar pin como GPIO sin usar funcion dedicada \"pin_gpio_init\" \n"); } // else // { // printf("[info] pin_init:\n"); // } // printf("\t puerto %hhu, pin %hhu, modo %hhu, funcion %hhu\n", port, pin, mode, func); // Setea modo (inactivo/pulldown/pullup/repeater) y funcion del pin } Chip_IOCON_PinMux(LPC_IOCON, port, pin, mode, func); // Setea modo y funcion del pin } #endif /* BASICS_HEADER_INIT_H_ */
C#
UTF-8
590
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ggj_engine.Source.Level { public class Tile { public int Type; public bool Walkable; public int X, Y; public Tile Parent; public float GScore, HScore, FScore; public Tile(int type, bool walkable, int x, int y) { Type = type; Walkable = walkable; X = x; Y = y; Parent = null; GScore = 0; HScore = 0; FScore = 0; } } }
C++
UTF-8
1,109
3.09375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; const int inf = INT_MAX; bool is_valid(int n, int m, int i, int j){ return i > -1 && j > -1 && i < n && j < m; } int main(){ int n, m; //n no of rows and m no of columns cin >> n >> m; vector<vector<int>> v(n, vector<int>(m)); for (int i = 0; i < n; i++){ for (int j = 0; j < m; j++){ cin >> v[i][j]; } } int dest_row, dest_col; cin >> dest_row >> dest_col; for (int i = dest_row; i >= 0;i--){ for (int j = dest_col; j >= 0; j--){ int tmp = inf; //Down if(is_valid(n, m, i+1, j)){ tmp = v[i + 1][j] + v[i][j]; } //Right if(is_valid(n, m, j+1, i)){ tmp = min(tmp, v[i][j + 1] + v[i][j]); } //Diagonal Down if(is_valid(n, m, i+1, j+1)){ tmp = min(tmp, v[i + 1][j + 1] + v[i][j]); } if(tmp == inf) tmp = v[i][j]; v[i][j] = tmp; } } cout << v[0][0] << endl; }
Python
UTF-8
1,219
3.25
3
[]
no_license
# Read Input f = open("input.txt", "r") actionNorth = "N" actionSouth = "S" actionEast = "E" actionWest = "W" actionLeft = "L" actionRight = "R" actionForward = "F" directionNorth = 0 directionEast = 1 directionSouth = 2 directionWest = 3 direction = directionEast startX = 0 startY = 0 x = startX y = startY waypointX = 10 waypointY = -1 for l in f: action = l[0] value = int(l[1:]) if action == actionNorth: waypointY -= value elif action == actionSouth: waypointY += value elif action == actionEast: waypointX += value elif action == actionWest: waypointX -= value elif action == actionLeft: if value == 90: tmp = waypointX waypointX = waypointY waypointY = -tmp elif value == 180: waypointX *= -1 waypointY *= -1 elif value == 270: tmp = waypointX waypointX = -waypointY waypointY = tmp elif action == actionRight: if value == 90: tmp = waypointX waypointX = -waypointY waypointY = tmp elif value == 180: waypointX *= -1 waypointY *= -1 elif value == 270: tmp = waypointX waypointX = waypointY waypointY = -tmp elif action == actionForward: x += waypointX * value y += waypointY * value print(abs(x - startX) + abs(y - startY))
Markdown
UTF-8
1,699
2.625
3
[ "MIT" ]
permissive
# Crypto-Vote This is a demonstration of how Blind Signature can be used in the scenario of E-Voting. Read the reference or [my presentation at INFAS 2017](https://www.slideshare.net/s3131212/ss-76836570) for more information on how the schema works. # Screenshot ![Vote Page](screenshot1.png) ![Result Page](screenshot2.png) ## Installation ### Production First clone the repo: ``` git clone https://github.com/s3131212/Crypto-Vote.git cd Crypto-Vote ``` Then build the frontend: ``` cd client # pwd = /path/to/repo/client npm install npm run build ``` Edit the database connection info: ``` cd ../server # pwd = /path/to/repo/server vim index.js ``` Make sure you have already import `db.sql` Last, start the server: ``` npm install npm start ``` When no port is set in environment variable, port `5000` will be used. ### Development Start both backend server and React dev server. To start backend server, use: ``` # pwd = /path/to/repo/server npm start ``` Before starting React dev server, change the `proxy` in `package.json` to backend server address. Then start the React dev server: ``` cd ../client # pwd = /path/to/repo/client npm start ``` Now use `localhost:3000` (or the port React dev server used) to access Crypto-Vote. ## References ### Paper J. Radwin, Michael & Phil Klein, Professor. (1997). An Untraceable, Universally Verifiable Voting Scheme. 蘇品長(Pin-Chang Su);葉昱宗(Yui-Chong Yeh)(2017)。新型態之電子投票機制設計。電子商務學報。19(1)。29-50。 ### Code [Deploying a React app with React-Router and an Express Backend](https://dev.to/nburgess/creating-a-react-app-with-react-router-and-an-express-backend-33l3) # LICENSE MIT
C
UTF-8
378
3.046875
3
[]
no_license
#include <stdio.h> int main() { int num, i; char str[19], c; FILE *fp, *fop; fp = fopen ("numbers.txt", "w"); if(fp == NULL) { printf("Error!"); return; } for(;num!=-1;){ printf("Enter number between 1-10: "); scanf("%d", &num); fprintf(fp, "%d ", num); } fclose(fp); return 0; }
C
UTF-8
2,145
3.65625
4
[]
no_license
#include <stdio.h> //inclusione delle librerie necessarie al programma #include <string.h> #include <stdlib.h> #include <time.h> #define MAX 128 //limite dei caratteri per le stringhe int main ( void ) { char M[128]; printf( "Inserire una stringa M da cifrare\n"); //inserimento da parte dell'utente della stringa iniziale plaintext M scanf("%127s", M); fgets(M, MAX, stdin); printf("%s", "Inserire 1 se l'utente desidera digitare una stringa a suo piacimento \n" // dare la possibilità all'utente di decidere tra 2 opzioni "Inserire 2 se l'utente desidera generare casualmente una stringa k di lunghezza pari ad M : \n"); int order; scanf("%d", &order); if (order == 1) { // istruzioni se l'utente decide la prima opzione di inserire la stringa a piacere char plaintext[MAX]; char chiave[MAX]; int M; int k; puts("Inserire stringa a piacere di lunghezza uguale o superiore a M"); scanf( "%d", &k); M=strlen(plaintext); k=strlen(chiave); if (M==k) printf("Le stringhe hanno lo stesso numero di caratteri\n"); else if(M<k) printf("La prima stringa è minore rispetto alla seconda\n"); else printf ("La seconda stringa è più lunga della prima"); } char k; scanf ("%127s", M); char C; scanf("%127s", M); scanf("%127s", k); C = M^k; printf("\n"); // conclusione dell'istruzione 1 sulla scelta di inserire una stringa a piacere if ( order == 2 ) { // istruzioni se l'utente decide di utilizzare la seconda opzione di generare una stringa casualmente puts("Genero casualmente una stringa k"); char r; srand(time(NULL)); //inizializzazione del generatore di caratteri casuali for(int i = 0; i<=128; i++) { r = ((char) (rand()%96)+ 32); printf ("%127d", r);} int i; char plaintext[MAX]; char chiave[MAX]; char M; char k; M=strlen(plaintext); k=strlen(chiave); if (M==k) printf("Le stringhe hanno lo stesso numero di caratteri\n"); else if(M<k) printf("La prima stringa è minore rispetto alla seconda\n"); else printf ("La seconda stringa è più lunga della prima"); } } // conclusione main
Java
UTF-8
6,177
2.3125
2
[]
no_license
/*** * MainCounterFragment.java * Fragment that displays the cross counter. * Here you can choose what project you want to count up and down and * you can ... count the crosses in it up and down. * * It has one counter to count half crosses and one counter to count full crosses */ package com.example.skysk.stickeli; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SimpleAdapter; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; public class MainCounterFragment extends Fragment implements View.OnClickListener, CameraHelper.CameraListener { ProjectModel mProjectModel; View mView; TextView mHalfCrossesTextView; TextView mFullCrossesTextView; ImageView mBannerImage; ToolbarActivity mParentActivity; @Override public void onClick(View view) { switch(view.getId()) { case R.id.fab_camera: onClickFAB(); } } @Override public void onPictureSuccess() { mProjectModel .mProjects .get(mProjectModel .GetCurrentlySelected()) .SetThumbnailUri(CameraHelper.GetLastPictureURI()); mBannerImage.setImageURI(mProjectModel.GetCurrentlySelectedImageUri()); } public interface ToolbarActivity { public void SetToolbarTitle(String pTitle); }; /*** * Inner class defining the click listeners for the counters. * They are controlled by setting halfCrossFactor, which says how many half crosses * will be added/removed when clicking. */ private class CounterOnClickListener implements View.OnClickListener { MainCounterFragment mParent; int mHalfCrossFactor; CounterOnClickListener(MainCounterFragment pParent, int pHalfCrossFactor) { mParent = pParent; mHalfCrossFactor = pHalfCrossFactor; } @Override public void onClick(View pView) { if( mParent.mProjectModel.IncrementStitchCount( mParent.mProjectModel.GetCurrentlySelected(), mHalfCrossFactor )) { mParent.mHalfCrossesTextView.setText( String.format(Locale.getDefault(), "%d", mParent.mProjectModel.GetStitchCount( mParent.mProjectModel.GetCurrentlySelected()))); mParent.mFullCrossesTextView.setText( String.format(Locale.getDefault(), "%d", mParent.mProjectModel.GetStitchCount( mParent.mProjectModel.GetCurrentlySelected()) / 2)); } } } private void InitializeViews() { mHalfCrossesTextView.setText( String.format(Locale.getDefault(), "%d", mProjectModel.GetStitchCount( mProjectModel.GetCurrentlySelected()))); mFullCrossesTextView.setText( String.format(Locale.getDefault(), "%d", mProjectModel.GetStitchCount( mProjectModel.GetCurrentlySelected()) / 2)); mBannerImage.setImageURI(mProjectModel.GetCurrentlySelectedImageUri()); } /*** * RegisterButtonListeners * Registers all the button listeners in this fragment */ private void RegisterButtonListeners() { RegisterCounterButtonListener(R.id.counter_full_crosses, 2); RegisterCounterButtonListener(R.id.counter_half_crosses, 1); (mView.findViewById(R.id.fab_camera)).setOnClickListener(this); } /*** * RegisterCounterButtonListeners(final int counter_id) * * Registers the add and remove buttons for a given counter view. * * @param pCounterId */ private void RegisterCounterButtonListener( final int pCounterId, final int pHalfCrossFactor) { View counter = mView.findViewById(pCounterId); ImageButton add = counter.findViewById(R.id.counter_add); ImageButton remove = counter.findViewById(R.id.counter_remove); add.setOnClickListener(new CounterOnClickListener( this, pHalfCrossFactor)); remove.setOnClickListener(new CounterOnClickListener( this, - pHalfCrossFactor)); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mProjectModel = ProjectModel.getInstance(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mParentActivity = (ToolbarActivity) getActivity(); mParentActivity.SetToolbarTitle(mProjectModel.GetCurrentlySelectedName()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment mView = inflater.inflate(R.layout.fragment_main_counter, container, false); mFullCrossesTextView = mView.findViewById(R.id.counter_full_crosses) .findViewById(R.id.counter_count); mHalfCrossesTextView = mView.findViewById(R.id.counter_half_crosses) .findViewById(R.id.counter_count); mBannerImage = mView.findViewById(R.id.project_banner_image); RegisterButtonListeners(); InitializeViews(); return mView; } public void onClickFAB() { CameraHelper.TakePicture(getActivity()); } }
Python
UTF-8
11,380
3.75
4
[]
no_license
import pygame import time import random #Tutorial PART 42. pygame.init() # Initialise pygame white = (255,255,255) # (|RED|GREEN|BLUE|) black = (0, 0, 0) red = (255,0,0) green = (0,155,0) display_width = 800 display_height = 600 gameDisplay = pygame.display.set_mode([display_width,display_height]) # Sets up the game display and the window pygame.display.set_caption("Slither")# Sets the game title icon = pygame.image.load("apple.png") pygame.display.set_icon(icon) #a function which edits the icon at the top left. BEST TO USE A 32 by 32 image for icon. #pygame.display.update() Updates whats on the screen. DO THIS EVERY TIME YOU EDIT WINDOW img = pygame.image.load("snakehead.png") # pygame.image.load loads an image. IMAGE HAS TO BE IN THE SAME DIRECTORY AS THE CODE. arg 'image.png' appleimg = pygame.image.load("apple.png") AppleThickness = 30 block_size = 20 FPS = 30 clock = pygame.time.Clock() # sleep function in pygame. direction = "right" # initial direction of the snake. smallfont = pygame.font.SysFont("comicsansms", 25) #Takes a font object from the "SysFont" library. arg1: font arg2: font size. medfont = pygame.font.SysFont("comicsansms", 50) largefont = pygame.font.SysFont("comicsansms", 80) def game_intro(): #Intro screen intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_c: intro = False if event.key == pygame.K_q: pygame.quit() quit() gameDisplay.fill(white) message_to_screen("Welcome to Slither", green, -100, size="large") message_to_screen("The objective of the game is to eat red apples", black, -30) #These will be given a "small" font by default message_to_screen("The more apples you eat the longer you get", black, 10) message_to_screen("If you run into yourself or the edges, you die!", black, 50) message_to_screen("Press C to play or Q to quit.", black, 180) pygame.display.update() clock.tick(4) def pause(): paused = True message_to_screen("Paused", black, -100, size="large") message_to_screen("Press C to continue, P to pause or Q to quit", black, 25) pygame.display.update() while paused: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_c: paused = False elif event.key == pygame.K_q: pygame.quit() quit() #gameDisplay.fill(white) clock.tick(5) def score(score): text = smallfont.render("Score: "+str(score), True, black) gameDisplay.blit(text, [0,0]) def randAppleGen(): randAppleX = round(random.randrange(0, display_width - AppleThickness)) randAppleY = round(random.randrange(0, display_height - AppleThickness)) return randAppleX, randAppleY def snake(block_size, snakeList): if direction == "right": head = pygame.transform.rotate(img, 270) #the function rotates an image anti-clockwise arg1: image arg2: degrees if direction == "left": head = pygame.transform.rotate(img, 90) if direction == "up": head = img if direction == "down": head = pygame.transform.rotate(img, 180) gameDisplay.blit(head, (snakeList[-1][0], snakeList[-1][1])) for XnY in snakeList[:-1]: pygame.draw.rect(gameDisplay, green, [XnY[0],XnY[1],block_size,block_size]) ## (Location to draw, Colour, [Location along X (Starts from top left of screen), Loc along Y, Width, Height]) def text_object(text, colour, size): if size == "small": textSurface = smallfont.render(text, True, colour) elif size == "medium": textSurface = medfont.render(text, True, colour) elif size == "large": textSurface = largefont.render(text, True, colour) return textSurface, textSurface.get_rect() # .get_rect() is a function that turns the text into a rectangle, def message_to_screen(msg,colour, y_displace=0, size="small"): textSurf, textRect = text_object(msg,colour,size) #screen_text = font.render(msg, True, colour) #creates the text and assigns it to the variable. arg1: text arg2: True arg3:colour #gameDisplay.blit(screen_text, [display_width/2,display_height/2]) #prints text on gameDisplay arg1: text arg2: location in form of a list (width,height). textRect.center = (display_width / 2), (display_height / 2) + y_displace # .center is the center point of the rectangle. that can be assigned a new value by giving an x and y value it tuple form. gameDisplay.blit(textSurf, textRect) def gameLoop(): global direction direction = "right" # Did this to reset the direction to right. gameExit = False gameOver = False lead_x = display_width/2 lead_y = display_height/2 lead_x_change = 10 lead_y_change = 0 randAppleX, randAppleY = randAppleGen() snakeList = [] snakeLength = 1 while not gameExit: if gameOver == True: message_to_screen(("Game over"), red, -50, size="large") message_to_screen("Press C to play again or Q to quit", black, 50) pygame.display.update() while gameOver == True: for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True gameOver = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: gameExit = True gameOver = False if event.key == pygame.K_c: gameLoop() for event in pygame.event.get(): # All the events in pygame #print(event) #Its like the serial monitor in Arduino if event.type == pygame.QUIT: # Search in Google "pygame.event" for all the events such as KEYDOWN gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: direction = "left" lead_x_change = -block_size lead_y_change = 0 elif event.key == pygame.K_RIGHT: direction = "right" lead_x_change = block_size lead_y_change = 0 elif event.key == pygame.K_UP: direction = "up" lead_y_change = -block_size lead_x_change = 0 elif event.key == pygame.K_DOWN: direction = "down" lead_y_change = block_size lead_x_change = 0 elif event.key == pygame.K_p: pause() '''if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: #Moves whilst holding key. lead_x_change = 0''' if lead_x >= display_width or lead_x <= 0 or lead_y >= display_height or lead_y <= 0: #exits the game when you move out of the screen. gameOver = True #print(snakeLength - 1) lead_x += lead_x_change #continuously increments by 10. lead_y += lead_y_change gameDisplay.fill(white) #pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, AppleThickness, AppleThickness]) gameDisplay.blit(appleimg, (randAppleX, randAppleY)) snakeHead = [] snakeHead.append(lead_x) #forming a head block into a list. snakeHead.append(lead_y) snakeList.append(snakeHead) #appending snakeHead to snakeList to form the body of the snake aswell as the head in form of a 2D array. if len(snakeList) > snakeLength: del snakeList[0] # this prevents the snake from growing constantly for eachSegment in snakeList[:-1]: if eachSegment == snakeHead: gameOver = True #print(snakeLength - 1) snake(block_size, snakeList) score(snakeLength-1) pygame.display.update() #gameDisplay.fill(red, rect = [200, 200, 50, 50]) # Another way of Drawing than the method above. ## if lead_x == randAppleX and lead_y == randAppleY: #EAT APPLE ## randAppleX = round(random.randrange(0, display_width - block_size)/10.0)*10.0 ## randAppleY = round(random.randrange(0, display_height - block_size)/10.0)*10.0 ## while lead_x == randAppleX and lead_y == randAppleY:# Makes Sure apple spawns in different area and not the same place it was eaten in. ## randAppleX = round(random.randrange(0, display_width - block_size)/10.0)*10.0 ## randAppleY = round(random.randrange(0, display_height - block_size)/10.0)*10.0 ## snakeLength += 1 ## if lead_x >= randAppleX and lead_x <= randAppleX + AppleThickness: ## if lead_y >= randAppleY and lead_y <= randAppleY + AppleThickness: ## randAppleX = round(random.randrange(0, display_width - block_size))#/10.0)*10.0 ## randAppleY = round(random.randrange(0, display_height - block_size))#/10.0)*10.0 ## while lead_x == randAppleX and lead_y == randAppleY: ## randAppleX = round(random.randrange(0, display_width - block_size))#/10.0)*10.0 ## randAppleY = round(random.randrange(0, display_height - block_size))#/10.0)*10.0 ## snakeLength += 1 if lead_x > randAppleX and lead_x < randAppleX + AppleThickness or lead_x + block_size > randAppleX and lead_x + block_size < randAppleX + AppleThickness: if lead_y > randAppleY and lead_y < randAppleY + AppleThickness: #randAppleX = round(random.randrange(0, display_width - AppleThickness))#/10.0)*10.0 #randAppleY = round(random.randrange(0, display_height - AppleThickness))#/10.0)*10.0 randAppleX, randAppleY = randAppleGen() #This is the same thing as the commented code directly above but called from a function to make the code more easy to maintain. while lead_x == randAppleX and lead_y == randAppleY: randAppleX, randAppleY = randAppleGen() snakeLength += 1 elif lead_y + block_size > randAppleY and lead_y + block_size < randAppleY + AppleThickness: randAppleX, randAppleY = randAppleGen() while lead_x == randAppleX and lead_y == randAppleY: randAppleX, randAppleY = randAppleGen() snakeLength += 1 clock.tick(FPS) # sleep function with FPS taken as the arg. pygame.quit() quit game_intro() gameLoop()
SQL
UTF-8
4,802
3.359375
3
[]
no_license
COL con_id FOR 999 HEA 'Con|ID'; COL pdb_name FOR A30 HEA 'PDB Name' FOR A30 TRUNC; COL avg_et_ms FOR 99,999,990.000 HEA 'Avg Elapsed|Time (ms)'; COL avg_cpu_ms FOR 99,999,990.000 HEA 'Avg CPU|Time (ms)'; COL avg_io_ms FOR 99,999,990.000 HEA 'Avg User IO|Time (ms)'; COL avg_appl_ms FOR 99,999,990.000 HEA 'Avg Appl|Time (ms)'; COL avg_conc_ms FOR 99,999,990.000 HEA 'Avg Conc|Time (ms)'; COL avg_bg FOR 999,999,999,990 HEA 'Avg|Buffer Gets'; COL avg_disk FOR 999,999,999,990 HEA 'Avg|Disk Reads'; COL avg_read_bytes FOR 999,999,999,990 HEA 'Avg Physical|Read Bytes'; COL avg_write_bytes FOR 999,999,999,990 HEA 'Avg Physical|Write Bytes'; COL avg_row FOR 999,999,990.000 HEA 'Avg Rows|Processed'; COL executions FOR 999,999,999,990 HEA 'Executions'; COL fetches FOR 999,999,999,990 HEA 'Fetches'; COL tot_et_secs FOR 999,999,990 HEA 'Total ET|(secs)'; COL tot_cpu_secs FOR 999,999,990 HEA 'Total CPU|(secs)'; COL tot_io_secs FOR 999,999,990 HEA 'Total IO|(secs)'; COL tot_appl_secs FOR 999,999,990 HEA 'Total Appl|(secs)'; COL tot_conc_secs FOR 999,999,990 HEA 'Total Conc|(secs)'; COL tot_buffer_gets FOR 999,999,999,990 HEA 'Total|Buffer Gets'; COL tot_disk_reads FOR 999,999,999,990 HEA 'Total|Disk Reads'; COL total_read_bytes FOR 999,999,999,999,990 HEA 'Physical Read Bytes|Total'; COL total_write_bytes FOR 999,999,999,999,990 HEA 'Physical Write Bytes|Total'; COL tot_rows_processed FOR 999,999,999,990 HEA 'Total Rows|Processed'; -- PRO PRO SQL STATS (v$sqlstats since instance startup on &&cs_startup_time., &&cs_startup_days. days ago, or since SQL was first loaded into cursor cache) PRO ~~~~~~~~~ SELECT s.con_id, c.name AS pdb_name, '|' AS "|", s.executions, s.fetches, '|' AS "|", s.elapsed_time/NULLIF(s.executions, 0)/1e3 AS avg_et_ms, s.cpu_time/NULLIF(s.executions, 0)/1e3 AS avg_cpu_ms, s.user_io_wait_time/NULLIF(s.executions, 0)/1e3 AS avg_io_ms, s.application_wait_time/NULLIF(s.executions, 0)/1e3 AS avg_appl_ms, s.concurrency_wait_time/NULLIF(s.executions, 0)/1e3 AS avg_conc_ms, s.buffer_gets/NULLIF(s.executions, 0) AS avg_bg, s.disk_reads/NULLIF(s.executions, 0) AS avg_disk, s.physical_read_bytes/NULLIF(s.executions, 0) AS avg_read_bytes, s.physical_write_bytes/NULLIF(s.executions, 0) AS avg_write_bytes, s.rows_processed/NULLIF(s.executions, 0) AS avg_row, '|' AS "|", s.elapsed_time/1e6 AS tot_et_secs, s.cpu_time/1e6 AS tot_cpu_secs, s.user_io_wait_time/1e6 AS tot_io_secs, s.application_wait_time/1e6 AS tot_appl_secs, s.concurrency_wait_time/1e6 AS tot_conc_secs, s.buffer_gets AS tot_buffer_gets, s.disk_reads AS tot_disk_reads, s.physical_read_bytes AS total_read_bytes, s.physical_write_bytes AS total_write_bytes, s.rows_processed AS tot_rows_processed FROM v$sqlstats s, v$containers c WHERE s.sql_id = '&&cs_sql_id.' AND c.con_id = s.con_id ORDER BY s.con_id / -- PRO PRO SQL STATS (v$sqlstats since last AWR snapshot on &&cs_max_snap_end_time., &&cs_last_snap_mins. mins ago) PRO ~~~~~~~~~ SELECT s.con_id, c.name AS pdb_name, '|' AS "|", s.delta_execution_count AS executions, s.delta_fetch_count AS fetches, '|' AS "|", s.delta_elapsed_time/NULLIF(s.delta_execution_count, 0)/1e3 AS avg_et_ms, s.delta_cpu_time/NULLIF(s.delta_execution_count, 0)/1e3 AS avg_cpu_ms, s.delta_user_io_wait_time/NULLIF(s.delta_execution_count, 0)/1e3 AS avg_io_ms, s.delta_application_wait_time/NULLIF(s.delta_execution_count, 0)/1e3 AS avg_appl_ms, s.delta_concurrency_time/NULLIF(s.delta_execution_count, 0)/1e3 AS avg_conc_ms, s.delta_buffer_gets/NULLIF(s.delta_execution_count, 0) AS avg_bg, s.delta_disk_reads/NULLIF(s.delta_execution_count, 0) AS avg_disk, s.delta_physical_read_bytes/NULLIF(s.delta_execution_count, 0) AS avg_read_bytes, s.delta_physical_write_bytes/NULLIF(s.delta_execution_count, 0) AS avg_write_bytes, s.delta_rows_processed/NULLIF(s.delta_execution_count, 0) AS avg_row, '|' AS "|", s.delta_elapsed_time/1e6 AS tot_et_secs, s.delta_cpu_time/1e6 AS tot_cpu_secs, s.delta_user_io_wait_time/1e6 AS tot_io_secs, s.delta_application_wait_time/1e6 AS tot_appl_secs, s.delta_concurrency_time/1e6 AS tot_conc_secs, s.delta_buffer_gets AS tot_buffer_gets, s.delta_disk_reads AS tot_disk_reads, s.delta_physical_read_bytes AS total_read_bytes, s.delta_physical_write_bytes AS total_write_bytes, s.delta_rows_processed AS tot_rows_processed FROM v$sqlstats s, v$containers c WHERE s.sql_id = '&&cs_sql_id.' AND c.con_id = s.con_id ORDER BY s.con_id / --
TypeScript
UTF-8
330
3.125
3
[ "MIT" ]
permissive
module behaviourTree { /** * 包装一个ExecuteAction,这样它就可以作为一个ConditionalAction使用 */ export class ExecuteActionConditional<T> extends ExecuteAction<T> implements IConditional<T>{ public constructor(action: (t: T) => TaskStatus) { super(action); } } }
Markdown
UTF-8
3,330
2.765625
3
[]
no_license
--- layout: page title: Coding Projects permalink: /projects/ --- <head> <!-- <link rel="stylesheet" type="text/css" href="page.css"> --> <style> .entry{ /* --background-color: #F5F5F5; */ display: grid; border-style: solid; border-color: #F5F5F5; grid-auto-rows: auto; padding: 5%; position: relative; box-sizing: border-box; border-radius: 5px; } img{ object-fit: cover; width: 12em; height: 7em; padding:0em 0em 0em 0em; } .image{ max-width: 100%; object-fit: cover; width: 12em; height: 7em; padding:0em 0em 0em 0em; } .grid{ display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 2fr)); grid-template-rows: auto auto auto; grid-column-gap: 0.5em; grid-row-gap: 1em; } .no-picture { margin-top: 0.5em; } #section{ font-size: 0.7em; } #headline{ font-size: 0.9em; } #date{ font-size: 0.6em; } </style> </head> <h2>CS projects</h2> <p>Here are some of the projects I've been working on!</p> <section class="grid"> <entry-component> <a slot="link" href="https://kaylinli.github.io/SentenceMosaicsWebsite/"></a> <img slot="imagesrc" src="/img/sentencemosaicswebsite.png"> <span slot="headline">Sentence Mosaics website</span><br /> <span slot="description">Developed website</span> <span slot="date" id="date">Sept 2020 - present</span></slot> </entry-component> <!-- <entry-component> <a slot="link" href="https://kaylinli.github.io/SentenceMosaicsWebsite/"> <img src="/img/sentencemosaicswebsite.png"> </a> <a slot="link" href="https://kaylinli.github.io/SentenceMosaicsWebsite/"> <span id="headline">Sentence Mosaics website</span><br /> </a> <span slot="description">Developed website</span> <span slot="date" id="date">Sept 2020 - present</span></slot> </entry-component> --> <div class="entry"> <div class="image"> <a href="https://kaylinli.github.io/SentenceMosaicsWebsite/"> <img src="/img/sentencemosaicswebsite.png"> </a> </div> <div class="text"> <a href="https://kaylinli.github.io/SentenceMosaicsWebsite/"> <span id="headline">Sentence Mosaics website</span><br /> <span>Developed</span><br /> </a> <span id="date">Sept 2020 - present</span><br /> </div> </div> <div class="entry"> <div class="image"> <a href="https://github.com/shruthikmusukula/homeroom"> <img src="/img/homeroomtask.png"> </a> </div> <div class="text"> <a href="https://github.com/shruthikmusukula/homeroom"> <span id="headline">HomeRoom Developer</span><br /> <span>Developed productivity app at HackIllinois</span><br /> </a> <span id="date">Aug 2020</span><br /> </div> </div> <div class="entry"> <div class="image"> <a href="https://github.com/shruthikmusukula/DiDAP"> <img src="https://raw.githubusercontent.com/shruthikmusukula/DiDAP/master/fig1.PNG"> </a> </div> <div class="text"> <span id="section">MONTEREY, CA</span><br /> <a href="https://github.com/shruthikmusukula/DiDAP"> <span id="headline">Intern in Science Engineering Apprenticeship Program</span><br /> <span id="section">Developed sonar data analysis platform at Naval Postgraduate School</span><br /> </a> <span id="date">June-Aug 2019, 2020</span><br /> </div> </div> </section>
Java
UTF-8
461
2.15625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package calcula2; import javax.swing.JOptionPane; /** * * @author rpachotome */ public class Vista { public static void imprimir(Modelo mod){ JOptionPane.showMessageDialog(null, mod.getNum1()+mod.getOperacion()+mod.getNum2()+"="+mod.getResultado()); } }
SQL
UTF-8
418
3.109375
3
[]
no_license
CREATE TABLE Movie( movie_id SERIAL, movie_name varchar(100), movie_year date, ratings int ); CREATE TABLE Actor( actor_id SERIAL, actor_first_name varchar(100), actor_last_name varchar(100), actor_age INT ); CREATE TABLE Actress( actress_id SERIAL, actress_first_name varchar(100), actress_last_name varchar(100), actress_age INT ); CREATE TABLE movie_actor_actress( movie_id INT, actor_id INT, actress_id INT );
PHP
UTF-8
610
2.78125
3
[]
no_license
<?php class View { public $route; private $val_arr; public function __construct($route){ $this->route = $route; } public function renderView(){ foreach($this->val_arr as $key => $val){ if (!is_object($val) && !is_array($val)){ $$key = $val; } } include_once(APP_DIR.'view/layout/default.php'); } public function loadContent(){ $view_file = $this->route->getActionName().'.php'; include_once(APP_DIR.'view/'.$this->route->getControllerName().'/'.$view_file); } public function setVals(array $val_arr){ $this->val_arr = $val_arr; } } ?>
Markdown
UTF-8
3,432
2.953125
3
[]
no_license
--- layout: default title: '从接种新冠疫苗谈群体免疫' date: 2021-04-03T00:00:00.000000+08:00 author: display_name: 冰室山人 --- 从接种新冠疫苗谈群体免疫 作者:冰室山人 近期,中国开始大规模开展新冠疫苗接种工作,现在乡镇医疗卫生机构都能接种新冠疫苗了。据国务院联防联控机制发布的消息,截至3月27日,我国接种剂次已超一亿。只要产能跟得上,以中国体制的动员能力,大部分民众很快就能接种上疫苗。毕竟,中国体制能让整个社会停摆很长一段时间,这种动员能力,是其他国家无法做到的。 现在媒体、政府公众号都大力号召民众去接种新冠疫苗,目的很多说是共筑免疫屏障。对个体来说是建立免疫屏障,但对整个社会而言就是建成群体免疫。免疫屏障和群体免疫都是免疫学的概念。免疫屏障是指个体能够阻挡病原体入侵。而群体免疫是指当一个群体中达到一定规模的人对某一传染病有免疫力后,这种传染病就无法有效传播。 现在有些人可能有意无意地避免使用群体免疫这个词,因为群体免疫被污名化了。新冠病毒爆发之时,英国采取了宽松的防疫策略,英国的解释是当一定的民众有免疫力后,就能达成群体免疫,以阻断新冠病毒的传播。英国的防疫策略受到了很多人的批评,群体免疫也就跟着被妖魔化了。诚然,防疫策略有宽有严。防疫最严的除了朝鲜就是我们国家了,中国体制有强大的社会动员能力,有效地阻断了新冠病毒的传播。其他国家有宽有严的,并都不具备中国的这种能力,阻断不了新冠病毒的传播。若要批评英国,就应该批评所采取宽松的防疫策略。群体免疫不是策略,而是目标。 直到现在,媒体仍然在污名化群体免疫,报道说英国首相后悔群体免疫的决定。现在,世界各国都把达成群体免疫作为一个目标,怎么能说是后悔群体免疫的决定呢?要达成群体免疫有两种途径,一种是一定规模的人群接种疫苗,另一种是一定人群的人自然感染后痊愈获得免疫力。要说后悔也应该说后悔使用第二种策略,而不是说后悔群体免疫的决定。 英国宣布采取宽松防疫策略以达成群体免疫后,国内还有一位大牛撰文抨击,是北大教授饶毅。饶毅教授称英国不可能形成群体免疫,因为还没有疫苗,却不明白形成群体免疫不只只有接种疫苗这一途径。 相比一些人避免使用群体免疫这个词,我国炙手可热的防疫大佬现在却说得比较坦率。近日,中国疾控中心主任高福院士在接受央视采访时称,希望国内在2022年初实现群体免疫,在全世界带头做到群体免疫。网红医生张文宏也说,70%的国人接种才有可能达成群体免疫。 群体免疫是免疫学的一个概念,要把这个概念讲清楚是很简单的一件事。我一个大外行,通过阅读方舟子的科普文章,经思考、分析后都弄明白了,一些媒体人却不愿意做一点基础工作,就大义凛然地抨击群体免疫,甚至连北大教授饶毅也没能讲明白群体免疫,不能不说是一个遗憾。一个简单的群体免疫就如此,又何况其他呢? (XYS20210403)
Java
GB18030
971
2.671875
3
[]
no_license
package com.ws.service.impl; import java.util.ArrayList; import java.util.List; import com.ws.domain.Customer; import com.ws.service.CustomerService; public class CustomerServiceImpl implements CustomerService { public void save(Customer customer) { System.out.println("ͻˡ"); } public void delete(Long id) { System.out.println("ͻɾˡ"); } public void update(Customer customer) { System.out.println("ͻ޸ˡ"); } public List<Customer> findAll() { System.out.println("ѯпͻ"); List<Customer> list = new ArrayList<Customer>(); list.add(new Customer(1L, "С", "135111111111")); list.add(new Customer(2L, "С", "135222222222")); list.add(new Customer(3L, "С", "135333333333")); return list; } public Customer findById(Long id) { System.out.println("ѯһͻ"); return new Customer(1L, "С", "13544444444444"); } }
JavaScript
UTF-8
6,225
3.234375
3
[]
no_license
'use strict'; // BANKIST APP // Data const account1 = { owner: 'Jonas Schmedtmann', movements: [200, 450, -400, 3000, -650, -130, 70, 1300], interestRate: 1.2, // % pin: 1111, }; const account2 = { owner: 'Jessica Davis', movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30], interestRate: 1.5, pin: 2222, }; const account3 = { owner: 'Steven Thomas Williams', movements: [200, -200, 340, -300, -20, 50, 400, -460], interestRate: 0.7, pin: 3333, }; const account4 = { owner: 'Sarah Smith', movements: [430, 1000, 700, 50, 90], interestRate: 1, pin: 4444, }; const accounts = [account1, account2, account3, account4]; // Elements const labelWelcome = document.querySelector('.welcome'); const labelDate = document.querySelector('.date'); const labelBalance = document.querySelector('.balance__value'); const labelSumIn = document.querySelector('.summary__value--in'); const labelSumOut = document.querySelector('.summary__value--out'); const labelSumInterest = document.querySelector('.summary__value--interest'); const labelTimer = document.querySelector('.timer'); const containerApp = document.querySelector('.app'); const containerMovements = document.querySelector('.movements'); const btnLogin = document.querySelector('.login__btn'); const btnTransfer = document.querySelector('.form__btn--transfer'); const btnLoan = document.querySelector('.form__btn--loan'); const btnClose = document.querySelector('.form__btn--close'); const btnSort = document.querySelector('.btn--sort'); const inputLoginUsername = document.querySelector('.login__input--user'); const inputLoginPin = document.querySelector('.login__input--pin'); const inputTransferTo = document.querySelector('.form__input--to'); const inputTransferAmount = document.querySelector('.form__input--amount'); const inputLoanAmount = document.querySelector('.form__input--loan-amount'); const inputCloseUsername = document.querySelector('.form__input--user'); const inputClosePin = document.querySelector('.form__input--pin'); //function of adding movements to user interface const addMovements = function(movements, sort = false){ //first clean the container containerMovements.innerHTML = ''; const movs = sort ? movements.slice().sort((a, b) => a - b) : movements; movs.forEach(function(mov, i){ const type = mov > 0 ? 'deposit':'withdrawal'; const html = ` <div class="movements__row"> <div class="movements__type movements__type--${type}">${i+1} ${type}</div> <div class="movements__value">${Math.abs(mov)}€</div> </div>` //which div want to add? containerMovements.insertAdjacentHTML('afterbegin', html); }); }; // insertAdjacentHTML is an order to overwrite html sentence //computing inputUsername //map() //for each account do as below const createUser = function(accs){ accs.forEach(function(acc){ acc.userName = acc.owner .toLowerCase() .split(' ') .map(function(name){ return name[0]; }) .join('') .toUpperCase(); console.log(acc.userName); }) } createUser(accounts); //function called and automaticly added username into object /*console.log(accounts); //check if error*/ const calPrintBalance = function(acc){ acc.balance = acc.movements.reduce((acc, cur) => acc + cur, 0); labelBalance.innerHTML = `${acc.balance}€`; } //calculateBalance const calculateBalance = function(acc){ const depositBal = acc.movements.filter(mov => mov > 0).reduce((acc, dep) => acc + dep, 0); labelSumIn.innerHTML = `${depositBal}€`; const withdrawBal = acc.movements.filter(mov => mov < 0).reduce((accu, wit) => accu + wit, 0); labelSumOut.innerHTML = `${Math.abs(withdrawBal)}€`; const interestBal = acc.movements.filter(mov => mov > 0).map(amt => amt * acc.interestRate/100).filter(amt => amt > 1).reduce((accu, amt) => accu + amt, 0); labelSumInterest.innerHTML = `${interestBal}€`; } let currentUser; const updateUI = function(acc){ addMovements(acc.movements); calculateBalance(acc); calPrintBalance(acc); } btnLogin.addEventListener('click', function(event){ event.preventDefault(); currentUser = accounts.find(acc => acc.userName === inputLoginUsername.value.toUpperCase()); if (currentUser?.pin === Number(inputLoginPin.value)){ labelWelcome.innerHTML = `Welcome back, ${currentUser.owner.split(' ')[0]}!`; inputLoginPin.blur(); containerApp.style.opacity = 100; inputLoginUsername.value = inputLoginPin.value = ''; updateUI(currentUser); } }) //transfer function btnTransfer.addEventListener('click', function(e){ event.preventDefault(); const transferTo = accounts.find(acc => acc.userName === inputTransferTo.value.toUpperCase()); const transferAmount = Number(inputTransferAmount.value); inputTransferTo.value = inputTransferAmount.value = ''; if (transferAmount > 0 && transferTo && currentUser.balance >= transferAmount && transferTo?.userName !== currentUser.userName){ currentUser.movements.push(-transferAmount); transferTo.movements.push(transferAmount); updateUI(currentUser); } }) btnClose.addEventListener('click', function(e){ e.preventDefault(); if (inputCloseUsername.value.toUpperCase() === currentUser.userName && Number(inputClosePin.value) === currentUser.pin){ const index = accounts.findIndex(acc => acc.userName === currentUser.userName); accounts.splice(index, 1); containerApp.style.opacity = 0; } inputCloseUsername.value = inputClosePin.value = ''; }) btnLoan.addEventListener('click',function(e){ e.preventDefault(); const amount = Number(inputLoanAmount.value); if (amount > 0 && currentUser.movements.some(mov => mov >= amount*0.1)){ currentUser.movements.push(amount); updateUI(currentUser); } inputLoanAmount.value = ''; }) let sorted = false; btnSort.addEventListener('click', function(e){ e.preventDefault(); addMovements(currentUser.movements, !sorted); sorted = !sorted; }) //get data from website labelBalance.addEventListener('click', function(){ const movementsUI = Array.from(document.querySelectorAll('.movements__value'), el => Number(el.textContent.replace('€',''))); //Array.from have their own bulit in map function (second position) console.log(movementsUI); })
Markdown
UTF-8
6,344
3.234375
3
[]
no_license
### [MongoDB ](../MongoDB.md) > [Administration and Maintenance](Administration and Maintenance.md) > Scalability ___ As your data grows, your sever won't be able to handle the high rate of queries and the larger sets will exceed the server storage capacity. To address these issues, you will have to do either a vertical or horizontal scaling. You can scale your server vertically by adding more CPUs and storage resources but there is always a limit to what you can add to a single server machine. In the other hand, you can scale horizontally by distributing your data over multiple servers which is also called Sharding. Each shard will act as a separate database and all the shards make up the complete logical database. By using sharding, you can meet the demands of the high throughput read/write operations as well as the very large data sets. Fortunately, MongoDB supports sharding by using a sharded cluster which is composed of three components: the query routers, the configuration servers and the shards. In the following sections, I will explain these components in more details. Sharding in MongoDB is done only on the collection level. You can also either shard one collection, multiple collections or the whole data as you choose. ![image](https://docs.mongodb.org/manual/_images/sharded-cluster.png) ##### Query Routers These are mongos instances which are used by the client applications to interact with the sharded data. Client applications can't access the shards directly and can only submit read and write requests to mongos instance. Mongos instance is the one responsible for routing these reads and writes requests to the respective shards. Mongos has no persistent state and knows only what data is in which shard by tracking the metadata information stored in the configuration servers. Mongos performs operations in sharded data by broadcasting to all the shards that holds the documents of a collection or target only shard based on the shard key. Usually, multi-update and remove operations are a broadcast operations. In general, most sharded clusters contain multiple mongos instances to divide the client requests load, but you also use only a single instance. ##### Config Servers The config servers holds the metadata of the sharded cluster such as the shards locations of each sharded data. Config servers contain very important information for the sharded cluster to work and if the servers are down for any reason, the sharded cluster becomes inoperable. For this reason, it is a good idea to replicate the data in the config server using a replica set configuration which allows the sharded cluster to have more than 3 config servers and up to 50 servers to ensure availability. MongoDB stores the sharded cluster metadata information in the config servers and update this information whenever there is a chunk split or chunk migration. A chunk split happens when chunk's data grows beyond the chunk size which will make the mongos instance split this chunk into halves. This can lead to an unevenly data distribution among shards which starts the balancing process that leads to chunk migration. A chunk migration is the process of moving one chunk from a particular shard to another to achieve even data distribution among shards. ![image](https://docs.mongodb.org/manual/_images/sharding-splitting.png) ![image](https://docs.mongodb.org/manual/_images/sharding-migrating.png) ##### Shards The shards are a replica set or a single server to hold part of the sharded data. Usually, each shard is a replica set which provides high availability and data redundancy that can be used in case of disaster recovery. In any sharded cluster, there is a primary set that contains the unsharded collections. ![image](https://docs.mongodb.org/manual/_images/sharded-cluster-primary-shard.png) To find out which shard is a primary in a sharded cluster, you can run the mongo shell command sh.status(). ##### Data Distribution in a Sharded Cluster First to shard the data, a shard key needs to be selected. The sharded key should be either a single indexed field or a compound index. Mongodb then divid the sharded key values evenly over the shards as chunks. To ensure that the data in the different shards are distributed evenly. MongoDB use a splitting and a balancing background processes. The splitting process splits the chunks data whenever the data grows beyond a pre-defined chunk size. And the balancing process moves the chunks between different shards whenever the data in unevenly distributed. The splitting and balancing processes usually triggered when a new data is added or removed, and when a new shard is added or removed. For a step by step tutorial on how to deploy a sharded cluster, please have a look at [MongoDB documentation.](https://docs.mongodb.org/manual/tutorial/deploy-shard-cluster/) ##### Data Partitioning As explained previously, MongoDB partition the data based on the sharded key. To partition the data using the sharded key, MongoDB either use range based partitioning or hash based partitioning as explained below: ###### Range Based Sharding MongoDB divides the data into ranges based on the sharded key values. For instance, if we have a numeric sharded key values, we will divid the data based on the possible range of this numeric value. Then MongoDB partitions the data based on the value of the sharded key and distribute it to the shard responsible for that value range as shown below: ![image](https://docs.mongodb.org/manual/_images/sharding-range-based.png) Range based sharding is better for range queries because MongoDB will check which shards are within the requested range. However, range based sharding can result in an uneven distribution which is not good for scalability. ###### Hash Based Sharding MongoDB supports also Hash Based Sharding which compute a hash value for the sharded key and then use this hash value to select the shard. This ensures better data distribution where data is evenly distributed across the cluster. However it is not efficient when it comes to range queries since the data is randomly distributed across the sharded cluster based on the hash function. An example is shown below: ![image](https://docs.mongodb.org/manual/_images/sharding-hash-based.png)
Java
UTF-8
1,150
2.109375
2
[ "MIT" ]
permissive
package org.master.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.*; /** * Created by kaenry on 2016/9/20. * RestExceptionHandler */ @ControllerAdvice(annotations = RestController.class) public class RestExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(RestExceptionHandler.class); @ExceptionHandler @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) private <T> RestResult<T> runtimeExceptionHandler(Exception e) { LOGGER.error("---------> huge error!", e); return RestResultGenerator.genErrorResult(ErrorCode.SERVER_ERROR); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) private <T> RestResult<T> illegalParamsExceptionHandler(MethodArgumentNotValidException e) { LOGGER.error("---------> invalid request!", e); return RestResultGenerator.genErrorResult(ErrorCode.ILLEGAL_PARAMS); } }
Markdown
UTF-8
9,443
2.90625
3
[ "MIT" ]
permissive
### 1. Overview ROBOTIS-OP3 Action Editor Node This chapter explains how to create and edit action file used in the [op3_action_module] of ROBOTIS-OP3. #### 1.1 Action File The action file contains ROBOTIS-OP3’s poses and time data. The current position describes positions of Dynamixels which converted from actual Dynamixel resolution to 4095 resolution. The action file is written as binary file so users can read its contents with op3_action_editor. ROBOTIS currently provides a default action file with source code. It is located in "op3_action_module/data" directory. The action file contains 256 pages. Each page can store up to 7 stages (or steps) of action data. The default action file does not use all pages and user can add own actions by writing them on the empty page. ### 2. Getting started #### 2.1 Download & Build > Reference : [Installing ROBOTIS ROS Package] #### 2.2 Run Execute the launch file. `op3_action_editor` has a direct control over ROBOTIS-OP3, therefore other control programs such as `op3_manager`, `op3_offset_tuner` and `op3_walking_tuner` should not be running. Before executing the `op3_action_editor` launch file, other programs should be terminated. ``` $ roslaunch op3_action_editor op3_action_editor.launch ``` #### 2.3 UI ![](/assets/images/platform/op3/thormang3_action_editor_tui.jpg) **Page number**: Page number is the listed page number. If user wants to create a new action poses, user can use any empty page. **Page title**: ROBOTIS recommends user to use a page title when creating a new action on an empty page. **Current position**: The current position describes position of Dynamixel which converted from actual Dynamixel resolution to 4095 resolution. This data is represented by STP7 in op3_action_editor. Sometimes the position may be read as ---- in op3_action_editor. This means position of the Dynamixel has not been read (or torque is off). If user turns the Dynamixel off, current position cannot be read until turn it back on. User can turn off the torque of specific Dynamixels. This is very convenient when acquiring position values directly from Dynamixels for a new robot posture instead of calculating those values. To do that, turn off the torque of desired Dynamixels, then make a posture and hold the robot joint by hand until turn the torque back on. The robot will be remaining at current posture and user can read position values of corresponding Dynamixels. **Steps or stages**: Each page can store up to 7 steps, from STP0 to STP6. However, some actions may be required more than 7 stages to perform completely. This can be resolved by simply using multiple pages and link them with “Next”. **Next**: “Next” indicates whether to continue action on a different page. To continue actions, just list the page number where the action is to be continued. Number 0 indicates that action does not continue onto another page (default value). Linking page does not have to have the numerical order. **Play Count**: “Play Count” is the number of times the action of the page is to be played. **Exit**: There might be some cases when an action has to be stopped. In these cases, the robot may be in unstable position. “Exit” is much like "Next", so "Exit" should be linked to a page where ROBOTIS-OP3 can return to a stable pose. If "Exit" is 0, it means that there is no linked exit page (default value). Tip: When calling an action requires multiple pages, ROBOTIS strongly suggests user to call the action from the starting page. For example, “clap” starts at page 7 and ends at page 8. This means you should call page 7 when calling “clap.” Calling the page 8 may cause unexpected behavior of the robot. **STP7**: "STP7" column is the current position of the Dynamixel which converted to 4095 resolution from its original resolution. "----" means that torque has been released. **PauseTime**: "PauseTime" is the pause duration period for motion playback for step STP[x]. **Time(x 8msec)** : "Time" is the time period for ROBOTIS-OP3 to complete step STP[x]. Each time unit account for 8ms of time. It is strongly advised that when user tests user’s own newly-created or edited actions, there should be small incremental changes in position, speed/time, and pause values for the sake of ROBOTIS-OP3's stability. #### 2.4 The Contents of The Default Action File The below table shows the contents of the default action file. | page number | page title | brief description of page | number of pages | |-------------|------------|-------------------------------------------------------|-----------------| | 1 | walki_init | initial standing pose | 1 | | 2 | hello | greeting | 1 | | 3 | thank_you | Thank you | 1 | | 4 | yes | yes | 1 | | 5 | no | no | 1 | | 6 | fighting | fighting | 1 | | 7 | clap | clap | 2 | | 9 | S_H_RE | ready for shaking hands | 1 | | 10 | S_H | shaking hands | 1 | | 11 | S_H_END | move to initialpose fram ready pose for shaking hands | 1 | | 12 | scanning | looking around | 1 | | 13 | ceremony | ceremony | 1 | #### 2.5 Basic Command of Action Editor After typing "help", the commend list will appear as shown below. ![](/assets/images/platform/op3/thormang3_action_editor_tui_command_list.jpg) **exit**: exits the program. **re**: refreshes the screen. **b**: moves to the previous page. **n**: moves to the next page. **page [index]**: moves to the [index] page. For example typing page 5 outputs data from page 5 on screen. **list**: outputs a list of pages. **new**: initializes current page by clearing all actuator position data. **copy [index]**: copies data from page [index] to current page. For example if you are on page 5 and want to copy page 9 then type copy 9. **set [value]**: sets position value on chosen actuator. For example If you want ID19 (head pan) to have a value of 512 then using the keyboard's directional keys place the cursor on ID19 and type set 512. **save**: saves any changes you've made. the saved motion file (motion_4096.bin can be found at "op3_action_module/data") **play**: plays motion(s) of current page. **name**: changes the name of the current page. You can view the name of the page at the top right portion of the screen. For example, page 2 is titled hello; to change the name type name and press the "ENTER" key. "name:" will appear at the bottom of the screen. Input the desired name for the page, good for instance, and press the "ENTER" key again. **i**: inserts data from STP7 to STP0. Moves data from STP[x] to STP[x + 1] if any. **i [index]**: inserts data from STP7 to STP[index]. Moves data from STP[index] to STP[index + 1] if any. **m [index] [index2]**: moves data from [index2] to [index]. **d [index]**: deletes data from STP[index]. Moves data from STP[index] to STP[index - 1]. **on/off**: turns on/off torque from all Dynamixels. **on/off [index1] [index2] [index3] …** : turns torque on/off from ID[index1] ID[index2] ID[index3]. For example off 20 releases torque from ID20. Notice that STP7 for ID20 will read [----]. Typing on 20 turns torque from ID20 on again and the screen outputs the current position data of ID20. #### 2.6 Example Action editing with op3_action_editor 1) Run the op3_action_editor 2) Find the page where the "walking_init page" is by typing "list" ![](/assets/images/platform/op3/thormang3_action_editor_tui_action_editing_example1.jpg) 3) Exit the list and go to any blank page by typing "page [x]"(for example, page 15). ![](/assets/images/platform/op3/thormang3_action_editor_tui_action_editing_example2.jpg) 4) And copy the page 1 to page [x]. ![](/assets/images/platform/op3/thormang3_action_editor_tui_action_editing_example3.jpg) 3) Go to "walking_init" pose by typing "play" 5) Turn off the torque of ID 2, 4 and 8 by typing "off 2 4 8" ![](/assets/images/platform/op3/thormang3_action_editor_tui_action_editing_example4.jpg) 6) After getting the desired pose turn torque on again by simple typing on. And insert the pose to step 1 by typing "i 1" ![](/assets/images/platform/op3/thormang3_action_editor_tui_action_editing_example5.jpg) 7) Edit "Pause Time", "Time" of STP1 and "Page Step" as shown below. ![](/assets/images/platform/op3/thormang3_action_editor_tui_action_editing_example6.jpg) 8) Type "play" and check the ROBOTIS-OP3's action [&lt;&lt; Back] [op3_action_module]:[op3_action_module] [&lt;&lt; Back]:[robotis_op3_tools.md] [Installing ROBOTIS ROS Package]:OP3_Recovery_of_ROBOTIS_OP3#24_installation_robotis_ros_packages.md
Markdown
UTF-8
833
3.125
3
[]
no_license
<div> <h1 style="text-align:center; color:#005086;">Tweety - The Twitter Clone</h1> <h3 style="text-align:center; margin-top:-11px; color:#005086;">A Twitter clone.</h1> <br /> <p> Made in Laravel 6, currently, this is the basic version of Twitter with basic functionalities. We're going to extend the features of the app by using different technologies like ReactJS, MaterialUI, etc. </p> #### Features Here is the list of functionalities that you can find in this app: <ol> <li>A user can tweet</li> <li>A user can view its profile</li> <li>A user can edit its profile</li> <li>A user can Explore other users and their profiles</li> <li>A user can like or dislike a tweet</li> </ol> #### Technologies Used Laravel, VueJS, TailwindCSS, Turbolinks ##### Thank You, and stay tuned for future updates. </div>
PHP
UTF-8
317
3.46875
3
[]
no_license
<?php $X = 100; $Y = 50; $Z = ($X == $Y) xor ($X > $Y); echo "($X == $Y) xor ($X > $Y) :"; if ($Z == true) { echo "Hello PHP"; } echo "<br>"; echo "<br>"; echo "($X == $Y) xor ($X > $Y) : "; if ($Z == false) { echo "Maaf Kondisinya tidak sesuai"; } ?>
Java
UTF-8
1,172
3.234375
3
[]
no_license
/***************************************************************************** * Author: Rahul Jagetia * Date: 10/06/2019 * Project Description: Class to define Deck for Rummy. Provides a deck of * cards, and allows users to pull from the "deck" object * **************************************************************************** */ import java.util.Random; public class Deck { private Card[] theDeck; private String suits[] = {"Diamonds", "Clubs", "Spades", "Hearts"}; public int numberOfCards; public Deck() { numberOfCards = 52; theDeck = new Card[numberOfCards]; for(int i = 0; i < 52; i++){ theDeck[i] = new Card((i % 13) + 1, suits[i/13]); } } public Card dealACard(){ int i = (int) (Math.random() * 51); while (theDeck[i] == null) { i = (int) (Math.random() * 51); } Card currentCard = theDeck[i]; theDeck[i] = null; numberOfCards--; return currentCard; } public String toString(){ return ""; } }
JavaScript
UTF-8
1,053
2.90625
3
[ "MIT" ]
permissive
const randomHelper = require('../helpers/random-helper'), enums = require('../model/enums'), surnames = require('../model/surnames'), names = require('../model/names'); let getNameRandom = { execute: function (gender) { let nameModel; switch (enums.genders[gender]) { case enums.genders.male: nameModel = names.maleNames; break; case enums.genders.female: nameModel = names.femaleNames; break; default: nameModel = randomHelper.randomBool() ? names.maleNames : names.femaleNames; break; } let firstName = nameModel[randomHelper.randomInt(0, nameModel.length - 1)]; let qSurnames = randomHelper.randomInt(1, 4); let name = []; name.push(firstName); for (var i = 0; i < qSurnames; i++) { let currentSurname = surnames[randomHelper.randomInt(0, surnames.length - 1)]; if (name.indexOf(currentSurname) === -1) { name.push(currentSurname); } } return name.join(' '); } } module.exports = getNameRandom;
SQL
UTF-8
765
4
4
[ "MIT" ]
permissive
CREATE TABLE IF NOT EXISTS CUSTOMER_ORDER( id UUID NOT NULL, creation_time TIMESTAMP, address VARCHAR, city VARCHAR, country VARCHAR, email VARCHAR, first_name VARCHAR, last_name VARCHAR, phone VARCHAR, zipcode VARCHAR, price NUMERIC(19,2) NOT NULL, PRIMARY KEY (id) ); CREATE TABLE IF NOT EXISTS ORDER_ITEM( id UUID NOT NULL, quantity INT NOT NULL, article_id UUID, PRIMARY KEY(id), FOREIGN KEY (article_id) REFERENCES ARTICLE(id) ); CREATE TABLE IF NOT EXISTS CUSTOMER_ORDER_ITEMS( customer_order_id UUID, items_id UUID, UNIQUE (customer_order_id, items_id), FOREIGN KEY (items_id) REFERENCES ORDER_ITEM(id), FOREIGN KEY (customer_order_id) REFERENCES CUSTOMER_ORDER(id) );
C++
UTF-8
4,537
2.59375
3
[]
no_license
/* * HaoRan ImageFilter Classes v0.3 * Copyright (C) 2012 Zhenjun Dai * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation. */ #if !defined(ColorToneFilter_H) #define ColorToneFilter_H #include "IImageFilter.h" namespace imagefilter{ class ColorToneFilter : public IImageFilter{ private: double _hue ; double _saturation ; double _lum_tab[256] ; public: /// @name RGB <--> HLS (Hue, Lightness, Saturation). //@{ /** RGB --> HLS \n prgb - address of 24bpp or 32bpp pixel. */ static void RGBtoHLS (int rgb, double& H, double& L, double& S) { Color color(rgb); int n_cmax = max(color.R, max(color.G, color.B)); int n_cmin = min(color.R, min(color.G, color.B)); L = (n_cmax + n_cmin) / 2.0 / 255.0 ; if (n_cmax == n_cmin) { S = H = 0.0 ; return ; } double r = color.R / 255.0, g = color.G / 255.0, b = color.B / 255.0, cmax = n_cmax / 255.0, cmin = n_cmin / 255.0, delta = cmax - cmin ; if (L < 0.5) S = delta / (cmax + cmin) ; else S = delta / (2.0 - cmax - cmin) ; if (color.R == n_cmax) H = (g-b) / delta ; else if (color.G == n_cmax) H = 2.0 + (b-r) / delta ; else H = 4.0 + (r-g) / delta ; H /= 6.0 ; if (H < 0.0) H += 1.0 ; } static int DoubleRGB_to_RGB (double r, double g, double b) { return Color::rgb(SAFECOLOR(r*255), SAFECOLOR(g*255), SAFECOLOR(b*255)) ; } static double HLS_Value (double n1, double n2, double h) { if (h > 6.0) h -= 6.0 ; else if (h < 0.0) h += 6.0 ; if (h < 1.0) return n1 + (n2 - n1) * h ; else if (h < 3.0) return n2 ; else if (h < 4.0) return n1 + (n2 - n1) * (4.0 - h) ; return n1 ; } /// HLS --> RGB. static int HLStoRGB (double H, double L, double S) { if ((!(S > 0)) && (!(S < 0))) // == 0 return DoubleRGB_to_RGB (L, L, L) ; double m1, m2 ; if (L > 0.5) m2 = L + S - L*S ; else m2 = L * (1.0 + S) ; m1 = 2.0*L - m2 ; double r = HLS_Value (m1, m2, H*6.0 + 2.0) ; double g = HLS_Value (m1, m2, H*6.0) ; double b = HLS_Value (m1, m2, H*6.0 - 2.0) ; return DoubleRGB_to_RGB (r,g,b) ; } /** Calculate grayscale value of pixel \n prgb - address of 24bpp or 32bpp pixel. */ static int GetGrayscale (int r, int g , int b) { return (int)((30*r + 59*g + 11*g) / 100) ; } ColorToneFilter(int tone, int saturation) { double l ; RGBtoHLS (tone, _hue, l, _saturation) ; _saturation = _saturation * (saturation/255.0) * (saturation/255.0) ; _saturation = ((_saturation < 1) ? _saturation : 1) ; for (int i=0 ; i < 256 ; i++) { int cr = Color::rgb(i,i,i) ; double h, ll, s ; RGBtoHLS (cr, h, ll, s) ; ll = ll * (1 + (128-abs(saturation-128)) / 128.0 / 9.0) ; _lum_tab[i] = ((ll < 1) ? ll : 1) ; } }; std::string get_type_id() { return typeid(this).name(); } virtual Image process(Image imageIn) { int r, g, b; for(int x = 0 ; x < imageIn.getWidth() ; x++){ for(int y = 0 ; y < imageIn.getHeight() ; y++){ r = imageIn.getRComponent(x, y); g = imageIn.getGComponent(x, y); b = imageIn.getBComponent(x, y); double l = _lum_tab[GetGrayscale(r, g, b)] ; int cr =HLStoRGB (_hue, l, _saturation) ; imageIn.setPixelColor(x, y, cr); } } return imageIn; } }; }// namespace imagefilter #endif
Swift
UTF-8
479
3.59375
4
[ "MIT" ]
permissive
//: [Previous](@previous) import Foundation enum SegueIdentifier: String { case ShowPhoto case NewPhoto case Share } func performSegue(id: String) { let segue = SegueIdentifier(rawValue: id) if let segue = segue { switch segue { case .ShowPhoto: print("Perform ShowPhoto") case .NewPhoto: print("Perform NewPhoto") case .Share: print("Perform Share") } } } performSegue("ShowPhoto") performSegue("Delete") //: [Next](@next)
Swift
UTF-8
384
2.90625
3
[]
no_license
// // CategoryModel.swift // Charity_App // // Created by Sankeerth V S on 4/16/21. // import Foundation class CategoryModel { var categoryID: String = "" var imageURL: String = "" var name: String = "" init(categoryID: String, imageURL: String, name: String) { self.categoryID = categoryID self.imageURL = imageURL self.name = name } }
Java
UTF-8
3,691
2.0625
2
[]
no_license
package com.tuxing.sdk.db.entity; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your custom includes here import java.util.List; // KEEP INCLUDES END /** * Entity mapped to table feed. */ public class Feed implements java.io.Serializable { private Long id; private long feedId; private String content; private String attachments; private Long userId; private String userName; private String userAvatar; private Integer userType; private Integer feedType; private Long publishTime; private Boolean hasMoreComment; // KEEP FIELDS - put your custom fields here Long ActivityId; List<Comment> comments; List<Comment> likes; // KEEP FIELDS END public Feed() { } public Feed(Long id) { this.id = id; } public Feed(Long id, long feedId, String content, String attachments, Long userId, String userName, String userAvatar, Integer userType, Integer feedType, Long publishTime, Boolean hasMoreComment) { this.id = id; this.feedId = feedId; this.content = content; this.attachments = attachments; this.userId = userId; this.userName = userName; this.userAvatar = userAvatar; this.userType = userType; this.feedType = feedType; this.publishTime = publishTime; this.hasMoreComment = hasMoreComment; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public long getFeedId() { return feedId; } public void setFeedId(long feedId) { this.feedId = feedId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAttachments() { return attachments; } public void setAttachments(String attachments) { this.attachments = attachments; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserAvatar() { return userAvatar; } public void setUserAvatar(String userAvatar) { this.userAvatar = userAvatar; } public Integer getUserType() { return userType; } public void setUserType(Integer userType) { this.userType = userType; } public Integer getFeedType() { return feedType; } public void setFeedType(Integer feedType) { this.feedType = feedType; } public Long getPublishTime() { return publishTime; } public void setPublishTime(Long publishTime) { this.publishTime = publishTime; } public Boolean getHasMoreComment() { return hasMoreComment; } public void setHasMoreComment(Boolean hasMoreComment) { this.hasMoreComment = hasMoreComment; } // KEEP METHODS - put your custom methods here public Long getActivityId() { return ActivityId; } public void setActivityId(Long activityId) { ActivityId = activityId; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } public List<Comment> getLikes() { return likes; } public void setLikes(List<Comment> likes) { this.likes = likes; } // KEEP METHODS END }
PHP
UTF-8
5,539
2.65625
3
[]
no_license
<?php /* * SifeiService * cfdi33® * ® 2017, Softcoatl * http://www.softcoatl.mx * @author Rolando Esquivel Villafaña, Softcoatl * @version 1.0 * @since dic 2017 */ namespace cfdi33; require_once ("cfdi33/utils/SOAPClient.php"); require_once ("cfdi33/SelloCFDI.php"); require_once ("PACService.php"); class SifeiService implements PACService { /* @var $PAC SifeiPACWrapper */ private $PAC; private $error; function __construct($PAC) { $this->PAC = $PAC; } function getPAC() { return $this->PAC; } function getError() { return $this->error; } function setPAC($PAC) { $this->PAC = $PAC; } private function zip($xmlCFDI) { $file = tempnam("tmp", "zip"); trigger_error("Zipping into file " . $file); $zip = new \ZipArchive(); if ($zip->open($file, \ZipArchive::OVERWRITE)) { $zip->addFromString('.xml', $xmlCFDI); $zip->close(); $contents = file_get_contents($file); return $contents; } return FALSE; }//zip private function unzip($xmlCFDIZipped) { $file = tempnam("tmp", "zip"); trigger_error("Unzipping into file " . $file); file_put_contents($file, $xmlCFDIZipped); $zip = new \ZipArchive(); if ($zip->open($file)) { $zip->renameIndex(0, '.xml'); $cfdiTimbrado = $zip->getFromIndex(0); $zip->close(); return $cfdiTimbrado; } return FALSE; }//unzip public function timbraComprobante($xmlCFDI) { $zipped = $this->zip($xmlCFDI); $b64Zipped = base64_encode($zipped); trigger_error($b64Zipped); $params = array( "Usuario" => $this->PAC->getUser(), "Password" => $this->PAC->getPassword(), "archivoXMLZip" => $b64Zipped, "Serie" => $this->PAC->getSerie(), "IdEquipo" => $this->PAC->getIdEquipo() ); trigger_error("CFDI33_2 :: " . print_r($params, TRUE)); /* @var $wsClient nusoap_client */ $wsClient = \com\softcoatl\SOAPClient::getClient($this->PAC->getUrl()); try { $wsResponse = $wsClient->call("getCFDI", $params, "http://MApeados/"); trigger_error("CFDI33_2 :: " . print_r($wsResponse, TRUE)); trigger_error("CFDI33_2 :: " . $wsClient->debug_str); $wsError = $wsClient->getError(); if ($wsError) { if ($wsResponse['detail']['SifeiException']['codigo'] == '307') { return $this->getTimbre($xmlCFDI); } else { echo $wsClient->debug_str; $this->error = $wsResponse['detail']['SifeiException']['error']; return FALSE; } } else { return $this->unzip(base64_decode($wsResponse['return'])); } } catch (\Exception $e) { $this->error = $e->getMessage(); } return FALSE; }//timbraComprobante public function getTimbre($xmlCFDI) { $cfdi = new \DOMDocument("1.0","UTF-8"); $cfdi->loadXML($xmlCFDI); $originalBytes = SelloCFDI::getOriginalBytes($xmlCFDI); $digestion = sha1($originalBytes); "<br/>Cadena Original::<br/>" . $originalBytes . "</br>"; $params = array( "rfc" => $this->PAC->getUser(), "pass" => $this->PAC->getPassword(), "hash" => $digestion ); /* @var $wsClient nusoap_client */ $wsClient = \com\softcoatl\SOAPClient::getClient($this->PAC->getUrl()); try { $wsResponse = $wsClient->call("getXML", $params, "http://MApeados/"); "<br/>SOAP Trace::<br/>" . $wsClient->debug_str . "</br>"; $wsError = $wsClient->getError(); if ($wsError) { $this->error = $wsResponse['detail']['SifeiException']['error']; return FALSE; } else { return $wsResponse['return']; } } catch (\Exception $e) { $this->error = $e->getMessage(); } return FALSE; }//getTimbre /** * * @param String $rfc RFC del Emisor * @param String $uuid UUID del Comprobante * @param String $pass Password del archivo PFX * @return boolean */ public function cancelaComprobante($rfc, $uuid, $pass) { $params = array( "usuarioSIFEI" => $this->PAC->getUser(), "passUser" => $this->PAC->getPassword(), "rfc" => $rfc, "pfx" => base64_encode(file_get_contents('certificado/file.pfx')), "passPFX" => $pass, "UUIDS"=> array($uuid) ); /* @var $wsClient nusoap_client */ $wsClient = \com\softcoatl\SOAPClient::getClient($this->PAC->getUrl()); try { $wsResponse = $wsClient->call("cancelaCFDI", $params, "http://MApeados/"); "<br/>SOAP Trace::<br/>" . $wsClient->debug_str . "</br>"; $wsError = $wsClient->getError(); if ($wsError) { $this->error = $wsResponse['detail']['SifeiException']['error']; return FALSE; } else { return $wsResponse['return']; } } catch (\Exception $e) { $this->error = $e->getMessage(); } return FALSE; }//cancelaComprobante }//SifeiService
Java
UTF-8
8,482
2.390625
2
[ "Apache-2.0", "LicenseRef-scancode-unicode" ]
permissive
/* * Copyright (C) 2014 The Android Open Source Project * * 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 android.bluetooth.le; import android.os.Parcel; import android.os.Parcelable; /** * The {@link AdvertiseSettings} provide a way to adjust advertising preferences for each * Bluetooth LE advertisement instance. Use {@link AdvertiseSettings.Builder} to create an * instance of this class. */ public final class AdvertiseSettings implements Parcelable { /** * Perform Bluetooth LE advertising in low power mode. This is the default and preferred * advertising mode as it consumes the least power. */ public static final int ADVERTISE_MODE_LOW_POWER = 0; /** * Perform Bluetooth LE advertising in balanced power mode. This is balanced between advertising * frequency and power consumption. */ public static final int ADVERTISE_MODE_BALANCED = 1; /** * Perform Bluetooth LE advertising in low latency, high power mode. This has the highest power * consumption and should not be used for continuous background advertising. */ public static final int ADVERTISE_MODE_LOW_LATENCY = 2; /** * Advertise using the lowest transmission (TX) power level. Low transmission power can be used * to restrict the visibility range of advertising packets. */ public static final int ADVERTISE_TX_POWER_ULTRA_LOW = 0; /** * Advertise using low TX power level. */ public static final int ADVERTISE_TX_POWER_LOW = 1; /** * Advertise using medium TX power level. */ public static final int ADVERTISE_TX_POWER_MEDIUM = 2; /** * Advertise using high TX power level. This corresponds to largest visibility range of the * advertising packet. */ public static final int ADVERTISE_TX_POWER_HIGH = 3; /** * The maximum limited advertisement duration as specified by the Bluetooth SIG */ private static final int LIMITED_ADVERTISING_MAX_MILLIS = 180 * 1000; private final int mAdvertiseMode; private final int mAdvertiseTxPowerLevel; private final int mAdvertiseTimeoutMillis; private final boolean mAdvertiseConnectable; private AdvertiseSettings(int advertiseMode, int advertiseTxPowerLevel, boolean advertiseConnectable, int advertiseTimeout) { mAdvertiseMode = advertiseMode; mAdvertiseTxPowerLevel = advertiseTxPowerLevel; mAdvertiseConnectable = advertiseConnectable; mAdvertiseTimeoutMillis = advertiseTimeout; } private AdvertiseSettings(Parcel in) { mAdvertiseMode = in.readInt(); mAdvertiseTxPowerLevel = in.readInt(); mAdvertiseConnectable = in.readInt() != 0; mAdvertiseTimeoutMillis = in.readInt(); } /** * Returns the advertise mode. */ public int getMode() { return mAdvertiseMode; } /** * Returns the TX power level for advertising. */ public int getTxPowerLevel() { return mAdvertiseTxPowerLevel; } /** * Returns whether the advertisement will indicate connectable. */ public boolean isConnectable() { return mAdvertiseConnectable; } /** * Returns the advertising time limit in milliseconds. */ public int getTimeout() { return mAdvertiseTimeoutMillis; } @Override public String toString() { return "Settings [mAdvertiseMode=" + mAdvertiseMode + ", mAdvertiseTxPowerLevel=" + mAdvertiseTxPowerLevel + ", mAdvertiseConnectable=" + mAdvertiseConnectable + ", mAdvertiseTimeoutMillis=" + mAdvertiseTimeoutMillis + "]"; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mAdvertiseMode); dest.writeInt(mAdvertiseTxPowerLevel); dest.writeInt(mAdvertiseConnectable ? 1 : 0); dest.writeInt(mAdvertiseTimeoutMillis); } public static final @android.annotation.NonNull Parcelable.Creator<AdvertiseSettings> CREATOR = new Creator<AdvertiseSettings>() { @Override public AdvertiseSettings[] newArray(int size) { return new AdvertiseSettings[size]; } @Override public AdvertiseSettings createFromParcel(Parcel in) { return new AdvertiseSettings(in); } }; /** * Builder class for {@link AdvertiseSettings}. */ public static final class Builder { private int mMode = ADVERTISE_MODE_LOW_POWER; private int mTxPowerLevel = ADVERTISE_TX_POWER_MEDIUM; private int mTimeoutMillis = 0; private boolean mConnectable = true; /** * Set advertise mode to control the advertising power and latency. * * @param advertiseMode Bluetooth LE Advertising mode, can only be one of {@link * AdvertiseSettings#ADVERTISE_MODE_LOW_POWER}, * {@link AdvertiseSettings#ADVERTISE_MODE_BALANCED}, * or {@link AdvertiseSettings#ADVERTISE_MODE_LOW_LATENCY}. * @throws IllegalArgumentException If the advertiseMode is invalid. */ public Builder setAdvertiseMode(int advertiseMode) { if (advertiseMode < ADVERTISE_MODE_LOW_POWER || advertiseMode > ADVERTISE_MODE_LOW_LATENCY) { throw new IllegalArgumentException("unknown mode " + advertiseMode); } mMode = advertiseMode; return this; } /** * Set advertise TX power level to control the transmission power level for the advertising. * * @param txPowerLevel Transmission power of Bluetooth LE Advertising, can only be one of * {@link AdvertiseSettings#ADVERTISE_TX_POWER_ULTRA_LOW}, {@link * AdvertiseSettings#ADVERTISE_TX_POWER_LOW}, * {@link AdvertiseSettings#ADVERTISE_TX_POWER_MEDIUM} * or {@link AdvertiseSettings#ADVERTISE_TX_POWER_HIGH}. * @throws IllegalArgumentException If the {@code txPowerLevel} is invalid. */ public Builder setTxPowerLevel(int txPowerLevel) { if (txPowerLevel < ADVERTISE_TX_POWER_ULTRA_LOW || txPowerLevel > ADVERTISE_TX_POWER_HIGH) { throw new IllegalArgumentException("unknown tx power level " + txPowerLevel); } mTxPowerLevel = txPowerLevel; return this; } /** * Set whether the advertisement type should be connectable or non-connectable. * * @param connectable Controls whether the advertisment type will be connectable (true) or * non-connectable (false). */ public Builder setConnectable(boolean connectable) { mConnectable = connectable; return this; } /** * Limit advertising to a given amount of time. * * @param timeoutMillis Advertising time limit. May not exceed 180000 milliseconds. A value * of 0 will disable the time limit. * @throws IllegalArgumentException If the provided timeout is over 180000 ms. */ public Builder setTimeout(int timeoutMillis) { if (timeoutMillis < 0 || timeoutMillis > LIMITED_ADVERTISING_MAX_MILLIS) { throw new IllegalArgumentException("timeoutMillis invalid (must be 0-" + LIMITED_ADVERTISING_MAX_MILLIS + " milliseconds)"); } mTimeoutMillis = timeoutMillis; return this; } /** * Build the {@link AdvertiseSettings} object. */ public AdvertiseSettings build() { return new AdvertiseSettings(mMode, mTxPowerLevel, mConnectable, mTimeoutMillis); } } }
C#
UTF-8
1,024
2.5625
3
[ "MS-PL" ]
permissive
using System; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; namespace STPWPDemo { public partial class SpinTextBlock : UserControl { public event EventHandler<EventArgs> Increment; public event EventHandler<EventArgs> Decrement; public SpinTextBlock() { InitializeComponent(); } void Dec_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (Decrement != null) { Decrement(this, EventArgs.Empty); } } void Inc_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (Increment != null) { Increment(this, EventArgs.Empty); } } public string Text { get { return TextBlock.Text; } set { TextBlock.Text = value; } } } }
Java
UTF-8
1,584
2.5625
3
[ "MIT" ]
permissive
package mage.cards.i; import java.util.UUID; import mage.abilities.Mode; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.effects.common.CounterUnlessPaysEffect; import mage.abilities.effects.common.DamageTargetEffect; import mage.abilities.effects.common.DrawDiscardControllerEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.filter.StaticFilters; import mage.target.TargetSpell; import mage.target.common.TargetCreaturePermanent; /** * * @author LevelX2 */ public final class IzzetCharm extends CardImpl { public IzzetCharm(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{U}{R}"); // Choose one — Counter target noncreature spell unless its controller pays {2}; this.getSpellAbility().addEffect(new CounterUnlessPaysEffect(new GenericManaCost(2))); this.getSpellAbility().getTargets().add(new TargetSpell(StaticFilters.FILTER_SPELL_NON_CREATURE)); // or Izzet Charm deals 2 damage to target creature; Mode mode = new Mode(new DamageTargetEffect(2)); mode.addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addMode(mode); // or draw two cards, then discard two cards. mode = new Mode(new DrawDiscardControllerEffect(2, 2)); this.getSpellAbility().addMode(mode); } private IzzetCharm(final IzzetCharm card) { super(card); } @Override public IzzetCharm copy() { return new IzzetCharm(this); } }
PHP
UTF-8
419
3.25
3
[]
no_license
<?php $sum = 0; $fh = fopen('input_d02.txt','r'); while ($line = fgetcsv($fh, 1000, "\t")) { sort($line); for ($i = 0; $i < count($line); $i ++) { for ($j = count($line) - 1; $j >= 0; $j--) { if ($line[$j] != $line[$i] && $line[$j] % $line[$i] === 0) { $sum += $line[$j] / $line[$i]; break 2; } } } } fclose($fh); var_dump($sum);
C++
UTF-8
1,145
2.609375
3
[ "MIT" ]
permissive
#include "Plane.h" Plane::Plane() { glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); Id = new float[4]; Id[0] = 1.0f; Id[1] = 1.0f; Id[2] = 1.0f; Id[3] = 1.0f; Ia = new float[4]; Ia[0] = 1.0f; Ia[1] = 1.0f; Ia[2] = 1.0f; Ia[3] = 1.0f; Is = new float[4]; Is[0] = 1.0f; Is[1] = 1.0f; Is[2] = 1.0f; Is[3] = 1.0f; Ip = new float[4]; Ip[0] = 1.0f; Ip[1] = 1.0f; Ip[2] = 1.0f; Ip[3] = 1.0f; glLightfv(GL_LIGHT0, GL_AMBIENT, Ia); glLightfv(GL_LIGHT0, GL_DIFFUSE, Id); glLightfv(GL_LIGHT0, GL_SPECULAR, Is); glLightfv(GL_LIGHT0, GL_POSITION, Ip); pos = new float[3]; dims = new float[3]; pos[0] = 0.0f; pos[1] = 0.0f; pos[2] = 0.0f; sintel = glmReadOBJ("assets/ojala/tectr.obj"); glmUnitize(sintel); glmFacetNormals(sintel); glmDimensions(sintel, dims); center = new float[3]; center[0] = pos[0] + dims[0] / 2.0f; center[1] = pos[1] + dims[1] / 2.0f; center[2] = pos[2] + dims[2] / 2.0f; } Plane::~Plane() {} void Plane::draw() { glPushMatrix(); { glScalef(20, 20, 20); glTranslatef(pos[0], pos[1], pos[2]); glRotatef(180, 1, 0, 0); glmDraw(sintel, GLM_SMOOTH | GLM_TEXTURE); } glPopMatrix(); }
Swift
UTF-8
5,748
2.78125
3
[]
no_license
// // ViewController.swift // stopwatch // // Created by nttr on 2017/07/14. // Copyright © 2017年 nttr. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { @IBOutlet var label: UILabel! var countNum: Int = 0 var isTimerRunning: Bool = false var timer: Timer = Timer() @IBOutlet var button: UIButton! @IBOutlet var lapTableView: UITableView! @IBOutlet var lapCustomTableView: UITableView! var lapTime: [Int] = [] var lapTimeImages: [UIImage] = [] var lapTimeImageNames: [String] = ["lap.jpg"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. button.backgroundColor = UIColor.cyan imageInit() lapTableView.dataSource = self lapTableView.tableFooterView = UIView() // needless cells made invisivles // CustomCells regist lapCustomTableView.dataSource = self lapCustomTableView.tableFooterView = UIView() let nib = UINib(nibName: "lapTableViewCell", bundle: Bundle.main) lapCustomTableView.register(nib, forCellReuseIdentifier: "CustomCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // images intialized function func imageInit(){ for i in 0..<lapTimeImageNames.count{ lapTimeImages.append(UIImage(named: lapTimeImageNames[i])!) } } // time label update func update(){ countNum+=1 label.text = count2String(count: countNum) } // Int count change to time format func count2String(count: Int) -> String { let ms = count % 100 let s = (count - ms) / 100 % 60 let m = (count - s - ms) / 6000 % 3600 return String (format: "%02d:%02d.%02d", m,s,ms) } // changing buttton Start and Stop func changeButton(){ if isTimerRunning{ button.backgroundColor = UIColor.red button.setTitle("Stop", for: UIControlState.normal) }else{ button.backgroundColor = UIColor.cyan button.setTitle("Start", for: UIControlState.normal) } } // Stop func stop(){ if isTimerRunning == true{ timer.invalidate() isTimerRunning = false } } // Start Timer @IBAction func startTimer(){ if isTimerRunning { stop() changeButton() } else { timer = Timer.scheduledTimer( timeInterval: 0.01, target:self, selector: #selector(ViewController.update), userInfo: nil, repeats: true ) isTimerRunning = true changeButton() } } /* @IBAction func showAlert(){ let alert = UIAlertController(title:"Coution!", message: "Description", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default){ (action) in alert.dismiss(animated: true, completion: nil) } alert.addAction(action) self.present(alert, animated: true, completion: nil) }*/ // reset button function @IBAction func reset(){ countNum = 0 label.text = "00:00.00" lapTime.removeAll() lapTableView.reloadData() } // laptime stock @IBAction func lapTimeStock(){ if isTimerRunning{ lapTime.append(countNum) print(lapTime) lapTableView.reloadData() lapCustomTableView.reloadData() }else{ return } } /* for Table View */ // Max amount of table cells func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView.tag == 1{ return lapTime.count // max cells }else if tableView.tag == 2 { return lapTime.count }else{ return lapTime.count } //return 4 :4つだけ表示したいとき } // Present Data for Cells func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView.tag == 1{ // get cell let cell = tableView.dequeueReusableCell(withIdentifier: "lapCell")! //cell.textLabel?.text = count2String(count: lapTime[indexPath.row]) // decide present views let lapImageView = cell.viewWithTag(1) as! UIImageView let lapLavelView = cell.viewWithTag(2) as! UILabel lapImageView.image = lapTimeImages[0] lapLavelView.text = count2String(count: lapTime[indexPath.row]) return cell }else if tableView.tag == 2{ let ccell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! lapTableViewCell ccell.lapImageView.image = lapTimeImages[0] ccell.lapLabel.text = count2String(count: lapTime[indexPath.row]) return ccell }else{ // get cell let cell = tableView.dequeueReusableCell(withIdentifier: "lapCell")! //cell.textLabel?.text = count2String(count: lapTime[indexPath.row]) // decide present views let lapImageView = cell.viewWithTag(1) as! UIImageView let lapLavelView = cell.viewWithTag(2) as! UILabel lapImageView.image = lapTimeImages[0] lapLavelView.text = count2String(count: lapTime[indexPath.row]) return cell } } }
Java
UTF-8
1,918
2.03125
2
[]
no_license
package com.lala.lashop.ui.user.presenter; import com.lala.lashop.base.mvp.BasePresenter; import com.lala.lashop.http.ApiSubscribers; import com.lala.lashop.http.HttpResult; import com.lala.lashop.http.exception.ApiException; import com.lala.lashop.ui.user.model.UserDetailModel; import com.lala.lashop.ui.user.view.UserDetailView; /** * Created by JX on 2018/4/19. */ public class UserDetailPresenter extends BasePresenter<UserDetailView> { private UserDetailModel mModel; public UserDetailPresenter() { mModel = new UserDetailModel(); } public void update() { getView().showLoadingDialog(); mModel.user_updateinfo(getView().getUserId(), getView().getName(), getView().getImg(), getView().getSex(), getView().getEmail(), getView().getBirthday()) .compose(this.<HttpResult>compose()) .subscribe(new ApiSubscribers<HttpResult>(getView()) { @Override public void onSuccess(HttpResult httpResult) { getView().toast(httpResult.getMess().toString()); getView().updateSuccess(); } @Override public void onError(ApiException e) { } }); } public void uploadImage() { getView().showLoadingDialog(); mModel.upload_image(getView().getHeadFile()) .compose(this.<HttpResult<String>>compose()) .subscribe(new ApiSubscribers<HttpResult<String>>(getView()) { @Override public void onSuccess(HttpResult<String> stringHttpResult) { getView().uploadSuccess(stringHttpResult.getMess()); } @Override public void onError(ApiException e) { } }); } }
C#
UTF-8
896
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xrm.Sdk.Metadata; namespace MarkMpn.FetchXmlToWebAPI { /// <summary> /// Provides metadata for the <see cref="FetchXmlToWebAPIConverter"/> /// </summary> public interface IMetadataProvider { /// <summary> /// Indicates if a connection to CRM is available /// </summary> bool IsConnected { get; } /// <summary> /// Gets the metadata for an entity /// </summary> /// <param name="logicalName">The logical name of the entity to get the metadata of</param> /// <returns>The metadata of the requested entity</returns> /// <remarks> /// If the <paramref name="logicalName"/> is not valid, this method throws an exception /// </remarks> EntityMetadata GetEntity(string logicalName); } }
Python
UTF-8
1,418
2.5625
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """pytest Roles API wrapper tests and fixtures.""" import pytest import ciscosparkapi __author__ = "Chris Lunsford" __author_email__ = "chrlunsf@cisco.com" __copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates." __license__ = "MIT" # Helper Functions def get_list_of_roles(api, max=None): return api.roles.list(max=max) def get_role_by_id(api, roleId): return api.roles.get(roleId) def is_valid_role(obj): return isinstance(obj, ciscosparkapi.Role) and obj.id is not None def are_valid_roles(iterable): return all([is_valid_role(obj) for obj in iterable]) # pytest Fixtures @pytest.fixture(scope="session") def roles_list(api): return list(get_list_of_roles(api)) @pytest.fixture(scope="session") def roles_dict(roles_list): return {role.name: role for role in roles_list} # Tests class TestRolesAPI(object): """Test RolesAPI methods.""" def test_list_roles(self, roles_list): assert are_valid_roles(roles_list) def test_list_roles_with_paging(self, api): paging_generator = get_list_of_roles(api, max=1) roles = list(paging_generator) assert len(roles) > 1 assert are_valid_roles(roles) def test_get_role_by_id(self, api, roles_list): assert len(roles_list) >= 1 role_id = roles_list[0].id role = get_role_by_id(api, roleId=role_id) assert is_valid_role(role)
C#
UTF-8
1,499
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Gastos.DB; using Gastos.Models; namespace App_Gastos_Mensais { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); GastosDB.gastos.Add(new Compra(12.0, "Presunto")); GastosDB.gastos.Add(new Compra(15.0, "Cerveja")); GastosDB.gastos.Add(new Compra(32.0, "Carne")); Gasto.ItemsSource = GastosDB.gastos; } private async void Compras_selected(object sender, SelectedItemChangedEventArgs e) { Gasto selecionar = (Gasto)e.SelectedItem; Detalhes detalhes = new Detalhes(selecionar); await Navigation.PushAsync(detalhes); } private void Cadastrar(object sender, EventArgs e) { if (string.IsNullOrEmpty(descricaoCompra.Text) || string.IsNullOrEmpty(preco.Text)) { DisplayAlert("Erro", "Campos mal preenchidos", "Ok"); } else { double preco; if (double.TryParse(precoCompra.Text, out preco)) { GastosDB.gastos.Add(new Gasto(preco, descricao.Text)); descricao.Text = ""; preco.Text = ""; } } } } }
Python
UTF-8
63
2.765625
3
[]
no_license
from math import pi radius = 8 area = pi * 8 ** 2 print(area)
Swift
UTF-8
1,341
4.71875
5
[]
no_license
//: ## 神奇的转义功能 //: 你已经利用将字符放在引号之间的方法定义了很多字符串。但如果想创建一个包含引号的字符串,该怎么办呢? //: //: 可以尝试直接将引号加入字符串中间。 //: //: 取消以下 `badString` 代码行的注释,看看会发生什么: //let badString = "He said, "Hi there!" as he passed by." //: 出现了一个错误,因为 Swift 在遇到第二个引号(就是`“Hi”`之前)时就认为字符串定义已经完成。它不知道如何解析代码行的其余部分。 //: //: 尝试完以后,重新给代码加上注释,这样错误就消失了。 //: ### 解决方案 //: 要在字符串中包含引号,应在引号前键入一个反斜杠: let stringWithQuotationMarks = "He said, \"Hi there!\" as he passed by." //: 这个反斜杠会告诉 Swift 将下一个字符作为特殊字符处理。因为引号字符跟在反斜杠后面,Swift 会以不同方式进行处理。它会将引号包含在字符串中,而不是用于结束字符串定义。 //: //:反斜杠字符对字符串的正常行为进行“转义”,因此称为“转义字符”。 //: //: 现在,我们来学习使用转义字符可以实现的其他功能。 //: //:[上一页](@previous) | 第 10 页,共 16 页 | [下一页:转义序列](@next)
Java
UTF-8
980
3.171875
3
[]
no_license
package InterviewCake; public class CakeOrderChecker { public static boolean checkCakeOrders(int[] takeOut, int[] dineIn, int[] servedOrders) { int takeOutIndex = 0; int dineInIndex = 0; if (servedOrders.length != dineIn.length + takeOut.length) { return false; } for (int order: servedOrders) { if (dineInIndex < dineIn.length && order == dineIn[dineInIndex]) { dineInIndex++; continue; } if (takeOutIndex < takeOut.length && order == takeOut[takeOutIndex]) { takeOutIndex++; continue; } return false; } return true; } public static void main(String args[]) { int[] takeOut = {1, 15, 87, 3, 21}; int[] dineIn = {16, 76, 32}; int[] served = {16, 76, 21, 1, 15, 87, 3, 32}; System.out.println(checkCakeOrders(takeOut, dineIn, served)); } }
C#
UTF-8
3,323
3.015625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TicTacToeCommon.Interfaces; namespace TicTacToeCommon { public class Player : ITicTacToePlayer { // properties public int PlayerID { get; set; } public string PlayerFirstName { get; set; } public string PlayerLastName { get; set; } public DateTime Birthdate { get; set; } public char Gender { get; set; } public PlayerType PlayerType { get; set; } public char PlayerToken { get; set; } public int PlayerOrderByPlay { get; set; } // constructor that takes parameters public Player(string inFirstNameInput, string inLastNameInput, string inBirthdateInput, string inGenderInput, PlayerType inPlayerType) { this.PlayerFirstName = inFirstNameInput; this.PlayerLastName = inLastNameInput; this.PlayerType = inPlayerType; // this assume is is it not empty, it's in a acceptable format this.Birthdate = string.IsNullOrEmpty(inBirthdateInput) ? DateTime.MinValue : DateTime.ParseExact(inBirthdateInput, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture); // ternary example //this.Gender = string.IsNullOrEmpty(inGenderInput) || inGenderInput.ToUpper() != "M" // || inGenderInput.ToUpper() != "F" ? ' ' : Convert.ToChar(inGenderInput); if (!string.IsNullOrEmpty(inGenderInput) && (inGenderInput.ToUpper() == "M" || inGenderInput.ToUpper() == "F")) { // good value this.Gender = Convert.ToChar(inGenderInput); } else { this.Gender = ' '; } } // empty constructor public Player() { } // methods public string BotMove(char[,] inBoardState) { BotLogic _botLogic = new BotLogic(); //Random _random = new Random(); string _position = ""; ////1-5 = 2, 6-10 = 4, 11-15 = 6, 16-20 = 8, 21-100 = center //// if first by bot, then go on offense //if (_botLogic.IsFirstMove(inBoardState)) //{ // int _somenumber = _random.Next(1, 101); // if (_somenumber >= 1 && _somenumber <= 5) // { // _position = "2"; // } // else if (_somenumber >= 6 && _somenumber <= 10) // { // _position = "4"; // } // else if (_somenumber >= 11 && _somenumber <= 15) // { // _position = "6"; // } // else if (_somenumber >= 16 && _somenumber <= 20) // { // _position = "8"; // } // else // { // _position = "5"; // } //} //else //{ // // analyze board _position = _botLogic.Analyze(inBoardState, this); //} return _position; } } }
Markdown
UTF-8
7,314
3
3
[ "MIT" ]
permissive
--- title: QuicKey comments: true --- # Use <b><kbd>ctrl</kbd><kbd>tab</kbd></b> as a QuicKey shortcut Do you wish Chrome had the same <b><kbd>ctrl</kbd><kbd>tab</kbd></b> tab navigation as Firefox? There are two key features Chrome is missing: - **Switch to the previously used tab** - Press <b><kbd>ctrl</kbd><kbd>tab</kbd></b> and then release both keys - **Select an open tab from a menu using the keyboard** - Press <b><kbd>ctrl</kbd><kbd>tab</kbd></b> but then release just <kbd>tab</kbd> - Press <kbd>tab</kbd> repeatedly to select older tabs in the menu - Release <kbd>ctrl</kbd> to switch to the selected tab Chrome extensions can't provide this functionality all by themselves, unfortunately. With a little work, however, it *is* possible to achieve both these features with *QuicKey*, though the second one requires some additional Windows-only software. (*QuicKey* does support [keyboard-driven selection](/QuicKey/#mru-gif) of a tab from a menu without any additional setup; it's just that you can't use <b><kbd>ctrl</kbd><kbd>tab</kbd></b> as the shortcut without these workarounds.) You can use either of the options below, but don't use both. Following the steps in [Option 1](#option-1) will prevent [Option 2](#option-2) from working correctly. Note that with either option, you'll obviously lose the <b><kbd>ctrl</kbd><kbd>tab</kbd></b> and <b><kbd>ctrl</kbd><kbd>shift</kbd><kbd>tab</kbd></b> keyboard shortcuts to move the next or previous tab within the current window. On Windows and Linux, you can use <b><kbd>ctrl</kbd><kbd>pg dn</kbd> / <kbd>pg up</kbd></b> to move to the next/previous tab, and on macOS you can use <b><kbd>cmd</kbd><kbd>opt</kbd><kbd>→</kbd> / <kbd>←</kbd></b>. ## <a name="option-1"></a>Option 1: Use <b><kbd>ctrl</kbd><kbd>tab</kbd></b> to switch to previously used tabs Chrome's *Keyboard shortcuts* screen normally blocks you from using <b><kbd>ctrl</kbd><kbd>tab</kbd></b> as a shortcut, but it is possible to use the Chrome developer tools to work around this limitation. (This is also much simpler and more reliable than other approaches that require messing around with Chrome's preferences files.) 1. [Install QuicKey](https://chrome.google.com/webstore/detail/quickey-%E2%80%93-the-quick-tab-s/ldlghkoiihaelfnggonhjnfiabmaficg). 2. Right-click the *QuicKey* icon <img src="../img/icon-38.png" style="height: 19px; vertical-align: text-bottom;"> and select *Options* from the menu. <img src="../img/options-in-menu.png" style="width: 208px;"> 3. Scroll down the *QuicKey Options* page and then click the *Change Chrome shortcuts* button. <img src="../img/chrome-shortcuts-button.png" style="width: 485px;"> 4. After the *Keyboard shortcuts* page opens, press <b><kbd>ctrl</kbd><kbd>shift</kbd><kbd>J</kbd></b> on Windows/Linux or <b><kbd>cmd</kbd><kbd>opt</kbd><kbd>J</kbd></b> on macOS to open the Chrome DevTools. <img src="../img/console-open.png"> 5. Copy this block of code: chrome.developerPrivate.updateExtensionCommand({ extensionId: "ldlghkoiihaelfnggonhjnfiabmaficg", commandName: "1-previous-tab", keybinding: "Ctrl+Tab" }); chrome.developerPrivate.updateExtensionCommand({ extensionId: "ldlghkoiihaelfnggonhjnfiabmaficg", commandName: "2-next-tab", keybinding: "Ctrl+Shift+Tab" }); <button class="copy" onclick="copyCode()">Copy to Clipboard</button> 6. Click into the console area of DevTools and paste the code next to the >. <img src="../img/code-pasted.png"> 7. Press <kbd>enter</kbd> to run it. <img src="../img/ctrl-tab-selected.png"> That's it! Now you can press <b><kbd>ctrl</kbd><kbd>tab</kbd></b> to switch to the previously used tab. If you press it again within .75 seconds, while the icon is inverted <img src="../img/icon-38-inverted.png" style="height: 19px; vertical-align: text-bottom;">, you'll switch to the tab before that. You can press <b><kbd>ctrl</kbd><kbd>shift</kbd><kbd>tab</kbd></b> to navigate in the other direction. If you later change your mind and want to remove these shortcuts, just go back into the *Keyboard shortcuts* screen and click the delete button next to the shortcuts, or change them to something else. (You should always be cautious about copying code from a website and running it in DevTools, but even if you don't know JavaScript, it's hopefully clear what the snippet above is doing. It's calling a private updateExtensionCommand() function twice to set <b><kbd>ctrl</kbd><kbd>tab</kbd></b> and <b><kbd>ctrl</kbd><kbd>shift</kbd><kbd>tab</kbd></b> keyboard shortcuts. The "ldlgh..." string is *QuicKey*'s extension ID, which you can see in its [Chrome webstore link](https://chrome.google.com/webstore/detail/quickey-%E2%80%93-the-quick-tab-s/ldlghkoiihaelfnggonhjnfiabmaficg), so this code won't affect any other extensions you have installed.) ## <a name="option-2"></a>Option 2: Use <b><kbd>ctrl</kbd><kbd>tab</kbd></b> to switch to a tab via a menu (Windows only) ![mru-menu](../img/ctrl-tab-mru.png) This option provides the closest experience to Firefox. It lets you quickly press and release <b><kbd>ctrl</kbd><kbd>tab</kbd></b> to switch to the previous tab, while also showing a menu of recent tabs if you hold down <kbd>ctrl</kbd>. 1. [Install QuicKey](https://chrome.google.com/webstore/detail/quickey-%E2%80%93-the-quick-tab-s/ldlghkoiihaelfnggonhjnfiabmaficg). 2. Download and install [AutoHotkey](https://www.autohotkey.com/download/ahk-install.exe), a Windows utility for remapping keys. 3. Press <b><kbd>Win</kbd><kbd>R</kbd></b> to open the *Run* dialog. (Or click the Start menu, type "run", and pick the first result.) 4. Type `shell:startup` into the dialog and press <kbd>enter</kbd> to open your PC's startup folder. 6. Download [`quickey-ctrl-tab.ahk`](quickey-ctrl-tab.ahk), an AutoHotkey script that sets up the keyboard shortcuts for *QuicKey*. 7. Drag the `quickey-ctrl-tab.ahk` file to your startup folder and then double-click the file. Now switch between a few different tabs in Chrome using the mouse (since *QuicKey* was just installed, it won't have any recent tab history). Then press and release <b><kbd>ctrl</kbd><kbd>tab</kbd></b> to switch to the previous tab. If you press <b><kbd>ctrl</kbd><kbd>tab</kbd></b> and keep holding <kbd>ctrl</kbd>, a menu of recent tabs will open. Press <kbd>tab</kbd> to move the selection down in the list, <b><kbd>shift</kbd><kbd>tab</kbd></b> to move up. When the desired tab is selected, release <kbd>ctrl</kbd> to switch to it. The other default shortcuts continue to work, so you can still press <b><kbd>alt</kbd><kbd>Q</kbd></b> to open *QuicKey* and search for a tab by name or URL instead of picking a recent one. <script> function copyCode() { var copyFrom = document.createElement("textarea"), body = document.body, result; copyFrom.textContent = document.getElementsByClassName("highlight")[1].textContent; body.appendChild(copyFrom); copyFrom.select(); result = document.execCommand("copy"); body.removeChild(copyFrom); if (!result) { alert("The browser blocked the copy action for some reason."); } } </script>
Shell
UTF-8
439
2.5625
3
[]
no_license
if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then echo "Merge happend and starting deployment" docker build -t="scriptnull/mm-filter:$BRANCH.$BUILD_NUMBER" . docker push scriptnull/mm-filter:$BRANCH.$BUILD_NUMBER ssh ubuntu@34.209.45.202 echo "hello world" ssh ubuntu@34.209.45.202 docker rm -f mm-filter-app || true ssh ubuntu@34.209.45.202 docker run --name mm-filter-app -d -p 80:3000 scriptnull/mm-filter:$BRANCH.$BUILD_NUMBER fi
Java
UTF-8
2,373
2.40625
2
[]
no_license
package baseclass; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.opera.OperaDriver; import org.testng.annotations.AfterTest; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; import baseclass.BaseClass; import pageclasses.CruisesPage; import pageclasses.DeckPage; import pageclasses.LandingPage; import pageclasses.NairobiSearchResultsPage; import utils.ExtentReportManager; public class Browser { public WebDriver driver; public ExtentReports report = ExtentReportManager.getReportInstance(); public ExtentTest logger; public LandingPage landingpage; public NairobiSearchResultsPage nairobi_Search_Results_Page; public CruisesPage cruises_page; public DeckPage deck_page; public void invokeBrowser(String browserName) { try { if(browserName.equalsIgnoreCase("chrome")) { String driverPath = System.getProperty("user.dir") + "\\Drivers\\chromedriver.exe"; System.setProperty("webdriver.chrome.driver", driverPath); driver = new ChromeDriver(); logger.log(Status.PASS,"Chrome Browser Successfully Launched"); BaseClass.BaseClass(driver,logger); } else if(browserName.equalsIgnoreCase("edge")) { String driverPath = System.getProperty("user.dir") + "\\Drivers\\msedgedriver.exe"; System.setProperty("webdriver.edge.driver", driverPath); driver = new EdgeDriver(); logger.log(Status.PASS,"Edge Browser Successfully Launched"); } else if(browserName.equalsIgnoreCase("firefox")) { String driverPath = System.getProperty("user.dir") + "\\Drivers\\geckodriver.exe"; System.setProperty("webdriver.gecko.driver", driverPath); driver = new FirefoxDriver(); logger.log(Status.PASS,"Fiefox Browser Successfully Launched"); } else { System.out.println("Invalid choice of browser"); } } catch(Exception e) { logger.log(Status.FAIL,e.getMessage()); } } @AfterTest public void flushReports() { report.flush(); } //Close the Driver public void tearDown() { driver.close(); } //Quit the Driver @AfterTest public void closeBrowser() { driver.quit(); } }
C#
UTF-8
2,810
2.5625
3
[ "MIT" ]
permissive
using TicTacToe.IO; using UniRx; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; namespace TicTacToe { /// <inheritdoc /> /// <summary> /// Main menu of the game /// </summary> public class MainMenu : MonoBehaviour { /// <summary> /// New game button /// </summary> [SerializeField] private Button newGameButton; /// <summary> /// Continue button /// </summary> [SerializeField] private Button continueButton; /// <summary> /// History button /// </summary> [SerializeField] private Button historyButton; /// <summary> /// Options button /// </summary> [SerializeField] private Button optionsButton; private void Start() { //play main menu music MusicManager.Instance.PlayMainMenuMusic(); newGameButton.OnClickAsObservable().Subscribe(_ => NewGame()); continueButton.OnClickAsObservable().Subscribe(_ => ContinueGame()); historyButton.OnClickAsObservable().Subscribe(_ => History()); optionsButton.OnClickAsObservable().Subscribe(_ => Options()); //disable continue button if no snapshot if (!DataHelper.FileExists("snapshot")) continueButton.interactable = false; //disable history button if no history if (!DataHelper.FileExists("history")) historyButton.interactable = false; } /// <summary> /// Go to new game /// </summary> private static void NewGame() { BetweenSceneData.Mode = BetweenSceneData.GameMode.NewGame; SceneManager.LoadSceneAsync("Scenes/TicTacToe"); } /// <summary> /// Go to continue game /// </summary> private static void ContinueGame() { BetweenSceneData.Mode = BetweenSceneData.GameMode.ContinueGame; BetweenSceneData.SnapShot = DataHelper.GetJsonContent<GameSnapshot>("snapshot"); SceneManager.LoadSceneAsync("Scenes/TicTacToe"); } /// <summary> /// Go to history /// </summary> private static void History() { SceneManager.LoadSceneAsync("Scenes/History"); } /// <summary> /// Go to options /// </summary> private static void Options() { SceneManager.LoadSceneAsync("Scenes/Options"); } /// <summary> /// Go back to main menu /// </summary> public static void GoBackToMainMenu() { SceneManager.LoadSceneAsync("Scenes/MainMenu"); } } }
PHP
UTF-8
1,651
2.5625
3
[ "MIT" ]
permissive
<?php namespace Codingbeard\Devtools\Message; class GenerateMessageProcessorMessage { /** * @devtoolsOverwritable * * @var string */ protected $namespace; /** * @devtoolsOverwritable * * @var string */ protected $processorName; /** * @devtoolsOverwritable * * @var array */ protected $properties; /** * @devtoolsOverwritable * * @return string */ public function getNamespace() { return $this->namespace; } /** * @devtoolsOverwritable * * @param string $namespace * * @return GenerateMessageProcessorMessage */ public function setNamespace($namespace) { $this->namespace = $namespace; return $this; } /** * @devtoolsOverwritable * * @return string */ public function getProcessorName() { return $this->processorName; } /** * @devtoolsOverwritable * * @param string $processorName * * @return GenerateMessageProcessorMessage */ public function setProcessorName($processorName) { $this->processorName = $processorName; return $this; } /** * @devtoolsOverwritable * * @return array */ public function getProperties() { return $this->properties; } /** * @devtoolsOverwritable * * @param array $properties * * @return GenerateMessageProcessorMessage */ public function setProperties($properties) { $this->properties = $properties; return $this; } /** * @devtoolsOverwritable */ public function preSerialize() { } /** * @devtoolsOverwritable */ public function postUnserialize() { } }
C#
UTF-8
5,846
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; namespace DataAccess { public class EmpleadosData : ConnectionToSql { private SqlDataReader LeerFilas; //ATRIBUTOS private int idempleado; private string codigo; private string nombre; private string apellido; private string cedula; private string telefono; private string direccion; public int Idempleado { get => idempleado; set => idempleado = value; } public string Codigo { get => codigo; set => codigo = value; } public string Nombre { get => nombre; set => nombre = value; } public string Apellido { get => apellido; set => apellido = value; } public string Cedula { get => cedula; set => cedula = value; } public string Telefono { get => telefono; set => telefono = value; } public string Direccion { get => direccion; set => direccion = value; } public DataTable Listarempleado() { DataTable Tabla = new DataTable(); using (var connection = GetConnection()) { connection.Open(); using (var command = new SqlCommand()) { command.Connection = connection; command.CommandText = "listarEmpleado"; command.CommandType = CommandType.StoredProcedure; LeerFilas = command.ExecuteReader(); Tabla.Load(LeerFilas); LeerFilas.Close(); } connection.Close(); return Tabla; } } public void InsertarEmpleado() { using (var connection = GetConnection()) { connection.Open(); using (var command = new SqlCommand()) { command.Connection = connection; command.CommandText = "Insertar_Empleado"; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@codigo", codigo); command.Parameters.AddWithValue("@nombre", nombre); command.Parameters.AddWithValue("@apellido", apellido); command.Parameters.AddWithValue("@cedula", cedula); command.Parameters.AddWithValue("@telefono", telefono); command.Parameters.AddWithValue("@direccion", direccion); command.ExecuteNonQuery(); command.Parameters.Clear(); } connection.Close(); } } public void EditarEmpleado() { using (var connection = GetConnection()) { connection.Open(); using (var command = new SqlCommand()) { command.Connection = connection; command.CommandText = "Editar_Empleado"; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@idempleado", idempleado); command.Parameters.AddWithValue("@codigo", codigo); command.Parameters.AddWithValue("@nombre", nombre); command.Parameters.AddWithValue("@apellido", apellido); command.Parameters.AddWithValue("@cedula", cedula); command.Parameters.AddWithValue("@telefono", telefono); command.Parameters.AddWithValue("@direccion", direccion); command.ExecuteNonQuery(); command.Parameters.Clear(); } connection.Close(); } } public void EliminarEmpleado() { using (var connection = GetConnection()) { connection.Open(); using (var command = new SqlCommand()) { command.Connection = connection; command.CommandText = "Eliminar_empleado"; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@idempleado", idempleado); command.ExecuteNonQuery(); command.Parameters.Clear(); } connection.Close(); } } public int obtener_idEmpleado() { int aux = 0; using (var connection = GetConnection()) { connection.Open(); using (var command = new SqlCommand()) { command.Connection = connection; command.CommandText = "select * from tbl_empleado where idempleado = (select MAX(idempleado) from tbl_empleado);"; command.CommandType = CommandType.Text; SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { aux = reader.GetInt32(0); } return aux; } else { return 0; } } } } } }
C++
UTF-8
7,455
2.875
3
[]
no_license
#include <QOsg/PropertyUtils.h> #include <iomanip> #include <osg/io_utils> using namespace osgDB; // same as std::to_string but allows us to set precision for decimal numbers template <typename T> std::string to_string_with_precision(const T a_value, const int n = 6) { std::ostringstream out; out << std::fixed << std::setprecision(n) << a_value; return out.str(); } template <typename T> std::string property_to_string(osgDB::ClassInterface* ci, osg::Object* obj, std::string propname) { T value; ci->getProperty<T>(obj, propname, value); int precision = DECIMAL_PLACES return to_string_with_precision<T>(value, precision); } template <typename T> T string_to_type(const std::string aString) { T value; std::istringstream in(aString); in >> value; return value; } template <typename T> void string_to_property(osgDB::ClassInterface* ci, osg::Object* obj, std::string propname, std::string aValueString) { T value = string_to_type<T>(aValueString); ci->setProperty<T>(obj, propname, value); } // // returns the number of elements for a type (int=1, vec2=2, vec4=4 etc) // int getNumElementsForType(osgDB::BaseSerializer::Type aType) { switch(aType) { case osgDB::BaseSerializer::RW_STRING: case osgDB::BaseSerializer::RW_INT: case osgDB::BaseSerializer::RW_UINT: case osgDB::BaseSerializer::RW_FLOAT: case osgDB::BaseSerializer::RW_DOUBLE: return 1; case osgDB::BaseSerializer::RW_VEC2F: case osgDB::BaseSerializer::RW_VEC2D: return 2; case osgDB::BaseSerializer::RW_VEC3F: case osgDB::BaseSerializer::RW_VEC3D: return 3; case osgDB::BaseSerializer::RW_VEC4F: case osgDB::BaseSerializer::RW_VEC4D: return 4; case osgDB::BaseSerializer::RW_MATRIXF: case osgDB::BaseSerializer::RW_MATRIXD: return 16; default: break; } return 1; } // // convert property value to an std string, if value has multiple elements they are seperated by a , // bool getPropertyAsString(osg::Object* anObject, const std::string& aPropertyName, std::string& aValueString) { osgDB::ClassInterface ci; osgDB::BaseSerializer::Type type; if(!ci.getPropertyType(anObject, aPropertyName, type)) return false; switch(type) { case osgDB::BaseSerializer::RW_STRING: aValueString = property_to_string<std::string>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_INT: aValueString = property_to_string<int>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_UINT: aValueString = property_to_string<unsigned int>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_FLOAT: aValueString = property_to_string<float>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_DOUBLE: aValueString = property_to_string<double>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_VEC2F: aValueString = property_to_string<osg::Vec2f>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_VEC2D: aValueString = property_to_string<osg::Vec2d>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_VEC3F: aValueString = property_to_string<osg::Vec3f>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_VEC3D: aValueString = property_to_string<osg::Vec3d>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_VEC4F: aValueString = property_to_string<osg::Vec4f>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_VEC4D: aValueString = property_to_string<osg::Vec4d>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_MATRIXF: aValueString = property_to_string<osg::Matrixf>(&ci, anObject, aPropertyName); break; case osgDB::BaseSerializer::RW_MATRIXD: aValueString = property_to_string<osg::Matrixd>(&ci, anObject, aPropertyName); break; default: break; } return true; } // // set the property from a string, multi elements should be seperated by , // bool setPropertyFromString(osg::Object* anObject, const std::string& aPropertyName, const std::string& aValueString) { osgDB::ClassInterface ci; osgDB::BaseSerializer::Type type; if(!ci.getPropertyType(anObject, aPropertyName, type)) return false; osgDB::StringList elements; switch(type) { case osgDB::BaseSerializer::RW_STRING: string_to_property<std::string>(&ci, anObject, aPropertyName, aValueString); break; case osgDB::BaseSerializer::RW_INT: string_to_property<int>(&ci, anObject, aPropertyName, aValueString); break; case osgDB::BaseSerializer::RW_UINT: string_to_property<unsigned int>(&ci, anObject, aPropertyName, aValueString); break; case osgDB::BaseSerializer::RW_FLOAT: string_to_property<float>(&ci, anObject, aPropertyName, aValueString); break; case osgDB::BaseSerializer::RW_DOUBLE: string_to_property<double>(&ci, anObject, aPropertyName, aValueString); break; case osgDB::BaseSerializer::RW_VEC2F: string_to_property<osg::Vec2f>(&ci, anObject, aPropertyName, aValueString); break; case osgDB::BaseSerializer::RW_VEC2D: string_to_property<osg::Vec2d>(&ci, anObject, aPropertyName, aValueString); break; case osgDB::BaseSerializer::RW_VEC3F: string_to_property<osg::Vec3f>(&ci, anObject, aPropertyName, aValueString); break; case osgDB::BaseSerializer::RW_VEC3D: string_to_property<osg::Vec3d>(&ci, anObject, aPropertyName, aValueString); break; case osgDB::BaseSerializer::RW_MATRIXF: //string_to_property<osg::Matrix>(&ci, anObject, aPropertyName, aValueString); break; case osgDB::BaseSerializer::RW_MATRIXD: //string_to_property<osg::Matrixd>(&ci, anObject, aPropertyName, aValueString); break; default: break; } return true; } // // // bool getPropertyAsStringVector(osg::Object* anObject, const std::string& aPropertyName, std::vector<std::string>& aStringVector) { std::string vstring; getPropertyAsString(anObject, aPropertyName, vstring); osgDB::split(vstring, aStringVector, ' '); return true; } bool setPropertyFromStringVector(osg::Object* anObject, const std::string& aPropertyName, const std::vector<std::string>& aStringVector) { std::string concat = ""; for(unsigned int i=0; i<aStringVector.size(); i++) { concat += aStringVector[i] + " "; } concat = concat.substr(0, concat.size() - 1); setPropertyFromString(anObject, aPropertyName, concat); return true; }
C++
UTF-8
947
3.765625
4
[]
no_license
/********************************************************************** Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 **********************************************************************/ void flatten(TreeNode *root) { TreeNode *head = NULL, *tail = NULL, *cur; std::stack<TreeNode *> nodeStack; if (NULL == root) return ; nodeStack.push(root); while (!nodeStack.empty()) { cur = nodeStack.top(); nodeStack.pop(); if (cur->right) nodeStack.push(cur->right); if (cur->left) nodeStack.push(cur->left); if (NULL == head) { head = cur; tail = cur; } else { tail->right = cur; tail = cur; } cur->left = NULL; } tail->right = NULL; }
C++
WINDOWS-1250
25,473
3
3
[]
no_license
#include <iostream> #include <vector> #include <fstream> #include "Piece.h" using namespace std; //Turn Number int turn_number = 0; //The Board int Board[8][8] = { 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0 }; PieceBasic* Find_piece(char letter, int number, vector <PieceBasic*> vector ) { for (size_t i = 0; i < vector.size(); i++) { if ((*vector[i]).get_letter() == letter && (*vector[i]).get_number() == number) { return vector[i]; } } return NULL; } vector <PieceBasic*> White_pieces; vector <PieceBasic*> Black_pieces; void PrintTheBoard() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 3; j++){ for (int x = 0; x < 8; x++){ if ((i + x) % 2 == 0 && j != 1) cout << "* * *"; else if ((i + x) % 2 == 1 && j != 1) cout << " "; else if ((i + x) % 2 == 0 && j == 1) { cout << "* "; switch (Board[i][x]) { case 0: { cout << "*"; break; } case 1: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "p"; } else cout << "P"; break; } case 2: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "n"; } else cout << "N"; break; } case 3: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "b"; } else cout << "B"; break; } case 4: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "r"; } else cout << "R"; break; } case 5: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "q"; } else cout << "Q"; break; } case 6: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "k"; } else cout << "K"; break; } } cout << " *"; } else if ((i + x) % 2 == 1 && j == 1) { cout << " "; switch (Board[i][x]) { case 0: {cout << " "; break; } case 1: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "p"; } else cout << "P"; break; } case 2: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "n"; } else cout << "N"; break; } case 3: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "b"; } else cout << "B"; break; } case 4: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "r"; } else cout << "R"; break; } case 5: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "q"; } else cout << "Q"; break; } case 6: { if (Find_piece(x+'a', 8-i,White_pieces)!=NULL) { cout << "k"; } else cout << "K"; break; } } cout << " "; } } if (j == 1) { cout << " " << 8 - i; } cout << endl; } } cout << endl; for (char i = 'a'; i <= 'h'; i++){ cout << " " << i << " "; } cout << endl << endl; } void rocade(King* king, Rook* rook) { if ((*rook).get_letter() == 'a') { Board[8 - ((*rook).get_number())][(*rook).get_letter() - 'a'] = 0; (*rook).set_place((*king).get_letter()+1, (*king).get_number()); Board[8 - (*king).get_number()][(*king).get_letter() + 1 - 'a'] = 4; (*rook).set_first_turn(); (*king).set_first_turn(); } if ((*rook).get_letter() == 'h') { Board[8 - ((*rook).get_number())][(*rook).get_letter() - 'a'] = 0; (*rook).set_place((*king).get_letter() - 1, (*king).get_number()); Board[8 - (*king).get_number()][(*king).get_letter() - 1 - 'a'] = 4; (*rook).set_first_turn(); (*king).set_first_turn(); } } bool check_check(King* king,vector<PieceBasic*> vector) { for (size_t i = 0; i < vector.size(); i++){ char old_letter = (*vector[i]).get_letter(); int old_number = (*vector[i]).get_number(); (*vector[i]).move((*king).get_letter(),(*king).get_number(),Board); if ((*vector[i]).get_letter() != old_letter || (*vector[i]).get_number() != old_number) { Board[8 - (*vector[i]).get_number()][(*vector[i]).get_letter() - 'a'] = 6; Board[8 - (old_number)][old_letter - 'a'] = (*vector[i]).symbol(); (*vector[i]).set_place(old_letter, old_number); return true; } } return false; } bool check_mate(King* king, vector <PieceBasic*> vector_our, vector <PieceBasic*> vector_enemy) { char old_letter; int old_number; PieceBasic* piece; for (size_t i = 0; i < vector_our.size(); i++) { old_letter = (*vector_our[i]).get_letter(); old_number = (*vector_our[i]).get_number(); for (int j = 1; j <= 8; j++) { for (char x = 'a'; x <= 'h'; x++) { if (Board[8-j][x-'a'] == 0) { (*vector_our[i]).move(x, j, Board); if (!check_check(king, vector_enemy)) { Board[8 - old_number][old_letter - 'a'] = (*vector_our[i]).symbol(); (*vector_our[i]).set_place(old_letter, old_number); Board[8 - j][x - 'a'] = 0; return false; } Board[8 - old_number][old_letter - 'a'] = (*vector_our[i]).symbol(); (*vector_our[i]).set_place(old_letter, old_number); Board[8 - j][x - 'a'] = 0; } else if (Find_piece(x, j, vector_enemy) != NULL) { piece = (Find_piece(x, j, vector_enemy)); (*vector_our[i]).move(x, j, Board); if (!check_check(king, vector_enemy)) { Board[8 - old_number][old_letter - 'a'] = (*vector_our[i]).symbol(); (*vector_our[i]).set_place(old_letter, old_number); vector_enemy.push_back(piece); Board[8 - j][x - 'a'] = (*piece).symbol(); return false; } Board[8 - old_number][old_letter - 'a'] = (*vector_our[i]).symbol(); (*vector_our[i]).set_place(old_letter, old_number); vector_enemy.push_back(piece); Board[8 - j][x - 'a'] = (*piece).symbol(); } } } } PrintTheBoard(); return true; } bool Game() { bool checkmate = 0; char letter, new_letter; int number, new_number; bool correct_move = 0; Pawn a2('a', 2, Board), //white pieces on the board b2('b', 2, Board), c2('c', 2, Board), d2('d', 2, Board), e2('e', 2, Board), f2('f', 2, Board), g2('g', 2, Board), h2('h', 2, Board), a7('a', 7, Board), //black pieces on the board b7('b', 7, Board), c7('c', 7, Board), d7('d', 7, Board), e7('e', 7, Board), f7('f', 7, Board), g7('g', 7, Board), h7('h', 7, Board); Knight Nb1('b', 1, Board), Ng1('g', 1, Board), Nb8('b', 8, Board), Ng8('g', 8, Board); Bishop Bc1('c', 1, Board), Bf1('f', 1, Board), Bc8('c', 8, Board), Bf8('f', 8, Board); Rook Ra1('a', 1, Board), Rh1('h', 1, Board), Ra8('a', 8, Board), Rh8('h', 8, Board); Queen Qd1('d', 1, Board), Qd8('d', 8, Board); King Ke1('e', 1, Board), Ke8('e', 8, Board); White_pieces.push_back(&a2); White_pieces.push_back(&b2); White_pieces.push_back(&c2); White_pieces.push_back(&d2); White_pieces.push_back(&e2); White_pieces.push_back(&f2); White_pieces.push_back(&h2); White_pieces.push_back(&g2); White_pieces.push_back(&Nb1); White_pieces.push_back(&Ng1); White_pieces.push_back(&Bc1); White_pieces.push_back(&Bf1); White_pieces.push_back(&Ra1); White_pieces.push_back(&Rh1); White_pieces.push_back(&Qd1); White_pieces.push_back(&Ke1); Black_pieces.push_back(&a7); Black_pieces.push_back(&b7); Black_pieces.push_back(&c7); Black_pieces.push_back(&d7); Black_pieces.push_back(&e7); Black_pieces.push_back(&f7); Black_pieces.push_back(&h7); Black_pieces.push_back(&g7); Black_pieces.push_back(&Nb8); Black_pieces.push_back(&Ng8); Black_pieces.push_back(&Bc8); Black_pieces.push_back(&Bf8); Black_pieces.push_back(&Ra8); Black_pieces.push_back(&Rh8); Black_pieces.push_back(&Qd8); Black_pieces.push_back(&Ke8); for (size_t i = 0; i < Black_pieces.size(); i++){ (*Black_pieces[i]).set_color(1); } PrintTheBoard(); //Start the game while (checkmate == 0) { //check for mate and check if (check_check(&Ke1, Black_pieces)) { if (check_mate(&Ke1, White_pieces, Black_pieces)) { cout << "Checkmate! Black win!" << endl; correct_move = 1; checkmate = 1; return 1; } else { cout << "Check!" << endl; correct_move = 0; cout << "White's turn. Which piece you want to move?" << endl; } } else { cout << "White's turn. Which piece you want to move?" << endl; correct_move = 0; } //white's turn starts while (correct_move == 0) { cin >> letter >> number; while (letter<'a' || letter>'h' || number < 1 || number>8) { cout << "Invalid command." << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin >> letter >> number; } PieceBasic* piece = Find_piece(letter, number, White_pieces); //there is no piece if (Board[8 - number][letter - 'a'] == 0) cout << "There is no piece there! Enter again." << endl; //there is a piece, but its not white else if (piece == NULL) cout << "The piece is black! Type carefully" << endl; //its our piece else { cout << (*piece).get_letter() << (*piece).get_number() << " goes to?" << endl;; cin >> new_letter >> new_number; if (new_letter<'a' || new_letter>'h' || new_number < 1 || new_number>8) { cout << "Invalid command. Which piece you want to move?" << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } //there is no piece on the square we want to go else if (Find_piece(new_letter, new_number, White_pieces) == NULL && Find_piece(new_letter, new_number, Black_pieces) == NULL) { (*piece).move(new_letter, new_number, Board); //if you moved and there is a check if ((*piece).get_letter() == new_letter && (*piece).get_number() == new_number && check_check(&Ke1, Black_pieces)) { cout << "You are in check, invalid command!" << endl; Board[8 - (*piece).get_number()][(*piece).get_letter() - 'a'] = 0; (*piece).set_place(letter, number); Board[8 - (number)][letter - 'a'] = (*piece).symbol(); } //if you moved and there is no check else if ((*piece).get_letter() == new_letter && (*piece).get_number() == new_number && !check_check(&Ke1, Black_pieces)) { bool flag = true; /*if (piece == &Ke1 && Ke1.get_flag1()) { rocade(&Ke1, &Ra1); } else if (piece == &Ke1 && Ke1.get_flag2()) { rocade(&Ke1, &Rh1); }*/ if (piece == &Ke1 && Ke1.get_flag1() && Ra1.get_first_turn() && Ra1.get_number() == Ke1.get_number()) { for (int i = 1; i < 4 && flag==true; i++){ King *temp_K = new King (i + 'a', 1, Board); if (check_check(temp_K, Black_pieces)) { Board[7][i] = 0; flag = false; } delete temp_K; } if (flag == true) { rocade(&Ke1, &Ra1); } else { Board[7][2] = 0; Board[7][4] = 6; Ke1.set_place('e', 1); Ke1.set_false_first_turn(); } } else if (piece == &Ke1 && Ke1.get_flag2() && Rh1.get_first_turn() && Rh1.get_number() == Ke1.get_number()) { for (int i = 5; i < 7 && flag == true; i++) { King *temp_K = new King(i + 'a', 1, Board); if (check_check(temp_K, Black_pieces)) { Board[7][i] = 0; flag = false; } delete temp_K; } if (flag == true) { rocade(&Ke1, &Rh1); } else { Board[7][6] = 0; Board[7][4] = 6; Ke1.set_place('e', 1); Ke1.set_false_first_turn(); } } //Pawn promotion else if ((*piece).symbol() == 1 && new_number == 8) { char new_piece_symbol; cout << (*piece).get_letter() << (*piece).get_number() << " will turn into?"<< endl; cin >> new_piece_symbol; while (new_piece_symbol != 'n' && new_piece_symbol != 'b' && new_piece_symbol != 'r' && new_piece_symbol != 'q') { cout << "Invalid command. Please type one of the following: n/b/r/q" << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin >> new_piece_symbol; } for (size_t i=0; i < White_pieces.size(); i++) { if(White_pieces[i]==piece){ switch (new_piece_symbol) { case 'n': { White_pieces.erase(White_pieces.begin()+i); Knight *ptr = new Knight((*piece).get_letter(), (*piece).get_number(), Board); White_pieces.push_back(ptr); break; } case 'b': { White_pieces.erase(White_pieces.begin() + i); Bishop *ptr = new Bishop((*piece).get_letter(), (*piece).get_number(), Board); White_pieces.push_back(ptr); break; } case 'r': { White_pieces.erase(White_pieces.begin() + i); Rook *ptr = new Rook((*piece).get_letter(), (*piece).get_number(), Board); White_pieces.push_back(ptr); break; } case 'q': { White_pieces.erase(White_pieces.begin() + i); Queen *ptr = new Queen((*piece).get_letter(), (*piece).get_number(), Board); White_pieces.push_back(ptr); break; } } } } } if (flag) { correct_move = 1; system("CLS"); PrintTheBoard(); } } //if you didn't move else cout << "Not a valid command, try again!" << endl; } //if there is a black piece else if (Find_piece(new_letter, new_number, Black_pieces) != NULL) { (*piece).move(new_letter, new_number, Board); //you moved and there is no check if ((*piece).get_letter() == new_letter && (*piece).get_number() == new_number && !check_check(&Ke1, Black_pieces)) { //Pawn promotion if ((*piece).symbol() == 1 && new_number == 8) { char new_piece_symbol; cout << (*piece).get_letter() << (*piece).get_number() << " will turn into?" << endl; cin >> new_piece_symbol; while (new_piece_symbol != 'n' && new_piece_symbol != 'b' && new_piece_symbol != 'r' && new_piece_symbol != 'q') { cout << "Invalid command. Please type one of the following: n/b/r/q" << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin >> new_piece_symbol; } for (size_t i = 0; i < White_pieces.size(); i++) { if (White_pieces[i] == piece) { switch (new_piece_symbol) { case 'n': { White_pieces.erase(White_pieces.begin() + i); Knight *ptr = new Knight((*piece).get_letter(), (*piece).get_number(), Board); White_pieces.push_back(ptr); break; } case 'b': { White_pieces.erase(White_pieces.begin() + i); Bishop *ptr = new Bishop((*piece).get_letter(), (*piece).get_number(), Board); White_pieces.push_back(ptr); break; } case 'r': { White_pieces.erase(White_pieces.begin() + i); Rook *ptr = new Rook((*piece).get_letter(), (*piece).get_number(), Board); White_pieces.push_back(ptr); break; } case 'q': { White_pieces.erase(White_pieces.begin() + i); Queen *ptr = new Queen((*piece).get_letter(), (*piece).get_number(), Board); White_pieces.push_back(ptr); break; } } } } } correct_move = 1; system("CLS"); PrintTheBoard(); for (size_t i = 0; i < Black_pieces.size(); i++) { if (Find_piece(new_letter, new_number, Black_pieces) == Black_pieces[i]) Black_pieces.erase(Black_pieces.begin() + i); } } //you moved and there is a check else if ((*piece).get_letter() == new_letter && (*piece).get_number() == new_number && check_check(&Ke1, Black_pieces)) { cout << "You are in check, invalid command!" << endl; Board[8 - (*piece).get_number()][(*piece).get_letter() - 'a'] = (*Find_piece(new_letter, new_number, Black_pieces)).symbol(); (*piece).set_place(letter, number); Board[8 - (number)][letter - 'a'] = (*piece).symbol(); } //if you didn't move else cout << "Not a valid command, try again!" << endl; } else cout << "Not a valid command" << endl; } } //check for mate and check if (check_check(&Ke8, White_pieces)) { if (check_mate(&Ke8, Black_pieces, White_pieces)) { cout << "Checkmate! White win!" << endl; correct_move = 1; checkmate = 1; return 0; } else { cout << "Check!" << endl; correct_move = 0; cout << "Black's turn. Which piece you want to move?" << endl; } } else if (checkmate != 1) { cout << "Black's turn. Which piece you want to move?" << endl; correct_move = 0; } //Black's turn while (correct_move == 0) { cin >> letter >> number; while (letter<'a' || letter>'h' || number < 1 || number>8) { cout << "Invalid command." << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin >> letter >> number; } PieceBasic* piece = Find_piece(letter, number, Black_pieces); if (Board[8 - number][letter - 'a'] == 0) cout << "There is no piece there! Enter again." << endl; else if (piece == NULL) cout << "The piece is white! Type carefully" << endl; else { cout << (*piece).get_letter() << (*piece).get_number() << " goes to?" << endl;; cin >> new_letter >> new_number; if (new_letter<'a' || new_letter>'h' || new_number < 1 || new_number>8) { cout << "Invalid command. Which piece you want to move?" << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } else if (Find_piece(new_letter, new_number, White_pieces) == NULL && Find_piece(new_letter, new_number, Black_pieces) == NULL) { (*piece).move(new_letter, new_number, Board); //you moved and there is check if ((*piece).get_letter() == new_letter && (*piece).get_number() == new_number && check_check(&Ke8, White_pieces)) { cout << "You are in check, invalid command!" << endl; Board[8 - (*piece).get_number()][(*piece).get_letter() - 'a'] = 0; (*piece).set_place(letter, number); Board[8 - (number)][letter - 'a'] = (*piece).symbol(); } //you moved and there is no check else if ((*piece).get_letter() == new_letter && (*piece).get_number() == new_number && !check_check(&Ke8, White_pieces)) { bool flag = true; /*if (piece == &Ke8 && Ke8.get_flag1()) { rocade(&Ke8, &Ra8); } else if (piece == &Ke8 && Ke8.get_flag2()) { rocade(&Ke8, &Rh8); }*/ if (piece == &Ke8 && Ke8.get_flag1() && Ra8.get_first_turn() && Ra8.get_number() == Ke8.get_number()) { for (int i = 1; i < 4 && flag == true; i++) { King *temp_K = new King(i + 'a', 8, Board); if (check_check(temp_K, White_pieces)) { Board[0][i] = 0; flag = false; } delete temp_K; } if (flag == true) { rocade(&Ke8, &Ra8); } else { Board[0][2] = 0; Board[0][4] = 6; Ke8.set_place('e', 8); Ke8.set_false_first_turn(); } } else if (piece == &Ke8 && Ke8.get_flag2() && Rh8.get_first_turn() && Rh8.get_number() == Ke8.get_number()) { for (int i = 5; i < 7 && flag == true; i++) { King *temp_K = new King(i + 'a', 8, Board); if (check_check(temp_K, White_pieces)) { Board[0][i] = 0; flag = false; } delete temp_K; } if (flag == true) { rocade(&Ke8, &Rh8); } else { Board[0][6] = 0; Board[0][4] = 6; Ke8.set_place('e', 8); Ke8.set_false_first_turn(); } } else if ((*piece).symbol() == 1 && new_number == 1) { char new_piece_symbol; cout << (*piece).get_letter() << (*piece).get_number() << " will turn into?" << endl; cin >> new_piece_symbol; while (new_piece_symbol != 'N' && new_piece_symbol != 'B' && new_piece_symbol != 'R' && new_piece_symbol != 'Q') { cout << "Invalid command. Please type one of the following: N/B/R/Q" << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin >> new_piece_symbol; } for (size_t i=0; i < Black_pieces.size(); i++) { if (Black_pieces[i] == piece) { switch (new_piece_symbol) { case 'N': { Black_pieces.erase(Black_pieces.begin() + i); Knight *ptr = new Knight((*piece).get_letter(), (*piece).get_number(), Board); Black_pieces.push_back(ptr); (*ptr).set_color(1); break; } case 'B': { Black_pieces.erase(Black_pieces.begin() + i); Bishop *ptr = new Bishop((*piece).get_letter(), (*piece).get_number(), Board); Black_pieces.push_back(ptr); (*ptr).set_color(1); break; } case 'R': { Black_pieces.erase(Black_pieces.begin() + i); Rook *ptr = new Rook((*piece).get_letter(), (*piece).get_number(), Board); Black_pieces.push_back(ptr); (*ptr).set_color(1); break; } case 'Q': { Black_pieces.erase(Black_pieces.begin() + i); Queen *ptr = new Queen((*piece).get_letter(), (*piece).get_number(), Board); Black_pieces.push_back(ptr); (*ptr).set_color(1); break; } } } } } if (flag) { correct_move = 1; system("CLS"); PrintTheBoard(); } } //you didn't move else cout << "Not a valid command, try again!" << endl; } else if (Find_piece(new_letter, new_number, White_pieces) != NULL) { (*piece).move(new_letter, new_number, Board); if ((*piece).get_letter() == new_letter && (*piece).get_number() == new_number && !check_check(&Ke8, White_pieces)) { if ((*piece).symbol() == 1 && new_number == 1) { char new_piece_symbol; cout << (*piece).get_letter() << (*piece).get_number() << " will turn into?" << endl; cin >> new_piece_symbol; while (new_piece_symbol != 'N' && new_piece_symbol != 'B' && new_piece_symbol != 'R' && new_piece_symbol != 'Q') { cout << "Invalid command. Please type one of the following: N/B/R/Q" << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin >> new_piece_symbol; } for (size_t i=0; i < Black_pieces.size(); i++) { if (Black_pieces[i] == piece) { switch (new_piece_symbol) { case 'N': { Black_pieces.erase(Black_pieces.begin() + i); Knight *ptr = new Knight((*piece).get_letter(), (*piece).get_number(), Board); Black_pieces.push_back(ptr); (*ptr).set_color(1); break; } case 'B': { Black_pieces.erase(Black_pieces.begin() + i); Bishop *ptr = new Bishop((*piece).get_letter(), (*piece).get_number(), Board); Black_pieces.push_back(ptr); (*ptr).set_color(1); break; } case 'R': { Black_pieces.erase(Black_pieces.begin() + i); Rook *ptr = new Rook((*piece).get_letter(), (*piece).get_number(), Board); Black_pieces.push_back(ptr); (*ptr).set_color(1); break; } case 'Q': { Black_pieces.erase(Black_pieces.begin() + i); Queen *ptr = new Queen((*piece).get_letter(), (*piece).get_number(), Board); Black_pieces.push_back(ptr); (*ptr).set_color(1); break; } } } } } correct_move = 1; system("CLS"); PrintTheBoard(); for (size_t i = 0; i < White_pieces.size(); i++) { if (Find_piece(new_letter, new_number, White_pieces) == White_pieces[i]) White_pieces.erase(White_pieces.begin() + i); } } else if ((*piece).get_letter() == new_letter && (*piece).get_number() == new_number && !check_check(&Ke1, Black_pieces)) { cout << "You are in check, invalid command!" << endl; Board[8 - (*piece).get_number()][(*piece).get_letter() - 'a'] = (*Find_piece(new_letter, new_number, White_pieces)).symbol(); (*piece).set_place(letter, number); Board[8 - (number)][letter - 'a'] = (*piece).symbol(); } else cout << "Not a valid command, try again!" << endl; } else cout << "Not a valid command" << endl; } } } } int main() { char name2[11]; char name1[11]; string file_name="C:/Users/User/source/repos/Chess_45603/Files/"; cout << "Hi there! " << endl << "Enter your fabulous name:" << endl; cin.getline(name2, 10); cout << name2 << " will be facing: "; cin.getline(name1, 10); cout << name2 << " is white" << endl << name1 << " is black" << endl; file_name += name2; file_name +="-"; file_name += name1; file_name += ".txt"; ofstream chess_input(file_name.c_str(), ios::app); if (!chess_input) { cerr << "File couldnt be opened!\n"; } chess_input << name2 << " - " << name1; if (Game()) { chess_input << endl << "0 - 1"; } else chess_input << endl << "1 - 0"; chess_input << endl; cout << "works"; system("PAUSE"); return 0; }
Markdown
UTF-8
18,574
2.8125
3
[ "Apache-2.0", "CC-BY-3.0" ]
permissive
--- title: 'Images' authors: - estelleweyl description: An overview of images in HTML. date: 2023-02-14 tags: - html --- Decorative images, such as background gradients on buttons or background images on sections of content or the full page, are presentational and should be applied with CSS. When an image adds context to a document, it is content and should be embedded with HTML. The main method for including images is the [`<img>`](https://developer.mozilla.org/docs/Web/HTML/Element/img) tag with the `src` attribute referencing an image resource and the `alt` attribute describing the image. ```html <img src="images/eve.png" alt="Eve"> ``` Both the [`srcset`](/learn/images/descriptive/) attribute on `<img>` and the [`<picture>`](/learn/images/prescriptive/) element provide a way to include multiple image sources with associated media queries, each with a fallback image source, enabling serving the most appropriate image file based on the device's resolution, browser capabilities, and the viewport size. The `srcset` attribute enables providing multiple image versions based on resolution and, along with the `sizes` attribute, browser viewport size. ```html <img src="images/eve.png" alt="Eve" srcset="images/eve.png 400w, images/eve-xl.jpg 800w" sizes="(max-width: 800px) 400px, 800px" /> ``` This can also be done with the [`<picture>`](https://developer.mozilla.org/docs/Web/HTML/Element/picture) element, along with [`<source>`](https://developer.mozilla.org/docs/Web/HTML/Element/picture) children, which takes an [`<img>`](https://developer.mozilla.org/docs/Web/HTML/Element/img) as a default source. ```html <picture> <source src="images/eve.png" media="(max-width: 800px)" /> <source src="images/eve-xl.jpg" /> <img src="images/eve.png" alt="Eve" /> </picture> ``` In addition to these built-in HTML [responsive image methods](/learn/design/responsive-images/), HTML also enables image render performance to be improved via attributes. The `<img>` tag, and therefore graphical submit buttons [`<input type="image">`](https://developer.mozilla.org/docs/Web/HTML/Element/input/image), can include `height` and `width` attributes to set the image's aspect ratio to reduce content layout shift. The `lazy` attribute enables [lazy loading](/learn/images/performance-issues/#deferring-image-requests). HTML also supports the inclusion of SVG images using the [`<svg>`](https://www.w3.org/Graphics/SVG/) directly, though SVG images with the `.svg` extension (or as a [data-uri](https://css-tricks.com/data-uris/)) can be embedded using the `<img>` element. {% Aside %} The [`<figure>`](https://developer.mozilla.org/docs/Web/HTML/Element/figure) element, along with its nested [`<figcaption>`](https://developer.mozilla.org/docs/Web/HTML/Element/figcaption) element, enables an image with an associated description to be included. A [figure](https://developer.mozilla.org/docs/Web/Accessibility/ARIA/Roles/figure_role) is not limited to just including images. It is a semantic way of referencing images, code snippets, example text, or other content, along with a caption for that content, as a single unit. When including a `<figcaption>`, make sure it is the first or last child nested within the `<figure>`. {% endAside %} At a minimum, each foreground image should include `src` and `alt` attributes. The `src` file is the path and filename of the embedded image. The `src` attribute is used to provide the URL for the image. The browser then fetches the asset and renders it to the page. This attribute is required by `<img>`; without it, there is nothing to render. The `alt` attribute provides alternative text for the image, providing a description of the image for those unable to see the screen (think search engines and assistive technologies, and even Alexa, Siri, and Google Assistant), and may be displayed by the browser if the image doesn't load. In addition to users with slow networks or capped bandwidth, the `alt` text is incredibly useful in HTML emails, as many users block images in their email applications. ```html <img src="path/filename" alt="descriptive text" /> ``` If the image is of SVG file type, also include [`role="img"`](https://developer.mozilla.org/docs/Web/Accessibility/ARIA/Roles/Img_role), which is necessary due to [VoiceOver](https://bugs.webkit.org/show_bug.cgi?id=216364) [bugs](https://bugs.webkit.org/show_bug.cgi?id=240656). ```html <img src="switch.svg" alt="light switch" role="img" /> ``` {% Aside %} These examples include a slash at the end, also misnamed as a self-closing tag; this is a feature of XML, including SVG and XHTML, but not HTML. For more information about this see the note in the [forms](/learn/html/forms/) module. {% endAside %} ## Writing effective `alt` image descriptions Alt attributes aim to be short and concise, providing all the relevant information that the image conveys while omitting information that is redundant to other content in the document or otherwise isn't useful. In writing the text, the tone should reflect the tone of the site. To write effective alternative text, imagine that you are reading the entire page to a person who can't see it. By using the [semantic](/learn/html/semantic-html/#the-role-attribute) `<img>` element, screen reader users and bots are informed that the element is an image. It is redundant to include "This is an image/screenshot/photo of" in the `alt`. The user doesn't need to know there's an image, but they do need to know what information the image conveys. Normally, you would not say, "This is a grainy image of a dog wearing a red hat." Rather, you would relay what the image is conveying in relation to the context of the rest of the document; and what you convey will change depending on the context and the content of the surrounding text. For example, the photo of a dog will be described in different ways, depending on the context. If Fluffy is an avatar next to a review for Yuckymeat dog food, `alt="Fluffy"` suffices. If the photo is part of Fluffy's adoption page on an animal shelter website, the target audience is the prospective dog parent. The text should describe the information conveyed in the image that is relevant to an adopter and which is not duplicated in the surrounding text. A longer description, such as `alt="Fluffy, a tri-color terrier with very short hair, with a tennis ball in her mouth"` is appropriate. The text of an adoption page generally includes the species, breed, age, and gender of the adoptable pet, so this does not need to be repeated in the alt text. But the dog's written biography probably doesn't include hair length, colors, or toy preferences. Note that we didn't describe the image: the prospective dog owner does not need to know if the dog is indoors or outdoors, or that it has a red collar and a blue leash. When using images for iconography, as the `alt` attribute provides the accessible name, convey the meaning of the icon, not a description of the image. For example, the magnifying glass icon's alt attribute is `search`. The icon which looks like a house has `home` as the alt text. The 5-inch floppy disc icon's description is `save`. If there are two icons of Fluffy used to indicate best practices and anti-patterns, the smiling dog in a green beret could have `alt="good"` set, while the snarling dog in a red beret might read `alt="bad"`. That said, only use standard iconography, and if you use non-standard icons such as the good and bad Fluffy, include a legend and ensure that the icons are not the only ways of deciphering the meaning of your UI elements, If the image is a screenshot or a graph, write what is learned from the image rather than describing the appearance. While an image can definitely be worth a thousand words, the description should concisely convey everything that is learned. Omit information the user already knows from the context and is otherwise informed about in the content. For example, if you're on a tutorial page about changing browser settings and the page is about clicking icons in the browser chrome, the URL of the page in the screen capture isn't important. Limit the `alt` to the topic at hand: how to change settings. The `alt` might be "The settings icon is in the navigation bar below the search field." Don't include "screenshot" or "machinelearningworkshop" as the user doesn't need to know it's a screenshot and doesn't need to know where the techwriter was surfing when they wrote the instructions. The description of the image is based on the context of why the image was included in the first place. If the screen capture shows how to find the browser version number by going to `chrome://version/`, include the URL in the content of the page as instructions, and provide an empty string as the alt attribute as the image provides no information that is not in the surrounding text. If the image provides no additional information or is purely decorative, the attribute should still be there, just as an empty string. ```html <img src="svg/magazine.svg" alt="" role="none" /> ``` MachineLearningWorkshop.com has seven foreground images, therefore seven images with alt attributes: an easter egg light switch, a manual icon, two biographical photos of Hal and Eve, and three avatars of a blender, a vacuum cleaner, and a toaster. The foreground image that looks like a magazine is the only one that is purely decorative. The page also has two background images; these are also decorative and, as they are added with CSS, are inaccessible. The magazine, being purely decorative, has an empty `alt` attribute, and a [`role` of `none`](https://developer.mozilla.org/docs/Web/Accessibility/ARIA/Roles/presentation_role) as the image is a purely presentational SVG. If meaningful, SVG images should include the `role="img"`. ```html <img src="svg/magazine.svg" alt="" role="none" /> ``` There are three reviews at the bottom of the page, each with an image of the poster. Usually, the `alt` text is the name of the person pictured. ```html <img src="images/blender.svg" alt="Blendan Smooth" role="img" /> ``` Instead, because this is a joke page, you should convey what may not be apparent to low-vision users so they don't miss the humor; we use the original machine function as the `alt` instead of using the character's name: ```html <img src="images/blender.svg" alt="blender" role="img" /> ``` The photos of the instructors aren't just avatars: they are biographical images and therefore get a more detailed description. If this were a real site, you would provide the bare minimum description of what the teacher looks like so a prospective student might recognize them when entering the classroom. ```html <img src="svg/hal.svg" role="img" alt="Hal 9000; a camera lens containing a red dot that sometimes changes to yellow." /> ``` Because this is a joke site, provide the information that is relevant in the joke context instead: ```html <img src="svg/hal.svg" role="img" alt="Hal 9000, the sentient AI computer from 2001: a Space Odyssey depicted as a camera lens with a red dot that changes to yellow when hovered." /> ``` If you were reading the page to a friend over the phone, they wouldn't care what the red dot looks like. In this case, the history of the movie reference matters. When writing descriptive text, consider what information the image conveys that is important and relevant to the user and include that. Remember, the content of the `alt` attribute for an image differs based on the context. All information conveyed in an image that a sighted user can access and is relevant to the context is what needs to be conveyed; nothing more. Keep it short, precise, and useful. The `src` and `alt` attributes are minimum requirements for embedded images. There are a few other attributes we need to discuss. ## Responsive images There are a myriad of viewport sizes. There are also different screen resolutions. You don't want to waste a mobile user's bandwidth by serving them an image wide enough for a large screen monitor, but you might want to serve higher resolution images for tiny devices that have four times the normal screen resolution. There are a few ways to serve different images based on the viewport size and the screen resolution. ### `<img> srcset` attribute The [`srcset`](/learn/design/responsive-images/#responsive-images-with-srcset) attribute enables suggesting multiple image files, with the browser selecting which image to request based on multiple media queries including viewport size and screen resolution. There can be a single `srcset` attribute per `<img>` element, but that `srcset` can link to multiple images. The `srcset` attribute accepts a list of comma-separated values, each containing the URL of the asset followed by a space followed by descriptors for that image option. If a width descriptor is used, you must also include the `sizes` attribute with a media query or source size for each `srcset` option other than the last one. The Learn sections covering [responsive images with `srcset`](/learn/design/responsive-images/#responsive-images-with-srcset) and [descriptive syntaxes](/learn/images/descriptive/) are worth reading. The `srcset` image will take precedence over the `src` image if there is a match. ### `<picture>` and `<source>` Another method for providing multiple resources and allowing the browser to render the most appropriate asset is with the [`<picture>`](https://developer.mozilla.org/docs/Web/HTML/Element/picture) element. The `<picture>` element is a container element for multiple image options listed in an unlimited number of [`<source>`](https://developer.mozilla.org/docs/Web/HTML/Element/source) elements and a single required [`<img>`](https://developer.mozilla.org/docs/Web/HTML/Element/img) element. The [`<source>`](https://developer.mozilla.org/docs/Web/HTML/Element/source) attributes include `srcset`, `sizes`, `media`, `width`, and `height`. The `srcset` attribute is common to `img`, `source`, and `link`, but is generally implemented slightly differently on source as media queries can be listed in the `<srcset>`'s media attribute instead. `<source>` also supports image formats defined in the `type` attribute. The browser will consider each child `<source>` element and choose the best match among them. If no matches are found, the URL of the `<img>` element's [`src`](https://developer.mozilla.org/docs/Web/HTML/Element/img#attr-src) attribute is selected. The accessible name comes from the `alt` attribute of the nested `<img>`. The Learn sections covering the [`<picture>`](/learn/design/picture-element/) element and [prescriptive syntaxes](/learn/images/prescriptive/) are also worth a read. ## Additional performance features ### Lazy loading The [`loading` attribute](/learn/design/responsive-images/#loading-hints/) tells the JS-enabled browser how to load the image. The default `eager` value means the image is loaded immediately as the HTML is parsed, even if the image is outside the visible viewport. By setting [`loading="lazy"`](/lazy-loading/) the image loading is deferred until it is likely to come into the viewport. “Likely" is defined by the browser based on the distance the image is from the viewport. This is updated as the user scrolls. Lazy loading helps save bandwidth and CPU, improving performance for most users. If JavaScript is disabled, for security reasons, all images will default to `eager`. ```html <img src="switch.svg" alt="light switch" loading="lazy" /> ``` ### Aspect ratio Browsers start rendering HTML when it is received, making requests for assets when encountered. This means the browser is already rendering the HTML when it encounters the `<img>` tag and makes the request. And images can take a while to load. By default, browsers don't reserve space for images other than the size required to render `alt` text. The `<img>` element has always supported unitless `height` and `width` attributes. These properties fell out of use in favor of CSS. CSS may define image dimensions, often setting a single dimension such as `max-width: 100%;` to ensure the aspect ratio is preserved. As CSS is usually included in the `<head>`, it is parsed before any `<img>` is encountered. But without explicitly listing the `height` or aspect ratio, the space reserved is the height (or width) of the `alt` text. With most developers only declaring a width, the receipt and rendering of images leads to [cumulative layout shift](/cls/) which harms [web vitals](/learn-core-web-vitals/). To resolve this issue, browsers support image aspect ratios. Including `height` and `width` attributes on the `<img>` acts as [sizing hints](/learn/design/responsive-images/#sizing-hints), informing the browser of the aspect ratio, enabling the right amount of space to be reserved for eventual image rendering. By including a height and width value on an image, the browser knows the aspect ratio of that image. When the browser encounters a single dimension, such as our 50% example, it saves space for the image adhering to the CSS dimension and with the other dimension maintaining the width-to-height aspect ratio. ```html <img src="switch.svg" alt="light switch" role="img" width="70" height="112" /> ``` Your images will still be responsive if the CSS was set up correctly to make them responsive. Yes, the included unitless `height` and `width` values will be overridden with CSS. The purpose of including these attributes is to reserve the space at the right aspect ratio, improving performance by reducing layout shift. The page will still take approximately the same amount of time to load, but the UI won't jump when the image is painted to the screen. ## Other image features The `<img>` element also supports the `crossorigin`, `decoding`, `referrerpolicy`, and, in Blink-based browsers, `fetchpriority` attributes. Rarely used, if the image is part of a server-side map, include the `ismap` boolean attribute and nest the `<img>` in a link for users without pointing devices. The `ismap` attribute isn't necessary, or even supported, on the `<input type="image" name="imageSubmitName">` as the `x` and `y` coordinates of the click location are sent during form submission, appending the values to the input name, if any. For example, something like `&imageSubmitName.x=169&imageSubmitName.y=66` will be submitted with the form when the user clicks the image, submitting it. If the image doesn't have a `name` attribute, the x and y are sent: `&x=169&y=66`. {% Assessment 'images' %}
Python
UTF-8
6,406
3.3125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Jun 15 14:59:16 2018 @author: abhinav.jhanwar """ # Artificial Neural Network # Installing Theano # pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git # Installing Tensorflow # pip install tensorflow # Installing Keras # pip install --upgrade keras # Installing keras saving module # conda install h5py # ctrl+I to check function details ################################ # Part 1 - Data Preprocessing ################################ # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import os # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) onehotencoder = OneHotEncoder(categorical_features = [1]) X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) ########################################## # Part 2 - Now let's make the ANN! ########################################## # Importing the Keras libraries and packages from keras.models import Sequential, load_model from keras.layers import Dense # Initialising the ANN classifier = Sequential() # weights: defines the weightage of each node/feature according to their impact on target value # learning rate: defines the value by which weights of nodes will be changed while back propagation # units = output_dimension: usually average of input features and output variable # Adding the input layer and the first hidden layer # units = 6 as input = 11, output is binary = 1, average = 11+1/2=6 # kernel_initializer: defines how weightage will be given to nodes, with 'uniform' we make sure it is least possible # activation: defines the output function = [relu', 'tanh'] # kernel_initializer: defines the initial weights of nodes = ['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform'] classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11)) # Adding the second hidden layer classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) # Adding the output layer # sigmoid activation function is used to enable probablity and when units is 1 then it works as logistic regression # if output is more than 1 class then activation will go as 'softmax' which is nothing but sigmoid function just to handle multi classes # softmax also converts the final output into 1 i.e. it take cares that probability of all categories sum up to 1 # activation = [regression: 'linear', binary classification: 'sigmoid', multiclass: 'softmax'] classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) # Compiling the ANN # Some of the most popular optimization algorithms used are # the Stochastic Gradient Descent (SGD), ADAM and RMSprop. # Depending on whichever algorithm you choose, # you'll need to tune certain parameters, such as learning rate or momentum. # The choice for a loss function depends on the task that you have at hand: # for example, for a regression problem, you'll usually use the Mean Squared Error (MSE). # As you see in this example, # you used binary_crossentropy for the binary classification problem of determining whether a person will leave bank or not. # Lastly, with mulit-class classification, you'll make use of categorical_crossentropy. # optimizer = ['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam'] # loss = [regression: 'mean_squared_error', binary: 'binary_crossentropy', multi: 'categorical_crossentropy'] # crossentropy(works only for classification) is prefered over rms as it provides logarithmic values hence more accurate value to determine any error in prediction classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # saving the keras model with all the weights if not os.path.exists("SavedModels/classifier"): os.makedirs("SavedModels/classifier") classifier.save("SavedModels/classifier/model.h5") # load model classifier = load_model("SavedModels/classifier/model.h5") # Fitting the ANN to the Training set & get history of training & validation in each epoch # batch_size: defines the number of records after which weights will be modified or backpropagation takes place # epochs: defines number of times back propagation will take place history = classifier.fit(X_train, y_train, batch_size = 100, epochs = 100, validation_split=0.2).history ######################################################## # Part 3 - Making predictions and evaluating the model ######################################################## # Predicting the Test set results y_pred = classifier.predict(X_test) # y_pred has all the probabilities but we need True or False # hence converting accordingly y_pred = (y_pred > 0.5) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) loss, accuracy = classifier.evaluate(X_test, y_test,verbose=1) ####################################################### # Part 4 - Testing with new Data ####################################################### newData = pd.DataFrame(data={ 'CreditScore': 600, 'Geography': 'France', 'Gender': 'Male', 'Age': 40, 'Tenure': 3, 'Balance': 60000, 'NumOfProducts': 2, 'HasCrCard': 1, 'IsActiveMember': 1, 'EstimatedSalary': 50000}, index=[0]) newData['Geography'] = labelencoder_X_1.transform(newData['Geography']) newData['Gender'] = labelencoder_X_2.transform(newData['Gender']) newData = onehotencoder.transform(newData).toarray() newData = newData[:, 1:] newData = sc.transform(newData) prediction = classifier.predict(newData) prediction = (prediction>0.5)
C#
UTF-8
967
2.546875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TogglePlateform : MonoBehaviour { // temps de disparation de la plateforme public float time = 5; //temps avant le prochain switch private float remaining_time = 0; //booléen de switch private bool isHidden = false; // plateform cible public GameObject plateform; // Start is called before the first frame update void Start() { // initialisation this.remaining_time = this.time; } // Update is called once per frame void Update() { if (this.remaining_time <= 0) { //si le temps est écoulé, je relance un timer, j'inverse le boolean et modifie le setActive de la plateforme this.remaining_time = this.time; this.isHidden = !this.isHidden; plateform.SetActive(this.isHidden); } this.remaining_time -= Time.deltaTime; } }
Markdown
UTF-8
1,074
2.90625
3
[ "MIT" ]
permissive
# gulp-styledocdown [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] > [styledocdown](https://github.com/etylsarin/styledocdown) plugin for [gulp](https://github.com/wearefractal/gulp) ## Usage First, install `gulp-styledocdown` as a development dependency: ```shell npm install --save-dev gulp-styledocdown ``` Then, add it to your `gulpfile.js`: ```javascript var styledocdown = require("gulp-styledocdown"); gulp.src("./src/*.ext") .pipe(styledocdown({ root: "root/folder/for/relatively/linked/files/" })) .pipe(gulp.dest("./dist")); ``` ## API ### styledocdown(options) #### options.root Type: `String` Default: File directory Set the location where the linked files are hosted. ## License [MIT License](http://en.wikipedia.org/wiki/MIT_License) [npm-url]: https://npmjs.org/package/gulp-styledocdown [npm-image]: https://badge.fury.io/js/gulp-styledocdown.png [travis-url]: http://travis-ci.org/etylsarin/gulp-styledocdown [travis-image]: https://secure.travis-ci.org/etylsarin/gulp-styledocdown.png?branch=master
C++
UTF-8
544
2.828125
3
[]
no_license
#include "BitMap.h" #include <iostream> using namespace BitMap_Lib; using namespace std; int main(int argc, char* argv[]) { string path = "image.bmp"; try { auto map = new BitMap(path); auto x = map->width() / 2; auto y = map->height() / 2; auto channel = 0; auto pixle = map->getData(x, y, channel); auto color = map->getColor(x, y); cout << hex; cout << pixle << endl; cout << color << endl; delete map; } catch (const BitMapIOException e) { cout << e.what() << endl; } }
Markdown
UTF-8
919
2.515625
3
[]
no_license
--- title: 云间 date: 2019-01-18 15:48:14 tags: - 古筝 - 自冾 categories: - 创作 --- ![](/images/yunjian.jpg) ### 终于是完成了一首 《云·间》这首作品在挣扎中诞生了。 最近每天播放量都在500+,持续了3天了,不知道是哪家忘记关了电脑。挺好,放着吧,让久违的虚荣心喷薄而出吧。 纪老师听了这首作品后,提到说可以投稿给上海民族乐团。这意味着得把它变成人能看得懂的谱,对我来说是个不小的挑战。音乐中的听说读写,读应该是我现在最短的板,这是个好机会。万一选上,可就光宗耀祖了。 想要离舒适区远一点,舒适区反而会追上来,我是越来越胆大,越来越不怕错了。 其他几首估计是不能在策划的时间里完成了,意料之中,意料之中。。。 不过改10遍,应该会强于写10首,就安慰自己吧。
Java
UTF-8
3,496
2.0625
2
[]
no_license
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.store.serialization.xml.internal; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.xpn.xwiki.doc.XWikiAttachment; /** * Tests for AttachmentMetadataSerializer * * @version $Id: 366c227d0f23a575c96dce540c3dec631c34a37c $ * @since 3.0M2 */ public class AttachmentMetadataSerializerTest { private static final String TEST_CONTENT = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<attachment serializer=\"attachment-meta/1.0\">\n" + " <filename>file1</filename>\n" + " <filesize>10</filesize>\n" + " <author>me</author>\n" + " <version>1.1</version>\n" + " <comment>something whitty</comment>\n" + " <date>1293045632168</date>\n" + "</attachment>"; private AttachmentMetadataSerializer serializer; @Before public void setUp() { this.serializer = new AttachmentMetadataSerializer(); } @Test public void testParse() throws Exception { final ByteArrayInputStream bais = new ByteArrayInputStream(TEST_CONTENT.getBytes("US-ASCII")); final XWikiAttachment attach = this.serializer.parse(bais); bais.close(); Assert.assertEquals("Attachment1 had wrong name", "file1", attach.getFilename()); Assert.assertEquals("Attachment1 had wrong author", "me", attach.getAuthor()); Assert.assertEquals("Attachment1 had wrong version", "1.1", attach.getVersion()); Assert.assertEquals("Attachment1 had wrong comment", attach.getComment(), "something whitty"); // We drop milliseconds for consistency with the database so last 3 digits are 0. Assert.assertEquals("Attachment1 had wrong date.", attach.getDate().getTime() + "", "1293045632000"); } @Test public void testParseSerialize() throws Exception { final ByteArrayInputStream bais = new ByteArrayInputStream(TEST_CONTENT.getBytes("US-ASCII")); final XWikiAttachment attach = this.serializer.parse(bais); bais.close(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(this.serializer.serialize(attach), baos); final String test = new String(baos.toByteArray(), "US-ASCII"); final String control = TEST_CONTENT.replaceAll("[0-9][0-9][0-9]</date>", "000</date>"); Assert.assertEquals("Parsing and serializing yields a different output.", control, test); } }
Java
UTF-8
2,555
2.53125
3
[]
no_license
import common.AbstractRequest; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; public class Network { private static Network network = new Network(); private SocketChannel channel; private ClientHandler clientHandler = new ClientHandler(); private static final String HOST = "localhost"; private static final int PORT = 8189; public static Network getInstance() { if (network == null) network = new Network(); return network; } public ClientHandler getClientHandler() { return clientHandler; } private Network() { new Thread(() -> { EventLoopGroup worker = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(worker) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) { channel = socketChannel; socketChannel.pipeline() .addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new ObjectEncoder(), clientHandler); } }); ChannelFuture future = bootstrap.connect(HOST, PORT).sync(); future.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { worker.shutdownGracefully(); } }).start(); } public boolean sendMessage(AbstractRequest request) { try { System.out.println("TRY"); channel.writeAndFlush(request); return true; } catch (Exception e) { e.printStackTrace(); } return false; } public void close() { channel.close(); } }
JavaScript
UTF-8
1,243
2.8125
3
[ "CC0-1.0", "MIT" ]
permissive
$( document ).ready(function() { var manualCheck=false; window.applicationCache.addEventListener('cached', handleCacheEvent, false); window.applicationCache.addEventListener('checking', handleCacheEvent, false); window.applicationCache.addEventListener('downloading', handleCacheEvent, false); window.applicationCache.addEventListener('error', handleCacheError, false); window.applicationCache.addEventListener('noupdate', handleCacheEvent, false); window.applicationCache.addEventListener('obsolete', handleCacheEvent, false); window.applicationCache.addEventListener('progress', handleCacheEvent, false); window.applicationCache.addEventListener('updateready', handleUpdate, false); function handleCacheError(e) { console.log('Error: Cache failed to update!'); }; function handleCacheEvent(e) { console.log ('handleCacheEvent: ' + e.type); if (e.type == 'noupdate') { checkCacheManually(); } } function checkCacheManually() { if (window.applicationCache && manualCheck==false) { console.log ('checkCacheManually: ' + window.applicationCache); manualCheck=true; window.applicationCache.update(); } } function handleUpdate() { console.log ('handleUpdate: reload'); window.location.reload(); } });
Python
UTF-8
909
2.703125
3
[]
no_license
from pyspark import SparkContext, SparkConf conf = SparkConf().setMaster("local[2]").setAppName("filter") sc = SparkContext(conf=conf) filter_data = {"emp_id": '609373628', "index": 2} # could be fetch from anywhere lookup = sc.broadcast(filter_data) lines = sc.textFile('poc.csv') def format_lines(l): lookup_map = lookup.value values = l.split(',') new_value = "" new_key = "" for index, value in enumerate(values): if index == lookup_map["index"]: new_key = value else: new_value = new_value + " " + value return new_key, new_value def filter_key(pair): k, v = pair lookup_map = lookup.value # print k , v if k == lookup_map["emp_id"]: return False else: return True out = lines.map(lambda l: format_lines(l)).filter(lambda pair: filter_key(pair)) print out.collect() out.saveAsTextFile('out')
Python
UTF-8
1,100
3.21875
3
[]
no_license
import time def coinChange(coins, amount): m = 2**31 - 1 def coinChangeHelper(index, amount, count): nonlocal m, coins if amount == 0: m = min(m, count) for j in range(index, len(coins), 1): if coins[j] <= amount < (m - count)*coins[j]: # most important line n = amount//coins[j] i = n while i > 0: if amount - i * coins[j] < (m - count - i)*coins[j]: # most important line coinChangeHelper(j+1, amount - i*coins[j], count + i) else: break i -= 1 coins.sort(reverse = True) coinChangeHelper(0, amount, 0) return m if m < 2**31 - 1 else -1 t0 = time.time() print(coinChange([243,291,335,209,177,345,114,91,313,331], 1000000000)) #print(coinChange([88,227,216,96,209,172,259], 6928)) #print(coinChange([5,306,188,467,494], 7047)) #print(coinChange([1, 2, 5], 11)) #print(coinChange([3, 10, 25], 51)) #print(coinChange([186, 419, 83, 408], 6249)) print(time.time() - t0)
JavaScript
UTF-8
964
3.484375
3
[]
no_license
var victims = [] var volunteers = [] var combine = [] var names = [] var names2 = [] var response = prompt("How many victims?") var vicinfo = function(name, phone, address){ name = prompt("What is the victims name?") phone = prompt("What is the victims phone?") address = prompt("What is the victims address?") victims.push([name, phone, address]) names.push(name) } for(var i = 0; i<response; i++){ vicinfo() } var response2 = prompt("How many volunteers?") var volinfo = function(name, phone, address){ name = prompt("What is the volunteer's name?") phone = prompt("What is the volunteer's phone?") address = prompt("What is the volunteer's address?") volunteers.push([name, phone, address]) names2.push(name) } for(var i = 0; i<response2; i++){ volinfo() } alert("Victims " + victims.length + " " + "Volunteers " + volunteers.length + " " + "Victim Names: " + names + " " + "Volunteer Names:" + names2 )
Python
UTF-8
3,506
2.921875
3
[]
no_license
import time import os import sys import RPi.GPIO as GPIO if sys.version_info[0] == 3: from _thread import * else: from thread import * class PI_ADC: def __init__(self, num_avgs, limit): self.num_avg = 0 #init to 0 if (num_avgs < 1): num_avgs = 1 self.max_num_avg = num_avgs #number of times to average self.avg_arr = [] self.avg = 0 self.limit = limit class PI_ADC_MONITOR: def __init__(self, num_channels=8, num_avgs=3, limit=100): self.initialized = False self.num_channels = num_channels self.adc = [] #insert class here (Somehow pass parameters? or default them?) #initialize the adc GPIO.setmode(GPIO.BCM) # SPI ports on the ADC to the Cobbler self.SPI_CLK = 11 self.SPI_MISO = 9 self.SPI_MOSI = 10 self.SPI_CS = 8 # set up the SPI interface pins GPIO.setup(self.SPI_MOSI, GPIO.OUT) GPIO.setup(self.SPI_MISO, GPIO.IN) GPIO.setup(self.SPI_CLK, GPIO.OUT) GPIO.setup(self.SPI_CS, GPIO.OUT) # initialize number of channels for i in range(self.num_channels): self.adc.append(PI_ADC(num_avgs, limit)) # average 3 times #start thread self.initialized = True #start_new_thread(self.monitor_thread,()) def read_adc(self, channel): #read from ADC at index if ((channel > 7) or (channel < 0)): return -1 GPIO.output(self.SPI_CS, True) GPIO.output(self.SPI_CLK, False) # start clock low GPIO.output(self.SPI_CS, False) # bring CS low commandout = channel commandout |= 0x18 # start bit + single-ended bit commandout <<= 3 # we only need to send 5 bits here for i in range(5): if (commandout & 0x80): GPIO.output(self.SPI_MOSI, True) else: GPIO.output(self.SPI_MOSI, False) commandout <<= 1 GPIO.output(self.SPI_CLK, True) GPIO.output(self.SPI_CLK, False) adcout = 0 # read in one empty bit, one null bit and 10 ADC bits for i in range(12): GPIO.output(self.SPI_CLK, True) GPIO.output(self.SPI_CLK, False) adcout <<= 1 if (GPIO.input(self.SPI_MISO)): adcout |= 0x1 GPIO.output(self.SPI_CS, True) adcout >>= 1 # first bit is 'null' so drop it return adcout def monitor_thread(self): #while True: for i in range(self.num_channels): value = self.read_adc(i) if (self.adc[i].num_avg < self.adc[i].max_num_avg):# initialize num avg to zero first (this is the number that have been read) self.adc[i].num_avg += 1 else: #shift every array elem down 1 and remove oldest #put in new elem self.adc[i].avg_arr.pop(0) # shifts all elements left self.adc[i].avg_arr.append(value) # appends new element self.adc[i].avg = sum(self.adc[i].avg_arr)/len(self.adc[i].avg_arr) def get_adc_avg(self, index): return self.adc[index].avg #should default to 0 def channel_triggered(self,index): return (self.adc[index].avg > self.adc[index].limit)
C#
UTF-8
2,822
2.6875
3
[ "MIT" ]
permissive
using System; using System.Xml; using System.Text; using System.Collections.Generic; namespace GenieLamp.Core.Metamodel { class AttributesCollection : MetaObjectNamedCollection<IAttribute, Attribute>, IAttributes { #region Constructors public AttributesCollection(Model model) : base(model) { } #endregion public Attribute GetByPersistentName(string name) { foreach (Attribute a in this) if (a.Persistence.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) return a; return null; } #region IAttributes implementation public bool Contains(IAttribute attribute) { IAttribute found = GetByName(attribute.Name); return found != null && found.Entity.FullName == attribute.Entity.FullName; } public string ToNamesString(string separator) { return ToNamesString(separator, String.Empty, String.Empty); } public string ToNamesString(string separator, string prefix, string suffix) { StringBuilder names = new StringBuilder(); int i = 1; foreach (Attribute a in this) { if (!String.IsNullOrEmpty(prefix)) names.Append(prefix); names.AppendFormat(a.Name); if (!String.IsNullOrEmpty(suffix)) names.Append(suffix); if (i++ < this.Count) names.Append(separator); } return names.ToString(); } public string ToArguments() { return ToNamesString(", "); } public string ToPersistentNamesString(string separator) { StringBuilder cols = new StringBuilder(); int i = 1; foreach (Attribute a in this) { cols.AppendFormat(a.Persistence.Name); if (i++ < this.Count) cols.Append(separator); } return cols.ToString(); } public int PersistentCount { get { int count = 0; foreach (Attribute a in this) { if (a.Persistence.Persisted) count++; } return count; } } public uint GetNamesHash(string prefix) { StringBuilder sb = new StringBuilder(); if (!String.IsNullOrWhiteSpace(prefix)) sb.AppendLine(prefix); foreach (Attribute a in this) { sb.AppendLine(a.Name); } return Utils.Cryptography.CalcCrc16(sb.ToString()); } #endregion } class Attributes<TOwner> : AttributesCollection, IAttributes where TOwner : MetaObject { private TOwner owner; public Attributes(TOwner owner) : base(owner.Model) { this.owner = owner; } public TOwner Owner { get { return owner; } } public void Update() { foreach (Attribute a in this) a.Update(); } public void Copy<TSource>(Attributes<TSource> source) where TSource : MetaObject { Clear(); foreach (Attribute a in source) { Add(a); } } } }
Java
ISO-8859-10
8,727
2.75
3
[]
no_license
/* NodePairTable.java */ package elvira; import java.util.Vector; import elvira.Relation; import elvira.FiniteStates; import elvira.potential.PotentialContinuousPT; /** * This class implements a pair of values * (<code>FiniteStates,Vector</code>), where the <code>Vector</code> contains * <code>Relations</code> where the <code>FiniteStates</code> variable * appears. It can be used in propagation algorithms to control * the relations in which a variable takes part, for instance, when the * variable is going to be deleted. * * @since 22/9/2000 */ public class NodePairTable { /** * A variable. */ protected Node variable; /** * Is a vector that contains all the relations where <code>variable</code> * appears. */ protected Vector relations; /** * Constructs an <code>NodePairTable</code>. * @param var a <code>Node</code> variable to put in this object. */ public NodePairTable(Node var) { variable = var; relations = new Vector(); } /** * Gets the variable in this pair. * @return the variable. */ public Node getVariable() { return variable; } /** * Computes the size of the potential resulting from the * combination of all the relations in the list, * considering fully expanded potentials and * <code>FiniteStates</code> variables. It takes into account only * finite-states variables to calculate the size. * @return the obtained size. */ public double totalSize() { Relation r; double s = 1.0; int i; NodeList nl = new NodeList(); for (i=0 ; i<relations.size() ; i++) { r = (Relation)relations.elementAt(i); nl.join(r.getVariables()); } for(i=0;i<nl.size();i++){ // Remove non finite-states nodes if(nl.elementAt(i).getTypeOfVariable()!=Node.FINITE_STATES){ nl.removeNode(nl.elementAt(i)); } } s = FiniteStates.getSize(nl); return s; } /** * Computes the size of the potential resulting from the * combination of all the relations in the list, * considering fully expanded potentials (in this case, ContinuousProbabilityTrees) and * <code>FiniteStates</code> variables. * @return the obtained size. */ public double continuousTotalSize() { Relation r; PotentialContinuousPT pot; double s = 1.0; int numSplits = 0; //This vble will contain the splits of the continuous variables int split; int numTerms = 1; int terms; double tamDiscrete; int i,j; NodeList varsInPot; //System.out.println("****Empiezo con totalSize****"); NodeList discreteNl = new NodeList(); NodeList nl = new NodeList(); //System.out.println("La variable que estamos mirando es: "); //variable.print(); //System.out.println("Hay "+relations.size()+" potenciales para esta variable"); for (i=0 ; i<relations.size() ; i++) { r = (Relation)relations.elementAt(i); pot = (PotentialContinuousPT)r.getValues(); //System.out.println("Primero este potencial:"); //pot.getTree().print(); //pot.setNumTerms(3); //pot.setNumSplits(2); split = pot.getNumSplits(); //System.out.println("splits es "+split); terms = pot.getNumTerms(); //System.out.println("terms es "+terms); //System.out.println("numTerms antes de multiplicar por terms "+numTerms); numTerms = numTerms * terms; //System.out.println("numTerms despues de multiplicar por terms "+numTerms); //numSplits += split; // Now I want to get splits^(number of cont var in pot). I will acumulate in s; varsInPot = new NodeList(); varsInPot = r.getVariables(); for(j=0 ; j<varsInPot.size() ; j++){ if(varsInPot.elementAt(j).getTypeOfVariable()== Node.CONTINUOUS){ //System.out.println("La variables es continua, luego hago s = s * split, con s= "+s+" y split= "+split); s = s*split; } } nl.join(r.getVariables()); } //System.out.println("Este es el nodelist de todas las vbles que estan en los potenciales"); //nl.print(); for(i=0;i<nl.size();i++){ if(nl.elementAt(i).getTypeOfVariable()== Node.FINITE_STATES){ //System.out.println("Inserto en las discretas la variable"); //(nl.elementAt(i)).print(); discreteNl.insertNode(nl.elementAt(i)); } //else{ // s *= numSplits; // System.out.println("La vble es cont, luego multiplico s por el numSplits y sale "+s); //} } if (discreteNl.size() > 0){ tamDiscrete = FiniteStates.getSize(discreteNl); //System.out.println("Este es el tamdiscrete que obtengo: "+tamDiscrete); //System.out.println("Hay alguna vble discreta."); s *= tamDiscrete; } //System.out.println("Esto es lo q vale numTerms: "+numTerms); s *= numTerms; //System.out.println("Y el tamao seria "+s); //System.out.println("****Acabo con totalSize****"); return s; } /** * Computes the number of links to add during the creation * of the potential resulting from the * combination of all the relations in the list, * considering fully expanded potentials and * <code>FiniteStates</code> variables. * @return the number of links calculated. */ public double numberOfLinksToAdd() { Relation r; int i, j, k, s; double newLinks = 0; boolean found; Node a, b; NodeList v, nl = new NodeList(); for (i=0 ; i<relations.size() ; i++) { r = (Relation)relations.elementAt(i); nl.join(r.getVariables()); } // as variable is contained in all the relations, // no link is added containing variable, so we can remove it nl.removeNode(variable); // now we are going to build s = nl.size(); for (i=0 ; i<(s-1) ; i++) { a = nl.elementAt(i); for (j=i+1 ; j<s ; j++) { b = nl.elementAt(j); // check that the link between the nodes in positions i and j exists found = false; for (k=0 ; k<relations.size() ; k++) { r = (Relation)relations.elementAt(k); v = r.getVariables(); if ( (v.getId(a)!=-1) && (v.getId(b)!=-1) ){ found = true; break; } } if (!found) newLinks++; } } return newLinks; } /** * Computes the number of links to add among the nodes of the explanation * set and the rest of nodes, when the considered node is deleted * during the triangulation. * @param expSet an explanation set. * @return the number of links calculated. */ public double numberOfLinksToAddBetweenExplanationAndRest(NodeList expSet) { Relation r; int i, j, k, s; double newLinks = 0; boolean found; Node a, b; NodeList v, nl = new NodeList(); for (i=0 ; i<relations.size() ; i++) { r = (Relation)relations.elementAt(i); nl.join(r.getVariables()); } // as variable is contained in all the relations, // no link is added containing variable, so we can remove it nl.removeNode(variable); // now we are going to build s = nl.size(); for (i=0 ; i<(s-1) ; i++) { a = nl.elementAt(i); for (j=i+1 ; j<s ; j++) { b = nl.elementAt(j); if (((expSet.getId(a)==-1) && (expSet.getId(b)!=-1)) || ((expSet.getId(a)!=-1) && (expSet.getId(b)==-1)) ) { // Check that the link between the nodes in positions i and j exists found = false; for (k=0 ; k<relations.size() ; k++) { r = (Relation)relations.elementAt(k); v = r.getVariables(); if ( (v.getId(a)!=-1) && (v.getId(b)!=-1) ) { found = true; break; } } if (!found) newLinks++; } } } return newLinks; } /** * Computes the number of links to add when the considered node is deleted * during the triangulation, but excluding the links among the nodes in * the explanation set. * @param expSet an explanation set. * @return the number calculated. */ public double numberOfLinksToAddExceptAmongExplanationNodes(NodeList expSet) { Relation r; int i, j, k, s; double newLinks = 0; boolean found; Node a, b; NodeList v, nl = new NodeList(); for (i=0 ; i<relations.size() ; i++) { r = (Relation)relations.elementAt(i); nl.join(r.getVariables()); } // as variable is contained in all the relations, // no link is add containing variable, so we can remove it nl.removeNode(variable); // now we are going to build s = nl.size(); for (i=0 ; i<(s-1) ; i++) { a = nl.elementAt(i); for (j=i+1 ; j<s ; j++) { b = nl.elementAt(j); if (!(expSet.getId(a)!=-1) && !(expSet.getId(b)!=-1) ) { // Check that the link between the nodes in positions i and j exists found = false; for (k=0 ; k<relations.size() ; k++) { r = (Relation)relations.elementAt(k); v = r.getVariables(); if ( (v.getId(a)!=-1) && (v.getId(b)!=-1) ) { found = true; break; } } if (!found) newLinks++; } } } return newLinks; } } // End of class.
Java
UTF-8
1,595
3.296875
3
[]
no_license
/** * Created by Administrator on 2017/1/11. */ public class HeapSort extends SortMethod{ public static void adjustHeap(int[] arr,int node,int size){ //叶节点无需调节 if(node*2+1<size){ int right=node*2+2; int left=node*2+1; if(right<size){ if(arr[right]>=arr[left]&&arr[right]>arr[node]){ swap(arr,right,node); adjustHeap(arr,right,size); }else if(arr[left]>arr[right]&&arr[left]>arr[node]){ swap(arr,left,node); adjustHeap(arr,left,size); } }else{ if(arr[left]>arr[node]){ swap(arr,left,node); adjustHeap(arr,left,size); } } } } public static void sort(int[] arr,int size){ //key:从第一个非叶子节点开始调节 if(size>2){ for(int i=size/2-1;i>=0;i--){ adjustHeap(arr,i,size); } //得到最大堆并交换最大值与队尾值 swap(arr,0,size-1); sort(arr,size-1); }else if(size==2){ if(arr[1]<arr[0]){ swap(arr,0,1); } } } public static void heapSort(int[] arr){ sort(arr,arr.length); } public static void main(String[] args) { int[] arr={6,2,1,8,3,9,4,54,5,567,55,12,34,654,23,45,66,7,6}; heapSort(arr); for(int i:arr){ System.out.println(i); } } }
Markdown
UTF-8
41,942
2.9375
3
[]
no_license
# 酒店预订系统软件详细设计描述文档 ## 文档修改历史 | 修改人员 | 日期 | 修改原因 | 版本号 | | :------: | --------- | ------------------------ | ------ | | 陈泔錞 | 2020.5.24 | 框架搭建 | v0.1 | | 陈泔錞 | 2020.6.20 | 初步完善业务逻辑层的分解 | v0.2 | | 陈泔錞 | 2020.6.30 | 完成详细设计文档 | v1.0 | | | | | | ## 目录 [TOC] ## 1. 引言 ### 1.1 编制目的 ​ 本报告详细完成对酒店预订系统的详细设计,达到指导后续软件构造的目的,同时实现和测试人员及用户的沟通。 ​ 本报告面向开发人员、测试人员及最终用户而编写,是了解系统的导航。 ### 1.2 词汇表 | 词汇名称 | 词汇含义 | 备 注 | | :--------: | :------: | :----------: | | Encryption | 加密 | | | | | | | | | | ### 1.3 参考资料 ## 2. 产品概述 ​ 参考酒店预订系统用例文档和酒店预订系统软件需求规格说明文档中对产品的概括描述。 ## 3. 体系结构设计概述 ​ 参考酒店预订系统软件体系结构文档中对体系结构设计的概述。 ## 4. 结构视角 ### 4.1 业务逻辑层的分解 ​ 业务逻辑层的开发包图参见软件体系结构文档。 #### 4.1.1 adminbl模块 1. 模块概述 adminbl模块承担的需求: i. 用户管理(客户、酒店工作人员) ​ \1. 查询用户信息 ​ \2. 查询,更改酒店工作人员信息。 ii. 添加酒店及其工作人员 ​ \1. 需要先添加工作人员,才能为其添加管理的酒店; ​ \2. 一个酒店只有一个工作人员账号 iii. 信用充值 ​ \1. 如果用户线下充值(系统不予考虑),营销人员可以为用户进行信用 增加 ​ \2. 增加的信用值为(充值额度*100) adminbl模块的职责及接口参见软件系统结构描述文档。 2. 整体结构 根据体系结构的设计,我们将系统分为了展示层、业务逻辑层、数据层。每一层之间为了增加灵活性,我们添加了接口。展示层和业务逻辑层之间,我们添加AdminService接口。业务逻辑层和数据层之间添加AdminMapper接口。由AdminController作为前后端的连接点。 ![](http://i.shuotu.vip/n=QQ图片20200630233820.png/p=unV6^qCU3k39W) adminbl模块各个类的职责: | 模块 | 职责 | | :-------------: | :------------------------------: | | AdminController | 负责管理员操作所需要的服务 | | AdminService | 负责管理员操作所需要的服务的实现 | | | | 3. 模块内部类的接口规范 AdminService的接口规范 | 接口名 | 语法 | ResponseVO addManager(UserForm userForm); | | ----------------------- | :----------- | ----------------------------------------- | | AdminService.addManager | **前置条件** | userFrom符合规范 | | | **后置条件** | 调用adminMapper.addManager方法 | | 接口名 | 语法 | List\<User\> getAllManagers(); | | --------------------------- | :----------- | ---------------------------------- | | AdminService.getAllManagers | **前置条件** | 无 | | | **后置条件** | 调用adminMapper.getAllManagers方法 | | 接口名 | 语法 | List<User\> getAllClients(); | | -------------------------- | :----------- | --------------------------------- | | AdminService.getAllClients | **前置条件** | 无 | | | **后置条件** | 调用adminMapper.getAllClients方法 | | 接口名 | 语法 | ResponseVO deleteUser(int userId); | | ----------------------- | :----------- | -------------------------------------- | | AdminService.deleteUser | **前置条件** | userId不为空 | | | **后置条件** | 调用adminMapper.deleteUser(userId)方法 | | 接口名 | 语法 | ResponseVO rechargeCredit(int rechargePoint,int userId); | | --------------------------- | :----------- | -------------------------------------------------------- | | AdminService.rechargeCredit | **前置条件** | 信息符合规范 | | | **后置条件** | 调用accountService.updateCredit方法 | AdminService需要的服务 | 服务名 | 服务 | | :------------------------: | ------------------------------------ | | AdminMapper.addManager | 在数据库建立一个新的酒店管理人员账号 | | AdminMapper.getAllManagers | 返回数据库里的所有酒店工作人员 | | AdminMapper.getAllClients | 返回数据库里的所有普通用户 | | AdminMapper.deleteUser | 删除用户 | 4. 业务逻辑层的设计原理 利用委托式控制风格,每个界面需要访问的业务逻辑由各自的控制器委托给不同的Service。 #### 4.1.2 couponbl模块 1. 模块概述 couponbl模块承担的需求: i. 制定酒店促销策略 ​ \1. 生日特惠折扣 ​ \2. 三间及以上预订特惠 ​ \3. 满减折扣 ​ \4. 限时折扣(在特定的期间住宿有折扣) ii. 调用所有可使用的优惠券 couponbl模块的职责及接口参见软件系统结构描述文档。 2. 整体结构 根据体系结构的设计,我们将系统分为了展示层、业务逻辑层、数据层。每一层之间为了增加灵活性,我们添加了接口。展示层和业务逻辑层之间,我们添加CouponService接口和CouponMatchStrategy接口。业务逻辑层和数据层之间添加CouponMapper接口。由CouponController作为前后端的连接点。 ![](http://i.shuotu.vip/n=QQ图片20200630233623.png/p=F_eU8UPmOkUsF) couponbl模块各个类的职责: | 模块 | 职责 | | :-----------------: | :----------------------------------: | | CouponController | 负责优惠券相关操作所需要的服务 | | CouponService | 负责优惠券相关操作所需要的服务的实现 | | CouponMatchStrategy | 负责各种类型的优惠券的匹配服务 | 3. 模块内部类的接口规范 CouponService的接口规范 | 接口名 | 语法 | List<Coupon\> getMatchOrderCoupon(OrderVO orderVO); | | --------------------------------- | :----------- | --------------------------------------------------- | | CouponService.getMatchOrderCoupon | **前置条件** | orderVO符合规范 | | | **后置条件** | 调用CouponMatchStrategy的isMatch方法 | | 接口名 | 语法 | List<Coupon\> getHotelAllCoupon(Integer hotelId); | | ------------------------------- | :----------- | ------------------------------------------------- | | CouponService.getHotelAllCoupon | **前置条件** | hotelId不为空 | | | **后置条件** | 调用couponMapper.selectByHotelId方法 | | 接口名 | 语法 | CouponVO addHotelTargetMoneyCoupon(HotelTargetMoneyCouponVO couponVO); | | --------------------------------------- | :----------- | ------------------------------------------------------------ | | CouponService.addHotelTargetMoneyCoupon | **前置条件** | couponVO符合规范 | | | **后置条件** | 调用couponMapper.insertCoupon方法 | | 接口名 | 语法 | CouponVO addHotelBirthdayCoupon(HotelBirthdayCouponVO couponVO); | | ------------------------------------ | :----------- | ------------------------------------------------------------ | | CouponService.addHotelBirthdayCoupon | **前置条件** | couponVO符合规范 | | | **后置条件** | 调用couponMapper.insertCoupon方法 | | 接口名 | 语法 | CouponVO addHotelMultipleRoomCoupon(HotelMultipleRoomCouponVO couponVO); | | ---------------------------------------- | :----------- | ------------------------------------------------------------ | | CouponService.addHotelMultipleRoomCoupon | **前置条件** | couponVO符合规范 | | | **后置条件** | 调用couponMapper.insertCoupon方法 | | 接口名 | 语法 | CouponVO addHotelTimeCoupon(HotelTimeCouponVO couponVO); | | -------------------------------- | :----------- | -------------------------------------------------------- | | CouponService.addHotelTimeCoupon | **前置条件** | couponVO符合规范 | | | **后置条件** | 调用couponMapper.insertCoupon方法 | ​ CouponService需要的服务 | 服务名 | 服务 | | :--------------------------: | ------------------------------ | | ManageMapper.selectByHotelId | 返回某一订单可用的优惠策略列表 | | ManageMapper.insertCoupon | 添加新的优惠券 | | | | ​ CouponMatchStrategy的接口规范 | 接口名 | 语法 | boolean isMatch(OrderVO orderVO, Coupon coupon); | | --------------------------- | :----------- | ------------------------------------------------ | | CouponMatchStrategy.isMatch | **前置条件** | orderVO 和 coupon 不为 null | | | **后置条件** | 无 | 4. 业务逻辑层的设计原理 利用委托式控制风格,每个界面需要访问的业务逻辑由各自的控制器委托给不同的Service。 #### 4.1.3 hotelbl模块 1. 模块概述 hotelbl模块承担的需求: i. 创建酒店 ii. 获得所需的酒店列表 iii. 添加房间 iv. 维护房间信息(数量) v. 维护酒店信息(姓名、地址、所属商圈、简介、设施服务、星级) vi. 删除酒店 vii. 添加评论 hotelbl模块的职责及接口参见软件系统结构描述文档。 2. 整体结构 根据体系结构的设计,我们将系统分为了展示层、业务逻辑层、数据层。每一层之间为了增加灵活性,我们添加了接口。展示层和业务逻辑层之间,我们添加HotelService接口、RoomService接口、RemarkService接口。业务逻辑层和数据层之间添加HotelMapper接口、RoomMapper接口、RemarkMapper接口。由HotelController作为前后端的连接点。 ![](http://i.shuotu.vip/n=QQ图片20200630233449.png/p=mo^7ZzaK[g19<) hotelbl模块各个类的职责: | 模块 | 职责 | | :-----------------: | :------------------------------------: | | HotelController | 负责酒店相关操作所需要的服务 | | HotelService | 负责酒店相关操作所需要的服务的实现 | | CouponMatchStrategy | 负责酒店房间相关操作所需要的服务的实现 | | RemarkService | 负责酒店评论相关操作所需要的服务的实现 | | | | 3. 模块内部类的接口规范 HotelService的接口规范 | 接口名 | 语法 | void addHotel(HotelVO hotelVO) throws ServiceException; | | --------------------- | :----------- | ------------------------------------------------------- | | HotelService.addHotel | **前置条件** | 输入的HotelVO符合规范 | | | **后置条件** | 调用hotelMapper.insertHotel方法 | | 接口名 | 语法 | void updateRoomInfo(Integer hotelId, String roomType,Integer rooms); | | --------------------------- | :----------- | ------------------------------------------------------------ | | HotelService.updateRoomInfo | **前置条件** | 更新的资料符合规范 | | | **后置条件** | 调用roomService.updateRoomInfo方法 | | 接口名 | 语法 | List\<HotelVO\> retrieveHotels(); | | --------------------------- | :----------- | ----------------------------------- | | HotelService.retrieveHotels | **前置条件** | 无 | | | **后置条件** | 调用hotelMapper的selectAllHotel方法 | | 接口名 | 语法 | HotelVO retrieveHotelDetails(Integer hotelId); | | --------------------------------- | :----------- | ---------------------------------------------- | | HotelService.retrieveHotelDetails | **前置条件** | 酒店id符合规范 | | | **后置条件** | 调用hotelMapper.selectById方法 | | 接口名 | 语法 | int getRoomCurNum(Integer hotelId,String roomType); | | -------------------------- | :----------- | --------------------------------------------------- | | HotelService.getRoomCurNum | **前置条件** | 输入的id符合规范 | | | **后置条件** | 调用roomService.getRoomCurNum方法 | | 接口名 | 语法 | List<HotelVO\> retrieveHotelsByManagerId(Integer userId); | | -------------------------------------- | :----------- | --------------------------------------------------------- | | HotelService.retrieveHotelsByManagerId | **前置条件** | 输入userId不为空 | | | **后置条件** | 调用hotelMapper.selectManagerHotel方法 | | 接口名 | 语法 | HotelRoom getRoomInfo(Integer roomId); | | ------------------------ | :----------- | -------------------------------------- | | HotelService.getRoomInfo | **前置条件** | 输入roomId不为空 | | | **后置条件** | 调用roomService.getRoomInfo方法 | | 接口名 | 语法 | ResponseVO deleteHotel(Integer hotelId); | | ------------------------ | :----------- | ------------------------------------------------------------ | | HotelService.deleteHotel | **前置条件** | 输入hotelId不为空 | | | **后置条件** | 调用roomService.deleteRoomsByHotelId和hotelMapper.deleteHotel方法 | | 接口名 | 语法 | ResponseVO updateHotelInfo(HotelInfoVO hotelInfoVO,Integer id); | | ---------------------------- | :----------- | ------------------------------------------------------------ | | HotelService.updateHotelInfo | **前置条件** | 输入信息不为空 | | | **后置条件** | 调用hotelMapper.updateHotelInfo方法 | | 接口名 | 语法 | ResponseVO updateHotelRate(Integer id, String rate); | | ---------------------------- | :----------- | ---------------------------------------------------- | | HotelService.updateHotelRate | **前置条件** | 输入信息不为空 | | | **后置条件** | 调用hotelMapper.updateHotelRate方法 | HotelService需要的服务 | 服务名 | 服务 | | :----------------------------: | --------------------------- | | HotelMapper.insertHotel | 在数据库插入一个hotel | | HotelMapper.selectAllHotel | 返回数据库所有的hotel | | HotelMapper.selectById | 根据id返回数据库对应的hotel | | HotelMapper.deleteHotel | 删除酒店 | | HotelMapper.updateHotelInfo | 维护酒店信息 | | HotelMapper.updateHotelRate | 更新酒店的评分 | | HotelMapper.selectManagerHotel | 获取某管理员管理的所有hotel | RoomService的接口规范 | 接口名 | 语法 | List\<HotelRoom\> retrieveHotelRoomInfo(Integer hotelId); | | --------------------------------- | :----------- | --------------------------------------------------------- | | RoomService.retrieveHotelRoomInfo | **前置条件** | 输入的酒店id符合规范 | | | **后置条件** | 调用roomMapper.selectRoomsByHotelId方法 | | 接口名 | 语法 | void insertRoomInfo(HotelRoom hotelRoom); | | -------------------------- | :----------- | ----------------------------------------- | | RoomService.insertRoomInfo | **前置条件** | 输入的HotelRoom符合规范 | | | **后置条件** | 调用roomMapper.insertRoom 方法 | | 接口名 | 语法 | void updateRoomInfo(Integer hotelId, String roomType, Integer rooms); | | -------------------------- | :----------- | ------------------------------------------------------------ | | RoomService.updateRoomInfo | **前置条件** | 输入的修改信息符合规范 | | | **后置条件** | 调用roomMapper.updateRoomInfo方法 | | 接口名 | 语法 | HotelRoom getRoomInfo(Integer roomId); | | ----------------------- | :----------- | -------------------------------------- | | RoomService.getRoomInfo | **前置条件** | 输入的roomId不为空 | | | **后置条件** | 调用roomMapper.getRoomById方法 | | 接口名 | 语法 | int getRoomCurNum(Integer hotelId, String roomType); | | ------------------------- | :----------- | ---------------------------------------------------- | | RoomService.getRoomCurNum | **前置条件** | 输入的资料符合规范 | | | **后置条件** | 调用roomMapper.getRoomCurNum方法 | | 接口名 | 语法 | void deleteRoomsByHotelId(Integer hotelId); | | -------------------------------- | :----------- | ------------------------------------------- | | RoomService.deleteRoomsByHotelId | **前置条件** | 输入的hotelId不为null | | | **后置条件** | 调用deleteRoomsByHotelId方法 | | 接口名 | 语法 | ResponseVO updateRoomTotalNum(Integer roomId, Integer totalChange); | | ------------------------------ | :----------- | ------------------------------------------------------------ | | RoomService.updateRoomTotalNum | **前置条件** | 输入有效的信息 | | | **后置条件** | 调用roomMapper.updateRoomTotalNum方法 | RoomService需要的服务 | 服务名 | 服务 | | :-----------------------------: | ------------------------------ | | RoomMapper.updateRoomInfo | 向数据库更新酒店信息 | | RoomMapper.insertRoom | 向数据库插入酒店 | | RoomMapper.selectRoomsByHotelId | 从数据库根据酒店id查找房间 | | RoomMapper.getRoomCurNum | 从数据库查询酒店房间现在的数量 | | RoomMapper.getRoomById | 从数据库根据id查找房间 | | RoomMapper.deleteRoomsByHotelId | 根据hotelId删除房间 | | RoomMapper.updateRoomTotalNum | 更新房间的总数 | RemarkService的接口规范 | 接口名 | 语法 | List<Remark\> retrieveHotelRemark(Integer hotelId); | | --------------------------------- | :----------- | --------------------------------------------------- | | RemarkService.retrieveHotelRemark | **前置条件** | hotelId 不为空 | | | **后置条件** | 调用RemarkMapper.getRemarkByHotelId方法 | | 接口名 | 语法 | List<Remark\> retrieveUserRemark(Integer userId); | | -------------------------------- | :----------- | ------------------------------------------------- | | RemarkService.retrieveUserRemark | **前置条件** | userId 不为空 | | | **后置条件** | 调用RemarkMapper.getRemarkByUserId方法 | | 接口名 | 语法 | void addHotelRemark(Remark remark) throws ServiceException; | | ---------------------------- | :----------- | ------------------------------------------------------------ | | RemarkService.addHotelRemark | **前置条件** | remark不为null | | | **后置条件** | 调用RemarkSMapper.insertRemark方法 | ​ RemarkService需要的服务 | 服务名 | 服务 | | :-----------------------------: | ---------------------------- | | RemarkMapper.getRemarkByHotelId | 获取某个酒店的全部评论给信息 | | RemarkMapper.getRemarkByUserId | 获取某个用户的全部评论给信息 | | RemarkMapper.insertRemark | 用户添加评论 | 4. 业务逻辑层的设计原理 利用委托式控制风格,每个界面需要访问的业务逻辑由各自的控制器委托给不同的Service。 #### 4.1.4 orderbl模块 1. 模块概述 orderbl模块承担的需求: i. 预订酒店 ii.撤销订单 iii. 更新入住和退房信息 ​ \1. 如果有订单执行情况,实时更新入住信息(入住时间、预计 离开时间); ​ \2. 更新订单的退房信息(实际离开时间) ​ \3. 房间只有在实际退房后才可以被再次预定 ​ \4. 如果有非订单(线下)的入住/退房导致的可用房间发生变化,也要 及时更新信息; iv. 浏览订单 ​ \1. 浏览未执行的房间预订的订单 ​ \2. 浏览已执行的订单 ​ \3. 浏览异常和已撤销的订单 v. 订单执行 ​ \1. 当用户已入住,改变订单状态为已执行。 ​ \2. 置为异常订单 ​ a. 酒店工作人员可以查看本地的异常订单,并手工为其补登记执行 情况(即延迟入住), 该订单置为已执行订单,恢复扣除的信用值 ​ b. 置为异常的同时扣除用户等于订单的总价值的信用值 ​ \3. 已执行的订单用户可以获得等于订单价值的信用值增加 orderbl模块的职责及接口参见软件系统结构描述文档。 2. 整体结构 根据体系结构的设计,我们将系统分为了展示层、业务逻辑层、数据层。每一层之间为了增加灵活性,我们添加了接口。展示层和业务逻辑层之间,我们添加OrderService接口。业务逻辑层和数据层之间添加OrderMapper接口。由OrderController作为前后端的连接点。 ![](http://i.shuotu.vip/n=123123.png/p=\hanN\6YVJw1B) orderbl模块各个类的职责: | 模块 | 职责 | | :-------------: | :--------------------------------: | | OrderController | 负责订单相关操作所需要的服务 | | OrderService | 负责订单相关操作所需要的服务的实现 | | | | 3. 模块内部类的接口规范 OrderService的接口规范 | 接口名 | 语法 | ResponseVO addOrder(OrderVO orderVO); | | --------------------- | :----------- | ------------------------------------- | | OrderService.addOrder | **前置条件** | 输入的OrderVO符合规范 | | | **后置条件** | 调用orderMapper.addOrder方法 | | 接口名 | 语法 | List\<Order\> getAllOrders(); | | ------------------------- | :----------- | -------------------------------- | | OrderService.getAllOrders | **前置条件** | 输入的OrderVO符合规范 | | | **后置条件** | 调用orderMapper.getAllOrders方法 | | 接口名 | 语法 | List\<Order\> getUserOrders(int userid); | | -------------------------- | :----------- | ---------------------------------------- | | OrderService.getUserOrders | **前置条件** | 输入的用户id符合规范 | | | **后置条件** | 调用orderMapper.getUserOrders方法 | | 接口名 | 语法 | List<Order\> getManageOrders(int userId); | | ---------------------------- | :----------- | ----------------------------------------- | | OrderService.getManageOrders | **前置条件** | 输入的用户id符合规范 | | | **后置条件** | 调用orderMapper.getHotelOrders方法 | | 接口名 | 语法 | ResponseVO annulOrder(int orderId); | | ----------------------- | :----------- | ----------------------------------- | | OrderService.annulOrder | **前置条件** | 输入的orederid符合规范 | | | **后置条件** | 调用orderMapper.annulOrder方法 | | 接口名 | 语法 | List<Order\> getHotelOrders(Integer hotelId); | | --------------------------- | :----------- | --------------------------------------------- | | OrderService.getHotelOrders | **前置条件** | 输入的hotelid符合规范 | | | **后置条件** | 调用orderMapper.getHotelOrders方法 | | 接口名 | 语法 | List<Order\> getRoomOrders(Integer roomId) | | -------------------------- | :----------- | ------------------------------------------ | | OrderService.getRoomOrders | **前置条件** | 输入的roomid符合规范 | | | **后置条件** | 调用orderMapper.getRoomOrders方法 | | 接口名 | 语法 | ResponseVO orderCheckIn(Integer orderId); | | ------------------------- | :----------- | ------------------------------------------------------------ | | OrderService.orderCheckIn | **前置条件** | 输入的orderid符合规范 | | | **后置条件** | 调用orderMapper.updateCheckInTime和orderMapper.updateState方法 | | 接口名 | 语法 | ResponseVO orderCheckOut(Integer orderId); | | -------------------------- | :----------- | ------------------------------------------------------------ | | OrderService.orderCheckOut | **前置条件** | 输入的orderid符合规范 | | | **后置条件** | 调用orderMapper.updateCheckOutTime和orderMapper.updateState方法 | | 接口名 | 语法 | ResponseVO errorOrder(Integer orderId); | | ----------------------- | :----------- | ------------------------------------------------------------ | | OrderService.errorOrder | **前置条件** | 输入的orderid符合规范 | | | **后置条件** | 调用orderMapper.updateErrorTime和orderMapper.updateState方法 | | 接口名 | 语法 | ResponseVO rmErrorOrder(Integer orderId); | | ------------------------- | :----------- | ----------------------------------------- | | OrderService.rmErrorOrder | **前置条件** | 输入的orderid符合规范 | | | **后置条件** | 调用checkIn方法 | | 接口名 | 语法 | ResponseVO getOrderByOrderId(Integer orderId); | | ------------------------------ | :----------- | ---------------------------------------------- | | OrderService.getOrderByOrderId | **前置条件** | 输入的orderid符合规范 | | | **后置条件** | 调用orderMapper.getOrderById方法 | OrderService需要的服务 | 服务名 | 服务 | | ------------------------------ | :------------------------------- | | OrderMapper.addOrder | 向数据库添加订单 | | OrderMapper.getAllOrders | 向数据库查询所有的订单 | | OrderMapper.getUserOrders | 根据用户id向数据库查询该用户订单 | | OrderMapper.annulOrder | 撤销订单 | | OrderMapper.getHotelOrders | 查看酒店的所有订单 | | OrderMapper.getRoomOrders | 查看某房间的所有订单 | | OrderMapper.updateCheckInTime | 增加订单check in时间 | | OrderMapper.updateCheckOutTime | 增加订单check out时间 | | OrderMapper.updateErrorTime | 增加订单异常时间 | | OrderMapper.updateState | 更改订单状态 | 4. 业务逻辑层的设计原理 利用委托式控制风格,每个界面需要访问的业务逻辑由各自的控制器委托给不同的Service。 #### 4.1.5 userbl模块 1. 模块概述 userbl模块承担的需求: i. 个人基本信息 ​ \1. 维护基本信息(姓名或名称,联系方式、信用) ​ a. 信用不能修改,只能查看 ​ \2. 浏览自己未执行的正常订单 ​ a. 可以撤销自己未执行的正常订单 ​ b. 如果撤销的订单距离最晚订单执行时间不足 6 个小时,撤销的同时扣除信用值,信用值 为订单的(总价值*1/2) ​ c. 撤销的订单并不会删除数据,只是置为已撤销状态,记录撤销时间 ​ \3. 浏览自己已执行的正常订单 ​ \4. 浏览自己异常订单和已撤销订单 ​ \5. 信用记录查看:查看自己每一次的信用变化情况 ​ a. 时间,订单号,动作(订单执行、订单异常、订单撤销、充值), 信用度变化、信用度结果 ii. 注册 iii. 登陆 iv. 数据加密 ​ \1.采用了Base64加密解密方法(用户的账号、密码、姓名、联系方式必须密文存储) userbl模块的职责及接口参见软件系统结构描述文档。 2. 整体结构 根据体系结构的设计,我们将系统分为了展示层、业务逻辑层、数据层。每一层之间为了增加灵活性,我们添加了接口。展示层和业务逻辑层之间,我们添加AccountService接口、EncryptionService接口、CreditService接口。业务逻辑层和数据层之间添加AccountMapper接口和CreditMapper接口。由AccountController作为前后端的连接点。 ![image-20200630234157695](http://i.shuotu.vip/n=image-20200630234157695.png/p=[PgFr7zMbOxE]) userbl模块各个类的职责: | 模块 | 职责 | | :---------------: | :--------------------------------------: | | AccountController | 负责用户相关操作所需要的服务 | | AccountService | 负责用户相关操作所需要的服务的实现 | | EncrytionService | 对用户的信息进行加密和解密 | | CreditService | 负责用户信用值相关操作所需要的服务的实现 | | | | 3. 模块内部类的接口规范 AccountService的接口规范 | 接口名 | 语法 | ResponseVO registerAccount(UserVO userVO); | | ------------------------------ | :----------- | ------------------------------------------ | | AccountService.registerAccount | **前置条件** | userVO符合规范 | | | **后置条件** | 创建新的user | | 接口名 | 语法 | User login(UserForm userForm); | | -------------------- | :----------- | --------------------------------------- | | AccountService.login | **前置条件** | userFrom符合规范 | | | **后置条件** | 调用accountMapper.getAccountByEmail方法 | | 接口名 | 语法 | User getUserInfo(int id); | | -------------------------- | :----------- | ------------------------------------ | | AccountService.getUserInfo | **前置条件** | 输入id合法且存在 | | | **后置条件** | 调用accountMapper.getAccountById方法 | | 接口名 | 语法 | ResponseVO updateUserInfo(int id, String password,String username,String phonenumber); | | ----------------------------- | :----------- | ------------------------------------------------------------ | | AccountService.updateUserInfo | **前置条件** | 1. 输入的id合法且存在 2. 更改的信息符合规范。 | | | **后置条件** | 调用accountMapper.updateAccount方法 | | 接口名 | 语法 | void updateCredit(int id,double credit); | | --------------------------- | :----------- | -------------------------------------------------- | | AccountService.updateCredit | **前置条件** | 1. 输入的id合法且存在 2. 更改的信息符合规范。 | | | **后置条件** | 调用AccountMapper.updateCredit方法 | | 接口名 | 语法 | String getNameById(int id); | | -------------------------- | :----------- | --------------------------------- | | AccountService.getNameById | **前置条件** | 1. 输入的id合法且存在 | | | **后置条件** | 调用AccountMapper.getNameById方法 | AccountService需要的服务 | 服务名 | 服务 | | :-----------------------------: | ------------------------------ | | AccountMapper.createNewAccount | 在数据库创建一个新的账号 | | AccountMapper.getAccountByEmail | 在数据库根据email查找账号信息 | | AccountMapper.getAccountById | 在数据库根据用户ID查找账号信息 | | AccountMapper.getNameById | 在数据库根据id查找姓名 | | AccountMapper.updateAccount | 在数据库更新用户信息 | ​ EncryptionService的接口规范 | 接口名 | 语法 | String encryptionOfData(String data); | | ---------------------------------- | :----------- | ------------------------------------- | | EncryptionService.encryptionOfData | **前置条件** | 输入不为null | | | **后置条件** | 调用AccountMapper.getNameById方法 | | 接口名 | 语法 | String decryptionOfData(String data); | | ---------------------------------- | :----------- | ------------------------------------- | | EncryptionService.decryptionOfData | **前置条件** | 输入不为null | | | **后置条件** | 无 | | 接口名 | 语法 | User encryptionOfUser(User user); | | ---------------------------------- | :----------- | --------------------------------- | | EncryptionService.encryptionOfUser | **前置条件** | 输入不为null | | | **后置条件** | 无 | | 接口名 | 语法 | User decryptionOfUser(User user); | | ---------------------------------- | :----------- | --------------------------------- | | EncryptionService.decryptionOfUser | **前置条件** | 输入不为null | | | **后置条件** | 无 | | 接口名 | 语法 | UserForm encryptionOfUserForm(UserForm userForm); | | -------------------------------------- | :----------- | ------------------------------------------------- | | EncryptionService.encryptionOfUserForm | **前置条件** | 输入不为null | | | **后置条件** | 无 | | 接口名 | 语法 | UserForm decryptionOfUserForm(UserForm userForm); | | -------------------------------------- | :----------- | ------------------------------------------------- | | EncryptionService.decryptionOfUserForm | **前置条件** | 输入不为null | | | **后置条件** | 无 | ​ CreditService的接口规范 | 接口名 | 语法 | List<Credit\> retrieveCreditRecord(Integer userId); | | ---------------------------------- | :----------- | --------------------------------------------------- | | CreditService.retrieveCreditRecord | **前置条件** | userId不为空 | | | **后置条件** | 调用creditMapper.selectByUserId方法 | | 接口名 | 语法 | void addCreditRecord(Credit credit); | | ----------------------------- | :----------- | ------------------------------------ | | CreditService.addCreditRecord | **前置条件** | credit不为null | | | **后置条件** | 调用creditMapper.addCreditRecord方法 | | 接口名 | 语法 | void rmCreditRecord(Integer orderId); | | ---------------------------- | :----------- | ------------------------------------- | | CreditService.rmCreditRecord | **前置条件** | orderId符合规范 | | | **后置条件** | 调用creditMapper.rmCreditRecord方法 | ​ CreditService需要的服务 | 服务名 | 服务 | | :--------------------------: | -------------------------------- | | CreditMapper.addCreditRecord | 在数据库中增加一条信用记录 | | CreditMapper.rmCreditRecord | 在数据库中删除一条信用记录 | | CreditMapper.selectByUserId | 在数据库中获取指定用户的信用记录 | 4. 业务逻辑层的设计原理 利用委托式控制风格,每个界面需要访问的业务逻辑由各自的控制器委托给不同的Service。 ## 5. 依赖视角 ### 5.1 开发包图 ![](http://i.shuotu.vip/n=开发包图2.png/p=iWB7bAvG=ZUo8)
Python
UTF-8
907
4.1875
4
[]
no_license
# Задача-2: Исходные значения двух переменных запросить у пользователя. # Поменять значения переменных местами. Вывести новые значения на экран. # Решите задачу, используя только две переменные. # Подсказки: # * постарайтесь сделать решение через действия над числами; # * при желании и понимании воспользуйтесь синтаксисом кортежей Python. number1 = int(input("Введите первое число: ")) number2 = int(input("Введите второе число: ")) number1 = number1 + number2 number2 = number1 - number2 number1 = number1 - number2 print("первое число:", number1, "второе число:", number2)
C#
UTF-8
2,661
3.09375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace guessing { class Program { static void Main(string[] args) { Console.BackgroundColor = ConsoleColor.DarkCyan; Console.Clear(); Console.ForegroundColor = ConsoleColor.White; //Console.Write("Press any key to continue"); //Console.ReadKey(); WELCOME t = new WELCOME(); t.Welcome(); // t.password(); // int numOfQuestion = 10; // int repons=10; //numOfQuestion ; int limit = 0; int num = 1; string userAnswer; int score=0; //randomize the order of the question // int l; // Random rnd = new Random(); // l = rnd.Next(0, 9); //call method in class Florida Florida q = new Florida(); Console.Write("1."); Console.WriteLine(q.Quest[limit]); //Console.WriteLine(); userAnswer = Console.ReadLine(); for (int i = 0;i==limit; i++) { num++; if (limit == 10) { break; } if (userAnswer == q.Ans[limit]) { Console.WriteLine(); limit++; //score++; Console.Write("{0}.", num); Console.WriteLine(q.Quest[limit]); userAnswer = Console.ReadLine(); // Console.WriteLine(); //limit++; score++; } else if (userAnswer != q.Ans[limit]) { Console.WriteLine(); limit++; Console.Write("{0}.", num ); Console.WriteLine(q.Quest[limit]); userAnswer = Console.ReadLine(); // Console.WriteLine(); //limit++; } } t.score(); Console.Write("\t\t\t\t\t "+score); Console.Write(" / "+11); Console.ReadLine(); } } }
C++
UTF-8
932
2.53125
3
[ "MIT" ]
permissive
// // File: SoundManager.hpp // Class: SoundManager // Author: John Barbero Unenge // All code is my own except where credited to others. // // Copyright (c) 2012 Catch22. All Rights Reserved. // // Date: 17/9-2012 // // License: The following code is licensed under the Catch22-License // // Description: // This class is used for audio playback. // class SoundManager { public: // Constructor SoundManager(); // Destructor ~SoundManager(); // Plays the given file as a sound effect. This means // that it will playback in parallell with music and // other sounds. void playSFX(const char* file); // Plays the given file as background music. This file // may very well be compressed. If music is already // playing then that music will be stopped and the // contents of the new file will start playing. void playBGMusic(const char* file); };
Markdown
UTF-8
720
3.5
4
[]
no_license
# 问题描述 购房从银行贷了一笔款d,准备每月还款额为p,月利率为r,计算多少月能还清。计算还清月数的公式如下: m=(log(p/(p-d*r))/log(1+r) # 格式 ## 输入 三个数d,p,r,以空格分隔。(d,p为整数,且200000<=d<=500000,1000<=p<=10000.r为实数,且0.005<=r<=0.02) ## 输出 一个数m(保留两位小数) # 样例数据 <style> table,table tr th, table tr td { border:1px solid #0094ff; } table { width: 200px; min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse;} </style> <table> <tr> <td>输入样例</td> <td>输出样例</td> </tr> <tr><td>300000,6000,0.01</td><td>69.7</td></tr></table>
C
UTF-8
6,187
3.0625
3
[]
no_license
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ #include <stdarg.h> #include "newzpost.h" #include "../ui/errors.h" static long buff_data_length(char *fmt, va_list ap); file_entry * file_entry_alloc(){ file_entry * fe = malloc(sizeof(file_entry)); fe->parts = NULL; fe->filename = NULL; fe->rwlock = NULL; fe->parts_posted = 0; fe->post_started = FALSE; return fe; } file_entry * file_entry_free(file_entry *fe){ if(fe != NULL){ if(fe->parts != NULL) free(fe->parts); if(fe->filename != NULL) buff_free(fe->filename); if(fe->rwlock != NULL) { pthread_rwlock_destroy(fe->rwlock); free(fe->rwlock); } free(fe); } return NULL; } Buff * buff_getline(Buff *buff, FILE *file){ char c = fgetc(file); buff = buff_free(buff); while(TRUE){ if((c == '\n') || (c == EOF)) break; buff = buff_add(buff, "%c", c); c = fgetc(file); } return buff; } /* Accepts subset of printf() syntax. Supports %c, %s, %i, %%, and %0*i More can be added in buff_data_length() */ Buff *buff_create(Buff *buff, char *data, ... ){ va_list ap; long datalength; /* find out the total length of the data */ va_start(ap, data); datalength = buff_data_length(data, ap); va_end(ap); /* this function frees whatever *buff points to! */ if(buff != NULL) buff = buff_free(buff); if(datalength == 0) return NULL; /* initialize the Buff */ buff = malloc(sizeof(Buff)); buff->length = datalength; /* determine the real length to make this buffer */ /* real length is more than length... this reduces the number of realloc()s */ for(buff->real_length = 2 ; buff->real_length <= datalength; buff->real_length = buff->real_length * 2){} buff->data = malloc(buff->real_length); /* write the data to the memory we just malloced */ va_start(ap, data); vsprintf(buff->data,data,ap); va_end(ap); buff->data[buff->length] = '\0'; return buff; } /* Accepts subset of printf() syntax. Supports %c, %s, %i, %%, and %0*i More can be added in buff_data_length() */ Buff *buff_add(Buff *buff, char *data, ... ){ va_list ap; long datalength; /* find out the total length of the data */ va_start(ap, data); datalength = buff_data_length(data, ap); va_end(ap); va_start(ap, data); if(buff == NULL){ if(datalength == 0) return NULL; /* initialize the Buff */ buff = malloc(sizeof(Buff)); buff->length = datalength; /* determine the real length to make this buffer */ for(buff->real_length = 2 ; buff->real_length <= datalength; buff->real_length = buff->real_length * 2){} buff->data = malloc(buff->real_length); /* write the data to the memory we just malloced */ vsprintf(buff->data,data,ap); } else{ /* save the old length (where to start writing data) and update the Buff */ int oldlength = buff->length; buff->length += datalength; /* realloc more memory if necessary */ if(buff->length >= buff->real_length){ for(; buff->real_length <= buff->length; buff->real_length = buff->real_length * 2){} buff->data = realloc(buff->data, buff->real_length); } /* append the data to the buff */ vsprintf((buff->data + oldlength), data, ap); } va_end(ap); buff->data[buff->length] = '\0'; return buff; } Buff * buff_free(Buff *buff){ if(buff != NULL){ free(buff->data); free(buff); } return NULL; } /* Find last occurrence of '/' or '\\'; return rest of string */ const char *n_basename(const char *path) { const char *current; for (current = path; *current; current++) if (('/' == *current) || ('\\' == *current)) path = current + 1; return path; } SList *slist_next(SList *slist) { return slist->next; } SList *slist_remove(SList *slist, void *data) { SList *si = slist; SList *prev = NULL; while (si != NULL) { if (si->data == data) { if (prev == NULL) { si = si->next; free(slist); return si; } prev->next = si->next; free(si); return slist; } prev = si; si = si->next; } return slist; } SList *slist_append(SList *slist, void *data) { SList *si; if (slist == NULL) { slist = (SList *) malloc(sizeof(SList)); slist->data = data; slist->next = NULL; return slist; } else { si = slist; while (si->next != NULL) si = si->next; si->next = (SList *) malloc(sizeof(SList)); si = si->next; si->data = data; si->next = NULL; return slist; } } SList *slist_prepend(SList *slist, void *data) { SList *si; if (slist == NULL) { slist = (SList *) malloc(sizeof(SList)); slist->data = data; slist->next = NULL; return slist; } else { si = (SList *) malloc(sizeof(SList)); si->data = data; si->next = slist; return si; } } void slist_free(SList *slist) { SList *si; while (slist != NULL) { si = slist; slist = slist->next; free(si); } } int slist_length(SList *slist) { int i = 0; while (slist != NULL) { i++; slist = slist->next; } return i; } /** *** Private Routines **/ static long buff_data_length(char *fmt, va_list ap){ char *pi; char lengthstr[64]; /* all numbers will fit in here */ long retval = 0; /* go through the string, looking for '%' */ for(pi = fmt; *pi; pi++){ if(*pi == '%'){ switch(*++pi){ case 's': /* add the length of the string argument */ retval += strlen(va_arg(ap, char *)); break; case '%': /* add one. its just a '%'! */ retval++; break; case 'c': /* add one. we have to call va_arg() to go to the next argument */ va_arg(ap, int); retval++; break; case 'i': /* add the length of the number */ sprintf(lengthstr,"%i",va_arg(ap, int)); retval += strlen(lengthstr); break; case '0': /* add the number of zeroes used in zero-padding */ if(*++pi == '*'){ if(*++pi == 'i'){ retval += va_arg(ap, int); va_arg(ap, int); break; } } /* This only works with a subset of printf syntax. If you want to add more you must handle it above. */ default: fprintf(stderr, "\nInternal Error: see utils.c\n"); exit(EXIT_UNKNOWN); } } else{ /* a plain character */ retval++; } } return retval; }
C#
UTF-8
618
4.09375
4
[ "MIT" ]
permissive
using System; using System.Linq; /// <summary> /// /// Write a method that reverses the digits of given decimal number. /// /// </summary> class ReverseNumber { static void Main() { // Input Console.Write("Enter number to reverse: "); double number = double.Parse(Console.ReadLine()); // Solution and Output ReverseAndPrint(number); } private static void ReverseAndPrint(double number) { string strNumber = number.ToString(); char[] array = strNumber.ToArray(); Array.Reverse(array); Console.WriteLine(array); } }