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
Rust
UTF-8
6,412
3.515625
4
[ "BSD-3-Clause" ]
permissive
use std::cmp::Ordering; use std::fmt; use value::{ Value }; use error::{ RuntimeError, RuntimeResult }; use function::Callable; /// Operator kind. #[derive(PartialEq, Debug, Copy, Clone)] pub enum OperatorKind { /// Single argument operator, i.e negation. Unary { value: &'static str }, /// Two argument operator, i.e sum. Binary { value: &'static str, associativity: Associativity }, /// Any operator handled by extension (i.e. the "=" operator). Other, } impl OperatorKind { pub fn new_binary(value: &'static str, associativity: Associativity) -> OperatorKind { OperatorKind::Binary { value: value, associativity: associativity } } pub fn new_binary_left(value: &'static str) -> OperatorKind { OperatorKind::Binary { value: value, associativity: Associativity::Left } } pub fn new_binary_right(value: &'static str) -> OperatorKind { OperatorKind::Binary { value: value, associativity: Associativity::Right } } pub fn new_unary(value: &'static str) -> OperatorKind { OperatorKind::Unary { value: value } } pub fn new_other() -> OperatorKind { OperatorKind::Other } } /// Operator options for parsing, sets precedence and weather it is unary/binary. #[derive(Debug, Copy, Clone)] pub struct OperatorOptions { pub precedence: Option<u16>, pub kind: OperatorKind, } impl OperatorOptions { pub fn new_binary(chars: &'static str, precedence: u16, associativity: Associativity) -> OperatorOptions { OperatorOptions { precedence: Some(precedence), kind: OperatorKind::new_binary(chars, associativity), } } pub fn new_binary_left(chars: &'static str, precedence: u16) -> OperatorOptions { OperatorOptions::new_binary(chars, precedence, Associativity::Left) } pub fn new_binary_right(chars: &'static str, precedence: u16) -> OperatorOptions { OperatorOptions::new_binary(chars, precedence, Associativity::Right) } pub fn new_unary(chars: &'static str, precedence: u16) -> OperatorOptions { OperatorOptions { precedence: Some(precedence), kind: OperatorKind::new_unary(chars), } } pub fn new_other() -> OperatorOptions { OperatorOptions { precedence: None, kind: OperatorKind::new_other(), } } } /// Represents environment operator. pub struct Operator { /// Operator options. pub options: OperatorOptions, /// Operator callable. pub callable: Callable, } impl fmt::Debug for Operator { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({:?}, callable)", self.options) } } impl Operator { pub fn new_binary<F: 'static>( chars: &'static str, precedence: u16, associativity: Associativity, callable: F ) -> Operator where F: for<'e> Fn(&'e Value, &'e Value) -> RuntimeResult<Value> { Operator { options: OperatorOptions::new_binary(chars, precedence, associativity), callable: Callable::Dynamic(Box::new(move |args| { if args.len() != 2 { return Err( RuntimeError::InvalidArgumentCount { defined: 2, given: args.len() } ) } callable( unsafe { args.get_unchecked(0) }, unsafe { args.get_unchecked(1) } ) })), } } pub fn new_binary_left<F: 'static>( chars: &'static str, precedence: u16, callable: F ) -> Operator where F: for<'e> Fn(&'e Value, &'e Value) -> RuntimeResult<Value> { Operator::new_binary( chars, precedence, Associativity::Left, callable ) } pub fn new_binary_right<F: 'static>( chars: &'static str, precedence: u16, callable: F ) -> Operator where F: for<'e> Fn(&'e Value, &'e Value) -> RuntimeResult<Value> { Operator::new_binary( chars, precedence, Associativity::Right, callable ) } pub fn new_unary<F: 'static>( chars: &'static str, precedence: u16, callable: F ) -> Operator where F: for<'e> Fn(&'e Value) -> RuntimeResult<Value> { Operator { options: OperatorOptions::new_unary(chars, precedence), callable: Callable::Dynamic(Box::new(move |args| { if args.len() != 1 { return Err( RuntimeError::InvalidArgumentCount { defined: 1, given: args.len() } ) } callable( unsafe { args.get_unchecked(0) } ) })), } } } /// Operator associativity. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Associativity { Left, Right, } impl PartialOrd for Associativity { fn partial_cmp(&self, other: &Associativity) -> Option<Ordering> { match (*self, *other) { (Associativity::Left, Associativity::Right) => Some(Ordering::Less), (Associativity::Right, Associativity::Left) => Some(Ordering::Greater), _ => Some(Ordering::Equal), } } } impl Ord for Associativity { fn cmp(&self, other: &Associativity) -> Ordering { match (*self, *other) { (Associativity::Left, Associativity::Right) => Ordering::Less, (Associativity::Right, Associativity::Left) => Ordering::Greater, _ => Ordering::Equal, } } } #[cfg(test)] mod test { use super::Associativity; #[test] fn associativity_left_should_be_less_than_right() { assert!(Associativity::Left < Associativity::Right); } #[test] fn associativity_right_should_be_greater_than_left() { assert!(Associativity::Right > Associativity::Left); } #[test] fn associativity_right_should_be_equal_to_right() { assert!(Associativity::Right == Associativity::Right); } }
C++
UTF-8
771
2.546875
3
[]
no_license
#ifndef __RBLOCK_H__ #define __RBLOCK_H__ class Block { int x; int y; int c; public: Block(); void printBlock(); friend class BlockA; }; class BlockSet{ public: int blocknum; int x; int y; int c; int xarr[4]; int yarr[4]; }; class BlockA : public BlockSet{ static Block blarr[10][18]; public: int maxY(); int minY(); BlockA(int blocknum); void display(); void firstSet(); void setBlock(int blocknum); void clear(int blocknum); void color(int c); void rotationB(int blocknum1,int blocknum2); bool check(); int check0(); void moveL(); void moveR(); void moveD();//밑으로 void moveB();//바닥 void moveU();//돌리기 void addScore(int& score); }; #endif
Java
UTF-8
230
1.53125
2
[]
no_license
package com.shopping.demo.entity; import lombok.Data; /** * @Author Gao * @Date 2021/2/12 23:49 * @Version 1.0 */ @Data public class OrderUser extends Order { private String userName; private String goodsName; }
Java
UTF-8
3,304
2.671875
3
[]
no_license
package com.cisco.eManager.common.event; import java.util.Date; import com.cisco.eManager.common.event.EventType; import com.cisco.eManager.common.event.EventSeverity; public abstract class AbstractEventMessage implements Comparable { private String displayText; private Date eventTime; private EventType eventType; private EventSeverity severity; private boolean syncGenerated; public AbstractEventMessage (AbstractEventMessage object) { eventType = object.eventType; eventTime = object.eventTime; displayText = object.displayText; severity = object.severity; syncGenerated = object.syncGenerated; } /** * @param eventType * @param eventTime * @param severity * @param displayText * @roseuid 3F4E5CF8012A */ public AbstractEventMessage(EventType eventType, Date eventTime, EventSeverity severity, String displayText) { this.eventType = eventType; this.eventTime = eventTime; this.severity = severity; this.displayText = displayText; this.syncGenerated = false; } /** * Access method for the displayText property. * * @return the current value of the displayText property */ public String getDisplayText() { return displayText; } /** * Access method for the eventTime property. * * @return the current value of the eventTime property */ public Date getEventTime() { return eventTime; } public void setEventTime(Date eventTime) { this.eventTime = eventTime; } /** * Access method for the eventType property. * * @return the current value of the eventType property */ public EventType getEventType() { return eventType; } public void setEventType(EventType eventType) { this.eventType = eventType; } /** * Access method for the severity property. * * @return the current value of the severity property */ public EventSeverity getSeverity() { return severity; } public boolean getSyncGenerated () { return syncGenerated; } public void setSyncGenerated (boolean syncGenerated) { this.syncGenerated = syncGenerated; } public int compareTo (Object object) { boolean baseClassFound; Class objectClasses[]; objectClasses = object.getClass().getClasses(); baseClassFound = false; for (int i = 0; i < objectClasses.length; i++) { if (this.getClass().equals (objectClasses[i])) { baseClassFound = true; break; } } if (baseClassFound == true) { return getEventTime().compareTo( ( (AbstractEventMessage)object).getEventTime()); } return 0; } public boolean equals (Object object) { if (object instanceof AbstractEventMessage) { AbstractEventMessage aObject; aObject = (AbstractEventMessage) object; if (displayText.equals(aObject.displayText) && eventTime.equals(aObject.eventTime) && eventType.equals(aObject.eventType) && severity.equals(aObject.severity)) return true; } return false; } }
Python
UTF-8
358
3.234375
3
[]
no_license
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] print(planets[0:0]) # [] empty set print(planets[0:1]) # ['Mercury'] print(planets[0:]) # ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] print(planets[:7]) # ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus'] #eof
Markdown
UTF-8
475
2.53125
3
[]
no_license
# terminal-emulator This is just a simple project to figure out how process creation in linux works ##Currently Working## * execute single or many processes with |, >, ;, &, && * execute ls and cd alone * file redirect and pipes with no more than two processes ##Broken## * more than two pipes causes zombie processes * something bugs out when multiple & run ##Missing Features## * to Parser.h: parse commands where a builtin (i.e. ls or cd) is run with another command
Markdown
UTF-8
6,705
2.65625
3
[ "CC-BY-3.0", "LicenseRef-scancode-generic-cla" ]
permissive
<properties pageTitle="開始在 Azure 入口網站中使用 Azure 排程器 | Microsoft Azure" description="" services="scheduler" documentationCenter=".NET" authors="krisragh" manager="dwrede" editor=""/> <tags ms.service="scheduler" ms.workload="infrastructure-services" ms.tgt_pltfrm="na" ms.devlang="dotnet" ms.topic="hero-article" ms.date="02/17/2016" ms.author="krisragh"/> # 開始在 Azure 入口網站中使用 Azure 排程器 在 Azure 排程器中建立排程作業很簡單。在本教學課程中,您將了解如何建立作業。您也將學習排程器的監視和管理功能。 ## 建立工作 1. 登入 [Azure 入口網站](https://portal.azure.com/)。 2. 按一下 [+新增] > 在搜尋方塊中輸入_排程器_ > 在結果中選取 [排程器] > 按一下 [建立]。 ![][marketplace-create] 3. 讓我們使用 GET 要求建立只要點擊 http://www.microsoft.com/ 的工作。在 [排程器作業] 畫面中,輸入下列資訊: 1. **名稱:** `getmicrosoft` 2. **訂用帳戶:**您的 Azure 訂用帳戶 3. **作業集合:**選取現有的作業集合,或按一下 [建立新項目] > 輸入名稱。 4. 接下來,在 [動作設定] 中,定義下列值: 1. **動作類型:** ` HTTP` 2. **方法:** `GET` 3. **URL:**` http://www.microsoft.com` ![][action-settings] 5. 最後,讓我們定義排程。作業可以定義為一次性的工作,但我們挑選週期性排程: 1. **週期**:`Recurring` 2. **開始**:今天的日期 3. **重複頻率**:`12 Hours` 4. **結束於**:今天日期的前兩天 ![][recurrence-schedule] 6. 按一下 [建立] ## 管理和監視作業 建立作業之後,它會出現在主要 Azure 儀表板。按一下作業,即會開啟新視窗並顯示下列索引標籤: 1. 屬性 2. 動作設定 3. 排程 4. 歷程記錄 5. 使用者 ![][job-overview] ### 屬性 這些唯讀屬性說明排程器作業的管理中繼資料。 ![][job-properties] ### 動作設定 按一下 [作業] 畫面中的作業,可讓您設定該作業。如果您沒有在快速建立精靈中進行進階設定,這可讓您設定它們。 對於所有的動作類型,您可以變更重試原則和錯誤動作。 對於 HTTP 和 HTTPS 工作動作類型,您可能會將方法變更為任何允許的 HTTP 動詞。您也可以新增、刪除或變更標頭和基本驗證資訊。 對於儲存體佇列動作類型,您可能變更儲存體帳戶、佇列名稱、SAS 權杖和主體。 對於服務匯流排動作類型,您可以變更命名空間、主題/佇列路徑、驗證設定、傳輸類型、訊息屬性和訊息本文。 ![][job-action-settings] ### 排程 如果您想要變更您在快速建立精靈中建立的排程,這可讓您重新設定排程。 這是[在作業中建置複雜的排程和進階週期](scheduler-advanced-complexity.md)的機會 您可以變更開始日期和時間、週期排程,以及結束日期和時間 (如果工作重複發生。) ![][job-schedule] ### 歷程記錄 [歷程記錄] 索引標籤為選取的作業顯示系統中每次執行作業時選取的度量。這些度量提供有關排程器健全狀況的即時值: 1. 狀態 2. 詳細資料 3. 重試次數 4. 發生次數:第 1 次、第 2 次、第 3 次等。 5. 執行開始時間 6. 執行結束時間 ![][job-history] 您可以按一下執行來檢視 [記錄詳細資料],包括每次執行的完整回應。此對話方塊也可讓您將回應複製到剪貼簿。 ![][job-history-details] ### 使用者 Azure 角色型存取控制 (RBAC) 可以對 Azure 排程器進行更細緻的存取權管理。若要了解如何使用 [使用者] 索引標籤,請參閱 [Azure 角色型存取控制](../active-directory/role-based-access-control-configure.md) ## 另請參閱 [排程器是什麼?](scheduler-intro.md) [排程器概念、術語及實體階層](scheduler-concepts-terms.md) [Azure 排程器的計劃和計費](scheduler-plans-billing.md) [如何使用 Azure 排程器建立複雜的排程和進階週期](scheduler-advanced-complexity.md) [排程器 REST API 參考](https://msdn.microsoft.com/library/mt629143) [排程器 PowerShell Cmdlet 參考](scheduler-powershell-reference.md) [排程器高可用性和可靠性](scheduler-high-availability-reliability.md) [排程器限制、預設值和錯誤碼](scheduler-limits-defaults-errors.md) [排程器輸出驗證](scheduler-outbound-authentication.md) [marketplace-create]: ./media/scheduler-get-started-portal/scheduler-v2-portal-marketplace-create.png [action-settings]: ./media/scheduler-get-started-portal/scheduler-v2-portal-action-settings.png [recurrence-schedule]: ./media/scheduler-get-started-portal/scheduler-v2-portal-recurrence-schedule.png [job-properties]: ./media/scheduler-get-started-portal/scheduler-v2-portal-job-properties.png [job-overview]: ./media/scheduler-get-started-portal/scheduler-v2-portal-job-overview-1.png [job-action-settings]: ./media/scheduler-get-started-portal/scheduler-v2-portal-job-action-settings.png [job-schedule]: ./media/scheduler-get-started-portal/scheduler-v2-portal-job-schedule.png [job-history]: ./media/scheduler-get-started-portal/scheduler-v2-portal-job-history.png [job-history-details]: ./media/scheduler-get-started-portal/scheduler-v2-portal-job-history-details.png [1]: ./media/scheduler-get-started-portal/scheduler-get-started-portal001.png [2]: ./media/scheduler-get-started-portal/scheduler-get-started-portal002.png [3]: ./media/scheduler-get-started-portal/scheduler-get-started-portal003.png [4]: ./media/scheduler-get-started-portal/scheduler-get-started-portal004.png [5]: ./media/scheduler-get-started-portal/scheduler-get-started-portal005.png [6]: ./media/scheduler-get-started-portal/scheduler-get-started-portal006.png [7]: ./media/scheduler-get-started-portal/scheduler-get-started-portal007.png [8]: ./media/scheduler-get-started-portal/scheduler-get-started-portal008.png [9]: ./media/scheduler-get-started-portal/scheduler-get-started-portal009.png [10]: ./media/scheduler-get-started-portal/scheduler-get-started-portal010.png [11]: ./media/scheduler-get-started-portal/scheduler-get-started-portal011.png [12]: ./media/scheduler-get-started-portal/scheduler-get-started-portal012.png [13]: ./media/scheduler-get-started-portal/scheduler-get-started-portal013.png [14]: ./media/scheduler-get-started-portal/scheduler-get-started-portal014.png [15]: ./media/scheduler-get-started-portal/scheduler-get-started-portal015.png <!---HONumber=AcomDC_0218_2016-->
Python
UTF-8
543
2.921875
3
[]
no_license
print("--- 1 ---") import my_package print("--- 2 ---") import my_package.my_module my_package.my_module.my_method() print("--- 3 ---") from my_package import my_module my_module.my_method() print("--- 4 ---") from my_package.my_module import my_method my_method() print("--- 5 ---") import my_package.my_subpackage1 print("--- 6 ---") from my_package import shadowed print(shadowed) print("--- 7 ---") from my_package.my_subpackage2 import * A.a() C.c() try: B.b() except NameError: print("Package B was not imported!")
Shell
UTF-8
1,401
3.65625
4
[]
no_license
#!/bin/bash if [ "$1" == "" ] then echo "Usage: $0 releasetag" echo "" exit 1 fi if [[ $1 == v* ]] then echo "Bad releasetag. Use only numbers, like '33'" echo "" exit 1 fi RELEASEP=$1 if [ -d themes ] ; then echo "Removing old themes directory" rm -rf themes > /dev/null fi echo "Creating themes directory" mkdir themes > /dev/null pushd themes > /dev/null REPOS=( "git@github.com:MythTV-Themes/Arclight.git" "git@github.com:MythTV-Themes/blue-abstract-wide.git" "git@github.com:MythTV-Themes/Functionality.git" "git@github.com:MythTV-Themes/LCARS.git" "git@github.com:MythTV-Themes/Mythbuntu.git" "git@github.com:MythTV-Themes/Steppes-large.git" "git@github.com:MythTV-Themes/Steppes.git" "git@github.com:MythTV-Themes/TintedGlass.git" #"git@github.com:paul-h/MythCenterXMAS-wide.git" #"git@github.com:paul-h/MythCenterXMASKIDS-wide.git" ) for REPO in ${REPOS[@]} do BASE=$(basename $REPO .git) echo "###" echo "Checking out ${BASE} theme" git clone ${REPO} > /dev/null 2>&1 pushd ${BASE} >> /dev/null BRANCHNAME="origin/fixes/${RELEASEP}" REMOTENAME=$(git branch -l -r ${BRANCHNAME}) if [[ "$REMOTENAME" == *"fixes"* ]] ; then echo "${BRANCHNAME} exists" else echo "Creating branch ${BRANCHNAME}" git push origin HEAD:refs/heads/fixes/${RELEASEP} fi echo "###" echo "" popd >> /dev/null done popd > /dev/null
Python
UTF-8
1,123
2.71875
3
[]
no_license
import os import seaborn as sns import numpy as np from PIL import Image from matplotlib import pyplot as plt from sklearn.decomposition import PCA from sklearn.manifold import TSNE images = [] filenames = [] folder = "imgs" for filename in os.listdir(folder): image = Image.open(folder + "/" + filename) ratio = 0.2 w, h = image.size image = np.asarray(image.resize((int(w * ratio), int(h * ratio)))).flatten() images.append(image) filenames.append("imgs/" + filename) images = np.array(images) print(images.shape) idx = np.random.randint(len(images), size=600) images = images[idx] filenames = [filenames[i] for i in idx] print(images.shape, len(filenames)) pca = PCA(n_components=50) pca_result = pca.fit_transform(images) print(pca_result.shape) tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=2000) tsne_results = tsne.fit_transform(pca_result) print(tsne_results.shape) np.save("data/tsne.npy", tsne_results) with open('data/filenames.txt', 'w') as f: for item in filenames: f.write("%s\n" % item) plt.scatter(tsne_results[:, 0], tsne_results[:, 1]) plt.show()
Markdown
UTF-8
1,837
2.75
3
[]
no_license
--- title: Protetor Facial Face Shield - Proteção Covid 19 categoria: Equipamentos de segurança image: "/uploads/protetor-facial-face-shield.jpg" --- - Fácil higienização (água e alcool) - Suporte anatômico, firmeza na adaptação - Facilidade de respiração - Transparente, com maior campo de visão - Clareza na comunicação - Reutilizável (lavável integralmente) - Utilizada em conjunto com máscaras convencionais, aumenta sua durabilidade <div data-grid="row"> <div data-cell="1of3"> <img src="/uploads/protetor-facial-face-shield-amostras-1.jpg" alt="Face Shield"> </div> <div data-cell="1of3"> <img src="/uploads/protetor-facial-face-shield-amostras-2.jpg" alt="Face Shield"> </div> </div> ## Características Temos dois tipos de Máscara Face Shield, que são: ### 1. Visor Fixo - Material: PetG ou Acetato, variando de 0,4 a 0,5 mm de espessura. - Dimensões: 240 mm x 275 mm O corpo é produzido 100% em polipropileno, alta resistência e lavável. A altura é de 10 mm e espessura de 3,5 mm. ### 2. Visor articulado - Material: PetG ou Acetato, variando de 0,4 a 0,5 mm de espessura. - Dimensões: 240 mm x 275 mm O corpo é produzido 100% em termoplástico, alta resistência e lavável. <div data-grid="spacing"> <div data-cell="2of3"> <p> <strong>Atenção:</strong> A cor de ambos é transparente e as máscaras são vendidas por unidade. As máscaras chegam desmontadas; para montagem adequada, basta seguir as orientações que chegarão junto com as peças. </p> <p> Para a higiene, basta usar hipoclorito de sódio ou álcool 70%. Seguindo essa instrução de limpeza, é possível usar a máscara de forma ilimitada. </p> </div> <div data-cell="1of3"> <img src="/uploads/protetor-facial-face-shield-2.jpg" alt="Face Shield"> </div> </div>
Java
UTF-8
2,616
1.9375
2
[]
no_license
package com.nandasatria.api.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.nandasatria.api.model.GeneralResponse; import com.nandasatria.api.model.RequestAlert; import com.nandasatria.api.service.ValidationAlert; import com.nandasatria.elastic.job.JobScheduler; import com.nandasatria.elastic.job.JobSchedulerProcessor; import com.nandasatria.elastic.service.AlertElasticService; import com.nandasatria.elastic.service.IndexElasticService; @RestController @Service public class AlertApiController { @Autowired JobSchedulerProcessor jobSchedulerProcessor; @Autowired AlertElasticService alertElasticService; @Autowired IndexElasticService indexElasticService; @Autowired JobScheduler jobScheduler; @Autowired ValidationAlert validationAlert; @PostMapping(value = "/v1/alert", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> searchData(@RequestBody RequestAlert request) { GeneralResponse response = null; try { response = validationAlert.validate(request); if (response.isValid() == true) { String responseString = alertElasticService.registerAlert(request); response.setErrorDescription(responseString); } return new ResponseEntity<>(response, response.getErrorCode()); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } @GetMapping(value = "/v1/run-alert") public ResponseEntity<?> runAlert(@RequestParam("id") String id) { RequestAlert request = jobSchedulerProcessor.process(id); return new ResponseEntity<>(request, HttpStatus.OK); } @GetMapping(value = "/v1/run-all-alert") public ResponseEntity<?> runAlltAlert() { return new ResponseEntity<>(jobScheduler.jobRunner(), HttpStatus.OK); } @GetMapping(value = "/v1/mapping-index") public ResponseEntity<?> getListMappingIndex(@RequestParam("index") String index) { List<String> listHeaders = indexElasticService.getHeaderIndex(index); return new ResponseEntity<>(listHeaders, HttpStatus.OK); } }
Java
UTF-8
3,022
2.921875
3
[]
no_license
package controller; import java.io.FileReader; import java.util.Scanner; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import model.data_structures.DobleListaEncadenada; import model.logic.Comparendos; import model.logic.Modelo; import view.View; public class Controller { /* * */ private DobleListaEncadenada<Comparendos> listaComparendos; /* Instancia del Modelo*/ private Modelo modelo; /* Instancia de la Vista*/ private View view; private Comparendos comparendo; public static final String ruta="./data/comparendos.geojson"; /** * Crear la vista y el modelo del proyecto * @param capacidad tamaNo inicial del arreglo */ public Controller() { listaComparendos= new DobleListaEncadenada<Comparendos>(); view = new View(); modelo = new Modelo(); } public void run() { Scanner lector = new Scanner(System.in); Comparable<Comparendos>[] arreglos = new Comparendos[listaComparendos.getSize()]; boolean fin = false; Integer dato = null; Object datoS = null; String respuesta = ""; while( !fin ){ view.printMenu(); int option = lector.nextInt(); switch(option){ case 0: modelo = new Modelo(); modelo.loadComparendos(ruta); System.out.println(modelo); System.out.println("Se han cargado los datos"); System.out.println("Numero actual de elementos " + modelo.darTamano() + "\n---------"); System.out.println("Primer Elemento: " + modelo.retornoPrimero() + "\n---------"); System.out.println("Ultimo Elemento: " + modelo.retornoUltimo() + "\n---------"); break; case 1: modelo.copiarComparendos(); arreglos = modelo.copiarComparendos(); System.out.println("Se creo el arreglo copia"); System.out.println("Numero de comparendos copia: " + modelo.tamanioCopia()); break; case 2: long tiempoI = System.nanoTime(); modelo.shellsort(arreglos); long tiempoF = System.nanoTime(); double demora = (tiempoF - tiempoI)/ 1e6; modelo.primerosYUltimos(); System.out.println("TIEMPO DEMORA SHELLSORT: "+demora+" Micro Segundos"); break; case 3: long tiempoIN = System.nanoTime(); modelo.mergesort(arreglos); long tiempoFIN = System.nanoTime(); double demoraM = (tiempoFIN - tiempoIN)/ 1e6; modelo.primerosYUltimos(); System.out.println("TIEMPO DEMORA MERGESORT: "+demoraM+" Micro Segundos"); break; case 4: long tiempoINI = System.nanoTime(); modelo.quickSort(arreglos); long tiempoFINAL = System.nanoTime(); double demoraMI = (tiempoFINAL - tiempoINI)/ 1e6; modelo.primerosYUltimos(); System.out.println("TIEMPO DEMORA QUICKSORT: "+demoraMI+" Micro Segundos"); break; default: System.out.println("--------- \n Opcion Invalida !! \n---------"); break; } } } }
Markdown
UTF-8
1,634
2.765625
3
[]
no_license
# Introduction ![README](https://img.shields.io/badge/readme-release-blue.svg) This repository provides materials to be read before creating a repository in this **Data Driven Modelling UST GitHub**. You need to be included in the **Data Driven Modelling UST GitHub Member** list in order to have see **privite repositories** of this GitHib. Please contact the reppository owner for **write** access. # Label It is recommended to add a label to represent the current status | Status | Color | Example | Description | :--- | :--- | :--- | :--- | | Develpoment | Bright green | ![DOC](https://img.shields.io/badge/doc-dev-brightgreen.svg) | Document under development | | Work in progress | Yellow green | ![PROJ](https://img.shields.io/badge/proj-wip-yellowgreen.svg) | Project in progress | | Released | Blue | ![TOOL](https://img.shields.io/badge/tool-1.2-blue.svg) | Current version of a tool | # Access control Member privileges and repository read/ write permission are shown below. For repository creation, please contact the owners of this GitHub. ## Member privileges | Member type | Create repository and team | Add member/ collaborator | Comment on repository | | :--- | :---: | :---: | :---: | | Organization Owner | Y | Y | Y | | Repository Team Member | N | Y (repository dependent)| Y | | Organization Member | N | N | Y | ## Repository read/ write | Member type | Public repository | Privite repository | | :--- | :---: | :---: | | Organization Owner | R/W | R/W | | Repository Team Member | R/W | R/W (for the repository belongs to)| | Organization Member | R/W | R | # References and useful repositories
Java
UTF-8
2,004
2.0625
2
[]
no_license
package fr.epsi.verbes; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.w3c.dom.Text; public class ScoreActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_score); String partieId = getIntent().getStringExtra("partieId"); final TextView score = (TextView) findViewById(R.id.scoreDisplay); final TextView previousScore = (TextView) findViewById(R.id.scoreDisplayPrevious); RequestQueue queue = Volley.newRequestQueue(this); String url = "http://10.0.2.2:8000/partie/" + partieId + "/score"; final SharedPreferences sp = getSharedPreferences("app", MODE_PRIVATE); if (sp.contains("previousScore")) { previousScore.setText(sp.getString("previousScore", "0")); } else { previousScore.setVisibility(View.INVISIBLE); } StringRequest req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { score.setText(response); sp.edit().putString("previousScore", response).apply(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.w("Verbes/FetchScore", error.networkResponse.toString()); } }); queue.add(req); } public void onHomeButtonClicked(View v) { finish(); } }
C++
UTF-8
5,415
2.6875
3
[]
no_license
// // Created by zhoubin on 3/2/18. // #include <cstring> #include "Client.h" #include"ClientMes.h" #include"ServerMes.h" #include"Functools.h" #include<stdio.h> #define CLIENT_MES_SIZE 124 #define SERVER_MES_SIZE 124 using namespace std; void Client::Connect() { if(connect(m_connFd,(sockaddr *)&m_servAddr,sizeof(m_servAddr))==-1) { throw runtime_error(strerror(errno)); } } int Client::Socket() { m_connFd=socket(AF_INET,SOCK_STREAM,0); if(m_connFd==-1) { throw runtime_error(strerror(errno)); } return m_connFd; } void Client::MainMenu() { int choose; startup: cout<<"1:Login"<<endl; cout<<"2:Register"<<endl; cout<<"3:Quit"<<endl; cin>>choose; switch(choose) { case 1: { if(Login()) { SecondaryMenu(); } else { goto startup; } }break; case 2: { }break; case 3: { } } } void Client::Run() { MainMenu(); } bool Client::Login(){ Socket(); Connect(); cout<<"输入用户名:"<<endl; string userName; string userPw; cin>>userName; cout<<"输入密码:"<<endl; cin>>userPw; ClientMes loginMes; loginMes.m_command=0; string tmp=userName+"="+MD5(userPw).toStr(); strcpy(loginMes.m_message,tmp.c_str()); write(m_connFd,&loginMes,sizeof(loginMes)); ServerMes loginResult; int n=read(m_connFd,&loginResult,sizeof(loginResult)); if(loginResult.m_command==MES_SERVER_LOGSUCCESS) { cout<<loginResult.m_message<<endl; return true; } else { cout<<loginResult.m_message<<endl; close(m_connFd); return false; } } Client::~Client() { } Client::Client() { m_servAddr.sin_family=AF_INET; m_servAddr.sin_port=htons(8090); inet_pton(AF_INET,"127.0.0.1",&m_servAddr.sin_addr); m_isLogin=false; m_inRoom=false; m_roomId=-1; } void Client::SecondaryMenu() { Sstartup: cout<<"1.Get ChatRoomList"<<endl; cout<<"2.Quit"<<endl; int choose; cin>>choose; switch(choose) { case(1): { vector<string> chatroom_list; GetChatRoomList(chatroom_list); int chatroom_id=ChooseChatRoom(chatroom_list); if(JoinChatRoom(chatroom_id)) { StartChat(); goto Sstartup; } else { cout<<"Join chatroom fail!"<<endl; goto Sstartup; } } } } void Client::GetChatRoomList(vector<string> &chatList) { SendClientMes(m_connFd,MES_CLIENT_GETCHATLIST,""); ServerMes recvMes=RecvServerMes(m_connFd); string message(recvMes.m_message); string del("="); Functools::Split(message,del,chatList); } bool Client::JoinChatRoom(int chatRoomId) { string chatroom_id=to_string(chatRoomId); SendClientMes(m_connFd,MES_CLIENT_JOINCHAT,chatroom_id); ServerMes recvMes; recvMes=RecvServerMes(m_connFd); if(recvMes.m_command==MES_SERVER_JOINCHATSUCCESS) { return true; } else { return false; } } void Client::StartChat() { int epfd; epfd=epoll_create(2); epoll_event std_in,net_in; epoll_event result[2]; std_in.data.fd=fileno(stdin); std_in.events=EPOLLIN; net_in.data.fd=m_connFd; net_in.events=EPOLLIN; epoll_ctl(epfd,EPOLL_CTL_ADD,fileno(stdin),&std_in); epoll_ctl(epfd,EPOLL_CTL_ADD,m_connFd,&net_in); int nready=0; while(true) { nready=epoll_wait(epfd,result,2,-1); for(int i=0;i<nready;i++) { if(!(result[i].events&EPOLLIN)) continue; if(result[i].data.fd==fileno(stdin)) { if(!HandleStdInput()) return; } else if(result[i].data.fd==m_connFd) { ServerMes recvMes2=RecvServerMes(m_connFd);; if(recvMes2.m_command==MES_SERVER_CHATROOMMES) { cout<<"RECEIVE A MESSAGE"<<endl; PutOutMessage(recvMes2.m_message); } } } } } void Client::PutOutMessage(char *src) { string mes(src); auto pos=mes.find('='); string userName(mes.begin(),mes.begin()+pos); string message(mes.begin()+pos+1,mes.end()); cout<<userName<<":"<<message<<endl; } bool Client::HandleStdInput() { char std_mes[STD_INPUT_SIZE]; int nSize=read(fileno(stdin),std_mes,STD_INPUT_SIZE); std_mes[nSize-1]='\0'; if(strcmp(std_mes,"exit")==0) { cout<<"Exit The Chat"<<endl; LeaveChatRoom(); return false; } else { SendClientMes(m_connFd,MES_CLIENT_CHATMESSAGE,std_mes); return true; } } void Client::LeaveChatRoom() { ClientMes sendMes; SendClientMes(m_connFd,MES_CLIENT_LEAVECHAT); } int Client::ChooseChatRoom(const vector<string> &chatRoomList) { int chatroom_num=chatRoomList.size(); for(int i=0;i<chatroom_num;i++) { cout<<i+1<<":"<<chatRoomList[i]<<endl; } int choose; cin>>choose; return choose; }
C++
UTF-8
1,914
3.578125
4
[]
no_license
#include "string.h" #include "iostream" #include "stdio.h" #include <fstream> using namespace std; void Cezar(char string [500]) //Caesar { char key; int shift; cout << "Enter the shift: "; cin >> shift; for (int i = 0; i < strlen(string); i++) //ENCODING { if (string[i] != 32) { string[i] += (shift % 26); if (string[i] > 122) { string[i] = (string[i] % 122) + 96; } if (string[i] < 97) { string[i] += 230; } } } cout << "Encoded string: " << string << endl; for (int i = 0; i < strlen(string); i++) //DECODING { if (string[i] != 32) { string[i] -= shift % 26; while (string[i] < 97) { string[i] += 26; } } } cout << "Decoded string: " << string << endl; } void Vigenere(char string[500]) //Vigener { int a; cout.flush(); int j; cout << "Enter the secret word: "; cin >> a; char shift[100]; gets(shift); for (int i = 0; i < strlen(string); i++) //ENCODING { if (string[i] != 32) { j = i % strlen(shift); shift[j] = shift[j] % 96; string[i] += shift[j]; if (string[i] > 122) { string[i] = (string[i] % 122) + 96; } if (string[i] < 97) { string[i] += 230; } } } cout << "Encoded string: " << string << endl; for (int i = 0; i < strlen(string); i++) //DECODING { if (string[i] != 32) { j = i % strlen(shift); shift[j] = shift[j] % 96; string[i] -= shift[j]; while (string[i] < 96) { string[i] = string[i] + 26; } } } cout << "Decoded string: " << string << endl; } int main(int argc, char* argv[]) { setlocale(LC_ALL, "Russian"); char string[500]; cout << "Enter text: "; gets(string); int key; cout << "1 - Caesar" << endl << "2 - Vigener" << endl; cout << "Enter the encryption method: "; cin >> key; switch (key) { case 1: Cezar(string); break; case 2: Vigenere(string); break; } system("pause"); return 0; }
Java
UTF-8
375
1.789063
2
[]
no_license
package com.redhat.cdi.basic.resource; import com.redhat.cdi.util.Constants; import javax.ejb.Local; import javax.ws.rs.Consumes; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; @Local @Provider @Consumes(Constants.MEDIA_TYPE_TEST_XML) public interface EJBBookReader extends MessageBodyReader<EJBBook> { int getUses(); void reset(); }
Python
UTF-8
759
2.625
3
[]
no_license
import unittest import olap.xmla.utils as utils class TestUtils(unittest.TestCase): def testaslist(self): for x in ["Blah", None, {}, 7, (), set([1,2,3]), True]: self.assertIsInstance( utils.aslist(x), list) x = ["blah"] self.assertEqual( utils.aslist(x), x) def testschemaNameToMethodName(self): mn=utils.schemaNameToMethodName self.assertEqual(mn("DBSCHEMA_palim"), "getDBSchemaPalim") self.assertEqual(mn("MDSCHEMA_palim"), "getMDSchemaPalim") self.assertEqual(mn("DISCOVER_palim"), "getPalim") self.assertEqual(mn("I_KNOW_WHAT_YOU_DID_LAST_SPRINGBREAK"), "getIKnowWhatYouDidLastSpringbreak") if __name__ == "__main__": unittest.main()
C#
UTF-8
677
3.671875
4
[ "MIT" ]
permissive
namespace Tutorial.Introduction { using System; internal static partial class Functions { internal static int Add(int a, int b) // Pure. { return a + b; } internal static int AddWithLog(int a, int b) // Impure. { int result = a + b; Console.WriteLine("{0} + {1} => {2}", a, b, result); return result; } } internal static partial class Functions { internal static int AddWithLog(int a, int b, Action<int, int, int> logger) { int result = a + b; logger(a, b, result); return result; } } }
Java
UTF-8
12,337
1.53125
2
[]
no_license
package com.hongshi.wuliudidi.activity; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.hongshi.wuliudidi.DidiApp; import com.hongshi.wuliudidi.R; import com.hongshi.wuliudidi.adapter.AccountAdapter; import com.hongshi.wuliudidi.cashier.TiXianActivity; import com.hongshi.wuliudidi.impl.ChildAfinalHttpCallBack; import com.hongshi.wuliudidi.model.AcctInfoVO; import com.hongshi.wuliudidi.model.MoneyAccountModel; import com.hongshi.wuliudidi.model.TradeRecordVO; import com.hongshi.wuliudidi.model.WalletModel; import com.hongshi.wuliudidi.params.GloableParams; import com.hongshi.wuliudidi.plugin.Util.PluginUtil; import com.hongshi.wuliudidi.plugin.bean.PluginParams; import com.hongshi.wuliudidi.qr.ConfirmGoodsActivity; import com.hongshi.wuliudidi.utils.CloseRefreshTask; import com.hongshi.wuliudidi.utils.ToastUtil; import com.hongshi.wuliudidi.utils.Util; import com.hongshi.wuliudidi.view.DiDiTitleView; import com.hongshi.wuliudidi.view.TextViewWithDrawable; import net.tsz.afinal.http.AjaxParams; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * @author huiyuan * Created by huiyuan on 2017/6/5. */ public class CashAccountActivity extends Activity implements View.OnClickListener { private DiDiTitleView cash_account_title; private PullToRefreshListView mPullToRefreshListView; private ListView detailListview; private AccountAdapter accountAdapter; private TextViewWithDrawable withdrawal,scan_payment,bank_card; private ImageView time_shift_detail,no_data_tip; private TextView account_money; private int currentPage = 1; private boolean isEnd = false; private BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if("com.action.cash".equals(action)){ getSummaryData(); sessionLoadData(true); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cash_account_activity); initViews(); getSummaryData(); sessionLoadData(true); } private void initViews(){ cash_account_title = (DiDiTitleView) findViewById(R.id.cash_account_title); cash_account_title.setBack(this); cash_account_title.setTitle("现金余额"); account_money = (TextView) findViewById(R.id.account_money); withdrawal = (TextViewWithDrawable) findViewById(R.id.withdrawal); scan_payment = (TextViewWithDrawable) findViewById(R.id.scan_payment); bank_card = (TextViewWithDrawable) findViewById(R.id.bank_card); time_shift_detail = (ImageView) findViewById(R.id.time_shift_detail); no_data_tip = (ImageView) findViewById(R.id.no_data_tip); withdrawal.setOnClickListener(this); scan_payment.setOnClickListener(this); bank_card.setOnClickListener(this); time_shift_detail.setOnClickListener(this); mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.account_detail_list); mPullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH); mPullToRefreshListView.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载"); mPullToRefreshListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载"); mPullToRefreshListView.getLoadingLayoutProxy(false, true).setReleaseLabel("松开加载更多"); mPullToRefreshListView.getLoadingLayoutProxy(true, false).setPullLabel("松开刷新"); mPullToRefreshListView.getLoadingLayoutProxy(true, false).setRefreshingLabel("刷新中"); mPullToRefreshListView.getLoadingLayoutProxy(true, false).setReleaseLabel("下拉刷新"); detailListview = mPullToRefreshListView.getRefreshableView(); mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { if (mPullToRefreshListView.isRefreshing()) { if (mPullToRefreshListView.isHeaderShown()){ currentPage = 1; sessionLoadData(true); } else if (mPullToRefreshListView.isFooterShown()) { // 加载更多 if(isEnd){ Toast.makeText(CashAccountActivity.this, "已经是最后一页", Toast.LENGTH_SHORT).show(); CloseRefreshTask closeRefreshTask = new CloseRefreshTask(mPullToRefreshListView); closeRefreshTask.execute(); return; } currentPage = currentPage + 1; sessionLoadData(false); } } } }); accountAdapter = new AccountAdapter(CashAccountActivity.this,accountDetailList); detailListview.setAdapter(accountAdapter); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.action.cash"); registerReceiver(mRefreshBroadcastReceiver,intentFilter); } private final String account_detail_url = GloableParams.HOST + "tradeRecord/list.do?"; // private final String account_detail_url = "http://192.168.158.150:8080/gwcz/tradeRecord/list.do?"; private List<TradeRecordVO> accountDetailList = new ArrayList<>(); private void sessionLoadData(final boolean isRefresh){ if(isRefresh){ currentPage = 1; } AjaxParams params = new AjaxParams(); params.put("acctType", "1"); params.put("tradeType",type); params.put("beginTime", start_time); params.put("endTime",end_time); params.put("currentPage", ""+currentPage); params.put("pageSize","10"); DidiApp.getHttpManager().sessionPost(CashAccountActivity.this, account_detail_url, params, new ChildAfinalHttpCallBack() { @Override public void data(String t) { JSONObject jsonObject; try { if(isRefresh){ if(accountDetailList.size() > 0){ accountDetailList.clear(); } isEnd = false; mPullToRefreshListView.onRefreshComplete(); } jsonObject = new JSONObject(t); JSONObject body = jsonObject.getJSONObject("body"); String all = body.getString("items"); //判断是否还有下一页 isEnd = body.getBoolean("end"); currentPage = body.getInt("currentPage"); List<TradeRecordVO> tempList = JSON.parseArray(all,TradeRecordVO.class); accountDetailList.addAll(tempList); if(accountDetailList.size() > 0){ no_data_tip.setVisibility(View.GONE); mPullToRefreshListView.setVisibility(View.VISIBLE); }else { no_data_tip.setImageResource(R.drawable.driver_transit_record_null); no_data_tip.setVisibility(View.VISIBLE); } accountAdapter.notifyDataSetChanged(); mPullToRefreshListView.onRefreshComplete(); } catch (JSONException e) { mPullToRefreshListView.onRefreshComplete(); } } @Override public void onFailure(String errCode, String errMsg, Boolean errSerious) { mPullToRefreshListView.onRefreshComplete(); } }); } private final String account_summary_url = GloableParams.HOST + "carrier/app/acct/acctInfo.do"; // private final String account_summary_url = "http://192.168.158.150:8080/gwcz/carrier/app/acct/acctInfo.do"; private void getSummaryData(){ AjaxParams params = new AjaxParams(); params.put("acctType","1"); DidiApp.getHttpManager().sessionPost(CashAccountActivity.this, account_summary_url, params, new ChildAfinalHttpCallBack() { @Override public void onFailure(String errCode, String errMsg, Boolean errSerious) { Toast.makeText(CashAccountActivity.this,errMsg,Toast.LENGTH_LONG).show(); } @Override public void data(String t) { try { JSONObject jsonObject = new JSONObject(t); String all = jsonObject.getString("body"); AcctInfoVO acctInfoVO = JSON.parseObject(all,AcctInfoVO.class); account_money.setText(acctInfoVO.getBalance()); } catch (JSONException e) { e.printStackTrace(); } } }); } private void doWithdrawl(){ String cashCode = getSharedPreferences("config",MODE_PRIVATE).getString("cifUserId",""); if(cashCode == null || "".equals(cashCode)){ return; } if(cashCode != null && cashCode.length() > 0){ HashMap<String,String> params = new HashMap<>(); params.put("userId", cashCode); // PluginUtil.startPlugin(CashAccountActivity.this, // PluginParams.MY_CASH_ACTION, PluginParams.MY_CASH, params); Intent intent = new Intent(CashAccountActivity.this, TiXianActivity.class); intent.putExtra("params",params); startActivity(intent); }else{ ToastUtil.show(CashAccountActivity.this, "资金信息获取失败"); } } @Override public void onClick(View v) { switch (v.getId()){ case R.id.withdrawal: doWithdrawl(); break; case R.id.scan_payment: Intent scannerIntent = new Intent(this, ConfirmGoodsActivity.class); scannerIntent.putExtra("from","cash_activity"); startActivity(scannerIntent); break; case R.id.bank_card: Intent intent0 = new Intent(this, MyBankcardsActivity.class); startActivity(intent0); break; case R.id.time_shift_detail: Intent intent = new Intent(CashAccountActivity.this,FilterActivity.class); intent.putExtra("account_value",1); startActivityForResult(intent,1); break; default: break; } } private String start_time = ""; private String end_time = ""; private String type = ""; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); if(requestCode == 1 && data != null){ start_time = data.getStringExtra("start_time"); end_time = data.getStringExtra("end_time"); String type_ = data.getStringExtra("type"); if("消费".equals(type_)){ type = "1"; }else if("提现".equals(type_)){ type = "2"; }else if("结算".equals(type_)){ type = "3"; }else { type = ""; } sessionLoadData(true); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mRefreshBroadcastReceiver); } }
Go
UTF-8
2,326
2.515625
3
[ "Apache-2.0" ]
permissive
package command import ( "testing" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/ShotaKitazawa/minecraft-bot/pkg/botplug" "github.com/ShotaKitazawa/minecraft-bot/pkg/domain/i18n" "github.com/ShotaKitazawa/minecraft-bot/pkg/mock" ) var ( loggerForTestCommandTitle = logrus.New() ) func TestCommandTitle(t *testing.T) { t.Run(`ReceiveMessage()`, func(t *testing.T) { t.Run(`normal`, func(t *testing.T) { t.Run(`1 user login`, func(t *testing.T) { p := PluginTitle{ Logger: loggerForTestCommandTitle, Rcon: &mock.RconClientMockValid{ LoginUsernames: []string{mock.MockUserNameValue}, }, } output := p.ReceiveMessage(&botplug.MessageInput{ Messages: []string{`title`, `test`}, }) assert.Equal(t, 1, len(output.Queue)) result, ok := output.Queue[0].(string) assert.True(t, ok) assert.Equal(t, i18n.T.Sprintf(i18n.MessageSentMessage, mock.MockUserNameValue), result) }) t.Run(`no users login`, func(t *testing.T) { p := PluginTitle{ Logger: loggerForTestCommandList, Rcon: &mock.RconClientMockValid{}, } output := p.ReceiveMessage(&botplug.MessageInput{ Messages: []string{`title`, `test`}, }) assert.Equal(t, 1, len(output.Queue)) result, ok := output.Queue[0].(string) assert.True(t, ok) assert.Equal(t, i18n.T.Sprintf(i18n.MessageNoLoginUserExists), result) }) }) t.Run(`abnormal (input)`, func(t *testing.T) { p := PluginTitle{ Logger: loggerForTestCommandList, Rcon: &mock.RconClientMockValid{}, } output := p.ReceiveMessage(&botplug.MessageInput{ Messages: []string{}, // abnormal (len < 2) }) assert.Equal(t, 1, len(output.Queue)) result, ok := output.Queue[0].(string) assert.True(t, ok) assert.Equal(t, i18n.T.Sprintf(i18n.MessageInvalidArguments), result) }) t.Run(`abnormal (rcon)`, func(t *testing.T) { p := PluginTitle{ Logger: loggerForTestCommandList, Rcon: &mock.RconClientMockInvalid{}, // abnormal } output := p.ReceiveMessage(&botplug.MessageInput{ Messages: []string{`title`, `test`}, }) assert.Equal(t, 1, len(output.Queue)) result, ok := output.Queue[0].(string) assert.True(t, ok) assert.Equal(t, i18n.T.Sprintf(i18n.MessageError), result) }) }) }
Java
UTF-8
540
1.664063
2
[]
no_license
package com.bonc.product.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import com.bonc.product.domain.ActivityDetailTmp; @RepositoryRestResource(collectionResourceRel = "activitydetailtmp", path = "activitydetailtmp") public interface ActivityDetailTmpRepository extends JpaRepository<ActivityDetailTmp, Long> , JpaSpecificationExecutor<ActivityDetailTmp>{ }
Java
UTF-8
550
2.03125
2
[]
no_license
package gpath.store; import java.util.Comparator; import gpath.store.statistics.LabelStatistics; import gpath.store.statistics.Statistics; public interface StatisticsGraphStore extends GraphStore{ public Statistics getVertexStatistics(String labelname); public Statistics getEdgeStatistics(String labelname); public <T extends Comparator<byte[]>> void prepareVertexStatistics(Class<T> comparatorClass, String labelName); public <T extends Comparator<byte[]>> void prepareEdgeStatistics(Class<T> comparatorClass, String labelName); }
Python
UTF-8
104
3.84375
4
[]
no_license
word = input("Enter a word: ") number = int(input("Enter a number: ")) print(word[0] + word[-number:])
Markdown
UTF-8
3,882
2.75
3
[]
no_license
--- description: "Recipe of Award-winning Vegetable soup" title: "Recipe of Award-winning Vegetable soup" slug: 1534-recipe-of-award-winning-vegetable-soup date: 2021-03-09T22:54:34.189Z image: https://img-global.cpcdn.com/recipes/10baa69c263b174b/680x482cq70/vegetable-soup-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/10baa69c263b174b/680x482cq70/vegetable-soup-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/10baa69c263b174b/680x482cq70/vegetable-soup-recipe-main-photo.jpg author: Emma Ellis ratingvalue: 4.1 reviewcount: 13634 recipeingredient: - "2 quarts stock" - "1/2 cup diced raw carrots" - "1/2 cup diced celery" - "11/2 cups diced potatoes" - " Salt" - "2 cups tomatoes" - "1/2 cup canned peas" - "1 onion cut" - " Pepper" - " Onion seasoning" - " Celery salt" recipeinstructions: - "Heat stock add vegetables simmer 1 hour" - "Add seasoning" - "Serve hot" categories: - Recipe tags: - vegetable - soup katakunci: vegetable soup nutrition: 185 calories recipecuisine: American preptime: "PT25M" cooktime: "PT54M" recipeyield: "1" recipecategory: Lunch --- ![Vegetable soup](https://img-global.cpcdn.com/recipes/10baa69c263b174b/680x482cq70/vegetable-soup-recipe-main-photo.jpg) Hey everyone, it's me, Dave, welcome to my recipe site. Today, we're going to make a distinctive dish, vegetable soup. One of my favorites. This time, I am going to make it a little bit unique. This is gonna smell and look delicious. Vegetable soup is one of the most popular of recent trending foods on earth. It is simple, it is quick, it tastes yummy. It's enjoyed by millions daily. They're nice and they look fantastic. Vegetable soup is something that I have loved my entire life. Vegetable soup is a common soup prepared using vegetables and leaf vegetables as primary ingredients. It dates to ancient history, and is a mass-produced food product in contemporary times. Vegetable soup is prepared using vegetables, leafy greens, mushrooms. Vegetable Soup - This Vegetable Soup has become one of my most popular soup recipes and for good reason! To begin with this particular recipe, we must prepare a few ingredients. You can cook vegetable soup using 11 ingredients and 3 steps. Here is how you can achieve that. <!--inarticleads1--> ##### The ingredients needed to make Vegetable soup: 1. Prepare 2 quarts stock 1. Get 1/2 cup diced raw carrots 1. Prepare 1/2 cup diced celery 1. Prepare 11/2 cups diced potatoes 1. Prepare Salt 1. Take 2 cups tomatoes 1. Prepare 1/2 cup canned peas 1. Make ready 1 onion cut 1. Make ready Pepper 1. Prepare Onion seasoning 1. Take Celery salt Get your five servings of vegetables in one bowl with these delicious and healthy vegetable soup recipes. Potato soup, gazpacho, butternut squash soup—find the best recipes for all your favorite vegetable soups. It calms the mind and soothes the soul. And the simple addition of beans or whole grains can turn your masterpiece into an incredibly healthy soup. <!--inarticleads2--> ##### Instructions to make Vegetable soup: 1. Heat stock add vegetables simmer 1 hour 1. Add seasoning 1. Serve hot It calms the mind and soothes the soul. And the simple addition of beans or whole grains can turn your masterpiece into an incredibly healthy soup. These soups make it easy to eat your veggies. This homemade vegetable soup is healthy, easy to make, and tastes fantastic. When we&#39;re looking for a comforting meal packed with vegetables, this easy veggie soup is where we turn. So that's going to wrap this up with this special food vegetable soup recipe. Thanks so much for reading. I'm confident you will make this at home. There is gonna be interesting food in home recipes coming up. Don't forget to save this page on your browser, and share it to your loved ones, colleague and friends. Thanks again for reading. Go on get cooking!
Java
UTF-8
5,092
2.09375
2
[]
no_license
package com.zoptal.chinamoonbuffet.JsonClasses; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import com.zoptal.chinamoonbuffet.adapter.CustomListAdapter; import com.zoptal.chinamoonbuffet.url.RegisterUrl; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class Json_MenuData extends AsyncTask<String, String, String> { Context context; String coderesponse; ProgressDialog loading; public static Model_MenuData model_menudata=new Model_MenuData(); public CustomListAdapter adapter_customlist; public Json_MenuData(Context context,CustomListAdapter adapter_customlist) { // TODO Auto-generated constructor stub this.context = context; this.adapter_customlist=adapter_customlist; } @Override protected void onPreExecute() { super.onPreExecute(); loading = new ProgressDialog(context); loading.setMessage("loading"); loading.show(); } @Override protected String doInBackground(String... params) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( RegisterUrl.menu_data); try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("category",params[0])); nameValuePairs.add(new BasicNameValuePair("search",params[1])); nameValuePairs.add(new BasicNameValuePair("page_no",params[2])); nameValuePairs.add(new BasicNameValuePair("no_of_post",params[3])); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Log.e("paramerts---",""+nameValuePairs); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { String result1 = EntityUtils.toString(entity); Log.e("menu data result------",""+result1.trim()); model_menudata = new Model_MenuData(); ArrayList<MenuData> menudata = new ArrayList<MenuData>(); JSONObject main_obj = new JSONObject(result1); coderesponse=main_obj.getString("code"); JSONArray ary_products =main_obj.getJSONArray("data"); for (int i = 0; i < ary_products.length(); i++) { JSONObject obj = ary_products.getJSONObject(i); String id = obj.getString("id"); String title = obj.getString("title"); String category = obj.getString("category"); String category_name = obj.getString("category_name"); String image = obj.getString("image"); String description = obj.getString("description"); String price = obj.getString("price"); String posted = obj.getString("posted"); MenuData f = new MenuData(); f.setId(id); f.setTitle(title); f.setCategory(category); f.setCategoryname(category_name); f.setImage(image); f.setDescription(description); f.setPrice(price); f.setPosted(posted); menudata.add(f); } model_menudata.setAl_menudata(menudata); } } catch (Exception e) { Log.e("==+result menudata===", "======" + e); } return coderesponse; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); loading.dismiss(); ArrayList<MenuData> menudataArrayList=new ArrayList<>(); ArrayList<MenuData> menudatalist= adapter_customlist.getCurrentList(); for (int i = 0; i <model_menudata.getAl_menudata().size(); i++) { boolean check=true; for (int j = 0; j< menudatalist.size() ; j++) { if (menudatalist.get(j).getId().equalsIgnoreCase(model_menudata.getAl_menudata().get(i).getId()) ) { check=false; } } if(check) { menudataArrayList.add(model_menudata.getAl_menudata().get(i)); } } adapter_customlist.setAddList(menudataArrayList); } }
Python
UTF-8
1,421
3.359375
3
[ "MIT" ]
permissive
from scope import Scope class Frame(object): def __init__(self, name, global_scope): self.name = name scope_name = '{0}_00'.format(name) self.current_scope = self.create_new_scope(scope_name, global_scope) self.scopes = [] self.scopes.append(self.current_scope) @staticmethod def create_new_scope(name, global_scope): """ Helper function to create new scope :param name: :param global_scope: :return: """ curr_scope = Scope(name, global_scope) return curr_scope def add_scope(self): """ Function used to add a new scope :return None: """ val = int(self.current_scope[-2:]) + 1 name = '{}_{:02d}'.format(self.current_scope.name[:-2], val) self.current_scope = self.create_new_scope(name, self.current_scope) self.scopes.append(self.current_scope) def del_scope(self): """ Function used to delete a scope :return: """ temp_scope = self.current_scope self.current_scope = temp_scope.parent_scope del temp_scope self.scopes.pop(len(self.scopes) - 1) def __contains__(self, key): """ Function used to see if a current key value exists in the current scope :param key: :return: """ return key in self.current_scope
Markdown
UTF-8
5,829
2.796875
3
[ "Apache-2.0" ]
permissive
### Specification ||| | --- | --- | |Module name| dir-overlay-install | |Supports rollback|yes| |Requires restart|no| |Artifact generation script|yes| |Full system updater|no| |Source code|[Update Module](https://github.com/mirzak/dir-overlay-install/blob/master/modules/dir-overlay-install), [Artifact Generator](https://github.com/mirzak/dir-overlay-install/blob/master/modules-artifact-gen/dir-overlay-install-artifact-gen)| #### Prerequisites Generating Mender Update modules requires you to have the Mender Artifact tool installed on your system. Instructions on how to install can be found [here](https://docs.mender.io/artifacts/modifying-a-mender-artifact#compiling-mender-artifact). #### Functional description The Directory Overlay Install Update Module installs a user defined file tree structure into a given destination directory in the target. Before the deploy into the destination folder on the device, the Update Module will take a backup copy of the current contents, allowing for restore of it using the rollback mechanism of the Mender client if something goes wrong. The Update Module will also delete the current installed content that was previously installed using the same module, this means that each deployment is self contained and there is no residues left on the system from the previous deployment. ### Device requirements The `dir-overlay-install` module will store state information in `/var/lib/mender`, and that is: - Manifest files of current and previous installation - list of files - Backup of current installed files based on previous manifest, which is used in case of roll-back Sample directory layout: ```bash $ ls /var/lib/mender/dir-overlay-install/ backup.tar manifest manifest.prev ``` The `dir-overlay-install` directory is created by the module. ### Installation on device This Update Module is out-of-the-box for Mender client 2.0 and later versions. If you need to install from sources, you can download the latest version directly to your device with: mkdir -p /usr/share/mender/modules/v3 && wget -P /usr/share/mender/modules/v3 https://raw.githubusercontent.com/mirzak/dir-overlay-install/master/modules/dir-overlay-install && chmod +x /usr/share/mender/modules/v3/dir-overlay-install ### Artifact creation For convenience, an Artifact generator tool `dir-overlay-install-artifact-gen` is provided along the module. This tool will generate Mender Artifacts in the same format that the Update Module expects them. To download `dir-overlay-install-artifact-gen`, run the following: ```bash wget https://raw.githubusercontent.com/mirzak/dir-overlay-insall/master/modules-artifact-gen/dir-overlay-install-artifact-gen ``` Make it executable by running, ```bash chmod +x dir-overlay-install-artifact-gen ``` Lets create example root filesystem content to deploy, ```bash mkdir -p rootfs_overlay/etc rootfs_overlay/usr/bin rootfs_overlay/usr/share/app touch rootfs_overlay/etc/app.conf touch rootfs_overlay/usr/bin/app touch rootfs_overlay/usr/share/app/data.txt ``` And the result should look like this: ```bash $ tree rootfs_overlay/ rootfs_overlay/ ├── etc │   └── app.conf └── usr ├── bin │   └── app └── share └── app └── data.txt 5 directories, 3 files ``` You can now generate your Artifact using the following command: ```bash ARTIFACT_NAME="my-update-1.0" DEVICE_TYPE="my-device-type" OUTPUT_PATH="my-update-1.0.mender" DEST_DIR="/" OVERLAY_TREE="rootfs_overlay" ./dir-overlay-install-artifact-gen -n ${ARTIFACT_NAME} -t ${DEVICE_TYPE} -d ${DEST_DIR} -o ${OUTPUT_PATH} ${OVERLAY_TREE} ``` - `ARTIFACT_NAME` - The name of the Mender Artifact - `DEVICE_TYPE` - The compatible device type of this Mender Artifact - `OUTPUT_PATH` - The path where to place the output Mender Artifact. This should always have a `.mender` suffix - `DEST_DIR` - The path on target device where content of `OVERLAY_TREE` will be installed. - `OVERLAY_TREE` - The path a folder containing the contents to be installed on top of the `DEST_DIR` on the device in the update. You can either deploy this Artifact in managed mode with the Mender server as described in [Deploy to physical devices](https://docs.mender.io/getting-started/deploy-to-physical-devices#upload-the-artifact-to-the-server) or by using the Mender client only in [Standalone deployments](https://docs.mender.io/architecture/standalone-deployments?target=_blank). #### Artifact technical details The Mender Artifact used by this Update Module has three payload files: - `update.tar` - a tarball containing all the files to be deployed - `dest_dir` - a regular file with the `DEST_DIR` in plain text - `manifest` - a regular file with a list of files installed in plain text The Mender Artifact contents will look like: ```bash Artifact my-update-1.0.mender generated successfully: Mender artifact: Name: my-update-1.0 Format: mender Version: 3 Signature: no signature Compatible devices: '[my-device-type]' Provides group: Depends on one of artifact(s): [] Depends on one of group(s): [] State scripts: Updates: 0: Type: dir-overlay-install Provides: Nothing Depends: Nothing Metadata: Nothing Files: name: update.tar size: 10240 modified: 2019-04-01 12:01:41 +0000 UTC checksum: fabfd7f6739d35130dd05dbab42ff7fe8baa76fea22f134b254671bd52604807 Files: name: dest_dir size: 2 modified: 2019-04-01 12:01:41 +0000 UTC checksum: f465c3739385890c221dff1a05e578c6cae0d0430e46996d319db7439f884336 Files: name: manifest size: 48 modified: 2019-04-01 12:01:41 +0000 UTC checksum: fc582174946ec48e2782ed9357e9d4389cc0e2a3bfbc261b418d4fd5a326d472 ```
Markdown
UTF-8
1,317
2.578125
3
[]
no_license
# Parsing-Solving-PlaningProblems This is the third step of my work related to MDPs and some famous solvers. In previous repositories I took a simple 'Maze-like' problem, I coded both a declarative and a generative description of the problem and I proposed some solvers to find the solution. Some of them use the declarative version whereas the most complex algorithms use the generative one. However, in this new repository I am trying to go even further. My intentions are: 1) Collect some famous problems to test a brandnew algorithm and compare the results with other state-of-the-art solvers. For some reason, I have decided to use PPDDL language to describe the problems... Honestly, I do not know why because RDDL is the most updated descriptor language. In fact, ICAPS and the International Probabilistic Planning Competition is not providing the PPDDL description since no competitor asked for it. 2) Develop a parser to read and compile .ppddl files. The final code shall understand the description of the problems and create a generative model of the problem. In other words, a kind of black box that can be used by the solvers. IMPORTANT: I must thank Thiagopbueno and his repositories for providing the skeleton of the parser. 3) Implement several solvers and do some tests.
Java
UTF-8
617
2.6875
3
[]
no_license
package stuff; public class Weapon { //Completely pointless at the moment private int x , y; private boolean visible; private boolean possessed; public void setPosition(){ x = 387; y = 287; } public int getX() { return x; } public int getY() { return y; } public int getDimensions() { return 25; } public void setVisible(boolean visible){ this.visible = visible; } public boolean isVisible(){ return visible; } public boolean isPossessed(){ return possessed; } }
C++
UTF-8
573
3.1875
3
[ "BSD-3-Clause" ]
permissive
#include "ActionStack.h" #include <exception> using namespace std; ActionStack::ActionStack() { current = -1; } ActionStack::~ActionStack() { } void ActionStack::push(Action* a) { this->elems.push_back(a); this->current++; this->size = this->current+1; } Action* ActionStack::pop() { if (current == -1) { throw exception{ "Can't undo anymore!" }; this->current--; } return this->elems[current]; } void ActionStack::increment() { this->current++; if (this->current >= this->size) { this->current--; throw exception{ "Can't redo anymore!" }; } }
C++
UTF-8
765
3.390625
3
[]
no_license
//Problem Link:- https://leetcode.com/problems/search-a-2d-matrix/ #include<bits/stdc++.h> using namespace std; class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int left = 0; const int n = matrix.size(); const int m = matrix[0].size(); int right = n*m - 1; while (left <= right){ int mid = left + (right - left)/2; int x = mid / m; int y = mid % m; if (matrix[x][y] == target){ return true; } else if (matrix[x][y] > target){ right = mid - 1; } else{ left = mid +1; } } return false; } };
C++
UTF-8
2,601
3.453125
3
[]
no_license
// // directedHashGraph.h // Tarjan // // Created by Alex Zabrodskiy on 4/24/17. // Copyright © 2017 Alex Zabrodskiy. All rights reserved. // // Implements the graph class in an ajacency list representation // #ifndef directedHashGraph_h #define directedHashGraph_h #include "graph.h" #include <unordered_set> #include <unordered_map> using namespace std; template <class V> class DirectedHashGraph: public Graph<V>{ private: std::unordered_map<V, std::unordered_set<V>* > edges; public: void insertVertex(V vertex); void insertEdge(V from, V to); const std::unordered_set<V>& getNeighbors(V vertex) const; std::unordered_set<V>* getVerticies() const; inline int size() const {return (int) edges.size();} void removeVertex(V vertex); void removeEdge(V from, V to); void bulkInsertEdges(const initializer_list<pair<V,V>>& list); bool edgeExists(V from, V to) const ; virtual ~DirectedHashGraph(){ //Delete the unordered sets of verticies for(auto& vertex: edges) delete vertex.second; } }; template<class V> void DirectedHashGraph<V>::insertVertex(V vertex){ if(edges.count(vertex) == 0) //If the vertex is not in the graph, add it edges[vertex] = new unordered_set<V>; } template<class V> void DirectedHashGraph<V>::insertEdge(V from, V to){ if(edges.count(from) == 0) //If the vertex is not in the graph, add it edges[from] = new unordered_set<V>; if(edges.count(to) == 0) //If the vertex is not in the graph, add it edges[to] = new unordered_set<V>; edges[from]->insert(to); } template<class V> const unordered_set<V>& DirectedHashGraph<V>::getNeighbors(V vertex) const { return *(edges.at(vertex)); } template<class V> unordered_set<V>* DirectedHashGraph<V>::getVerticies() const { unordered_set<V>* vertices = new unordered_set<V>; for(auto& vertex: edges) vertices->insert(vertex.first); return vertices; } template<class V> void DirectedHashGraph<V>::removeVertex(V vertex){ edges.erase(vertex); } template<class V> void DirectedHashGraph<V>::removeEdge(V from, V to){ edges[from]->erase(to); } template<class V> void DirectedHashGraph<V>::bulkInsertEdges(const initializer_list<pair<V,V>>& list){ for(auto& pair: list) insertEdge(pair.first, pair.second); } template<class V> bool DirectedHashGraph<V>::edgeExists(V from, V to) const { return (edges.at(from)->count(to)) != 0; } #endif /* directedHashGraph_h */
Ruby
UTF-8
1,913
2.859375
3
[ "MIT" ]
permissive
class Volunteer attr_accessor :name, :project_id attr_reader :id def initialize(attributes) @name = attributes.fetch(:name).downcase.capitalize! @project_id = attributes.fetch(:project_id) @id = attributes.fetch(:id) end def self.all returned_volunteers = DB.exec("SELECT * FROM volunteers;") volunteers = [] returned_volunteers.each do |volunteer| name = volunteer.fetch("name") project_id = volunteer.fetch("project_id") id = volunteer.fetch("id") volunteers.push(Volunteer.new({:name => name, :project_id => project_id, :id => id})) end volunteers end def save new_volunteer = DB.exec("INSERT INTO volunteers (name, project_id) VALUES ('#{@name}', #{@project_id.to_i}) RETURNING id;") @id = new_volunteer.first.fetch("id").to_i end def ==(volunteer_to_compare) (self.name.downcase.eql?(volunteer_to_compare.name.downcase))&&(self.project_id.to_i.eql?(volunteer_to_compare.project_id.to_i)) end def self.find(id) volunteer = DB.exec("SELECT * FROM volunteers WHERE id = #{id};").first name = volunteer.fetch("name") project_id = volunteer.fetch("project_id") id = volunteer.fetch("id").to_i Volunteer.new({:name => name, :project_id => project_id, :id => id}) end def self.find_by_project(id) returned_volunteers = DB.exec("SELECT * FROM volunteers WHERE project_id = #{id};") volunteers = [] returned_volunteers.each do |volunteer| name = volunteer.fetch("name") project_id = volunteer.fetch("project_id") id = volunteer.fetch("id").to_i volunteers.push(Volunteer.new({:name => name, :project_id => project_id, :id => id})) end volunteers end def update(new_attributes) @name = new_attributes.fetch(:name) DB.exec("UPDATE volunteers SET name = '#{@name}' WHERE id = #{@id}") end def delete DB.exec("DELETE FROM volunteers WHERE id =#{@id};") end def self.clear DB.exec("DELETE FROM volunteers *;") end end
C++
UTF-8
2,051
2.671875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/testapp.h> #include <vespa/messagebus/blob.h> #include <vespa/messagebus/blobref.h> using mbus::Blob; using mbus::BlobRef; TEST_SETUP(Test); Blob makeBlob(const char *txt) { Blob b(strlen(txt) + 1); strcpy(b.data(), txt); return b; } BlobRef makeBlobRef(const Blob &b) { return BlobRef(b.data(), b.size()); } Blob returnBlob(Blob b) { return b; } BlobRef returnBlobRef(BlobRef br) { return br; } int Test::Main() { TEST_INIT("blob_test"); // create a blob Blob b = makeBlob("test"); EXPECT_TRUE(b.size() == strlen("test") + 1); EXPECT_TRUE(strcmp("test", b.data()) == 0); // create a ref to a blob BlobRef br = makeBlobRef(b); EXPECT_TRUE(br.size() == strlen("test") + 1); EXPECT_TRUE(strcmp("test", br.data()) == 0); EXPECT_TRUE(b.data() == br.data()); // non-destructive copy of ref BlobRef br2 = returnBlobRef(br); EXPECT_TRUE(br.size() == strlen("test") + 1); EXPECT_TRUE(strcmp("test", br.data()) == 0); EXPECT_TRUE(b.data() == br.data()); EXPECT_TRUE(br2.size() == strlen("test") + 1); EXPECT_TRUE(strcmp("test", br2.data()) == 0); EXPECT_TRUE(b.data() == br2.data()); br = br2; EXPECT_TRUE(br.size() == strlen("test") + 1); EXPECT_TRUE(strcmp("test", br.data()) == 0); EXPECT_TRUE(b.data() == br.data()); EXPECT_TRUE(br2.size() == strlen("test") + 1); EXPECT_TRUE(strcmp("test", br2.data()) == 0); EXPECT_TRUE(b.data() == br2.data()); // destructive copy of blob Blob b2 = returnBlob(std::move(b)); EXPECT_EQUAL(0u, b.size()); EXPECT_TRUE(b.data() == 0); EXPECT_TRUE(b2.size() == strlen("test") + 1); EXPECT_TRUE(strcmp("test", b2.data()) == 0); b.swap(b2); EXPECT_EQUAL(0u, b2.size()); EXPECT_TRUE(b2.data() == 0); EXPECT_TRUE(b.size() == strlen("test") + 1); EXPECT_TRUE(strcmp("test", b.data()) == 0); TEST_DONE(); }
C#
UTF-8
1,578
2.5625
3
[]
no_license
using System.ComponentModel; using System.Runtime.CompilerServices; using SQLite.Net.Attributes; namespace PermisC.Models { public class Tracteur : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; [PrimaryKey, AutoIncrement] public int ID { get; set; } string immatriculation; public string Immatriculation { get { return immatriculation; } set { immatriculation = value; OnPropertyChanged(); } } string poidTracteur; public string PoidTracteur { get { return poidTracteur; } set { poidTracteur = value; OnPropertyChanged(); } } string essieux; public string Essieux { get { return essieux; } set { essieux = value; OnPropertyChanged(); } } string entreprise; public string Entreprise { get { return entreprise; } set { entreprise = value; OnPropertyChanged(); } } void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } }
Java
UTF-8
500
1.6875
2
[]
no_license
package service; import java.util.List; import vo.PersonalVO; public interface PSService { List<PersonalVO> selectList(); PersonalVO selectOne(PersonalVO vo); int insert(PersonalVO vo); int update(PersonalVO vo); int delete(PersonalVO vo); int IdCheck(String id); int emailCheck(String email_id, String email_domain); void verify(PersonalVO vo); PersonalVO findid(PersonalVO vo); int eupdate(PersonalVO vo); int pwupdate(PersonalVO vo); }
C
UTF-8
1,291
4.5625
5
[]
no_license
/*EX8 converts the first letter of every word in a string to uppercase Write a function that converts the first letter of every word in a string to uppercase. Write a program that asks user to enter a string and then calls the function above. The program keeps asking for strings until user enters "stop" or "STOP". When user enters stop the program terminates.*/ #include <string.h> #include <stdio.h> #include <stdbool.h> void convert(char *str); void convert(char *str) { const char s[2] = " "; char *token; //get the first token token = strtok(str, s); //walk through other tokens while( token != NULL ) { token[0] = toupper(token[0]); //change the first letter to upper case printf( "%s ", token ); //print token = strtok(NULL, s); } printf("\n"); } int main () { char str[256]; bool checked = false; //Variable to check when to stop the program do { printf("Enter a string: "); gets(str); //if the entered string isn't "stop" or "STOP", run the convert function if (strcmp(str,"stop") != 0 && strcmp(str,"STOP") != 0) convert(str); else checked = true; //else stop the program } while (checked == false); printf("Program stopped."); return(0); }
C#
UTF-8
6,670
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions; namespace PagerControl { /// <summary> /// 分页控件 /// RecordCount: 记录总数 /// PageSize: 每页显示,默认值为20 /// PageCount: 显示总页数 /// PageIndex: 当前显示页数 /// 加载此控件时,需先设置RecordCount /// 在此控件的DataPaging 事件函数中 实现绑定刷新DataView功能 /// </summary> public partial class PagerControl : UserControl { public delegate void Paging(); public PagerControl() { InitializeComponent(); } #region Public Constant Variables public const int DEFAULT_PAGEINDEX = 1; public const int DEFAULT_PAGESIZE = 20; //默认每页显示记录数为20 #endregion #region private variables private int recordCount = 0; private int pageCount = 0; private int pageSize = DEFAULT_PAGESIZE; private int pageIndex = DEFAULT_PAGEINDEX; #endregion #region Public Events //自定义控件event public event Paging DataPaging = null; #endregion #region Properties /// <summary> /// 每页显示记录数 /// </summary> public int PageSize { get { return pageSize; } set { pageSize = value; GetPageCount(); } } /// <summary> /// 当前页数 /// </summary> public int PageIndex { get { return pageIndex; } set { pageIndex = value; RefreshControlInfo(); } } /// <summary> /// 记录总条数 /// </summary> public int RecordCount { get { return recordCount; } set { recordCount = value; GetPageCount(); RefreshControlInfo(); //BindData(); } } /// <summary> /// 计算获得总页数 /// </summary> private void GetPageCount() { if (this.RecordCount > 0) { pageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(this.RecordCount) / Convert.ToDouble(this.PageSize))); } else { pageCount = 0; } } /// <summary> /// 刷新显示分页控件的信息 /// </summary> private void RefreshControlInfo() { this.lblRecordCount.Text = "记录总数:" + this.RecordCount.ToString(); this.txtPageNo.Text = this.PageIndex.ToString(); this.txtPageSize.Text = this.PageSize.ToString(); this.lblPageCount.Text = "页 共" + this.pageCount.ToString() + "页"; } #endregion #region 数据绑定方法 /// <summary> /// 触发事件以便主界面获取,以便更新dataview数据 /// 同时刷新显示分页控件的信息 /// 控制button是否enable /// </summary> private void BindData() { if (pageIndex > pageCount) { pageIndex = pageCount; } if (pageIndex < 1) { pageIndex = 1; } if (DataPaging != null) { DataPaging(); } RefreshControlInfo(); if (this.PageIndex == 1) { this.btnPre.Enabled = false; this.btnFirst.Enabled = false; } else { btnPre.Enabled = true; btnFirst.Enabled = true; } if (this.PageIndex == this.pageCount) { this.btnLast.Enabled = false; this.btnNext.Enabled = false; } else { btnLast.Enabled = true; btnNext.Enabled = true; } if (this.recordCount == 0) { btnNext.Enabled = false; btnLast.Enabled = false; btnFirst.Enabled = false; btnPre.Enabled = false; } } #endregion #region component event //第一页 private void btnFirst_Click(object sender, EventArgs e) { if (pageIndex > 1) { pageIndex = 1; BindData(); } } //上一页 private void btnPre_Click(object sender, EventArgs e) { if (pageIndex > 1) { pageIndex--; BindData(); } } //下一页 private void btnNext_Click(object sender, EventArgs e) { if (pageIndex < pageCount) { pageIndex++; BindData(); } } //最后一页 private void btnLast_Click(object sender, EventArgs e) { if (pageIndex < pageCount) { pageIndex = pageCount; BindData(); } } //更改每页显示记录数,enter键确认修改 private void txtPageSize_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == '\r') { string strFormat = @"^[1-9][0-9]*$";//正则表达式 ,正整数 Regex reg = new Regex(strFormat); if (!reg.IsMatch(this.txtPageSize.Text.Trim())) { PageSize = DEFAULT_PAGESIZE; BindData(); } else { PageSize = Int32.Parse(txtPageSize.Text.Trim()); //重新计算pagecount BindData(); } } } private void PagerControl_Load(object sender, EventArgs e) { this.txtPageNo.Text = pageIndex.ToString(); this.txtPageSize.Text = pageSize.ToString(); } #endregion } }
Rust
UTF-8
4,059
2.578125
3
[ "BSD-2-Clause", "MIT", "Apache-2.0" ]
permissive
// Copyright (c) 2021, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium. // Copyright (c) 2021, Cosmian Tech SAS, 53-55 rue La Boétie, Paris, France. use anyhow::Context as _; use scasm::lexer::{Operand, Register, RegisterKind, RegisterStruct}; use std::collections::HashMap; use tracing::{instrument, trace}; use walrus::{ir::InstrSeqId, GlobalId, LocalId, ValType}; #[derive(Default)] pub struct Stack { stack: Vec<Operand>, regs: RegisterStruct<u32>, globals: HashMap<GlobalId, Register>, /// Locals, arguments and return types. persistent: HashMap<PersistentKind, Register>, } impl Stack { pub fn from_locals<'a>(module_locals: impl Iterator<Item = &'a walrus::Local>) -> Self { let mut stack = Self::default(); for local in module_locals { let kind = local.ty().as_register_kind(); stack.local(PersistentKind::Local(local.id()), kind); } stack } } #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub enum PersistentKind { Local(LocalId), BlockReturn(InstrSeqId), /// The id is the id of the entry block FunctionReturn(InstrSeqId, usize), } pub trait AsRegisterKind { fn as_register_kind(&self) -> RegisterKind; } impl AsRegisterKind for ValType { fn as_register_kind(&self) -> RegisterKind { match self { ValType::I32 | ValType::I64 => RegisterKind::Regint, ValType::F32 => RegisterKind::Secret, ValType::F64 => RegisterKind::SecretRegint, ValType::V128 => RegisterKind::Clear, ValType::Externref => unreachable!(), ValType::Funcref => unreachable!(), } } } impl Stack { pub fn dump_stack(&self) { trace!("{:#?}", self.stack); } pub fn expect_stack_empty(&self) -> anyhow::Result<()> { if !self.stack.is_empty() { anyhow::bail!("stack is {:#?}", self.stack) } Ok(()) } /// Creates a register that is not on the stack. #[instrument(skip(self))] pub fn temp(&mut self, kind: RegisterKind) -> Register { let cregs = self.regs.access_mut(kind); let reg = Register::new(kind, *cregs); *cregs += 1; reg } pub fn push_temp(&mut self, kind: RegisterKind) -> Register { let reg = self.temp(kind); self.push(reg); reg } pub fn push(&mut self, op: impl Into<Operand>) { let op = op.into(); trace!(?op, "push"); self.stack.push(op); } pub fn pop(&mut self) -> anyhow::Result<Operand> { let op = self .stack .pop() .context("invalid wasm: stack did not contain any element on pop")?; trace!(?op, "pop"); Ok(op) } pub fn read_top(&self) -> anyhow::Result<Operand> { let op = self .stack .last() .copied() .context("invalid wasm: stack did not contain any element on read_top")?; trace!(?op, "read_top"); Ok(op) } #[instrument(skip(self))] pub fn local(&mut self, delay: PersistentKind, register_kind: RegisterKind) -> Register { if let Some(&r) = self.persistent.get(&delay) { return r; } let persistent_reg = self.temp(register_kind); self.persistent.insert(delay, persistent_reg); persistent_reg } #[instrument(skip(self))] #[track_caller] pub fn expect_local(&mut self, local: LocalId) -> Register { self.persistent[&PersistentKind::Local(local)] } #[instrument(skip(self))] pub fn global(&mut self, global: GlobalId) -> anyhow::Result<Register> { if let Some(&r) = self.globals.get(&global) { if r.kind() != RegisterKind::Regint { anyhow::bail!("the register should be a RegInt") } return Ok(r); } let persistent_reg = self.temp(RegisterKind::Regint); self.globals.insert(global, persistent_reg); Ok(persistent_reg) } }
Markdown
UTF-8
64
2.78125
3
[]
no_license
# Responsive-Portfolio Homework #2 portfolio using media querys
Markdown
UTF-8
4,377
2.6875
3
[ "ICU", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- title: " DTOJ4131简单题\t\t" tags: - dp url: 6578.html id: 6578 categories: - Solution date: 2019-02-24 11:26:16 --- 对于一个初始局面,四个角都有格子或者一三行有连续两个格子都是不合法的。下面仅考虑合法局面。 对于一三行,显然这边不用考虑先后顺序影响。并且,每个联通块之间的答案均是独立的。我们考虑对于每个联通块分别作dp,最后再扣去这部分的方案数。 显然,每个联通块都是由第二行全空加上一三行的散块组成的。由于一三行可以在任意时间填入,现在我们要解决的是一三行填入对于第二行顺序的影响。 记$f\[i\]\[j\]\[0/1\]$为连通块前$i$列所有空格子中,第二行第$i$列的棋子是是$j个放的,第$i+1$列的棋子它之后/之前放进去的。 考虑$f\[i-1\]\[k\]\[0\] \\to f\[i\]\[j\]\[0\]。这意味着相邻的几个格子都是按顺序放入的,并且一三行格子需要先放入。 $$f\[i−1\]\[k\]\[0\]×\[j-1\]_{tot\[i\]}\\tof\[i\]\[j\]\[0\]$$ 这个时候显然要有$k \\le j-tot\[i\]$。同理的,$f\[i-1\]\[k\]\[1\] \\to f\[i\]\[j\]\[0\], f\[i-1\]\[k\]\[1\] \\to f\[i\]\[j\]\[1\]$也有类似的转移。 接下来特殊考虑$f\[i−1\]\[k\]\[0\] \\to f\[i\]\[j\]\[1\] $。其特殊在于其第二行左右两个格子都已经放好了,那么一三行显然可以任意放置。那么 $$f\[i\]\[j\]\[1\] \\leftarrow f\[i-1\]\[k\]\[0\]\\times \[j-1\]\_s\\times \[sum\_i-j\]_{tot\[i\]-s}\\binom{v}{s}$$ $s$表示我们枚举当前选了几个,$sum_i$则为前面空格子个数的前缀和。 具体细节看代码吧。 #include<bits/stdc++.h> #define mod 1000000007 #define N 6005 int n, fac\[N\], inv\[N\], sum\[N\], tot\[N\], f\[N / 3\]\[N\]\[2\], ans; char A\[3\]\[N\]; void mul (int &x, int y) { x = x + y >= mod ? x + y - mod : x + y; } int P (int a, int b) { return 1ll * fac\[a\] * inv\[a - b\] % mod; } int main () { scanf ("%d", &n); scanf ("%s%s%s", A\[0\] + 1, A\[1\] + 1, A\[2\] + 1); fac\[0\] = inv\[0\] = inv\[1\] = 1; for (int i = 1; i < N; i++) fac\[i\] = 1ll * fac\[i - 1\] * i%mod; for (int i = 2; i < N; i++) inv\[i\] = 1ll * (mod - mod / i)*inv\[mod%i\] % mod; for (int i = 2; i < N; i++) inv\[i\] = 1ll * inv\[i - 1\] * inv\[i\] % mod; for (int i = 1; i <= n; i++) { if (A\[0\]\[i\] == 'x' && (A\[0\]\[i - 1\] != 'o' || A\[0\]\[i + 1\] != 'o')) return puts ("0"), 0; if (A\[2\]\[i\] == 'x' && (A\[2\]\[i - 1\] != 'o' || A\[2\]\[i + 1\] != 'o')) return puts ("0"), 0; } for (int i = 1; i <= n; i++) tot\[i\] = (A\[0\]\[i\] == 'x') + (A\[1\]\[i\] == 'x') + (A\[2\]\[i\] == 'x'), sum\[i\] = sum\[i - 1\] + tot\[i\]; ans = fac\[sum\[n\]\]; for (int i = 1, nxt = 1; i <= n; i = nxt + 1) { if (A\[1\]\[i\] == 'o') { nxt = i; continue; } for (nxt = i; nxt < n && A\[1\]\[nxt + 1\] == 'x'; nxt++); for (int j = 1; j <= tot\[i\]; j++) f\[i\]\[j\]\[1\] = 1ll * j * fac\[tot\[i\] - 1\] % mod; f\[i\]\[1\]\[0\] = fac\[tot\[i\] - 1\]; for (int j = i + 1; j <= nxt; j++) { for (int k = 1; k <= sum\[j - 1\] - sum\[i - 1\]; k++) { mul (f\[j\]\[k + 1\]\[1\], 1ll * f\[j - 1\]\[k\]\[1\] * P (sum\[j\] - sum\[i - 1\] - k - 1, tot\[j\] - 1) % mod); mul (f\[j\]\[k + 1\]\[0\], 1ll * f\[j - 1\]\[k\]\[1\] * P (sum\[j\] - sum\[i - 1\] - k - 1, tot\[j\] - 1) % mod); mul (f\[j\]\[k\]\[0\], 1ll * f\[j - 1\]\[k\]\[0\] * P (sum\[j\] - sum\[i - 1\] - k, tot\[j\] - 1) % mod); if (tot\[j\] == 1) mul (f\[j\]\[k\]\[1\], f\[j - 1\]\[k\]\[0\]); if (tot\[j\] == 2) mul (f\[j\]\[k\]\[1\], 1ll * f\[j - 1\]\[k\]\[0\] * (sum\[j\] - sum\[i - 1\] - k) % mod), mul (f\[j\]\[k + 1\]\[1\], 1ll * f\[j - 1\]\[k\]\[0\] * k %mod); if (tot\[j\] == 3) mul (f\[j\]\[k\]\[1\], 1ll * f\[j - 1\]\[k\]\[0\] * P (sum\[j\] - sum\[i - 1\] - k, 2) % mod), mul (f\[j\]\[k + 1\]\[1\], 2ll * f\[j - 1\]\[k\]\[0\] * k % mod * (sum\[j\] - sum\[i - 1\] - k - 1) % mod), mul (f\[j\]\[k + 2\]\[1\], 1ll * f\[j - 1\]\[k\]\[0\] * P (k + 1, 2) % mod); } for (int k = 1; k <= sum\[j\] - sum\[i - 1\]; k++) mul (f\[j\]\[k\]\[1\], f\[j\]\[k - 1\]\[1\]); for (int k = sum\[j\] - sum\[i - 1\]; k >= 1; k--) mul (f\[j\]\[k\]\[0\], f\[j\]\[k + 1\]\[0\]); } ans = 1ll * ans * inv\[sum\[nxt\] - sum\[i - 1\]\] % mod * f\[nxt\]\[sum\[nxt\] - sum\[i - 1\]\]\[1\] % mod; } std::cout << ans << "\\n"; }
Ruby
UTF-8
976
3
3
[]
no_license
require_relative 'views' class Interface attr_reader :view, :config attr_writer :mode, :running def initialize(config, parser, writer) @config = config @view = View.new @mode = '' @running = true @parser = parser @writer = writer end def call self.greet_user while @running view.cache_summary(@parser, 'terse') if @parser.parsed_objects.size > 0 view.show_menu(config[:main_menu]) command = config[:main_menu][view.get_command][:fork] self.mode = command self.send command end end def greet_user view.greet(config[:user_name]) end def quit puts "Quiting program, have a nice day" self.running = false end def create_component command = view.ask_input @parser.new.parse_component_from(command) end def view_cache view.cache_summary(@parser, 'summary') end def write_all_objects @writer.new(@parser).call end end
JavaScript
UTF-8
3,833
2.96875
3
[]
no_license
var content = document.getElementById("window"); var ctx = document.getElementById('content').getContext('2d'); var disp = document.getElementById('data'); var World = new BitSet(1600); var time_inactive = 0; content.scrollLeft = 50; content.scrollTop = 50; function mod(n,m) { return ((n % m) + m) % m; } function writeCell(state,x,y) { World.set(y*40+x, state); xoffset = 800; yoffset = 800; if(x>=30) xoffset *= -1; else if(x > 10) xoffset = 0; if(y>=30) yoffset *= -1; else if(y > 10) yoffset = 0; x = x*20 + 200; y = y*20 + 200; if(state) { ctx.rect(x, y, 20, 20); ctx.rect(x+xoffset, y+yoffset, 20, 20); ctx.rect(x, y+yoffset, 20, 20); ctx.rect(x+xoffset, y, 20, 20); } } function readCell(world,x,y) { return world.get((mod(y,40))*40+(mod(x,40))); } function neighbors(world,x,y) { n = 0; for(i=-1; i<2; i++) if(readCell(world,x+i,y-1)) n++; if(readCell(world,x-1,y)) n++; if(readCell(world,x+1,y)) n++; for(i=-1; i<2; i++) if(readCell(world,x+i,y+1)) n++; return n; } function nextGen() { lastWorld = World.clone(); for(y=0; y<40; y++) { for(x=0; x<40; x++) { n = neighbors(lastWorld,x,y); if(n<2) writeCell(false, x, y); else if(n>3) writeCell(false, x, y); else if(n==2) writeCell(readCell(lastWorld,x,y),x,y); else if(n==3) writeCell(true,x,y); } } } function writeDisp(str) { disp.innerHTML = '<p>' + str + '</p>'; } ctx.beginPath(); for(i=0; i < 600; i++) { x = Math.floor((Math.random() * 40) + 0) % 40; y = Math.floor((Math.random() * 40) + 0) % 40; writeCell(true, x, y); } /* writeCell(true, 1,3); writeCell(true, 2,3); writeCell(true, 2,1); writeCell(true, 4,2); writeCell(true, 5,3); writeCell(true, 6,3); writeCell(true, 7,3); */ ctx.fillStyle="#FF7300"; ctx.fill(); /*ctx.strokeStyle="#FF7300"; ctx.stroke();*/ writeDisp(World.toString().slice(-1600).replace(/(.{40})/g,"$&" + "<br>")); setInterval(function() { ctx.clearRect(0, 0, 1200, 1200); ctx.beginPath(); nextGen(); ctx.fillStyle="#FF7300"; ctx.fill(); /*ctx.strokeStyle="#FF7300"; ctx.stroke();*/ writeDisp(World.toString().slice(-1600).replace(/(.{40})/g,"$&" + "<br>")); }, 50); /* alert(neighbors(World, 1,2)); writeDisp('hi'); for(i=17; i<23; i++) { for(j=17; j<23; j++) { d = readCell(i,j); r = ('0' + d[0].toString(16)).slice(-2); g = ('0' + d[1].toString(16)).slice(-2); b = ('0' + d[2].toString(16)).slice(-2); alert(i+', '+j+': '+r+g+b); } } writeDisp(neighbors(21,21)); */ setInterval(function() { if (content.scrollLeft <= 0) { content.scrollLeft = 800; } else if(content.scrollLeft >= 800) { content.scrollLeft = 0; } if (content.scrollTop <= 0) { content.scrollTop = 800; } else if(content.scrollTop >= 800) { content.scrollTop = 0; } }, 10); /* setInterval(function() { time_inactive += 1; }, 1000); setInterval(function() { if(time_inactive >= 4) content.scrollLeft += 1; }, 20); document.addEventListener('keydown', function(event) { if(event.keyCode) time_inactive = 0; });*/
Markdown
UTF-8
1,087
2.53125
3
[ "Apache-2.0" ]
permissive
# Webpack的概念与安装 ###为什么需要webpack? 工程复杂度增加了,难度增加了,项目人也变多了。 ###前端工程化 什么是前端工程化? 工程化是系统化,模块化,规范化的过程。 工程化主要解决"如何提高整个系统生产效率"的问题. 前端工程化的改变在哪些方面? 工具: 需要用到更多的自动化机械,更多的脚手架 人员:协作的人开始变得很多,需要有一定的机制保障合作的顺畅 写代码的方式: 大量的用到预制模板,用组件化的方式写项目 ###Webpack主要功能 1. 编译,包括javascript的编译,css编译 2. 文件的压缩,打包,合并,公共模块提取等 3. 图片等资源处理如压缩,合并雪碧图等 4. Tree-shaking等优化js工具 5. Webpack-dev-server,Eslint,热更新等帮助开发工具 ###安装 1. 安装node 2. npm install webpack -g (webpack4后需要 npm install webpack webpack-cli -g) 可以先安装npm在中国的淘宝镜像cnpm (npm install cnpm), 以后就直接用cnpm install ...
C#
UTF-8
431
3.109375
3
[]
no_license
using System; using System.IO; namespace FileEx3 { class MainClass { public static void Main (string[] args) { TextReader input = new StreamReader ("1MB.txt"); TextWriter output = new StreamWriter ("1mbDup.txt"); char[] buffer = new char[500]; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write (buffer, 0, read); } input.Close (); output.Close (); } } }
PHP
UTF-8
976
2.703125
3
[]
no_license
<?php require_once("datosConexion.php"); require("headers.php"); $datos = json_decode(file_get_contents("php://input")); $mysqli = new mysqli($host, $user, $pass, $database); $sql = "INSERT INTO ventas (%s) values (%s); "; $i = 0; $sqli = ""; foreach ($datos as $dato => $value) { $valores = ""; $campos = ""; foreach ($value as $dato => $valor) { if ($dato!='index'){ $campos .= "$dato" . ","; $valores .= "'$valor'" . ","; } } $campos = substr($campos, 0, strlen($campos) - 1); $valores = substr($valores, 0, strlen($valores) - 1); $sqli .= sprintf($sql, $campos, $valores); } if ($mysqli->multi_query($sqli)) $datos = array("Mensaje" => "Registros Insertados Correctamente", "SQL" => $sqli); else $datos = array("Mensaje" => "Error", "MySQL Error" => $mysqli->error, "SQL" => $sqli); echo json_encode($datos); $mysqli->close();
Java
UTF-8
55,102
1.671875
2
[ "MIT" ]
permissive
/** * Copyright (C) 2002-2015 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol; import java.awt.Dimension; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.IOException; import java.net.InetAddress; import java.net.URL; import java.net.JarURLConnection; import java.util.Arrays; import java.util.Locale; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import net.sf.freecol.client.ClientOptions; import net.sf.freecol.client.FreeColClient; import net.sf.freecol.common.FreeColException; import net.sf.freecol.common.FreeColSeed; import net.sf.freecol.common.debug.FreeColDebugger; import net.sf.freecol.common.i18n.Messages; import net.sf.freecol.common.io.FreeColDirectories; import net.sf.freecol.common.io.FreeColSavegameFile; import net.sf.freecol.common.io.FreeColTcFile; import net.sf.freecol.common.io.Mods; import net.sf.freecol.common.logging.DefaultHandler; import net.sf.freecol.common.model.NationOptions.Advantages; import net.sf.freecol.common.model.Specification; import net.sf.freecol.common.model.StringTemplate; import net.sf.freecol.common.option.OptionGroup; import static net.sf.freecol.common.util.CollectionUtils.*; import net.sf.freecol.server.FreeColServer; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; /** * This class is responsible for handling the command-line arguments * and starting either the stand-alone server or the client-GUI. * * @see net.sf.freecol.client.FreeColClient FreeColClient * @see net.sf.freecol.server.FreeColServer FreeColServer */ public final class FreeCol { private static final Logger logger = Logger.getLogger(FreeCol.class.getName()); /** The FreeCol release version number. */ private static final String FREECOL_VERSION = "0.11.6"; /** The difficulty levels. */ public static final String[] DIFFICULTIES = { "veryEasy", "easy", "medium", "hard", "veryHard" }; /** The extension for FreeCol saved games. */ public static final String FREECOL_SAVE_EXTENSION = "fsg"; /** The Java version. */ private static final String JAVA_VERSION = System.getProperty("java.version"); /** The maximum available memory. */ private static final long MEMORY_MAX = Runtime.getRuntime().maxMemory(); public static final String CLIENT_THREAD = "FreeColClient:"; public static final String SERVER_THREAD = "FreeColServer:"; public static final String METASERVER_THREAD = "FreeColMetaServer:"; public static final String META_SERVER_ADDRESS = "meta.freecol.org"; public static final int META_SERVER_PORT = 3540; /** Specific revision number (currently the git tag of trunk at release) */ private static String freeColRevision = null; /** The locale, either default or command-line specified. */ private static Locale locale = null; // Cli defaults. private static final Advantages ADVANTAGES_DEFAULT = Advantages.SELECTABLE; private static final String DIFFICULTY_DEFAULT = "model.difficulty.medium"; private static final int EUROPEANS_DEFAULT = 4; private static final int EUROPEANS_MIN = 1; private static final Level LOGLEVEL_DEFAULT = Level.INFO; private static final String JAVA_VERSION_MIN = "1.8"; private static final int MEMORY_MIN = 128; // Mbytes private static final int PORT_DEFAULT = 3541; private static final String SPLASH_DEFAULT = "splash.jpg"; private static final String TC_DEFAULT = "freecol"; public static final int TIMEOUT_DEFAULT = 60; // 1 minute public static final int TIMEOUT_MIN = 10; // 10s private static final int GUI_SCALE_MIN_PCT = 100; private static final int GUI_SCALE_MAX_PCT = 200; private static final int GUI_SCALE_STEP_PCT = 25; public static final float GUI_SCALE_MIN = GUI_SCALE_MIN_PCT / 100.0f; public static final float GUI_SCALE_MAX = GUI_SCALE_MAX_PCT / 100.0f; public static final float GUI_SCALE_STEP = GUI_SCALE_STEP_PCT / 100.0f; public static final float GUI_SCALE_DEFAULT = 1.0f; // Cli values. Often set to null so the default can be applied in // the accessor function. private static boolean checkIntegrity = false, consoleLogging = false, debugStart = false, fastStart = false, headless = false, introVideo = true, javaCheck = true, memoryCheck = true, publicServer = true, sound = true, standAloneServer = false; /** The type of advantages. */ private static Advantages advantages = null; /** The difficulty level id. */ private static String difficulty = null; /** The number of European nations to enable by default. */ private static int europeanCount = EUROPEANS_DEFAULT; /** A font override. */ private static String fontName = null; /** The level of logging in this game. */ private static Level logLevel = LOGLEVEL_DEFAULT; /** The client player name. */ private static String name = null; /** How to name and configure the server. */ private static int serverPort = -1; private static String serverName = null; /** A stream to get the splash image from. */ private static InputStream splashStream; /** The TotalConversion / ruleset in play, defaults to "freecol". */ private static String tc = null; /** The time out (seconds) for otherwise blocking commands. */ private static int timeout = -1; /** * The size of window to create, defaults to impossible dimensions * to require windowed mode with best determined screen size. */ private static Dimension windowSize = new Dimension(-1, -1); /** How much gui elements get scaled. */ private static float guiScale = GUI_SCALE_DEFAULT; private FreeCol() {} // Hide constructor /** * The entrypoint. * * @param args The command-line arguments. */ public static void main(String[] args) { freeColRevision = FREECOL_VERSION; JarURLConnection juc; try { juc = getJarURLConnection(FreeCol.class); } catch (IOException ioe) { juc = null; System.err.println("Unable to open class jar: " + ioe.getMessage()); } if (juc != null) { try { String revision = readVersion(juc); if (revision != null) { freeColRevision += " (Revision: " + revision + ")"; } } catch (Exception e) { System.err.println("Unable to load Manifest: " + e.getMessage()); } try { splashStream = getDefaultSplashStream(juc); } catch (Exception e) { System.err.println("Unable to open default splash: " + e.getMessage()); } } // Java bug #7075600 causes BR#2554. The workaround is to set // the following property. Remove if/when they fix Java. System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); // We can not even emit localized error messages until we find // the data directory, which might have been specified on the // command line. String dataDirectoryArg = findArg("--freecol-data", args); String err = FreeColDirectories.setDataDirectory(dataDirectoryArg); if (err != null) fatal(err); // This must not fail. // Now we have the data directory, establish the base locale. // Beware, the locale may change! String localeArg = findArg("--default-locale", args); if (localeArg == null) { locale = Locale.getDefault(); } else { int index = localeArg.indexOf('.'); // Strip encoding if present if (index > 0) localeArg = localeArg.substring(0, index); locale = Messages.getLocale(localeArg); } Messages.loadMessageBundle(locale); // Now that we can emit error messages, parse the other // command line arguments. handleArgs(args); // Do the potentially fatal system checks as early as possible. if (javaCheck && JAVA_VERSION_MIN.compareTo(JAVA_VERSION) > 0) { fatal(StringTemplate.template("main.javaVersion") .addName("%version%", JAVA_VERSION) .addName("%minVersion%", JAVA_VERSION_MIN)); } if (memoryCheck && MEMORY_MAX < MEMORY_MIN * 1000000) { fatal(StringTemplate.template("main.memory") .addAmount("%memory%", MEMORY_MAX) .addAmount("%minMemory%", MEMORY_MIN)); } // Having parsed the command line args, we know where the user // directories should be, so we can set up the rest of the // file/directory structure. String userMsg = FreeColDirectories.setUserDirectories(); // Now we have the log file path, start logging. final Logger baseLogger = Logger.getLogger(""); final Handler[] handlers = baseLogger.getHandlers(); for (Handler handler : handlers) { baseLogger.removeHandler(handler); } String logFile = FreeColDirectories.getLogFilePath(); try { baseLogger.addHandler(new DefaultHandler(consoleLogging, logFile)); Logger freecolLogger = Logger.getLogger("net.sf.freecol"); freecolLogger.setLevel(logLevel); } catch (FreeColException e) { System.err.println("Logging initialization failure: " + e.getMessage()); e.printStackTrace(); } Thread.setDefaultUncaughtExceptionHandler((Thread thread, Throwable e) -> { baseLogger.log(Level.WARNING, "Uncaught exception from thread: " + thread, e); }); // Now we can find the client options, allow the options // setting to override the locale, if no command line option // had been specified. // We have users whose machines default to Finnish but play // FreeCol in English. // If the user has selected automatic language selection, do // nothing, since we have already set up the default locale. if (localeArg == null) { String clientLanguage = ClientOptions.getLanguageOption(); Locale clientLocale; if (clientLanguage != null && !Messages.AUTOMATIC.equalsIgnoreCase(clientLanguage) && (clientLocale = Messages.getLocale(clientLanguage)) != locale) { locale = clientLocale; Messages.loadMessageBundle(locale); logger.info("Loaded messages for " + locale); } } // Now we have the user mods directory and the locale is now // stable, load the mods and their messages. Mods.loadMods(); Messages.loadModMessageBundle(locale); // Report on where we are. if (userMsg != null) logger.info(Messages.message(userMsg)); logger.info(getConfiguration().toString()); // Ready to specialize into client or server. if (standAloneServer) { startServer(); } else { startClient(userMsg); } } /** * Get the JarURLConnection from a class. * * @return The <code>JarURLConnection</code>. */ private static JarURLConnection getJarURLConnection(@SuppressWarnings("rawtypes") Class c) throws IOException { String resourceName = "/" + c.getName().replace('.', '/') + ".class"; URL url = c.getResource(resourceName); return (JarURLConnection)url.openConnection(); } /** * Extract the package version from the class. * * @param juc The <code>JarURLConnection</code> to extract from. * @return A value of the package version attribute. */ private static String readVersion(JarURLConnection juc) throws IOException { Manifest mf = juc.getManifest(); return (mf == null) ? null : mf.getMainAttributes().getValue("Package-Version"); } /** * Get a stream for the default splash file. * * Note: Not bothering to check for nulls as this is called in try * block that ignores all exceptions. * * @param juc The <code>JarURLConnection</code> to extract from. * @return A suitable <code>InputStream</code>, or null on error. */ private static InputStream getDefaultSplashStream(JarURLConnection juc) throws IOException { JarFile jf = juc.getJarFile(); ZipEntry ze = jf.getEntry(SPLASH_DEFAULT); return jf.getInputStream(ze); } /** * Exit printing fatal error message. * * @param template A <code>StringTemplate</code> to print. */ public static void fatal(StringTemplate template) { fatal(Messages.message(template)); } /** * Exit printing fatal error message. * * @param err The error message to print. */ public static void fatal(String err) { if (err == null || err.isEmpty()) { err = "Bogus null fatal error message"; Thread.dumpStack(); } System.err.println(err); System.exit(1); } /** * Just gripe to System.err. * * @param template A <code>StringTemplate</code> to print. */ public static void gripe(StringTemplate template) { System.err.println(Messages.message(template)); } /** * Just gripe to System.err. * * @param key A message key. */ public static void gripe(String key) { System.err.println(Messages.message(key)); } /** * Find an option before the real option handling can get started. * Takes care to use the *last* instance. * * @param option The option to find. * @param args The command-line arguments. * @return The option's parameter. */ private static String findArg(String option, String[] args) { for (int i = args.length - 2; i >= 0; i--) { if (option.equals(args[i])) { return args[i+1]; } } return null; } /** * Processes the command-line arguments and takes appropriate * actions for each of them. * * @param args The command-line arguments. */ @SuppressWarnings("static-access") private static void handleArgs(String[] args) { Options options = new Options(); final String help = Messages.message("cli.help"); final File dummy = new File("dummy"); final String argDirectory = Messages.message("cli.arg.directory"); // Help options. options.addOption(OptionBuilder.withLongOpt("usage") .withDescription(help) .create()); options.addOption(OptionBuilder.withLongOpt("help") .withDescription(help) .create()); // Special options handled early. options.addOption(OptionBuilder.withLongOpt("freecol-data") .withDescription(Messages.message("cli.freecol-data")) .withArgName(argDirectory) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("default-locale") .withDescription(Messages.message("cli.default-locale")) .withArgName(Messages.message("cli.arg.locale")) .hasArg() .create()); // Ordinary options, handled here. options.addOption(OptionBuilder.withLongOpt("advantages") .withDescription(Messages.message(StringTemplate .template("cli.advantages") .addName("%advantages%", getValidAdvantages()))) .withArgName(Messages.message("cli.arg.advantages")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("check-savegame") .withDescription(Messages.message("cli.check-savegame")) .withArgName(Messages.message("cli.arg.file")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("clientOptions") .withDescription(Messages.message("cli.clientOptions")) .withArgName(Messages.message("cli.arg.clientOptions")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("debug") .withDescription(Messages.message(StringTemplate .template("cli.debug") .addName("%modes%", FreeColDebugger.getDebugModes()))) .withArgName(Messages.message("cli.arg.debug")) .hasOptionalArg() .create()); options.addOption(OptionBuilder.withLongOpt("debug-run") .withDescription(Messages.message("cli.debug-run")) .withArgName(Messages.message("cli.arg.debugRun")) .hasOptionalArg() .create()); options.addOption(OptionBuilder.withLongOpt("debug-start") .withDescription(Messages.message("cli.debug-start")) .create()); options.addOption(OptionBuilder.withLongOpt("difficulty") .withDescription(Messages.message("cli.difficulty")) .withArgName(Messages.message("cli.arg.difficulty")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("europeans") .withDescription(Messages.message("cli.european-count")) .withArgName(Messages.message("cli.arg.europeans")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("fast") .withDescription(Messages.message("cli.fast")) .create()); options.addOption(OptionBuilder.withLongOpt("font") .withDescription(Messages.message("cli.font")) .withArgName(Messages.message("cli.arg.font")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("full-screen") .withDescription(Messages.message("cli.full-screen")) .create()); options.addOption(OptionBuilder.withLongOpt("gui-scale") .withDescription(Messages.message(StringTemplate .template("cli.gui-scale") .addName("%scales%", getValidGUIScales()))) .withArgName(Messages.message("cli.arg.gui-scale")) .hasOptionalArg() .create()); options.addOption(OptionBuilder.withLongOpt("headless") .withDescription(Messages.message("cli.headless")) .create()); options.addOption(OptionBuilder.withLongOpt("load-savegame") .withDescription(Messages.message("cli.load-savegame")) .withArgName(Messages.message("cli.arg.file")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("log-console") .withDescription(Messages.message("cli.log-console")) .create()); options.addOption(OptionBuilder.withLongOpt("log-file") .withDescription(Messages.message("cli.log-file")) .withArgName(Messages.message("cli.arg.name")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("log-level") .withDescription(Messages.message("cli.log-level")) .withArgName(Messages.message("cli.arg.loglevel")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("name") .withDescription(Messages.message("cli.name")) .withArgName(Messages.message("cli.arg.name")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("no-intro") .withDescription(Messages.message("cli.no-intro")) .create()); options.addOption(OptionBuilder.withLongOpt("no-java-check") .withDescription(Messages.message("cli.no-java-check")) .create()); options.addOption(OptionBuilder.withLongOpt("no-memory-check") .withDescription(Messages.message("cli.no-memory-check")) .create()); options.addOption(OptionBuilder.withLongOpt("no-sound") .withDescription(Messages.message("cli.no-sound")) .create()); options.addOption(OptionBuilder.withLongOpt("no-splash") .withDescription(Messages.message("cli.no-splash")) .create()); options.addOption(OptionBuilder.withLongOpt("private") .withDescription(Messages.message("cli.private")) .create()); options.addOption(OptionBuilder.withLongOpt("seed") .withDescription(Messages.message("cli.seed")) .withArgName(Messages.message("cli.arg.seed")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("server") .withDescription(Messages.message("cli.server")) .create()); options.addOption(OptionBuilder.withLongOpt("server-name") .withDescription(Messages.message("cli.server-name")) .withArgName(Messages.message("cli.arg.name")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("server-port") .withDescription(Messages.message("cli.server-port")) .withArgName(Messages.message("cli.arg.port")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("splash") .withDescription(Messages.message("cli.splash")) .withArgName(Messages.message("cli.arg.file")) .hasOptionalArg() .create()); options.addOption(OptionBuilder.withLongOpt("tc") .withDescription(Messages.message("cli.tc")) .withArgName(Messages.message("cli.arg.name")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("timeout") .withDescription(Messages.message("cli.timeout")) .withArgName(Messages.message("cli.arg.timeout")) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("user-cache-directory") .withDescription(Messages.message("cli.user-cache-directory")) .withArgName(argDirectory) .withType(dummy) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("user-config-directory") .withDescription(Messages.message("cli.user-config-directory")) .withArgName(argDirectory) .withType(dummy) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("user-data-directory") .withDescription(Messages.message("cli.user-data-directory")) .withArgName(argDirectory) .withType(dummy) .hasArg() .create()); options.addOption(OptionBuilder.withLongOpt("version") .withDescription(Messages.message("cli.version")) .create()); options.addOption(OptionBuilder.withLongOpt("windowed") .withDescription(Messages.message("cli.windowed")) .withArgName(Messages.message("cli.arg.dimensions")) .hasOptionalArg() .create()); CommandLineParser parser = new PosixParser(); boolean usageError = false; try { CommandLine line = parser.parse(options, args); if (line.hasOption("help") || line.hasOption("usage")) { printUsage(options, 0); } if (line.hasOption("default-locale")) { ; // Do nothing, already handled in main(). } if (line.hasOption("freecol-data")) { ; // Do nothing, already handled in main(). } if (line.hasOption("advantages")) { String arg = line.getOptionValue("advantages"); Advantages a = selectAdvantages(arg); if (a == null) { fatal(StringTemplate.template("cli.error.advantages") .addName("%advantages%", getValidAdvantages()) .addName("%arg%", arg)); } } if (line.hasOption("check-savegame")) { String arg = line.getOptionValue("check-savegame"); if (!FreeColDirectories.setSavegameFile(arg)) { fatal(StringTemplate.template("cli.err.save") .addName("%string%", arg)); } checkIntegrity = true; standAloneServer = true; } if (line.hasOption("clientOptions")) { String fileName = line.getOptionValue("clientOptions"); if (!FreeColDirectories.setClientOptionsFile(fileName)) { // Not fatal. gripe(StringTemplate.template("cli.error.clientOptions") .addName("%string%", fileName)); } } if (line.hasOption("debug")) { // If the optional argument is supplied use limited mode. String arg = line.getOptionValue("debug"); if (arg == null || arg.isEmpty()) { // Let empty argument default to menus functionality. arg = FreeColDebugger.DebugMode.MENUS.toString(); } if (!FreeColDebugger.setDebugModes(arg)) { // Not fatal. gripe(StringTemplate.template("cli.error.debug") .addName("%modes%", FreeColDebugger.getDebugModes())); } // user set log level has precedence if (!line.hasOption("log-level")) logLevel = Level.FINEST; } if (line.hasOption("debug-run")) { FreeColDebugger.enableDebugMode(FreeColDebugger.DebugMode.MENUS); FreeColDebugger.configureDebugRun(line.getOptionValue("debug-run")); } if (line.hasOption("debug-start")) { debugStart = true; FreeColDebugger.enableDebugMode(FreeColDebugger.DebugMode.MENUS); } if (line.hasOption("difficulty")) { String arg = line.getOptionValue("difficulty"); String difficulty = selectDifficulty(arg); if (difficulty == null) { fatal(StringTemplate.template("cli.error.difficulties") .addName("%difficulties%", getValidDifficulties()) .addName("%arg%", arg)); } } if (line.hasOption("europeans")) { int e = selectEuropeanCount(line.getOptionValue("europeans")); if (e < 0) { gripe(StringTemplate.template("cli.error.europeans") .addAmount("%min%", EUROPEANS_MIN)); } } if (line.hasOption("fast")) { fastStart = true; introVideo = false; } if (line.hasOption("font")) { fontName = line.getOptionValue("font"); } if (line.hasOption("full-screen")) { windowSize = null; } if (line.hasOption("gui-scale")) { String arg = line.getOptionValue("gui-scale"); if(!setGUIScale(arg)) { gripe(StringTemplate.template("cli.error.gui-scale") .addName("%scales%", getValidGUIScales()) .addName("%arg%", arg)); } } if (line.hasOption("headless")) { headless = true; } if (line.hasOption("load-savegame")) { String arg = line.getOptionValue("load-savegame"); if (!FreeColDirectories.setSavegameFile(arg)) { fatal(StringTemplate.template("cli.error.save") .addName("%string%", arg)); } } if (line.hasOption("log-console")) { consoleLogging = true; } if (line.hasOption("log-file")) { FreeColDirectories.setLogFilePath(line.getOptionValue("log-file")); } if (line.hasOption("log-level")) { setLogLevel(line.getOptionValue("log-level")); } if (line.hasOption("name")) { setName(line.getOptionValue("name")); } if (line.hasOption("no-intro")) { introVideo = false; } if (line.hasOption("no-java-check")) { javaCheck = false; } if (line.hasOption("no-memory-check")) { memoryCheck = false; } if (line.hasOption("no-sound")) { sound = false; } if (line.hasOption("no-splash")) { splashStream = null; } if (line.hasOption("private")) { publicServer = false; } if (line.hasOption("server")) { standAloneServer = true; } if (line.hasOption("server-name")) { serverName = line.getOptionValue("server-name"); } if (line.hasOption("server-port")) { String arg = line.getOptionValue("server-port"); if (!setServerPort(arg)) { fatal(StringTemplate.template("cli.error.serverPort") .addName("%string%", arg)); } } if (line.hasOption("seed")) { FreeColSeed.setFreeColSeed(line.getOptionValue("seed")); } if (line.hasOption("splash")) { String splash = line.getOptionValue("splash"); try { FileInputStream fis = new FileInputStream(splash); splashStream = fis; } catch (FileNotFoundException fnfe) { gripe(StringTemplate.template("cli.error.splash") .addName("%name%", splash)); } } if (line.hasOption("tc")) { setTC(line.getOptionValue("tc")); // Failure is deferred. } if (line.hasOption("timeout")) { String arg = line.getOptionValue("timeout"); if (!setTimeout(arg)) { // Not fatal gripe(StringTemplate.template("cli.error.timeout") .addName("%string%", arg) .addName("%minimum%", Integer.toString(TIMEOUT_MIN))); } } if (line.hasOption("user-cache-directory")) { String arg = line.getOptionValue("user-cache-directory"); String errMsg = FreeColDirectories.setUserCacheDirectory(arg); if (errMsg != null) { // Not fatal. gripe(StringTemplate.template(errMsg) .addName("%string%", arg)); } } if (line.hasOption("user-config-directory")) { String arg = line.getOptionValue("user-config-directory"); String errMsg = FreeColDirectories.setUserConfigDirectory(arg); if (errMsg != null) { // Not fatal. gripe(StringTemplate.template(errMsg) .addName("%string%", arg)); } } if (line.hasOption("user-data-directory")) { String arg = line.getOptionValue("user-data-directory"); String errMsg = FreeColDirectories.setUserDataDirectory(arg); if (errMsg != null) { // Fatal, unable to save. fatal(StringTemplate.template(errMsg) .addName("%string%", arg)); } } if (line.hasOption("version")) { System.out.println("FreeCol " + getVersion()); System.exit(0); } if (line.hasOption("windowed")) { String arg = line.getOptionValue("windowed"); setWindowSize(arg); // Does not fail } } catch (ParseException e) { System.err.println("\n" + e.getMessage() + "\n"); usageError = true; } if (usageError) printUsage(options, 1); } /** * Prints the usage message and exits. * * @param options The command line <code>Options</code>. * @param status The status to exit with. */ private static void printUsage(Options options, int status) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -Xmx 256M -jar freecol.jar [OPTIONS]", options); System.exit(status); } /** * Get the specification from a given TC file. * * @param tcf The <code>FreeColTcFile</code> to load. * @param advantages An optional <code>Advantages</code> setting. * @param difficulty An optional difficulty level. * @return A <code>Specification</code>. */ public static Specification loadSpecification(FreeColTcFile tcf, Advantages advantages, String difficulty) { Specification spec = null; try { if (tcf != null) spec = tcf.getSpecification(); } catch (IOException ioe) { System.err.println("Spec read failed in " + tcf.getId() + ": " + ioe.getMessage() + "\n"); } if (spec != null) spec.prepare(advantages, difficulty); return spec; } /** * Get the specification from the specified TC. * * @return A <code>Specification</code>, quits on error. */ private static Specification getTCSpecification() { Specification spec = loadSpecification(getTCFile(), getAdvantages(), getDifficulty()); if (spec == null) { fatal(StringTemplate.template("cli.error.badTC") .addName("%tc%", getTC())); } return spec; } // Accessors, mutators and support for the cli variables. /** * Gets the default advantages type. * * @return Usually Advantages.SELECTABLE, but can be overridden at the * command line. */ public static Advantages getAdvantages() { return (advantages == null) ? ADVANTAGES_DEFAULT : advantages; } /** * Sets the advantages type. * * Called from NewPanel when a selection is made. * * @param advantages The name of the new advantages type. * @return The type of advantages set, or null if none. */ private static Advantages selectAdvantages(String advantages) { Advantages adv = find(Advantages.values(), a -> Messages.getName(a).equals(advantages), null); if (adv != null) setAdvantages(adv); return adv; } /** * Sets the advantages type. * * @param advantages The new <code>Advantages</code> type. */ public static void setAdvantages(Advantages advantages) { FreeCol.advantages = advantages; } /** * Gets a comma separated list of localized advantage type names. * * @return A list of advantage types. */ private static String getValidAdvantages() { return Arrays.stream(Advantages.values()) .map(a -> Messages.getName(a)).collect(Collectors.joining(",")); } /** * Gets the difficulty level. * * @return The name of a difficulty level. */ public static String getDifficulty() { return (difficulty == null) ? DIFFICULTY_DEFAULT : difficulty; } /** * Selects a difficulty level. * * @param arg The supplied difficulty argument. * @return The name of the selected difficulty, or null if none. */ public static String selectDifficulty(String arg) { String difficulty = find(map(DIFFICULTIES, d -> "model.difficulty."+d), k -> Messages.getName(k).equals(arg), null); if (difficulty != null) setDifficulty(difficulty); return difficulty; } /** * Sets the difficulty level. * * @param difficulty The actual <code>OptionGroup</code> * containing the difficulty level. */ public static void setDifficulty(OptionGroup difficulty) { setDifficulty(difficulty.getId()); } /** * Sets the difficulty level. * * @param difficulty The new difficulty. */ public static void setDifficulty(String difficulty) { FreeCol.difficulty = difficulty; } /** * Gets the names of the valid difficulty levels. * * @return The valid difficulty levels, comma separated. */ public static String getValidDifficulties() { return Arrays.stream(DIFFICULTIES) .map(d -> Messages.getName("model.difficulty." + d)) .collect(Collectors.joining(",")); } /** * Get the number of European nations to enable by default. */ public static int getEuropeanCount() { return europeanCount; } /** * Sets the number of enabled European nations. * * @param n The number of nations to enable. */ public static void setEuropeanCount(int n) { europeanCount = n; } /** * Sets the scale for GUI elements. * * @param arg The optional command line argument to be parsed. * @return If the argument was correctly formatted. */ public static boolean setGUIScale(String arg) { boolean valid = true; if(arg == null) { guiScale = GUI_SCALE_MAX; } else { try { int n = Integer.parseInt(arg); if (n < GUI_SCALE_MIN_PCT) { valid = false; n = GUI_SCALE_MIN_PCT; } else if(n > GUI_SCALE_MAX_PCT) { valid = false; n = GUI_SCALE_MAX_PCT; } else if(n % GUI_SCALE_STEP_PCT != 0) { valid = false; } guiScale = ((float)(n / GUI_SCALE_STEP_PCT)) * GUI_SCALE_STEP; } catch (NumberFormatException nfe) { valid = false; guiScale = GUI_SCALE_MAX; } } return valid; } /** * Gets the valid scale factors for the GUI. * * @return A string containing these. */ public static String getValidGUIScales() { String result = ""; for(int i=GUI_SCALE_MIN_PCT; i<GUI_SCALE_MAX_PCT; i+=GUI_SCALE_STEP_PCT) result += i + ","; result += GUI_SCALE_MAX_PCT; return result; } /** * Selects a European nation count. * * @param arg The supplied count argument. * @return A valid nation number, or negative on error. */ public static int selectEuropeanCount(String arg) { try { int n = Integer.parseInt(arg); if (n >= EUROPEANS_MIN) { setEuropeanCount(n); return n; } } catch (NumberFormatException nfe) {} return -1; } /** * Sets the log level. * * @param arg The log level to set. */ private static void setLogLevel(String arg) { logLevel = Level.parse(arg.toUpperCase()); } /** * Gets the user name. * * @return The user name, defaults to the user.name property, then to * the "main.defaultPlayerName" message value. */ public static String getName() { return (name != null) ? name : System.getProperty("user.name", Messages.message("main.defaultPlayerName")); } /** * Sets the user name. * * @param name The new user name. */ public static void setName(String name) { FreeCol.name = name; logger.info("Set FreeCol.name = " + name); } /** * Get the selected locale. * * @return The <code>Locale</code> currently in use. */ public static Locale getLocale() { return FreeCol.locale; } /** * Gets the current revision of game. * * @return The current version and SVN Revision of the game. */ public static String getRevision() { return freeColRevision; } /** * Get the default server host name. * * @return The host name. */ public static String getServerHost() { return InetAddress.getLoopbackAddress().getHostAddress(); } /** * Gets the server network port. * * @return The port number. */ public static int getServerPort() { return (serverPort < 0) ? PORT_DEFAULT : serverPort; } /** * Sets the server port. * * @param arg The server port number. * @return True if the port was set. */ public static boolean setServerPort(String arg) { if (arg == null) return false; try { serverPort = Integer.parseInt(arg); } catch (NumberFormatException nfe) { return false; } return true; } /** * Gets the current Total-Conversion. * * @return Usually TC_DEFAULT, but can be overridden at the command line. */ public static String getTC() { return (tc == null) ? TC_DEFAULT : tc; } /** * Sets the Total-Conversion. * * Called from NewPanel when a selection is made. * * @param tc The name of the new total conversion. */ public static void setTC(String tc) { FreeCol.tc = tc; } /** * Gets the FreeColTcFile for the current TC. * * @return The <code>FreeColTcFile</code>. */ public static FreeColTcFile getTCFile() { try { return new FreeColTcFile(getTC()); } catch (IOException ioe) {} return null; } /** * Gets the timeout. * Use the command line specified one if any, otherwise default * to `infinite' in single player and the TIMEOUT_DEFAULT for * multiplayer. * * @param singlePlayer True if this is a single player game. * @return A suitable timeout value. */ public static int getTimeout(boolean singlePlayer) { return (timeout >= TIMEOUT_MIN) ? timeout : (singlePlayer) ? Integer.MAX_VALUE : TIMEOUT_DEFAULT; } /** * Sets the timeout. * * @param timeout A string containing the new timeout. * @return True if the timeout was set. */ public static boolean setTimeout(String timeout) { try { int result = Integer.parseInt(timeout); if (result >= TIMEOUT_MIN) { FreeCol.timeout = result; return true; } } catch (NumberFormatException nfe) {} return false; } /** * Gets the current version of game. * * @return The current version of the game using the format "x.y.z", * where "x" is major, "y" is minor and "z" is revision. */ public static String getVersion() { return FREECOL_VERSION; } /** * Sets the window size. * * Does not fail because any empty or invalid value is interpreted as * `windowed but use as much screen as possible'. * * @param arg The window size specification. */ private static void setWindowSize(String arg) { String[] xy; if (arg != null && (xy = arg.split("[^0-9]")) != null && xy.length == 2) { try { windowSize = new Dimension(Integer.parseInt(xy[0]), Integer.parseInt(xy[1])); } catch (NumberFormatException nfe) {} } if (windowSize == null) windowSize = new Dimension(-1, -1); } /** * Utility to make a load failure message. * * @param file The <code>File</code> that failed to load. * @return A <code>StringTemplate</code> with the error message. */ public static StringTemplate badLoad(File file) { return StringTemplate.template("error.couldNotLoad") .addName("%name%", file.getPath()); } /** * Utility to make a save failure message. * * @param file The <code>File</code> that failed to save. * @return A <code>StringTemplate</code> with the error message. */ public static StringTemplate badSave(File file) { return StringTemplate.template("error.couldNotSave") .addName("%name%", file.getPath()); } /** * We get a lot of lame bug reports with insufficient configuration * information. Get a buffer containing as much information as we can * to embed in the log file and saved games. * * @return A <code>StringBuilder</code> full of configuration information. */ public static StringBuilder getConfiguration() { File autosave = FreeColDirectories.getAutosaveDirectory(); File clientOptionsFile = FreeColDirectories.getClientOptionsFile(); File save = FreeColDirectories.getSaveDirectory(); File userConfig = FreeColDirectories.getUserConfigDirectory(); File userData = FreeColDirectories.getUserDataDirectory(); File userMods = FreeColDirectories.getUserModsDirectory(); StringBuilder sb = new StringBuilder(256); sb.append("Configuration:") .append("\n version ").append(getRevision()) .append("\n java: ").append(JAVA_VERSION) .append("\n memory: ").append(MEMORY_MAX) .append("\n locale: ").append(locale) .append("\n data: ") .append(FreeColDirectories.getDataDirectory().getPath()) .append("\n userConfig: ") .append((userConfig == null) ? "NONE" : userConfig.getPath()) .append("\n userData: ") .append((userData == null) ? "NONE" : userData.getPath()) .append("\n autosave: ") .append((autosave == null) ? "NONE" : autosave.getPath()) .append("\n logFile: ") .append(FreeColDirectories.getLogFilePath()) .append("\n options: ") .append((clientOptionsFile == null) ? "NONE" : clientOptionsFile.getPath()) .append("\n save: ") .append((save == null) ? "NONE" : save.getPath()) .append("\n userMods: ") .append((userMods == null) ? "NONE" : userMods.getPath()); return sb; } // The major final actions. /** * Start a client. * * @param userMsg An optional user message key. */ private static void startClient(String userMsg) { Specification spec = null; File savegame = FreeColDirectories.getSavegameFile(); if (debugStart) { spec = FreeCol.getTCSpecification(); } else if (fastStart) { if (savegame == null) { // continue last saved game if possible, // otherwise start a new one savegame = FreeColDirectories.getLastSaveGameFile(); if (savegame == null) { spec = FreeCol.getTCSpecification(); } } // savegame was specified on command line } final FreeColClient freeColClient = new FreeColClient(splashStream, fontName, guiScale, headless); freeColClient.startClient(windowSize, userMsg, sound, introVideo, savegame, spec); } /** * Start the server. */ private static void startServer() { logger.info("Starting stand-alone server."); final FreeColServer freeColServer; File saveGame = FreeColDirectories.getSavegameFile(); if (saveGame != null) { try { final FreeColSavegameFile fis = new FreeColSavegameFile(saveGame); freeColServer = new FreeColServer(fis, (Specification)null, serverPort, serverName); if (checkIntegrity) { boolean integrityOK = freeColServer.getIntegrity() > 0; gripe((integrityOK) ? "cli.check-savegame.success" : "cli.check-savegame.failure"); System.exit((integrityOK) ? 0 : 2); } } catch (Exception e) { if (checkIntegrity) gripe("cli.check-savegame.failure"); fatal(Messages.message(badLoad(saveGame)) + ": " + e.getMessage()); return; } } else { Specification spec = FreeCol.getTCSpecification(); try { freeColServer = new FreeColServer(publicServer, false, spec, serverPort, serverName); } catch (Exception e) { fatal(Messages.message("server.initialize") + ": " + e.getMessage()); return; } if (publicServer && freeColServer != null && !freeColServer.getPublicServer()) { gripe(Messages.message("server.noRouteToServer")); } } String quit = FreeCol.SERVER_THREAD + "Quit Game"; Runtime.getRuntime().addShutdownHook(new Thread(quit) { @Override public void run() { freeColServer.getController().shutdown(); } }); } }
Java
UTF-8
864
2.953125
3
[]
no_license
package leetcode.d78; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if(nums == null || nums.length == 0){ return result; } Arrays.sort(nums); dfs(nums,0,new ArrayList<>(),result); return result; } private void dfs(int[] nums, int index, ArrayList<Integer> tmpList, List<List<Integer>> result) { result.add(new ArrayList<>(tmpList)); for(int i = index; i < nums.length ; i++){ tmpList.add(nums[i]); dfs(nums,i + 1,tmpList,result); tmpList.remove(tmpList.size() - 1); } } public static void main(String[] args) { new Solution().subsets(new int[]{1,2,3}); } }
C++
UTF-8
1,889
3.75
4
[]
no_license
/* * File: main.cpp * Author: Daniel Wallander * * Created on January 17, 2018, 6:12 PM */ #include <iostream> using namespace std; int main(int argc, char** argv) { string name1,name2,name3; int time1,time2,time3; cout <<"Type the first name of the first runner: "; cin >>name1; cout <<"How many seconds did it take for him/her " "to complete the race? "; cin >>time1; cout <<"Type the name of the second runner: "; cin >>name2; cout <<"How many seconds did it take for him/her " "to complete the race? "; cin >>time2; cout <<"Type the name of the third runner: "; cin >>name3; cout <<"How many seconds did it take for him/her " "to complete the race? "; cin >>time3; if (time1 > time2 && time2 >time3) { cout <<"1st place: "<<name1<<endl; cout <<"2nd place: "<<name2<<endl; cout <<"3rd place: "<<name3<<endl; } if (time1 > time3 && time3 >time2) { cout <<"1st place: "<<name1<<endl; cout <<"2nd place: "<<name3<<endl; cout <<"3rd place: "<<name2<<endl; } if (time2 > time1 && time1 >time3) { cout <<"1st place: "<<name2<<endl; cout <<"2nd place: "<<name1<<endl; cout <<"3rd place: "<<name3<<endl; } if (time3 > time1 && time1 >time2) { cout <<"1st place: "<<name3<<endl; cout <<"2nd place: "<<name1<<endl; cout <<"3rd place: "<<name2<<endl; } if (time2 > time3 && time3 >time1) { cout <<"1st place: "<<name2<<endl; cout <<"2nd place: "<<name3<<endl; cout <<"3rd place: "<<name1<<endl; } if (time3 > time2 && time2 >time1) { cout <<"1st place: "<<name3<<endl; cout <<"2nd place: "<<name2<<endl; cout <<"3rd place: "<<name1<<endl; } return 0; }
Markdown
UTF-8
1,687
2.6875
3
[ "MIT", "BSD-3-Clause" ]
permissive
--- layout: post title: The sea is the sea date: 2018-10-18 00:01:00.000000000 +08:00 type: post published: true status: publish categories: - blog tags: [poem, puisi, yuna] --- This is an intro from one of the Yuna's songs. A deep parable. <br><br> <hr> <br> Sometimes you find yourself trying to let go of something <br>But it's like, you have been swimming on the ocean for a very very long time <br>And you feel like you belong there <br>You are one with the waves <br>The warmth of the water <br>And your body moves in sync with the ocean <br>And you swim around just trying to stay afloat <br>Then you get tired and you start to drown <br>And you swim back to land <br>When you get there you just feel so heavy because you lost touch with gravity for so long <br>And you collapse on the beach as you try to find balance again <br>And then your feet finds gravity <br>You stand up and you look at the horizon one last time <br>And you just know that no matter how beautiful the sea was <br>And how good it made you feel It was never yours to keep <br>And somedays you'll miss it, you know <br>And you feel yourself moving with the waves and you dream of diving in <br>Then you realize your feet was meant for land <br>And not cut out for the ocean <br>Maybe you're meant to climb trees, or hike hills, or just run really fast <br>Letting go is not easy <br>There's nothing quite like swimming in the ocean <br>Just like how it's natural for your feet to find gravity <br>It's natural for you to let go <br>And find your true purpose in life again <br>The sea is the sea <br>And you are just you <br><br>I have to let go <br>But sometimes I find myself waking up at the beach again
TypeScript
UTF-8
485
2.71875
3
[]
no_license
import { BaseCommandInteraction, Message } from 'discord.js'; export default interface Command { /** * List of aliases for the command. * The first name in the list is the primary command name. */ readonly commandNames: string[]; readonly data?: any; // Usage documentation help(commandPrefix: string): string; // Execute the command run(parsedUserCommand: Message): Promise<void>; runInteraction(parsedUserCommand: BaseCommandInteraction): Promise<void>; }
Java
UTF-8
1,213
3.515625
4
[]
no_license
import java.util.Random; public class largest { private int[] nums; private Random rand = new Random(); public largest(int[] numbers) { this.numbers = numbers; } //find the nth largest number using quickSelect public int nthLargest(int n) throws Exception { if (n >= this.nums.length) { throw new Exception(); } int left = 0; int right = this.nums.length - 1; while (true) { int length = partition(left, right, rand.nextInt(right)); if (length == n && length = left) { return this.nums[n]; }else if (length > n) { //re-establish the bounds for partitioning right = length; } else { left = length; } } } //partition the data with numbers larger than the pivot on the left public int partition(int left, int right, int pivot) { pivotValue = this.nums[pivot]; swap(pivot, right); storeIndex = left; for (int i = left; i<right; i++) { if (this.nums[i] > pivotValue) { swap(storeIndex, i); storeIndex++; } } swap(storeIndex, right); return storeIndex; } //swap the numbers at a and b public void swap(int a, int b) { int temp = this.nums[a]; this.nums[a] = this.nums[b]; this.nums[b] = temp; } }
Markdown
UTF-8
1,074
2.796875
3
[]
no_license
--- title: Linux 判断是否安装某个软件 date: 2018-06-27 18:15:26 tags: [linux] --- Linux 中如果想要判断某个软件是否安装过,可以使用 `command` 命令 <!-- more --><!-- toc --> **使用** ```bash $ command -pvV command [arg ...] ``` **实例** ```bash $ command -v java /usr/bin/java $ command -V java java is /usr/bin/java $ command -p java Usage: java [-options] class [args...] (to execute a class) or java [-options] -jar jarfile [args...] (to execute a jar file) where options include: -d32 use a 32-bit data model if available -d64 use a 64-bit data model if available -server to select the "server" VM -zero to select the "zero" VM -dcevm to select the "dcevm" VM The default VM is server. -cp <class search path of directories and zip/jar files> -classpath <class search path of directories and zip/jar files> ... ``` **判断是否安装** ```bash if [ `command -v java` ];then echo 'java 已经安装' fi ```
Java
UTF-8
1,503
2.078125
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright (c) 2006-2010 eBay Inc. All Rights Reserved. * 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 *******************************************************************************/ package org.ebayopensource.turmeric.eclipse.repositorysystem.ui.pref; import org.ebayopensource.turmeric.eclipse.repositorysystem.preferences.core.PreferenceConstants; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; /** * The listener interface for receiving preference events. * The class that is interested in processing a preference * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addPreferenceListener</code> method. When * the preference event occurs, that object's appropriate * method is invoked. * * @author smathew * * This class is not used now. Place holder for future use */ public class PreferenceListener implements IPropertyChangeListener { /** * {@inheritDoc} */ @Override public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals( PreferenceConstants.PREF_REPOSITORY_SYSTEM)) { } } }
Ruby
UTF-8
256
2.90625
3
[]
no_license
_, m = gets.split.map(&:to_i) a = gets.split.map(&:to_i) while m > 0 i = a.index(a.max) tmp_a = a.clone tmp_a.delete(a.max) second_max = tmp_a.max while m > 0 && a[i] > second_max a[i] = (a[i] / 2).floor m -= 1 end end puts a.inject(:+)
Markdown
UTF-8
1,101
3.40625
3
[ "MIT" ]
permissive
--- layout: post title: "04: Function Design Recipe (FDR)" category: "DV/Python" comments: true tags: [python] feature-img: "assets/img/3.jpg" feature-title: "" use_math: true series: "Python Basic" summary: "파이썬에서 변수는 어떻게 구성되어 있을까?" --- # Function Design Recipe (FDR) 우리는 파이썬에서 제공하는 다양한 내장 함수들에 대한 설명을 보고싶을때, `help()` 함수를 통해 정보를 확인할 수 있었다. 마찬가지로 내가 정의한 함수를 `help()` 를 통해 설명을 볼 수 있게 하는 것이 좋은 개발자의 방향이다. ```python def convert_to_celsius(fahrenheit): """ (int) -> int #1 Return the celcius number from the given fahrenheit number. #2 >>> Return the celsius(212) #3 100 #4 """ #5 return (fahrenheit - 32) * 5/9 ``` 함수를 선언하고 `"""` 을 써준뒤 주석을 달아준다. 이 때, 1. 입력파라미터와 리턴값을 써준다. 2. 함수의 설명을 써준다. 3. 예제를 써준다. 이 세가지를 두루한다면 가장 완벽한 주석이 될 거다!
C
UTF-8
226
3.515625
4
[]
no_license
#include "holberton.h" #include <stdio.h> /** * _abs - computes de absolute value of an integer *@n: is a variable * Return: Always 0. * */ int _abs(int n) { if (n >= 0) { return (n); } else { return (-n); } }
C#
UTF-8
747
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace person { public class Person { private string name; private string photo; public Person(string aName) { Name = aName; Photo = null; } public string Name { get { return name; } set { name = value; } } public string Photo { get { return photo; } set { photo = value; } } } }
Markdown
UTF-8
1,509
4.125
4
[]
no_license
--- title: C++ Vector begin() function permalink: /cpp-vector-begin --- ## C++ Vector begin() Function <br/><br/> The C++ vector.begin() function returns an iterator to the first element of a vector. This function takes no parameters. If the vector is empty, the returned iterator will be equal to end(). <br/><br/> Syntax: ```cpp v1.begin(); ``` Returns an iterator to the first element of a vector <br/><br/> <p align="center"> <img width="700" height="202" src="images\videos\Cpp11\vector_begin_end.jpg" title="Vector.begin() Example"> </p> <br/><br/> This example uses the assign function with the first and last parameters to assign the value of another vector (v1) to vector v2. We are using the vector begin and end functions to retrieve the starting and ending elements of vector v1 and using them in the vector assign() parameter list. ```cpp std::vector<int> v1 {1,2,3,4,5}; std::vector<int> v2; v2.assign(v1.begin(), v1.end()); for( v : v2 ) std::cout << v2 << " "; ``` Output: 1 2 3 4 5 <br/><br/><br/> This example is a complete program using vector the begin() function to print the contents of a vector. We are also using the vector end() function to determine the number of elements in the vector to iterate through. ```cpp #include<iostream> #include<vector> int main() { std::vector<int> v1{1,2,3,4,5,6}; for(std::vector<int>::iterator itr = v1.begin();itr !=v1.end();itr++) std::cout << * itr << " "; return 0; } ``` Output: 1 2 3 4 5 6 <br/><br/> <br/><br/>
PHP
UTF-8
4,423
2.515625
3
[]
no_license
<?php /** * Auto generated from m2maas.proto at 2018-07-02 09:18:05 * * mapgoo.mlb.m2maas.request.data package */ namespace Mapgoo\Mlb\M2maas\Request\Data { /** * RequestBaseInfo message */ class RequestBaseInfo extends \ProtobufMessage { /* Field index constants */ const MESSAGEID = 1; const SOURETYPE = 2; const SYNCTYPE = 3; const CALLBACKURL = 4; const PRIORITY = 5; /* @var array Field descriptors */ protected static $fields = array( self::MESSAGEID => array( 'name' => 'messageId', 'required' => true, 'type' => \ProtobufMessage::PB_TYPE_STRING, ), self::SOURETYPE => array( 'name' => 'soureType', 'required' => true, 'type' => \ProtobufMessage::PB_TYPE_INT, ), self::SYNCTYPE => array( 'name' => 'syncType', 'required' => true, 'type' => \ProtobufMessage::PB_TYPE_INT, ), self::CALLBACKURL => array( 'name' => 'callbackUrl', 'required' => false, 'type' => \ProtobufMessage::PB_TYPE_STRING, ), self::PRIORITY => array( 'name' => 'priority', 'required' => true, 'type' => \ProtobufMessage::PB_TYPE_INT, ), ); /** * Constructs new message container and clears its internal state */ public function __construct() { $this->reset(); } /** * Clears message values and sets default ones * * @return null */ public function reset() { $this->values[self::MESSAGEID] = null; $this->values[self::SOURETYPE] = null; $this->values[self::SYNCTYPE] = null; $this->values[self::CALLBACKURL] = null; $this->values[self::PRIORITY] = null; } /** * Returns field descriptors * * @return array */ public function fields() { return self::$fields; } /** * Sets value of 'messageId' property * * @param string $value Property value * * @return null */ public function setMessageId($value) { return $this->set(self::MESSAGEID, $value); } /** * Returns value of 'messageId' property * * @return string */ public function getMessageId() { $value = $this->get(self::MESSAGEID); return $value === null ? (string)$value : $value; } /** * Sets value of 'soureType' property * * @param integer $value Property value * * @return null */ public function setSoureType($value) { return $this->set(self::SOURETYPE, $value); } /** * Returns value of 'soureType' property * * @return integer */ public function getSoureType() { $value = $this->get(self::SOURETYPE); return $value === null ? (integer)$value : $value; } /** * Sets value of 'syncType' property * * @param integer $value Property value * * @return null */ public function setSyncType($value) { return $this->set(self::SYNCTYPE, $value); } /** * Returns value of 'syncType' property * * @return integer */ public function getSyncType() { $value = $this->get(self::SYNCTYPE); return $value === null ? (integer)$value : $value; } /** * Sets value of 'callbackUrl' property * * @param string $value Property value * * @return null */ public function setCallbackUrl($value) { return $this->set(self::CALLBACKURL, $value); } /** * Returns value of 'callbackUrl' property * * @return string */ public function getCallbackUrl() { $value = $this->get(self::CALLBACKURL); return $value === null ? (string)$value : $value; } /** * Sets value of 'priority' property * * @param integer $value Property value * * @return null */ public function setPriority($value) { return $this->set(self::PRIORITY, $value); } /** * Returns value of 'priority' property * * @return integer */ public function getPriority() { $value = $this->get(self::PRIORITY); return $value === null ? (integer)$value : $value; } } }
Java
UTF-8
438
1.929688
2
[]
no_license
package esadrcanfer.us.alumno.autotesting.inagraph.actions; import androidx.test.uiautomator.UiObject; import androidx.test.uiautomator.UiObjectNotFoundException; public class SpinnerAction extends Action { public SpinnerAction(UiObject spinner) { super(spinner, ActionType.SPINNER); } public void perform() throws UiObjectNotFoundException { value = target.getText(); this.target.click(); } }
Java
UTF-8
7,468
1.890625
2
[ "MIT" ]
permissive
package fr.adrienbrault.idea.symfony2plugin.util.completion; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.completion.CompletionUtil; import com.intellij.codeInsight.completion.InsertHandler; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.psi.PsiElement; import com.jetbrains.php.PhpBundle; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.completion.PhpCompletionUtil; import com.jetbrains.php.completion.PhpLookupElement; import com.jetbrains.php.completion.PhpVariantsUtil; import com.jetbrains.php.completion.insert.PhpInsertHandlerUtil; import com.jetbrains.php.lang.psi.elements.Field; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpNamedElement; import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider; import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProviderLookupArguments; import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; public class PhpConstGotoCompletionProvider extends GotoCompletionProvider { private static final String[] SPECIAL_STUB_CONSTANTS = new String[]{"true", "false", "null"}; private static final String SCOPE_OPERATOR = "::"; public PhpConstGotoCompletionProvider(@NotNull PsiElement element) { super(element); } @Override public void getLookupElements(@NotNull GotoCompletionProviderLookupArguments arguments) { PhpIndex phpIndex = PhpIndex.getInstance(this.getProject()); CompletionResultSet resultSet = arguments.getResultSet(); var elementText = getElement().getText(); var scopeOperatorPos = elementText.indexOf(SCOPE_OPERATOR); var cursorPos = elementText.indexOf(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED); // Class constants: !php/const Foo::<caret> if (scopeOperatorPos > -1 && scopeOperatorPos < cursorPos) { var prefix = elementText.replace(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED, ""); var classFQN = prefix.substring(0, scopeOperatorPos); var phpClass = PhpElementsUtil.getClassInterface(this.getProject(), classFQN); if (phpClass != null) { // reset the prefix matcher, starting after :: resultSet = resultSet.withPrefixMatcher(prefix.substring(prefix.indexOf(SCOPE_OPERATOR) + 2)); resultSet.addAllElements(PhpVariantsUtil.getLookupItems(phpClass.getFields().stream().filter(f -> f.isConstant() && f.getModifier().isPublic()).collect(Collectors.toList()), false, null)); } return; } Collection<LookupElement> elements = new ArrayList<>(); // Global constants: !php/const BAR for (String constantName : phpIndex.getAllConstantNames(resultSet.getPrefixMatcher())) { if (Arrays.asList(SPECIAL_STUB_CONSTANTS).contains(constantName)) { continue; } elements.addAll(PhpVariantsUtil.getLookupItems(phpIndex.getConstantsByName(constantName), false, null)); } if (arguments.getParameters().getInvocationCount() <= 1) { String completionShortcut = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction("CodeCompletion")); resultSet.addLookupAdvertisement(PhpBundle.message("completion.press.again.to.see.more.variants", completionShortcut)); // Classes and interfaces: !php/const Foo for (String className : phpIndex.getAllClassNames(resultSet.getPrefixMatcher())) { addAllClasses(elements, phpIndex.getClassesByName(className)); addAllClasses(elements, phpIndex.getInterfacesByName(className)); } } else { // Constants from all classes and interfaces: !php/const Foo::BAR for (String className : phpIndex.getAllClassNames(null)) { addAllClassConstants(elements, phpIndex.getClassesByName(className)); addAllClassConstants(elements, phpIndex.getInterfacesByName(className)); } } arguments.addAllElements(elements); } private void addAllClasses(Collection<LookupElement> elements, Collection<PhpClass> classes) { for (PhpClass phpClass : classes) { // Filter by classes only with constants (including inherited constants) if (PhpElementsUtil.hasClassConstantFields(phpClass)) { elements.add(wrapClassInsertHandler(new MyPhpLookupElement(phpClass))); } } } private void addAllClassConstants(Collection<LookupElement> elements, Collection<PhpClass> classes) { for (PhpClass phpClass : classes) { // All class constants List<Field> fields = Arrays.stream(phpClass.getOwnFields()).filter(f -> f.isConstant() && f.getModifier().isPublic()).collect(Collectors.toList()); for (PhpNamedElement field : fields) { // Foo::BAR String lookupString = phpClass.getName() + SCOPE_OPERATOR + field.getName(); elements.add(wrapClassConstInsertHandler(new MyPhpLookupElement(field, lookupString))); } } } private static MyPhpLookupElement wrapClassInsertHandler(MyPhpLookupElement lookupElement) { return lookupElement.withInsertHandler(PhpClassWithScopeOperatorInsertHandler.getInstance()); } private static MyPhpLookupElement wrapClassConstInsertHandler(MyPhpLookupElement lookupElement) { return lookupElement.withInsertHandler(PhpReferenceTrimBackslashInsertHandler.getInstance()); } private static class MyPhpLookupElement extends PhpLookupElement { MyPhpLookupElement(@NotNull PhpNamedElement namedElement) { super(namedElement); } MyPhpLookupElement(@NotNull PhpNamedElement namedElement, @NotNull String lookupString) { super(namedElement); this.lookupString = lookupString; } MyPhpLookupElement withInsertHandler(InsertHandler insertHandler) { this.handler = insertHandler; return this; } } public static class PhpClassWithScopeOperatorInsertHandler extends PhpReferenceTrimBackslashInsertHandler { private static final PhpClassWithScopeOperatorInsertHandler instance = new PhpClassWithScopeOperatorInsertHandler(); public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) { super.handleInsert(context, lookupElement); if (context.getCompletionChar() == ':') { context.setAddCompletionChar(false); } if (!PhpInsertHandlerUtil.isStringAtCaret(context.getEditor(), SCOPE_OPERATOR)) { PhpInsertHandlerUtil.insertStringAtCaret(context.getEditor(), SCOPE_OPERATOR); } PhpCompletionUtil.showCompletion(context); } public static PhpClassWithScopeOperatorInsertHandler getInstance() { return instance; } } }
C++
UTF-8
631
2.65625
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include "imgui.h" #include "imgui-SFML.h" #include "window.h" class GameBase { private: Window window; protected: // Sets up anything needed for the window. virtual void setup() = 0; // Updates anything needed for the current class. virtual const bool update(const sf::Event& event, const float tickRate) = 0; // Draws everything to the screen. virtual void draw(Window& window, const float alpha) = 0; public: GameBase(); ~GameBase(); // Starts the game loop. const bool run(); };
C++
UTF-8
417
2.765625
3
[]
no_license
#ifndef PRODUCT_H #define PRODUCT_H #include <QString> class Product { private: QString id; QString nameProduct; double priceProduct; public: Product(); QString getId() const; void setId(const QString &value); QString getNameProduct() const; void setNameProduct(const QString &value); double getPriceProduct() const; void setPriceProduct(double value); }; #endif // PRODUCT_H
JavaScript
UTF-8
3,511
3.75
4
[]
no_license
// Function constructor /* var john = { name: 'John', yearOfBirth: 1990, job: 'teacher' }; var Person = function(name, yearOfBirth, job) { this.name = name; this.yearOfBirth = yearOfBirth; this.job = job; }; Person.prototype.calculateAge = function() { console.log(2016 - this.yearOfBirth); }; Person.prototype.lastName = 'Smith'; var john = new Person('John', 1990, 'teacher'); john.calculateAge(); var jane = new Person('jane', 1969, 'designer'); var mark var personProto = { calculateAge: function() { console.log(2016 - this.yearOfBirth); } }; var john = Object.create(personProto); */ /* var years = [1990, 1965, 1937, 2005, 1998]; function arrayCalc(arr, fn) { var arrRes = []; for (var i = 0; i <arr.length; i++) { arrRes.push(fn(arr[i])); } return arrRes; } function calculateAge(el) { return 2016 - el; } function isFullAge(el) { return el >= 18; } function maxHeartRate(el) { if (el >= 18 && el <= 81) { return Math.round(206.9 - (0.67 * el)); } else { return -1; } } var ages = arrayCalc(years, calculateAge); var fullAges = arrayCalc(ages, isFullAge); var rates = arrayCalc(ages, maxHeartRate); console.log(ages); console.log(fullAges); console.log(rates); */ /* function interviewQuestion(job) { if (job === 'designer') { return function(name) { console.log(name + ', can you please explain what UX design is?'); } } else if (job === 'teacher') { return function(name) { console.log('What subject do you teach, ' + name + '?'); } } else { return function(name) { console.log('Hello, ' + name + 'what do you do?'); } } } var teacherQuestion = interviewQuestion('teacher'); teacherQuestion('John'); */ /* function retirement(retirementAge) { var a = ' years left until retirement.'; return function(yearOfBirth) { var age = 2016 - yearOfBirth; console.log((retirementAge - age) + a); } } var retirementUS = retirement(66); retirement(66)(1990); retirementUS(1990); */ /* function interviewQuestion(job) { return function(name) { if (job === 'designer') { return console.log(name + ', can you please explain what UX design is?'); } else if (job === 'teacher') { return console.log('What subject do you teach, ' + name + '?'); } else { return console.log('Hello, ' + name + 'what do you do?'); } } } interviewQuestion('teacher')('Jane'); */ // CODING CHALLENGE var Question = function(question, answerChoices, correctAnswer) { this.question = question; this.answerChoices = answerChoices; this.correctAnswer = correctAnswer; } var firstQuestion = new Question('What year is it?', ['0: 2018', '1: 2019', '2: 2020'], 1); var secondQuestion = new Question('What month is it?', ['0: Jan', '1: Feb', '2: Mar'], 1); var thirdQuestion = new Question('What day number is it?', ['0: 20th', '1: 21st', '2: 22nd'], 1); var arrQuestions = [firstQuestion, secondQuestion, thirdQuestion]; function randQuestion(arr) { return arr[Math.random() * arr.length]; } var currQuestion = randQuestion(arrQuestions); console.log(currQuestion.question); console.log(currQuestion.answerChoices[0]); console.log(currQuestion.answerChoices[1]); console.log(currQuestion.answerChoices[2]); var answer = prompt('Please enter you answer below:'); console.log(answer);
JavaScript
UTF-8
764
2.515625
3
[]
no_license
const express = require('express'); const app = express(); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const cors = require('cors'); require('dotenv/config'); //Any time we hit any request //Middlewares app.use(cors()); app.use(bodyParser.json()); //Import Routes const personsRoute = require('./routes/persons'); app.use('/persons', personsRoute); //ROUTES app.get('/', (req, res) => { res.send('We are on home'); }); //Connect to DB mongoose.connect( process.env.DB_CONNECTION, { useNewUrlParser: true }, () => console.log('connected to rememberme\'s database') ); //Start listening to the server const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Listening on port ${port}`));
Python
UTF-8
518
2.921875
3
[]
no_license
n=int(input()) x=input().split(' ') y=input().split(' ') a=[] i=0 while i<n: a.append(int(x[i])) i=i+1 b=[] i=0 while i<n: b.append(int(y[i])) i=i+1 a.sort() b.sort() c=[] i=0 while i<n: c.append((i+1)*(n-i)) i=i+1 s=0 mod=998244353 i=0 ts=0 while i<n: ts=(ts+(a[i]*b[i])%mod)%mod s=(s+ts)%mod i=i+1 ##print(s) i=0 ts=s while i<n-1: ts=(ts-((a[i]*b[i])%mod*(n-i))%mod)%mod ## print(ts) s=(s+ts)%mod i=i+1 print(s)
Java
UTF-8
368
2.265625
2
[]
no_license
package graph.link; import graph.node.INode; public interface IEdge { /** * gets owner node * @return */ public INode getOwnerNode(); /** * gets owner id * @return */ public int getOwnerId(); /** * gets linked node * @return */ public INode getLinkedNode(); /** * gets cost of this edge * @return */ public int getCost(); }
Java
UTF-8
841
2.953125
3
[]
no_license
package com.javarush.task.task22.task2210; import java.util.StringTokenizer; /* StringTokenizer */ public class Solution { public static void main(String[] args) { /*int count = getTokens("level22.lesson13.task01", ".").length; String[] arch = getTokens("level22.lesson13.task01", "."); for (int i = 0; i < count; i++) { System.out.println(arch[i]); }*/ } public static String [] getTokens(String query, String delimiter) { StringTokenizer tokenizer = new StringTokenizer(query, delimiter); int count = tokenizer.countTokens(); String[] arch = new String[count]; while (tokenizer.hasMoreTokens()) { for (int i = 0; i < count; i++) { arch[i] = tokenizer.nextToken(); } } return arch; } }
Python
UTF-8
1,613
2.546875
3
[]
no_license
from mcpi.minecraft import Minecraft import mcpi.block as block #pos.x,pos.y,pos.z def roof(x0,y0,z0,L,W,H,M): p=open("roof.csv",'r').read().split('\n') a=-1 for i in p: a=a+1 b=-1 for j in i: b=b+1 if j=='1': mc.setBlock (x0+1+b,y0+H,z0+a,M) return def house(x0,y0,z0,L,W,H,M1,Mroof): for a in range(L): for j in range(W): for k in range(H): mc.setBlock (x0+1+a,y0+j,z0+k,M1) for a in range(L-2): for j in range(W-2): for k in range(H-2): mc.setBlock (x0+2+a,y0+1+j,z0+1+k,0) mc.setBlock (x0+1,y0+1,z0+W/2,0) mc.setBlock (x0+1,y0+2,z0+W/2,0) mc.setBlock (x0,y0,z0+W/2,M1) mc.setBlock (x0,y0+2,z0+W/2+1,50) mc.setBlock (x0,y0+2,z0+W/2-1,50) mc.setBlock (x0+L-1,y0+H-2,z0+W-2,50) mc.setBlock (x0+L-1,y0+H-2,z0+1,50) mc.setBlock (x0+L-1,y0+1,z0+1,26) mc.setBlock (x0+L-1,y0+1,z0+2,26) roof(x0,y0,z0,L,W,H,Mroof) for a in range(2): for j in range(2): mc.setBlock (x0+L/2+a,y0+H-4+j,z0+W-1,20) return def clear(L): pos=mc.player.getTilePos() for a in range(-L,L+1): for b in range(-L,L+1): for c in range(-L,L+1): mc.setBlock (pos.x+a,pos.y+b,pos.z+c,0) return def manyhouse(x0,y0,z0,L,W,H,M,n): for a in range(0,2*n*L,2*L): for j in range(0,2*n*L,2*L): for k in range(0,2*n*L,2*L): house(x0+a,y0+j,z0+k,L,W,H,M) return mc=Minecraft.create() pos=mc.player.getTilePos() while True: clear(100)
Java
UTF-8
626
2.25
2
[]
no_license
package com.edm.order.service; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.inject.Inject; import javax.inject.Named; import javax.validation.constraints.NotNull; import com.edm.order.domain.Order; import com.edm.order.repo.OrderRepository; @Named public class OrderQueryService { @Inject OrderRepository orderRepository; public Order getOrder(@NotNull UUID orderId) { return orderRepository.findById(orderId).get(); } public List<Order> getAllOrders() { List<Order> orders = new ArrayList<>(); orderRepository.findAll().forEach(orders::add); return orders; } }
Java
UTF-8
5,766
2.109375
2
[]
no_license
/* */ package org.jfree.data.jdbc; /* */ /* */ import java.sql.Connection; /* */ import java.sql.DriverManager; /* */ import java.sql.ResultSet; /* */ import java.sql.ResultSetMetaData; /* */ import java.sql.SQLException; /* */ import java.sql.Statement; /* */ import java.sql.Timestamp; /* */ import org.jfree.data.general.DefaultPieDataset; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class JDBCPieDataset /* */ extends DefaultPieDataset /* */ { /* */ static final long serialVersionUID = -8753216855496746108L; /* */ private Connection connection; /* */ /* */ public JDBCPieDataset(String url, String driverName, String user, String password) throws SQLException, ClassNotFoundException { /* 106 */ Class.forName(driverName); /* 107 */ this.connection = DriverManager.getConnection(url, user, password); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public JDBCPieDataset(Connection con) { /* 118 */ if (con == null) { /* 119 */ throw new NullPointerException("A connection must be supplied."); /* */ } /* 121 */ this.connection = con; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public JDBCPieDataset(Connection con, String query) throws SQLException { /* 136 */ this(con); /* 137 */ executeQuery(query); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 152 */ public void executeQuery(String query) throws SQLException { executeQuery(this.connection, query); } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public void executeQuery(Connection con, String query) throws SQLException { /* 169 */ statement = null; /* 170 */ resultSet = null; /* */ /* */ try { /* 173 */ statement = con.createStatement(); /* 174 */ resultSet = statement.executeQuery(query); /* 175 */ metaData = resultSet.getMetaData(); /* */ /* 177 */ int columnCount = metaData.getColumnCount(); /* 178 */ if (columnCount != 2) { /* 179 */ throw new SQLException("Invalid sql generated. PieDataSet requires 2 columns only"); /* */ } /* */ /* */ /* */ /* 184 */ int columnType = metaData.getColumnType(2); /* */ /* 186 */ while (resultSet.next()) { /* 187 */ Timestamp date; double value, value; Comparable key = resultSet.getString(1); /* 188 */ switch (columnType) { /* */ case -5: /* */ case 2: /* */ case 3: /* */ case 4: /* */ case 6: /* */ case 7: /* */ case 8: /* 196 */ value = resultSet.getDouble(2); /* 197 */ setValue(key, value); /* */ continue; /* */ /* */ case 91: /* */ case 92: /* */ case 93: /* 203 */ date = resultSet.getTimestamp(2); /* 204 */ value = date.getTime(); /* 205 */ setValue(key, value); /* */ continue; /* */ } /* */ /* 209 */ System.err.println("JDBCPieDataset - unknown data type"); /* */ } /* */ /* */ /* */ /* */ /* 215 */ fireDatasetChanged(); /* */ } /* */ finally { /* */ /* 219 */ if (resultSet != null) { /* */ try { /* 221 */ resultSet.close(); /* */ } /* 223 */ catch (Exception e) { /* 224 */ System.err.println("JDBCPieDataset: swallowing exception."); /* */ } /* */ } /* 227 */ if (statement != null) { /* */ try { /* 229 */ statement.close(); /* */ } /* 231 */ catch (Exception e) { /* 232 */ System.err.println("JDBCPieDataset: swallowing exception."); /* */ } /* */ } /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public void close() { /* */ try { /* 244 */ this.connection.close(); /* */ } /* 246 */ catch (Exception e) { /* 247 */ System.err.println("JdbcXYDataset: swallowing exception."); /* */ } /* */ } /* */ } /* Location: /Users/micahnut/Downloads/MiniSP.jar!/org/jfree/data/jdbc/JDBCPieDataset.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.0.3 */
Python
UTF-8
3,960
2.609375
3
[]
no_license
import ctypes import numpy as np import pandas as pd import codecs import os ##工具 lib_lcs = ctypes.CDLL('lcs.so') dict_word2vec = None ndim_word2vec = None set_wr = None dict_wordsame = None set_stopword = None #lcs def make_carray(s): n = len(s) array = (ctypes.c_int*n)() for i in range(n): array[i] = ord(s[i]) return array def lcs(s1,s2): c1 = make_carray(s1) c2 = make_carray(s2) return lib_lcs.lcs(c1,c2,len(s1),len(s2)) #word2vec def word2vec(word): if dict_word2vec is None: load_word2vec('word2vec.txt') if word in dict_word2vec: return dict_word2vec[word] else: return np.random.uniform(-0.1,0.1,ndim_word2vec) def load_word2vec(file): print("load word2vec") f = codecs.open(file, encoding='utf-8') global dict_word2vec global ndim_word2vec n,ndim_word2vec = map(int,f.readline().strip().split()) dict_word2vec = {} for i in range(n): line = f.readline() ls = line.strip().split() dict_word2vec[ls[0]] = [float(x) for x in ls[1:]] print("{}/{}".format(i,n),end='\r') print("") def save_word2vec(file): print("save word2vec") global dict_word2vec global ndim_word2vec with codecs.open(file, mode='w', encoding='utf-8') as f: n = len(dict_word2vec) f.write("{} {}\n".format(n,ndim_word2vec)) for i,word in enumerate(dict_word2vec): vec = dict_word2vec[word] f.write("{} {}\n".format(word,' '.join(map(str,vec)))) print("{}/{}".format(i,n),end='\r') print("") #疑问代词 def find_wr(words): for word in words: if is_wr(word): return word return "" def is_wr(word): if set_wr is None: load_wr('wr_vocab.txt') return word in set_wr def load_wr(file): f = codecs.open(file, encoding='utf-8') global set_wr set_wr = set([x.strip() for x in f.readlines()]) #同义词 def is_same(w1, w2): if dict_wordsame is None: load_wordsame('wordsame.txt') if w1 not in dict_wordsame or w2 not in dict_wordsame: return False return len(set(dict_wordsame[w1]).intersection(dict_wordsame[w2])) > 0 def load_wordsame(file): print("load wordsame") global dict_wordsame dict_wordsame = {} f = codecs.open(file, encoding='utf-8') data = f.readlines() for i,s in enumerate(data): g = s.strip().split() for word in g: if word not in dict_wordsame: dict_wordsame[word] = [] dict_wordsame[word].append(i) print("{}/{}".format(i,len(data)),end='\r') print("") #停用词 def is_stopword(word): if set_stopword is None: load_stopword('stopword.txt') return word in set_stopword def load_stopword(file): print("load wordsame") global set_stopword f = codecs.open(file, encoding='utf-8') set_stopword = set([x.strip() for x in f.readlines()]) #数据集文件读入 def load_file(file): f = codecs.open(file, encoding='utf-8') data = [] for line in f: line = line.strip().split('\t') data.append(line) data[-1][0] = int(data[-1][0]) df = pd.DataFrame(data) df.columns = ['label','question','answer'] return df def load_seg_file(file): file_base,file_ext = os.path.splitext(file) seg_file = file_base + '_seg' + file_ext f = codecs.open(seg_file, encoding='utf-8') n = int(f.readline().strip()) data = [] for i in range(n): label = f.readline().strip() q_words = f.readline().strip().split('\t') q_flags = f.readline().strip().split('\t') a_words = f.readline().strip().split('\t') a_flags = f.readline().strip().split('\t') data.append([label, q_words, q_flags, a_words, a_flags]) data[-1][0] = int(data[-1][0]) df = pd.DataFrame(data) df.columns = ['label','q_words','q_flags','a_words','a_flags'] return df def load_feature_file(file): file_base,file_ext = os.path.splitext(file) feature_file = file_base + '_feature' + file_ext if os.path.exists(feature_file): df = pd.read_csv(feature_file) else: df = pd.DataFrame() return df def save_feature_file(file, df): file_base,file_ext = os.path.splitext(file) feature_file = file_base + '_feature' + file_ext df.to_csv(feature_file, index=False)
Java
UTF-8
2,208
2.046875
2
[ "MIT" ]
permissive
package com.example.waygmaptest; import androidx.annotation.NonNull; import androidx.annotation.UiThread; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Color; import android.graphics.PointF; import android.os.Bundle; import com.naver.maps.geometry.LatLng; import com.naver.maps.map.MapFragment; import com.naver.maps.map.NaverMap; import com.naver.maps.map.OnMapReadyCallback; import com.naver.maps.map.overlay.InfoWindow; import com.naver.maps.map.overlay.Marker; public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, NaverMap.OnMapClickListener { NaverMap Map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MapFragment mapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(R.id.map); if(mapFragment == null){ mapFragment = MapFragment.newInstance(); getSupportFragmentManager().beginTransaction().add(R.id.map,mapFragment).commit(); } mapFragment.getMapAsync(this); } @UiThread @Override public void onMapReady(NaverMap naverMap){ naverMap.setMapType(NaverMap.MapType.Basic); naverMap.setSymbolScale(1.5f); Map = naverMap; naverMap.setOnMapClickListener(this); } @Override public void onPointerCaptureChanged(boolean hasCapture) { } @Override public void onMapClick(@NonNull PointF pointF, @NonNull LatLng latLng) { Marker marker1 = new Marker(); marker1.setPosition(latLng); marker1.setMap(Map); marker1.setSubCaptionText("????????"); marker1.setSubCaptionColor(Color.RED); marker1.setSubCaptionHaloColor(Color.YELLOW); marker1.setSubCaptionTextSize(10); InfoWindow infoWindow1 = new InfoWindow(); infoWindow1.setAdapter(new InfoWindow.DefaultTextAdapter(this) { @NonNull @Override public CharSequence getText(@NonNull InfoWindow infoWindow) { return "!!!!!!!!!!!!"; } }); infoWindow1.open(marker1); } }
JavaScript
UTF-8
333
3.546875
4
[]
no_license
function delayAdd(n1, n2, delayTime) { let p = new Promise(function(resolve, reject) { setTimeout(function() { resolve(n1 + n2) }, delayTime) }) return p } async function test() { // await 回傳 Promise 對象 let result = await delayAdd(2, 5, 2000) console.log(result) } test()
Markdown
UTF-8
1,464
3.15625
3
[]
no_license
# fillit 42 School project How to fit an elephant in a glass of whiskey ? Fillit is a project who let you discover and/or familiarize yourself with a recurring problematic in programming : searching for the optimal solution among a huge set of pos- sibilities. In this particular project, we have to create an algorithm which fits some Tetriminos together into the smallest possible square. A Tetriminos is a 4-blocks geometric figure that most of you might knows thanks to the popular game Tetris. Fillit does not consist of recoding Tetris, even if it’s still a variant of this game. The program takes a file as parameter which contains a list of Tetriminos and arranges them to create the smallest square possible. Obviously, main goal is to find this smallest square in the minimal amount of time, despite a exponentially growing number of possibilities each time a piece is added. The program must display the smallest square solution on the standard output. To identify each Tetriminos in the square solution, you will assign a capital letter (starting with ’A’) to each Tetriminos in the order they appear in the file. A file will contain 26 Tetriminos maximum. If the file contains at least one error, the program must display error on the standard output and exit properly. <img width="634" alt="screen shot 2017-07-16 at 11 30 49 pm" src="https://user-images.githubusercontent.com/25576444/28257341-df022a54-6a7e-11e7-86aa-c8b7579d84a9.png">
C++
UTF-8
2,423
2.578125
3
[]
no_license
// // Created by stone on 11/12/19. // // #include <uv.h> #include "portfolio.h" typedef uint64_t uv_timeval64_t; uv_timeval64_t tv; void uv_gettimeofday(uv_timeval64_t* tv) { UNUSED(tv); } namespace portfolio { Int2SessionMap gOnlineSession; String2SessionMap gRawSession; String2Interface gIfMap; String2Software gSoftwareMap; String2Operator gOperatorMap; Interface gInterfaces[1] = { {INTERFACE_ID_NONE, "China Future CTP"} }; Operator gOperator[2] = { {1, 1, "stone go!"}, {2, 128, "superuser"}, }; Software gSoftware[1] = { {1, "Eureka BIT"} }; Session* terminal_online(const char* raw_sid, const char* opname, const char* software, const char* interface, Session_Instance si, int fd) { if (gIfMap.find(interface) == gIfMap.end() || gOperatorMap.find(opname) == gOperatorMap.end() || gSoftwareMap.find(software) == gSoftwareMap.end()) return 0; uv_timeval64_t tv; uv_gettimeofday(&tv); Session* s = new Session; s->instance = gIfMap[interface]; s->software = gSoftwareMap[software]; s->op = gOperatorMap[opname]; s->instance = si; snprintf(s->raw_sid, SESSION_ID_LENGTH, raw_sid); // s->sid = tv.tv_sec * 1000 + tv.tv_usec / 1000; // s->last_act = s->start_time = static_cast<time_t>(tv.tv_sec); s->end_time = 0; s->set_network_params(fd); // // set ip and port from fd // gOnlineSession.insert(std::make_pair(s->sid, s)); gRawSession.insert(std::make_pair(raw_sid, s)); return s; } void terminal_offline(Session* s) { if (s == nullptr) return; auto it = gOnlineSession.find(s->sid); if (it != gOnlineSession.end()) { auto it2 = gRawSession.find((it->second)->raw_sid); if (it2 != gRawSession.end()) gRawSession.erase(it2); if (it->second) delete (it->second); gOnlineSession.erase(it); } } void init_portfolio() { gIfMap.insert(std::make_pair("China Future CTP", gInterfaces + 0)); gSoftwareMap.insert(std::make_pair("Eureka BIT", gSoftware + 0)); gOperatorMap.insert(std::make_pair("stone go!", gOperator + 0)); gOperatorMap.insert(std::make_pair("superuser", gOperator + 1)); } void release_portfolio() { for (auto& pair : gOnlineSession) if (pair.second != nullptr) delete pair.second; gOnlineSession.clear(); gRawSession.clear(); gOperatorMap.clear(); gSoftwareMap.clear(); gIfMap.clear(); } } // namespace portfolio
Java
UTF-8
1,538
3.4375
3
[]
no_license
import java.util.HashSet; import java.util.Queue; public class Solution { /** * @param n: An integer * @param edges: a list of undirected edges * @return: true if it's a valid tree, or false */ public boolean validTree(int n, int[][] edges) { // write your code here if(n==0){ return false; } if(edges.length!=n-1){ return false; } Map<Integer, Set<Integer>> graph = adjacentList(n, edges); Queue<Integer> queue = new LinkedList<Integer>(); Set<Integer> vistedNode = new HashSet<Integer>(); queue.add(0); vistedNode.add(0); while(!queue.isEmpty()){ int node = queue.poll(); for(int i: graph.get(node)){ if(!vistedNode.contains(i)){ vistedNode.add(i); queue.add(i); } } } if(vistedNode.size()!=n){ return false; } return true; } public Map<Integer, Set<Integer>> adjacentList(int n, int[][] edges){ Map<Integer, Set<Integer>> graph = new HashMap<Integer, Set<Integer>>(); for(int i=0; i<n; i++){ graph.put(i, new HashSet<Integer>()); } for(int i=0; i<edges.length; i++){ int node1 = edges[i][0]; int node2 = edges[i][1]; graph.get(node1).add(node2); graph.get(node2).add(node1); } return graph; } }
C
UTF-8
428
2.6875
3
[ "MIT" ]
permissive
#pragma once #include <stdint.h> /* Save linear float 32 bit data represented as a single channeled (r32) * rectangle of width x height size to Radiance HDR RGBE image format * replicating color across other channels. * * https://en.wikipedia.org/wiki/RGBE_image_format * * Returns 0 on success. * */ int image_hdr_save_r32(const char* filename, uint32_t width, uint32_t height, float* f32data);
PHP
UTF-8
1,431
2.65625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class SurveyRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required|max:150', 'surname' => 'required|max:150', 'phone-mobile' => 'required|max:20', 'location' => 'required|integer|exists:locations,id|unique:surveys,location_id,NULL,id,email,'.$this->input('email'), 'email' => 'required|email|max:255', 'district' => 'required|integer', 'type' => 'required' ]; } public function messages() { return [ 'location.unique' => 'Sorry, looks like you have already placed a request for this location', 'location.exists' => 'Select valid location', 'email.email' => 'Your email is invalid', 'phone-mobile.required' => 'The mobile number field is required.', 'location.required' => 'Please select location', 'type.required' => 'Please select type of installation', 'location.integer' => 'Selected location is invalid', ]; } }
Java
UTF-8
255
1.625
2
[]
no_license
package com.myschool.web.application.constants; /** * The Class OrganizationViewNames. */ public class OrganizationViewNames { /** The Constant MANAGE_ORGANIZATION. */ public static final String MANAGE_ORGANIZATION = "manage_organization"; }
C++
UTF-8
4,405
3.65625
4
[]
no_license
/* * Author: cc * Date : 2015-03-01 * Source: https://oj.leetcode.com/problems/valid-sudoku/ * Description: * The Sudoku board could be partially filled, where empty cells are filled with the character '.'. * * each row, col, 3 * 3 grids should only contain 0 ~ 9 * * A partially filled sudoku which is valid. * * Note: * A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. */ #include<iostream> #include<cmath> #include<stack> #include<vector> #include<string> #include<algorithm> #include<unordered_map> using namespace std; bool isValidSudoku(vector<vector<char> > &board) { bool result = true; int length = board.size(); if (length != 9) { return false; } if (board[0].size() != 9) { return false; } //check the row for (int i = 0; i < board.size(); ++i) { unordered_map<char, int> rowMap; for (int j = 0; j < board.size(); ++j) { if (board[i][j] != '.') { if (rowMap.find(board[i][j]) == rowMap.end()) { rowMap.insert(make_pair(board[i][j], 1)); }else{ return false; } } } } //check the coloumn for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board.size(); ++j) { unordered_map<char, int> colMap; for (int j = 0; j < board.size(); ++j) { if (board[j][i] != '.') { if (colMap.find(board[j][i]) == colMap.end()) { colMap.insert(make_pair(board[j][i], 1)); }else{ return false; } } } } } //check the 3 * 3 grids for (int i = 0; i < board.size(); i += 3) { for (int j = 0; j < board.size(); j += 3) { unordered_map<char, int> gridMap; for(int row = i; row < i + 3; row++) { for (int col = j; col < j + 3; col++) { if (board[row][col] != '.') { if (gridMap.find(board[row][col]) == gridMap.end()) { gridMap.insert(make_pair(board[row][col], 1)); }else{ return false; } } } } } } return result; } int main(int argc, char *argv[]) { vector<vector<char> > board; vector<char> row; row.push_back('5'); row.push_back('3'); row.push_back('.'); row.push_back('.'); row.push_back('7'); row.push_back('.'); row.push_back('.'); row.push_back('.'); row.push_back('.'); board.push_back(row); vector<char> row1; row1.push_back('6'); row1.push_back('.'); row1.push_back('.'); row1.push_back('1'); row1.push_back('9'); row1.push_back('5'); row1.push_back('.'); row1.push_back('.'); row1.push_back('.'); board.push_back(row1); vector<char> row2; row2.push_back('.'); row2.push_back('9'); row2.push_back('8'); row2.push_back('.'); row2.push_back('.'); row2.push_back('.'); row2.push_back('.'); row2.push_back('6'); row2.push_back('.'); board.push_back(row2); vector<char> row3; row3.push_back('8'); row3.push_back('.'); row3.push_back('.'); row3.push_back('.'); row3.push_back('6'); row3.push_back('.'); row3.push_back('.'); row3.push_back('.'); row3.push_back('3'); board.push_back(row3); vector<char> row4; row4.push_back('4'); row4.push_back('.'); row4.push_back('.'); row4.push_back('8'); row4.push_back('.'); row4.push_back('3'); row4.push_back('.'); row4.push_back('.'); row4.push_back('1'); board.push_back(row4); vector<char> row5; row5.push_back('.'); row5.push_back('9'); row5.push_back('8'); row5.push_back('.'); row5.push_back('.'); row5.push_back('.'); row5.push_back('.'); row5.push_back('6'); row5.push_back('.'); board.push_back(row5); return 0; }
C
UTF-8
962
3.53125
4
[]
no_license
/* * readAndClear.c * * Created on: 10.07.2018 * Author: Dominik */ #include "readAndClear.h" #include <stdio.h> #include <stdlib.h> void clearChar() { char c; while ((c = getchar()) != '\n' && c != EOF) { } } int scanInt(char* message) { int read = -1; int readChars = 0; while (readChars != 1) { fputs(message, stdout); fputs(" > ", stdout); readChars = scanf("%d", &read); clearChar(); } return read; } char * scanString(char* message) { int readChars = 0; char * string = malloc(sizeof(char) * 21); while (readChars != 1) { fputs(message, stdout); fputs(" > ", stdout); readChars = scanf("%s", string); clearChar(); } string[20] = 0; return string; } char scanChar(char* message) { int readChars = 0; char c = 0; while (readChars != 1) { fputs(message, stdout); fputs(" > ", stdout); readChars = scanf("%c", &c); clearChar(); } return c; }
Java
GB18030
3,554
2.109375
2
[]
no_license
package org.keyuan.entity; import java.io.Serializable; import java.util.Date; import org.compass.annotations.Index; import org.compass.annotations.Searchable; import org.compass.annotations.SearchableProperty; import org.compass.annotations.Store; @Searchable(root=false) public class BookDetail implements Serializable{ private static final long serialVersionUID = -6655417865605887561L; // private Integer detailId; //Ӧͼ private Book book; //༭Ƽ private String editCommentText; //ͼݼ private String contentGeneral; //Ŀ¼ private String list; //ý private String newsComment; //ͼ private String illustration; // private Integer revision; //ҳ private Integer page; // private Integer wordCount; //ӡʱ private Date paintDate; // private Integer format; // private Integer weight; //ӡ private Integer paintCount; //ͼISBN private String isbn; //װ private String packIng; //ղ private Integer collectionCount; @SearchableProperty(index=Index.NO,store=Store.YES) public Integer getDetailId() { return detailId; } public void setDetailId(Integer detailId) { this.detailId = detailId; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } @SearchableProperty public String getEditCommentText() { return editCommentText; } public void setEditCommentText(String editCommentText) { this.editCommentText = editCommentText; } public String getContentGeneral() { return contentGeneral; } public void setContentGeneral(String contentGeneral) { this.contentGeneral = contentGeneral; } public String getList() { return list; } public void setList(String list) { this.list = list; } public String getNewsComment() { return newsComment; } public void setNewsComment(String newsComment) { this.newsComment = newsComment; } public String getIllustration() { return illustration; } public void setIllustration(String illustration) { this.illustration = illustration; } public Integer getRevision() { return revision; } public void setRevision(Integer revision) { this.revision = revision; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getWordCount() { return wordCount; } public void setWordCount(Integer wordCount) { this.wordCount = wordCount; } public Date getPaintDate() { return paintDate; } public void setPaintDate(Date paintDate) { this.paintDate = paintDate; } public Integer getFormat() { return format; } public void setFormat(Integer format) { this.format = format; } public Integer getPaintCount() { return paintCount; } public void setPaintCount(Integer paintCount) { this.paintCount = paintCount; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Integer getCollectionCount() { return collectionCount; } public void setCollectionCount(Integer collectionCount) { this.collectionCount = collectionCount; } public String getPackIng() { return packIng; } public void setPackIng(String packIng) { this.packIng = packIng; } public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } }
Python
UTF-8
1,389
3.09375
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 8 13:46:02 2019 @author: lianghao """ # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Data PreProcessing dataset = pd.read_csv("Ads_CTR_Optimisation.csv") # Implementing UCB # number of ads import math N = 10000 d = 10 numbers_of_selections = [0] * d sums_of_selections = [0] * d ads_selected = [] total_reward = 0 for round in range(0,N): max_upper_bound = 0 best_ad = 0 for ads in range(0,d): if numbers_of_selections[ads] > 0: average_reward = sums_of_selections[ads] / numbers_of_selections[ads] delta_ads = math.sqrt(3/2 * math.log(round+1) / numbers_of_selections[ads]) upper_bound = average_reward + delta_ads else: upper_bound = 1e400 if upper_bound > max_upper_bound: max_upper_bound = upper_bound best_ad = ads ads_selected.append(best_ad) reward = dataset.values[round, best_ad] numbers_of_selections[best_ad] = numbers_of_selections[best_ad] + 1 sums_of_selections[best_ad] = sums_of_selections[best_ad] + reward total_reward = total_reward + reward # Visualising the results plt.hist(ads_selected) plt.title('Histogram of ads selections') plt.xlabel('Ads') plt.ylabel('Number of times each ad was selected') plt.show()
Java
UTF-8
395
2.890625
3
[]
no_license
public enum VehicleType { SEDAN("Sedan", 39.99), TRUCK_OR_VAN("Truck or van", 49.99), SUV("SUV", 42.99); private final String name; private final double fee; private VehicleType(String name, double fee) { this.name = name; this.fee = fee; } public String getName() { return name; } public double getFee() { return fee; } }
Markdown
UTF-8
5,800
3.09375
3
[]
no_license
--- ID: 5060 post_title: > How to Insert Sheet in Microsoft Excel 365? author: Indhuja R post_excerpt: "" layout: post permalink: > https://geekexcel.com/how-to-insert-sheet-in-microsoft-excel-365/ published: true post_date: 2020-03-17 17:31:04 --- <h2>Insert Sheet in Excel:</h2> In this article, we describe <strong>How to Insert Sheet</strong> in Microsoft Excel using different ways. <h2>Jump To:</h2> <ul> <li><a href="#1"><strong>How to Insert Sheet in Microsoft Excel 365?</strong></a></li> <li><a href="#2"><strong>Closure</strong></a></li> </ul> <h2 id="1">How to Insert Sheet in Microsoft Excel 365?</h2> <h4><strong>Way 1:</strong></h4> <ul> <li>First, you have to open the <strong>New Excel Workbook</strong>.</li> <li>Then you can<strong> Insert the new sheet</strong> by just clicking the <strong>+ </strong>sign appears at the bottom of the workbook.</li> <li>Refer to the below<strong> screenshot</strong> to Find the <strong>+ </strong>sign in the workbook.</li> </ul> [caption id="attachment_5063" align="aligncenter" width="527"]<img class="wp-image-5063 size-full" src="https://geekexcel.com/wp-content/uploads/2020/03/Screenshot_2-49.png" alt="new sheet" width="527" height="298" /> New sheet[/caption] <ul> <li>By clicking the <strong>+ </strong>sign the <strong>New sheet</strong> will be added into the Excel workbook.</li> </ul> [caption id="attachment_5064" align="aligncenter" width="474"]<img class="wp-image-5064 size-full" src="https://geekexcel.com/wp-content/uploads/2020/03/Screenshot_3-48.png" alt="Newly inserted sheet" width="474" height="242" /> Newly inserted sheet[/caption] <h4>Way 2:</h4> <ul> <li><strong>Right-click</strong> on the sheet1 which is placed at the bottom of the workbook.</li> <li>The <strong>popup menu</strong> gets opened there you want to select<strong> Insert option.</strong></li> </ul> [caption id="attachment_5065" align="aligncenter" width="390"]<img class="wp-image-5065 size-full" src="https://geekexcel.com/wp-content/uploads/2020/03/Screenshot_4-38.png" alt="Pop up menu" width="390" height="342" /> Pop up menu[/caption] <ul> <li>The <strong>Insert window</strong> will appear, here the<strong> worksheet</strong> option preselected by default and so you just simply click<strong> OK.</strong></li> </ul> [caption id="attachment_5066" align="aligncenter" width="635"]<img class="wp-image-5066 size-full" src="https://geekexcel.com/wp-content/uploads/2020/03/Screenshot_5-31.png" alt="Insert Window " width="635" height="470" /> Insert Window[/caption] <ul> <li>The <strong>new sheet</strong> will be Inserted on the workbook.</li> </ul> [caption id="attachment_5067" align="aligncenter" width="406"]<img class="wp-image-5067 size-full" src="https://geekexcel.com/wp-content/uploads/2020/03/Screenshot_6-26.png" alt="Newly inserted sheet" width="406" height="277" /> Newly inserted sheet[/caption] <h4>Way 3:</h4> <ul> <li><strong style="font-size: 19px;">Go to menu bar → click the home menu → cells options</strong><span style="font-size: 19px;"> will appear, there you can find the <strong>Insert option.</strong></span></li> </ul> [caption id="attachment_5068" align="aligncenter" width="1174"]<img class="wp-image-5068 size-full" src="https://geekexcel.com/wp-content/uploads/2020/03/Screenshot_10-6.png" alt="Insert option" width="1174" height="391" /> Insert option[/caption] <ul> <li>Click the Dropdown menu of the insert option and in that, you need to select the option <b>Insert sheet.</b></li> </ul> [caption id="attachment_5069" align="aligncenter" width="1192"]<img class="wp-image-5069 size-full" src="https://geekexcel.com/wp-content/uploads/2020/03/Screenshot_8-14.png" alt="Different options" width="1192" height="426" /> Different options[/caption] <ul> <li>The new sheet will be<strong> inserted</strong> into the Excel workbook.</li> </ul> [caption id="attachment_5070" align="aligncenter" width="471"]<img class="wp-image-5070 size-full" src="https://geekexcel.com/wp-content/uploads/2020/03/Screenshot_9-7.png" alt="SHEET" width="471" height="310" /> Newly inserted sheet[/caption] <h4>Way 4:</h4> <ul> <li>Use the <strong>shortcut key</strong> to insert the new sheet<strong> (Shift + F11) </strong>in your current workbook.</li> <li>This is the simplest way to insert the sheet.</li> </ul> <h2 id="2">Closure:</h2> Hoping that the above article gave you clear information about<strong> Insert sheet in Excel 365.</strong> Don't forget to share your valuable <strong>Feedback</strong>, and kindly drop if there any <strong>queries/suggestions</strong> in the comment box. Thanks for visiting <strong><a href="https://geekexcel.com/">Geek Excel!!</a></strong> Keep Learning with us!! <h2>Related Articles:</h2> <ul> <li><strong><a href="https://geekexcel.com/how-to-hide-formula-in-microsoft-excel-365/">Hide Formula in Excel</a></strong></li> <li style="font-size: 19px;"><strong><a style="font-size: 19px; transition-property: all;" href="https://geekexcel.com/how-to-delete-a-row-easily-in-microsoft-excel-365/">Delete a row in Excel</a></strong></li> <li><a href="https://geekexcel.com/how-to-insert-a-new-row-in-microsoft-excel-365/"><strong>Insert a New row in Excel</strong></a></li> <li><a href="https://geekexcel.com/how-to-change-a-row-height-in-microsoft-excel-365/"><strong>Change Row Height in Excel</strong></a></li> <li><a href="https://geekexcel.com/how-to-create-a-border-on-a-cell-in-microsoft-excel-365/"><strong>Create a border on a cell in Excel</strong></a></li> <li><a href="https://geekexcel.com/how-to-hide-row-in-microsoft-excel-365/"><strong>Hide Row in Excel</strong></a></li> <li><a href="https://geekexcel.com/how-to-protect-the-cell-in-microsoft-excel-365/"><strong>Protect the cell in Excel</strong></a></li> </ul> &nbsp;
Java
UTF-8
786
2.296875
2
[]
no_license
public Object configure(Object obj) throws Exception { // Check the class of the object Class<?> oClass = nodeClass(_root); if (oClass != null && !oClass.isInstance(obj)) { String loaders = (oClass.getClassLoader()==obj.getClass().getClassLoader())?"":"Object Class and type Class are from different loaders."; throw new IllegalArgumentException("Object of class '"+obj.getClass().getCanonicalName()+"' is not of type '" + oClass.getCanonicalName()+"'. "+loaders+" in "+_url); } String id=_root.getAttribute("id"); if (id!=null) _configuration.getIdMap().put(id,obj); configure(obj,_root,0); return obj; }
C#
UTF-8
1,712
2.734375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerHealth : MonoBehaviour { public int health = 100; public HealthBar healthBar; int lastHealth; int targetHealth; bool canDrain = false; bool canAdd = false; void Start() { healthBar.SetMaxHealth(health); } void Update() { AddHealth(); DrainHealth(); } public void IncreaseHealth(int healthAmount) { lastHealth = health; targetHealth = health + healthAmount; if(targetHealth > 100){ targetHealth = 100; } // Set max target health if over increased canAdd = true; health += healthAmount; if(health > 100){ health = 100; } // Set max health if over increased } public void TakeDamage(int damage) { lastHealth = health; targetHealth = health - damage; canDrain = true; health -= damage; if(health <= 0) { // Process post death methods GetComponent<DeathHandler>().HandleDeath(); } } private void AddHealth() { if(canAdd == false){ return; } if(lastHealth < targetHealth) { // Debug.Log("Increasing health"); lastHealth++; healthBar.SetHealth(lastHealth); } else { canAdd = false; } } private void DrainHealth() { if(canDrain == false){ return; } if(lastHealth > targetHealth) { lastHealth--; healthBar.SetHealth(lastHealth); } else { canDrain = false; } } }
Java
UTF-8
1,818
2.390625
2
[]
no_license
package com.example.movieslist; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.util.ArrayList; public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> { private ArrayList<MovieList> movieListArrayList; private Activity activity; public MovieAdapter(ArrayList<MovieList> movieListArrayList, Activity activity) { this.movieListArrayList = movieListArrayList; this.activity = activity; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { MovieList list= movieListArrayList.get(position); Glide.with(activity).load(list.getPosterPath()).diskCacheStrategy(DiskCacheStrategy.ALL) .into(holder.poster); holder.title.setText(list.getTitle()); } @Override public int getItemCount() { return movieListArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { ImageView poster; TextView title; public ViewHolder(@NonNull View itemView) { super(itemView); poster=itemView.findViewById(R.id.poster); title=itemView.findViewById(R.id.title); } } }
C
UTF-8
1,809
3.109375
3
[]
no_license
#include "cbc-decrypt.h" #include "aes.h" #include <stdio.h> #include <string.h> /* The input ciphertext is assumed to have length an integer multiple of the blocklength. The code below is not robust to buffer-overflow attacks; exploiting these is not the purpose of this exercise */ int cbcdec(unsigned char *CText, int length) { unsigned char MBlock[16]; unsigned char CBlock_cur[16]; unsigned char CBlock_prev[16]; unsigned char Key[16]; //FILE *fpOut; AES_KEY AESkey; // This is just for illustration; the actual key used was not the all-0 key! Key[0] = Key[1] = Key[2] = Key[3] = 0x00; Key[4] = Key[5] = Key[6] = Key[7] = 0x00; Key[8] = Key[9] = Key[10] = Key[11] = 0x00; Key[12] = Key[13] = Key[14] = Key[15] = 0x00; AES_set_decrypt_key((const unsigned char *)Key, 128, &AESkey); if (length < 2) return 0; for (int i = 0; i < 16; i++) { CBlock_prev[i] = CText[i]; } int j = 1; while (j < length) { for (int i = 0; i < 16; i++) { CBlock_cur[i] = CText[16 * j + i]; } AES_decrypt((const unsigned char *)CBlock_cur, MBlock, (const AES_KEY *)&AESkey); for (int i = 0; i < 16; i++) { MBlock[i] ^= CBlock_prev[i]; //printf("%X", MBlock[i]/16), printf("%X", MBlock[i]%16); // Uncomment this to output the message + the padding for debugging purposes. // If we were implementing this for real, we would only output the message CBlock_prev[i] = CBlock_cur[i]; } j++; } j = MBlock[15]; if ((j == 0) || (j > 16)) { printf("Error: final byte out of range\n"); return 0; } for (int i = 14; i >= 16 - j; i--) { if (MBlock[i] != j) { printf("Error: incorrect padding\n"); return 0; } } // printf("Everything fine\n"); return 1; }
Python
UTF-8
6,579
2.75
3
[ "BSD-3-Clause" ]
permissive
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 import sys from django.utils.encoding import smart_str from harness import MockRouter, EchoApp from rapidsms.backends.backend import Backend from rapidsms.message import Message import unittest, re try: from django.test import TestCase except: from unittest import TestCase from datetime import datetime class MetaTestScript (type): def __new__(cls, name, bases, attrs): for key, obj in attrs.items(): if key.startswith("test") and not callable(obj): cmds = TestScript.parseScript(obj) def wrapper (self, cmds=cmds): return self.runParsedScript(cmds) attrs[key] = wrapper return type.__new__(cls, name, bases, attrs) class TestScript (TestCase): __metaclass__ = MetaTestScript """ The scripted.TestScript class subclasses unittest.TestCase and allows you to define unit tests for your RapidSMS apps in the form of a 'conversational' script: from myapp.app import App as MyApp from rapidsms.tests.scripted import TestScript class TestMyApp (TestScript): apps = (MyApp,) testRegister = \""" 8005551212 > register as someuser 8005551212 < Registered new user 'someuser' for 8005551212! \""" testDirectMessage = \""" 8005551212 > tell anotheruser what's up?? 8005550000 < someuser said "what's up??" \""" This TestMyApp class would then work exactly as any other unittest.TestCase subclass (so you could, for example, call unittest.main()). """ apps = None def setUp (self): self.router = MockRouter() self.backend = Backend(self.router) self.router.add_backend(self.backend) if not self.apps: raise Exception( "You must define a list of apps in your TestScript class!") for app_class in self.apps: app = app_class(self.router) self.router.add_app(app) def tearDown (self): if self.router.running: self.router.stop() @classmethod def parseScript (cls, script): cmds = [] for line in map(lambda(x): x.strip(), script.split("\n")): if not line or line.startswith("#"): continue tokens = re.split(r'([<>])', line, 1) num, dir, txt = map(lambda (x):x.strip(), tokens) # allow users to optionally put dates in the number # 19232922@200804150730 if "@" in num: num, datestr = num.split("@") date = datetime.strptime(datestr, "%Y%m%d%H%M") else: date = datetime.now() cmds.append((num, date, dir, txt)) return cmds def runParsedScript (self, cmds): self.router.start() last_msg = '' for num, date, dir, txt in cmds: if dir == '>': last_received = txt msg = self.backend.message(num, txt) msg.date = date self.backend.route(msg) elif dir == '<': msg = self.backend.next_message() if sys.stdout.encoding: # Encode 'strange' characters for proper output on the console # so we don't get 'unprintable assertion errors' try: txt = txt.encode(sys.stdout.encoding, 'replace') except UnicodeDecodeError: # This error occurs when the input is not standardized (i.e. unicode) self.fail("Could not encode unit test string to stdout character encoding. Make sure your RapidSMS unit tests are unicode strings!") # The following 3 try...catch blocks handle the case where the unit test strings # are not properly decoded in tests.py. Basically, there is no way to reliably # determine the encoding of a character > 127 bits a posteriori. The best we can # do is catch errors when these strings prove incompatible and then print out # as much as we can. try: msgIsNotNoneMsg = "Message was not returned.\nMessage: '%s'\nExpecting: '%s')" % (last_msg, txt) except UnicodeDecodeError: msgIsNotNoneMsg = "Message was not returned.\nMessage: '%s')" % (last_msg) self.assertTrue(msg is not None, msgIsNotNoneMsg) if sys.stdout.encoding: msg.text = msg.text.encode(sys.stdout.encoding, 'replace') try: msgWrongRecipient = "Expected to send to %s, but message was sent to %s\nMessage: '%s'" % \ (num, msg.peer, last_msg) except UnicodeDecodeError: msgWrongRecipient = "Expected to send to one number but got sent to another. \nMessage: '%s'" % (last_msg) self.assertEquals(msg.peer, num, msgWrongRecipient) try: msgUnexpectedReceipt = "\nMessage: %s\nReceived text: %s\nExpected text: %s\n" % \ (last_msg, msg.text, txt) except UnicodeDecodeError: msgUnexpectedReceipt = "Unexpected response. \nResponse: %s" % \ (msg.text) self.assertEquals(msg.text.strip(), txt.strip(), msgUnexpectedReceipt) last_msg = txt self.router.stop() def runScript (self, script): self.runParsedScript(self.parseScript(script)) class MockTestScript (TestScript): apps = (EchoApp,) testScript = """ 8005551212 > hello 8005551212 < 8005551212: hello """ testScript2 = """ 1234567890 > echo this! 1234567890 < 1234567890: echo this! """ def testClosure (self): self.assertEquals(type(self.testScript.func_defaults), tuple) self.assertEquals(type(self.testScript.func_defaults[0]), list) self.assertNotEquals(self.testScript.func_defaults, self.testScript2.func_defaults) def testRunScript (self): self.runScript(""" 2345678901 > echo? 2345678901 < 2345678901: echo? """) if __name__ == "__main__": unittest.main()
PHP
UTF-8
1,867
3.1875
3
[]
no_license
<?php class person{ var $fname; var $lname; var $othername; var $email; var $country; var $city; var $location; var $postaladdress; var $tel; function __construct() { $this->fname = ""; $this->lname = ""; $this->othername = ""; $this->email = ""; $this->country = ""; $this->city = ""; $this->location = ""; $this->postaladdress = ""; $this->tel = ""; } function set_FirstName($fname) { $this->fname = $fname; } function get_FirstName() { return $this->fname; } function set_LastName($lname) { $this->lname = $lname; } function get_LastName() { return $this->lname; } function set_OtherName($othername) { $this->othername = $othername; } function get_OtherName() { return $this->othername; } function set_Email($email) { $this->email = $email; } function get_Email() { return $this->email; } function set_Country($country) { $this->country = $country; } function get_Country() { return $this->country; } function set_City($city) { $this->city = $city; } function get_City() { return $this->city; } function set_Location($location) { $this->location = $location; } function get_Location() { return $this->location; } function set_Postaladdress($postaladdress) { $this->postaladdress = $postaladdress; } function get_Postaladdress() { return $this->postaladdress; } function set_Tel($tel) { $this->tel = $tel; } function get_Tel() { return $this->tel; } } ?>
C#
UTF-8
2,491
2.609375
3
[]
no_license
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace WeddingWebsiteCore.Models { [Table("addresses")] public class Address { public int AddressId { get; set; } [Column("name")] public string Name { get; set; } [Required, Column("streetNumber")] public string StreetNumber { get; set; } [Required, Column("streetName")] public string StreetName { get; set; } [Column("streetDetail")] public string StreetDetail { get; set; } [Required, Column("city")] public string City { get; set; } [Required, Column("state")] public string State { get; set; } [Required, Column("postalCode")] public string PostalCode { get; set; } [Required, Column("country")] public string Country { get; set; } [NotMapped] public string FullString { get { var builder = new StringBuilder(); if (!string.IsNullOrWhiteSpace(StreetNumber)) { builder.Append(StreetNumber); } if (!string.IsNullOrWhiteSpace(StreetName)) { builder.Append(" "); builder.Append(StreetName); } if (!string.IsNullOrWhiteSpace(StreetDetail)) { builder.Append(" "); builder.Append(StreetDetail); } builder.Append(", "); if (!string.IsNullOrWhiteSpace(City)) { builder.Append(City); builder.Append(", "); } if (!string.IsNullOrWhiteSpace(State)) { builder.Append(State); } if (!string.IsNullOrWhiteSpace(PostalCode)) { builder.Append(" "); builder.Append(PostalCode); } return builder.ToString(); } } public ICollection<Family> Families { get; set; } public ICollection<Event> Events { get; set; } public ICollection<Vendor> Vendors { get; set; } } }
Java
UTF-8
1,426
1.757813
2
[ "Apache-2.0" ]
permissive
package com.walmartlabs.concord.plugins.git.v1; /*- * ***** * Concord * ----- * Copyright (C) 2017 - 2020 Walmart Inc. * ----- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ===== */ import com.walmartlabs.concord.plugins.git.GitHubTask; import com.walmartlabs.concord.sdk.Context; import com.walmartlabs.concord.sdk.InjectVariable; import com.walmartlabs.concord.sdk.Task; import javax.inject.Inject; import javax.inject.Named; import java.util.Map; @Named("github") public class GitHubTaskV1 implements Task { private final GitHubTask delegate; @InjectVariable("githubParams") private Map<String, Object> defaults; @Inject public GitHubTaskV1() { this.delegate = new GitHubTask(); } @Override public void execute(Context ctx) { Map<String, Object> result = delegate.execute(ctx.toMap(), defaults); result.forEach(ctx::setVariable); } }
Java
UTF-8
36,256
1.523438
2
[]
no_license
package com.example.myapplicationpln.fragment; import android.app.Dialog; import android.app.ProgressDialog; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.room.Room; import com.example.myapplicationpln.R; import com.example.myapplicationpln.model.MHistory; import com.example.myapplicationpln.model.MSpinnerSelectx; import com.example.myapplicationpln.model.PointValue; import com.example.myapplicationpln.preference.SessionPrefference; import com.example.myapplicationpln.roomDb.AppDatabase; import com.example.myapplicationpln.roomDb.GHistory; import com.example.myapplicationpln.roomDb.GhistoryMeter; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.components.Description; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import com.github.mikephil.charting.formatter.PercentFormatter; import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.github.mikephil.charting.utils.Utils; 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.jjoe64.graphview.GraphView; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class HistoryFragment extends Fragment { private View mView; RecyclerView mRecyclerview; private FirebaseDatabase mDatabase; private Query mUserDatabase, mUserDatabase2; private FirebaseRecyclerAdapter firebaseRecyclerAdapter; private LinearLayoutManager mManager; private static final String TAG = HistoryFragment.class.getSimpleName(); private Query needsQuery; private Query offersQuery; SessionPrefference session; private Dialog dialog; LineChart lineChart; DatabaseReference databaseReference2; SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); GraphView graphView; LineGraphSeries series; private List<MHistory> listData; private ArrayList<GHistory> listHistLocal; private ArrayList<GhistoryMeter> listHistMeterLocal; private MyAdapter adapter; private LineChart mChart; private AppDatabase db; LineDataSet lineDataSet = new LineDataSet(null, null); ArrayList<ILineDataSet> lineDataSets = new ArrayList<>(); LineData lineData; MSpinnerSelectx mSpinnerSelectx = new MSpinnerSelectx(); String selected; public HistoryFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_historyi, container, false); // Inflate the layout for this fragment DatabaseReference referenceHistor = FirebaseDatabase.getInstance().getReference(); db = Room.databaseBuilder(getActivity(), AppDatabase.class, "tbGrainHistory") .allowMainThreadQueries() .fallbackToDestructiveMigration() .addMigrations(AppDatabase.MIGRATION_1_7) .build(); graphView = view.findViewById(R.id.jjoe); series = new LineGraphSeries(); graphView.addSeries(series); listData = new ArrayList<>(); listHistLocal = new ArrayList<>(); listHistMeterLocal = new ArrayList<>(); mChart = view.findViewById(R.id.line_chartFbase); mChart.setTouchEnabled(true); mChart.setPinchZoom(true); MyMarkerView mv = new MyMarkerView(getActivity(), R.layout.custom_marker_view); mv.setChartView(mChart); mChart.setMarker(mv); GhistoryMeter[] gHistory = db.gHistorySpinnerDao().readDataHistory3(); // disable dismiss by tapping outside of the dialog showDataRoom(gHistory); dialog = new Dialog(getActivity()); session = new SessionPrefference(getActivity()); mRecyclerview = view.findViewById(R.id.recyclerViewHistory); mRecyclerview.setHasFixedSize(true); mManager = new LinearLayoutManager(getActivity()); mRecyclerview.setLayoutManager(mManager); Log.e(TAG, "firebaseoption"); //add string & get from session String userId = session.getUserId(); Log.d("get userzId Historiy", " : " + userId); mDatabase = FirebaseDatabase.getInstance(); // mUserDatabase = mDatabase.getReference().child("History").child(session.getPhone()).orderByChild("createdAt"); //20210729 String selectedIdPelanggan = "1111"; //ambil dengan cara setperti pencet tombol String selectedUserID = ""; FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference mDatabaseRefs = database.getReference(); DatabaseReference reference = FirebaseDatabase.getInstance().getReference(); Query query = reference.child("Address").child(session.getPhone()); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { final List<String> areasList = new ArrayList<String>(); int lenght = (int) dataSnapshot.getChildrenCount(); for (DataSnapshot spinnerSnapshot : dataSnapshot.getChildren()) { String idName = spinnerSnapshot.child("id_pelanggan").getValue(String.class); areasList.add(idName); } Spinner spinner = (Spinner) view.findViewById(R.id.listItemHisotrySpinner); ArrayAdapter<String> areasAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, areasList); areasAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(areasAdapter); DatabaseReference references = FirebaseDatabase.getInstance().getReference(); Query queryx = references.child("SpinnerDbx").child(session.getPhone()); queryx.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { String valueSpinner; mSpinnerSelectx = dataSnapshot.getValue(MSpinnerSelectx.class); String hyde = mSpinnerSelectx.getSpinner_long(); valueSpinner = mSpinnerSelectx.getSpinner_value(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { selected = areasAdapter.getItem(i); //20210803 listData = new ArrayList(); mDatabaseRefs.child("SpinnerDbx").child(session.getPhone()).child("spinner_value").setValue(String.valueOf(i)); mDatabaseRefs.child("SpinnerDbx").child(session.getPhone()).child("spinner_long").setValue(String.valueOf(selected)); mSpinnerSelectx.setSpinner_value(String.valueOf(i)); mSpinnerSelectx.setSpinner_long(areasAdapter.getItem(i)); //2021-07-30 //tunjukkan array atau list yang diambil dari firebase //masukkan ke dalam variable bernama listHistoryFirebase mUserDatabase = mDatabase.getReference().child("HistoryMeter").child(session.getPhone()).child(String.valueOf("Electricity")).child(selected).orderByChild("createdAt"); final DatabaseReference nm = FirebaseDatabase.getInstance().getReference("data"); mUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { float f = 50, d; double y; if (dataSnapshot.exists()) { for (DataSnapshot npsnapshot : dataSnapshot.getChildren()) { MHistory l = npsnapshot.getValue(MHistory.class); listData.add(l); } //20210716 //ambil history dari room database untuk user tersebut //masukkan ke list atau array dengan nama listHistoryLocal // = new List<GHistory>(); List<GHistory> listHistJoin; //gabungan local dan firebase //iterasi list firebase --> listData int countHist = listData.size(); String idpel = session.getIdPelanggan(); long value1 = Long.valueOf(selected); List<GHistory> listHistoryCount = db.gHistorySpinnerDao().selectHistoryfromRoom3(); List<GhistoryMeter> listHistoryMeterCount = db.gHistorySpinnerDao().selectHistoryfromRoomMeter(); List<GhistoryMeter> listHistoryMeterSelected = db.gHistorySpinnerDao().selectHistoryfromRoomMeterSelected(value1); String fileNameLocal = ""; String fileNameLocalMeter = ""; if (listHistoryMeterSelected.size()!=countHist){ fileNameLocalMeter = " "; }else { for (int i = 0; i < countHist; i++) { listHistJoin = new ArrayList<>(); //cari di room database lokasi file long idHist = listData.get(i).getId(); double meter = listData.get(i).getMeter(); //find di local db int countHistLocal = listHistLocal.size(); for (int j = 0; j < listHistoryMeterSelected.size(); j++) { GhistoryMeter ghistoryMeter = listHistoryMeterSelected.get(i); int idHistLocalMeter = ghistoryMeter.getId(); if (idHist == idHistLocalMeter) { fileNameLocalMeter = ghistoryMeter.getImagez(); Log.d("", " " + fileNameLocal); break; } } } } adapter = new MyAdapter(listData, getActivity(), fileNameLocalMeter, listHistMeterLocal); mRecyclerview.setAdapter(adapter); } } @Override public void onCancelled(DatabaseError databaseError) { } }); adapterView.setTag(selected); ((TextView)adapterView.getChildAt(0)).setTextColor(Color.BLUE); String value = areasAdapter.getItem(i); String id_user = session.getUserId(); //firebase check if data > 0 , insert if (lenght == 0) { Log.d("DATA CHANGE insertz", "insertz: "); } else { Log.d("DATA CHANGE updatez", "updatez: "); // Toast.makeText(getActivity().getApplicationContext(), "value if " + value + " choosen", Toast.LENGTH_LONG).show(); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } @Override public void onCancelled(DatabaseError databaseError) { } }); /* //mUserDatabase = mDatabase.getReference().child("HistoryMeter").child(session.getPhone()).child(String.valueOf("Electricity")).child(session.getIdPelanggan()).orderByChild("createdAt"); mUserDatabase = mDatabase.getReference().child("HistoryMeter").child(session.getPhone()).child(String.valueOf("Electricity")).child(session.getIdPelanggan()).orderByChild("meter"); final DatabaseReference nm = FirebaseDatabase.getInstance().getReference("data"); mUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { float f = 50, d; double y; if (dataSnapshot.exists()) { for (DataSnapshot npsnapshot : dataSnapshot.getChildren()) { MHistory l = npsnapshot.getValue(MHistory.class); listData.add(l); GHistory[] gHistory = db.gHistorySpinnerDao().readDataHistory3(); // showData(listData,l,gHistory); // ArrayList<Entry> datavals = new ArrayList<Entry>(); // f = f + 50; // y =l.getMeter(); // float c = (float) y; // datavals.add(new Entry(f,c)); // showData(listData); // showChart(datavals,c); } //20210716 //ambil history dari room database untuk user tersebut //masukkan ke list atau array dengan nama listHistoryLocal // = new List<GHistory>(); List<GHistory> listHistJoin; //gabungan local dan firebase //iterasi list firebase --> listData int countHist = listData.size(); String idpel = session.getIdPelanggan(); long value1 = Long.valueOf(idpel); List<GHistory> listHistoryCount = db.gHistorySpinnerDao().selectHistoryfromRoom3(); List<GhistoryMeter> listHistoryMeterCount = db.gHistorySpinnerDao().selectHistoryfromRoomMeter(); List<GhistoryMeter> listHistoryMeterSelected = db.gHistorySpinnerDao().selectHistoryfromRoomMeterSelected(value1); String fileNameLocal = ""; String fileNameLocalMeter = ""; for (int i = 0; i < countHist; i++) { listHistJoin = new ArrayList<>(); //cari di room database lokasi file long idHist = listData.get(i).getId(); double meter = listData.get(i).getMeter(); //find di local db int countHistLocal = listHistLocal.size(); for (int j = 0; j < listHistoryMeterCount.size(); j++) { // GHistory history = listHistoryCount.get(i); GhistoryMeter ghistoryMeter = listHistoryMeterCount.get(i); // GHistory histLocal = listHistLocal.get(j); // int idHistLocal = history.getId(); int idHistLocalMeter = ghistoryMeter.getId(); // String mImageFileLocation = db.gHistorySpinnerDao().getImageHistory(String.valueOf(history.getMeter())); if (idHist == idHistLocalMeter) { //amvil id tersebut //ambil lokasi file tersebut // fileNameLocal = history.getImagez(); fileNameLocalMeter = ghistoryMeter.getImagez(); Log.d("", " " + fileNameLocal); // showData(listData); break; } } } adapter = new MyAdapter(listData, getActivity(), fileNameLocalMeter, listHistMeterLocal); mRecyclerview.setAdapter(adapter); } } @Override public void onCancelled(DatabaseError databaseError) { } }); */ /* setListener(); mUserDatabase2 = mDatabase.getReference().child("History"); Query queryhistory = referenceHistor.child("History").child("33"); queryhistory.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { if (dataSnapshot.getChildrenCount()==0){ Log.d("DATA < 0 Historyi", "onDataChange: " + dataSnapshot.getValue()); }else { Log.d("DATA Historyi > 0 ", "onDataChange: \n" + dataSnapshot.getValue()); } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); // Rumus Firebase one to many // mUserDatabase = mDatabase.getReference().child("User").orderByChild("address").equalTo("Kilmarnock"); // firebase.database().ref('Address').orderBy('User').equalTo('id'); // needsQuery = mUserDatabase.orderByChild("address").equalTo("Kilmarnock"); // offersQuery = mUserDatabase.orderByChild("type").equalTo("offer"); FirebaseRecyclerOptions<MHistory> options = new FirebaseRecyclerOptions.Builder<MHistory>(). setQuery(mUserDatabase, MHistory.class). build(); firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<MHistory, UserViewHolder>(options) { @Override protected void onBindViewHolder(@NonNull UserViewHolder holder, int position, @NonNull MHistory model) { Log.d("stringset"," "+model.getMeter()); holder.setFname(model.getMeter()); holder.setLname(model.getScoreClassification()); holder.setAname(model.getScoreIdentification()); Date timeCreated = model.getCreatedAt() ; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String strTimeCreated = formatter.format(timeCreated); String dateVal = String.valueOf(model.getCreatedAt()); holder.setDate(strTimeCreated); int status = 1; holder.setStatusName(1); Log.d("get getMeter ", " : " + model.getMeter()); dialog = new Dialog(getActivity()); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.setTitle("Item"); dialog.setContentView(R.layout.dialog_chart_design); TextView oke = dialog.findViewById(R.id.oke); PieChart pieChart; pieChart = dialog.findViewById(R.id.chart1); pieChart.setUsePercentValues(true); ArrayList<PieEntry> yvalues = new ArrayList<PieEntry>(); float f = Float.parseFloat(String.valueOf(model.getMeter())); yvalues.add(new PieEntry((float) f, model.getMeter())); PieDataSet dataSet = new PieDataSet(yvalues, getString(R.string.gcm_defaultSenderId)); PieData data = new PieData(dataSet); data.setValueFormatter(new PercentFormatter()); pieChart.setData(data); Description description = new Description(); description.setText(getString(R.string.project_id)); pieChart.setDescription(description); pieChart.setDrawHoleEnabled(true); pieChart.setTransparentCircleRadius(58f); pieChart.setHoleRadius(58f); pieChart.setEntryLabelColor(Color.BLACK); dataSet.setColors(ColorTemplate.MATERIAL_COLORS); data.setValueTextSize(13f); data.setValueTextColor(Color.BLACK); Button button = dialog.findViewById(R.id.cancel); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); dialog.show(); } }); // holder.cardView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // // Context context = view.getContext(); // Intent intent = new Intent(context, EventDetailActivity.class); // intent.putExtra("userAddress", model.getAlamat_pelanggan()); // intent.putExtra("userDetailId", model.getId_pelanggan()); // intent.putExtra("userAddressId", model.getUser_address_id()); // // Log.d("Body model model", "model: " + model.getAlamat_pelanggan()); // context.startActivity(intent); // // // } // }); } @Override public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.row_history, parent, false); Log.e(TAG, "oncreate is called"); return new UserViewHolder(view); } }; mRecyclerview.setAdapter(firebaseRecyclerAdapter); */ return view; } /* @Override public void onStart() { super.onStart(); mUserDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { DataPoint[] dp = new DataPoint[(int) snapshot.getChildrenCount() ] ; int idx = 0 ; for (DataSnapshot snapshot1 : snapshot.getChildren()){ MHistory mHistory = snapshot1.getValue(MHistory.class); SimpleDateFormat formatter = new SimpleDateFormat("MM"); Date timeCreated = mHistory.getCreatedAt(); double strTimeCreated = Double.parseDouble(formatter.format(timeCreated)); dp[idx] = new DataPoint(mHistory.getId(),mHistory.getMeter()); idx++; } series.resetData(dp); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } */ private void showChart(ArrayList<Entry> datavals) { YAxis leftAxis = mChart.getAxisLeft(); leftAxis.removeAllLimitLines(); leftAxis.setAxisMaximum(300); leftAxis.setAxisMinimum(90); // leftAxis.enableGridDashedLine(c, c, 0f); leftAxis.setDrawZeroLine(false); leftAxis.setDrawLimitLinesBehindData(false); leftAxis.setValueFormatter(new MyValueFormatter()); lineDataSet.setValues(datavals); lineDataSet.setLabel("Dataset 1"); // lineDataSets.clear(); // lineDataSets.add(lineDataSet); // lineData = new LineData(lineDataSets); // mChart.clear(); // mChart.setData(lineData); // mChart.invalidate(); if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) { lineDataSet = (LineDataSet) mChart.getData().getDataSetByIndex(0); lineDataSet.setValues(datavals); mChart.getData().notifyDataChanged(); mChart.notifyDataSetChanged(); } else { lineDataSets.clear(); lineDataSets.add(lineDataSet); lineData = new LineData(lineDataSets); lineDataSet.setDrawIcons(false); lineDataSet.setColor(Color.GREEN); lineDataSet.setCircleColor(Color.GREEN); lineDataSet.setLineWidth(1f); lineDataSet.setCircleRadius(3f); lineDataSet.setDrawCircleHole(false); lineDataSet.setValueTextSize(9f); lineDataSet.setDrawFilled(true); lineDataSet.setFormLineWidth(1f); lineDataSet.setFormSize(15.f); if (Utils.getSDKInt() >= 18) { Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.fade_blue); lineDataSet.setFillDrawable(drawable); } else { lineDataSet.setFillColor(Color.GREEN); } } mChart.clear(); mChart.setData(lineData); mChart.invalidate(); } private void showDataRoom(GhistoryMeter[] gHistory) { double x, y; for (int i = 0; i < gHistory.length; i++) { Date itemDate = gHistory[i].getDate_time(); String myDateStr = new SimpleDateFormat("dd-MM-yyyy").format(itemDate); System.out.println(myDateStr); y = gHistory[i].getMeter(); x = gHistory[i].getScoreClassfification(); float c = (float) y; YAxis leftAxis = mChart.getAxisLeft(); leftAxis.removeAllLimitLines(); leftAxis.setAxisMaximum(300); leftAxis.setAxisMinimum(90); leftAxis.enableGridDashedLine(c, c, 0f); leftAxis.setDrawZeroLine(false); leftAxis.setDrawLimitLinesBehindData(false); leftAxis.setValueFormatter(new MyValueFormatter()); } mChart.getAxisRight().setEnabled(false); setDataRoom(gHistory); } private void setDataRoom(GhistoryMeter[] listHistory) { GHistory gHistory = new GHistory(); ArrayList<Entry> values = new ArrayList<>(); int historyCount = listHistory.length; LineDataSet set1; double x; double y; float f = (float) 50; for (int i = 0; i < historyCount; i++) { y = listHistory[i].getMeter(); x = listHistory[i].getScoreClassfification(); float c = (float) y; f = f + 50; values.add(new Entry(f, c)); if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) { set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0); set1.setValues(values); mChart.getData().notifyDataChanged(); mChart.notifyDataSetChanged(); } else { set1 = new LineDataSet(values, "History Data"); set1.setDrawIcons(false); set1.setColor(Color.GREEN); set1.setCircleColor(Color.GREEN); set1.setLineWidth(1f); set1.setCircleRadius(3f); set1.setDrawCircleHole(false); set1.setValueTextSize(9f); set1.setDrawFilled(true); set1.setFormLineWidth(1f); set1.setFormSize(15.f); if (Utils.getSDKInt() >= 18) { Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.fade_blue); set1.setFillDrawable(drawable); } else { set1.setFillColor(Color.GREEN); } } ArrayList<ILineDataSet> dataSets = new ArrayList<>(); dataSets.add(set1); LineData data = new LineData(dataSets); mChart.setData(data); } } private void showData(List<MHistory> listData, MHistory h, GHistory[] gHistory) { double x, y, z, a; for (int i = 0; i < listData.size(); i++) { Date itemDate = listData.get(i).getCreatedAt(); // listData.get(i).getCreatedAt(); String myDateStr = new SimpleDateFormat("dd-MM-yyyy").format(itemDate); System.out.println(myDateStr); y = listData.get(i).getMeter(); x = listData.get(i).getMeter(); z = listData.get(i).getId(); // x = listData.get(i).getScoreClassification(); float d = (float) x; YAxis leftAxis = mChart.getAxisLeft(); leftAxis.removeAllLimitLines(); leftAxis.setAxisMaximum(300); leftAxis.setAxisMinimum(90); leftAxis.enableGridDashedLine(d, d, 0f); leftAxis.setDrawZeroLine(false); leftAxis.setDrawLimitLinesBehindData(false); leftAxis.setValueFormatter(new MyValueFormatter()); } mChart.getAxisRight().setEnabled(false); setData(listData); } private void setData(List<MHistory> listData) { ArrayList<Entry> values = new ArrayList<>(); int historyCount = listData.size(); LineDataSet set1; double x; double y, z, a; float f = (float) 50; for (int i = 0; i < historyCount; i++) { y = listData.get(i).getMeter(); x = listData.get(i).getMeter(); float d = (float) x; z = listData.get(i).getId(); f = f + 50; values.add(new Entry(f, d)); if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) { set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0); set1.setValues(values); mChart.getData().notifyDataChanged(); mChart.notifyDataSetChanged(); } else { set1 = new LineDataSet(values, "History Data"); set1.setDrawIcons(false); set1.setColor(Color.GREEN); set1.setCircleColor(Color.GREEN); set1.setLineWidth(1f); set1.setCircleRadius(3f); set1.setDrawCircleHole(false); set1.setValueTextSize(9f); set1.setDrawFilled(true); set1.setFormLineWidth(1f); set1.setFormSize(15.f); if (Utils.getSDKInt() >= 18) { Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.fade_blue); set1.setFillDrawable(drawable); } else { set1.setFillColor(Color.GREEN); } } ArrayList<ILineDataSet> dataSets = new ArrayList<>(); dataSets.add(set1); LineData data = new LineData(dataSets); mChart.setData(data); } } private void setListener() { } /* @Override public void onStart() { super.onStart(); firebaseRecyclerAdapter.startListening(); } @Override public void onStop() { super.onStop(); firebaseRecyclerAdapter.stopListening(); } //ViewHolder class public static class UserViewHolder extends RecyclerView.ViewHolder { View mView; CardView cardView; public UserViewHolder(View itemView) { super(itemView); mView = itemView; cardView = itemView.findViewById(R.id.cvMain_addresss); // mView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Context context = v.getContext(); // Intent intent = new Intent(context, EventDetailActivity.class); // // context.startActivity(intent); // } // }); } public void setStatusName(int status){ TextView status0 = (TextView) mView.findViewById(R.id.status0); TextView status1 = (TextView) mView.findViewById(R.id.status1); ImageView imageView = mView.findViewById(R.id.img_check_done); ImageView imageView2 = mView.findViewById(R.id.img_check_done_all); if (status<=0){ status0.setVisibility(View.GONE); status1.setVisibility(View.GONE); imageView.setVisibility(View.VISIBLE); imageView2.setVisibility(View.GONE); }else{ status0.setVisibility(View.GONE); status1.setVisibility(View.GONE); imageView.setVisibility(View.GONE); imageView2.setVisibility(View.VISIBLE); } } public void setFname(double name) { TextView FName = (TextView) mView.findViewById(R.id.rMeter); String s=Double.toString(name); FName.setText(s); } public void setLname(double name) { TextView LName = (TextView) mView.findViewById(R.id.rIdentify); String s=Double.toString(name); Log.d("stringset"," "+s); LName.setText(s); } public void setAname(double name) { TextView AName = (TextView) mView.findViewById(R.id.rClassify); String s=Double.toString(name); Log.d("stringset"," "+s); AName.setText(s); } public void setDate(String d) { TextView DName = (TextView) mView.findViewById(R.id.txtDates); DName.setText(d); } public void setOrderSpinner(String status) { } } */ }
Java
UTF-8
6,966
2.234375
2
[]
no_license
package com.oreo.paint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import androidx.annotation.Nullable; import com.oreo.paint.settings.AbstractSetting; import com.oreo.paint.settings.Backgrounds; import com.oreo.paint.settings.Colors; import com.oreo.paint.settings.Fab; import com.oreo.paint.settings.PaperStates; import com.oreo.paint.settings.Shapes; import com.oreo.paint.settings.Strokes; import com.oreo.paint.settings.UndoRedoClear; import java.util.ArrayList; /** * holds a collection of widgets that manipulates the Paper */ public class PaperController extends View { ArrayList<AbstractSetting> verticalSettings; public PaperController(Context context) { super(context); init(); } public PaperController(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } Paint paint; Colors colors; Strokes strokes; Shapes shapes; Backgrounds backgrounds; UndoRedoClear undoRedoClear; PaperStates paperStates; Fab toggleUI; void init() { paint = new Paint(); vBarState = SettingTouchState.IDLE; verticalSettings = new ArrayList<>(); colors = new Colors(6); // 0 strokes = new Strokes(); // 1 strokes shapes = new Shapes(); // 2 shapes backgrounds = new Backgrounds(); undoRedoClear = new UndoRedoClear(); toggleUI = new Fab(); paperStates = new PaperStates(); verticalSettings.add(toggleUI); // check for first verticalSettings.add(colors); verticalSettings.add(strokes); verticalSettings.add(shapes); verticalSettings.add(backgrounds); verticalSettings.add(undoRedoClear); verticalSettings.add(paperStates); toggleUI.setToggleWork(this::toggleUI); Runnable startMain = () -> { if (activeSettingIndex >= 0 && activeSettingIndex < verticalSettings.size()) { vBarState = SettingTouchState.MAIN_ACTION; invalidate(); } }; Runnable stopMain = () -> { vBarState = SettingTouchState.IDLE; invalidate(); }; for (AbstractSetting s : verticalSettings) { s.setView(this); s.setStartMainAction(startMain); s.setEndMainAction(stopMain); } } Paper paper; void setPaper(Paper p) { paper = p; } static final int BAR_W = 80; int W, H; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); W = right - left; H = bottom - top; int yTop = (int) (H / 4.5); backgrounds.init(paper, BAR_W, 120, W - BAR_W, H, yTop - 190, 0); colors.init(paper, BAR_W, (int) (H * 0.3), W - BAR_W, H, yTop, 0); yTop += H * 0.3 + 80; strokes.init(paper, BAR_W, 80, W - BAR_W, H, yTop, 0); yTop += 80 + 80; shapes.init(paper, BAR_W, 80, W - BAR_W, H, yTop, 0); yTop += 80 + 80; undoRedoClear.init(paper, BAR_W, 120, W - BAR_W, H, yTop, 0); yTop += 80 + 80; paperStates.init(paper, BAR_W, 120, W - BAR_W, H, yTop, 0); // free icon, position not fixed toggleUI.init(paper, W / 8, W / 8, W - BAR_W, H, H - 280, W - 180); } int activeSettingIndex; SettingTouchState vBarState; @Override public boolean onTouchEvent(MotionEvent e) { if (hideUI) { if (toggleUI.inIcon(e.getX(), e.getY())) { vBarState = SettingTouchState.QUICK_ACTION; } if (vBarState == SettingTouchState.QUICK_ACTION) return toggleUI.handleQuickEvent(e); if (vBarState == SettingTouchState.MAIN_ACTION) return toggleUI.handleMainEvent(e); return false; } switch (e.getActionMasked()) { case MotionEvent.ACTION_DOWN: if(vBarState == SettingTouchState.IDLE) { for (int i = 0; i < verticalSettings.size(); i++) { if (verticalSettings.get(i).inIcon(e.getX(), e.getY())) { activeSettingIndex = i; vBarState = SettingTouchState.QUICK_ACTION; return verticalSettings.get(i).handleQuickEvent(e); } } break; } case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: switch (vBarState) { case QUICK_ACTION: return verticalSettings.get(activeSettingIndex).handleQuickEvent(e); case MAIN_ACTION: return verticalSettings.get(activeSettingIndex).handleMainEvent(e); } } return false; } float vBarXOff; @Override protected void onDraw(Canvas canvas) { canvas.save(); canvas.translate(vBarXOff, 0); if (vBarState == SettingTouchState.MAIN_ACTION) { // draw bound paint.setColor(Color.argb(50,50, 50, 50)); paint.setStyle(Paint.Style.FILL); canvas.drawRect(0, 0, BAR_W, H, paint); } for (int i = verticalSettings.size() - 1; i > -1; i--) { if (verticalSettings.get(i) == toggleUI) { // draw toggle ui here since it position should not change canvas.save(); canvas.translate(-vBarXOff, 0); } verticalSettings.get(i).drawIcon(canvas); if (activeSettingIndex == i && vBarState == SettingTouchState.MAIN_ACTION) { canvas.save(); canvas.translate(BAR_W, 0); canvas.clipRect(0, 0, W - BAR_W, H); verticalSettings.get(i).drawMain(canvas); canvas.restore(); } if (verticalSettings.get(i) == toggleUI) { // draw toggle ui here since it position should not change canvas.restore(); } } canvas.restore(); if (hideUI) { if (vBarXOff > -BAR_W) { vBarXOff += (-BAR_W - vBarXOff) * 0.2 - 1; invalidate(); } } else if (vBarXOff < 0) { vBarXOff += - vBarXOff * 0.2 + 1; if (vBarXOff > 0) { vBarXOff = 0; } invalidate(); } // animate } boolean hideUI = false; void toggleUI() { hideUI = !hideUI; invalidate(); } enum SettingTouchState { IDLE, QUICK_ACTION, MAIN_ACTION } }
JavaScript
UTF-8
7,474
2.546875
3
[]
no_license
const botconfig = require("./botconfig.json"); const Discord = require("discord.js"); const {Client, RichEmbed} = require(`discord.js`); const bot = new Discord.Client({disableEveryone: true}); bot.on("ready", async () => { console.log(`${bot.user.username} is online!`); bot.user.setActivity("Monopoly."); }); const fs = require("fs"); bot.data = require("./data.json"); bot.on("message", async message => { if(message.author.bot) return; if(message.channel.type === "dm") return; let prefix = botconfig.prefix; let messageArray = message.content.split(" "); let cmd = messageArray[0]; let args = messageArray.slice(1); if(message.content === `${prefix}sucess`) { return message.channel.send("yes!"); } /** List of Commands */ if (message.content === `${prefix}help` && message.channel.name === "clan-information"){ const embed = new RichEmbed() .setTitle('The Minutemen Help Desk') .setColor(0xFF0000) .setDescription(`Once again, welcome to the Minutemen discord server! \n The purpose of this server is to communicate with other clan members about many different aspects of clash to strenghten our clan further and to have fun of course. \n Please keep the server Christian friendly and keep "it" in your pants! Happpy Clashing! \n \n Minutemen Informations: \n \n -elder -coleader -leader -inactive \n \n Minutemen Honorable Mentions: \n \n -firstpresident -donationgod -clangamesonic -howtogetgood -taxevasion -donttouchmyspaghet`); message.channel.send(embed); } else if(cmd === `${prefix}donttouchmyspaghet` && message.channel.name === "clan-information"){ /*minutemen vs phluffy*/ const embed = new RichEmbed() .setTitle("PHluffy v. theminutemen, 1976 (0 - 9)") .setColor(0xFFA07A) .setDescription(`Phluffy Czerwinski, a former clash of clan World War 3 veteran, filed a lawsuit against the minutemen government \n for not upholding the plan that the minutemen themselves have created. Despite the victory and high reward/benefits Phluffy recieved, \n he was furious that his favorite number was taken away from him. The case was settled with $5 million gold to Phluffy and a short term \n retirement from future war missions.`) .setImage("https://imgur.com/a/S5bwZX0"); message.channel.send(embed); } else if(cmd === `${prefix}clangamesonic` && message.channel.name === "clan-information"){ /* Clan Game Sonic */ const embed = new RichEmbed() .setTitle("Fastest Clan Game Grinder!") .setColor(0x1A45EE) .setDescription(`The Final Weeb have max the clan game points the fastest during our recent clan game! (oof sorry Phluffy) Can you steal The Final Weeb's position or will The Final Weeb maintain the current position?`) .setImage("https://memegenerator.net/img/instances/71878629/good-job.jpg"); message.channel.send(embed); } else if(cmd === `${prefix}firstpresident` && message.channel.name === "clan-information") { /* First President */ const embed = new RichEmbed() .setTitle("George Washington") .setColor(0xF7911D) .setDescription(`George Washington founded the minutemen clan in 1789 under the secret identity, Prajwal Chandrashekar. \n Bravely fought and led the clan in the famous French and Indian war and American Revolutionary War. \n Although no longer with us, the clan continued to thrive and left a legacy that wil be forever remembered.`) .setImage("https://i.imgur.com/QV9vctK.jpg"); message.channel.send(embed); } else if(cmd === `${prefix}taxevasion` && message.channel.name === "clan-information") { /* Tax Evasion */ const embed = new RichEmbed() .setTitle("Jack the wet noodle") .setColor(0xF7F01D) .setDescription(`There once was an uncivilized member named Jack (aka. wet noodle) \n that refused to pay his taxes(donation) while the other clan members were doing their part. \n The clan tried to persuade Jack to do his civil duties . . . \n but in response Jack assembled a team starting the infamous Minutemen Civil War of 1861.`) .setImage("https://i.imgur.com/zeh6TI7.jpg"); message.channel.send(embed); } else if(cmd == `${prefix}donationgod` && message.channel.name === "clan-information") { /* Donation God */ const embed = new RichEmbed() .setTitle("Highest Donation Achieved!") .setColor(0x19BF3A) .setDescription(`Lelouch achieved the highest donation count during a single season! \n Lelouch has donated +25,000 units! Can you beat Lelouch's record?`) .setImage("https://i.imgur.com/ctOFNMA.jpg"); message.channel.send(embed); } else if(cmd === `${prefix}elder` && message.channel.name === "clan-information") { /* Elder */ return message.channel.send(`Elder Requirement: 1. Be Active! 2. Be Courteous! 3. Donate 400 or more troops during a single season! 4. Show proficiency in war attacks! 5. Recieve an approval from the leaders!`); } else if(cmd === `${prefix}coleader` && message.channel.name === "clan-information"){ /* Coleader */ return message.channel.send(`Co-Leader Requirement: 1. Be Active! 2. Be Courteous! 3. Maintain the Elder status! 4. Donate 600 or more troops every season! 5. Earn a total of 42 wars stars from the minutemen regular clan wars. 6. Earn a total of 30 war stars from Clan League Wars. 7. Show leadership skills and dedication to the clan. 8. Recieve an approval from the leaders.`); } else if(cmd === `${prefix}leader` && message.channel.name === "clan-information"){ /* Leader */ return message.channel.send(`Leader Requirement: if( you == kim yoo suk) { System.out.println("You are leader!"); } else { System.out.println("You probably won't be leader unless kim yoo suk steps down!"); } return start a rebellion; }`); } else if(cmd === `${prefix}inactive` && message.channel.name === "clan-information"){ /* Inactive */ return message.channel.send(`Inactive Policy: If you have 19 or less victorious attacks within a seeason, you will be demoted and/or kicked!`); } else if(cmd === `${prefix}howtogetgood` && message.channel.name === "clan-information"){ /* How to get good */ const embed2 = new RichEmbed() .setTitle("Don't be like Cody! :)") .setColor(0xFF0000) .setDescription(`There once was a warrior named Cody. \n He was a pimped townhall 9 roaming the champion league fighting off the townhall 10s. \n One day, Cody was faced with a weak, pitful townhall 8 during a clan war. \n Without any hesitation, he unleashed his army upon the townhall 8. . . . but \n He somehow managed a 99% 2 stars. NOT 3 but a 2! And so the legend continues "Don't be like Cody! :)`) .setImage("https://i.imgur.com/8iMymSH.jpg"); message.channel.send(embed2); } /** Greeting New members. */ bot.on(`guildMemberAdd`, member => { const channel = member.guild.channels.find(ch => ch.name === 'welcome'); const embed2 = new RichEmbed() .setTitle('Greetings~') .setColor(0x00FF00) .setDescription(`${member}, welcome to the Minutemen Clan server! \n For more information, head on over to #discussion channel and type "-help".`); if(!channel) return; bot.channels.find("name", "welcome").send(embed2); }); }); bot.login(botconfig.token);