language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
6,416
2.5
2
[ "Apache-2.0" ]
permissive
package com.huxq17.example.utils; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.media.MediaScannerConnection; import android.media.ThumbnailUtils; import android.net.Uri; import android.os.Environment; import android.text.TextUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; /** * 图片处理工具类 * * @author wxl */ public class YnBitmapUtils { /** * app包名 */ private static final String APPPACKAGENAME = "com.yueniapp.sns"; /** * 释放bitmap * * @param bitmap */ public static void freeeBitmap(Bitmap bitmap) { if (null != bitmap && !bitmap.isRecycled()) { bitmap.recycle(); } } /** * 默认的bitmap压缩==》默认保存到sd/yueniapp/下 以原大小压缩 * @param bitmap * @return */ public static String compressBitmapDefault(Bitmap bitmap, int compressSize, CompressFormat type) { FileOutputStream fileOutputStream = null; String path = YnBitmapUtils.getProjectSDCardPath(); try { fileOutputStream = new FileOutputStream(new File(path)); bitmap.compress(type, compressSize, fileOutputStream); fileOutputStream.flush(); } catch (Exception e) { LogUtil.i("info",e.getMessage(),e); } finally { try { if(null != fileOutputStream) { fileOutputStream.close(); } } catch (Exception e) { LogUtil.i("info",e.getMessage(),e); } } return path; } /** * 获得项目SD卡的位置 */ public static String getProjectSDCardPath() { String sdcard_path = ""; // 判断SD卡是否为空 if (!Environment.MEDIA_REMOVED.equals(Environment.getExternalStorageState())) { sdcard_path = FileManager.getFilePath(); String strDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); sdcard_path = sdcard_path + APPPACKAGENAME + File.separator + "ypcrop" + strDate + ".jpg"; File file = new File(FileManager.getFilePath() + File.separator + APPPACKAGENAME); if (!file.exists()) { file.mkdirs(); } } return sdcard_path; } /** * 用来处理图片的太大的问题 * @param context * @param selectedImage 图片的uri * @return * @throws FileNotFoundException */ public static Bitmap decodeUri(Context context, Uri selectedImage) throws FileNotFoundException { BitmapFactory.Options options = new BitmapFactory.Options(); int width = 1080; options.inSampleSize = ImageUtil.computeSampleSize(options, -1, width * width);// 得到缩略图; AssetFileDescriptor fileDescriptor ; fileDescriptor = context.getContentResolver().openAssetFileDescriptor(selectedImage, "r"); Bitmap actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options); actuallyUsableBitmap = ThumbnailUtils.extractThumbnail(actuallyUsableBitmap, width, width); return actuallyUsableBitmap; } /* * 从数据流中获得数据 */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len ; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); inputStream.close(); return bos.toByteArray(); } /** * 网络下载图片 */ public static byte[] getImageFromNet(String path) { byte[] b = null; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inputStream = conn.getInputStream(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { b = readInputStream(inputStream); } }catch (Exception e){ LogUtil.i("info",e.getMessage(),e); } return b; } /** * 拍照时指定Uri */ public static String imagePath = null; public static Uri getCameraUri() { Uri uri ; String state = Environment.getExternalStorageState(); if (!TextUtils.isEmpty(state) && state.equals(Environment.MEDIA_MOUNTED)) { File file = new File(FileUtil.PATH); if (!file.exists()) { file.mkdirs(); } } else { // 返回手机的内存地址 File file = new File(Environment.getDataDirectory().getAbsolutePath() + "/data/"); if (!file.exists()) { file.mkdirs(); } } String strDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); // 照片的名字 String imageName = "yeuniapp_" + strDate + ".jpg"; // 图片的路径 imagePath = FileUtil.PATH + imageName; uri = Uri.fromFile(new File(imagePath)); return uri; } /** * 保存图片到相册 */ public static void savePic(Context context, String folderName, String fileName, Bitmap bitmap) { File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); System.out.println("path===="+path.toString()); File file = new File(path, folderName + "/" + fileName); file.getParentFile().mkdirs(); try { bitmap.compress(CompressFormat.JPEG, 90, new FileOutputStream(file)); MediaScannerConnection.scanFile(context, new String[]{file.toString()}, null, null); } catch (FileNotFoundException e) { LogUtil.i("info",e.getMessage(),e); } } }
JavaScript
UTF-8
6,588
2.546875
3
[ "MIT" ]
permissive
const express = require("express"); const users = express.Router(); //Middleware const protect = require("../middleware/authMiddleware"); //Functions from Controller const registerUser = require("../controllers/userController").registerUser; const loginUser = require("../controllers/userController").loginUser; const getAllUsers = require("../controllers/userController").getAllUsers; const getUserById = require("../controllers/userController").getUserById; const registerInstructor = require("../controllers/userController") .registerInstructor; /** * @swagger * components: * schemas: * User: * type: object * required: * -id * -firstName * -lastName * -userName * -email * -password * -isInstructor * properties: * id: * type: string * description: Autogenerated ID by db * firstName: * type: string * description: The first name of the user * lastName: * type: string * description: The last name of the user * userName: * type: string * description: The user's username * email: * type: string * description: The user's email * password: * type: string * description: the users email address * isInstructor: * type: boolean * description: Determines if the usr is an instructor * courses: * type: Array * description: The list of courses the user has created. * */ /** * @swagger * tags: * name: Users * description: Users routes */ /** * @swagger * /api/users/register: * post: * summary: Registers one user into the database * tags: [Users] * parameters: * - in: body * name: user * description: The user information to add to database * schema: * type: object * required: * -firstName * -lastName * -userName * -email * -password * properties: * firstName: * type: string * lastName: * type: string * userName: * type: string * email: * type: string * password: * type: string * responses: * 200: * description: Successfully registered one into database. * 401: * description: Something went wrong registering a user. * */ users.route("/register").post(registerUser); /** * @swagger * /api/users/login: * post: * summary: Authenticates a user * tags: [Users] * parameters: * - in: body * name: user * description: The users login information * schema: * type: object * required: * -email * -password * properties: * email: * type: string * password: * type: string * responses: * 200: * description: User successfully authenticated. * content: * application/json: * schema: * type: object * properties: * firstName: * type: string * lastName: * type: string * userName: * type: string * Token: * type: string * 401: * description: Something went wrong registering a user. * 409: * description: Incorrect username or password * */ users.route("/login").post(loginUser); /** * @swagger * /api/users/all: * get: * summary: Returns all users in database * tags: [Users] * responses: * 200: * description: An array of objects with user information * 401: * description: An error occured getting the list of users. * */ users.route("/all").get(getAllUsers); /** * @swagger * /api/users/user/{id}: * get: * summary: Returns one user that is found by the users id. * tags: [Users] * parameters: * - in: header * name: JSON Web Token * type: string * required: true * - in: path * name: id * schema: * type: string * required: true * description: the id of a user. * responses: * 200: * description: The information of one users returns * contents: * application/json: * schema: * $ref: '#/components/schemas/User' * * 404: * description: User was not found. * 401: * description: Not authorized. * */ users.route("/user/:id").get(protect, getUserById); /** * @swagger * /api/users/instructor/register: * post: * summary: Registers one instructor into the database * tags: [Users] * parameters: * - in: body * name: user * description: The user information to add to database * schema: * type: object * required: * -firstName * -lastName * -userName * -email * -password * properties: * firstName: * type: string * lastName: * type: string * userName: * type: string * email: * type: string * password: * type: string * responses: * 200: * description: Successfully registered one instructor into database. * 401: * description: Something went wrong registering an instructor. * */ users.route("/instructor/register").post(registerInstructor); module.exports = users;
Markdown
UTF-8
5,562
2.703125
3
[ "MIT" ]
permissive
## 2017.7.22. ## Sungkyu Cho - sungkyu1.cho@gmail.com PWNABLE KR - TODDLER - Passcode - 10pt 쉽게 풀릴 줄 알았던 문제인데, 의외로 정말 오랫동안 애를 먹었던 문제. 이유는 나중에 설명을 하겠지만, 작은 힌트에 대해서 너무 쉽게 생각했던 내 안이함이 큰 원인이었다. # 0.우선은 소스코드 살펴보기 passcode.c 파일을 살펴보면 welcome() 에서 username 을 받고, login()에서 모든 비교 작업을 하는 것을 알 수 있음. 매우 간단한 코드. 그럼 이제 실제로 어딜 보면 좋을지를 알기 위해서 gdb 로 asm 코드를 보니 ![fig1](./_fig/1.png "Who are you") * passcode1 에는 338150, passcode2 에는 13371337을 집어넣으면 flag를 잡을 것이고 * passcode1 과 passcode2는 아마도 ```$ebp-0x10``` 과 ```$ebp-0xc```에 있을 것으로 추정됨 - 이유는,cmp 명령어가 두 번 보이는데 그게 각각 338150과 13371337을 비교하기 위한 것일테고 - 그 비교 대상이라고 하면 결국 passcode1과 passcode2 밖에 없기 때문임 * 아마도 추정하길 ~~추정은 금물. 난 다 틀려~~ username으로 받아들인 변수가 passcode1과 passcode2에 착착 들어가겠지? 라는 착각으로 조금 더 살펴보기 시작함 # 1.처음에 쉽게 생각했던 이유 동작내용을 보면 "name" 변수에 string 을 받아들이는데, 아마도 여기서 뭔가 터지는 부분이 있겠거니 하는 마음으로 매우 긴 string을 포함시켰음 이 때, 어디서 에러를 발생시키는지 위치를 정확하게 파악하기 위해서 사용한 string은 아래와 같음 ```0123456789abcdefghijklmnopqrstuvwxyz0a0b0c0d0f0g0h0i0j0k0l0m0n0o0p0q0r0s0t0u0v0w0x0y0z1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1q1r1s1t1u1v1w1x1y1z2a2b2c2d2e2f2g2h2i2j2k2l2m2n2o2p2q2r2s2t2u2v2w2x2y2z``` ![fig2](./_fig/2.png) * 예상과 비슷하게 ```$ebp-0x10```과 ```$ebp-0xc```에는 비교 대상이 포함되었고, ```$ebp-0x10```에 ```name``` 변수의 맨 마지막 4 byte가 들어가는 것을 확인함 * 0x67316631은 ```1f1g``` 이므로 입력 맨 마지막 변수가 비교대상으로 포함되는 것을 알 수 있었음 # 2. 시련은 여기부터 숱한 삽질을 해도, 어떻게든 ```passcode1```에는 값이 들어가고 또 비교문구도 통과도 하지만 * 더 긴 ~~그리고 더 긴, 긴...~~~ username 을 넣어봐도 * username은 짧게 하고 passcode1에 긴 값을 넣어봐도 아무래도 더 진행은 어려웠는데...(사실 걍 포기한 상태였고, 그 이후에 pwnable kr 을 모두 풀어보자는 그룹에 가입) # 3. Assist GOT와 PLT를 봐보라는 조언으로 다시 시작. [GOT와 PLT #1](https://bpsecblog.wordpress.com/2016/03/07/about_got_plt_1/) [GOT와 PLT #2](http://expointer.tistory.com/13) * Special thanks to @hackpupu & @min # 4. Reload (앞서 말했던 것처럼)결론적으로 내가 가장 등한시 했던 부분이 바로 scanf 함수에 대한 이해였음. scanf를 너무 쉽게 사용했음에도 그것에 대해서 잘 고민해보는 시간이 없었던터라.. [scanf 설명 ~~너무도 당연한~~~](http://itguru.tistory.com/36) 곰곰히 잘 생각해보면 1) scanf("%d", &var)는 var의 주소가 0x0add 라면 0x0add에 입력받은 10진정수를 저장하라는 것이고 1000을 입력하면 0x0add = 1000 이 된다. ~~~당연하지~~~ 2) 근데 현재 passcode 상에서의 code 는 ```&``` 가 없는 상태인데 여기에 1000을 입력하면 - 1000이라는 주소를 사용자가 지정하게 되어버리는 꼴 - 따라서, scanf 함수 내에서 당연히 죽어버리게 됨 3) 결론적으로 **코드에서 작성된 scanf의 bug를 이용하여 exploit 하는 방향이었고, 이 때 활용할 수 있는 카드가 GOT&PLT** 였던 것임 4) 그럼 대상이 어떻게 되어야 할 것이냐를 보면, 위 ```gdb) disas login``` 상에서 쭉 보면 알겠지만, 간단하게 fflush가 뛰어야 할 정상 주소가 아닌, ```cmp``` 명령어 이후의 ```0x80485e3```으로 뛰면 된다. 바로 뒤에 system 함수가 호출되는 ```0x80485ea```로 뛰지 않는 이유는 간단하다. ``` "/bin/cat flag" ``` 라는 문자열이 셋업된 이후에 뛰어야 하기 때문임 ![fig3](./_fig/3.png) _강제로 ```eip```를 0x80485e3으로 변경한 후 스택에 올라온 값을 확인해보면 /bin/cat flag가 출격 대기중임_ 결론적으로, scanf를 통해(+코드 버그) + passcode1의 값(100byte 끝의 마지막 4byte)를 지정할 수 있고 + passcode1가 위치할 주소를 정할 수 있으므로 + 특정 위치와 그 값을 지정할 수 있다는 얘기이며 + 이 조건은 fflush 함수를 살펴보면 알게되듯이, plt 를 통해 ```jmp *(addr)``` 의 형식으로 지정되어 있는 fflush 함수를 활용한 특정위치로의 코드 점프를 가능하게 함 (아래 그림 참조) ![fig4](./_fig/4.png) # 5. Exploit payload 구성은 아래와 같음 + 96byte의 의미없는 byte stream -> "A" + scanf를 통해 입력될 passcode1의 위치(주소값) -> ```"0x8048a004"``` (fflush 원래 코드가 위치하는 jmp 이후의 주소) + scanf안에 들어갈 ```passcode1```값 (```jmp```를 통해 어디로 뛸 지 주소값) -> ```0x80485e3```(fflush를 통해 동작하게 될 코드 위치) ![fig5](./_fig/5.png) 여기서 ```134514147```은 ```0x80485e3```의 decimal value인데. 이걸 hexa로 넣을지, ```""``` 를 넣을지 뺄지 가지고도 한참 삽질했던 것은 비밀. 근데 그 비밀의 열쇠도 결국 ```scanf```가 가지고 있었다. ```%d"```로 값을 받아들였으니, 당연히 decimal로 입력해야 하는 것이니까..ㅋ
C++
UTF-8
1,614
3.203125
3
[]
no_license
/* CSE 109: Fall 2018 Lydia Cornwell lac221 Makes hash map Program #6 */ #ifndef HASH_H #define HASH_H #include<vector> #include<cstring> #include<string> #include<iostream> #include<sstream> using namespace std; class Hash_t { public: Hash_t(); Hash_t(size_t buckets); Hash_t(size_t buckets, int(*hashfunc)(const void*, size_t)); Hash_t(Hash_t &src); Hash_t& operator=(const Hash_t&); bool insert(unsigned int); Hash_t& operator+=(unsigned int); bool find(unsigned int); bool remove(unsigned int); Hash_t& operator-=(unsigned int); string to_string() const; size_t size() const; bool resize(size_t); friend ostream& operator<<(ostream&, const Hash_t&); class iterator { friend class Hash_t; public: iterator(); iterator(std::vector<std::vector<unsigned int> >*, size_t, size_t); iterator(const iterator&); iterator& operator=(const iterator&); bool operator!=(const iterator&) const; bool operator==(const iterator&) const; iterator operator+(size_t amt) const; iterator& operator+=(size_t amt); iterator operator-(size_t amt) const; iterator& operator-=(size_t amt); iterator& operator++(); iterator& operator--(); //postfix iterator operator++(int); iterator operator--(int); const unsigned int& operator*() const; private: std::vector<std::vector<unsigned int> >* bucket_ptr; size_t bucket_idx; size_t data_idx; }; iterator begin(); iterator end(); iterator remove(iterator& it); private: vector<vector<unsigned int>> buckets; int(*function)(const void*, size_t); size_t _size; unsigned int getIndex(const unsigned int&) const; }; #endif
Java
UTF-8
466
1.695313
2
[ "Apache-2.0" ]
permissive
package io.ebeaninternal.api; import io.ebeaninternal.server.querydefn.OrmQueryProperties; import java.util.List; /** * The secondary query paths for 'query joins' and 'lazy loading'. */ public interface SpiQuerySecondary { /** * Return a list of path/properties that are query join loaded. */ List<OrmQueryProperties> queryJoins(); /** * Return the list of path/properties that are lazy loaded. */ List<OrmQueryProperties> lazyJoins(); }
Java
UTF-8
380
2.859375
3
[]
no_license
package nl.capgemini.diving.assignmentdequeu; public class Task { private String personName; public Task(String personName) { this.personName = personName; } public String getPersonName() { return personName; } public void execute() { System.out.println("This is a Task which is invoked for name: "+getPersonName()); } }
C#
UTF-8
1,901
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using fitapp.DAL; using fitapp.Models; using fitapp.ViewModels; using PagedList; namespace fitapp.Controllers { public class HomeController : Controller { private FitappDbContext db = new FitappDbContext(); //INDEX - zawartosc do usuniecia public ActionResult Index() { var products = db.Products.ToList(); return View(products); } // SEARCH public ActionResult Search(string searchQuery) { var products = db.Products.Where(p => p.Name.ToLower().StartsWith(searchQuery.ToLower()) || searchQuery == null).ToList(); return View(products); } // PRODUCT SUGGESTIONS public ActionResult ProductsSuggestions(string term) { var products = this.db.Products.Where(p => p.Name.ToLower().StartsWith(term.ToLower())).Take(10).Select(p => new { label = p.Name }); return Json(products, JsonRequestBehavior.AllowGet); } // SZCZEGÓŁY PRODUKTU //public ActionResult Details(int id) //{ // var product = db.Products.Find(id); // if (product == null) // { // return HttpNotFound(); // } // return View(product); //} // CAŁA BAZA PRODUKTÓW public ActionResult ProductsList(int? page = 1) { var products = db.Products.ToList(); int pageNumber = (page ?? 1); int productsOnPage = 20; return View(products.ToPagedList(pageNumber, productsOnPage)); } // STATIC CONTENT public ActionResult StaticContent(string viewname) { return View(viewname); } } }
Java
UTF-8
423
2.953125
3
[]
no_license
package com.company; public class Circle extends Shape{ private String name; public Circle(int height, int width) { super(height, width); } @Override float AreaCalc() { return 0; } @Override int getCenter() { return 0; } @Override int CircumCalc() { return 0; } @Override boolean isInsideShape() { return false; } }
PHP
UTF-8
1,806
3.265625
3
[ "BSD-3-Clause" ]
permissive
<?php if (!function_exists('dd')) { /** * Dump the passed variables and end the script. * * @param mixed * @return void */ function dd($expression, $_ = null) { var_dump(func_get_args()); die(1); } } if (!function_exists('object_get')) { /** * Get an item from an object using "dot" notation. * * @param object $object * @param string $key * @param mixed $default * @return mixed */ function object_get($object, $key, $default = null) { if (is_null($key) || trim($key) == '') { return $object; } foreach (explode('.', $key) as $segment) { if (!is_object($object) || !isset($object->{$segment})) { return value($default); } $object = $object->{$segment}; } return $object; } } if (!function_exists('class_basename')) { /** * Get the class "basename" of the given object / class. * * @param string|object $class * @return string */ function class_basename($class) { $class = is_object($class) ? get_class($class) : $class; return basename(str_replace('\\', '/', $class)); } } if (!function_exists('loop')) { /** * @param callable $handle * @param integer $count */ function loop($handle, $count) { foreach (range(1, $count) as $i) { $handle($i); } } } if (!function_exists('randomDate')) { function randomDate($start_date, $end_date) { // Convert to timetamps $min = strtotime($start_date); $max = strtotime($end_date); // Generate random number using above bounds $val = rand($min, $max); return $val; } }
Java
UTF-8
3,271
2.203125
2
[]
no_license
package com.springReactive.practice.utils; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.ValidationException; import org.springframework.http.HttpStatus; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.ServerResponse; import com.springReactive.practice.constant.CommonConstants; import com.springReactive.practice.error.PlatformError; import com.springReactive.practice.model.Anime; import com.springReactive.practice.model.AnimeResponse; import com.springReactive.practice.model.ValidationResult; import reactor.core.publisher.Mono; public final class PlatformErrorUtils { private static Map<Integer, String> errorMessage = new HashMap<>(); static { errorMessage.put(HttpStatus.NOT_FOUND.value(), CommonConstants.OBJECT_NOT_FOUND_ERROR); errorMessage.put(HttpStatus.INTERNAL_SERVER_ERROR.value(), CommonConstants.INTERNAL_SERVER_ERROR); errorMessage.put(HttpStatus.BAD_REQUEST.value(), CommonConstants.BAD_REQUEST); errorMessage.put(HttpStatus.CONFLICT.value(), CommonConstants.CONFLICT_REQUEST); errorMessage.put(HttpStatus.UNPROCESSABLE_ENTITY.value(), CommonConstants.UNPROCESSABLE_ENTITY); } public static PlatformError createPlatformError(String userDesc, int statusCode) { PlatformError error = new PlatformError(); error.setTimestamp(CommonUtils.getTimeStamp()); error.setMessage(userDesc); error.setStatus(statusCode); error.setError(errorMessage.get(statusCode)); return error; } public static ValidationResult createValidationResult(List<String> errors, HttpStatus status) { ValidationResult validationResult = new ValidationResult(); validationResult.setFailureFlag(Boolean.TRUE); validationResult.setErrors(errors); validationResult.setStatus(status); return validationResult; } private static Mono<ServerResponse> createErrorResponse(String message, int statusCode) { return ServerResponse.status(statusCode) .body(BodyInserters.fromObject(createPlatformError(message, statusCode))); } public static Mono<ServerResponse> handleExceptions(Throwable ex) { if (ex instanceof ValidationException) { String message = ex.getMessage(); String errorCode = ((ValidationException) ex).getErrorCode(); int statusCode = HttpStatus.valueOf(errorCode).value(); return ServerResponse.status(statusCode) .body(BodyInserters.fromObject(createErrorResponse(message, statusCode))); } else { return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).body(BodyInserters.fromObject( createErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), 500))); } } public static Mono<AnimeResponse> createValidationError(Anime anime) { AnimeResponse animeResponse = new AnimeResponse(); PlatformError platformError = createPlatformError( anime.getValidationResult().getErrors().toString(), anime.getValidationResult().getStatus().value()); animeResponse.setError(platformError); animeResponse.setStatus(HttpStatus.BAD_REQUEST.value()); animeResponse.setEntityStatus(CommonConstants.ERROR); return Mono.just(animeResponse); } }
Java
UTF-8
1,208
3.890625
4
[]
no_license
/////////////////////////////////////////////////////////////////////////// // // Java5401 Write a program that implements a Queue data structure. // Complete the <remove(int i)> method so that it removes // the parameter number, but leaves the remaining queue intact. // // eg. // 43 92 41 39 10 32 62 17 29 51 35 44 24 15 72 66 // // remove(6); // // 62 17 29 51 35 44 24 15 72 66 // // /////////////////////////////////////////////////////////////////////////// import java.util.*; import static java.lang.System.*; public class Java5401{ public static void main(String[] args) { new Model(); }} class Model { Queue<Integer> myQueue; public Model() { myQueue = new LinkedList<Integer>(); myQueue.add(43); myQueue.add(92); myQueue.add(41); myQueue.add(39); myQueue.add(10); myQueue.add(32); myQueue.add(62); myQueue.add(17); myQueue.add(29); myQueue.add(51); myQueue.add(35); myQueue.add(44); myQueue.add(24); myQueue.add(15); myQueue.add(72); myQueue.add(66); out.println(myQueue); for (int i = 0; i < 7; i++) { myQueue.poll(); } out.println(myQueue); } }
Java
UTF-8
796
2.890625
3
[]
no_license
package com.core; public class Main { private static int previousHash; public static void main(String[] args) { BlockChain blockchain = new BlockChain(); String[] SecondTransactions = new String[]{"First transaction: Kishore sent 100 dimecoins to Alice","Alice sent 150 dimecoins to Bob"}; String[] ThirdTransactions = new String[]{"Second transaction: Bob sent 100 dimecoin to kishore","Alice sent 50 dimecoins to Eve"}; blockchain.addBlock(SecondTransactions); blockchain.addBlock(ThirdTransactions); System.out.println(); System.out.println("***********************************************************"); System.out.println("List of Hashes in blockchain: "); for (long i: blockchain.getBlockChainInstance().getBlockChain()){ System.out.println(i); } } }
Java
UTF-8
2,007
4.125
4
[]
no_license
/*********************************************************************************** (Suma elementos columna por columna) Escribe un método que devuelva la suma de todos * * elementos en una columna especificada en una matriz usando el siguiente encabezado: * * public static double sumColumnas (double [] [] m, int columnasIndex) * * Escriba un programa de prueba que lea una matriz de 3 por 4 y muestre la suma de cada * * columna. * ************************************************************************************/ package ejercicio08_01; import java.util.Scanner; /** * * @author sesion */ public class Ejercicio08_01 { /** * @param args the command line arguments */ public static void main(String[] args) { // Lea una matriz de 3 por 4 double[][] matrix = getMatrix(); // Muestra la suma de cada columna for (int col = 0; col < matrix[0].length; col++) { System.out.println( "Suma de los elementos en la columna " + col + " es " + sumColumnas(matrix, col)); } } /** etMatrix inicializa una matriz con valores de entrada del usuario * @return */ public static double[][] getMatrix() { // Crear el Scanner Scanner input = new Scanner(System.in); final int FILAS = 3; final int COLUMNAS = 4; double[][] m = new double[FILAS][COLUMNAS]; // Pedir al usuario que ingrese una matriz de 3 por 4 System.out.println("Enter a " + FILAS + "-by-" + COLUMNAS + " matrix row by row:"); for (int fila = 0; fila < m.length; fila++) for (int col = 0; col < m[fila].length; col++) m[fila][col] = input.nextDouble(); return m; } /** sum devuelve la suma de los elementos en columnasIndex*/ public static double sumColumnas(double[][] m, int columnasIndex) { double sum = 0; for (int row = 0; row < m.length; row++) { sum += m[row][columnasIndex]; } return sum; } }
Python
UTF-8
434
2.59375
3
[]
no_license
import sys import os #import shutil import subprocess #shutil.copy(source,dest) #os.path.exists('/var') def List(dirName): cmd = 'ls l ' + dirName (status,output) = subprocess.getstatusoutput(cmd) if status: sys.stderr.write('there was an error: ' + output) sys.exit(1) print('This is not running\n') print(output) def main(): List(sys.argv[1]) if __name__ == '__main__': main()
Ruby
UTF-8
2,508
3.28125
3
[ "MIT" ]
permissive
require 'optparse' module CompareFiles class Cli def self.parse! args = Struct.new(:left, :right, :remember).new opt_parser = OptionParser.new do |opts| opts.banner = <<~BANNER Usage: compare_files --left=SRC --right=DEST [--remember=file] compare_files will output items in LEFT that are not in RIGHT" Example: Remember files from SRC, and output new files since command was last run. compare_files --left=SRC --right=seen.txt --remember=seen.txt BANNER opts.summary_width = 20 opts.on("--left=LEFT", "Required. Source side to compare against. May be a folder, or text file.") do |op| args.left = op end opts.on("--right=RIGHT", "Required. Destination side to compare against. May be a folder, or text file.") do |op| args.right = op end opts.on("--remember=FILE", "Save value of LEFT option to FILE. Useful for comparing SRC to itself through time.") do |op| pn = Pathname.new(op) valid_file_name = (pn.exist? && pn.file?) || !pn.exist? raise Error, "Invalid file name #{op}" unless valid_file_name args.remember = op end opts.on("-h", "--help", "Prints this help") do puts opts exit end opts.on("-v", "--version", "Prints the version (#{VERSION})") do puts VERSION exit end end opt_parser.parse! # verify we got the right combos valid_args = false valid_args = true if args.left && args.left unless valid_args puts "Missing required options.\n\n" puts opt_parser exit 1 end return args end def self.standardize_input(input) case when Pathname.new(input).directory? DirectoryList.list_of_files(input) when Pathname.new(input).file? file_as_str = File.open(input) do |file| file.read end Helpers.split_lines(file_as_str) when input.is_a?(String) pn = Pathname.new(input) file_as_str = if pn.exist? File.open(input) do |file| file.read end else FileUtils.touch(input) '' end Helpers.split_lines(file_as_str) when input.is_a?(Array) input else raise CompareFiles::Error, "unknown input type: #{input.class} " end end end end
Python
UTF-8
1,563
3.265625
3
[]
no_license
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: if not matrix or len(matrix) == 0 or len(matrix[0]) == 0: return 0 maxarea = 0 rows = len(matrix) cols = len(matrix[0]) heights = [0] * cols for i in range(rows): for j in range(cols): if matrix[i][j] == "1": heights[j] += 1 else: heights[j] = 0 result = self.largestRectangleArea(heights) maxarea = max(maxarea, result) return maxarea def largestRectangleArea(self, heights: List[int]) -> int: if not heights or len(heights) == 0: return 0 lessfromleft = [0] * (len(heights) + 1) lessfromright = [0] * (len(heights) + 1) lessfromleft[0] = -1 lessfromright[len(heights) - 1] = len(heights) for i in range(1, len(heights)): p = i - 1 while p >= 0 and heights[p] >= heights[i]: p = lessfromleft[p] lessfromleft[i] = p for i in range(len(heights) - 2, -1, -1): p = i + 1 while p < len(heights) and heights[i] <= heights[p]: p = lessfromright[p] lessfromright[i] = p maxarea = 0 for i in range(len(heights)): maxarea = max(maxarea, heights[i] * (lessfromright[i] - lessfromleft[i] - 1)) return maxarea
Java
UTF-8
27,798
2.125
2
[]
no_license
package com.example.rrcasino; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.media.Image; import android.os.Build; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; public class activityGamePoker extends AppCompatActivity { //Custom popup for help button Dialog myDialog; //Seek Bar private SeekBar playerBet; //Text private TextView betAmount; private TextView pot; private TextView playerBalance; //Buttons // private Button check; //private Button call; private Button bet; private Button fold; private Button deal; //Image Views for community cards and player cards private ImageView theflop; private ImageView theflopone; private ImageView thefloptwo; private ImageView theturn; private ImageView theriver; private ImageView pcard; private ImageView pcardone; private ImageView compCard; private ImageView compCardOne; private float transparent = 0; private float opaque = 1; //Array of Images for player and the table cards private ImageView[] playerCardImages; private ImageView[] computerCardImages; private ImageView[] communityCardImages; //Game Variables private DeckHandler.Deck deck; private PokerDealer dealer; private Player player; private Player computer; private int currentBet; private int buyIn = 10; private int minBet = buyIn; private int computerBet; private int potAmount; private int round = 0; private int startingFunds = 500; private String cardFaceDown = "b2fv"; private int playerBetAmount = 0; private boolean playerInitialBuyin = false; private boolean playerBetted = false; private boolean computerBetted = false; private boolean computerFolds = false; private boolean playerFold = false; private boolean cardsDealt = false; private Hand hand; private Hand temp; private enum gameResult { WIN, LOSE, TIE } @SuppressLint("WrongViewCast") @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_poker); //Initialize dialog this.myDialog = new Dialog(this); //Initialize Seekbar this.playerBet = findViewById(R.id.playerBet); playerBet.setMin(buyIn); playerBet.setMax(100); playerBet.setProgress(buyIn); //Text initialized this.betAmount = findViewById(R.id.betAmount); this.pot = findViewById(R.id.pot); this.playerBalance = findViewById(R.id.playerBalance); //Image views initialized this.theflop = findViewById(R.id.theflop); this.theflopone = findViewById(R.id.theflopone); this.thefloptwo = findViewById(R.id.thefloptwo); this.theturn = findViewById(R.id.theturn); this.theriver = findViewById(R.id.theriver); this.pcard = findViewById(R.id.pcard); this.pcardone = findViewById(R.id.pcardone); this.compCard = findViewById(R.id.ccard); this.compCardOne = findViewById(R.id.ccard1); playerCardImages = new ImageView[] {pcard, pcardone}; computerCardImages = new ImageView[] {compCard, compCardOne}; communityCardImages = new ImageView[] {theflop, theflopone, thefloptwo, theturn, theriver}; //Initialize buttons this.fold = findViewById(R.id.fold); //this.check = findViewById(R.id.check); //this.call = findViewById(R.id.call); this.bet = findViewById(R.id.bet); this.deal = findViewById(R.id.deal); fold.setEnabled(false); // check.setEnabled(false); //call.setEnabled(false); bet.setEnabled(false); betAmount.setEnabled(false); //Set button click handlers fold.setOnClickListener(clicked); //check.setOnClickListener(clicked); //call.setOnClickListener(clicked); bet.setOnClickListener(clicked); deal.setOnClickListener(clicked); //Initialize New Game this.deck = new DeckHandler.Deck(); this.dealer = new PokerDealer("dealer", 0); this.player = new Player("player", startingFunds); this.computer = new Player("computer", 1000); playerBalance.setText("Balance: $" + player.getBalance()); playerBet.setMax(player.getBalance()); //Handle All Listeners playerBet.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progressChangedValue = 0; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progressChangedValue = progress; betAmount.setText("Current Bet: $"+progressChangedValue); bet.setText("BET"); if(progressChangedValue == player.getBalance()){ bet.setText("ALL IN"); } //System.out.println(progressChangedValue); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { currentBet = progressChangedValue; playerBetAmount += currentBet; } }); } private View.OnClickListener clicked = new View.OnClickListener() { /* * Onclick listener for buttons * */ @Override public void onClick(View view) { switch (view.getId()){ case R.id.deal: //Disable the deal cards button deal.setEnabled(false); cardsDealt = true; playerBet.setVisibility(View.VISIBLE); betAmount.setVisibility(View.VISIBLE); pot.setText("POT"); startGame(); //System.out.println(Check_win()); System.out.println("DEAL was pressed"); break; case R.id.bet: playerInitialBuyin = true; playerBetted = true; potAmount += currentBet; pot.setText("$"+potAmount); System.out.println("BET was pressed"); System.out.println("In BET player buy in: "+playerInitialBuyin); checkRounds(); break; case R.id.fold: playerFold = true; System.out.println("FOLD was pressed"); endRound(); break; //end the round and update player balance if folded anywhere //after the first buy in } } }; //Show Help Popup public void ShowPopup(View v) { FloatingActionButton closepopup; myDialog.setContentView(R.layout.custompopup); closepopup = myDialog.findViewById(R.id.closepopup); closepopup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myDialog.dismiss(); } }); myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); myDialog.show(); } private void setImageResource (char participant, int cardNum, String imageSource) { /* * First parameter takes in a 'p' or 'd' character specifying whether a player or dealer card is * being updated. Essentially this specifies the ImageView ID affix pCard or dCard. * Second parameter specifies the ImageView ID suffix by card number, eg 1 or 2 for pCard1 or pCard2 * respectively. * Third parameter takes in a Card object (usually the last dealt card) that holds the image source * as a string */ Resources resources = getResources(); final int resourceId = resources.getIdentifier(imageSource,"drawable",getPackageName()); switch (participant) { case 'p': { switch (cardNum) { case 1: playerCardImages[cardNum-1].setAlpha(opaque); pcard.setImageResource(resourceId); break; case 2: playerCardImages[cardNum-1].setAlpha(opaque); pcardone.setImageResource(resourceId); break; } break; } case 'c': { switch (cardNum) { case 1: computerCardImages[cardNum-1].setAlpha(opaque); compCard.setImageResource(resourceId); break; case 2: computerCardImages[cardNum-1].setAlpha(opaque); compCardOne.setImageResource(resourceId); break; } break; } case 'd': { switch (cardNum) { case 1: communityCardImages[cardNum-1].setAlpha(opaque); theflop.setImageResource(resourceId); break; case 2: communityCardImages[cardNum-1].setAlpha(opaque); theflopone.setImageResource(resourceId); break; case 3: communityCardImages[cardNum-1].setAlpha(opaque); thefloptwo.setImageResource(resourceId); break; case 4: communityCardImages[cardNum-1].setAlpha(opaque); theturn.setImageResource(resourceId); break; case 5: communityCardImages[cardNum-1].setAlpha(opaque); theriver.setImageResource(resourceId); break; } break; } } } //Start the game private void startGame() { /* Create clean round * 1. Disable/Enable buttons * 2. Check that players hands are empty * 3. Update card images to face down, and make non-dealt cards transparent * 4. Enable SeekBar to set new bet amount * 5. Deal cards, and check for natural win */ // Update usable buttons bet.setEnabled(true); fold.setEnabled(true); //check.setEnabled(true); round++; //call.setEnabled(true); pot.setVisibility(View.VISIBLE); // Loop through participant hands and set to all cards to null card for (int i = 1; i <= 2; i++) { setImageResource('p', i, cardFaceDown); playerCardImages[i-1].setAlpha(transparent); setImageResource('c', i, cardFaceDown); computerCardImages[i-1].setAlpha(transparent); } //Loop through community table cards and set to NUll for(int i = 1; i <= 5; i++) { setImageResource('d', i, cardFaceDown); communityCardImages[i-1].setAlpha(transparent); } // Check that hands are empty if (player.getHand().getHandValue()>0) player.returnCards(); if (dealer.getHand().getHandValue()>0) dealer.returnCards(); if (computer.getHand().getHandValue()>0) computer.returnCards(); dealPlayerCards(); } //Deal initial player cards private void dealPlayerCards() { // Deal First Player Card dealer.dealCard(player, deck); setImageResource('p',player.getHand().getNumOfCardsInHand(), dealer.getLastDealtCard().getImageSource()); // Deal Computer First card dealer.dealCard(computer,deck); setImageResource('c', computer.getHand().getNumOfCardsInHand(), cardFaceDown); compCard.setRotation(270); //Deal Second player card dealer.dealCard(player,deck); setImageResource('p', player.getHand().getNumOfCardsInHand(), dealer.getLastDealtCard().getImageSource()); //Deal Second computer card dealer.dealCard(computer, deck); setImageResource('c', computer.getHand().getNumOfCardsInHand(), cardFaceDown); compCardOne.setRotation(270); //Dealing all community cards to test CheckWin() function /* dealer.dealCard(dealer,deck); setImageResource('d', dealer.getHand().getNumOfCardsInHand(), dealer.getLastDealtCard().getImageSource()); dealer.dealCard(dealer,deck); setImageResource('d', dealer.getHand().getNumOfCardsInHand(), dealer.getLastDealtCard().getImageSource()); dealer.dealCard(dealer,deck); setImageResource('d', dealer.getHand().getNumOfCardsInHand(), dealer.getLastDealtCard().getImageSource()); dealer.dealCard(dealer,deck); setImageResource('d', dealer.getHand().getNumOfCardsInHand(), dealer.getLastDealtCard().getImageSource()); dealer.dealCard(dealer,deck); setImageResource('d', dealer.getHand().getNumOfCardsInHand(), dealer.getLastDealtCard().getImageSource()); */ } //Functions to deal out cards. The flop initial deal of three cards, the turn deals one card, and the river deals the last card //Total of 5 cards laid out on the table private void dealTheFlop() { //First Flop Card dealer.dealCard(dealer, deck); setImageResource('d', dealer.getHand().getNumOfCardsInHand(),dealer.getLastDealtCard().getImageSource()); //Second Flop Card dealer.dealCard(dealer, deck); setImageResource('d', dealer.getHand().getNumOfCardsInHand(),dealer.getLastDealtCard().getImageSource()); //Third Flop Card dealer.dealCard(dealer, deck); setImageResource('d', dealer.getHand().getNumOfCardsInHand(),dealer.getLastDealtCard().getImageSource()); } private void dealTheTurn() { //Deal turn card dealer.dealCard(dealer, deck); setImageResource('d', dealer.getHand().getNumOfCardsInHand(), dealer.getLastDealtCard().getImageSource()); } private void dealTheRiver() { //Deal the river card dealer.dealCard(dealer,deck); setImageResource('d', dealer.getHand().getNumOfCardsInHand(), dealer.getLastDealtCard().getImageSource()); } private void checkRounds() { System.out.println("Entering 'checkRounds'.........."); System.out.println("Start Game player initial: " + playerInitialBuyin); System.out.println("Start Game player bet: " + playerBetted); System.out.println("Round: " +round); //Check the bettings for the initial round the deal the first three cards if(playerBetted && round == 1) { System.out.println("About to deal the Flop"); auto(computer); System.out.println("Computer Betted"); dealTheFlop(); System.out.println("Flop was dealt"); } //Check the bettings for the flop then deal a card else if (playerBetted && round == 2) { System.out.println("About to deal the Turn"); auto(computer); dealTheTurn(); } //Check the bettings for the turn then deal a card else if (playerBetted && round == 3) { System.out.println("About to deal the River"); auto(computer); dealTheRiver(); } //Check the Final bettings else if (playerBetted && round == 4) auto(computer); System.out.println("Current round: "+round); System.out.println("Start Game end player bet: " + playerBetted); System.out.println("Start Game player buy in: " + playerInitialBuyin); //endRound(); round++; playerBetted = false; System.out.println("Round amount: "+round); if(round == 5) { System.out.println("About to call end round"); endRound(); round = 0; } } private void endRound () { System.out.println("In endRound function"); bet.setEnabled(false); fold.setEnabled(false); //call.setEnabled(false); //check.setEnabled(false); deal.setEnabled(true); float cash = 0; Toast gameMesage; if(round == 5) { System.out.println("Revealing computer cards"); setImageResource('c',1 ,computer.getHand().getCard(0).getImageSource()); setImageResource('c', 2,computer.getHand().getCard(1).getImageSource()); round = 0; } if(playerFold && !playerInitialBuyin) { //Player doesnt lose cash player.addToBalance(cash); round = 0; // } else { switch (Check_win()) { case WIN: cash += potAmount; player.addToBalance(cash); gameMesage = Toast.makeText(activityGamePoker.this, "Player Wins", Toast.LENGTH_SHORT); //gameMesage.setGravity(Gravity.CENTER,0,0); gameMesage.show(); break; case TIE: gameMesage = Toast.makeText(activityGamePoker.this, "TIE", Toast.LENGTH_SHORT); //gameMesage.setGravity(Gravity.CENTER,0,0); gameMesage.show(); break; case LOSE: cash -= playerBetAmount; player.addToBalance(cash); gameMesage = Toast.makeText(activityGamePoker.this, "Computer Wins", Toast.LENGTH_SHORT); //gameMesage.setGravity(Gravity.CENTER,0,0); gameMesage.show(); break; } } // Set mew maximum bet; Player cannot bet more than available funds //reset booleans playerInitialBuyin = false; playerBetted = false; computerFolds = false; playerFold = false; potAmount = 0; round = 0; System.out.println("end round player buy: " + playerInitialBuyin); playerBet.setMax(player.getBalance()); playerBalance.setText("Balance: $"+player.getBalance()); System.out.println(Check_win()); // Update player balance TextView } /**Daniel's addition**/ public void Check_Hand (Player player) { // load hand combining hand this.hand = new Hand(); // load hand for unique value for straight check this.temp = new Hand(); // Flush flag int suit [] = {0, 0, 0, 0}; // pairs flag int pairs [] = {0,0,0,0,0,0,0,0,0,0,0,0,0}; // add players hand to temp hand for (int i = 0; i < player.getHand().getNumOfCardsInHand(); i++) { hand.addCard(player.getHand().getCard(i)); } // add dealer hand to temp hand for (int i = 0; i < dealer.getHand().getNumOfCardsInHand(); i++) { hand.addCard(dealer.getHand().getCard(i)); } //sort temp array use quick sort array is small insertion_sort(hand); //check for hand Flush for(int i=0 ;i<7 ;i++) { if (hand.getSuit(i) == 1 ) { suit[0]+=1; } else if (hand.getSuit(i) == 1 ) { suit[1]+=1; } else if (hand.getSuit(i) == 1 ) { suit[2]+=1; } else if (hand.getSuit(i) == 1 ) { suit[3]+=1; } } //flag for Flush for (int i=0;i<4;i++) { if (suit[i] >= 5) { player.setcondition(4); } } int count = 0; temp.addCard(hand.getCard(count)); for(int i=1;i<7;i++) { //if match update array if (hand.getCard(i).getRank() == temp.getCard(count).getRank()) { //check 3 of a king //if pair and not three of a kind if(player.getcondition(8) == 1 && (temp.getCard(count-1).getValue() != temp.getCard(count-2).getValue())) { player.setcondition(7); } //Flag pairs player.setcondition(8); } //track how many of each card ar ein the hand pairs[hand.getCard(i).getRank()-1] += 1; //if card value != temp value +1 replace temp //don't increase hand unless next part of rank if(hand.getCard(i).getValue() != temp.getCard(count).getValue() + 1) { temp.getHand().set(count, hand.getCard(i)); }else{ temp.addCard(hand.getCard(i)); count++; } } //if temp hand has 5 cards then hand is straight // flag straight if (temp.getNumOfCardsInHand() >= 5) { player.setcondition(5); } // if (royal flush) // search highest possible straight manually // and is Flush if (temp.getAcesInHand() == 1 && temp.getCard(1).getRank() == 10 && temp.getCard(2).getRank() == 11 && temp.getCard(3).getRank() == 12 && temp.getCard(4).getRank() == 13 ) { if (player.getcondition(4) == 1) { player.setcondition(0); } } // if (straight Flush ) if (player.getcondition(4) == 1 && player.getcondition(5) == 1) { player.setcondition(1); } //if (four of a kind) // flags for pairs in hands this.check_pairs(pairs); //else if (Flush) if(player.getcondition(4) == 1 && player.getcondition(5) != 1) { player.setcondition(4); } // else if (straight) if(player.getcondition(4) != 1 && player.getcondition(5) == 1) { player.setcondition(5); } } private void check_pairs(int[] pairs) { for(int i=12;i>0;i--) { //flag 4 of a kind if (pairs[i] == 3) { player.setcondition(2); //flag three of a kind } else if (pairs[i] == 2) { player.setcondition(6); // flag pair } else if (pairs[i] == 1) { player.setcondition(8); } } //if 3ofakind and pair are Flagged then flag fullhouse if (player.getcondition(6) == 1 && player.getcondition(8) == 1 ) { player.setcondition(3); } } //Quick sort for small array private void insertion_sort(Hand hand) { int n = player.getHand().getNumOfCardsInHand(); for(int i=1;i<n-1;i++) { DeckHandler.Card v = hand.getCard(i); int j = i - 1; while (j>=0 & hand.getCard(j).getValue() > v.getValue()) { hand.getHand().set(j+1, hand.getHand().get(j)); j = j -1; hand.getHand().set(j+1, v); } } } private void auto (Player player) { // this.Check_Hand(player); /* if (player.highestHand() >= 5) { // raise //just bet the min amount computerBet = minBet; potAmount += computerBet; computerBetted = true; } else if (player.highestHand() < 5 && player.highestHand() > 8) { //call //if player betted //set the bet to that amount if(playerBetted) { computerBet = currentBet; potAmount += computerBet; computerBetted = true; } } else { //fold //Just end the round //endround() as player wins computerFolds = true; endRound(); } */ Toast computerMessage; // System.out.println("Player bet boolean: "+playerBetted); if(playerInitialBuyin && round == 1) { computerBet = currentBet; potAmount += computerBet; computerBetted = true; computerMessage = Toast.makeText(activityGamePoker.this, "Computer Called", Toast.LENGTH_SHORT); //computerMessage.setGravity(Gravity.CENTER,0,0); computerMessage.show(); } else { computerBet = currentBet; potAmount += computerBet; computerBetted = true; computerMessage = Toast.makeText(activityGamePoker.this, "Computer Called", Toast.LENGTH_SHORT); //computerMessage.setGravity(Gravity.CENTER,0,0); computerMessage.show(); } } private gameResult Check_win () { gameResult result = activityGamePoker.gameResult.TIE; //2. compare highest win condition //win by hand if (player.highestHand() < computer.highestHand()) { result = activityGamePoker.gameResult.WIN; return result; } else if (player.highestHand() > computer.highestHand()) { result = activityGamePoker.gameResult.LOSE; return result; } else if (player.highestHand() == computer.highestHand()) { //check strength of hand if tie }else if (player.getHand().getHandValue() > computer.getHand().getHandValue()) { result = activityGamePoker.gameResult.WIN; return result; } else if (player.getHand().getHandValue() < computer.getHand().getHandValue()) { result = activityGamePoker.gameResult.LOSE; return result; } else if (player.getHand().getHandValue() == computer.getHand().getHandValue()) { //check kicker //check if the first card in player hand is the kicker }else if (player.getHand().getCard(0).getValue() > (computer.getHand().getCard(0).getValue() | computer.getHand().getCard(1).getValue())) { result = activityGamePoker.gameResult.WIN; return result; //check if the second card in player hand is the kicker } else if (player.getHand().getCard(1).getValue() > (computer.getHand().getCard(0).getValue() | computer.getHand().getCard(1).getValue())) { result = activityGamePoker.gameResult.WIN; return result; // player ties } else if (player.getHand().getHandValue() == computer.getHand().getHandValue()) { result = activityGamePoker.gameResult.TIE; return result; } else { result = activityGamePoker.gameResult.LOSE; } return result; } }
Java
UTF-8
2,451
3.59375
4
[]
no_license
package com.yang.sh.juc; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; class MyCache{ private volatile Map<String,Object> map = new HashMap<>(); private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); public void put (String k,String v){ readWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+"\t 写入数据"+k); try { TimeUnit.MICROSECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } map.put(k,v); System.out.println(Thread.currentThread().getName()+"\t 写入完成"); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.writeLock().unlock(); } } public void get (String k){ readWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName()+"\t 读取数据"); try { TimeUnit.MICROSECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } Object o = map.get(k); System.out.println(Thread.currentThread().getName()+"\t 读取完成"+o); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.readLock().unlock(); } } } /* * 多线程同时读一个资源类没有任何问题,所以为了满足并发量,读取共享资源应该同时进行 * 但是如果有一个资源想去写共享资源 * 就不应该有其他的线程可以对该资源进行读和写 * 小总结 * 读-读 可共存 * 读-写 不能共存 * 写-写 不能共存 * * */ public class ReadWriteLockDemo { public static void main(String[] args) { MyCache myCache = new MyCache(); for (int i = 1; i <= 5; i++) { int finalI = i; new Thread(()->{ myCache.put(finalI+"",finalI+""); },String.valueOf(i)).start(); } for (int i = 1; i <= 5; i++) { int finalI = i; new Thread(()->{ myCache.get(finalI+""); },String.valueOf(i)).start(); } } }
C++
UTF-8
2,837
3.15625
3
[]
no_license
// xml.h // Leitor XML baseado em eventos. Semi-completo. // Estruturas de Dados - T1 // 2911524 - Yuri Kunde Schlesner #ifndef YURIKS_T1_XML_H #define YURIKS_T1_XML_H #include <iostream> #include <stdexcept> namespace yuriks { namespace xml { /** Interface a ser implementada por classes que desejarem receber eventos do parser. */ class EventConsumer { public: // Abertura de tag virtual void tag_open(const char* tag_name) = 0; // Fechamento de tag virtual void tag_close(const char* tag_name) = 0; // Atributo de tag virtual void tag_prop(const char* prop_name, const char* prop_val) = 0; // Trecho textual virtual void tag_text_node(const char* value) = 0; }; /** Excecao lancada quando forem encontrados erros na leitura do xml. */ struct ReadingException : std::runtime_error { ReadingException(const std::string& str) : std::runtime_error(str) { } }; /** Leitor XML. Acredito suportar um sub-conjunto do formato adequado a este trabalho. * * A medida que a leitura do arquivo for sendo realizada, o leitor ira * chamar as funcoes do EventConsumer passado para read_xml. */ class Reader { public: Reader(std::istream& f); // Executa a leitura do arquivo, chamando os eventos em `consumer`. void read_xml(EventConsumer& consumer); // Numero da ultima linha lida. Util para mensagens de erro. unsigned int line_num() const; private: static const unsigned int max_tag_depth = 8; static const unsigned int max_tag_len = 16; static const unsigned int max_prop_name_len = 16; static const unsigned int max_prop_value_len = 64; static const unsigned int max_tag_content_len = 64; bool used; std::istream& f; int cur_line; std::istream& getch(char& c); // Le ate encontrar caractere nao-espaco. void skip_whitespace(); bool read_next_tag(char* tag, unsigned int tag_len); bool read_next_prop(char* prop, unsigned int prop_len, char* val, unsigned int val_len); void read_to_tag_end(); bool read_tag_content(char* content, unsigned int content_len); // Retorna true se c for [A-Za-z_] bool read_identifier(char* id, unsigned int id_len); // Le um valor entre aspas. void read_quoted(char* val, unsigned int val_len); // Le uma entity (&amp; etc) e retorna o caractere que representa. char read_entity(); // Le ate encontrar determinado caractere. void read_to_char(char ch, char* str, unsigned int str_len); // Le ate caractere, decodificando entities. void read_to_char_entdec(char ch, char* str, unsigned int str_len); // Nao assignable Reader& operator=(const Reader&); }; // Escreve uma string codificando entities XML std::ostream& write_string_entenc(std::ostream& s, const char* str); } // namespace xml } // namespace yuriks #endif // YURIKS_T1_XML_H
Markdown
UTF-8
1,705
3.046875
3
[ "MIT" ]
permissive
--- Title: Using build counters in Azure DevOps Tags: - Azure DevOps --- We recently migrated some builds from TeamCity to Azure DevOps at my client, and couldn't find a feature analog to TeamCity's `%build.counter%` which we've been using to get automatically incremented version numbers for artifacts. <!--excerpt--> Since we couldn't find the corresponding feature in Azure DevOps we settled on using the `$(Build.BuildId)` variable which is the canonical ID for a build. Not exactly ideal but it solved the immediate issue. Today I found a way of accomplishing the same thing in Azure DevOps, but sadly it's not properly documented even if it's [briefly mentioned][1] in the official documentation. The following lines in your `azure-devops.yml` will set the build number to an incrementing number that's scoped to the build definition. ```yml name: 1.0.$(myBuildCounter) variables: myBuildCounter: $[counter('buildCounter',1)] ``` The example above will create a build definition counter called `buildCounter` that will be initialized to the value `1`. This value will be incremented for each new build. If you ever want to reset or reseed this value you'll have to use the [Azure DevOps HTTP API][2]. If you have an option, consider using something like [GitVersion][3] or [MinVer][4] to dynamically calculate a version number from a git repository. [1]:https://docs.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#set-variables-using-expressions [2]:https://docs.microsoft.com/en-us/rest/api/azure/devops/build/definitions?view=vsts-rest-tfs-4.1 [3]:https://gitversion.readthedocs.io/en/latest/ [4]:https://github.com/adamralph/minver
C
UTF-8
1,169
3.703125
4
[]
no_license
#include<stdio.h> enum sex {boy,girl,Invalid}; enum season {spring,summer,autumn,winter,fail}; enum sex select1(void){ int temp; do { puts("请选择性别 男----0 女----1"); scanf("%d",&temp); if (temp<boy||temp>Invalid) puts("请不要拿您的性别开玩笑"); }while(temp<boy||temp>Invalid); return temp; } enum season select2(void){ int temp; do { puts("请选择出生季节 春---0 夏---1 秋---2 冬---3"); scanf("%d",&temp); if(temp<spring||temp>fail) puts("请重新选择您的出生季节"); }while(temp<spring||temp>fail); return temp; } int main(){ enum sex selected1 = select1(); enum season selected2 = select2(); if(selected1==0){ switch(selected2){ case spring: printf("春天男孩\n"); break; case summer: printf("夏天男孩\n"); break; case autumn: printf("秋天男孩\n");break; case winter: printf("冬天男孩\n");break; } }else{ switch(selected2){ case spring: puts("春天女孩\n");break; case autumn: puts("秋天女孩\n");break; case winter: puts("冬天女孩\n");break; case summer: puts("夏天女孩\n");break; } } return 0; }
JavaScript
UTF-8
520
2.6875
3
[ "Apache-2.0" ]
permissive
export function onOriginResponse (request, response) { response.setHeader('Edge-Cache-Tag', getCacheTagsForPath(request.path)); } function getCacheTagsForPath (path) { const cacheTagPrefix = 'path--'; const cacheTagFolderSeparator = '|'; const folderNames = path.split('/'); const cacheTags = []; for (let i = 1; i < folderNames.length; i++) { cacheTags.push(cacheTagPrefix + cacheTagFolderSeparator + folderNames.slice(1, i + 1).join(cacheTagFolderSeparator)); } return '' + cacheTags.join(','); }
Shell
UTF-8
499
3.34375
3
[]
no_license
#!/bin/bash . ~/dotfiles/install-scripts/lib/platform.sh if [[ $platform != "linux" ]]; then if [[ $platform != "arch" ]]; then echo "Backup for Linux only" exit 1 fi fi HOSTNAME=`hostname` echo "MONTHLY BACKUP" function cleanup { sudo umount /backup echo "Unmounted /backup" } trap cleanup EXIT cd ~/dotfiles/cron sudo mount /backup sudo mkdir -p /backup/$HOSTNAME/monthly echo "MONTHLY BACKUP" tar -cvjf /backup/$HOSTNAME/monthly/monthly_$(date +%Y%m%d).tar.bz2 /backup/daily
Markdown
UTF-8
1,295
3.984375
4
[ "MIT" ]
permissive
--- layout: post title: My favorite way of telling if a number is odd or even published: true --- My uncle (a CS guy) once gave me an interesting puzzle: write a function to tell if a number is even or odd without using the modulus operator (e.g. "%"). At that time he had just given me ["Let's Talk Lisp"](https://images-na.ssl-images-amazon.com/images/I/31prZs8fkaL._SY298_BO1,204,203,200_.jpg), a book about the programming language [Lisp](https://en.wikipedia.org/wiki/Lisp_(programming_language)) and about recursive thinking in general. Thus, my answer to his question was this: ```lisp (defun odd (n) (cond ((= n 1) t) ;; if n is 1 (t (even (- n 1))))) ;; otherwise call even(n-1) (defun even (n) (cond ((= n 1) nil) ;; if n is 1, it's NOT even (t (odd (- n 1))))) ;; otherwise call odd(n-1) ``` Or, if TypeScript/JavaScript works better for you: ```typescript function odd(n: number): boolean { if (n == 1) return true; return even(n - 1); } function even(n: number): boolean { if (n == 1) return false; return odd(n - 1); } ``` Try it! If you call `odd(3)` it recursively bounces the function from one to the other and spits out `true`. Same with `even(4)` and `odd(9)` and `even(48938)`. Kinda cool, thanks [Larry](http://larry.denenberg.com).
C
UTF-8
1,033
2.625
3
[ "Apache-2.0" ]
permissive
/* ** EPITECH PROJECT, 2018 ** my_rpg ** File description: ** create_fight_container */ #include "fight.h" chrono_t *create_chrono(void) { chrono_t *ptr = malloc(sizeof(*ptr)); if (!ptr) return (NULL); ptr->clock = sfClock_create(); ptr->my_sec = 0; return (ptr); } bool verify_fight_container(fight_t *ptr) { if (!ptr) return (false); if (!ptr-> particles || !ptr->menus || \ !ptr->background || !ptr->inst || ptr->status < 0 || ptr->status > 2) return (false); return (true); } fight_t *create_fight_container(int status) { fight_t *ptr = malloc(sizeof(*ptr)); if (ptr == NULL) return (NULL); ptr->status = status; ptr->particles = init_particles("./ressource/blood.png", 1150, 240); ptr->menus = prepare_menus(); ptr->select = BASIC; ptr->ennemy = create_ennemy(status); ptr->background = set_background(status); ptr->inst = malloc(sizeof(int) * 2); if (verify_fight_container(ptr) == false) { free_fight_container(ptr); return (NULL); } ptr->inst[0] = 0; ptr->inst[1] = 0; return (ptr); }
Ruby
UTF-8
3,803
2.828125
3
[]
no_license
require 'open3' module ADAdapters module PBIS extend self def get_info(group) LOG.debug "PBIS::get_info: Getting JSON data for group #{group}" str = `/opt/pbis/bin/adtool -a lookup-object --dn="#{group}" --attr=info`.strip LOG.debug "PBIS::get_info: Info attr data returned for group #{group}: #{str}" str end def get_groups(objectName, objectType) LOG.debug "gettings subgroups of #{objectName}, which is of type #{objectType}" computerName = `scutil --get ComputerName`.strip currentUser = `id -un`.strip if objectType == "user" raw_groups = `/opt/pbis/bin/list-groups-for-user #{currentUser}`.strip raw_groups = raw_groups.split("\n") raw_groups.shift # Remove first line: summary output group_names = [] groups = [] raw_groups.each do |group| group_names << /name = ([^\s]*)/.match(group)[1] end group_names.compact! group_names.each do |group| cmd = "/opt/pbis/bin/adtool -a search-group --name '#{group}'" Open3.popen3(cmd) do |stdin, stdout, stderr| err = stderr.read out = stdout.read dn = out.split("\n").first groups << dn.strip unless dn.nil? || dn.empty? end end puts groups.inspect else case objectType when "computer" action = "search-computer" when "group" action = "search-group" else LOG.error "Unknown object type: #{objectName}" exit end groups = nil dn = nil # Why not pipe these two commands together? Great question. # I can't reproduce it in any other environment, but when I pipe these together the second cmd # can't read the keytab, as if it were not being run as root. if currentUser == "root" cmd = "/opt/pbis/bin/adtool -k /etc/krb5.keytab -n '#{computerName.upcase}$' -a #{action} --name '#{objectName}'" else cmd = "/opt/pbis/bin/adtool -a #{action} --name '#{objectName}'" end Open3.popen3(cmd) do |stdin, stdout, stderr| err = stderr.read out = stdout.read dn = out.split("\n").first dn.strip! if dn end unless dn.nil? || dn.empty? if currentUser == "root" cmd = "/opt/pbis/bin/adtool -k /etc/krb5.keytab -n '#{computerName.upcase}$' -a lookup-object --dn='#{dn}' --attr=memberOf'" else cmd = "/opt/pbis/bin/adtool -a lookup-object --dn='#{dn}' --attr=memberOf" end Open3.popen3(cmd) do |stdin, stdout, stderr| err = stderr.read out = stdout.read groups = out end else LOG.warn "Unable to determine DN for object: #{objectName}" return nil end end if groups.nil? || groups.empty? LOG.debug "No more groups for #{objectName}\n\n" return else groups = groups.split("\n") unless groups.is_a? Array # split into an array by line # groups = ADAdapters.extract_cns(groups) LOG.debug "Found #{groups.count} groups: #{groups.inspect}" immu_groups = Array.new groups immu_groups.each do |group| LOG.debug "\nContinuing recursion from #{objectName} with group: #{group}" new_groups = get_groups(group, "group") new_groups.compact.map {|g| groups << g unless groups.include? g } unless new_groups.nil? end LOG.debug "End of recursion for #{objectName}\n\n" end groups end end end
C++
UTF-8
665
2.5625
3
[]
no_license
#pragma once using namespace System; using namespace System::Windows::Forms; using namespace System::Drawing; ref class Mybutton :Button { private: public: Mybutton(int x, int y, String ^name, String ^color); }; Mybutton::Mybutton(int x, int y, String ^name, String ^color) { if (color == "num") this->BackColor = SystemColors::ActiveCaption; else this->BackColor = Color::Silver; this->Font = (gcnew System::Drawing::Font(L"Bahnschrift", 15, FontStyle::Bold, GraphicsUnit::Point, static_cast<System::Byte>(0))); this->Location = Point(x, y); this->Name = name; this->Size = System::Drawing::Size(60, 60); this->Text = name; this->TabIndex = 0; }
JavaScript
UTF-8
208
2.90625
3
[]
no_license
let cambiarbtn=document.getElementById('cambiarbtn'); cambiarbtn.onclick=function () { let titulo=document.getElementById('titulo'); titulo.innerHTML='holaaaaaa'; titulo.style.color='red'; }
Ruby
UTF-8
429
3.6875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) new_array = [] name_hash.each do |key, value| new_array << value if new_array.length == 0 new_array << value if value <= new_array[-1] end low_value = new_array[-1] name_hash.each do |key, value| return key if value == low_value end return nil if name_hash == {} end
JavaScript
UTF-8
2,811
2.609375
3
[]
no_license
#!/usr/bin/env node import * as fs from 'fs'; import * as commander from "commander"; import Forker from './forker'; import Constants from './constants'; let API = require('./api'); let CONFIG_PATH = Constants.CONFIG_PATH; class CLI { private commander: commander.CommanderStatic; private api: any; private config: any; constructor() { this.commander = commander; this.api = new API(); this._setVersion(); this._setOptions(); this._loadConfig(); } public _setVersion() { let pinfo = require('../package.json'); this.commander.version(pinfo.version); } public _setOptions() { this.commander .usage('[options] <uris ...>') .arguments('<uris...>') .action((uris: string) => { this.commander.uris = uris; }) .option('-a, --access-token <token>', 'Spotify Web API access token') .option('-p, --public', 'Create all forks as public') .parse(process.argv) } public _loadConfig() { try { let data = fs.readFileSync(CONFIG_PATH, 'utf8') this.config = JSON.parse(data); } catch (error) { fs.writeFileSync(CONFIG_PATH, ''); this.config = {}; } if(this.commander.accessToken) { this.config.accessToken = this.commander.accessToken; } } public async _validateAPI() { return this.api.getMe(); } public async _loadAPI() { // Verify that the access token that we have works try { this.api.setAccessToken(this.config.access_token); await this._validateAPI(); } // The access token doesn't work, regenerate it. catch(e) { console.log("Missing or invalid access token. Regenerating..."); try { let token = await this.api.generateAccessToken() this.config.access_token = token; } catch(e) { console.error("Could not generate/obtain access token. Exiting..."); throw e; } } // Save config for future use fs.writeFile(CONFIG_PATH, JSON.stringify(this.config), (error?: Error) => { if(error) { console.log("Could not write access token to file") } }) } public async execute() { if(!this.commander.uris) { console.error('Please specify uris as arguments'); return; } try { await this._loadAPI(); } catch(e) { console.error(e.toString()); return; } let forker = new Forker({ visible: this.commander.public, accessToken: this.config.access_token }); console.log("\nForking..."); for (let uri of this.commander.uris) { try { console.log(`\n+ URI: ${uri}`); await forker.fork(uri) console.log(" done!") } catch(err) { console.error(" " + err.toString()) } } } } export default CLI; new CLI().execute();
Markdown
UTF-8
1,043
2.65625
3
[ "MIT", "Apache-2.0" ]
permissive
--- layout: post data: 2018-04-22 title: "gdb反汇编调试" subtitle: "Debugging with GDB disas!" author: "Zxy" tags: - Linux --- **在利用gdb调试的时候,我们发现,有时可以通过查看它的汇编代码进行汇编级别的调试,并通过观察寄存器内值的变化来推测机器内部层次的操作,更好的理解程序在机器内部的运行,这里就给出gdb上查看汇编代码的手段。** `(gdb) disas main`用来查看main函数的汇编代码,这个时候没有加任何的参数,显示出来就是单纯的main函数全部的汇编代码。 `(gdb) disas /m main`依旧用来查看main函数的汇编代码,但是这个时候会将所有的代码也一起映照到上层,推荐这种写法。 通过b设置完断点以后,通过r开始运行,当运行到第一个断点停止的时候,利用`display /i $pc`指令进行设置 `(gdb) si`通过si指令单步跟踪一条机器指令 `(gdb) i r`使用i r指令查看所有寄存器的值 使用x/na %esp查看堆栈的变化。
C
UTF-8
1,837
4.46875
4
[]
no_license
/* * Name : Kuldeep Singh Bhandari * Roll No. : 111601009 * Aim : To search an element in a circular linked * Date : 08-08-2017 */ #include<stdio.h> #include<stdlib.h> //structure to store data, previous pointer and next pointer typedef struct node { int data; struct node *next; struct node *prev; } node; //creating the node node * createNode (int N) { node *head = (node *) malloc(sizeof(node)); int value; printf("Enter data : "); scanf("%d", &value); head->data = value; head->prev = NULL; head->next = NULL; node *t = head; int i; for (i = 1; i < N; i++) { scanf("%d", &value); node *p = (node *) malloc(sizeof(node)); p->data = value; if (i != 1) { p->prev = t; } t->next = p; t = p; } head->prev = t; t->next = head; return head; //returning head pointer } //display the data void display (node *head) { node *p = head; do { printf("Data : %d\n", p->data); p = p->next; } while (p != head); } //checking if the element is there or not in the list int IsElementThere (node *head, int ele) { node *p = head; int success = 0; do { if (p->data == ele) { success = 1; break; } p = p->next; } while (p != head); return success; //return 1 if elements exists, 0 otherwise } int main () { int N; printf("Enter the number of elements : \n"); scanf("%d", &N); node *head = createNode(N); //creating the Node display (head); int searchElement; printf("ENTER THE SEARCH ELEMENT : \n"); scanf("%d", &searchElement); //entering the search Element printf("SEARCHING THE ELEMENT %d IN THE LIST : \n", searchElement); if (IsElementThere (head, searchElement)) { printf("BINGO !! The element %d exists.\n", searchElement); } else { printf("SORRY !! The element %d doesn't exist.\n", searchElement); } return 0; }
Java
UTF-8
2,068
2.109375
2
[]
no_license
package com.android.poinku.viewmodel; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.MutableLiveData; import com.android.poinku.api.response.BaseResponse; import com.android.poinku.api.response.DataPoinResponse; import com.android.poinku.api.response.KriteriaResponse; import com.android.poinku.api.response.KriteriaTugasKhususResponse; import com.android.poinku.api.response.MahasiswaResponse; import com.android.poinku.api.response.NilaiResponse; import com.android.poinku.api.response.TotalPoinResponse; import com.android.poinku.repository.OnlineRepository; public class MainViewModel extends AndroidViewModel { private OnlineRepository onlineRepository; public MainViewModel(@NonNull Application application) { super(application); onlineRepository = new OnlineRepository(); } public MutableLiveData<MahasiswaResponse> getMahasiswa(String nrp) { return onlineRepository.getMahasiswa( nrp ); } public MutableLiveData<TotalPoinResponse> getTotalPoin(String nrp) { return onlineRepository.getTotalPoin( nrp ); } public MutableLiveData<BaseResponse> getIsValidasi(String nrp) { return onlineRepository.getIsValidasi( nrp ); } public MutableLiveData<NilaiResponse> getNilai(String id) { return onlineRepository.getNilai( id ); } public MutableLiveData<KriteriaResponse> getKriteria(String id) { return onlineRepository.getKriteria( id ); } public MutableLiveData<KriteriaTugasKhususResponse> getKriteriaTugasKhusus(String nrp) { return onlineRepository.getKriteriaTugasKhusus( nrp ); } public MutableLiveData<BaseResponse> putPengajuanTugasKhusus(String nrp, String nilai) { return onlineRepository.putPengajuanTugasKhusus( nrp, nilai ); } }
PHP
UTF-8
8,596
3.03125
3
[]
no_license
<?php <<<<<<< HEAD require_once "conexion.php"; class ModeloUsuarios{ ======= namespace Modelos; require_once "conexion.php"; use \Modelos\Conexion; use \Exception, \PDOException; use PDO; use Libs\Helper; class ModeloUsuarios extends Conexion{ >>>>>>> fernando /*============================================= MOSTRAR USUARIOS =============================================*/ static public function mdlMostrarUsuarios($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= REGISTRO DE USUARIO =============================================*/ static public function mdlIngresarUsuario($tabla, $datos){ <<<<<<< HEAD $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(nombre, usuario, password, perfil, foto, correo) VALUES (:nombre, :usuario, :password, :perfil, :foto, :correo)"); ======= $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(nombre, usuario, password, perfil, foto) VALUES (:nombre, :usuario, :password, :perfil, :foto)"); >>>>>>> fernando $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR); $stmt->bindParam(":password", $datos["password"], PDO::PARAM_STR); $stmt->bindParam(":perfil", $datos["perfil"], PDO::PARAM_STR); $stmt->bindParam(":foto", $datos["foto"], PDO::PARAM_STR); <<<<<<< HEAD $stmt->bindParam(":correo", $datos["correo"], PDO::PARAM_STR); ======= >>>>>>> fernando if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= EDITAR USUARIO =============================================*/ static public function mdlEditarUsuario($tabla, $datos){ <<<<<<< HEAD $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, password = :password, perfil = :perfil, foto = :foto, correo = :correo WHERE usuario = :usuario"); ======= $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, password = :password, perfil = :perfil, foto = :foto WHERE usuario = :usuario"); >>>>>>> fernando $stmt -> bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt -> bindParam(":password", $datos["password"], PDO::PARAM_STR); $stmt -> bindParam(":perfil", $datos["perfil"], PDO::PARAM_STR); $stmt -> bindParam(":foto", $datos["foto"], PDO::PARAM_STR); <<<<<<< HEAD $stmt -> bindParam(":correo", $datos["correo"], PDO::PARAM_STR); $stmt -> bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR); ======= $stmt -> bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR); >>>>>>> fernando if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } /*============================================= ACTUALIZAR USUARIO =============================================*/ static public function mdlActualizarUsuario($tabla, $item1, $valor1, $item2, $valor2){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET $item1 = :$item1 WHERE $item2 = :$item2"); $stmt -> bindParam(":".$item1, $valor1, PDO::PARAM_STR); $stmt -> bindParam(":".$item2, $valor2, PDO::PARAM_STR); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } /*============================================= BORRAR USUARIO =============================================*/ static public function mdlBorrarUsuario($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } <<<<<<< HEAD ======= /*============================================= VERIFICACION DE CORREO =============================================*/ static public function getUserWithEmail($p_correo) { $stmt = Conexion::conectar()->prepare("SELECT id, nombre, usuario,correo, password , perfil,foto, estado,ultimo_login, Ordenes, fecha, codigo, fechaRecuperacion FROM usuarios WHERE correo= :p_correo LIMIT 1"); $parameters = array(':p_correo' => $p_correo); try { $query = $stmt; $query->execute($parameters); return ($query->rowcount() ? $query->fetch() : false); } catch (PDOException $e) { $logModel = new Log(); $sql = Helper::debugPDO($stmt, $parameters); $logModel->addLog($sql, 'User', $e->getCode(), $e->getMessage()); return false; } catch (Exception $e) { $logModel = new Log(); $sql = Helper::debugPDO($sql, $parameters); $logModel->addLog($sql, 'User', $e->getCode(), $e->getMessage()); return false; } } /** * Obtener una persona por el código generado para el cambio de contraseña * @param string $p_codigo */ public function getUserWithCode($p_codigo) { $sql = "SELECT id, nombre, usuario,correo, password , perfil,foto, estado,ultimo_login, Ordenes, fecha, codigo, fechaRecuperacion FROM usuario WHERE codigo = :p_codigo LIMIT 1"; $parameters = array(':p_codigo' => $p_codigo); try { $query = $this->db->prepare($sql); $query->execute($parameters); return ($query->rowcount() ? $query->fetch() : false); } catch (PDOException $e) { $logModel = new Log(); $sql = Helper::debugPDO($sql, $parameters); $logModel->addLog($sql, 'User', $e->getCode(), $e->getMessage()); return false; } catch (Exception $e) { $logModel = new Log(); $sql = Helper::debugPDO($sql, $parameters); $logModel->addLog($sql, 'User', $e->getCode(), $e->getMessage()); return false; } } /*============================================= ACTUALIACION DE CODIGO Y FECHA DE RECUPERACION =============================================*/ public function recoverPassword($p_correo, $p_codigo, $p_fechaRecuperacion) { $stmt = Conexion::conectar()->prepare( "UPDATE usuarios SET codigo = :p_codigo, fechaRecuperacion = :p_fechaRecuperacion WHERE correo = :p_correo"); $parameters = array( ':p_correo' => $p_correo, ':p_codigo' => $p_codigo, ':p_fechaRecuperacion' => $p_fechaRecuperacion ); try { $query = $stmt; return $query->execute($parameters); } catch (PDOException $e) { $logModel = new Log(); $sql = Helper::debugPDO($stmt, $parameters); $logModel->addLog($sql, 'User', $e->getCode(), $e->getMessage()); return false; } catch (Exception $e) { $logModel = new Log(); $sql = Helper::debugPDO($sql, $parameters); $logModel->addLog($sql, 'User', $e->getCode(), $e->getMessage()); return false; } } /** * Cambiar la contraseña desde la recuperación de la cuenta * @param string $p_idUsuario Id Usuario * @param string $p_contrasena Contraseña */ public function updatePasswordFromRecover($p_id, $p_password) { $stmt = Conexion::conectar()->prepare("UPDATE usuarios SET password = :p_password, codigo = NULL, fechaRecuperacion = NULL WHERE id = :p_id"); $parameters = array( ':p_password' => $p_password, ':p_id' => $p_id ); try { $query = $stmt; return $query->execute($parameters); } catch (PDOException $e) { $logModel = new Log(); $sql = Helper::debugPDO($stmt, $parameters); $logModel->addLog($sql, 'User', $e->getCode(), $e->getMessage()); return false; } catch (Exception $e) { $logModel = new Log(); $sql = Helper::debugPDO($sql, $parameters); $logModel->addLog($sql, 'User', $e->getCode(), $e->getMessage()); return false; } } >>>>>>> fernando }
Go
UTF-8
1,628
3.3125
3
[ "MIT" ]
permissive
package repository import ( "github.com/jinzhu/gorm" "log" ) type ExchangeRate struct { ID int64 `json:"id"` CurrencyFrom string `json:"currency_from"` CurrencyTo string `json:"currency_to"` } type RateRepositoryItf interface { GetExchangeRateList() ([]ExchangeRate) InsertExchangeRate(*ExchangeRate) error DeleteExchangeRateByID(*ExchangeRate) error GetExchangeRateIDByCurrencyPair(*ExchangeRate) (int64, error) } type RateRepository struct { DB *gorm.DB } func (r RateRepository) GetExchangeRateList() []ExchangeRate { var rateList []ExchangeRate result := r.DB.Find(&rateList) if result.Error != nil { log.Printf("[RateRepository - GetExchangeRateList] : %s", result.Error) return nil } return rateList } func (r RateRepository) InsertExchangeRate(rate *ExchangeRate) error { result := r.DB.Create(rate) if result.Error != nil { log.Printf("[RateRepository - InsertExchangeRate] : %s", result.Error) return result.Error } return nil } func (r RateRepository) DeleteExchangeRateByID(rate *ExchangeRate) error { result := r.DB.Delete(rate) if result.Error != nil { log.Printf("[RateRepository - DeleteExchangeRateByID] : %s", result.Error) return result.Error } return nil } func (r RateRepository) GetExchangeRateIDByCurrencyPair(rate *ExchangeRate) (id int64, err error) { err = r.DB.Raw("SELECT id "+ "FROM exchange_rates "+ "WHERE currency_from = ? AND currency_to = ?", rate.CurrencyFrom, rate.CurrencyTo).Row().Scan(&id) if err != nil { log.Printf("[RateRepository - GetExchangeRateIDByCurrencyPair] : %s", err) return 0, err } return id, nil }
C++
UTF-8
1,067
2.734375
3
[ "MIT" ]
permissive
#ifndef NIL_SRC_META_INC_META_NONESUCH_HPP_ #define NIL_SRC_META_INC_META_NONESUCH_HPP_ #include <type_traits> namespace nil { struct none_such { none_such() = delete; none_such(const none_such&) = delete; none_such(none_such&&) = delete; none_such& operator=(const none_such&) = delete; none_such& operator=(none_such&&) = delete; }; struct MoveOnly { MoveOnly() = default; MoveOnly(const MoveOnly&) = delete; MoveOnly& operator=(const MoveOnly&) = delete; MoveOnly(MoveOnly&&) noexcept = default; MoveOnly& operator=(MoveOnly&&) noexcept = default; }; struct NonDefaultConstructible { NonDefaultConstructible() = delete; NonDefaultConstructible(int ii_) : ii{ii_} {} NonDefaultConstructible(const NonDefaultConstructible&) = default; NonDefaultConstructible& operator=(const NonDefaultConstructible&) = default; NonDefaultConstructible(NonDefaultConstructible&&) = default; NonDefaultConstructible& operator=(NonDefaultConstructible&&) = default; int ii; }; } // namespace nil #endif // NIL_SRC_META_INC_META_NONESUCH_HPP_
C++
UTF-8
694
3.046875
3
[]
no_license
#include <iostream> #include <windows.h> #include "Song.h" using namespace std; void main() { Song s1; Song s2; Song s3("Ne sum siguren", 1,90); Song s4; cout << s3.getName() << " " << s3.getMinutes() << " " << s3.getSeconds() << endl; //expect Ne sum siguren 1 30 cout << (s1 != s2) << endl; // expect 0 s2.setName("Uber guiar solo"); s2.setMinutes(2); s2.setSeconds(-1); cout << s2.getName() << " " << s2.getMinutes() << " "<< s2.getSeconds() << endl; // expect: Uber guitar solo 2 0 cout << (s1 > s2) << endl; // expect 0 s3 = "Smells like teen spirit 04:23"; cout << s3.getName() << " " << s3.getMinutes() << " " << s3.getSeconds() << endl; system("pause"); }
C++
WINDOWS-1252
610
2.859375
3
[]
no_license
/* * @Author: your name * @Date: 2020-04-02 16:56:10 * @LastEditTime: 2020-04-02 19:27:49 * @LastEditors: Please set LastEditors * @Description: Stack * @FilePath: \Stack\Src\main.cpp */ #include <iostream> #include "Stack.h" #include <vector> int main( ){ // std::vector<int> v; // v.push_back( 1 ); // v.push_back( 2 ); // v.push_back( 3 ); // v.pop_back( ); Stack<int> s; s.push( 1 ); s.push( 2 ); s.push( 3 ); s.print( ); s.pop( ); int num = s.top( ); Stack<int> s1( s ); Stack<int> s2; s2 = s1; s2.clear( ); return 0; }
Python
UTF-8
17,139
2.515625
3
[]
no_license
import numpy as np import itertools import DIRECT from scipy.optimize import fsolve, minimize from scipy.stats import norm, lognorm from sympy import * from sklearn.metrics.pairwise import euclidean_distances import copy import os Theta1 = 0.35 #hyperparameter of kernel Theta2 = 0.005 #hyperparameter of kernel N_Iteration = 10 #number of iteration of bending path Gamma = 10 #hyperparameter of optimization Gran = 10 #hyperparameter of optimization class Interactive_BO(): def __init__(self, bound, filepath, mode="linewise", sgm=1, theta_fixed=True): self._theta_fixed = theta_fixed self._bound = np.array(bound) assert len(self._bound.shape) == 2 assert sgm > 0 self._ndim = self._bound.shape[0] self._x = [] #already presented parameters self._u = [] #where is selected parameter in x self._v = [] #where is not selected parameter in x self._sgm = sgm #hyperparameter self._theta = np.ones(self._ndim+2)*Theta1 #hyperparameter self._theta[self._ndim:] = Theta2 #hyperparameter self._kernel = RBF(self._ndim) self._filepath = filepath self._mode = mode def query(self, last_selected=[], N=5): self._x = [] self._u = [] self._v = [] pll = [] qll = [] #get data from a history file if not os.path.exists(self._filepath): print("No history file") if self._mode == "setwise": candidates = self._init_candidates_setwise(N) elif self._mode == "linewise": candidates = self._init_candidates_linewise() elif self._mode == "pathwise": candidates = self._init_candidates_pathwise(N) else: print("mode"+ self._mode +" is not implemented!") raise else: try: with open(self._filepath) as f: lines=f.readlines() for line in lines: line = line.split('>') pl = line[0].split(' ') ql = line[1].split(' ') pl = [np.array([float(i) for i in p.strip('[]').split(',')]) for p in pl] ql = [np.array([float(i) for i in q.strip('[]\n').split(',')]) for q in ql] for p in pl: if self._x == [] or not np.any(np.all(self._x == p,axis=1)): self._x.append(p) for q in ql: if self._x == [] or not np.any(np.all(self._x == q,axis=1)): self._x.append(q) self._x = list(map(np.array, set(map(tuple, self._x)))) pll.append(pl) qll.append(ql) except: print("Invalid history file") raise else: for i in range(len(pll)): pl = pll[i] ql = qll[i] for p in pl: self._u.append(np.where(np.all(self._x==p,axis=1))[0][0]) self._v.append([np.where(np.all(self._x==q,axis=1))[0][0] for q in ql]) self._klu =np.linalg.cholesky(self._kernel(self._x)) self._klu_t =np.linalg.cholesky(self._kernel(self._x).T) #estimate hyperparameter and latent utility function self._kernel._X = self._x self._maximize_posterior() print("self._fMAP",self._fMAP) print("self._theta",self._theta) self._kfmap = np.linalg.solve(self._kernel(self._x),self._fMAP) if self._mode == "setwise": candidates = self._candidates_setwise(N, last_selected) elif self._mode == "linewise": candidates = self._candidates_linewise(last_selected) elif self._mode == "pathwise": candidates = self._candidates_pathwise(N, last_selected) else: print("mode"+ self._mode +" is not implemented!") raise return candidates def _init_candidates_setwise(self, N): candidates = np.array(self._bound[:,0]) + (np.array(self._bound[:,1]) - np.array(self._bound[:,0])) * np.random.rand(N,self._ndim) return candidates def _init_candidates_linewise(self): init_rand = np.array([np.zeros(self._ndim),np.ones(self._ndim)]) init = np.array(self._bound[:,0]) + (np.array(self._bound[:,1]) - np.array(self._bound[:,0])) * init_rand candidates = [init[0],init[1]] return candidates def _init_candidates_pathwise(self, N): init_rand = np.array([np.zeros(self._ndim),np.ones(self._ndim)]) init = np.array(self._bound[:,0]) + (np.array(self._bound[:,1]) - np.array(self._bound[:,0])) * init_rand candidates = np.array([np.linspace(i[0],i[1],N) for i in init.T]).T return candidates def _candidates_setwise(self, N, last_selected): """ Return set of candidates. """ candidates = last_selected x_swap = copy.deepcopy(self._x) f_swap = copy.copy(self._fMAP) for i in range(N-len(last_selected)): self._kfmap = np.linalg.solve(self._kernel(self._x),self._fMAP) self._klu =np.linalg.cholesky(self._kernel(self._x)) self._klu_t =np.linalg.cholesky(self._kernel(self._x).T) x_ie = self._argmax_expected_improvement() + 0.001*np.random.rand() self._fMAP = np.append(self._fMAP,self._mean([x_ie])) self._x.append(x_ie) candidates = np.vstack((candidates,np.array([x_ie]))) self._x = copy.deepcopy(x_swap) self._fMAP = copy.copy(f_swap) self._klu =np.linalg.cholesky(self._kernel(self._x)) self._klu_t =np.linalg.cholesky(self._kernel(self._x).T) self._kfmap = np.linalg.solve(self._kernel(self._x),self._fMAP) return candidates def _candidates_linewise(self, last_selected): x_ei = self._argmax_expected_improvement() """if np.any(np.sum((x_ie-np.array(self._x))**2,axis=1) < 1e-5): raise Exception("Maximum expected improvement is duplicated") """ if last_selected == []: #set one end as last_selected input x_max = self._x[np.argmax(self._fMAP)] else: x_max = last_selected[0] candidates = [x_max,x_ei] return candidates def _candidates_pathwise(self, N, last_selected): def obj_sd(x,data): return (-self._sd([x]),0) if last_selected == []: #set one end as last_selected input x_max = self._x[np.argmax(self._fMAP)] else: x_max = last_selected[0] # use DIRECT algorithm x_argmax_sd, _, _ = DIRECT.solve(obj_sd, self._bound[:,0], self._bound[:,1], maxf=1000, algmethod=1) pivots = np.array([np.linspace(x_max[i],x_argmax_sd[i],N) for i in range(len(x_max))]).T pivots = self._bend(pivots) return list(pivots) def _log_likelihood(self, f=None): if f is None: f = self._fMAP frac = np.exp(f[np.array(self._u)]/self._sgm) denomi = np.zeros(len(self._v)) for i in range(len(self._v)): denomi[i] += np.sum(np.exp(f[np.array(self._v)[i]]/self._sgm)) denomi += np.exp(f[np.array(self._u)]/self._sgm) return np.sum(np.log(frac/denomi)) def _d_log_likelihood(self, f=None): d_ll = np.zeros(len(f)+self._ndim+2) for i, fi in enumerate(f): for j in range(len(self._u)): pat2 = -np.exp(fi/(self._sgm)) / (self._sgm * (np.sum(np.exp(f[np.array(self._v[j])]))+np.exp(f[self._u[j]]))) pat1 = 1 / self._sgm + pat2 if i == self._u[j]: d_ll[i] += pat1 elif np.any(i==np.array(self._v[j])): d_ll[i] += pat2 return d_ll def _log_prior_theta(self, theta): if theta is None: theta = self._theta lnd1 = lognorm.pdf(theta[0:self._ndim],0.1,loc=np.log(0.5)) lnd2 = lognorm.pdf(theta[self._ndim:],0.1,loc=np.log(0.005)) return np.sum(np.log(lnd1)) + np.sum(np.log(lnd2)) def _d_log_prior_theta(self, theta): if theta is None: theta = self._theta d_lpt = np.zeros(len(self._x)+len(theta)) loc = np.append(np.ones(self._ndim)*np.log(0.5),np.ones(2)*np.log(0.005)) d_lpt[len(self._x):] = -1/theta + (-1/theta) * (np.log(theta)-loc)/((0.1)**2) return d_lpt def _log_prior(self, f, theta): if f is None: f = self._fMAP if self._theta_fixed == True: alpha = np.linalg.solve(self._klu,f) return -0.5*np.sum(alpha**2) else: alpha = np.linalg.solve(np.linalg.cholesky(self._kernel(X=self._x,theta=theta)),f) return -0.5*np.sum(alpha**2) + self._log_prior_theta(theta) def _d_log_prior_fix(self, f, theta): alpha = np.linalg.solve(self._klu,f) return -alpha def _d_log_prior(self, f, theta): if f is None: f = self._fMAP d_lp = np.zeros(len(f)+len(theta)) alpha = np.linalg.solve(np.linalg.cholesky(self._kernel(X=self._x,theta=theta)),f) d_lp[0:len(f)] = -alpha for k in range(len(theta)): kernel = self._kernel(X=self._x,theta=theta) if k < self._ndim: d_kernel = np.array([[theta[self._ndim] * np.exp(-np.sum((np.array(i)-np.array(j))**2/(2*theta[0:self._ndim]**2))) * (np.array(i)[k]-np.array(j)[k])**2/(theta[k]**3) for i in self._x] for j in self._x]) elif k == self._ndim: d_kernel = np.array([[np.exp(-np.sum((np.array(i)-np.array(j))**2/(2*theta[0:self._ndim]**2))) for i in self._x] for j in self._x]) else: d_kernel = np.eye(len(f)) d_lp[len(f)+k] = 0.5 * np.matmul(f, np.linalg.solve(kernel, np.matmul(d_kernel, np.linalg.solve(kernel,f))) ) d_lp[len(f)+k] += -0.5 * np.trace(np.matmul(np.linalg.inv(kernel),d_kernel)) if self._theta_fixed == True: return d_lp else: return d_lp + self._d_log_prior_theta(theta) def _unnorm_log_posterior_fix(self, f): if f is None: f = self._fMAP return -self._log_likelihood(f) - self._log_prior(f,self._theta) def _unnorm_log_posterior(self, f, theta): if f is None: f = self._fMAP return -self._log_likelihood(f) - self._log_prior(f,theta) def _d_unnorm_log_posterior_fix(self, f): if f is None: f = self._fMAP return -self._d_log_likelihood(f)[:len(f)] - self._d_log_prior_fix(f,self._theta) def _d_unnorm_log_posterior(self, f, theta): if f is None: f = self._fMAP return -self._d_log_likelihood(f) - self._d_log_prior(f,theta) def _unnorm_log_posterior_sub_fix(self, X=None): return self._unnorm_log_posterior_fix(X[0:len(self._x)]) def _unnorm_log_posterior_sub(self, X=None): return self._unnorm_log_posterior(X[0:len(self._x)],X[len(self._x):]) def _d_unnorm_log_posterior_sub_fix(self, X=None): return self._d_unnorm_log_posterior_fix(X[0:len(self._x)]) def _d_unnorm_log_posterior_sub(self, X=None): return self._d_unnorm_log_posterior(X[0:len(self._x)],X[len(self._x):]) def _argmax_posterior_fix(self): init = np.zeros(len(self._x)) bns = [(-5,5)]*(len(self._x)) self._klu = np.linalg.cholesky(self._kernel(X=self._x,theta=self._theta)) opt = minimize(self._unnorm_log_posterior_sub_fix,init,method='L-BFGS-B', bounds=bns, jac=self._d_unnorm_log_posterior_sub_fix, options={'maxiter':100}) return opt.x def _argmax_posterior(self): init = np.zeros(len(self._x)+self._ndim+2) init[len(self._x):] = np.ones(self._ndim+2)*0.1 bns = [(-5,5)]*(len(self._x)+self._ndim+2) bns[len(self._x):] = [(0.000001,None)]*(self._ndim+2) opt = minimize(self._unnorm_log_posterior_sub,init,method='L-BFGS-B', bounds=bns, jac=self._d_unnorm_log_posterior_sub, options={'maxiter':100}) return opt.x def _maximize_posterior(self): if self._theta_fixed == True: opt = self._argmax_posterior_fix() self._fMAP = opt self._kernel._theta = self._theta else: opt = self._argmax_posterior() #predicted value at observed points self._fMAP = opt[0:len(self._x)] self._theta = opt[len(self._x):] self._kernel._theta = self._theta def _mean(self, x): ks = self._kernel(x,self._x) return np.matmul(ks.T, self._kfmap) def _d_mean(self,x): ks = self._kernel(x,self._x) ks_d = np.array([[[0 if np.all(i==j) else self._theta[self._ndim] * (-(i[k]-j[k])/self._theta[k]**2) * np.exp(-np.sum((np.array(i)-np.array(j))**2/(2*self._theta[0:self._ndim]**2))) for k in range(self._ndim)] for i in x] for j in self._x]) ks_d = ks_d.transpose() return np.matmul(ks_d, self._kfmap).transpose() def _sd(self, x): kss = self._kernel(x,x) ks = self._kernel(x,self._x) sd = np.diag(kss) - np.sum(np.linalg.solve(self._klu,ks)**2,axis=0) return sd def _co_sd(self, x): """ standard co-deviation """ kss = self._kernel(x,x) ks = self._kernel(x,self._x) sol = np.linalg.solve(self._klu,ks) sd = kss - np.matmul(sol.T,sol) return sd def _d_sd(self, x): ks = self._kernel(x,self._x) ks_d = np.array([[[0 if np.all(i==j) else self._theta[self._ndim] * (-(i[k]-j[k])/self._theta[k]**2) * np.exp(-np.sum((np.array(i)-np.array(j))**2/(2*self._theta[0:self._ndim]**2))) for k in range(self._ndim)] for i in x] for j in self._x]) ks_d = ks_d.transpose() sd_d = - np.matmul(ks_d, (np.linalg.solve(self._klu.T,np.linalg.solve(self._klu,ks))+np.linalg.solve(self._klu_t.T,np.linalg.solve(self._klu_t,ks)))).transpose() return sd_d def expected_improvement(self,x): mean_max = np.max(self._fMAP) mean = self._mean(x) sd = self._sd(x) ind = sd > 0 cdf = np.zeros(mean.shape) cdf[ind] = norm.cdf((mean_max-mean[ind])/sd[ind]) x_ei = (mean-mean_max)*cdf+sd*cdf return x_ei def _d_expected_improvement(self,x): mean_max = np.max(self._fMAP) mean = self._mean(x) d_mean = self._d_mean(x) sd = self._sd(x) d_sd = self._d_sd(x) ind = sd > 0 cdf = np.zeros(mean.shape) pdf = np.zeros(mean.shape) cdf[ind] = norm.cdf((mean_max-mean[ind])/sd[ind]) pdf[ind] = norm.pdf((mean_max-mean[ind])/sd[ind]) d_x_ei = d_mean*cdf + (mean-mean_max)*pdf + d_sd*cdf + sd*pdf return d_x_ei def _argmax_expected_improvement(self): def obj(x,data): return (-self.expected_improvement([x]),0) # use DIRECT algorithm x, _, _ = DIRECT.solve(obj, self._bound[:,0], self._bound[:,1], maxf=1000, algmethod=1) return x def _bend(self, pivots): """ bend a path by moving pivots """ for i in range(N_Iteration): for j in range(len(pivots)-2): j = j + 1 F = self._d_expected_improvement([pivots[j]]).reshape(self._ndim) pivots[j] = pivots[j] + Gamma * F d = np.linalg.norm(pivots[j] - pivots[j-1]) if d < 0.01: pivots[j] = pivots[j-1] + 0.01 * (pivots[j] - pivots[j-1]) if d > 0.4: pivots[j] = pivots[j-1] + 0.4 * (pivots[j] - pivots[j-1]) for k in range(self._ndim): if pivots[j][k] < self._bound[k,0]: pivots[j][k] = self._bound[k,0] if pivots[j][k] > self._bound[k,1]: pivots[j][k] = self._bound[k,1] return pivots class RBF(): """ ARD squered exponential kernel """ def __init__(self, dim, X=None, Y=None, theta=None): self._ndim = dim if X is None: self._X = None else: self._X = np.array(X) if Y is None: self._Y = None else: self._Y = np.array(Y) if theta is None: self._theta = np.ones(self._ndim+2) * 0.1 else: self._theta = theta def __call__(self, X=None, Y=None, theta=None): if X is None and Y is None and theta is None: return self._K if X is None: X = self._X if Y is None: Y = self._Y if Y is None: Y = X if theta is None: theta = self._theta self._ssd = np.array([[theta[self._ndim] + theta[self._ndim+1] if np.all(i==j) else theta[self._ndim] * np.exp(-np.sum((np.array(i)-np.array(j))**2/(2*theta[0:self._ndim]**2))) for i in X] for j in Y]) return self._ssd
Swift
UTF-8
3,475
2.78125
3
[]
no_license
// // PostPinViewController.swift // On The Map // // Created by Jason Yu on 6/15/20. // Copyright © 2020 Jason Yu. All rights reserved. // import UIKit import MapKit class PostPinViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var locationManger: CLLocationManager? var firstName: String? var lastName: String? var mediaUrl: String? var location: String? var lat: Double? var long: Double? @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // activityIndicator.hidesWhenStopped = true activityIndicator.startAnimating() // Do any additional setup after loading the view. print("POSTPIN: \(String(describing: lat))") zoomToLatestLocation() } @IBAction func finishTapped(_ sender: Any) { guard let firstName = firstName, let lastName = lastName, let mediaUrl = mediaUrl, let location = location, let lat = lat, let long = long else { let alert = UIAlertController(title: "Error getting User Data", message: "", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) return } UserAPI.shared.postUserRequest(firstName: firstName, lastName: lastName, mediaUrl: mediaUrl, location: location, lat: lat, long: long) { result in switch result { case .success(_): print("Success POSTING::") DispatchQueue.main.async { if let nav = self.navigationController { nav.popViewController(animated: false) nav.popViewController(animated: true) } else { self.dismiss(animated: true, completion: nil) } } case .failure(let error): print("Failure POSTING:: \(error)") DispatchQueue.main.async { let alert = UIAlertController(title: "Failed Post - Please try again", message: "\(error)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) } } } } func zoomToLatestLocation() { guard let lat = lat, let long = long, let firstName = firstName, let lastName = lastName, let mediaUrl = mediaUrl else { return } let postLocation = CLLocation(latitude: lat, longitude: long) let regionRadius: CLLocationDistance = 2000000.0 let region = MKCoordinateRegion(center: postLocation.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius) mapView.setRegion(region, animated: true) addAnnotations(title: "\(String(describing: firstName)) \(String(describing: lastName))", subTitle: "\(String(describing: mediaUrl))", coordinate: CLLocationCoordinate2DMake(lat, long)) mapView.delegate = self activityIndicator.stopAnimating() } func addAnnotations(title: String, subTitle: String, coordinate: CLLocationCoordinate2D) { let userAnnotation = UserMarker(title: title, subtitle: subTitle, coordinate: coordinate) mapView.addAnnotation(userAnnotation) } }
Python
UTF-8
1,237
2.5625
3
[ "MIT" ]
permissive
#!/usr/bin/env python import pickle import sys import getopt import numpy as np def main(argv, N_POINTS=100): # parsing parameters def usage(): print(""" usage: -h: help -n(--n_points): number of real space grid -f: input files, seperated by ':' """) return 100 try: opt_vals, _ = getopt.getopt(argv, 'hn:f:', ['help', 'file=', 'n_points=']) except getopt.GetoptError as err: print(err) return usage() for (opt, vals) in opt_vals: if opt in ['-h', '--help']: return usage() elif opt in ['-f', '--file']: file_list = vals.split(':') elif opt in ['-n', '--n_points']: N_POINTS = int(vals) # read and transform files for fname in file_list: with open(fname, 'rb') as f: data = pickle.load(f) scaler, vec_q = data[:, 0].real, data[:, 1:] vec_x = np.fft.irfft(vec_q, axis=1, n=N_POINTS)*N_POINTS vec_x = vec_x.real data_t = np.c_[scaler.reshape((-1, 1)), vec_x] with open('_'.join([fname, '2x']), 'wb') as f2: pickle.dump(file=f2, obj=data_t) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
Shell
UTF-8
1,687
3.375
3
[]
no_license
#!/bin/bash # Copyright (C) 2014 Julien Bonjean <julien@bonjean.info> # Copyright (C) 2014 Alexander Keller <github@nycroth.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # The first parameter sets the step to change the volume by (and units to display) # This may be in in % or dB (eg. 5% or 3dB) STEP="${1:-5%}" # http://unix.stackexchange.com/a/251920/41707 getdefaultsinkname() { pacmd stat | awk -F": " '/^Default sink name: /{print $2}' } volume() { pacmd list-sinks | awk '/^\s+name: /{indefault = $2 == "<'$(getdefaultsinkname)'>"} /^\s+volume: / && indefault {print $5; exit}' } ismuted() { pacmd list-sinks | awk '/^\s+name: /{indefault = $2 == "<'$(getdefaultsinkname)'>"} /^\s+muted: / && indefault {print $2; exit}' } case $BLOCK_BUTTON in 3) pactl set-sink-mute $(getdefaultsinkname) toggle ;; # right click, mute/unmute 4) pactl set-sink-volume $(getdefaultsinkname) +${STEP} ;; # scroll up, increase 5) pactl set-sink-volume $(getdefaultsinkname) -${STEP} ;; # scroll down, decrease esac #volume ismuted | grep "yes" > /dev/null && echo "Muted" || volume
Java
UTF-8
777
2.578125
3
[]
no_license
/** * Gets article count of the specified day. * @param day the specified day * @return article count */ public int getArticleCntInDay(final Date day){ final long time=day.getTime(); final long start=Times.getDayStartTime(time); final long end=Times.getDayEndTime(time); final Query query=new Query().setFilter(CompositeFilterOperator.and(new PropertyFilter(Keys.OBJECT_ID,FilterOperator.GREATER_THAN_OR_EQUAL,start),new PropertyFilter(Keys.OBJECT_ID,FilterOperator.LESS_THAN,end),new PropertyFilter(Article.ARTICLE_STATUS,FilterOperator.NOT_EQUAL,Article.ARTICLE_STATUS_C_INVALID))); try { return (int)articleRepository.count(query); } catch ( final RepositoryException e) { LOGGER.log(Level.ERROR,"Count day article failed",e); return 1; } }
Go
UTF-8
1,157
2.65625
3
[]
no_license
package cli import ( "fmt" "os" "github.com/bernos/ecso/pkg/ecso" "github.com/bernos/ecso/pkg/ecso/dispatcher" "gopkg.in/urfave/cli.v1" ) func NewEnvironmentCliCommand(project *ecso.Project, dispatcher dispatcher.Dispatcher) cli.Command { return cli.Command{ Name: "environment", Usage: "Manage ecso environments", Subcommands: []cli.Command{ NewEnvironmentAddCliCommand(project, dispatcher), NewEnvironmentPsCliCommand(project, dispatcher), NewEnvironmentUpCliCommand(project, dispatcher), NewEnvironmentRmCliCommand(project, dispatcher), NewEnvironmentDescribeCliCommand(project, dispatcher), NewEnvironmentDownCliCommand(project, dispatcher), }, } } func makeEnvironmentCommand(c *cli.Context, project *ecso.Project, fn func(*ecso.Environment) ecso.Command) (ecso.Command, error) { name := c.Args().First() if name == "" { name = os.Getenv("ECSO_ENVIRONMENT") } if name == "" { return nil, ecso.NewArgumentRequiredError("environment") } if !project.HasEnvironment(name) { return nil, fmt.Errorf("Environment '%s' does not exist in the project", name) } return fn(project.Environments[name]), nil }
Markdown
UTF-8
1,047
2.8125
3
[ "MIT" ]
permissive
# 스크립트 간 참조 [전역 변수](/AdvancedFunctions/Global_Static_Variables/)나 [사용자 정의 함수](/AdvancedFunctions/Custom_Functions/)를 가지는 모든 스크립트는 스크립트 간 참조 목록에 등록됩니다.</2> dot-notaion을 사용하여 이 필드나 함수를 액세스 할수 있습니다. ## 설명 - 스크립트 간 참조는 `scripts` 경로서부터 시작됩니다. - `scripts.mySubfolder.a.zs`와 같이 스크립트 디렉토리를 기준으로 경로를 지칭할 수 있습니다. - [import 선언](/AdvancedFunctions/Import/)과 같은 표기법을 사용하여 참조할 스크립트를 고를 수 있습니다. - ZenScript에서 먼저 매칭되는 디렉토리를 먼저 확인한 후 파일이나 값을 확인합니다. ## 예제 `a.zs`와 `b.zs` 두 스크립트 파일이 있다고 가정해봅시다. a.zs: ```zenscript static myVal as string = "myVal"; function makeLine() { print("---------------"); } ``` b.zs ```zenscript print(scripts.a.myVal); scripts.a.makeLine(); ```
Java
UTF-8
818
2.71875
3
[]
no_license
package commands.authenicationCommands.login; import commands.authenicationCommands.AuthenticationCommand; /** * The type Login command. */ public class LoginCommand extends AuthenticationCommand { private final String username; private final String password; /** * Instantiates a new Login command. * * @param username the email * @param password the password */ public LoginCommand(String username, String password) { this.username = username; this.password = password; } /** * Gets email. * * @return the email */ public String getUsername() { return username; } /** * Gets password. * * @return the password */ public String getPassword() { return password; } }
Markdown
UTF-8
1,473
3.109375
3
[]
no_license
# twiggyrj-kshatriya-jquery-slider This is a basic carousel slider that was built in a day as a learning exercise to get better at JavaScript, jQuery and learn a bit of ES6. This slider takes the following items when initialised: | Option | Expected Value | What it is used for | Does it a default fallback | | ------ | -------------- | ------------------- | -------------------------- | | el | Carousel as an jQuery Object | Used to select the carousel item | No, this needs to be filled | | sliderTrack | Carousel slider track as an jQuery Object | Used to select the carousel track | No, this needs to be filled | | next | The element that will act as the next button | Will have an event bound to it | No, this needs to be filled | | prev | The element that will act as the back button | Will have an event bound to it | No, this needs to be filledE | | autoplay | Boolean TRUE/FALSE | Will decide if the carousel should autoplay | This set to FALSE if it is empty | | autoplayCancel | Boolean TRUE/FALSE | Will decide if autoplay should stop once the controls have been interacted with | This set to TRUE if it is empty | | autoplaySpeed | Time in MS e.g. 350ms is 0.35s | Will set how long a slide will show for before the carousel autoplays | This is set to 3000 if it is empty | | speed | Time in MS e.g. 750ms is 0.75s | Will set the transition speed between each slide | This is set to 350 if it is empty | This carousel includes a basic example in index.html
JavaScript
UTF-8
1,030
4.40625
4
[]
no_license
/* // Create datatypes.js file and use the JavaScript typeof operator to // check different data types. Check the data type of each variable */ let alineName = 'Aline' let strong = true let undefinedVar let nullVar = null // Declare four variables without assigning values let var1 let var2 let var3 let var4 // Declare four variables with assigned values let var5 = 5 let var6 = 6 let var7 = 7 let var8 = 8 // Declare variables to store your first name, last name, marital status, country and age in multiple lines let firstName = 'Aline' let lastName = 'Fukuhara' let maritalStatus = 'Single' let country = 'Brazil' let age = 28 // Declare variables to store your first name, last name, marital status, country and age in a single line let firstName1 = 'Aline', lastName1 = 'Fukuhara', maritalStatus1 = 'Single', country1 = 'Brazil', age1 = 28 // Declare two variables myAge and yourAge and assign them initial values and log to the browser console. let myAge = 28 let yourAge = 30 console.log(myAge, yourAge)
C
UTF-8
2,456
2.71875
3
[]
no_license
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_6__ TYPE_2__ ; typedef struct TYPE_5__ TYPE_1__ ; /* Type definitions */ struct TYPE_5__ {int /*<<< orphan*/ * uuid128; int /*<<< orphan*/ uuid32; int /*<<< orphan*/ uuid16; } ; struct TYPE_6__ {scalar_t__ len; TYPE_1__ uu; } ; typedef TYPE_2__ tBT_UUID ; typedef int /*<<< orphan*/ UINT8 ; typedef int BOOLEAN ; /* Variables and functions */ int LEN_UUID_128 ; scalar_t__ LEN_UUID_16 ; scalar_t__ LEN_UUID_32 ; int TRUE ; int /*<<< orphan*/ gatt_convert_uuid16_to_uuid128 (int /*<<< orphan*/ *,int /*<<< orphan*/ ) ; int /*<<< orphan*/ gatt_convert_uuid32_to_uuid128 (int /*<<< orphan*/ *,int /*<<< orphan*/ ) ; scalar_t__ memcmp (int /*<<< orphan*/ *,int /*<<< orphan*/ *,int) ; BOOLEAN gatt_uuid_compare (tBT_UUID src, tBT_UUID tar) { UINT8 su[LEN_UUID_128], tu[LEN_UUID_128]; UINT8 *ps, *pt; /* any of the UUID is unspecified */ if (src.len == 0 || tar.len == 0) { return TRUE; } /* If both are 16-bit, we can do a simple compare */ if (src.len == LEN_UUID_16 && tar.len == LEN_UUID_16) { return src.uu.uuid16 == tar.uu.uuid16; } /* If both are 32-bit, we can do a simple compare */ if (src.len == LEN_UUID_32 && tar.len == LEN_UUID_32) { return src.uu.uuid32 == tar.uu.uuid32; } /* One or both of the UUIDs is 128-bit */ if (src.len == LEN_UUID_16) { /* convert a 16 bits UUID to 128 bits value */ gatt_convert_uuid16_to_uuid128(su, src.uu.uuid16); ps = su; } else if (src.len == LEN_UUID_32) { gatt_convert_uuid32_to_uuid128(su, src.uu.uuid32); ps = su; } else { ps = src.uu.uuid128; } if (tar.len == LEN_UUID_16) { /* convert a 16 bits UUID to 128 bits value */ gatt_convert_uuid16_to_uuid128(tu, tar.uu.uuid16); pt = tu; } else if (tar.len == LEN_UUID_32) { /* convert a 32 bits UUID to 128 bits value */ gatt_convert_uuid32_to_uuid128(tu, tar.uu.uuid32); pt = tu; } else { pt = tar.uu.uuid128; } return (memcmp(ps, pt, LEN_UUID_128) == 0); }
Java
UTF-8
4,563
2.203125
2
[]
no_license
package cn.onlineexam.exam.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.itcast.servlet.BaseServlet; import cn.onlineexam.manager.domain.Json; import cn.onlineexam.question.domain.Cloze; import cn.onlineexam.question.domain.Judge; import cn.onlineexam.question.domain.Program; import cn.onlineexam.question.domain.QuestionSelect; import cn.onlineexam.student.domain.Student; import cn.onlineexam.exam.domain.Score; import cn.onlineexam.exam.service.ExamService; @SuppressWarnings("serial") public class ExamServlet extends BaseServlet { ExamService examService=new ExamService(); public String selectExam(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { String selectString=examService.getSelect(); List<QuestionSelect> questionSelects=examService.selectExam(selectString); String judgeString=examService.getJudge(); List<Judge> judges=examService.judgeExam(judgeString); String clozeString=examService.getCloze(); List<Cloze> clozes=examService.clozeExam(clozeString); String programString=examService.getProgram(); List<Program> programs=examService.programExam(programString); request.setAttribute("selectList",questionSelects); request.setAttribute("judgeList", judges); request.setAttribute("clozeList", clozes); request.setAttribute("programList", programs); return "f:/examCenter.jsp"; } public void count(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { List<String> selects=new ArrayList<String>(); List<String> judges=new ArrayList<String>(); List<String> clozes=new ArrayList<String>(); for(int i=1;i<=10;i++){ String selectOption=request.getParameter("selectOption"+i); if(selectOption==null){ selects.add("no answer"); }else{ selects.add(selectOption); } String judgeOption=request.getParameter("judgeOption"+i); if(judgeOption==null){ judges.add("no answer"); }else{ judges.add(judgeOption); } String cloze=request.getParameter("cloze"+i); if(cloze==null){ clozes.add("no answer"); }else{ clozes.add(cloze); } } String programString=examService.getProgram(); List<Program> programs=examService.programExam(programString); String question=programs.get(0).getQuestion(); String program=""; program=request.getParameter("program1"); if(program==null||program.trim().isEmpty()){ program="no answer"; } //System.out.println(program); HttpSession session=request.getSession(); Student student=(Student) session.getAttribute("sessionStudent"); if(student==null){ //response.sendRedirect("/online/loginStudent.jsp"); /*RequestDispatcher rd = request.getRequestDispatcher("/loginStudent.jsp"); rd.forward(request, response);*/ Json json=new Json(); String msg="你还没有登录,请重新登录!!!"; json.setSuccess(false); json.setMsg(msg); response.getWriter().print(json); response.getWriter().close(); }else{ String loginname=student.getLoginname(); examService.addProgramSubmit(loginname,question,program); String selectString=examService.getSelect(); String judgeString=examService.getJudge(); String clozeString=examService.getCloze(); int selectCount=examService.selectCount(selects,selectString); int judgeCount=examService.judgeCount(judges,judgeString); int clozeCount=examService.clozeCount(clozes,clozeString); int score=selectCount+judgeCount+clozeCount; examService.addScore(loginname,score,selectCount,judgeCount,clozeCount); double selectPercent=selectCount/10.0; double judgePercent=judgeCount/10.0; double clozePercent=clozeCount/8.0; String msg="你的客观题分数是"+score+" "+"选择题正确率:"+selectPercent+" "+"判断题正确率:"+judgePercent+" " +"填空题正确率:"+clozePercent+" "+"程序题分数待老师查阅!!"; //System.out.println(msg); Score scoreNew=examService.findStudent(loginname); HttpSession sessionNew = request.getSession(); sessionNew.setAttribute("sessionScore",scoreNew); Json json=new Json(); json.setSuccess(true); json.setMsg(msg); response.getWriter().print(json); response.getWriter().close(); } } }
JavaScript
UTF-8
1,188
2.953125
3
[]
no_license
import { ratingsTemplate } from "./templates"; const ratings = [ { stars: 1, people: 20 }, { stars: 2, people: 25 }, { stars: 3, people: 66 }, { stars: 4, people: 52 }, { stars: 5, people: 93 } ]; let prevIdx; function allPeople(arr) { return arr.map(item => item.people).reduce((accumulator, currentValue) => accumulator + currentValue); } export function renderRatingsList() { removeRatingList(); const idx = document.querySelectorAll('.rating__star-item--clicked').length; if ((idx > 0) && (idx !== prevIdx)) { if (prevIdx) ratings[prevIdx - 1].people = ratings[prevIdx - 1].people - 1; prevIdx = idx; ratings[idx - 1].people = ratings[idx - 1].people + 1; document.querySelector('.rating').insertAdjacentHTML('beforeend', ratingsTemplate(ratings, allPeople(ratings))); document.querySelector('.remove-btn').addEventListener('click', removeRatingList); } }; function removeRatingList() { if (document.querySelector('.rating__list')) { document.querySelector('.rating__list').remove(); document.querySelector('.remove-btn').removeEventListener('click', removeRatingList); document.querySelector('.remove-btn').remove(); } };
Python
UTF-8
75
3.734375
4
[]
no_license
n=int(input("enter a number:")) for i in range(2,n): if n%i==0: print(i)
Python
UTF-8
2,786
3.03125
3
[]
no_license
import numpy as np class LMKNN: def __init__(self, k): self.__dataTrain = {} self.__predict = {} self.__k = k @property def dataTrain(self): return self.__dataTrain @property def predict(self): return self.__predict @property def k(self): return self.__k @dataTrain.setter def dataTrain(self, input): self.__dataTrain = input @predict.setter def predict(self, input): self.__predict = input @k.setter def k(self, input): self.__k = input def euclidean(self, features, predict): return np.linalg.norm(np.array(features)-np.array(predict)) def calc_distances_data(self, dataTrain, predict): distancesDict = {} for group in dataTrain: distancesList = [] for index in range(len(dataTrain[group])): features = dataTrain[group][index] euclideanDistance = self.euclidean(features, predict) distancesList.append([euclideanDistance, index]) distancesDict[group] = distancesList return distancesDict def calc_local_mean(self, distancesData, dataTrain, k): local_mean = {} for x in distancesData: prev = 0 for y in sorted(distancesData[x])[:k]: for label, features in dataTrain.items(): if x == label: summation = np.add(np.array(features[y[1]]), prev) prev = summation result = np.true_divide(summation, k) local_mean[x] = list(result) summation = 0 return local_mean def calc_closestDist_localMean(self, localMean, predict): closestDist = [] for label in localMean: localMeanVector = localMean[label] euclideanDistance = self.euclidean(localMeanVector, predict) closestDist.append((euclideanDistance, label)) minimum = np.argmin(closestDist, axis=0) result = closestDist[minimum[0]][1] return result def local_mean_based_knn(self, dataTrain, predict, k): distancesData = self.calc_distances_data(dataTrain, predict) localMean = self.calc_local_mean(distancesData, dataTrain, k) lmknn = self.calc_closestDist_localMean(localMean, predict) return lmknn def pred(self, trainSet, testSet, k): correct = 0 total = 0 for label in testSet: for testData in testSet[label]: result = self.local_mean_based_knn(trainSet, testData, k) if label == result: correct += 1 total += 1 return float(correct / total)
Python
UTF-8
219
2.625
3
[]
no_license
n=int(input()) if n<1000: print(1000-n) else: str1="" k=n//1000 l=len(str(n))-len(str(k)) str1=str(k)+'0'*l if str1==str(n): print(0) else: p=int(str1)+1000 print(p-n)
Java
UTF-8
667
2.15625
2
[]
no_license
package com.psl.test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.psl.business.StudentBo; import com.psl.model.Student; public class Client { public static void main(String[] args) { ConfigurableApplicationContext ap = new ClassPathXmlApplicationContext("com/psl/resources/test.xml"); StudentBo sbo = (StudentBo)ap.getBean("bo"); try { int i = sbo.createStudent(new Student(101, "aaa", "aas@gmail.com", "knp")); System.out.println(i); ap.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Java
UTF-8
1,787
2.875
3
[]
no_license
package mc; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; public class ChanceCardSewagePlant extends ChanceCard { GameMaster gameMaster; GamePane gamePane; Player currentPlayer; JButton sewagePlantButton; private boolean failed; public ChanceCardSewagePlant(){ failed = false; } public void performCard(){ gameMaster = GameMaster.getInstance(); gamePane = GamePane.getInstance(); sewagePlantButton = new JButton("Build Sewage Plant"); sewagePlantButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ sewagePlantButtonPerformed(); } }); gamePane.clearSelectedDistrict(); gamePane.setMessagePanelText("You drew the Sewage Plant Card! Select " + "a District to build a Sewage Plant on!"); if(failed)gamePane.addMessagePanelText("District cannot have a Bonus on it!"); gamePane.addMessagePanelButton(sewagePlantButton); } protected void sewagePlantButtonPerformed() { int selectedDistrictIndex = gamePane.getSelectedDistrict(); Board board = gameMaster.getBoard(); if(selectedDistrictIndex != -1){ Square selectedSquare = board.getSquare(selectedDistrictIndex); District district; if(selectedSquare.getType() == SQUARETYPE.DISTRICT){ district = (District)selectedSquare; if(district.bonus == null){ gamePane.clearSelectedDistrict(); district.hazard = STRUCTURE.SEWAGEPLANT; gamePane.setMessagePanelText(district.getName() +" now has a Sewage Plant!"); failed = false; GameMaster.getInstance().setPerformed(true); sewagePlantButton.setVisible(false); gamePane.update(); }else{ failed = true; performCard(); }} } else{ failed = true; performCard(); } } }
JavaScript
UTF-8
1,700
2.515625
3
[]
no_license
/** @jsx jsx */ import React, { useState } from 'react'; import { css, jsx } from '@emotion/core' import ProjectsContent from './ProjectsContent'; import ProjectSlide from './ProjectSlide'; import Arrow from "./Arrow" import Dots from './Dots' /** * @function Projects */ const Projects = props => { const getWidth = () => window.innerWidth console.log(getWidth()) const [state, setState] = useState({ activeIndex: 0, translate: 0, transition: 0.45 }) const { translate, transition, activeIndex } = state const nextSlide = () => { if (activeIndex === props.slides.length - 1) { return setState({ ...state, translate: 0, activeIndex: 0 }) } setState({ ...state, activeIndex: activeIndex + 1, translate: (activeIndex + 1) * getWidth() }) } const prevSlide = () => { if (activeIndex === 0) { return setState({ ...state, translate: (props.slides.length - 1) * getWidth(), activeIndex: props.slides.length - 1 }) } setState({ ...state, activeIndex: activeIndex - 1, translate: (activeIndex - 1) * getWidth() }) } return ( <div css={SliderCSS}> <ProjectsContent translate={translate} transition={transition} width={getWidth() * props.slides.length} > {props.slides.map((slide, i) => ( <ProjectSlide key={slide + i} content={slide} /> ))} </ProjectsContent> <Arrow direction="left" handleClick={prevSlide} /> <Arrow direction="right" handleClick={nextSlide} /> <Dots slides={props.slides} activeIndex={activeIndex} /> </div> ) } const SliderCSS = css` position: relative; height: 60vh; width: 80vw; margin: 0 auto; overflow: hidden; ` export default Projects
Markdown
UTF-8
3,759
3.71875
4
[]
no_license
#####1、双花括号 语法: <any>{{表达式}}</any> 作用: 将表达式执行的结果 输出当调用元素的innerHTML中;还可以将数据绑定到视图 #####2、指令-循环指令 基本语法1: <any v-for="tmp in array"></any> 基本语法2: <any :key='value.id' v-for="(value,index) in array"></any> 作用: 在遍历array这个集合时,将临时变量保存在tmp中,创建多个any标签 v-show:控制元素显示隐藏 v-if:新增或删除节点 #####3、指令-选择指令 语法: <any v-if="表达式"></any> <any v-else-if="表达式"></any> <any v-else="表达式"></any> 作用: 根据表达式执行结果的真假,来决定是否要将当前的这个元素 挂载到DOM树 #####4、指令-事件绑定 语法: <any v-on:click="handleEvent"></any> <any @click="handleEvent(arg1,arg2)"></any> 作用: 给指定的元素 将handleEvent的方法绑定给指定click事件 1.事件修饰符 .stop阻止冒泡 <a v-on:click.stop="handle">跳转</a> .prevent阻止默认行为 <a v-on:click.prevent="handle">跳转</a> @click.self:只处理自己本身的事件,不处理孩子冒泡上来触发的事件 @click.once:只触发一次 2.按键修饰符 .enter回车键 <input v-on:keyup.enter='submit'> .delete删除键 <input v-on:keyup.delete='handle'> @input="handleInput" 文本框内容改变时触发 @change="handleInput" 文本框改变并失去焦点时触发 3.表单域修饰符 number:转化为数值 trim:去掉开始和结尾的空格 lazy:将input事件切换为change事件 <input v-model.number="age" type="number"> #####5、指令-属性绑定 基本语法: <any v-bind:myProp="表达式"></any> 补充,支持简写: <any :myProp="表达式"></any> 作用: 将表达式执行的结果 绑定 到当前元素的myProp属性 <img v-bind:src="'img/'+myImg" alt=""> 动态样式绑定 <p :style="{backgroundColor:myBGColor}">动态样式绑定</p> class样式动态绑定 <div v-bind:class="{isActive? "red":"yellow"}"></div> <h1 :class="{myRed:true,myBule:true}">动态样式类的绑定</h1> <div v-bind:class="[active1,active2]"></div> style样式动态绑定(和class差不多) <div v-bind:style="{color:#fff}"></div> <h1 :class="{myRed:false}">动态样式类的绑定</h1> <div v-bind:style="[baseStyle1,style2]"></div> 绑定单选和多选: <input type="checkbox" v-model="isChecked"/> <input type="checkbox" v-model="checkgroup" value="长跑"/> <input type="checkbox" v-model="checkgroup" value="游泳"/> {{checkgroup}} new Vue({ el:"#box" data:{ isChecked:true, checkgroup:[], } }) 文本: <input type="text" v-mode.lazy="mytext"/> <input type="text" v-mode.number="mytext"/> <input type="text" v-mode.trim="mytext"/> v-mode.lazy:懒双向绑定,回车之后再绑定 v-mode.number:输入内容为数字 v-mode.trim:去掉输入字符两端空格 #####6.数据绑定指令 v-text填充纯文本(比插值表达式简洁) v-html填充HTML片段(存在安全问题,本网站内部数据可以使用,来自第三方数据不可以用) v-pre填充原始信息 v-once显示的内容后续不再修改 #####7、指令-双向数据绑定 方向1:数据绑定到视图 方向2:将视图中(表单元素)用户操作的结果绑定到数据 基本语法: <表单元素 v-model="变量"> </表单元素>
JavaScript
UTF-8
1,766
2.984375
3
[]
no_license
const chai = require('chai'); const expect = chai.expect; const Turn = require('../src/Turn') const Card = require('../src/Card'); describe('Turn', function() { it('should be a function', function() { const turn = new Turn(); expect(Turn).to.be.a('function'); }); it('Turn should be instantiated with a Guess and a Card', function() { const turn = new Turn(); expect(turn).to.be.an.instanceof(Turn); }); it('should be a function with a guess and a Card', function() { const turn = new Turn(); const card = new Card(); }); it('should return the players guess', function() { const card = new Card(1, "What allows you to define a set of related information using key-value pairs?", ["object", "array", "function"], "object") const turn = new Turn('array', card); expect(turn.returnGuess()).to.equal('array'); }); it('should return the card', function() { const card = new Card(1, "What allows you to define a set of related information using key-value pairs?", ["object", "array", "function"], "object") const turn = new Turn('array', card); expect(turn.returnCard()).to.equal(card); }); it('should evaluate the guess', function() { const card = new Card(1, "What allows you to define a set of related information using key-value pairs?", ["object", "array", "function"], "object") const turn = new Turn('array', card); expect(turn.evaluateGuess()).to.equal(false); }); it('should give feedback', function() { const card = new Card(1, "What allows you to define a set of related information using key-value pairs?", ["object", "array", "function"], "object") const turn = new Turn('array', card); expect(turn.giveFeedback()).to.equal('❌ Incorrect') }); });
Java
UTF-8
1,385
2.125
2
[ "MIT" ]
permissive
package de.tudresden.inf.st.mquat.solving; import de.tudresden.inf.st.mquat.generator.ScenarioDescription; import de.tudresden.inf.st.mquat.generator.ScenarioGenerator; import de.tudresden.inf.st.mquat.jastadd.model.Root; import de.tudresden.inf.st.mquat.jastadd.model.Solution; import de.tudresden.inf.st.mquat.solving.ilp.ILPExternalSolver; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class ILPObjectiveTest { private static Logger logger; @BeforeClass public static void initLogger() { logger = LogManager.getLogger(ILPObjectiveTest.class); } @Test public void test_config_01() throws SolvingException { int tlc = 1; int iac = 1; int isd = 0; int cac = 0; int csd = 0; int dep = 2; int imp = 2; int res = 10; int req = 1; int cpu = 1; int seed = 0; ScenarioGenerator generator = new ScenarioGenerator(new ScenarioDescription(tlc, iac, isd, cac, csd, dep, imp, res, req, cpu, seed)); Root model = generator.generate(); ILPExternalSolver solver = new ILPExternalSolver().setDeleteFilesOnExit(false); Solution solution = solver.solve(model); Assert.assertTrue(solution.isValid()); logger.info("Solution (objective={}): {}", solution.computeObjective(), solution); } }
PHP
UTF-8
724
2.765625
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { /** * Atributos asignables en masa. */ protected $fillable = [ 'name', 'email', 'password', 'type', ]; /** * Atributos que deben ocultarse para las matrices. */ protected $hidden = [ 'password', 'remember_token', ]; public static function checkEmail($email){ $userList = User::all(); $found = false; foreach ($userList as $u): if ($u->email == $email): $found = true; endif; endforeach; return $found; } }
C++
UTF-8
1,259
2.625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <limits.h> int main() { char mappings[26]; mappings[0] = 'y'; // a mappings[1] = 'h'; // b mappings[2] = 'e'; // c mappings[3] = 's'; // d mappings[4] = 'o'; mappings[5] = 'c'; mappings[6] = 'v'; mappings[7] = 'x'; mappings[8] = 'd'; mappings[9] = 'u'; mappings[10] = 'i'; mappings[11] = 'g'; mappings[12] = 'l'; mappings[13] = 'b'; mappings[14] = 'k'; mappings[15] = 'r'; mappings[16] = 'z'; mappings[17] = 't'; mappings[18] = 'n'; mappings[19] = 'w'; mappings[20] = 'j'; mappings[21] = 'p'; mappings[22] = 'f'; mappings[23] = 'm'; mappings[24] = 'a'; mappings[25] = 'q'; int dobreak = 0; int N; scanf("%d *[^\n]", &N); int i; for (i = 0; i < N; i++) { char line[LINE_MAX]; // Check fgets succeeds if (fgets(line, LINE_MAX, stdin) != NULL) { printf("Case #%d: ", i+1); int j; for (j = 0; j < LINE_MAX; j++) { if (line[j] == ' ') { printf(" "); } else if (line[j] == '\n') { break; } else { int x = line[j]; x -= 97; printf("%c", mappings[x]); } } } printf("\n"); } return 0; }
C++
UTF-8
397
2.640625
3
[]
no_license
#include <bits/stdc++.h> struct Node{ char character; int value; struct Node* esq; struct Node* dir; }; struct binary_tree{ struct Node* first_node; }; struct binary_tree* criarArvoreBinaria (){ struct binary_tree* bt = (binary_tree*)malloc(sizeof(binary_tree)); bt->first_node = NULL; return bt; } void binaryTreeAddElement (char c, int v){ } int main(){ }
Java
UTF-8
812
2.859375
3
[ "Apache-2.0" ]
permissive
package dea.monitor.tools; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexTester { public static void main(String[] args) { String[] response = { "Station reported <span id=\"update_time\">11 seconds ago</span></span></h2>", "Station reported <span id=\"update_time\">1 minute ago</span></span></h2>", "Station reported <span id=\"update_time\">2 minutes ago</span></span></h2>" }; Pattern pattern = null; String regexString = "seconds ago</span></span>|>[1-9] minute[s]{0,1} ago</span></span>"; if (regexString != null) { pattern = Pattern.compile(regexString); } for (int i = 0; i < response.length; i++) { Matcher matcher = pattern.matcher(response[i]); System.out.println("found:" + matcher.find()); } } }
Swift
UTF-8
2,012
2.59375
3
[ "MIT" ]
permissive
// // STPPaymentResult.swift // StripeiOS // // Created by Jack Flintermann on 1/15/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // import Foundation /// When you're using `STPPaymentContext` to request your user's payment details, this is the object that will be returned to your application when they've successfully made a payment. /// See https://stripe.com/docs/mobile/ios/basic#submit-payment-intents public class STPPaymentResult: NSObject { /// The payment method that the user has selected. This may come from a variety of different payment methods, such as an Apple Pay payment or a stored credit card. - seealso: STPPaymentMethod.h /// If paymentMethod is nil, paymentMethodParams will be populated instead. @objc public private(set) var paymentMethod: STPPaymentMethod? /// The parameters for a payment method that the user has selected. This is /// populated for non-reusable payment methods, such as FPX and iDEAL. - seealso: STPPaymentMethodParams.h /// If paymentMethodParams is nil, paymentMethod will be populated instead. @objc public private(set) var paymentMethodParams: STPPaymentMethodParams? /// The STPPaymentOption that was used to initialize this STPPaymentResult, either an STPPaymentMethod or an STPPaymentMethodParams. @objc public weak var paymentOption: STPPaymentOption? { if paymentMethod != nil { return paymentMethod } else { return paymentMethodParams } } /// Initializes the payment result with a given payment option. This is invoked by `STPPaymentContext` internally; you shouldn't have to call it directly. @objc public init( paymentOption: STPPaymentOption? ) { super.init() if paymentOption is STPPaymentMethod { paymentMethod = paymentOption as? STPPaymentMethod } else if paymentOption is STPPaymentMethodParams { paymentMethodParams = paymentOption as? STPPaymentMethodParams } } }
Java
UTF-8
4,859
1.882813
2
[]
no_license
/* * Copyright(C) 2011-2012 Alibaba Group Holding Limited * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Authors: * wentong <wentong@taobao.com> */ package com.taobao.tdhs.client.request; import com.taobao.tdhs.client.common.TDHSCommon; import com.taobao.tdhs.client.exception.TDHSEncodeException; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author <a href="mailto:wentong@taobao.com">文通</a> * @since 11-11-1 下午4:10 */ public class Get extends RequestWithCharset implements Request { private TableInfo tableInfo; private List<String[]> _key = new ArrayList<String[]>(); private int ____find_flag = TDHSCommon.FindFlag.TDHS_EQ.getValue(); private int _start; private int _limit; private Filters filters = new Filters(); public Get(TableInfo tableInfo, String keys[][], TDHSCommon.FindFlag findFlag, int start, int limit) { this.tableInfo = tableInfo; if (keys != null) { Collections.addAll(this._key, keys); } this.____find_flag = findFlag.getValue(); this._start = start; this._limit = limit; } public Get(TableInfo tableInfo, String keys[][], TDHSCommon.FindFlag findFlag, int start, int limit, @Nullable Filter filters[]) { this(tableInfo, keys, findFlag, start, limit); if (filters != null && filters.length > 0) { for (Filter f : filters) { this.addFilter(f); } } } public Get(TableInfo tableInfo) { this.tableInfo = tableInfo; } public TableInfo getTableInfo() { return tableInfo; } public void setTableInfo(TableInfo tableInfo) { this.tableInfo = tableInfo; } public List<String[]> getKey() { return _key; } public void setKey(String[] key) { _key.clear(); _key.add(key); } public void setKey(String[][] keys) { _key.clear(); if (keys != null) { Collections.addAll(this._key, keys); } } public void setKey(List<String>[] keys) { _key.clear(); for (List<String> k : keys) { _key.add(k.toArray(new String[k.size()])); } } public int getFindFlag() { return ____find_flag; } public void setFindFlag(TDHSCommon.FindFlag findFlag) { this.____find_flag = findFlag.getValue(); } public int getStart() { return _start; } public void setStart(int start) { this._start = start; } public int getLimit() { return _limit; } public void setLimit(int limit) { this._limit = limit; } public void addFilter(Filter filter) { filters.addFilter(filter); } public void addFilter(String field, TDHSCommon.FilterFlag flag, String value) { filters.addFilter(field, flag, value); } public void isValid(TDHSCommon.ProtocolVersion version) throws TDHSEncodeException { if (tableInfo == null) { throw new TDHSEncodeException("tableInfo can't be empty!"); } tableInfo.isValid(version); if (_key == null || _key.size() == 0) { throw new TDHSEncodeException("key can't be missing!"); } if (version.equals(TDHSCommon.ProtocolVersion.V1)) { if (_key.size() > TDHSCommon.REQUEST_MAX_KEY_NUM) { throw new TDHSEncodeException("too many keys(in) ,larger than 10!"); } } for (String[] k : _key) { if (k == null || k.length == 0) { throw new TDHSEncodeException("key can't be empty!"); } if (k.length > TDHSCommon.REQUEST_MAX_KEY_NUM) { throw new TDHSEncodeException("too many keys ,larger than 10!"); } } if (filters != null) { filters.isValid(version); } if (____find_flag == TDHSCommon.FindFlag.TDHS_BETWEEN.getValue() && _key.size() < 2) { throw new TDHSEncodeException("between need at least 2 keys"); } } @Override public String toString() { return "Get{" + "tableInfo=" + tableInfo + ",key=" + _key + ", find_flag=" + ____find_flag + ", start=" + _start + ", limit=" + _limit + ", filters=" + filters + '}'; } }
Java
UTF-8
856
2.296875
2
[]
no_license
package com.shana.elasticsearch; public class Command { private String index; private String type; private String queryString; private Method method; private Object httpBody; public enum Method{ POST,DELETE,GET,PUT,PATCH } public String getIndex() { return index; } public void setIndex(String index) { this.index = index; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getQueryString() { return queryString; } public void setQueryString(String queryString) { this.queryString = queryString; } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; } public Object getHttpBody() { return httpBody; } public void setHttpBody(Object httpBody) { this.httpBody = httpBody; } }
Shell
UTF-8
174
2.765625
3
[ "WTFPL" ]
permissive
#!/bin/bash # # grm - short command to search through Minimy python files # cd $HOME/minimy grep -n "$@" *py */*py */*/*py */*/*/*py 2>/dev/null | sed "s:^:$HOME/minimy/:g"
Python
UTF-8
101,809
3.75
4
[]
no_license
""" Cities. version 1.2 with graphs. Life simulation. """ from re import split as slt # for parsing values while creating a new city # random is everywhere from random import weibullvariate as wb, gammavariate as gm, randrange as rdr, \ random as rdm, choice as chc from json import load, dump # loading and saving data for running a script from time import time as tm # how long does it take to make 1 year from math import sqrt # counting root of something from prettytable import PrettyTable # printing information by using tables class World: """ This is a place, where everything exists. The __str__ representation is a general information about each city. The __len__ representation is a number of alive people in each city, which exist in this world (Environment.__len__() must exist). 1 World() -> few Environment() -> more ResourceFacility() and more House() -> a lot of Human() """ world = [] # [Environment(), ...] year = 0 # world time data = {"years": 0, "seconds per year": []} # general data for building graphs def __init__(self, name): self.name = name # str : name of an object of the class World def __len__(self): """ for 1 000 000 iterations ::: sum of an lengths array >>> ~ 3.4 - 3.5 s looping >>> ~ 3.85 - 3.9 s functools.reduce() >>> ~ 4.9 - 5 s """ return sum([len(city) for city in self.world]) def __str__(self): return "-" * 22 + f" Object: '{self.name}' (class " \ f"'{self.__class__.__name__}'), Residents: {len(self)}. " \ f"Year: {self.year} " + "-" * 22 def cities_creator(self, number): print("\nDefault settings for city creation:\nname=input(), people=250, " "water~1500, food~1500, wood~1000, ore=0, metal=0, stone=0\nYou can " "print a name with any register.\n\nIf you want to create a city with " "a default settings, just print: \nname=input()\n\nFor creating a city " "with a unique settings, print:\nparameter (people, food, wood, etc.) " "and value.\nFor example: name=input(), people=100, metal=1000, ore=500") iteration = 0 while iteration != number: name, people, water, food = None, 250, None, None wood, ore, metal, stone = None, None, None, None city_data = input(f"City : {iteration + 1} / {number}\nData : ") reorganized_data = [data for data in slt(r"[=|, |~]", city_data) if data] if len(reorganized_data) % 2 != 0: print(f"{reorganized_data}\nProbably, you made a mistake. " f"Please, try again.") else: for index in range(0, len(reorganized_data), 2): parameter = reorganized_data[index].lower() value = reorganized_data[index + 1] if parameter == "name": name = self.city_name_parser(name=value, message="Name") elif parameter == "people": people = integer_checker(value=value, message="People") elif parameter == "water": water = integer_checker(value=value, message="Water") elif parameter == "food": food = integer_checker(value=value, message="Food") elif parameter == "wood": wood = integer_checker(value=value, message="Wood") elif parameter == "ore": ore = integer_checker(value=value, message="Ore") elif parameter == "metal": metal = integer_checker(value=value, message="Metal") elif parameter == "stone": stone = integer_checker(value=value, message="Stone") city = Environment(name, water, food, wood, ore, metal, stone) for _ in range(people + 1): city.adults.append( Human(age=int(wb(25, 50)), wish_attr=round(wb(2.5, 7.5), 2))) self.world.append(city) iteration += 1 def city_name_parser(self, name=None, message=None): name = name or input() while True: if name == "": if message: print(f"{message} >>> you can't pass a space blanked name. " "Please, try again.") else: print("You can't pass a space blanked name. Please, try again.") elif name.title() in [city.name for city in self.world]: if message: print(f"{message} >>> this city is already exist. " "Please, try again.") else: print("This city is already exist. Please, try again.") else: return name.title() name = input("name=") def year_maker(self): for city in self.world: h_c, p_s, c_s = city.first_block_functions() # a first block of functions counting all resources and make dictionaries # for other blocks ::: h_c = human costs, p_s = products, c_s = costs. f_l = city.second_block_functions(p_s, c_s) # a second block of functions, using the city.requests dictionary, # checking if a request is true, than appending it to the city.queue. # returning f_l = maximum forge level of the city for other blocks. city.third_block_functions(h_c, p_s, c_s, f_l) # a third block of functions takes all requests from city.queue and # placing them into two different arrays => city.alert or city.non_urgent. # After it, it makes a plan (city.plan) of deeds people should do. city.fourth_block_functions(f_l) # a fourth block of functions making all requests from city.plan and # try to make all of it. After, finishing the hole building cycle. city.fifth_block_functions() # a fifth block of functions managing all people changes. class Environment: """ Environment, basically, is a city or a village, depends on the environment population. All cities have a unique name. The __str__ representation is a general information about quantity of people overall, kids, adults, elders, dead people, information about each resource and building with its level. (ResourceFacility.__str__() must exist). The __len__ representation is a number of alive people in the environment ([kids], [adults] and [elders] must exist). All adults can make a new family and append themselves into the family dictionary with a unique family index. Each city has resources. People can use resources for building or upgrading facilities, eating, drinking and etc. {requests} dictionary used for sending codes for the life management. """ requests = { "water is out": 1, "food is out": 2, "wood is out": 3, "ore is out": 4, "water is out next year": 11, "water trend is strong": 13, "water is up too slow": 14, "water is too much": 15, "food is out next year": 21, "food trend is strong": 23, "food is up too slow": 24, "food is too much": 25, "wood is out next year": 31, "wood trend is strong": 33, "wood is up too slow": 34, "wood is too much": 35, "ore is out next year": 41, "ore trend is strong": 43, "ore is up too slow": 44, "ore is too much": 45, "metal is out next year": 51, "metal trend is strong": 53, "metal is up too slow": 54, "metal is too much": 55, "stone is out next year": 61, "stone trend is strong": 63, "stone is up too slow": 64, "stone is too much": 65, "build the family house": 91, "upgrade the family house": 92, "build a house for a human": 93, "no well": 111, "no farm": 121, "no hunting house": 122, "no port": 123, "no sawmill": 131, "no mine": 141, "no forge": 151, "no quarry": 161, "build well": 211, "upgrade well": 212, "build farm": 221, "upgrade farm": 222, "build hunting house": 223, "upgrade hunting house": 224, "build port": 225, "upgrade port": 226, "build sawmill": 231, "upgrade sawmill": 232, "build mine": 241, "upgrade mine": 242, "build forge": 251, "upgrade forge": 252, "build quarry": 261, "upgrade quarry": 262, "water need forge": 311, "food need forge": 321, "wood need forge": 331, "ore need forge": 341, "stone need forge": 361, "stop farm": 421, "stop forge": 451 } def __init__(self, name, water, food, wood, ore, metal, stone): self.name = name # str : name of an object of the class Environment # attributes for people ::: class - Human() self.kids, self.adults, self.elders = [], [], [] # alive people are here self.family_index = 1 # int : a unique family number-key in {families} self.families = {} # {family_index: {"house": house_index, # "parents": [], "children": []}} self.grave = [] # dead people are here # attributes for resources self.water = water or gm(1500, 1) # user input or ~ 1500 units self.food = food or gm(1500, 1) # user input or ~ 1500 units self.wood = wood or gm(1000, 1) # user input or ~ 1000 units self.ore = ore or 0 # user input or 0 self.metal = metal or 0 # user input or 0 self.stone = stone or 0 # user input or 0 self.resources = {"water": self.water, "food": self.food, "wood": self.wood, "ore": self.ore, "metal": self.metal, "stone": self.stone} # attributes for buildings and houses self.building_index = 1 # int : a unique building number-key in {buildings} self.buildings = {} # {building_index: ResourceFacility()} self.house_index = 1 # int : a unique house number-key in {houses} self.houses = {} # {house_index: House()} self.brigades = [] # people, that build any facility in a current year # resource_trend, requests and management self.queue = [] # an array of requests for making alert and non_urgent self.alert = [] # an array of the most important problems to solve self.non_urgent = [] # an array of problems that are non-urgent self.plan = [] # step by step maker # general data for building graphs self.data = { "kids": [], "adults": [], "elders": [], "people in the city": [], "families": [], "grave": [], "average life": None, "water": [], "food": [], "wood": [], "ore": [], "metal": [], "stone": [], "buildings": [], "houses": []} def __len__(self): return len(self.kids) + len(self.adults) + len(self.elders) def __str__(self): return f"{self.name} of the class '{self.__class__.__name__}' with " \ f"{len(self)} alive people:\n[People -> families = " \ f"{len(self.families)}; kids = {len(self.kids)}; adults = " \ f"{len(self.adults)}; elders = {len(self.elders)}; grave = " \ f"{len(self.grave)}]\n[Resources -> water = {round(self.water, 2)}" \ f"; food = {round(self.food, 2)}; wood = {round(self.wood, 2)}; " \ f"ore = {round(self.ore, 2)}; metal = {round(self.metal, 2)}" \ f"; stone = {round(self.stone, 2)}]\n[Buildings -> houses = " \ f"{len(self.houses)}, facilities = {len(self.buildings)}]\n" + \ "\n".join(f"{hs}" for hs in self.houses.values()) + "\n\n" + \ "\n".join(f"{bg}" for bg in self.buildings.values()) + "\n" def first_block_functions(self): self.queue = [] self.alert, self.non_urgent = [], [] self.plan = [] h_c = self.costs_of_human_life_counter() p_s, c_s, result, account_flag = self.production_counter() if account_flag: self.finishing_first_block(result) return h_c, p_s, c_s else: self.accounting_function(p_s, c_s, result) self.finishing_first_block(result) return h_c, p_s, c_s def costs_of_human_life_counter(self): h_costs = {"water": len(self), "food": len(self), "wood": 0} for array in (self.kids, self.adults, self.elders): for human in array: if not human.house_index: h_costs["wood"] += 1 for house in self.houses.values(): h_costs["wood"] += house.info[house.level]["cost: wood"] for res, value in h_costs.items(): self.resources[res] -= value return h_costs def production_counter(self): p_s = {"water": 0, "food": 0, "wood": 0, "ore": 0, "metal": 0, "stone": 0} c_s = {"water": 0, "food": 0, "wood": 0, "ore": 0} for building in self.buildings.values(): building.assets_and_liabilities_counter(p_s, c_s) building.more_experience_workers() result = {"water": 0, "food": 0, "wood": 0, "ore": 0, "metal": 0, "stone": 0} for res in result: result[res] = self.resources[res] + p_s[res] - c_s.get(res, 0) if all(x >= 0 for x in result.values()): return p_s, c_s, result, True return p_s, c_s, result, False def finishing_first_block(self, result): for res, value in result.items(): self.resources[res] = value self.water, self.food = self.resources["water"], self.resources["food"] self.wood, self.ore = self.resources["wood"], self.resources["ore"] self.metal, self.stone = self.resources["metal"], self.resources["stone"] def accounting_function(self, p_s, c_s, result): if result["water"] < 0: self.queue.append(self.requests["water is out"]) result["water"] = 0 if result["food"] < 0: self.queue.append(self.requests["food is out"]) result["food"] = 0 if result["wood"] < 0: self.queue.append(self.requests["wood is out"]) result["wood"] = 0 if result["ore"] < 0: self.queue.append(self.requests["ore is out"]) coefficient = c_s["ore"] / p_s["metal"] while result["ore"] < 0: p_s["metal"] -= 1 c_s["ore"] -= coefficient result["metal"] -= 1 result["ore"] += coefficient def second_block_functions(self, p_s, c_s): self.slow_growing_up_resource_requests_parser(p_s) self.most_of_resource_requests_parser(p_s, c_s) self.people_requests_parser() self.people_making_brigades_for_building_new_facilities() f_l = self.forge_level_parser() return f_l def slow_growing_up_resource_requests_parser(self, p_s): income = 0 for product in p_s.values(): income += product if income != 0: for res, value in p_s.items(): if value / income <= 0.05: self.queue.append(self.requests[f"{res} is up too slow"]) elif value / income >= 0.5: self.queue.append(self.requests[f"{res} is too much"]) def most_of_resource_requests_parser(self, p_s, c_s): for res, value in self.resources.items(): if self.resources[res] + p_s[res] - c_s.get(res, 0) < 0: self.queue.append(self.requests[f"{res} is out next year"]) else: trend = self.resources[res] + 10 * (p_s[res] - c_s.get(res, 0)) if trend <= 0 or self.resources[res] > 10 * trend: self.queue.append(self.requests[f"{res} trend is strong"]) for bld, class_ in {"well": Well, "farm": Farm, "hunting house": HuntingHouse, "port": Port, "sawmill": Sawmill, "mine": Mine, "quarry": Quarry, "forge": Forge}.items(): if class_ not in [type(clb) for clb in self.buildings.values()]: self.queue.append(self.requests[f"no {bld}"]) def people_requests_parser(self): for family in self.families.values(): if not family["house"]: self.queue.append(self.requests["build the family house"]) else: house = self.houses[family["house"]] if len(house.tenants) >= House.info[house.level]["max p_l"]: self.queue.append(self.requests["upgrade the family house"]) for array in (self.adults, self.elders): for human in array: if not human.house_index and not human.family_index: self.queue.append(self.requests["build a house for a human"]) def people_making_brigades_for_building_new_facilities(self): for array in (self.kids, self.adults, self.elders): for human in array: if 14 <= human.age <= 70 and not human.builder_status: self.brigades.append(human) human.builder_status = True def forge_level_parser(self): forge_level = 0 for building in self.buildings.values(): if "Forge" in building.name and forge_level < building.level: forge_level = building.level return forge_level def third_block_functions(self, h_c, p_s, c_s, f_l): ch_s = {"water": 0, "food": 0, "wood": 0, "ore": 0, "metal": 0, "stone": 0} copy = {k: v for k, v in self.resources.items()} self.alert_or_non_urgent_parser() self.result_of_the_year_for_people() self.the_most_important_alerts_parser(h_c, p_s, c_s, f_l, ch_s, copy) self.all_other_alerts_parser(f_l, ch_s, copy) self.all_non_urgent_parser(h_c, p_s, c_s, f_l, ch_s, copy) def alert_or_non_urgent_parser(self): for request in (1, 2, 3, 4, 11, 21, 31, 41): if request in self.queue: self.alert.append(request) self.request_humans_houses_parser(self.alert, 5) for request in (111, 121, 122, 123, 131, 141, 151, 161): if request in self.queue: self.alert.append(request) for request in (14, 24, 34, 44, 54, 64): if request in self.queue: self.non_urgent.append(request) self.request_humans_houses_parser(self.non_urgent, 3) for request in (13, 23, 33, 43, 53, 63): if request in self.queue: self.non_urgent.append(request) def request_humans_houses_parser(self, sending, number): if len(self.families) > 0: if self.requests["wood is too much"] in self.queue: for _ in range(self.queue.count(91)): sending.append(self.requests["build the family house"]) for _ in range(self.queue.count(92)): sending.append(self.requests["upgrade the family house"]) else: for _ in range(self.queue.count(91) // number): sending.append(self.requests["build the family house"]) for _ in range(self.queue.count(92) // number): sending.append(self.requests["upgrade the family house"]) if self.requests["wood is too much"] in self.queue: for _ in range(self.queue.count(93)): sending.append(self.requests["build a house for a human"]) else: add = 1 if self.queue.count(91) >= 15: add = 5 for _ in range(self.queue.count(93) // (number * add)): sending.append(self.requests["build a house for a human"]) def result_of_the_year_for_people(self): if 1 not in self.queue and 2 not in self.queue and 3 not in self.queue: for array in (self.kids, self.adults, self.elders): for human in array: human.death = 0.75 for elem in (1, 2, 3): if elem in self.queue: for array in (self.kids, self.adults, self.elders): for human in array: human.death -= 0.000025 def the_most_important_alerts_parser(self, h_c, p_s, c_s, f_l, ch_s, copy): """ 1, 2, 3, 4, 11, 21, 31, 41 """ self.sawmill_builder_template(ch_s, copy) self.well_builder_template(ch_s, copy) self.farm_builder_template(ch_s, copy) self.hunting_house_builder_template(ch_s, copy) self.port_builder_template(ch_s, copy) if self.requests["water is out"] in self.alert: self.plan.append(self.requests["stop farm"]) self.water_template(h_c, p_s, c_s, f_l, ch_s, copy, 50) if self.requests["food is out"] in self.alert: self.food_template(h_c, p_s, c_s, f_l, ch_s, copy, 50) if self.requests["wood is out"] in self.alert: self.wood_template(h_c, p_s, c_s, f_l, ch_s, copy, 50) if self.requests["ore is out"] in self.alert: self.plan.append(self.requests["stop forge"]) self.ore_template(h_c, p_s, c_s, f_l, ch_s, copy, 25) if self.requests["water is out next year"] in self.alert: self.plan.append(self.requests["stop farm"]) self.water_template(h_c, p_s, c_s, f_l, ch_s, copy, 25) if self.requests["food is out next year"] in self.alert: self.food_template(h_c, p_s, c_s, f_l, ch_s, copy, 25) if self.requests["wood is out next year"] in self.alert: self.wood_template(h_c, p_s, c_s, f_l, ch_s, copy, 25) if self.requests["ore is out next year"] in self.alert: self.plan.append(self.requests["stop forge"]) self.ore_template(h_c, p_s, c_s, f_l, ch_s, copy, 25) self.people_are_soo_people() def sawmill_builder_template(self, ch_s, copy): if self.requests["no sawmill"] in self.alert: self.building_planer("build sawmill", ch_s, "wood", Sawmill, copy, else_status=True) def building_planer(self, request, ch_s, res, obj, copy, else_status=False): if copy["wood"] - obj.info[1]["build"]["wood"] >= 0: copy["wood"] -= obj.info[1]["build"]["wood"] ch_s[res] += (obj.info[1]["max w_s"] * obj.info[1]["jun"]) self.plan.append(self.requests[request]) elif else_status and copy["wood"] < 0: copy["wood"] = 0 ch_s[res] += (obj.info[1]["max w_s"] * obj.info[1]["jun"]) self.plan.append(self.requests[request]) def well_builder_template(self, ch_s, copy): if self.requests["no well"] in self.alert: self.building_planer("build well", ch_s, "water", Well, copy, else_status=True) def farm_builder_template(self, ch_s, copy): if self.requests["no farm"] in self.alert: self.building_planer("build farm", ch_s, "food", Farm, copy, else_status=True) def hunting_house_builder_template(self, ch_s, copy): if self.requests["no hunting house"] in self.alert: self.building_planer("build hunting house", ch_s, "food", HuntingHouse, copy, else_status=True) def port_builder_template(self, ch_s, copy): if self.requests["no port"] in self.alert: self.building_planer("build port", ch_s, "food", Port, copy, else_status=True) def water_template(self, h_c, p_s, c_s, f_l, ch_s, copy, plus): for index in self.an_array_of_indexes_for_upgrade(Well): well = self.buildings[index] if well.level != 15: if self.upgrading_planer(well, f_l, ch_s, "upgrade well", copy, "water"): if self.resource_checker(h_c, p_s, c_s, "water", ch_s, plus): break else: if well.info[well.level + 1]["build"]["Forge"] > f_l: self.plan.append(self.requests["water need forge"]) else: if not self.resource_checker(h_c, p_s, c_s, "water", ch_s, plus): if copy["wood"] >= Well.info[1]["build"]["wood"]: self.building_planer("build well", ch_s, "water", Well, copy) self.random_behaviour(10, "build well", "build well", "upgrade well", "upgrade well", "upgrade well", "build sawmill", "upgrade sawmill") self.resource_navigation_template("water") def an_array_of_indexes_for_upgrade(self, obj): indexes = [i for i, b in self.buildings.items() if b is type(obj)] return indexes[::-1] def upgrading_planer(self, obj, forge_level, ch_s, request, copy, resource): upgrade_flag = True for res, value in obj.info[obj.level + 1]["build"].items(): if res == "Forge" and forge_level < value: upgrade_flag = False elif copy[res] - value < 0: upgrade_flag = False if upgrade_flag: for res, value in obj.info[obj.level + 1]["build"].items(): if res != "Forge": copy[res] -= value ch_s[resource] -= \ (obj.info[obj.level]["max w_s"] * obj.info[obj.level]["jun"]) ch_s[resource] += \ (obj.info[obj.level + 1]["max w_s"] * obj.info[obj.level + 1]["jun"]) self.plan.append(self.requests[request]) return True return False @staticmethod def resource_checker(h_c, p_s, c_s, res, ch_s, limit): if (p_s[res] - c_s.get(res, 0) - h_c.get(res, 0) + ch_s[res]) >= limit: return True return False def random_behaviour(self, limit, *args): for _ in range(rdr(0, limit + 1)): if rdm() >= 0.6: self.plan.append(self.requests[chc([*args])]) def resource_navigation_template(self, res): if self.requests[f"{res} is out next year"] in self.alert: self.alert.remove(self.requests[f"{res} is out next year"]) for request in (f"{res} trend is strong", f"{res} is up too slow"): if self.requests[request] in self.non_urgent: self.non_urgent.remove(self.requests[request]) def food_template(self, h_c, p_s, c_s, f_l, ch_s, copy, plus): if self.farm_parser_template(ch_s, copy, h_c, p_s, c_s, f_l, plus): if self.hunting_house_parser_template(ch_s, copy, h_c, p_s, c_s, f_l, plus): self.port_parser_template(ch_s, copy, h_c, p_s, c_s, f_l, plus) self.random_behaviour(20, "build farm", "build hunting house", "build port", "upgrade farm", "upgrade hunting house", "upgrade port", "upgrade hunting house", "upgrade port", "build sawmill", "upgrade sawmill") self.resource_navigation_template("food") def farm_parser_template(self, ch_s, copy, h_c, p_s, c_s, f_l, plus): if self.requests["stop farm"] in self.plan: return True for index in self.an_array_of_indexes_for_upgrade(Farm): farm = self.buildings[index] if farm.level != 15: if self.upgrading_planer(farm, f_l, ch_s, "upgrade farm", copy, "food"): if self.resource_checker(h_c, p_s, c_s, "food", ch_s, plus): return False else: if farm.info[farm.level + 1]["build"]["Forge"] > f_l: self.plan.append(self.requests["food need forge"]) else: if not self.resource_checker(h_c, p_s, c_s, "food", ch_s, plus): if copy["wood"] >= Farm.info[1]["build"]["wood"]: self.building_planer("build farm", ch_s, "food", Farm, copy) if self.resource_checker(h_c, p_s, c_s, "food", ch_s, plus): return False return True def hunting_house_parser_template(self, ch_s, copy, h_c, p_s, c_s, f_l, plus): for index in self.an_array_of_indexes_for_upgrade(HuntingHouse): hunt = self.buildings[index] if hunt.level != 10: if self.upgrading_planer(hunt, f_l, ch_s, "upgrade hunting house", copy, "food"): if self.resource_checker(h_c, p_s, c_s, "food", ch_s, plus): return False else: if hunt.info[hunt.level + 1]["build"]["Forge"] > f_l: self.plan.append(self.requests["food need forge"]) else: if not self.resource_checker(h_c, p_s, c_s, "food", ch_s, plus): if copy["wood"] >= HuntingHouse.info[1]["build"]["wood"]: self.building_planer("build hunting house", ch_s, "food", HuntingHouse, copy) if self.resource_checker(h_c, p_s, c_s, "food", ch_s, plus): return False return True def port_parser_template(self, ch_s, copy, h_c, p_s, c_s, f_l, plus): for index in self.an_array_of_indexes_for_upgrade(Port): port = self.buildings[index] if port.level != 12: if self.upgrading_planer(port, f_l, ch_s, "upgrade port", copy, "food"): if self.resource_checker(h_c, p_s, c_s, "food", ch_s, plus): break else: if port.info[port.level + 1]["build"]["Forge"] > f_l: self.plan.append(self.requests["food need forge"]) else: if not self.resource_checker(h_c, p_s, c_s, "food", ch_s, plus): if copy["wood"] >= Port.info[1]["build"]["wood"]: self.building_planer("build port", ch_s, "food", Port, copy) def wood_template(self, h_c, p_s, c_s, f_l, ch_s, copy, plus): for index in self.an_array_of_indexes_for_upgrade(Sawmill): sawmill = self.buildings[index] if sawmill.level != 15: if self.upgrading_planer(sawmill, f_l, ch_s, "upgrade sawmill", copy, "wood"): if self.resource_checker(h_c, p_s, c_s, "wood", ch_s, plus): break else: if sawmill.info[sawmill.level + 1]["build"]["Forge"] > f_l: self.plan.append(self.requests["wood need forge"]) else: if not self.resource_checker(h_c, p_s, c_s, "wood", ch_s, plus): if copy["wood"] >= Sawmill.info[1]["build"]["wood"]: self.building_planer("build sawmill", ch_s, "wood", Sawmill, copy) self.random_behaviour(10, "build sawmill", "upgrade sawmill", "upgrade sawmill") self.resource_navigation_template("wood") def ore_template(self, h_c, p_s, c_s, f_l, ch_s, copy, plus): for index in self.an_array_of_indexes_for_upgrade(Mine): mine = self.buildings[index] if mine.level != 10: if self.upgrading_planer(mine, f_l, ch_s, "upgrade mine", copy, "ore"): if self.resource_checker(h_c, p_s, c_s, "ore", ch_s, plus): break else: if mine.info[mine.level + 1]["build"]["Forge"] > f_l: self.plan.append(self.requests["ore need forge"]) else: if not self.resource_checker(h_c, p_s, c_s, "ore", ch_s, plus): if copy["wood"] >= Mine.info[1]["build"]["wood"]: self.building_planer("build mine", ch_s, "ore", Mine, copy) self.random_behaviour(10, "build mine", "upgrade mine", "upgrade mine", "build sawmill", "upgrade sawmill") self.resource_navigation_template("ore") def people_are_soo_people(self): for _ in range(10): if rdm() >= 0.65: self.plan.append(self.requests[chc([ "build well", "build well", "upgrade well", "upgrade well", "upgrade well", "upgrade well", "build farm", "build farm", "upgrade farm", "upgrade farm", "upgrade farm", "build hunting house", "build hunting house", "upgrade hunting house", "upgrade hunting house", "upgrade hunting house", "upgrade hunting house", "build port", "build port", "upgrade port", "upgrade port", "upgrade port", "upgrade port", "build sawmill", "build sawmill", "upgrade sawmill", "upgrade sawmill", "upgrade sawmill", "upgrade sawmill", "upgrade sawmill", "build mine", "upgrade mine", "upgrade mine", "build quarry", "upgrade quarry", "upgrade quarry", "build forge", "upgrade forge", "upgrade forge"])]) def all_other_alerts_parser(self, f_l, ch_s, copy): """ 91, 92, 93, 111, 121, 122, 123, 131, 141, 151, 161 """ if self.requests["build the family house"] in self.alert: self.house_building_planer("build the family house", copy, self.alert) if self.requests["upgrade the family house"] in self.alert: self.house_upgrading_planer(self.alert, f_l, copy, "upgrade the family house") if self.requests["build a house for a human"] in self.alert: self.house_building_planer("build a house for a human", copy, self.alert) self.mine_builder_template(ch_s, copy) self.quarry_builder_template(ch_s, copy) self.forge_builder_template(ch_s, copy) self.people_are_soo_people() def house_building_planer(self, request, copy, place): for _ in range(place.count(self.requests[request])): if copy["wood"] - House.info[1]["build"]["wood"] >= 0: self.plan.append(self.requests[request]) copy["wood"] -= House.info[1]["build"]["wood"] def house_upgrading_planer(self, place, forge_level, copy, request): for _ in range(place.count(self.requests[request])): for house in self.houses.values(): if house.level != 5: if len(house.tenants) >= house.info[house.level]["max p_l"]: upgrade_flag = True for res, val in house.info[house.level + 1]["build"].items(): if res == "Forge": if forge_level < val: upgrade_flag = False elif copy[res] - val < 0: upgrade_flag = False if upgrade_flag: for res, val in house.info[house.level + 1]["build"].items(): if res != "Forge": copy[res] -= val self.plan.append(self.requests[request]) def mine_builder_template(self, ch_s, copy): if self.requests["no mine"] in self.alert: self.building_planer("build mine", ch_s, "ore", Mine, copy) def quarry_builder_template(self, ch_s, copy): if self.requests["no quarry"] in self.alert: self.building_planer("build quarry", ch_s, "stone", Quarry, copy) def forge_builder_template(self, ch_s, copy): if self.requests["no forge"] in self.alert: self.building_planer("build forge", ch_s, "metal", Forge, copy) def all_non_urgent_parser(self, h_c, p_s, c_s, f_l, ch_s, copy): """ 14, 24, 34, 44, 54, 64, 91, 92, 93, 13, 23, 33, 43 """ self.people_are_soo_people() if self.requests["water is up too slow"] in self.non_urgent: self.water_template(h_c, p_s, c_s, f_l, ch_s, copy, 0) if self.requests["food is up too slow"] in self.non_urgent: self.food_template(h_c, p_s, c_s, f_l, ch_s, copy, 0) if self.requests["wood is up too slow"] in self.non_urgent: self.wood_template(h_c, p_s, c_s, f_l, ch_s, copy, 0) if self.requests["ore is up too slow"] in self.non_urgent: self.ore_template(h_c, p_s, c_s, f_l, ch_s, copy, 0) if self.requests["metal is up too slow"] in self.non_urgent: self.metal_template(h_c, p_s, c_s, f_l, ch_s, copy, 0) if self.requests["stone is up too slow"] in self.non_urgent: self.stone_template(h_c, p_s, c_s, f_l, ch_s, copy, 0) if self.requests["build the family house"] in self.non_urgent: self.house_building_planer("build the family house", copy, self.non_urgent) if self.requests["upgrade the family house"] in self.non_urgent: self.house_upgrading_planer(self.non_urgent, f_l, copy, "upgrade the family house") if self.requests["build a house for a human"] in self.non_urgent: self.house_building_planer("build a house for a human", copy, self.non_urgent) if self.requests["water trend is strong"] in self.non_urgent: self.water_template(h_c, p_s, c_s, f_l, ch_s, copy, -50) if self.requests["food trend is strong"] in self.non_urgent: self.food_template(h_c, p_s, c_s, f_l, ch_s, copy, -50) if self.requests["wood trend is strong"] in self.non_urgent: self.wood_template(h_c, p_s, c_s, f_l, ch_s, copy, -50) if self.requests["ore trend is strong"] in self.non_urgent: self.ore_template(h_c, p_s, c_s, f_l, ch_s, copy, -50) self.people_are_soo_people() def metal_template(self, h_c, p_s, c_s, f_l, ch_s, copy, plus): for index in self.an_array_of_indexes_for_upgrade(Forge): forge = self.buildings[index] if forge.level != 15: if self.upgrading_planer(forge, f_l, ch_s, "upgrade forge", copy, "metal"): if self.resource_checker(h_c, p_s, c_s, "metal", ch_s, plus): break else: if not self.resource_checker(h_c, p_s, c_s, "metal", ch_s, plus): if copy["wood"] >= Forge.info[1]["build"]["wood"]: self.building_planer("build forge", ch_s, "metal", Forge, copy) self.random_behaviour(10, "build forge", "upgrade forge", "upgrade forge", "build mine", "upgrade mine") self.resource_navigation_template("metal") def stone_template(self, h_c, p_s, c_s, f_l, ch_s, copy, plus): for index in self.an_array_of_indexes_for_upgrade(Quarry): quarry = self.buildings[index] if quarry.level != 10: if self.upgrading_planer(quarry, f_l, ch_s, "upgrade quarry", copy, "stone"): if self.resource_checker(h_c, p_s, c_s, "stone", ch_s, plus): break else: if quarry.info[quarry.level + 1]["build"]["Forge"] > f_l: self.plan.append(self.requests["stone need forge"]) else: if not self.resource_checker(h_c, p_s, c_s, "stone", ch_s, plus): if copy["wood"] >= Quarry.info[1]["build"]["wood"]: self.building_planer("build quarry", ch_s, "stone", Quarry, copy) self.random_behaviour(5, "build quarry", "upgrade quarry", "upgrade quarry") self.resource_navigation_template("stone") def fourth_block_functions(self, f_l): self.empty_facilities_parser() ore_flag = self.ore_is_too_much() self.plan_maker(f_l) Human.people_did_not_build_any_buildings(self) self.buildings_need_more_workers(ore_flag) self.house_management() def empty_facilities_parser(self): if len(self.buildings) == 0: return None counter = \ [len(bg.workers) for bg in self.buildings.values() if len(bg.workers) == 0] if len(counter) / len(self.buildings) >= 0.15: commands = [15, 25, 35, 45, 55, 65, 91, 92, 93, 212, 222, 224, 226, 232, 242, 252, 262, 311, 321, 331, 341, 361, 421, 451] self.plan = [cmd for cmd in self.plan if cmd in commands] def ore_is_too_much(self): if self.resources["ore"] >= 5000 and self.resources["metal"] <= 1000: return True return False def plan_maker(self, f_l): for element in self.plan: if element == self.requests["build the family house"]: if Human.people_want_to_build_new_facilities(self, 5): house = House.a_house_builder(self) if house: self.houses[self.house_index] = house self.house_index += 1 if element == self.requests["upgrade the family house"]: for value in self.families.values(): if value["house"]: house = self.houses[value["house"]] if house.level != 5: if len(house.tenants) >= house.info[house.level]["max p_l"]: if Human.people_want_to_build_new_facilities( self, house.level + 2): house.upgrade_the_house(self, f_l) break if element == self.requests["build a house for a human"]: if Human.people_want_to_build_new_facilities(self, 5): house = House.a_house_builder(self, family_flag=False, human_flag=True) if house: self.houses[self.house_index] = house self.house_index += 1 if element == self.requests["build well"]: if Human.people_want_to_build_new_facilities(self, 4): well = Well.building_a_new_facility(self) if well: self.buildings[self.building_index] = well self.building_index += 1 if element == self.requests["upgrade well"]: for value in self.buildings.values(): if type(value) is Well: if Human.people_want_to_build_new_facilities( self, value.level): if value.upgrade_the_facility(self, f_l): break if element == self.requests["build farm"]: if self.requests["stop farm"] not in self.plan: if Human.people_want_to_build_new_facilities(self, 4): farm = Farm.building_a_new_facility(self) if farm: self.buildings[self.building_index] = farm self.building_index += 1 if element == self.requests["upgrade farm"]: for value in self.buildings.values(): if type(value) is Farm: if Human.people_want_to_build_new_facilities( self, value.level): if value.upgrade_the_facility(self, f_l): break if element == self.requests["build hunting house"]: if Human.people_want_to_build_new_facilities(self, 4): hunting_house = HuntingHouse.building_a_new_facility(self) if hunting_house: self.buildings[self.building_index] = hunting_house self.building_index += 1 if element == self.requests["upgrade hunting house"]: for value in self.buildings.values(): if type(value) is HuntingHouse: if Human.people_want_to_build_new_facilities( self, value.level): if value.upgrade_the_facility(self, f_l): break if element == self.requests["build port"]: if Human.people_want_to_build_new_facilities(self, 4): port = Port.building_a_new_facility(self) if port: self.buildings[self.building_index] = port self.building_index += 1 if element == self.requests["upgrade port"]: for value in self.buildings.values(): if type(value) is Port: if Human.people_want_to_build_new_facilities( self, value.level): if value.upgrade_the_facility(self, f_l): break if element == self.requests["build sawmill"]: if Human.people_want_to_build_new_facilities(self, 4): sawmill = Sawmill.building_a_new_facility(self) if sawmill: self.buildings[self.building_index] = sawmill self.building_index += 1 if element == self.requests["upgrade sawmill"]: for value in self.buildings.values(): if type(value) is Sawmill: if Human.people_want_to_build_new_facilities( self, value.level): if value.upgrade_the_facility(self, f_l): break if element == self.requests["build mine"]: if Human.people_want_to_build_new_facilities(self, 4): mine = Mine.building_a_new_facility(self) if mine: self.buildings[self.building_index] = mine self.building_index += 1 if element == self.requests["upgrade mine"]: for value in self.buildings.values(): if type(value) is Mine: if Human.people_want_to_build_new_facilities( self, value.level): if value.upgrade_the_facility(self, f_l): break if element == self.requests["build quarry"]: if Human.people_want_to_build_new_facilities(self, 4): quarry = Quarry.building_a_new_facility(self) if quarry: self.buildings[self.building_index] = quarry self.building_index += 1 if element == self.requests["upgrade quarry"]: for value in self.buildings.values(): if type(value) is Quarry: if Human.people_want_to_build_new_facilities( self, value.level): if value.upgrade_the_facility(self, f_l): break if element == self.requests["build forge"]: if self.requests["stop forge"] not in self.plan: if Human.people_want_to_build_new_facilities(self, 4): forge = Forge.building_a_new_facility(self) if forge: self.buildings[self.building_index] = forge self.building_index += 1 if element in (self.requests["upgrade forge"], self.requests["water need forge"], self.requests["food need forge"], self.requests["wood need forge"], self.requests["ore need forge"], self.requests["stone need forge"]): for value in self.buildings.values(): if type(value) is Forge: if Human.people_want_to_build_new_facilities( self, value.level): if value.upgrade_the_facility(self, f_l): break def buildings_need_more_workers(self, ore_flag): for index, building in self.buildings.items(): for worker in building.workers: worker.job_status = None building.workers = [] for index, building in self.buildings.items(): if type(building) is Mine and ore_flag: continue limit = self.resource_is_too_much_parser(building) or \ building.info[building.level]["max w_s"] if len(building.workers) < limit: for array in (self.adults, self.elders): for human in array: if not human.job_status: if len(building.workers) < limit: building.workers.append(human) human.job_status = index else: break def resource_is_too_much_parser(self, building): for request, obj in {"water is too much": Well, "food is too much": [Farm, HuntingHouse, Port], "wood is too much": Sawmill, "ore is too much": Mine, "metal is too much": Forge, "stone is too much": Quarry}.items(): if request == "food is too much": for oj in obj: if building is type(oj) and self.requests[request] in self.plan: return building.info[building.level]["max w_s"] // 2 else: if building is type(obj) and self.requests[request] in self.plan: return building.info[building.level]["max w_s"] // 2 def house_management(self): for index, house in self.houses.items(): if len(house.tenants) == 0: for family in self.families.values(): if not family["house"]: family["house"] = index for human in ([*family["parents"], *family["children"]]): human.house_index = index house.tenants.append(human) break def fifth_block_functions(self): for array in (self.kids, self.adults, self.elders): for human in array: human.age += 1 human.attractiveness = human.attractiveness_parameter_changer() human.wish_attr = human.wish_attractiveness_parameter_changer() Human.moving_people_from_array_to_array(self) Human.people_want_to_make_families(self) Human.people_want_to_make_new_people(self) Human.dead_function_by_age(self) Human.removing_all_families_without_parents(self) class ResourceFacility: """ Core class for inheriting for other facilities that bring resources. Objects of this class stored inside of [Environment.buildings]. The __str__ representation is a general information about level and quantity of workers. Every object of class "ResourceFacility" has its own dictionary with all necessary information inside of it. Dictionary consists of: "max w_s" = int : maximum amount of workers on this level. "jun" = float : how many resources will make 1 non-professional worker. "pro" = float : how many resources will make 1 professional worker. "build" = {} : {"resource" or "facility": (amount of resources or level) = int}. All : [Farm, HuntingHouse, Port, Well, Sawmill, Mine, Quarry, Forge]. """ def __init__(self, name, index, level=1): self.name = name # str : name of an object of the class ResourceFacility self.index = index # int : is a Environment.building_index self.level = level # int : level of the facility self.workers = [] # amount of current workers def __str__(self): return f"{self.name} ({self.level}), amount of workers = {len(self.workers)}" def assets_and_liabilities_counter(self, assets, liabilities, costs, profession, years, place, minimum, maximum, resource): """ random.randrange ~~~ random.choice ~~< random.randint """ for worker in self.workers: if worker.employment_history[profession] >= years: assets[resource] += place[self.level]["pro"] \ * rdr(minimum, maximum) / 100 assets[resource] = round(assets[resource], 2) if profession in ("farmer", "blacksmith"): for res, value in costs.items(): liabilities[res] += place[self.level]["pro"] * value \ * rdr(75, 126) / 100 liabilities[res] = round(liabilities[res], 2) else: assets[resource] += place[self.level]["jun"] * rdr(minimum, 101) / 100 assets[resource] = round(assets[resource], 2) if profession in ("farmer", "blacksmith"): for res, value in costs.items(): liabilities[res] += place[self.level]["jun"] * value \ * rdr(85, 136) / 100 liabilities[res] = round(liabilities[res], 2) def more_experience_workers(self, profession): for worker in self.workers: worker.employment_history[profession] += 1 @staticmethod def building_a_new_facility(place, i_n, obj, name): if all(place.resources[res] - v >= 0 for res, v in i_n[1]["build"].items()): for res, value in i_n[1]["build"].items(): place.resources[res] -= value return obj(f"{name} {place.building_index}", place.building_index) def upgrade_the_facility(self, place, forge_level, i_n): upgrade_flag = True for res, value in i_n[self.level + 1]["build"].items(): if res == "Forge": if forge_level < value: upgrade_flag = False elif place.resources[res] - value < 0: upgrade_flag = False if upgrade_flag: self.level += 1 for res, value in i_n[self.level]["build"].items(): if res != "Forge": place.resources[res] -= value return True return False class Well(ResourceFacility): """ Making water by extraction. All information about wells are in the {info} {level: {information}}. def production_and_costs() ::: total production of water and total costs of metal from 1 well. Worker :: engineer, "pro" if worker.employment_history["engineer"] >= 10. """ info = { 1: {"max w_s": 1, "jun": 15, "pro": 15, "build": {"wood": 25}}, 2: {"max w_s": 1, "jun": 25, "pro": 25, "build": {"wood": 35}}, 3: {"max w_s": 1, "jun": 40, "pro": 40, "build": {"wood": 50}}, 4: {"max w_s": 1, "jun": 65, "pro": 65, "build": {"wood": 75}}, 5: {"max w_s": 2, "jun": 100, "pro": 100, "build": {"wood": 100, "stone": 500}}, 6: {"max w_s": 2, "jun": 150, "pro": 150, "build": {"wood": 150, "stone": 300}}, 7: {"max w_s": 2, "jun": 200, "pro": 200, "build": {"wood": 200, "stone": 400}}, 8: {"max w_s": 2, "jun": 250, "pro": 250, "build": {"wood": 250, "stone": 500}}, 9: {"max w_s": 2, "jun": 350, "pro": 350, "build": {"wood": 500, "stone": 500}}, 10: {"max w_s": 3, "jun": 500, "pro": 550, "build": {"wood": 2500, "metal": 2500, "stone": 5000, "Forge": 10}}, 11: {"max w_s": 4, "jun": 500, "pro": 550, "build": {"wood": 750, "metal": 250}}, 12: {"max w_s": 5, "jun": 500, "pro": 550, "build": {"wood": 850, "metal": 400}}, 13: {"max w_s": 6, "jun": 500, "pro": 550, "build": {"wood": 1000, "metal": 600}}, 14: {"max w_s": 7, "jun": 500, "pro": 550, "build": {"wood": 1500, "metal": 1000}}, 15: {"max w_s": 10, "jun": 500, "pro": 600, "build": {"wood": 7500, "metal": 5000, "stone": 10000, "Forge": 15}} } def __init__(self, *args): super().__init__(*args) def assets_and_liabilities_counter(self, assets, liabilities, costs=None, profession="engineer", years=10, place=None, minimum=85, maximum=106, resource="water"): super().assets_and_liabilities_counter(assets, liabilities, costs, profession, years, self.info, minimum, maximum, resource) def more_experience_workers(self, profession="engineer"): super().more_experience_workers(profession) @staticmethod def building_a_new_facility(place, i_n=None, obj=None, name=None): return ResourceFacility.building_a_new_facility(place, i_n=Well.info, obj=Well, name="Well") def upgrade_the_facility(self, place, forge_level, i_n=None): return ResourceFacility.upgrade_the_facility( self, place, forge_level, i_n=Well.info) class Farm(ResourceFacility): """ Making food by seeding and harvesting. All information about farms are in the {info} {level: {information}}. def production_and_costs() ::: total production of food and total costs of water, wood and metal from 1 farm. Worker :: farmer, "pro" if worker.employment_history["farmer"] >= 5. """ info = { 1: {"max w_s": 3, "jun": 6, "pro": 10, "build": {"wood": 25}}, 2: {"max w_s": 4, "jun": 7, "pro": 11, "build": {"wood": 35}}, 3: {"max w_s": 5, "jun": 8, "pro": 12, "build": {"wood": 50}}, 4: {"max w_s": 7, "jun": 9, "pro": 13, "build": {"wood": 100}}, 5: {"max w_s": 10, "jun": 11, "pro": 15, "build": {"wood": 150, "metal": 150, "Forge": 3}}, 6: {"max w_s": 15, "jun": 12, "pro": 16, "build": {"wood": 150, "metal": 100}}, 7: {"max w_s": 20, "jun": 13, "pro": 17, "build": {"wood": 200, "metal": 150}}, 8: {"max w_s": 25, "jun": 14, "pro": 18, "build": {"wood": 250, "metal": 200}}, 9: {"max w_s": 30, "jun": 15, "pro": 19, "build": {"wood": 350, "metal": 250}}, 10: {"max w_s": 50, "jun": 20, "pro": 30, "build": {"wood": 2500, "metal": 1500, "stone": 2500, "Forge": 8}}, 11: {"max w_s": 60, "jun": 20, "pro": 30, "build": {"wood": 500, "metal": 750}}, 12: {"max w_s": 70, "jun": 20, "pro": 30, "build": {"wood": 500, "metal": 800}}, 13: {"max w_s": 85, "jun": 20, "pro": 30, "build": {"wood": 550, "metal": 900}}, 14: {"max w_s": 100, "jun": 20, "pro": 30, "build": {"wood": 750, "metal": 1000}}, 15: {"max w_s": 125, "jun": 25, "pro": 40, "build": {"wood": 5000, "metal": 3000, "stone": 5000, "Forge": 15}} } def __init__(self, *args): super().__init__(*args) def assets_and_liabilities_counter(self, assets, liabilities, costs=None, profession="farmer", years=5, place=None, minimum=50, maximum=151, resource="food"): super().assets_and_liabilities_counter(assets, liabilities, {"water": 1}, profession, years, self.info, minimum, maximum, resource) def more_experience_workers(self, profession="farmer"): super().more_experience_workers(profession) @staticmethod def building_a_new_facility(place, i_n=None, obj=None, name=None): return ResourceFacility.building_a_new_facility(place, i_n=Farm.info, obj=Farm, name="Farm") def upgrade_the_facility(self, place, forge_level, i_n=None): return ResourceFacility.upgrade_the_facility( self, place, forge_level, i_n=Farm.info) class HuntingHouse(ResourceFacility): """ Making food by hunting prey. All information about hunting houses are in the {info} {level: {information}}. def production_and_costs() ::: total production of food and total costs of wood and metal from 1 hunting house. Worker :: hunter, "pro" if worker.employment_history["hunter"] >= 5. """ info = { 1: {"max w_s": 2, "jun": 2.5, "pro": 5, "build": {"wood": 50}}, 2: {"max w_s": 3, "jun": 2.5, "pro": 5.3, "build": {"wood": 100}}, 3: {"max w_s": 4, "jun": 2.5, "pro": 5.6, "build": {"wood": 150}}, 4: {"max w_s": 5, "jun": 2.5, "pro": 6, "build": {"wood": 200}}, 5: {"max w_s": 10, "jun": 5, "pro": 10, "build": {"wood": 500, "metal": 250, "stone": 250, "Forge": 3}}, 6: {"max w_s": 15, "jun": 5, "pro": 10.5, "build": {"wood": 500, "metal": 150}}, 7: {"max w_s": 20, "jun": 5, "pro": 11, "build": {"wood": 500, "metal": 200}}, 8: {"max w_s": 25, "jun": 5, "pro": 11.5, "build": {"wood": 500, "metal": 250}}, 9: {"max w_s": 35, "jun": 5, "pro": 12, "build": {"wood": 600, "metal": 300}}, 10: {"max w_s": 50, "jun": 7.5, "pro": 15, "build": {"wood": 1000, "metal": 500, "stone": 500, "Forge": 8}} } def __init__(self, *args): super().__init__(*args) def assets_and_liabilities_counter(self, assets, liabilities, costs=None, profession="hunter", years=5, place=None, minimum=70, maximum=131, resource="food"): super().assets_and_liabilities_counter(assets, liabilities, costs, profession, years, self.info, minimum, maximum, resource) def more_experience_workers(self, profession="hunter"): super().more_experience_workers(profession) @staticmethod def building_a_new_facility(place, i_n=None, obj=None, name=None): return ResourceFacility.building_a_new_facility(place, i_n=HuntingHouse.info, obj=HuntingHouse, name="Hunting house") def upgrade_the_facility(self, place, forge_level, i_n=None): return ResourceFacility.upgrade_the_facility( self, place, forge_level, i_n=HuntingHouse.info) class Port(ResourceFacility): """ Making food by fishing. All information about ports are in the {info} {level: {information}}. def production_and_costs() ::: total production of food and total costs of wood and metal from 1 port. Worker :: fisher, "pro" if worker.employment_history["fisher"] >= 3. """ info = { 1: {"max w_s": 3, "jun": 3, "pro": 5, "build": {"wood": 250}}, 2: {"max w_s": 4, "jun": 3, "pro": 5.2, "build": {"wood": 100}}, 3: {"max w_s": 5, "jun": 3, "pro": 5.4, "build": {"wood": 150}}, 4: {"max w_s": 7, "jun": 3, "pro": 5.7, "build": {"wood": 250}}, 5: {"max w_s": 10, "jun": 5, "pro": 10, "build": {"wood": 1000, "metal": 500, "stone": 1000, "Forge": 5}}, 6: {"max w_s": 15, "jun": 5, "pro": 10.5, "build": {"wood": 500, "metal": 50}}, 7: {"max w_s": 20, "jun": 5, "pro": 11, "build": {"wood": 500, "metal": 50}}, 8: {"max w_s": 25, "jun": 5, "pro": 11.5, "build": {"wood": 600, "metal": 75}}, 9: {"max w_s": 35, "jun": 5, "pro": 12, "build": {"wood": 600, "metal": 75}}, 10: {"max w_s": 50, "jun": 8, "pro": 19, "build": {"wood": 2000, "metal": 1000, "stone": 2500, "Forge": 10}}, 11: {"max w_s": 70, "jun": 8, "pro": 20, "build": {"wood": 750, "metal": 100}}, 12: {"max w_s": 100, "jun": 10, "pro": 25, "build": {"wood": 2500, "metal": 1500, "stone": 500, "Forge": 12}} } def __init__(self, *args): super().__init__(*args) def assets_and_liabilities_counter(self, assets, liabilities, costs=None, profession="fisher", years=3, place=None, minimum=85, maximum=116, resource="food"): super().assets_and_liabilities_counter(assets, liabilities, costs, profession, years, self.info, minimum, maximum, resource) def more_experience_workers(self, profession="fisher"): super().more_experience_workers(profession) @staticmethod def building_a_new_facility(place, i_n=None, obj=None, name=None): return ResourceFacility.building_a_new_facility(place, i_n=Port.info, obj=Port, name="Port") def upgrade_the_facility(self, place, forge_level, i_n=None): return ResourceFacility.upgrade_the_facility( self, place, forge_level, i_n=Port.info) class Sawmill(ResourceFacility): """ Making wood by chopping forest. All information about sawmills are in the {info} {level: {information}}. def production_and_costs() ::: total production of wood and total costs of metal from 1 sawmill. Worker :: chopper, "pro" if worker.employment_history["chopper"] >= 8. """ info = { 1: {"max w_s": 5, "jun": 5, "pro": 7.5, "build": {"wood": 50}}, 2: {"max w_s": 7, "jun": 5.2, "pro": 8, "build": {"wood": 75}}, 3: {"max w_s": 9, "jun": 5.4, "pro": 8.5, "build": {"wood": 100}}, 4: {"max w_s": 12, "jun": 5.7, "pro": 9, "build": {"wood": 100, "metal": 100, "Forge": 1}}, 5: {"max w_s": 20, "jun": 6, "pro": 10, "build": {"wood": 150, "metal": 50}}, 6: {"max w_s": 30, "jun": 6.3, "pro": 11, "build": {"wood": 200, "metal": 100}}, 7: {"max w_s": 40, "jun": 6.7, "pro": 12, "build": {"wood": 250, "metal": 150}}, 8: {"max w_s": 50, "jun": 7.1, "pro": 13, "build": {"wood": 250, "metal": 250}}, 9: {"max w_s": 60, "jun": 7.5, "pro": 14, "build": {"wood": 250, "metal": 500}}, 10: {"max w_s": 70, "jun": 10, "pro": 20, "build": {"wood": 1000, "metal": 2500, "stone": 2500, "Forge": 8}}, 11: {"max w_s": 80, "jun": 10.5, "pro": 22, "build": {"metal": 400, "stone": 250}}, 12: {"max w_s": 90, "jun": 11, "pro": 24, "build": {"metal": 500, "stone": 250}}, 13: {"max w_s": 100, "jun": 11.5, "pro": 26, "build": {"metal": 650, "stone": 250}}, 14: {"max w_s": 125, "jun": 12, "pro": 28, "build": {"metal": 750, "stone": 500}}, 15: {"max w_s": 150, "jun": 20, "pro": 40, "build": {"wood": 2500, "metal": 5000, "stone": 5000, "Forge": 15}} } def __init__(self, *args): super().__init__(*args) def assets_and_liabilities_counter(self, assets, liabilities, costs=None, profession="chopper", years=8, place=None, minimum=95, maximum=106, resource="wood"): super().assets_and_liabilities_counter(assets, liabilities, costs, profession, years, self.info, minimum, maximum, resource) def more_experience_workers(self, profession="chopper"): super().more_experience_workers(profession) @staticmethod def building_a_new_facility(place, i_n=None, obj=None, name=None): return ResourceFacility.building_a_new_facility( place=place, i_n=Sawmill.info, obj=Sawmill, name="Sawmill") def upgrade_the_facility(self, place, forge_level, i_n=None): return ResourceFacility.upgrade_the_facility( self, place, forge_level, i_n=Sawmill.info) class Mine(ResourceFacility): """ Extracting ore by mining. All information about mines are in the {info} {level: {information}}. def production_and_costs() ::: total production of ore and total costs of metal from 1 mine. Worker :: miner, "pro" if worker.employment_history["miner"] >= 10. """ info = { 1: {"max w_s": 5, "jun": 5, "pro": 10, "build": {"wood": 150}}, 2: {"max w_s": 7, "jun": 5, "pro": 10, "build": {"wood": 200}}, 3: {"max w_s": 10, "jun": 5, "pro": 10, "build": {"wood": 250, "metal": 50, "Forge": 1}}, 4: {"max w_s": 15, "jun": 5, "pro": 10, "build": {"wood": 250, "metal": 100}}, 5: {"max w_s": 20, "jun": 10, "pro": 15, "build": {"wood": 500, "metal": 250, "stone": 250, "Forge": 2}}, 6: {"max w_s": 25, "jun": 10, "pro": 15, "build": {"wood": 300, "metal": 300}}, 7: {"max w_s": 35, "jun": 10, "pro": 15, "build": {"wood": 300, "metal": 300}}, 8: {"max w_s": 50, "jun": 10, "pro": 15, "build": {"wood": 350, "metal": 350}}, 9: {"max w_s": 75, "jun": 10, "pro": 15, "build": {"wood": 500, "metal": 500}}, 10: {"max w_s": 100, "jun": 15, "pro": 30, "build": {"wood": 2500, "metal": 2000, "stone": 2000, "Forge": 10}} } def __init__(self, *args): super().__init__(*args) def assets_and_liabilities_counter(self, assets, liabilities, costs=None, profession="miner", years=10, place=None, minimum=95, maximum=106, resource="ore"): super().assets_and_liabilities_counter(assets, liabilities, costs, profession, years, self.info, minimum, maximum, resource) def more_experience_workers(self, profession="miner"): super().more_experience_workers(profession) @staticmethod def building_a_new_facility(place, i_n=None, obj=None, name=None): return ResourceFacility.building_a_new_facility(place, i_n=Mine.info, obj=Mine, name="Mine") def upgrade_the_facility(self, place, forge_level, i_n=None): return ResourceFacility.upgrade_the_facility( self, place, forge_level, i_n=Mine.info) class Quarry(ResourceFacility): """ Extracting stone by mining. All information about quarries are in the {info} {level: {information}}. def production_and_costs() ::: total production of stone and total costs of metal from 1 quarry. Worker :: miner, "pro" if worker.employment_history["miner"] >= 10. """ info = { 1: {"max w_s": 5, "jun": 5, "pro": 10, "build": {"wood": 150}}, 2: {"max w_s": 7, "jun": 5, "pro": 10, "build": {"wood": 200}}, 3: {"max w_s": 10, "jun": 5, "pro": 10, "build": {"wood": 250, "metal": 50, "Forge": 1}}, 4: {"max w_s": 15, "jun": 5, "pro": 10, "build": {"wood": 250, "metal": 200}}, 5: {"max w_s": 20, "jun": 10, "pro": 15, "build": {"wood": 500, "metal": 250, "stone": 250, "Forge": 2}}, 6: {"max w_s": 25, "jun": 10, "pro": 15, "build": {"wood": 300, "metal": 300}}, 7: {"max w_s": 35, "jun": 10, "pro": 15, "build": {"wood": 300, "metal": 300}}, 8: {"max w_s": 50, "jun": 10, "pro": 15, "build": {"wood": 350, "metal": 350}}, 9: {"max w_s": 75, "jun": 10, "pro": 15, "build": {"wood": 500, "metal": 500}}, 10: {"max w_s": 100, "jun": 15, "pro": 30, "build": {"wood": 2500, "metal": 2000, "stone": 2000, "Forge": 10}} } def __init__(self, *args): super().__init__(*args) def assets_and_liabilities_counter(self, assets, liabilities, costs=None, profession="miner", years=10, place=None, minimum=95, maximum=106, resource="stone"): super().assets_and_liabilities_counter(assets, liabilities, costs, profession, years, self.info, minimum, maximum, resource) def more_experience_workers(self, profession="miner"): super().more_experience_workers(profession) @staticmethod def building_a_new_facility(place, i_n=None, obj=None, name=None): return ResourceFacility.building_a_new_facility(place, i_n=Quarry.info, obj=Quarry, name="Quarry") def upgrade_the_facility(self, place, forge_level, i_n=None): return ResourceFacility.upgrade_the_facility( self, place, forge_level, i_n=Quarry.info) class Forge(ResourceFacility): """ Forge are used for getting metal from ore, upgrading facilities, making and repairing new equipment. It takes 2 ore for making 1 metal. All information about forges are in the {info} {level: {information}}. def production_and_costs() ::: total production of metal and total costs of ore, wood and metal from 1 forge. Worker :: blacksmith, "pro" if worker.employment_history["blacksmith"] >= 15. """ info = { 1: {"max w_s": 2, "jun": 1, "pro": 2.5, "build": {"wood": 500}}, 2: {"max w_s": 3, "jun": 1, "pro": 2.8, "build": {"wood": 100}}, 3: {"max w_s": 5, "jun": 1, "pro": 3.1, "build": {"wood": 150}}, 4: {"max w_s": 7, "jun": 1, "pro": 3.5, "build": {"wood": 200}}, 5: {"max w_s": 10, "jun": 5, "pro": 10, "build": {"wood": 1000, "metal": 150, "stone": 250}}, 6: {"max w_s": 15, "jun": 5, "pro": 10.5, "build": {"wood": 250, "metal": 100}}, 7: {"max w_s": 20, "jun": 5, "pro": 11, "build": {"wood": 250, "metal": 150}}, 8: {"max w_s": 25, "jun": 5, "pro": 11.5, "build": {"wood": 250, "metal": 200}}, 9: {"max w_s": 35, "jun": 5, "pro": 12, "build": {"wood": 250, "metal": 250}}, 10: {"max w_s": 50, "jun": 10, "pro": 20, "build": {"wood": 2500, "metal": 1500, "stone": 2500}}, 11: {"max w_s": 65, "jun": 10, "pro": 21, "build": {"wood": 500, "metal": 500, "stone": 750}}, 12: {"max w_s": 80, "jun": 10, "pro": 22, "build": {"wood": 500, "metal": 500, "stone": 1000}}, 13: {"max w_s": 100, "jun": 10, "pro": 23, "build": {"wood": 750, "metal": 1000, "stone": 1500}}, 14: {"max w_s": 125, "jun": 10, "pro": 24, "build": {"wood": 1000, "metal": 1500, "stone": 2000}}, 15: {"max w_s": 150, "jun": 15, "pro": 30, "build": {"wood": 5000, "metal": 5000, "stone": 10000}} } def __init__(self, *args): super().__init__(*args) def assets_and_liabilities_counter(self, assets, liabilities, costs=None, profession="blacksmith", years=15, place=None, minimum=95, maximum=106, resource="metal"): super().assets_and_liabilities_counter(assets, liabilities, {"ore": 2}, profession, years, self.info, minimum, maximum, resource) def more_experience_workers(self, profession="blacksmith"): super().more_experience_workers(profession) @staticmethod def building_a_new_facility(place, i_n=None, obj=None, name=None): return ResourceFacility.building_a_new_facility(place, i_n=Forge.info, obj=Forge, name="Forge") def upgrade_the_facility(self, place, forge_level, i_n=None): return ResourceFacility.upgrade_the_facility( self, place, forge_level, i_n=Forge.info) class House: """ House is a place, where people live. All houses have a unique number-key which is Environment.house_index. The __len__ representation is a number of alive people, living in the house. All information about houses are in the {info} {level: {information}}. """ info = { 1: {"max p_l": 4, "cost: wood": 0.9, "build": {"wood": 50}}, 2: {"max p_l": 8, "cost: wood": 0.8, "build": {"wood": 300, "metal": 50, "Forge": 1}}, 3: {"max p_l": 14, "cost: wood": 0.7, "build": {"wood": 750, "metal": 150, "Forge": 3}}, 4: {"max p_l": 22, "cost: wood": 0.6, "build": {"wood": 1000, "metal": 250, "stone": 1000, "Forge": 5}}, 5: {"max p_l": 32, "cost: wood": 0.5, "build": {"wood": 1500, "metal": 500, "stone": 2000, "Forge": 8}} } def __init__(self, index, level=1): self.index = index # int : is a Environment.house_index self.level = level # int : level of a facility self.tenants = [] # an array of people, who live in this house def __len__(self): return len(self.tenants) def __str__(self): return f"house {self.index} ({self.level}), amount of tenants = {len(self)}" @staticmethod def a_house_builder(place, family_flag=True, human_flag=False): wood = place.resources["wood"] - House.info[1]["build"]["wood"] if wood >= 0: place.resources["wood"] -= House.info[1]["build"]["wood"] house = House(place.house_index) if family_flag: for index, family in place.families.items(): if not family["house"]: family["house"] = house.index for array in (family["parents"], family["children"]): for human in array: human.house_index = house.index house.tenants.append(human) break elif human_flag: for array in (place.adults, place.elders): for human in array: if not human.house_index: human.house_index = house.index house.tenants.append(human) break return house def upgrade_the_house(self, place, f_l): upgrade_flag = True for res, value in self.info[self.level + 1]["build"].items(): if res == "Forge": if f_l < value: upgrade_flag = False elif place.resources[res] - value < 0: upgrade_flag = False if upgrade_flag: self.level += 1 for res, value in self.info[self.level]["build"].items(): if res != "Forge": place.resources[res] -= value class Human: """ Human is a alive create, who is trying to make his / her life. They try to make new families and children. They have resources for building facilities, like houses, where they can live, or buildings, where they can make other resources. For there life, they need 1 water, 1 food and, depends on the level of the house they are living in, 1 - 0.5 wood. """ def __init__(self, genome=None, surname=None, age=0, wish_attr=0.5, family_parent_index=None, family_history="", house_index=None): # base human attributes self.genome = genome or "".join([chr(rdr(65, 91)) for _ in range(46)]) # str : 46 upper letters value as a unique human code self.sex = "M" if rdm() >= 0.5 else "F" # str : Male or Female self.age = age # int : human years, 0 when was born self.death = 0.75 # int : number, which used in dead_function_by_age() function with open("list_of_names.json", "r") as names_dict: names = load(names_dict) self.name = names["name_man"][rdr(0, 340)] if self.sex == "M" \ else names["name_woman"][rdr(0, 204)] # str : human name self.surname = surname or names["surname"][rdr(0, 60)] # str : human surname # attributes for family self.attr = float("{:.2f}".format(wb(2.5, 2.5))) # float : attractiveness self.wish_attr = wish_attr # float : wish attractiveness self.marriage = None # Human() : None if not marriage else husband or wife self.family_index = None # int : is a Environment.family_index self.family_parent_index = family_parent_index # int : an index of the family # where human() is a child self.family_history = family_history # str : family history of the human self.indexes = [] # all family_indexes of a human # attributes for profession self.employment_history = {"builder": 0, "farmer": 0, "hunter": 0, "fisher": 0, "engineer": 0, "chopper": 0, "miner": 0, "blacksmith": 0} self.builder_status = False # bool : True if in Environment.brigades self.job_status = None # int : if ResourceFacility.index, else None # attribute for houses self.house_index = house_index # int : index of the human house def __str__(self): return f"{self.surname} {self.name}, {self.sex}, {self.age}, family = " \ f"{self.family_index}, house = {self.house_index}, history = " \ f"'{self.family_history}', genome = {self.genome}" @staticmethod def dead_function_by_age(place): for copies in (place.kids[:], place.adults[:], place.elders[:]): counter = 0 for number, human in enumerate(copies): if human.age < 25: bones = abs(2.626225 * rdm() - (human.age / 24950)) / 3.5 elif human.age < 61: bones = (2.3252332 * rdm() + ((human.age - 26) / 16250)) / 3.1 else: bones = (1.726726 * rdm() + ((human.age - 61) / 75)) / 2.3 if bones >= human.death: if human.age < 18: place.grave.append(place.kids.pop(number - counter)) elif human.age < 55: place.grave.append(place.adults.pop(number - counter)) elif human.age >= 55: place.grave.append(place.elders.pop(number - counter)) counter += 1 for corpse in place.grave: if corpse.family_parent_index: place.families[corpse.family_parent_index]["children"].remove(corpse) corpse.family_parent_index = None if corpse.marriage: for family in corpse.indexes: place.families[family]["parents"].remove(corpse) corpse.marriage.marriage = None corpse.marriage, corpse.indexes, corpse.family_index = None, [], None if not corpse.marriage and corpse.indexes: for family in corpse.indexes: place.families[family]["parents"].remove(corpse) corpse.indexes, corpse.family_index = [], None if corpse.house_index: place.houses[corpse.house_index].tenants.remove(corpse) corpse.house_index = None if corpse.job_status: if type(corpse.job_status) is int: place.buildings[corpse.job_status].workers.remove(corpse) corpse.job_status = None elif type(corpse.job_status) is bool: place.brigades.remove(corpse) corpse.job_status = None @staticmethod def removing_all_families_without_parents(place): for number, family in place.families.copy().items(): if len(family["parents"]) == 0: for child in family["children"]: child.family_parent_index = None del place.families[number] def attractiveness_parameter_changer(self): return float("{:.2f}".format(self.attr + ((rdm() / 2) * ((50 - self.age) / 100)))) def wish_attractiveness_parameter_changer(self): if self.age > 35 and not self.marriage: wish = float("{:.2f}".format(self.wish_attr + (rdm() * ((35 - self.age) / 200)))) else: wish = float("{:.2f}".format(self.wish_attr + (rdm() * ((50 - self.age) / 200)))) if wish < 0: return 0 return wish @staticmethod def genome_checker(genome_1, genome_2): counter, same = 0, 0 for _ in range(23): if genome_1[counter:counter + 2] == genome_2[counter:counter + 2]: same += 2 counter += 2 if same / 46 >= 0.15: return False return True @staticmethod def people_want_to_make_families(place): for human in place.adults: if not human.marriage: for challenger in place.adults: if not challenger.marriage and challenger.sex != human.sex \ and Human.genome_checker(human.genome, challenger.genome) \ and human.attr >= challenger.wish_attr \ and challenger.attr >= human.wish_attr: if rdm() >= (0.6 + (abs(human.age - challenger.age) / 100)): place.families[place.family_index] = { "house": None, "parents": [human, challenger], "children": []} human.marriage, challenger.marriage = challenger, human for parent in (human, challenger): parent.indexes.append(place.family_index) human.family_index = place.family_index challenger.family_index = place.family_index human.family_history += f"{place.family_index} " challenger.family_history += f"{place.family_index} " Human.new_house_for_a_new_family(place, human, challenger) place.family_index += 1 break continue @staticmethod def genome_parameter_for_making_a_new_human_via_a_family(genome_1, genome_2): genome, counter = "", 0 for _ in range(23): genome += chc([genome_1[counter:counter + 2], genome_2[counter:counter + 2]]) counter += 2 return genome @staticmethod def new_house_for_a_new_family(place, human, challenger): if human.house_index and len(place.houses[human.house_index].tenants) == 1: challenger.house_index = human.house_index place.houses[human.house_index].tenants.append(challenger) place.families[place.family_index]["house"] = human.house_index return if challenger.house_index and \ len(place.houses[challenger.house_index].tenants) == 1: human.house_index = challenger.house_index place.houses[challenger.house_index].tenants.append(human) place.families[place.family_index]["house"] = challenger.house_index return @staticmethod def baby_maker_function_via_a_family(gen_1, gen_2, surname, index, family_history, house_index, place): genome = Human.genome_parameter_for_making_a_new_human_via_a_family(gen_1, gen_2) baby = Human(genome=genome, surname=surname, family_parent_index=index, family_history=family_history, house_index=house_index) place.kids.append(baby) place.families[index]["children"].append(baby) if house_index: place.houses[house_index].tenants.append(baby) @staticmethod def people_want_to_make_new_people(place): for index, fml in place.families.items(): if len(fml["parents"]) == 2 and rdm() \ >= (0.8 + (sqrt(len(fml["children"])) * 5 / 100)): if fml["parents"][0].age in range(18, 56) and \ fml["parents"][1].age in range(18, 56): gen_1, gen_2, surname, family_history = None, None, None, None for parent in fml["parents"]: if parent.sex == "M": gen_1 = parent.genome surname = parent.surname family_history = parent.family_history else: gen_2 = parent.genome Human.baby_maker_function_via_a_family(gen_1, gen_2, surname, index, family_history, fml["house"], place) if rdm() >= 0.99: Human.baby_maker_function_via_a_family(gen_1, gen_2, surname, index, family_history, fml["house"], place) @staticmethod def moving_people_from_array_to_array(place): counter = 0 for number, child in enumerate(place.kids[:]): if child.age >= 18: place.adults.append(place.kids.pop(number - counter)) counter += 1 counter = 0 for number, adult in enumerate(place.adults[:]): if adult.age >= 55: place.elders.append(place.adults.pop(number - counter)) counter += 1 @staticmethod def people_want_to_build_new_facilities(place, need): have = 0 for builder in place.brigades: have += 2 if builder.employment_history["builder"] >= 10 else 1 builder.employment_history["builder"] += 1 place.brigades.remove(builder) builder.builder_status = False if have >= need: return True return False @staticmethod def people_did_not_build_any_buildings(place): for builder in place.brigades: builder.builder_status = False place.brigades.remove(builder) def integer_checker(question=None, value=None, message=None): if question: print(question) text = value or input() while True: try: number = int(text) if number < 0: if message: print(f"'{message}' >>> '{number}' is not acceptable. " f"Should be at least equal to 0. Please, try again.") else: print(f"'{number}' is not acceptable. " f"Should be at least equal to 0. Please, try again.") else: return number except ValueError: if message: print(f"'{message}' >>> '{text}' is not acceptable. " f"Please, print a number (int).") else: print(f"'{text}' is not acceptable. Please, print a number (int).") text = input() def average_life_function(place): if not place.grave: return 0 else: average_life = 0 for dead_bodies in place.grave: average_life += dead_bodies.age return float("{:.2f}".format(average_life / len(place.grave))) def data_collecting_function(seconds): global Earth Earth.data["years"] = Earth.year Earth.data["seconds per year"].append(seconds) for city in Earth.world: city.data["kids"].append(len(city.kids)) city.data["adults"].append(len(city.adults)) city.data["elders"].append(len(city.elders)) city.data["people in the city"].append(len(city)) city.data["families"].append(len(city.families)) city.data["grave"].append(len(city.grave)) city.data["average life"] = average_life_function(city) city.data["water"].append(round(city.water, 2)) city.data["food"].append(round(city.food, 2)) city.data["wood"].append(round(city.wood, 2)) city.data["ore"].append(round(city.ore, 2)) city.data["metal"].append(round(city.metal, 2)) city.data["stone"].append(round(city.stone, 2)) city.data["buildings"].append(len(city.buildings)) city.data["houses"].append(len(city.houses)) def printing(): global Earth print(Earth) print(f"It took {Earth.data['seconds per year'][-1]} seconds " f"for making {Earth.year} year.") table = PrettyTable(padding_width=2) table.add_column("", ["People", "Families", "Elders", "Adults", "Kids", "Corpses", "Average life", "Water", "Food", "Wood", "Ore", "Metal", "Stone", "Buildings", "Houses"]) for v in Earth.world: table.add_column(v.name, [str(v.data["people in the city"][-1]), str(v.data["families"][-1]), str(v.data["elders"][-1]), str(v.data["adults"][-1]), str(v.data["kids"][-1]), str(v.data["grave"][-1]), str(v.data["average life"]), str(v.data["water"][-1]), str(v.data["food"][-1]), str(v.data["wood"][-1]), str(v.data["ore"][-1]), str(v.data["metal"][-1]), str(v.data["stone"][-1]), str(v.data["buildings"][-1]), str(v.data["houses"][-1])]) print(table, end="\n\n") def city_picker_for_more_info(message): global Earth names = [rr_rr.name for rr_rr in Earth.world] print(f"'{message}' Please, choose a city (any register) : {', '.join(names)}") while True: city_pick = str(input()).title() if city_pick == "": print("You can't pass a space blanked name. Please, try again.") elif city_pick not in names: print(f"{city_pick} city doesn't exist. Please, try again.") else: index = names.index(city_pick) return Earth.world[index] if __name__ == "__main__": Earth = World("Earth") # creating the World Object with "Earth" name print(f"The world with the name '{Earth.name}' was created ...\n") Earth.cities_creator(integer_checker( question="Please, print how much cities do you want to have.")) looping = False # bool : if False -> press <enter> button for making a new year, # if True -> passing years depends on loop_ration loop_ratio = 0 # int : if looping = True, showing how much years computer # automatically will count while True: while looping: for _ in range(loop_ratio): start = tm() Earth.year += 1 Earth.year_maker() data_collecting_function(tm() - start) printing() else: looping = False start = tm() Earth.year += 1 Earth.year_maker() data_collecting_function(tm() - start) printing() flag = True while flag: print("Commands: city, kid, adult, elder, " "family, corpse, history, request, save, exit, (int).") command = input("Your command ..........................").lower() if command == "city": if len(Earth.world) == 1: city_city = Earth.world[0] else: city_city = city_picker_for_more_info("city") print(city_city) if command == "kid": if len(Earth.world) == 1: kids_from_the_city = Earth.world[0] else: kids_from_the_city = city_picker_for_more_info("kid") for xx_xx in kids_from_the_city.kids: print(xx_xx) print() if command == "adult": if len(Earth.world) == 1: adults_from_the_city = Earth.world[0] else: adults_from_the_city = city_picker_for_more_info("adult") for xx_xx in adults_from_the_city.adults: print(xx_xx) print() if command == "elder": if len(Earth.world) == 1: elders_from_the_city = Earth.world[0] else: elders_from_the_city = city_picker_for_more_info("elder") for xx_xx in elders_from_the_city.elders: print(xx_xx) print() if command == "family": if len(Earth.world) == 1: family_from_the_city = Earth.world[0] else: family_from_the_city = city_picker_for_more_info("family") if len(family_from_the_city.families) > 0: print("Families : ", end="\n\n") for ind, fam in family_from_the_city.families.items(): print(f"Family with {ind} index") print("Parents") for par in fam["parents"]: print(par) if len(fam["children"]) > 0: print("Children") for cld in fam["children"]: print(cld) print() if command == "corpse": if len(Earth.world) == 1: dead_from_the_city = Earth.world[0] else: dead_from_the_city = city_picker_for_more_info("corpse") if len(dead_from_the_city.grave) > 0: print("Grave") for dead_b in dead_from_the_city.grave: print(dead_b) print() if command == "history": if len(Earth.world) == 1: the_city_history = Earth.world[0] else: the_city_history = city_picker_for_more_info("history") for h in the_city_history.kids: print(f"{h.surname} {h.name}, {h.sex}, {h.age}, parent index = " f"{h.family_parent_index}, family history = " f"{h.family_history}") for ooo in (the_city_history.adults, the_city_history.elders): for o in ooo: if o.marriage: print(f"{o.surname} {o.name}, {o.sex}, {o.age}, marriage = " f"{o.marriage.surname} {o.marriage.name}, " f"parent index = {o.family_parent_index}, " f"family history = {o.family_history}") else: print(f"{o.surname} {o.name}, {o.sex}, {o.age}, " f"parent index = {o.family_parent_index}, " f"family history = {o.family_history}") print() if command == "request": for dd_ss in Earth.world: print(f"City : {dd_ss.name}\n") print(f"Queues : \n[{', '.join(map(str, dd_ss.queue))}]") print(f"Alerts : \n[{', '.join(map(str, dd_ss.alert))}]") print(f"Non_urgent : \n[{', '.join(map(str, dd_ss.non_urgent))}]") print(f"Plan : \n[{', '.join(map(str, dd_ss.plan))}]") print("-" * 103) if command == "save": with open("data_for_graph.json", "w") as file: temporary_dict = {"years": Earth.data["years"], "seconds per year": Earth.data["seconds per year"]} for jj_jj in Earth.world: temporary_dict[jj_jj.name] = jj_jj.data dump(temporary_dict, file) if command.isdigit(): looping, loop_ratio, flag = True, int(command), False if command == "": flag = False if command == "exit": exit()
Java
UTF-8
1,272
3.484375
3
[]
no_license
package org.dimigo.collection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MelonGenreChart { public static void main(String[] args) { Map<String,List<Music>> map = new HashMap<>(); System.out.println("-- << 멜론 장르별 챠트 >> --"); List<Music> list = new ArrayList<Music>(); map.put("발라드",list); list.add(new Music("팔레트","아이유")); list = new ArrayList<>(); map.put("댄스", list); list.add(new Music("I LUV IT","PSY")); list.add(new Music("맞지","언니쓰")); printMap(map); System.out.println(); System.out.println("-- << 댄스 2위 곡 변경 >> --"); map.get("댄스").set(1, new Music("SIGNAL","트와이스")); printMap(map); System.out.println(); System.out.println("-- << 댄스 1위 곡 삭제 >> --"); map.get("댄스").remove(0); printMap(map); System.out.println(); System.out.println("-- << 전체 리스트 삭제 >> --"); map.clear(); printMap(map); } public static void printMap(Map<String, List<Music> > map){ for(String key : map.keySet()){ int i=1; System.out.println("[" + key + "]"); for(Music m : map.get(key)){ System.out.println(i +". " + m); i++; } } } }
Markdown
UTF-8
1,206
2.578125
3
[ "MIT" ]
permissive
# React Native - The Practical Guide - 02.Diving into the Basics - [rn-basics - Course Goals App](https://github.com/mdamyanova/Udemy-Courses/tree/master/React%20Native%20-%20The%20Practical%20Guide/rn-basics) - working with Components, Styles, Flexbox and Scrollable view - 04.Components, Styling, Layouts - [rn-guess-number - Guess the Number App](https://github.com/mdamyanova/Udemy-Courses/tree/master/React%20Native%20-%20The%20Practical%20Guide/rn-guess-number) - working with basics + Headers, User Input, Alerts, Screens - 06.Navigation and React Navigation - [rn-meals - The Meals App](https://github.com/mdamyanova/Udemy-Courses/tree/master/React%20Native%20-%20The%20Practical%20Guide/rn-meals) - working with basics + advanced styling + Navigation + Menu + Redux - 08.The Shop App - [rn-shop - The Shop App](https://github.com/mdamyanova/Udemy-Courses/tree/master/React%20Native%20-%20The%20Practical%20Guide/rn-shop) - exercise app + http requests + authentication - 12.Native Device Features - [rn-places - Places App](https://github.com/mdamyanova/Udemy-Courses/tree/master/React%20Native%20-%20The%20Practical%20Guide/rn-places) - exercise app + camera + location + maps + SQLite
C++
UTF-8
815
2.546875
3
[]
no_license
#ifndef __ModuleWindow_H__ #define __ModuleWindow_H__ #include "Module.h" #include "SDL/include/SDL.h" #include "Module.h" #include "Globals.h" class Application; class ModuleWindow : public Module { public: //The window we'll be rendering to SDL_Window * window; public: ModuleWindow() {}; ~ModuleWindow() {}; // Called before quitting bool Init() { LOG("Init SDL window & surface"); bool ret = true; if (SDL_Init(SDL_INIT_VIDEO) < 0) { LOG("SDL_VIDEO could not initialize! SDL_Error: %s\n", SDL_GetError()); ret = false; } else { SDL_Window* window = SDL_CreateWindow("window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1200, 800, 0); } return ret; } // Called before quitting bool CleanUp() { SDL_DestroyWindow(window); } }; #endif // __ModuleWindow_H__
Java
UTF-8
14,672
1.90625
2
[]
no_license
package fr.ippon.kompetitors.web.rest; import fr.ippon.kompetitors.Kompetitors2App; import fr.ippon.kompetitors.config.TestSecurityConfiguration; import fr.ippon.kompetitors.domain.ListTechPartners; import fr.ippon.kompetitors.repository.ListTechPartnersRepository; import fr.ippon.kompetitors.service.ListTechPartnersService; import fr.ippon.kompetitors.service.dto.ListTechPartnersDTO; import fr.ippon.kompetitors.service.mapper.ListTechPartnersMapper; import fr.ippon.kompetitors.web.rest.errors.ExceptionTranslator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Base64Utils; import org.springframework.validation.Validator; import javax.persistence.EntityManager; import java.util.List; import static fr.ippon.kompetitors.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Integration tests for the {@link ListTechPartnersResource} REST controller. */ @SpringBootTest(classes = {Kompetitors2App.class, TestSecurityConfiguration.class}) public class ListTechPartnersResourceIT { private static final String DEFAULT_VALUE = "AAAAAAAAAA"; private static final String UPDATED_VALUE = "BBBBBBBBBB"; private static final byte[] DEFAULT_IMAGE = TestUtil.createByteArray(1, "0"); private static final byte[] UPDATED_IMAGE = TestUtil.createByteArray(1, "1"); private static final String DEFAULT_IMAGE_CONTENT_TYPE = "image/jpg"; private static final String UPDATED_IMAGE_CONTENT_TYPE = "image/png"; @Autowired private ListTechPartnersRepository listTechPartnersRepository; @Autowired private ListTechPartnersMapper listTechPartnersMapper; @Autowired private ListTechPartnersService listTechPartnersService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; @Autowired private Validator validator; private MockMvc restListTechPartnersMockMvc; private ListTechPartners listTechPartners; @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); final ListTechPartnersResource listTechPartnersResource = new ListTechPartnersResource(listTechPartnersService); this.restListTechPartnersMockMvc = MockMvcBuilders.standaloneSetup(listTechPartnersResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter) .setValidator(validator).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static ListTechPartners createEntity(EntityManager em) { ListTechPartners listTechPartners = new ListTechPartners() .value(DEFAULT_VALUE) .image(DEFAULT_IMAGE) .imageContentType(DEFAULT_IMAGE_CONTENT_TYPE); return listTechPartners; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static ListTechPartners createUpdatedEntity(EntityManager em) { ListTechPartners listTechPartners = new ListTechPartners() .value(UPDATED_VALUE) .image(UPDATED_IMAGE) .imageContentType(UPDATED_IMAGE_CONTENT_TYPE); return listTechPartners; } @BeforeEach public void initTest() { listTechPartners = createEntity(em); } @Test @Transactional public void createListTechPartners() throws Exception { int databaseSizeBeforeCreate = listTechPartnersRepository.findAll().size(); // Create the ListTechPartners ListTechPartnersDTO listTechPartnersDTO = listTechPartnersMapper.toDto(listTechPartners); restListTechPartnersMockMvc.perform(post("/api/list-tech-partners") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(listTechPartnersDTO))) .andExpect(status().isCreated()); // Validate the ListTechPartners in the database List<ListTechPartners> listTechPartnersList = listTechPartnersRepository.findAll(); assertThat(listTechPartnersList).hasSize(databaseSizeBeforeCreate + 1); ListTechPartners testListTechPartners = listTechPartnersList.get(listTechPartnersList.size() - 1); assertThat(testListTechPartners.getValue()).isEqualTo(DEFAULT_VALUE); assertThat(testListTechPartners.getImage()).isEqualTo(DEFAULT_IMAGE); assertThat(testListTechPartners.getImageContentType()).isEqualTo(DEFAULT_IMAGE_CONTENT_TYPE); } @Test @Transactional public void createListTechPartnersWithExistingId() throws Exception { int databaseSizeBeforeCreate = listTechPartnersRepository.findAll().size(); // Create the ListTechPartners with an existing ID listTechPartners.setId(1L); ListTechPartnersDTO listTechPartnersDTO = listTechPartnersMapper.toDto(listTechPartners); // An entity with an existing ID cannot be created, so this API call must fail restListTechPartnersMockMvc.perform(post("/api/list-tech-partners") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(listTechPartnersDTO))) .andExpect(status().isBadRequest()); // Validate the ListTechPartners in the database List<ListTechPartners> listTechPartnersList = listTechPartnersRepository.findAll(); assertThat(listTechPartnersList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void checkValueIsRequired() throws Exception { int databaseSizeBeforeTest = listTechPartnersRepository.findAll().size(); // set the field null listTechPartners.setValue(null); // Create the ListTechPartners, which fails. ListTechPartnersDTO listTechPartnersDTO = listTechPartnersMapper.toDto(listTechPartners); restListTechPartnersMockMvc.perform(post("/api/list-tech-partners") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(listTechPartnersDTO))) .andExpect(status().isBadRequest()); List<ListTechPartners> listTechPartnersList = listTechPartnersRepository.findAll(); assertThat(listTechPartnersList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void getAllListTechPartners() throws Exception { // Initialize the database listTechPartnersRepository.saveAndFlush(listTechPartners); // Get all the listTechPartnersList restListTechPartnersMockMvc.perform(get("/api/list-tech-partners?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(listTechPartners.getId().intValue()))) .andExpect(jsonPath("$.[*].value").value(hasItem(DEFAULT_VALUE))) .andExpect(jsonPath("$.[*].imageContentType").value(hasItem(DEFAULT_IMAGE_CONTENT_TYPE))) .andExpect(jsonPath("$.[*].image").value(hasItem(Base64Utils.encodeToString(DEFAULT_IMAGE)))); } @Test @Transactional public void getListTechPartners() throws Exception { // Initialize the database listTechPartnersRepository.saveAndFlush(listTechPartners); // Get the listTechPartners restListTechPartnersMockMvc.perform(get("/api/list-tech-partners/{id}", listTechPartners.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(listTechPartners.getId().intValue())) .andExpect(jsonPath("$.value").value(DEFAULT_VALUE)) .andExpect(jsonPath("$.imageContentType").value(DEFAULT_IMAGE_CONTENT_TYPE)) .andExpect(jsonPath("$.image").value(Base64Utils.encodeToString(DEFAULT_IMAGE))); } @Test @Transactional public void getNonExistingListTechPartners() throws Exception { // Get the listTechPartners restListTechPartnersMockMvc.perform(get("/api/list-tech-partners/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateListTechPartners() throws Exception { // Initialize the database listTechPartnersRepository.saveAndFlush(listTechPartners); int databaseSizeBeforeUpdate = listTechPartnersRepository.findAll().size(); // Update the listTechPartners ListTechPartners updatedListTechPartners = listTechPartnersRepository.findById(listTechPartners.getId()).get(); // Disconnect from session so that the updates on updatedListTechPartners are not directly saved in db em.detach(updatedListTechPartners); updatedListTechPartners .value(UPDATED_VALUE) .image(UPDATED_IMAGE) .imageContentType(UPDATED_IMAGE_CONTENT_TYPE); ListTechPartnersDTO listTechPartnersDTO = listTechPartnersMapper.toDto(updatedListTechPartners); restListTechPartnersMockMvc.perform(put("/api/list-tech-partners") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(listTechPartnersDTO))) .andExpect(status().isOk()); // Validate the ListTechPartners in the database List<ListTechPartners> listTechPartnersList = listTechPartnersRepository.findAll(); assertThat(listTechPartnersList).hasSize(databaseSizeBeforeUpdate); ListTechPartners testListTechPartners = listTechPartnersList.get(listTechPartnersList.size() - 1); assertThat(testListTechPartners.getValue()).isEqualTo(UPDATED_VALUE); assertThat(testListTechPartners.getImage()).isEqualTo(UPDATED_IMAGE); assertThat(testListTechPartners.getImageContentType()).isEqualTo(UPDATED_IMAGE_CONTENT_TYPE); } @Test @Transactional public void updateNonExistingListTechPartners() throws Exception { int databaseSizeBeforeUpdate = listTechPartnersRepository.findAll().size(); // Create the ListTechPartners ListTechPartnersDTO listTechPartnersDTO = listTechPartnersMapper.toDto(listTechPartners); // If the entity doesn't have an ID, it will throw BadRequestAlertException restListTechPartnersMockMvc.perform(put("/api/list-tech-partners") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(listTechPartnersDTO))) .andExpect(status().isBadRequest()); // Validate the ListTechPartners in the database List<ListTechPartners> listTechPartnersList = listTechPartnersRepository.findAll(); assertThat(listTechPartnersList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional public void deleteListTechPartners() throws Exception { // Initialize the database listTechPartnersRepository.saveAndFlush(listTechPartners); int databaseSizeBeforeDelete = listTechPartnersRepository.findAll().size(); // Delete the listTechPartners restListTechPartnersMockMvc.perform(delete("/api/list-tech-partners/{id}", listTechPartners.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isNoContent()); // Validate the database contains one less item List<ListTechPartners> listTechPartnersList = listTechPartnersRepository.findAll(); assertThat(listTechPartnersList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(ListTechPartners.class); ListTechPartners listTechPartners1 = new ListTechPartners(); listTechPartners1.setId(1L); ListTechPartners listTechPartners2 = new ListTechPartners(); listTechPartners2.setId(listTechPartners1.getId()); assertThat(listTechPartners1).isEqualTo(listTechPartners2); listTechPartners2.setId(2L); assertThat(listTechPartners1).isNotEqualTo(listTechPartners2); listTechPartners1.setId(null); assertThat(listTechPartners1).isNotEqualTo(listTechPartners2); } @Test @Transactional public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(ListTechPartnersDTO.class); ListTechPartnersDTO listTechPartnersDTO1 = new ListTechPartnersDTO(); listTechPartnersDTO1.setId(1L); ListTechPartnersDTO listTechPartnersDTO2 = new ListTechPartnersDTO(); assertThat(listTechPartnersDTO1).isNotEqualTo(listTechPartnersDTO2); listTechPartnersDTO2.setId(listTechPartnersDTO1.getId()); assertThat(listTechPartnersDTO1).isEqualTo(listTechPartnersDTO2); listTechPartnersDTO2.setId(2L); assertThat(listTechPartnersDTO1).isNotEqualTo(listTechPartnersDTO2); listTechPartnersDTO1.setId(null); assertThat(listTechPartnersDTO1).isNotEqualTo(listTechPartnersDTO2); } @Test @Transactional public void testEntityFromId() { assertThat(listTechPartnersMapper.fromId(42L).getId()).isEqualTo(42); assertThat(listTechPartnersMapper.fromId(null)).isNull(); } }
Python
UTF-8
1,862
2.859375
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- import pickle import networkx as nx import matplotlib.pyplot as plt FILENAME = "graph_properties_nobel_ger_demand_ger_uniform_Link_Disjoint.pkl" G = nx.Graph() def add_proprieties(protection_distance, demands, working_distance): for key in protection_distance.keys(): G.add_edge(key[0], key[1], protection_distance=protection_distance.get(key), demand=demands.get(key), working_distance = working_distance.get(key)) G[key[0]][key[1]]['color']='grey' def add_working_paths(obj): for key in obj.keys(): print(key[0], key[1]) for key_inner in obj.get(key): G.add_edge(key_inner[0], key_inner[1], type='working_path', connection=key) G[key_inner[0]][key_inner[1]]['color']='blue' def add_protection_path(obj): for key in obj.keys(): print(key[0], key[1]) for key_inner in obj.get(key): G.add_edge(key_inner[0], key_inner[1], type='protection_path', connection=key) G[key_inner[0]][key_inner[1]]['color']='red' with open(FILENAME, 'rb') as f: # The protocol version used is detected automatically, so we do not # have to specify it. data = pickle.load(f) protection_distance = data["protection_distance"] demands = data["demands"] working_distance = data["working_distance"] add_proprieties(protection_distance, demands, working_distance) working_paths = data["working_paths"] add_working_paths(working_paths) protection_path = data["protection_path"] add_protection_path(protection_path) print(data) edges = G.edges() colors = [] for (u,v,attrib_dict) in list(G.edges.data()): colors.append(attrib_dict['color']) nx.draw(G, with_labels=True, edges=edges, edge_color=colors) plt.show()
C#
UTF-8
4,573
2.546875
3
[ "MIT" ]
permissive
 using Newtonsoft.Json; using Open.Genersoft.Component.Logging.Facade; using System; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Xml; using System.Reflection; namespace Open.Genersoft.Component.Logging.Default { public class DefaultLogger : GeneralLogger { private readonly object lockObj = new object(); private StreamWriter writer; private readonly string processName; private string currentFile = ""; private int num = 0; public DefaultLogger() { DatePattern = "yyyy-MM-dd"; processName = Process.GetCurrentProcess().ProcessName; } public override void Debug(params string[] text) { if (Level > LogLevel.DEBUG) return; Print(LogLevel.DEBUG, text); } public override void Error(string text, Exception ex = null) { if (Level > LogLevel.ERROR) return; if (ex != null) Print(LogLevel.ERROR, text, ex.Message, ex.StackTrace); else Print(LogLevel.ERROR, text); } public override void Info(params string[] text) { if (Level > LogLevel.INFO) return; Print(LogLevel.INFO, text); } public override void Warn(params string[] text) { if (Level > LogLevel.WARN) return; Print(LogLevel.WARN, text); } private void Print(LogLevel level, params string[] text) { if (Level == LogLevel.OFF) return; StringBuilder sb = new StringBuilder(256); StackTrace st; StackFrame sf; MethodBase method = null; int line = 0; string className = ""; if (level == LogLevel.TRACE) { st = new StackTrace(true); sf = st.GetFrame(2); method = sf.GetMethod(); line = sf.GetFileLineNumber(); className = method.DeclaringType.FullName; } foreach (var s in text) { sb.Append(s); sb.Append(Environment.NewLine); } try { CreatePathIfNotExists(); bool token = false; while(!token) Monitor.TryEnter(lockObj, 100, ref token); if (token) { string date = DateTime.Now.ToString(DatePattern); if(!currentFile.Contains(date)) { num = 0; currentFile = Path + $"{Name}-Log{date}-part{num}.txt"; } else { SliceFileIfSpill(date); } using (writer = new StreamWriter(currentFile, true, Encoding.Default)) { string time = DateTime.Now.ToString(TimePattern); writer.AutoFlush = false; writer.WriteLine(time + $":【{ levelDict[level]}】"); if(level == LogLevel.FATAL) { writer.WriteLine("【系统错误】:" + text[0]); } if(level == LogLevel.TRACE) { writer.WriteLine("【进程】:" + processName); writer.WriteLine("【线程ID】:" + Thread.CurrentThread.ManagedThreadId); writer.WriteLine("【类名】:" + className); writer.WriteLine("【方法名】:" + method.Name); writer.WriteLine("【行号】:" + line); } writer.WriteLine("【信息】:" + sb); writer.Flush(); } Monitor.Exit(lockObj); } } catch (Exception) {} } public override void PrintObject(object obj) { Print(Level, JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented)); } /// <summary> /// xml打印 /// </summary> /// <param name="desc"></param> /// <param name="doc"></param> public override void PrintXml(string desc, string xmlStr) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlStr); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (XmlTextWriter writer = new XmlTextWriter(sw)) { writer.Indentation = 4; // 缩进个数 writer.IndentChar = ' '; // 缩进字符 writer.Formatting = System.Xml.Formatting.Indented; doc.WriteTo(writer); } Print(Level, desc, sb.ToString()); } private void CreatePathIfNotExists() { if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } } private void SliceFileIfSpill(string date) { if (File.Exists(currentFile)) { FileInfo info = new FileInfo(currentFile); if (info.Length > Slice * 1024 * 1024) { num++; currentFile = Path + $"{Name}-Log{date}-part{num}.txt"; } } } public override void Fatal(string text, Exception ex = null) { if (Level > LogLevel.FATAL) return; if (ex != null) Print(LogLevel.FATAL, text, ex.Message, ex.StackTrace); else Print(LogLevel.FATAL, text); } public override void Trace(params string[] text) { if (Level > LogLevel.TRACE) return; Print(LogLevel.TRACE, text); } } }
Markdown
UTF-8
3,489
3.1875
3
[]
no_license
# First Timers Contributions Make sure you have Git installed, If you don't have git on your machine, [install it]( https://help.github.com/articles/set-up-git/). ## Fork this repository <img align="right" width="300" src="./assets/image/fork.JPG" alt="fork this repository" /> Fork this repo by clicking on the fork button on the top of this page. This will create a copy of this repository in your account. ## Clone the repository <img align="right" width="300" src="./assets/image/clone.JPG" alt="clone this repository" /> Now clone the forked repo to your machine. Go to your GitHub account, open the forked repo, click on the clone button and then click the *copy to clipboard* icon. Open a terminal and run the following git command: ``` git clone "url you just copied" ``` where "url you just copied" (without the quote marks) is the url to this repository (your fork of this project). See the previous steps to obtain the url. <img align="right" width="300" src="./assets/image/clipboard.JPG" alt="copy URL to clipboard" /> For example: ``` git clone https://github.com/this-is-you/starter-project.git ``` where `this-is-you` is your GitHub username. Here you're copying the contents of the starter-project repository in GitHub to your computer. ## Create a branch Change to the repository directory on your computer (if you are not already there): ``` cd starter-project ``` Now create a branch using the `git checkout` command: ``` git checkout -b <add-your-new-branch-name> ``` For example: ``` git checkout -b add-my-profile ``` (The name of the branch does not need to have the word *add* in it, but it's a reasonable thing to include because the purpose of this branch is to add your profile to a list.) ## Make necessary changes and commit those changes Now open `person.json` file in a text editor, add your name, image, and reason why you code to it. in the below format inside the square brackets [] and save your changes. ``` { "firstname": "Your firstname here", "lastname": "Your lastname here", "image": "/starter_project/assets/image/<your_image_name.ext>", "word": "Reason why you learn to code" }, ``` Now, save the file. <img align="right" width="450" src="./assets/image/status.JPG" alt="git status" /> If you go to the project directory and execute the command `git status`, you'll see there are changes. Add those changes to the branch you just created using the `git add` command: ``` git add person.json ``` Now commit those changes using the `git commit` command: ``` git commit -m "Add my profile to the list" ``` ## Push changes to GitHub Push your changes using the command `git push`: ``` git push origin <add-your-branch-name> ``` replacing `<add-your-branch-name>` with the name of the branch you created earlier. ## Submit your changes for review If you go to your repository on GitHub, you'll see a `Compare & pull request` button. Click on that button. <img style="float: right;" src="./assets/image/compare-and-pull.JPG" alt="create a pull request" /> Now submit the pull request. <img style="float: right;" src="./assets/image/submit-pull-request.JPG" alt="submit pull request" /> Soon I'll be merging all your changes into the master branch of this project. You will get a notification email once the changes have been merged. ## Where to go from here? Congrats! You just completed the standard _fork -> clone -> edit -> PR_ workflow that you'll encounter often as a contributor!
C#
UTF-8
890
2.75
3
[]
no_license
using System.Collections.Generic; using System.Linq; using Ecommerce.Dto; using Ecommerce.UnitOfWork; namespace Ecommerce.Service.Services { public class ProductService : IProductService { private readonly IUnitOfWork _uow; public ProductService(IUnitOfWork uow) { _uow = uow; } public ServiceResponse<List<ProductDto>> GetAll() { var products = _uow.ProductRepository.FindAll().Select(x => new ProductDto { ProductId = x.ProductId, Code = x.Code, Name = x.Name, Price = x.Price }).ToList(); return new ServiceResponse<List<ProductDto>> { Success = true, Message = "Products listed successfully.", Data = products }; } } }
Java
UTF-8
4,311
2.203125
2
[]
no_license
package com.jss.educenter.controller; import com.google.gson.Gson; import com.jss.commonutils.JwtUtils; import com.jss.educenter.entity.UcenterMember; import com.jss.educenter.service.UcenterMemberService; import com.jss.educenter.utils.ConstantWxUtils; import com.jss.educenter.utils.HttpClientUtils; import com.jss.servicebase.exceptionhandler.CollegeException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.net.URLEncoder; import java.util.HashMap; @Controller @RequestMapping("/api/ucenter/wx") @CrossOrigin public class WxApiController { @Autowired private UcenterMemberService service; @GetMapping("callback") public String callback(String code,String state){ //拼接地址 String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" + "?appid=%s" + "&secret=%s" + "&code=%s" + "&grant_type=authorization_code"; String accessTokenUrl = String.format( baseAccessTokenUrl, ConstantWxUtils.WX_OPEN_APP_ID, ConstantWxUtils.WX_OPEN_APP_SECRET, code ); try{ //拿着code去获取acess_token && openid String accessTokenInfo = HttpClientUtils.get(accessTokenUrl); //字符串 //System.out.println("======="+accessTokenInfo); //将accessTokenInfo转换成map,根据map的key获得值 Gson gson = new Gson(); HashMap mapToken = gson.fromJson(accessTokenInfo, HashMap.class); String accessToken = (String)mapToken.get("access_token"); String openid = (String)mapToken.get("openid"); //判断数据库中是否存在相同的微信 UcenterMember member = service.getOpenIdMember(openid); if(member == null){ //根据access_token && openid 访问微信的资源服务器,获取用户信息 String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" + "?access_token=%s" + "&openid=%s"; String urlInfoUrl = String.format( baseUserInfoUrl, accessToken, openid); //发送请求 String userInfo = HttpClientUtils.get(urlInfoUrl); //System.out.println("********"+userInfo); //获取返回后的扫码人信息 HashMap userMap = gson.fromJson(userInfo, HashMap.class); String nickname = (String) userMap.get("nickname"); String headimgurl = (String) userMap.get("headimgurl"); member = new UcenterMember(); member.setOpenid(openid); member.setNickname(nickname); member.setAvatar(headimgurl); service.save(member); } //生成token String token = JwtUtils.getJwtToken(member.getId(), member.getNickname()); return "redirect:http://localhost:3000?token="+token; }catch (Exception e){ e.printStackTrace(); throw new CollegeException(20001,"微信登录失败"); } } @GetMapping("login") public String getWxCode(){ String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" + "?appid=%s" + "&redirect_uri=%s" + "&response_type=code" + "&scope=snsapi_login" + "&state=%s" + "#wechat_redirect"; //对redirect_url进行编码 String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL; try{ redirectUrl = URLEncoder.encode(redirectUrl,"utf-8"); }catch (Exception e){ e.printStackTrace(); System.out.println("编码错误"); } String url = String.format( baseUrl, ConstantWxUtils.WX_OPEN_APP_ID, redirectUrl, "atguigu" ); return "redirect:"+url; } }
Java
UTF-8
3,196
2.953125
3
[]
no_license
package edu.gatech.virtual_pet_app; import java.util.ArrayList; import java.util.List; import java.util.Random; public class EventHandler { List<REvent> events; List<Interaction> inter; List<Illness> illness; public EventHandler(List<REvent> events, List<Interaction> interaction, List<Illness> illness) { this.events = events; this.inter = interaction; this.illness = illness; } public REvent getRandomEvent(Pet pet) { Random rand = new Random(); List <REvent> array = new ArrayList<REvent>(); int avgHunger=0; int hunHit = 0; int count = 0; int moodHit = 0; int hapHit = 0; int total = 0; calcMood(pet); for (Interaction s : inter) { if(s.getPostHunger() > 0) { avgHunger = avgHunger + s.getPostHap(); count++; } } avgHunger = avgHunger/count; if(avgHunger > 60 || avgHunger < 40) { hunHit = 20; } else if(avgHunger > 70 || avgHunger < 30) { hunHit = 40; } else { hunHit = 0; } if(pet.getMood() == Pet.Mood.AGRESSIVE) { moodHit = 40; } else if(pet.getMood() == Pet.Mood.DEPRESSED) { moodHit = 30; } else if(pet.getMood() == Pet.Mood.CONTENT) { moodHit = 20; } else { moodHit = 10; } if(pet.getHappiness() < 40) { hapHit = 20; } else if(pet.getHappiness() < 60) { hapHit = 15; } else if (pet.getHappiness() < 75) { hapHit = 10; } else { hapHit = 0; } total = hapHit + hunHit + moodHit; int number = 0; if(rand.nextInt(100) > total) { for(REvent e: events) { if((e.getHappiness() > 0 || e.getHealth() > 0 || e.getHunger() > 0) || (e.getItem() != null)) { array.add(e); number++; } } } else { for(REvent e: events) { if((e.getHappiness() > 0 || e.getHealth() > 0 || e.getHunger() > 0) || (e.getItem() != null)) {} else { array.add(e); number++; } } } return array.get((rand.nextInt(number))); } public void calcMood(Pet pet) { int count = 0; int hap = 0; for (Interaction s : inter) { if(s.getPostHap() > 0) { hap = hap + s.getPostHap(); count++; } } if((hap/count) > 75) { pet.setMood(Pet.Mood.FRIENDLY); } else if((hap/count) > 60) { pet.setMood(Pet.Mood.CONTENT); } else if((hap/count) > 40) { pet.setMood(Pet.Mood.DEPRESSED); } else { pet.setMood(Pet.Mood.AGRESSIVE); } } public int changeWeight(Pet pet) { int count = 0; int hun = 0; int avgHunger = 0; for (Interaction s : inter) { if(s.getPostHunger() > 0) { hun = hun + s.getPostHunger(); count++; } } avgHunger = hun/count; if(avgHunger > 50) { pet.setWeight(pet.getWeight() + (int)(((avgHunger-50)/10))); } else { pet.setWeight(pet.getWeight() - (int)(((avgHunger)/10))); } if(pet.getWeight() < 0) { pet.setWeight(1); } //if weight > x obesity given time //if weight < x mal-nutrition return pet.getWeight(); } }
Java
UTF-8
2,601
2.1875
2
[ "Apache-2.0" ]
permissive
package com.hs.mail.imap.processor.ext; import javax.security.auth.login.AccountNotFoundException; import com.hs.mail.exception.MailboxException; import com.hs.mail.exception.MailboxNotFoundException; import com.hs.mail.imap.ImapConstants; import com.hs.mail.imap.ImapSession; import com.hs.mail.imap.mailbox.Mailbox; import com.hs.mail.imap.mailbox.MailboxManager; import com.hs.mail.imap.mailbox.MailboxPath; import com.hs.mail.imap.message.request.AbstractMailboxRequest; import com.hs.mail.imap.message.response.HumanReadableText; import com.hs.mail.imap.processor.AbstractImapProcessor; import com.hs.mail.imap.user.UserManager; /** * * @author Wonchul Doh * @since December 4, 2016 * */ public abstract class AbstractACLProcessor extends AbstractImapProcessor { protected static final String ACL_ANYONE_RIGHTS = "acl_anyone_rights"; protected static final String ACL_OWNER_RIGHTS = "acl_owner_rights"; protected static final String ACL_OTHER_RIGHTS = "acl_other_rights"; protected long getUserID(String identifier) throws AccountNotFoundException { if (ImapConstants.ANYONE.equals(identifier)) { return ImapConstants.ANYONE_ID; } UserManager manager = getUserManager(); String address = manager.rewriteAddress(identifier); long userid = manager.getUserID(address); if (userid == 0) { throw new AccountNotFoundException("Account for " + identifier + " not found"); } return userid; } protected Mailbox getAuthorizedMailbox(ImapSession session, AbstractMailboxRequest request) throws MailboxException { MailboxPath path = buildMailboxPath(session, request.getMailbox()); MailboxManager manager = getMailboxManager(); Mailbox mailbox = manager.getMailbox(path.getUserID(), path.getFullName()); if (mailbox == null) { throw new MailboxNotFoundException( HumanReadableText.MAILBOX_NOT_FOUND); } String rights = manager.getRights(session.getUserID(), mailbox.getMailboxID(), true); /* * RFC 4314 section 6. * An implementation MUST make sure the ACL commands themselves do * not give information about mailboxes with appropriately * restricted ACLs. */ if (rights.indexOf('l') == -1) { throw new MailboxNotFoundException( HumanReadableText.MAILBOX_NOT_FOUND); } /* * RFC 4314 section 4. * Rights required to perform SETACL/DEETEACL/GETACL/LISTRIGHTS * commands. */ else if (rights.indexOf('a') == -1) { throw new MailboxException(HumanReadableText.INSUFFICIENT_RIGHTS); } return mailbox; } }
Java
UTF-8
3,318
2.390625
2
[ "Apache-2.0" ]
permissive
package com.example.android.sunshine.app; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.support.v4.view.accessibility.AccessibilityManagerCompat; import android.util.AttributeSet; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; public class CompassView extends View { private int mMyHeight; private int mMyWidth; private float mDirection; private Paint mOuterRing; private Paint mInnerRing; private Paint mArrow; public CompassView(Context context) { super(context); init(); } public CompassView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CompassView(Context context, AttributeSet attrs, int defaultStyle) { super(context, attrs, defaultStyle); init(); } private void init() { mOuterRing = new Paint(Paint.ANTI_ALIAS_FLAG); mOuterRing.setStyle(Paint.Style.FILL); mOuterRing.setColor(getResources().getColor(R.color.sunshine_dark_blue)); mInnerRing = new Paint(Paint.ANTI_ALIAS_FLAG); mInnerRing.setStyle(Paint.Style.FILL); mInnerRing.setColor(getResources().getColor(R.color.sunshine_blue)); mArrow = new Paint(Paint.ANTI_ALIAS_FLAG); mArrow.setStyle(Paint.Style.FILL_AND_STROKE); mArrow.setColor(getResources().getColor(android.R.color.white)); mArrow.setStrokeWidth(5f); sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int hSpecMode = MeasureSpec.getMode(heightMeasureSpec); int hSpecSize = MeasureSpec.getSize(heightMeasureSpec); mMyHeight = hSpecSize; int wSpecMode = MeasureSpec.getMode(widthMeasureSpec); int wSpecSize = MeasureSpec.getSize(widthMeasureSpec); mMyWidth = wSpecSize; if (hSpecMode == MeasureSpec.EXACTLY) { } else if (hSpecMode == MeasureSpec.AT_MOST) { } else if (hSpecMode == MeasureSpec.UNSPECIFIED) { } if (wSpecMode == MeasureSpec.EXACTLY) { } else if (wSpecMode == MeasureSpec.AT_MOST) { } else if (wSpecMode == MeasureSpec.UNSPECIFIED) { } setMeasuredDimension(mMyWidth, mMyHeight); } @Override protected void onDraw(Canvas canvas) { float cx = mMyHeight/2; float cy = mMyWidth/2; float outerRadius = mMyHeight/2; float innerRadius = mMyHeight/2 * 0.9f; canvas.drawCircle(cx, cy, outerRadius, mOuterRing); canvas.drawCircle(cx, cy, innerRadius, mInnerRing); canvas.drawLine( cx, cy, (float)(cx + innerRadius * Math.sin(Math.toRadians(mDirection))), (float)(cy - innerRadius * Math.cos(Math.toRadians(mDirection))), mArrow); } public void setDirection(float dir) { mDirection = dir; invalidate(); } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { event.getText().add(String.valueOf(mDirection)); return true; } }
C
UTF-8
7,060
3.3125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <string.h> #include <errno.h> #include <signal.h> #include <wait.h> #include <pthread.h> int item_to_produce; //현재 만들어야하는 아이템 담는 변수 int curr_buf_size; //현재 버퍼에 있는 크기 int total_items; //생산하고 싶은 총 아이템 수 (0~M-1) int consumed_item_size; //소비한 아이템 수 int max_buf_size; //버퍼 최대 크기 int num_workers; //워커 스레드의 수 int num_masters; //마스터 스레드의 수 int num_cur_workers; //현재 돌고있는 워커 스레드의 수 int num_cur_masters; //현재 돌고있는 마스터 스레드의 수 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //락 걸기 위한 mutex변수 생성 pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //쓰레드 조건변수 생성 int *buffer; //버퍼(배열) void print_produced(int num, int master) { //생산되었다는걸 출력하는 함수 printf("Produced %d by master %d\n", num, master); } void print_consumed(int num, int worker) { //소비되었다는걸 출력하는 함수 printf("Consumed %d by worker %d\n", num, worker); } //아이템 버퍼에 생성하는 마스터 쓰레드가 돌리는 함수 void *generate_requests_loop(void *data) { int thread_id = *((int *)data); //인자로 받은 데이터 정수형으로 타입 변환 while(1) //무한 반복 { pthread_mutex_lock(&mutex); //락걸기 if(item_to_produce >= total_items) { //현재 만들어야하는 변수가 범위 벗어날 경우 num_cur_masters--; pthread_cond_signal(&cond); //시그널 보내기 pthread_mutex_unlock(&mutex); //락 풀기 break; //무한 반복 탈출 } if(curr_buf_size > max_buf_size){ //최대 버퍼 사이즈를 넘어섰을 경우 pthread_cond_signal(&cond); //시그널 보내기 if(num_cur_masters > 1) pthread_cond_wait(&cond, &mutex); //시그널 기다리기 pthread_mutex_unlock(&mutex); //락 풀기 continue; } buffer[curr_buf_size++] = item_to_produce; //버퍼에 아이템 넣어주고 curr_buf_size 증가 print_produced(item_to_produce, thread_id); //생산한 아이템 인자로 넣어준 쓰레드 id와 함께 출력 item_to_produce++; //생산해야하는 아이템 재지정 pthread_cond_signal(&cond); //시그널 보내기 if(num_cur_masters > 1) pthread_cond_wait(&cond, &mutex); //시그널 기다리기 pthread_mutex_unlock(&mutex); //락 풀기 } return 0; } //아이템을 소비하고, 버퍼에서 지우는 워커 쓰레드가 돌리는 함수 void *consume_requests_loop(void *data) { int thread_id = *((int *)data); int item_to_consumed = 0; while(1) //무한 반복 { pthread_mutex_lock(&mutex); //락걸기 if(consumed_item_size >= total_items) { //다 소비했는데도 소비하려고 할 때 num_cur_workers--; pthread_cond_signal(&cond); //시그널 보내기 pthread_mutex_unlock(&mutex); //락 풀기 break; } if(curr_buf_size < 1){ //버퍼 다 비었는데 소비하려고 할 때 pthread_cond_signal(&cond); //시그널 보내기 if(num_cur_workers > 1) pthread_cond_wait(&cond, &mutex); //시그널 기다리기 pthread_mutex_unlock(&mutex); //락 풀기 continue; } item_to_consumed = buffer[curr_buf_size-1]; //버퍼 자리 아이템 consumed_item으로 빼주고 buffer[--curr_buf_size] = 0; //그 자리 비워주기 print_consumed(item_to_consumed, thread_id); //소비한 아이템 쓰레드 id와 함께 출력 consumed_item_size++; pthread_cond_signal(&cond); //시그널 보내기 if(num_cur_workers > 1) pthread_cond_wait(&cond, &mutex); //시그널 기다리기 pthread_mutex_unlock(&mutex); //락 풀기 } return 0; } //write function to be run by worker threads //ensure that the workers call the function print_consumed when they consume an item int main(int argc, char *argv[]) { int *master_thread_id; //마스터 쓰레드 아이디 담을 배열 pthread_t *master_thread; //마스터 쓰레드 담을 배열 int *worker_thread_id; //워커 쓰레드 아이디 담을 배열 pthread_t *worker_thread; //워커 쓰레드 담을 배열 item_to_produce = 0; curr_buf_size = 0; //현재 버퍼 차있는 정도 consumed_item_size = 0; //소비한 아이템 개수 int i; //입력인자 받는 과정 if (argc < 5) { printf("./master-worker #total_items #max_buf_size #num_workers #masters e.g. ./exe 10000 1000 4 3\n"); exit(1); } else { num_masters = atoi(argv[4]); num_workers = atoi(argv[3]); total_items = atoi(argv[1]); max_buf_size = atoi(argv[2]); } //여기까지 buffer = (int *)malloc (sizeof(int) * max_buf_size); //버퍼 메모리에 할당(입력한 버퍼 최대 크기 사이즈만큼) num_cur_masters = num_masters; num_cur_workers = num_workers; //create master producer threads master_thread_id = (int *)malloc(sizeof(int) * num_masters);//마스터 쓰레드 아이디 담을 배열 메모리에 할당 master_thread = (pthread_t *)malloc(sizeof(pthread_t) * num_masters); //마스터 쓰레드 배열 메모리에 할당 for (i = 0; i < num_masters; i++) //마스터 쓰레드 아이디 담을 배열 초기화 master_thread_id[i] = i; for (i = 0; i < num_masters; i++) //마스터 쓰레드 생성, 마쓰터 쓰레드가 돌릴 함수에 쓰레드 아이디 인자로 넘겨줌 pthread_create(&master_thread[i], NULL, generate_requests_loop, (void *)&master_thread_id[i]); //create worker consumer threads worker_thread_id = (int *)malloc(sizeof(int) * num_workers);//워커 쓰레드 아이디 담을 배열 메모리에 할당 worker_thread = (pthread_t *)malloc(sizeof(pthread_t) * num_workers); //워커 쓰레드 배열 메모리에 할당 for (i = 0; i < num_workers; i++) //워커 쓰레드 아이디 담을 배열 초기화 worker_thread_id[i] = i; for (i = 0; i < num_workers; i++) //워커 쓰레드 생성, 워커 쓰레드가 돌릴 함수에 쓰레드 아이디 인자로 넘겨줌 pthread_create(&worker_thread[i], NULL, consume_requests_loop, (void *)&worker_thread_id[i]); pthread_cond_signal(&cond); //cond로 시그널 보냄 //wait for all threads to complete for (i = 0; i < num_masters; i++) //전체 마스터 쓰레드에 대하여 { pthread_join(master_thread[i], NULL); //마스터 쓰레드 기다린다. printf("master %d joined\n", i); //종료된 마스터 쓰레드 출력 } //wait for all threads to complete for (i = 0; i < num_workers; i++) //전체 워커 쓰레드에 대하여 { pthread_join(worker_thread[i], NULL); //워커 쓰레드 기다린다. printf("worker %d joined\n", i); //종료된 워커 쓰레드 출력 } pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); return 0; }
Ruby
UTF-8
224
3.5
4
[]
no_license
for num in 1..100 do if num % 5 == 0 && num % 3 == 0 then puts num.to_s+":FizzBuzz" elsif num % 5 == 0 then puts num.to_s+":Buzz" elsif num % 3 == 0 then puts num.to_s+":Fizz" end end
Python
UTF-8
681
3.265625
3
[]
no_license
import random import string import json class VariousFunctions: def random_string(self, string_size, chars=string.ascii_uppercase + string.digits): self.string_size = string_size final_string = ''.join(random.choice(chars) for i in range(string_size)) return final_string def create_json(self, json_data, json_path): self.json_data = json_data self.json_path = json_path with open(self.json_path, 'w') as json_file: json.dump(self.json_data, json_file, indent=4) json_file.close() def random(self, pref): value = self.random_string(random.randint(5, 10)) return pref + value
Java
UTF-8
2,352
2.09375
2
[]
no_license
package com.uiet.casehearing; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; public class ResetPassword extends AppCompatActivity { private FirebaseAuth mAuth; ProgressDialog progressDialog; EditText email; Button reset; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reset_password); mAuth = FirebaseAuth.getInstance(); email = findViewById(R.id.emailId); reset = findViewById(R.id.resetButton); progressDialog = new ProgressDialog(this); reset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String userId = email.getText().toString(); if(userId.isEmpty()){ email.setError("Email is required"); return; } progressDialog.setMessage("Sending Email..."); progressDialog.show(); mAuth.sendPasswordResetEmail(userId).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { progressDialog.cancel(); Toast.makeText(getApplicationContext(),"Password Reset Mail Sent...",Toast.LENGTH_LONG).show(); Intent intent = new Intent(getApplicationContext(),Login.class); startActivity(intent); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.cancel(); Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show(); } }); } }); } }
Markdown
UTF-8
1,446
2.953125
3
[]
no_license
## About This project uses Springboot, NodeJS, and ReactJS. Search for a place to eat if you are hungry. mehungry utilizes the Yelp Developer's API to obtain multiple restaurant search results based on the type of food you want to eat, and location, as well as sorting by best match, lowest price, or most reviewed. Each restaurant listing contains important information you would want to know such as its name, address, price range, phone number, and rating. This project gets search results from the Yelp Developer's API. To run this project, make sure that you supply your own Yelp API key in the DiningPlaceController.java which can be obtained from creating an account with Yelp Developers at [this website](https://www.yelp.com/developers). ![](mehungry_web_demo.gif) ## Front-end 1. Open a command window and goes to restaurant-search\src\main\web 2. Run "npm install" 3. Run in development mode: npm start 4. Build production bundle: npm run build 1. This will generate a few files under "build" directory 2. Copy the above files to src/main/resources/public to be used by springboot server. ## Back-end 1. Run maven install 2. Start springboot server: two ways to do it 1. java -jar restaurant-search-0.0.1-SNAPSHOT.jar 2. In IDE, right click RestaurantSearchApplication.java to run as application. 3. Access from browser: http://localhost:8080/ *Front-end development is based on my Codeacademy project.
C++
UTF-8
494
3.125
3
[]
no_license
#include <iostream> using namespace std; int gcd(int a, int b) { while (b != 0) { int tmp = b; b = a % b; a = tmp; } return a; } int main() { int n; while (cin >> n && n != 0) { int G = 0; for (int i = 1; i < n; i++) { for (int j = i + 1; j <= n; j++) { G += gcd(j, i); } } cout << G << endl; } return 0; }
Java
UTF-8
718
2.84375
3
[]
no_license
package skipbo; public class DiscardPile extends Structure implements Pile { public void addCard(Card card) { list.add(card); } @Override public Card getTopCard() { Card card=list.get(list.size()-1); list.remove(list.size()-1); return card; } public Card geCard(int number) { Card card=list.get(number); list.remove(number); return card; } public Card getTopCardType() { return list.get(list.size()-1); } public int size() { return list.size(); } public int getTopCardValue() { return list.get(list.size()-1).getValue(); } }
Java
UTF-8
2,591
2.359375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package anhnd.rmi.impls; import anhnd.entity.Registrations; import anhnd.impl.repos.RegistrationsRepositoryImpl; import anhnd.intefaces.repos.IRegistrationsRepository; import anhnd.interfaces.rmi.IRegistrationsRMI; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; /** * * @author anhnd */ public class RegistrationsRMI extends UnicastRemoteObject implements IRegistrationsRMI{ private IRegistrationsRepository registrationsRepository; public RegistrationsRMI() throws RemoteException{ } @Override public ArrayList<Registrations> getAllRegistrations() throws RemoteException{ registrationsRepository = new RegistrationsRepositoryImpl(); return registrationsRepository.getAllRegistrations(); } @Override public Registrations findByRegistrationID(String id) throws RemoteException { registrationsRepository = new RegistrationsRepositoryImpl(); return registrationsRepository.findByRegistrationID(id); } @Override public boolean createRegistration(Registrations registration) throws RemoteException { registrationsRepository = new RegistrationsRepositoryImpl(); return registrationsRepository.createRegistration(registration); } @Override public boolean updateRegistration(Registrations registration) throws RemoteException { registrationsRepository = new RegistrationsRepositoryImpl(); return registrationsRepository.updateRegistration(registration); } @Override public boolean removeRegistration(String id) throws RemoteException { registrationsRepository = new RegistrationsRepositoryImpl(); return registrationsRepository.removeRegistration(id); } @Override public ArrayList<Registrations> findRegistrationByLikeName(String keywords) throws RemoteException { ArrayList<Registrations> result = new ArrayList<>(); registrationsRepository = new RegistrationsRepositoryImpl(); ArrayList<Registrations> registrations = registrationsRepository.getAllRegistrations(); for (Registrations registration : registrations) { if(registration.getFullname().toLowerCase().contains(keywords.toLowerCase())){ result.add(registration); } } return result; } }
Java
UTF-8
8,888
2.078125
2
[]
no_license
package com.dzf.zxkj.platform.service.common.impl; import com.dzf.zxkj.base.dao.SingleObjectBO; import com.dzf.zxkj.base.framework.SQLParameter; import com.dzf.zxkj.base.framework.processor.ResultSetProcessor; import com.dzf.zxkj.base.exception.BusinessException; import com.dzf.zxkj.base.exception.DAOException; import com.dzf.zxkj.base.exception.DZFWarpException; import com.dzf.zxkj.common.utils.StringUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * 基础数据引用表。 创建日期:(2001-7-17 15:44:24) * * @author:赵继江 */ @Slf4j public class ReferenceManagerDMO /* extends DataManageObject */ { private SingleObjectBO singleObjectBO; public SingleObjectBO getSingleObjectBO() { return singleObjectBO; } @Autowired public void setSingleObjectBO(SingleObjectBO singleObjectBO) { this.singleObjectBO = singleObjectBO; } class BD_Realtion { String corpfieldName; String fieldName; String selfPkName; String tableName; String errorMsg; /** * @param tableName * @param fieldName */ public BD_Realtion(String tableName, String fieldName, String selfPkName, String corpfieldName,String errorMsg) { super(); this.tableName = tableName; this.fieldName = fieldName; this.selfPkName = selfPkName; this.corpfieldName = corpfieldName; this.errorMsg = errorMsg; } } private static final String WITH_CORP_FLAG = "$"; private final ResultSetProcessor ResultSetHasDataJudger = new ResultSetProcessor() { private static final long serialVersionUID = 8347151336502175602L; public Object handleResultSet(ResultSet rs) throws SQLException { rs.next(); return rs.getInt(1) > 0; // if (rs.next()) // return Boolean.TRUE; // else // return Boolean.FALSE; } }; private HashMap<String, List<BD_Realtion>> tableName_ReferenceTables_Map; /** * ReferenceManagerDMO 构造子注解。 * * @exception javax.naming.NamingException * 异常说明。 * @exception nc.bs.pub.SystemException * 异常说明。 */ public ReferenceManagerDMO(SingleObjectBO singleObjectBO) { super(); if(singleObjectBO==null) throw new DAOException("SingleObjectBO未成功初始化"); this.singleObjectBO=singleObjectBO; } private boolean checkReferenceBySql(String tableName, String pk_corp, BD_Realtion relation, String key, String sql) { boolean referenced = false; try { SQLParameter para = new SQLParameter(); para.addParam(key); if (relation.corpfieldName != null && relation.corpfieldName.trim().length() > 0) para.addParam(pk_corp); referenced = (Boolean) getSingleObjectBO().executeQuery(sql, para, ResultSetHasDataJudger); } catch (DAOException e) {// 如果发生了错误一般是引用注册表中注册了不存在表(或对应产品没有安装).忽略. log.warn("查询数据库表" + relation.tableName + "对表" + tableName + "的引用时出错,可能是对应产品没安装"); log.warn(e.getMessage(), e); } return referenced; } private ArrayList<BD_Realtion> getRelationListByTableName(String tableName, boolean isModifyCheck) throws DAOException { return getRelationListByTableNameAndWithcorp(tableName, false, isModifyCheck); } /** * @param tableName * @return * @throws SQLException */ @SuppressWarnings("unchecked") private ArrayList<BD_Realtion> getRelationListByTableNameAndWithcorp( String tableName, boolean isWithCorp, boolean isModifyCheck) throws DAOException { String newTableName = isWithCorp ? WITH_CORP_FLAG + tableName : tableName; ArrayList<BD_Realtion> al = (ArrayList<BD_Realtion>) this .getTableName_ReferenceTables_Map().get(newTableName); if (al == null) { // 选择所有引用该表的表: String sql = "select referencedtablekey, referencingtablename, referencingtablecolumn, referencingcorpfield,refmsg from bd_ref_relation where referencedtablename = '" + tableName + "'"; if (isWithCorp) { sql += " and referencingcorpfield is not null "; } else { sql += " and referencingcorpfield is null "; } if (isModifyCheck) { sql += " and ismodifycheck = 'Y'"; } ResultSetProcessor p = new ResultSetProcessor() { private static final long serialVersionUID = 3730593948830478187L; public Object handleResultSet(ResultSet rs) throws SQLException { ArrayList<BD_Realtion> result = new ArrayList<BD_Realtion>(); while (rs.next()) { String ReferencedTableKey = rs .getString("referencedtablekey"); String ReferencingTableName = rs .getString("referencingtablename"); String ReferencingTableColumn = rs .getString("referencingtablecolumn"); String referencingcorpfield = rs .getString("referencingcorpfield"); String errormsg = rs.getString("refmsg"); BD_Realtion r = new BD_Realtion(ReferencingTableName, ReferencingTableColumn, ReferencedTableKey, referencingcorpfield,errormsg); result.add(r); } return result; } }; al = (ArrayList<BD_Realtion>) getSingleObjectBO().executeQuery(sql,null, p); getTableName_ReferenceTables_Map().put(newTableName, al); } return al; } /** * @param key * @param relation * @return */ private String getSqlQeury(String key, BD_Realtion relation) { // 利用where exists的短路特性来提高效率, 选用bd_currtype是因为 // 对于NC来说该表一定存在而且数据量够小。 以后可也考虑建立一个专门的辅助表. StringBuilder buf = new StringBuilder(); buf.append("select count(1) from dual where exists ("); buf.append("select "); buf.append("1"); buf.append(" from "); buf.append(relation.tableName); buf.append(" where "); buf.append(relation.fieldName); buf.append("="); buf.append("?"); if (relation.corpfieldName != null && relation.corpfieldName.trim().length() > 0) { buf.append(" and "); buf.append(relation.corpfieldName); buf.append(" = ? "); } buf.append(")"); String sql = buf.toString(); return sql; } private String getSqlQeuryWithDr(String key, BD_Realtion relation) { StringBuffer buf = new StringBuffer(); buf.append("select count(1) from dual where exists ("); buf.append("select "); buf.append("1"); buf.append(" from "); buf.append(relation.tableName); buf.append(" where "); buf.append(relation.fieldName); buf.append("="); buf.append("?"); if (relation.corpfieldName != null && relation.corpfieldName.trim().length() > 0) { buf.append(" and "); buf.append(relation.corpfieldName); buf.append(" = ? "); } buf.append(" and nvl(dr,0)=0"); buf.append(")"); String sql = buf.toString(); return sql; } protected HashMap<String, List<BD_Realtion>> getTableName_ReferenceTables_Map() { if (this.tableName_ReferenceTables_Map == null) { this.tableName_ReferenceTables_Map = new HashMap<String, List<BD_Realtion>>(); } return this.tableName_ReferenceTables_Map; } public void isReferencedRefmsg(String tableName, String key, boolean isModifyCheck) throws DZFWarpException { List<BD_Realtion> relationList = getRelationListByTableName(tableName, isModifyCheck); checkReferenceHelper(tableName, key, relationList); } private void checkReferenceHelper(String tableName, String key, List<BD_Realtion> relationList) throws DZFWarpException{ checkReferenceHelper(tableName, null, key, relationList); } private void checkReferenceHelper(String tableName, String pk_corp, String key, List<BD_Realtion> relationList) throws DZFWarpException{ // 没有引用该表的情况: if (relationList.size() == 0) return ; for (BD_Realtion relation : relationList) { String checkSqlWithoutDr = getSqlQeury(key, relation); String checkSqlWithDr = getSqlQeuryWithDr(key, relation); // 先不包含dr进行查询,尽量利用上索引,如果被引用了,则加上dr条件确认一下。 boolean referenced = checkReferenceBySql(tableName, pk_corp, relation, key, checkSqlWithoutDr) && checkReferenceBySql(tableName, pk_corp, relation, key, checkSqlWithDr); if (referenced) { if(!StringUtil.isEmpty(relation.errorMsg)){ throw new BusinessException(relation.errorMsg); }else{ throw new BusinessException("数据已被引用,不允许删除!"); } } } return ; } }
TypeScript
UTF-8
10,829
2.90625
3
[ "MIT" ]
permissive
/** * Specifies the direction of the ken burns effect. */ export const enum Direction { Normal = 'normal', Reverse = 'reverse', Random = 'random', } /** * All available ken burns CSS animations. */ export const animationNames = [ 'ken-burns-bottom-right', 'ken-burns-top-left', 'ken-burns-bottom-left', 'ken-burns-top-right', 'ken-burns-middle-left', 'ken-burns-middle-right', 'ken-burns-top-middle', 'ken-burns-bottom-middle', 'ken-burns-center', ]; const enum Attributes { AnimationDirection = 'animation-direction', AnimationNames = 'animation-names', FadeDuration = 'fade-duration', Images = 'images', SlideDuration = 'slide-duration', } const template = document.createElement('template') as HTMLTemplateElement; template.innerHTML = ` <style> :host { overflow: hidden; position: relative; } div, img { height: 100%; width: 100%; } div { position: absolute; will-change: transform; } img { filter: var(--img-filter); object-fit: cover; } @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } @keyframes ken-burns-bottom-right { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(-10%, -7%, 0); } } @keyframes ken-burns-top-right { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(-10%, 7%, 0); } } @keyframes ken-burns-top-left { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(10%, 7%, 0); } } @keyframes ken-burns-bottom-left { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(10%, -7%, 0); } } @keyframes ken-burns-middle-left { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(10%, 0, 0); } } @keyframes ken-burns-middle-right { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(-10%, 0, 0); } } @keyframes ken-burns-top-middle { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(0, 10%, 0); } } @keyframes ken-burns-bottom-middle { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(0, -10%, 0); } } @keyframes ken-burns-center { to { transform: scale3d(1.5, 1.5, 1.5); } } </style> `; if (typeof (window as any).ShadyCSS === 'object') { (window as any).ShadyCSS.prepareTemplate(template, 'ken-burns-carousel'); } /** * `ken-burns-carousel` * * Displays a set of images in a smoothly-fading ken burns style carousel. * * @demo ../demo/index.html */ export default class KenBurnsCarousel extends HTMLElement { static get observedAttributes(): string[] { return [ Attributes.AnimationDirection, Attributes.AnimationNames, Attributes.FadeDuration, Attributes.Images, Attributes.SlideDuration, ]; } /** * Specifies the list of ken burns animations to apply to the elements. * * This allows customizing the built-in animations to your liking by overriding * the ones you don't like with custom CSS animations. * * This can also be set via setting the `animation-names`-attribute to a space- * separated list of CSS animation names. * * @type String[] */ animationNames: string[] = animationNames; /** * The direction to play the animations in. * * Defaults to Direction.Random, meaning that with each image the associated ken * burns animation is either played forwards or backwards adding additional visual * diversity. * * This can also be set via the `animation-direction`-attribute. * * @type Direction */ animationDirection: Direction = Direction.Random; private _fadeDuration: number = 2500; private _imgList: string[] = []; private _slideDuration: number = 20000; private _timeout: number = 0; private _zCounter: number = 0; /** * The duration of the crossfading animation in millseconds. * * Must be smaller than the slide duration. Defaults to 2500ms. * This can also be set via the `fade-duration`-attribute. * * @type number */ get fadeDuration() { return this._fadeDuration; } set fadeDuration(val: number) { if (val > this.slideDuration) { throw new RangeError("Fade duration must be smaller than slide duration"); } this._fadeDuration = val; } /** * The list of URLs to the images to display. * * You can either set this property directly, or set the `images`-attribute * to a space-separated list of URLs. * * The element will dirty-check this property to avoid switching to the next image * even if the images set were the same. If you forcefully want to rerender, ensure * you pass a different array because the dirty-check will check for identity. * * @type string[] */ get images(): string[] { return this._imgList; } set images(images: string[]) { if (arraysEqual(this._imgList, images)) { return; } this._imgList = images; if (images.length > 0) { this.animateImages(images); } else { this.stop(); } } /** * The duration of the sliding (or ken burns) animation in millseconds. * * Must be greater than or equal to the fade duration. Defaults to 20s. * This can also be set via the `slide-duration`-attribute. * * @type number */ get slideDuration() { return this._slideDuration; } set slideDuration(val: number) { if (val < this.fadeDuration) { throw new RangeError("Slide duration must be greater than fade duration"); } this._slideDuration = val; } constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot!.appendChild(template.content.cloneNode(true)); } attributeChangedCallback(name: string, oldVal: string, newVal: string) { switch (name) { case Attributes.AnimationDirection: this.animationDirection = newVal as Direction; break; case Attributes.AnimationNames: this.animationNames = newVal ? newVal.split(' ').filter(name => name) : animationNames; break; case Attributes.FadeDuration: this.fadeDuration = Number(newVal); break; case Attributes.Images: this.images = newVal ? newVal.split(' ').filter(url => url) : []; break; case Attributes.SlideDuration: this.slideDuration = Number(newVal); break; } } connectedCallback() { if (typeof (window as any).ShadyCSS === 'object') { (window as any).ShadyCSS.styleElement(this); } } private animateImages(images: string[]) { const insert = (index: number, img: HTMLImageElement) => { const random = Math.random(); const animationIndex = Math.floor(random * this.animationNames.length); const direction = this.animationDirection === Direction.Random ? random > .5 ? 'normal' : 'reverse' : this.animationDirection; /* * Here we wrap the image element into a surrounding div that is promoted * onto a separate GPU layer using `will-change: transform`. The wrapping div * is then ken-burns-animated instead of the image itself. * * This leads the browser to pre-computing the image filter (--img-filter) * instead of computing it every frame. This can be a massive performance boost * if the filter is expensive. * * See https://developers.google.com/web/updates/2017/10/animated-blur for * more information. */ const wrap = document.createElement('div'); wrap.appendChild(img); wrap.style.animationName = `${this.animationNames[animationIndex]}, fade-in`; wrap.style.animationDuration = `${this.slideDuration}ms, ${this.fadeDuration}ms`; wrap.style.animationDirection = `${direction}, normal`; wrap.style.animationTimingFunction = 'linear, ease'; wrap.style.zIndex = String(this._zCounter++); this.shadowRoot!.appendChild(wrap); setTimeout(() => wrap.remove(), this.slideDuration); // Preload next image and place it in browser cache const nextIndex = (index + 1) % images.length; const next = document.createElement('img') as HTMLImageElement; next.src = images[nextIndex]; this._timeout = setTimeout( () => insert(nextIndex, next), this.slideDuration - this.fadeDuration, ); }; const img = document.createElement('img') as HTMLImageElement; img.src = images[0]; img.onload = () => { /* * Prevent race condition leading to wrong list being displayed. * * The problem arose when you were switching out the image list before * this callback had fired. The callback of a later list could have fired * faster than the one of earlier lists, which lead to the later slideshow * (the right one) being cancelled when the previous one became available. * * We now check whether we're still displaying the list we started * with and only then proceed with actually stopping the old slideshow * and displaying it. */ if (!arraysEqual(this._imgList, images)) { return; } this.stop(); insert(0, img); }; } private stop() { clearTimeout(this._timeout); this._timeout = 0; } } function arraysEqual<T>(arr1: T[] | null, arr2: T[] | null) { // tslint:disable-next-line:triple-equals if (arr1 === arr2 || (!arr1 && !arr2)) { // undefined == null here return true; } if (!arr1 || !arr2 || arr1.length !== arr2.length) { return false; } for (let i = 0; i < arr1.length; i++) { if (arr1[i] !== arr2[i]) { return false; } } return true; }
C++
UTF-8
1,057
2.859375
3
[ "Unlicense" ]
permissive
// // 2018 Rico Schulz // #pragma once #include "actuator.h" #define GHPI_PWM_CLOCK 384 #define GHPI_PWM_RANGE 1000 #define SERVO_OFF_POS 0 #define SERVO_ON_POS -130 namespace ghpi { // Class for the Kuman KY72 Servo class Servo : public Actuator { public: void TurnOn() override; void TurnOff() override; int get_angle(); void Initialize(); Servo(int max_angle, int init_angle); ~Servo(); private: // Functions void SetUpPWM(); void SetPosition(int angle); // Converts an angle to corresponding value for PWM. // Function assumes 50Hz and a PWM Range of 1000. // 0° is the neutral position of the motor // Angle is evenly spreaded around the neutral position. // ARGS: // angle: angle the motor should be steered to // RETURNS: // The corresponding value for the PWM int ConvertAngleToValue(int angle); // Data Member // Angle the motor can totaly rotate int max_angle_; // Current angle of the motor int angle_; }; };
Shell
UTF-8
666
3.21875
3
[]
no_license
#!/bin/sh # $Id$ # # #set -x # URL_SUM_24h="http://192.168.178.10:8080/api/getPlainValue/3862" URL_SUM="http://192.168.178.10:8080/api/getPlainValue/3858" # SCRIPT=`basename $0` EXITCODE="0" #------------------------------- info() { logger -t "${SCRIPT}[$$]" $* } error() { logger -p user.err -t "${SCRIPT}[$$]" "ERROR: $*" } debug() { logger -p user.debug -t "${SCRIPT}[$$]" $* } #-------------------------------------------- # MAIN #----- SUM_24h=`wget -q -O - $URL_SUM_24h` SUM=`wget -q -O - $URL_SUM` echo "Stromverbrauch letzte 24h: ${SUM_24h}. Summe: ${SUM}." | sendgtalk & #--------------------------------------------------- exit $EXITCODE # EOF
Java
UTF-8
746
3.140625
3
[ "MIT" ]
permissive
public class Matriz { public static float[][] transpose(float A[][]) { int Rows = A.length, int Columns = A[0].length; float[][] resultant = new float[Columns][Rows]; for(int i = 0; i < Rows; i++) for (int j = 0; j < Columns; j++) resultant[j][i] = a[i][j]; return resultant; } public static float[][] normalize(float A[][]){ int ARows = A.length, int AColumns = A[0].length; float[][] resultant = new float[ARows-1][AColumns]; for (int i = 0; i < ARows-1; i++){ for (int j = 0; j < AColumns; j++) resultant[i][j] = a[i][j]/A[ARows-1][j]; } return resultant; } }
Java
UTF-8
661
2.875
3
[]
no_license
import java.io.*; import java.net.*; public class server_rw { public static void main(String args[]) throws Exception { ServerSocket s1 = new ServerSocket(1055); Socket s = s1.accept(); DataInputStream din = new DataInputStream(s.getInputStream()); DataOutputStream dout= new DataOutputStream(s.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str1 = "", str2 = ""; while(!str1.equals("stop")) { str1 = din.readUTF(); System.out.println("Client says : " +str1); str2 = br.readLine(); dout.writeUTF(str2); dout.flush(); } din.close(); s.close(); s1.close(); } }
Shell
UTF-8
861
3.65625
4
[ "Apache-2.0" ]
permissive
set -e usage() { echo "Usage: $0 -o path [-b]" echo -e "\t-o package files output directory" echo -e "\t-b opencl backend" exit 1 } while getopts "o:hb" opt; do case "$opt" in o ) path=$OPTARG ;; b ) opencl=true ;; h|? ) usage ;; esac done # clear and create package directory ./schema/generate.sh rm -rf $path && mkdir -p $path TOOLS_PATH=$(realpath $path) CMAKE_ARGS="-DCMAKE_BUILD_TYPE=Release -DMNN_SEP_BUILD=OFF -DMNN_BUILD_SHARED_LIBS=OFF -DMNN_BUILD_CONVERTER=ON -DMNN_BUILD_TRAIN=ON -DMNN_PORTABLE_BUILD=ON -DMNN_BUILD_TOOLS=ON -DMNN_BUILD_QUANTOOLS=ON -DMNN_BUILD_BENCHMARK=ON -DMNN_BUILD_TEST=ON" if [ ! -z $opencl ]; then CMAKE_ARGS="$CMAKE_ARGS -DMNN_OPENCL=ON" fi rm -rf build && mkdir build pushd build [ -f CMakeCache.txt ] && rm CMakeCache.txt cmake $CMAKE_ARGS .. && make -j24 cp *.out $TOOLS_PATH popd
PHP
UTF-8
1,160
2.984375
3
[ "MIT" ]
permissive
<?php namespace core\Http; class Request { /** * Las peticiones * * @var array */ protected $requests = []; /** * Rescata las peticiones * * @return void */ public function __construct() { $this->requests = $this->mergeData($_POST, $_FILES); } /** * Fusiona datos de POST y FILES * * @param array $post * @param array $files * * @return array */ protected function mergeData(array $post, array $files) { foreach($post as $key => $value) { if(is_string($value)) { $post[$key] = trim($value); } } return array_merge($files, $post); } /** * Acceso a los datos de las peticiones * * @param string $name * * @return mixed */ public function input($name) { return array_key_exists($name, $this->requests) ? $this->requests[$name] : null; } /** * Obtener todas las requests * * @return array */ public function all() { return $this->requests; } }
Python
UTF-8
730
4.71875
5
[]
no_license
################################################################### # SORTING BY KEY # ################################################################### # use of common method for sorting values example_list = [[1, 4], [5, 8], [5, 4], [3, 2], [9, 1]] print(example_list) example_list.sort() # the list must first be sorted and then printed, sort() method can't be used alongside with print() method print(example_list) # use of better method for sorting values example_list.sort(key=lambda x: x[1]) # list will be sorted by second element of each list print(example_list) example_list.sort(key=lambda x: x[1], reverse=True) # return reversed list print(example_list)
C++
UTF-8
4,752
2.71875
3
[]
no_license
// _____________________________________ // | FuelTank.cpp - class implementation | // | Jack Flower - December 2012 | // |_____________________________________| // #include "FuelTank.h" #include "../../../Rendering/Drawable/Layers.h" #include "../../../Rendering/Animations/AnimSet.h" using namespace rendering::animation; using namespace rendering::drawable; namespace equipment { RTTI_IMPL(FuelTank, Actor) //Chroniony konstruktor domyślny FuelTank::FuelTank(const std::wstring & uniqueId) : Actor{ uniqueId },//konstruktor klasy bazowej m_fuel_tank_name{}, m_fuel_tank_capacity{ 0.0f }, m_fuel{ 0.0f }, m_fueltank_state{ EFuelTankState::FUELTANK_DEFAULT }, m_unit_controller{ true }//urządzenie włączone { setZIndexBody(Z_PHYSICAL_FUEL_TANK_BODY); setZIndexShadowBody(Z_PHYSICAL_SHADOW_FUEL_TANK_BODY); setZIndexHead(Z_PHYSICAL_FUEL_TANK_HEAD); setZIndexShadowHead(Z_PHYSICAL_SHADOW_FUEL_TANK_HEAD); } //Chroniony konstruktor kopiujący FuelTank::FuelTank(const FuelTank & FuelTankCopy) : Actor(FuelTankCopy),//konstruktor kopiujący klasy bazowej m_fuel_tank_name{ FuelTankCopy.m_fuel_tank_name }, m_fuel_tank_capacity{ FuelTankCopy.m_fuel_tank_capacity }, m_fuel{ FuelTankCopy.m_fuel }, m_fueltank_state{ FuelTankCopy.m_fueltank_state }, m_unit_controller{ FuelTankCopy.m_unit_controller } { setZIndexBody(Z_PHYSICAL_FUEL_TANK_BODY); setZIndexShadowBody(Z_PHYSICAL_SHADOW_FUEL_TANK_BODY); setZIndexHead(Z_PHYSICAL_FUEL_TANK_HEAD); setZIndexShadowHead(Z_PHYSICAL_SHADOW_FUEL_TANK_HEAD); } //Destruktor wirtualny FuelTank::~FuelTank(void) { //~Actor() m_fuel_tank_name = ""; m_fuel_tank_capacity = 0.0f; m_fuel = 0.0f; m_fueltank_state = EFuelTankState::FUELTANK_DEFAULT; m_unit_controller; } //Metoda zwraca typ obiektu /RTTI/ const std::string FuelTank::getType() const { return rtti.getNameClass(); } //Metoda zwraca nazwę zbiornika const std::string FuelTank::getFuelTankName() const { return m_fuel_tank_name; } //Metoda ustawia nazwę zbiornika void FuelTank::setFuelTankName(const std::string& fuel_tank_name) { m_fuel_tank_name = fuel_tank_name; } //Metoda zwraca pojemność zbiornika const float FuelTank::getFuelTankCapacity() const { return m_fuel_tank_capacity; } //Metoda ustawia pojemność zbiornika paliwa (tlenu) void FuelTank::setFuelTankCapacity(float fuel_tank_capacity) { if (fuel_tank_capacity < 0) return; m_fuel_tank_capacity = fuel_tank_capacity; } //Metoda zwraca ilość paliwa (tlenu) obiektu const float FuelTank::getFuel() const { return m_fuel; } //Metoda ustawia ilość paliwa (tlenu) obiektu void FuelTank::setFuel(float fuel) { if (fuel < 0) //jeśli tankujemy wartością ujemną - opuszczamy funkcję { m_fuel = 0; //zerujemy return; } if (m_fuel_tank_capacity > 0) //jeśli zbiornik ma pojemność { if (fuel >= m_fuel_tank_capacity) //jeśli ilość paliwa, którą chcemy zatankować //jest większa lub równa pojemności zbiornika //reszta (nadmiar) nie jest wykorzystany m_fuel = m_fuel_tank_capacity; //ustawiamy ilość paliwa na pojemność zbiornika else m_fuel = fuel; //tankujemy tyle ile zamierzamy (Parametr funkcji fuel) } else //zbiornik nie ma pojemnośći m_fuel = 0; //nie można tankować. } //Wirtualna metoda aktualizuje animacje w zależności od stanu logiki obiektu (move, attack, death, etc...) void FuelTank::updateAnimations(float dt) { switch (m_fueltank_state) { case EFuelTankState::FUELTANK_DEFAULT: { if (p_anim_set) { setAnimationBody(p_anim_set->getFuelBodyDefaultAnim()); setAnimationHead(p_anim_set->getFuelHeadDefaultAnim()); } break; } case EFuelTankState::FUELTANK_RESERVE: { if (p_anim_set) { setAnimationBody(p_anim_set->getFuelBodyReserveAnim()); setAnimationHead(p_anim_set->getFuelHeadReserveAnim()); } break; } case EFuelTankState::FUELTANK_EMPTY: { if (p_anim_set) { setAnimationBody(p_anim_set->getFuelBodyEmptyAnim()); setAnimationHead(p_anim_set->getFuelHeadEmptyAnim()); } break; } case EFuelTankState::FUELTANK_DAMAGE: { if (p_anim_set) { setAnimationBody(p_anim_set->getFuelBodyDamageAnim()); setAnimationHead(p_anim_set->getFuelHeadDamageAnim()); } break; } default: break; } } //Metoda zwraca referencjcę na moduł sterowania Switch & FuelTank::getUnitController() { return m_unit_controller; } //Wirtualna metoda aktualizująca obiekt void FuelTank::update(float dt) { updateShadow(dt); //aktualizacja shadow engine if (m_unit_controller.getState()) updateAnimations(dt); } }//namespace equipment
Java
UTF-8
663
3.453125
3
[]
no_license
package array; /** * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii */ public class BestTimeToBuyAndSellStockII { public int maxProfit(int[] prices) { if (prices == null || prices.length < 2) return 0; int profit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) { profit += prices[i] - prices[i - 1]; } } return profit; } public static void main(String[] args) { BestTimeToBuyAndSellStockII obj = new BestTimeToBuyAndSellStockII(); System.out.println(obj.maxProfit(new int[]{7, 1, 5, 3, 6, 4})); } }