language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
779
2.75
3
[]
no_license
## CORS is 💔 Next.js is ♥ Are you frustrated with the CORS error while using Github Jobs API? Use [this URL](https://github-api-next.vercel.app/api/positions) to get the data without the headache. You can pass all the query params that main API supports. [See it here](https://jobs.github.com/api) ![IMAGE](https://user-images.githubusercontent.com/36589645/108876414-311fcd00-7624-11eb-8aad-deead053ca86.png) Uses Next.js API routes to get the data from the main [Github Jobs API](https://jobs.github.com/positions.json) so you don't have to bang your head for CORS error. Thanks to [Next.js](https://nextjs.org/) and the [Vercel](https://vercel.com/) it only took 5 minutes. ## Read more about [CORS on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
Markdown
UTF-8
851
3.03125
3
[]
no_license
# React Blog Template Quickly create a simple react blog using this template. ## How to use * clone this repo * add markdown files for articles(in the articles directory) * edit config file(right now the only two blog theme options are Theme1 and Theme2) and add custom css(in the client directory) * swap out logo image for your own(in the assets directory) * in the terminal go to the scripts directory and run `node upload.js ../articles/ ../client/config.json` * run `yarn start` to see your blog locally * deploy blog using [surge](https://surge.sh/) or [GitHub Pages](https://pages.github.com/) ## Note After every change in the config file or to any articles you must run the upload script. ### Future features * Admin dashboard with all configs and articles editable there * More themes to choose from * "other" page template option
PHP
UTF-8
3,284
2.765625
3
[]
no_license
<?php include 'blob.php'; $target_dir = "./Pictures/"; $name=basename( $_FILES["fileToUpload"]["name"]); $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); $username; $address; $county; $country; $dob; $number; $message; $data; $blobUrl="https://phblobtest.blob.core.windows.net/mycontainer/".$name; // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { //Set variable to input form entries $username = $_POST['name']; $address = $_POST['address']; $county = $_POST['county']; $country = $_POST['country']; $dob = $_POST['dob']; $number = $_POST['number']; //Add variables to an array to be converted to json obejct $arr = array('Name' => $username, 'Address' => $address, 'County' => $county, 'Country' => $country, 'DOB' => $dob,'Number' => $number,'URL'=>$blobUrl); $data =json_encode($arr); $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { $uploadOk = 1; } else { $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { $message= "Sorry, file already exists."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { $message= "Sorry, your file was not uploaded. Please ensure your file is an image."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { $message= basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; //Create new blob instance and upload image to blob //upload json object to blob as well $blob = new Blob(); $blob->newBlob($name); $blob->JData($username,$data); } else { $message= "Sorry, there was an error uploading your file."; } } ?> <link href="style.css?ts=<?=time()?>&quot" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <html> <body id="body"> <div class="container-fluid"> <div class="row"> <div class="col-xs-12 col-md-12 top"> <h2><?php echo $message ?></h2> </div> </div> </div> <div class="container-fluid"> <div class="row"> <div class="col-xs-12 col-md-12 top"> <img class="img" src=./Pictures/<?php echo $name ?>> </div> </div> <div class="row"> <div class="col-xs-12 col-md-4"> </div> <div class="col-xs-12 col-md-4 mid head"> <a href="index.php" class="link" >Upload Another Image</a> <h2>Your Details</h2> <h3>Name</h3> <h4><?php echo $username ?></h4> <h3>Address</h3> <h4><?php echo $address ?></h4> <h3>County</h3> <h4><?php echo $county ?></h4> <h3>Country</h3> <h4><?php echo $country ?></h4> <h3>Number</h3> <h4><?php echo $number ?></h4> <h3>Date Of Birth</h3> <h4><?php echo $dob ?></h4> <a class="link" href="<?php echo $blobUrl ?>">Image Download</a> </div> <div class="col-xs-12 col-md-4"> </div> </div> </div> </body> </html>
C++
GB18030
966
3.0625
3
[]
no_license
// 10.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include <string> #include <vector> #include <iostream> using namespace std; class Solution { public: bool isMatch(string s, string p) { int m = s.size(); int n = p.size(); auto matches = [&](int i, int j) { if (i == 0) return false; if (p[j - 1] == '.') return true; return s[i - 1] == p[j - 1]; }; vector<vector<int>> f(m + 1, vector<int>(n + 1)); f[0][0] = true; for (int i = 0; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (p[j - 1] == '*') { f[i][j] = f[i][j - 2]; if (matches(i, j - 1)) { f[i][j] = f[i - 1][j]; } } else { if (matches(i, j)) { f[i][j] = f[i - 1][j - 1]; } } } } } }; int main() { Solution sol; string s = ""; string p = "c*"; cout << sol.isMatch(s, p) << endl; system("pause"); }
Java
UTF-8
505
2.515625
3
[]
no_license
package com.example.hkforum.model; public class Comment { public String Title, Comment, Username; public Comment(){ } public Comment(String Title, String comment, String username) { this.Title = Title; this.Comment = comment; this.Username = username; } public String getShowTitle(){ return Title; } public String getShowComment() { return Comment; } public String getShowUsername() { return Username; } }
C++
UTF-8
4,733
2.609375
3
[ "MIT" ]
permissive
#include "GY_85.h" void GY_85::SetAccelerometer() { //Put the ADXL345 into +/- 4G range by writing the value 0x01 to the DATA_FORMAT register. Wire.beginTransmission( ADXL345 ); // start transmission to device Wire.write( 0x31 ); // send register address Wire.write( 0x01 ); // send value to write Wire.endTransmission(); // end transmission //Put the ADXL345 into Measurement Mode by writing 0x08 to the POWER_CTL register. Wire.beginTransmission( ADXL345 ); // start transmission to device Wire.write( 0x2D ); // send register address //Power Control Register Wire.write( 0x08 ); // send value to write Wire.endTransmission(); // end transmission } int* GY_85::readFromAccelerometer() { static int axis[3]; int buff[6]; Wire.beginTransmission( ADXL345 ); // start transmission to device Wire.write( DATAX0 ); // sends address to read from Wire.endTransmission(); // end transmission Wire.beginTransmission( ADXL345 ); // start transmission to device Wire.requestFrom( ADXL345, 6 ); // request 6 bytes from device uint8_t i = 0; while(Wire.available()) // device may send less than requested (abnormal) { buff[i] = Wire.read(); // receive a byte i++; } Wire.endTransmission(); // end transmission axis[0] = ((buff[1]) << 8) | buff[0]; axis[1] = ((buff[3]) << 8) | buff[2]; axis[2] = ((buff[5]) << 8) | buff[4]; return axis; } //---------------------------------------- void GY_85::SetCompass() { //Put the HMC5883 IC into the correct operating mode Wire.beginTransmission( HMC5883 ); //open communication with HMC5883 Wire.write( 0x02 ); //select mode register Wire.write( 0x00 ); //continuous measurement mode Wire.endTransmission(); } int* GY_85::readFromCompass() { static int axis[3]; //Tell the HMC5883 where to begin reading data Wire.beginTransmission( HMC5883 ); Wire.write( 0x03 ); //select register 3, X MSB register Wire.endTransmission(); //Read data from each axis, 2 registers per axis Wire.requestFrom( HMC5883, 6 ); if(6<=Wire.available()){ axis[0] = Wire.read()<<8; //X msb axis[0] |= Wire.read(); //X lsb axis[2] = Wire.read()<<8; //Z msb axis[2] |= Wire.read(); //Z lsb axis[1] = Wire.read()<<8; //Y msb axis[1] |= Wire.read(); //Y lsb } return axis; } //---------------------------------------- int g_offx = 0; int g_offy = 0; int g_offz = 0; void GY_85::SetGyro() { Wire.beginTransmission( ITG3200 ); Wire.write( 0x3E ); Wire.write( 0x00 ); Wire.endTransmission(); Wire.beginTransmission( ITG3200 ); Wire.write( 0x15 ); Wire.write( 0x07 ); Wire.endTransmission(); Wire.beginTransmission( ITG3200 ); Wire.write( 0x16 ); Wire.write( 0x1E ); // +/- 2000 dgrs/sec, 1KHz, 1E, 19 Wire.endTransmission(); Wire.beginTransmission( ITG3200 ); Wire.write( 0x17 ); Wire.write( 0x00 ); Wire.endTransmission(); delay(10); GyroCalibrate(); } void GY_85::GyroCalibrate() { static int tmpx = 0; static int tmpy = 0; static int tmpz = 0; g_offx = 0; g_offy = 0; g_offz = 0; for( uint8_t i = 0; i < 10; i ++ ) //take the mean from 10 gyro probes and divide it from the current probe { delay(10); float* gp = readGyro(); tmpx += *( gp); tmpy += *(++gp); tmpz += *(++gp); } g_offx = tmpx/10; g_offy = tmpy/10; g_offz = tmpz/10; } float* GY_85::readGyro() { static float axis[4]; Wire.beginTransmission( ITG3200 ); Wire.write( 0x1B ); Wire.endTransmission(); Wire.beginTransmission( ITG3200 ); Wire.requestFrom( ITG3200, 8 ); // request 8 bytes from ITG3200 int i = 0; uint8_t buff[8]; while(Wire.available()) { buff[i] = Wire.read(); i++; } Wire.endTransmission(); axis[0] = ((buff[4] << 8) | buff[5]) - g_offx; axis[1] = ((buff[2] << 8) | buff[3]) - g_offy; axis[2] = ((buff[6] << 8) | buff[7]) - g_offz; axis[3] = ((buff[0] << 8) | buff[1]); // temperature return axis; } void GY_85::init() { SetAccelerometer(); SetCompass(); SetGyro(); }
TypeScript
UTF-8
3,641
2.75
3
[ "MIT" ]
permissive
import { expect } from 'chai'; import * as sinon from 'sinon'; import { idle } from '../src/index'; describe('Scheduler.Idle', () => { it('should exist', () => { expect(idle).exist; }); it('should act like the async scheduler if delay > 0', () => { let actionHappened = false; const sandbox = sinon.sandbox.create(); const fakeTimer = sandbox.useFakeTimers(); idle.schedule(() => { actionHappened = true; }, 50); expect(actionHappened).to.be.false; fakeTimer.tick(25); expect(actionHappened).to.be.false; fakeTimer.tick(25); expect(actionHappened).to.be.true; sandbox.restore(); }); it('should cancel animationFrame actions when delay > 0', () => { let actionHappened = false; const sandbox = sinon.sandbox.create(); const fakeTimer = sandbox.useFakeTimers(); idle .schedule(() => { actionHappened = true; }, 50) .unsubscribe(); expect(actionHappened).to.be.false; fakeTimer.tick(25); expect(actionHappened).to.be.false; fakeTimer.tick(25); expect(actionHappened).to.be.false; sandbox.restore(); }); it('should schedule an action to happen later', (done: MochaDone) => { let actionHappened = false; idle.schedule(() => { actionHappened = true; done(); }); //Scheduled action happened synchronously expect(actionHappened).to.be.false; }); it('should execute recursively scheduled actions in separate asynchronous contexts', ( done: MochaDone ) => { let syncExec1 = true; let syncExec2 = true; idle.schedule( function(index: any) { if (index === 0) { this.schedule(1); idle.schedule(() => { syncExec1 = false; }); } else if (index === 1) { this.schedule(2); idle.schedule(() => { syncExec2 = false; }); } else if (index === 2) { this.schedule(3); } else if (index === 3) { if (!syncExec1 && !syncExec2) { done(); } else { done(new Error('Execution happened synchronously.')); } } }, 0, 0 ); }); it('should cancel the animation frame if all scheduled actions unsubscribe before it executes', ( done: MochaDone ) => { let idleExec1 = false; let idleExec2 = false; const action1 = idle.schedule(() => { idleExec1 = true; }); const action2 = idle.schedule(() => { idleExec2 = true; }); expect(idle.scheduled).to.exist; expect(idle.actions.length).to.equal(2); action1.unsubscribe(); action2.unsubscribe(); expect(idle.actions.length).to.equal(0); expect(idle.scheduled).to.equal(undefined); idle.schedule(() => { expect(idleExec1).to.equal(false); expect(idleExec2).to.equal(false); done(); }); }); it('should execute the rest of the scheduled actions if the first action is canceled', ( done: MochaDone ) => { let actionHappened = false; let firstSubscription = null; let secondSubscription: any = null; firstSubscription = idle.schedule(() => { actionHappened = true; if (secondSubscription) { secondSubscription.unsubscribe(); } done(new Error('The first action should not have executed.')); }); secondSubscription = idle.schedule(() => { if (!actionHappened) { done(); } }); if (actionHappened) { done(new Error('Scheduled action happened synchronously')); } else { firstSubscription.unsubscribe(); } }); });
C++
UHC
2,450
2.65625
3
[]
no_license
#pragma once #include "Linear.h" /*==================================================================== Z-Order 浹 ó Player, Enemy, Object Ʈ ü ̴ GameObject ŬԴϴ. ====================================================================*/ struct tagShadow { RECT rc; vector3 LT, RT, RB, LB; vector3 pos; float width, height; }; class GameObject { public: GameObject* obstacle; OBJECT_GROUP group; //׷ OBJECT_TYPE type; //Ʈ Ÿ OBJECT_DESTRUCTION des; //ı int destructionCount; //ı Ƚ WEAPON_TYPE weaponType; // Ÿ ITEM_TYPE itemType; // Ÿ DIRECTION dir; //Ʈ image* img; //̹ POINT imgIndex; // ε animation* ani; //ִϸ̼ animation* ani1; //ִϸ̼ vector3 pos; //ġ vector3 prePos; // ġ vector3 size; //ũ (x,z) RECT rc; //Ʈ Linear topPlane[4]; // Linear bottomPlane[4]; //Ʒ Linear sideHeight[4]; // ׸ е, 浹 ó int alpha; // (0~255) float angle; // float zAngle; //Z float margin; //z bool isActive; //Ȱȭ bool isRender; // bool isShadow; //׸ڰ ִ bool isBroken; //Ʈ ı tagShadow shadow; //׸ ü tagShadow preShadow; public: GameObject() {} virtual ~GameObject() {} virtual void init(OBJECT_GROUP _group, image* _img, vector3 _pos); //ʱȭ virtual void init(OBJECT_GROUP _group, OBJECT_TYPE _type, image* _img, vector3 _pos, float a); //Ʈ ʱȭ virtual void release(); virtual void update(); virtual void render(); /*==================================================================== FUNCTION ====================================================================*/ void RectRenew(); //Ʈ void shadowUpdate(); void PolyLineRender(HDC hdc); // /*==================================================================== SETTER ====================================================================*/ void setGOAni(animation* an) { ani = an; } void setPosX(float x) { pos.x = x; } void setPosY(float y) { pos.y = y; } void setPosZ(float z) { pos.z = z; } };
C#
UTF-8
2,461
2.796875
3
[]
no_license
using System; using System.Collections.Generic; using BookStorage.Interfaces; using BookStorage.Models; using BookStorage.Service; using BookStorage.Storage; namespace BookStorage { internal class Program { private static void Main(string[] args) { Book bookForTest = new Book("978-0-141-34844-5", "Rebecca Donovan", "reason to breathe", "Pinguin Books", 2012, 531, 8); IFormatProvider formatProvider = new BookFormatter(); Console.WriteLine(String.Format(new BookFormatter(), "{0:all}", bookForTest)); Console.WriteLine(String.Format(new BookFormatter(), "{0:nameauthor}", bookForTest)); Console.WriteLine(String.Format(new BookFormatter(), "{0:nameauthoryearpages}", bookForTest)); Console.WriteLine(String.Format(new BookFormatter(), "{0:isbn}", bookForTest)); Console.WriteLine(String.Format(new BookFormatter(), "{0:price}", bookForTest)); Console.WriteLine(String.Format(new BookFormatter(), "{0}", bookForTest)); //Console.WriteLine(bookForTest.ToString("2", )); //Console.WriteLine(bookForTest.ToString("3", )); //Console.WriteLine(bookForTest.ToString("4", )); //Console.WriteLine(bookForTest.ToString("5", )); //Console.WriteLine(bookForTest.ToString("6", )); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("______________________________________________________________________"); IStorage<Book> storage = new BookListStorage("test.bin"); IService service = new BookListService(storage); ToConsole(service.GetAllBooks()); service.AddBook(new Book("978-3-16-123451-10", "test", "test", "test", 2152, 1264, 1111)); ToConsole(service.GetAllBooks()); ToConsole(service.FindBookByTag(service.GetAllBooks(), "name", "test")); ToConsole(service.SortBooksByTag(service.GetAllBooks(), "author")); Console.ReadLine(); } private static void ToConsole(List<Book> books) { foreach (var book in books) { Console.WriteLine(book); } Console.WriteLine(); } private static void ToConsole(Book book) { Console.WriteLine(book); Console.WriteLine(); } } }
C#
UTF-8
835
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BanqueAPP { class Program { static void Main(string[] args) { Client c1 = new Client("Zouhri","Hamza","casa"); Client c2 = new Client("Aya", "zouhri", "rabat"); MAD solde1 = new MAD(8000); MAD solde4 = new MAD(100); solde1.afficher(); Compte cc1 = new Compte(c2, solde1); cc1.crediter(solde4); cc1.debiter(solde4); cc1.consulter(); Compte_Epargne cpt = new Compte_Epargne(c1, solde1,50); cpt.calcule_interet(); cpt.consulter(); Console.ReadKey(); } } }
C++
UTF-8
1,632
2.6875
3
[]
no_license
#include <iostream> #include <bits/stdc++.h> #include <chrono> #include <stdlib.h> #include <algorithm> #include "cluster.h" using namespace std; using std::cout; using std::chrono::high_resolution_clock; using std::chrono::duration; int main(int argc, char* argv[]) { srand (time(NULL)); high_resolution_clock::time_point start; high_resolution_clock::time_point end; int N = stoi(argv[1]); int thread = stoi(argv[2]); float totalttime =0; int maxDist,threadID; int *arr = new(nothrow) int[N]; int *centers = new(nothrow) int[thread]; int *dists = new(nothrow) int[thread]; for (int i = 0; i < N; i++) { arr[i] = rand()%N+1; } sort(arr,arr+N); for (int i = 0; i <thread; i++) { centers[i] = (2*(i+1)-1)*N/(2*thread) ; dists[i] = 0; } for(int i=0;i<11;i++) { duration<double, std::milli> duration_sec; start = high_resolution_clock::now(); cluster(N,thread,arr,centers,dists); end = high_resolution_clock::now(); duration_sec = std::chrono::duration_cast<duration<double, std::milli>>(end - start); totalttime += duration_sec.count(); if(i!=10) { for(int i=0;i<thread;i++) { dists[i] =0; } } } //find maximum element index and value threadID = distance(dists, max_element(dists,dists + thread)); maxDist = dists[threadID]; // Print the required output cout<<maxDist<<endl; cout<<threadID<<endl; cout <<totalttime/10<<endl; delete[] centers; delete[] arr; delete[] dists; return 0; }
Python
UTF-8
1,360
2.953125
3
[]
no_license
import csv import numpy as np def readCSV(filename, dtype="int64", verbose=True): """ Input: Str of csv filename Output: numpy.ndarray of Nx17 """ with open(filename, 'r') as foo: if verbose: print("Reading labels from {}...".format(filename)) csvreader = csv.reader(foo, dialect='excel') label_mat = [] if dtype=="int64": dtype = np.int64 elif dtype=="float": dtype = np.float64 for line in csvreader: tmp = np.asarray(line).astype(dtype).reshape((1, -1)) label_mat.append(tmp) label_mat = np.concatenate(label_mat, axis=0) return label_mat def writeCSV(filename, label_mat): """ Input: filename: str label_mat: np.ndarray """ assert isinstance(label_mat, np.ndarray), "mat format error" assert label_mat.ndim==2 and label_mat.shape[1]==17, "mat format error" with open(filename, 'w', newline="") as csvfile: print("Writing labels to {}...".format(filename)) writer = csv.writer(csvfile, dialect='excel') writer.writerows(label_mat) print("Successful!") if __name__ == "__main__": y_pred_mat = readCSV("c:/users/pzq/desktop/result-merge-1202.csv") writeCSV("c:/users/pzq/desktop/test.csv", y_pred_mat) import ipdb; ipdb.set_trace()
TypeScript
UTF-8
4,684
2.53125
3
[ "MIT" ]
permissive
// tslint:disable:no-reserved-keywords no-bitwise /** * Team */ export enum Team { /** * Good */ good, /** * Bad */ bad, } export const enumMapTeam: Record<string, Team> = { Good: Team.good, Bad: Team.bad, good: Team.good, bad: Team.bad, }; // // Role // ------------------------------------------------------------ /** * Role, including complexity. */ export interface RoleData { /** * 核心 */ readonly carry: number; /** * 辅助 */ readonly support: number; /** * 爆发 */ readonly nuker: number; /** * 控制 */ readonly disabler: number; /** * 打野 */ readonly jungler: number; /** * 耐久 */ readonly durable: number; /** * 逃生 */ readonly escape: number; /** * 推进 */ readonly pusher: number; /** * 先手 */ readonly initiator: number; /** * 复杂程度 */ readonly complexity: number; } // // Armor // ------------------------------------------------------------ /** * Armor data. */ export interface DefenseData { readonly armorPhysical: number; readonly magicalResistance: number; } // // Attack // ------------------------------------------------------------ /** * Categories for attack capability. */ export enum AttackCapability { DOTA_UNIT_CAP_MELEE_ATTACK, DOTA_UNIT_CAP_RANGED_ATTACK, } export enum AttackDamageType { DAMAGE_TYPE_ArmorPhysical, } /** * Attack data. */ export interface AttackData { readonly capability: AttackCapability; readonly damage: { readonly type: AttackDamageType; readonly min: number; readonly max: number; }; readonly rate: number; readonly range: number; readonly animationPoint: number; readonly acquisitionRange: number; readonly projectileSpeed: number; } // // Attribute // ------------------------------------------------------------ /** * Categories for attribute. */ export enum Attribute { strength, agility, intelligence, } export const enumMapAttribute: Record<string, Attribute> = { DOTA_ATTRIBUTE_STRENGTH: Attribute.strength, DOTA_ATTRIBUTE_AGILITY: Attribute.agility, DOTA_ATTRIBUTE_INTELLECT: Attribute.intelligence, }; /** * Attribute data. */ export interface AttributeData { readonly primary: Attribute; readonly strength: { readonly base: number; readonly gain: number; }; readonly agility: { readonly base: number; readonly gain: number; }; readonly intelligence: { readonly base: number; readonly gain: number; }; } // // Movement // ------------------------------------------------------------ /** * Categories for movement capability. */ export enum MovementCapability { DOTA_UNIT_CAP_MOVE_NONE, DOTA_UNIT_CAP_MOVE_GROUND, DOTA_UNIT_CAP_MOVE_FLY, } /** * Movement data. */ export interface MobilityData { readonly capabilities: MovementCapability; readonly speed: number; readonly turnRate: number; readonly hasAggressiveStance: boolean; } // // Status // ------------------------------------------------------------ /** * Status data. */ export interface StatusData { readonly health: number; readonly healthRegen: number; readonly mana: number; readonly manaRegen: number; } // // Vision // ------------------------------------------------------------ /** * Vision data. */ export interface VisionData { readonly day: number; readonly night: number; } // // Game Mode // ------------------------------------------------------------ export interface GameModeData { readonly BotImplemented: boolean; readonly CMEnabled: boolean; readonly CMTournamentIgnore: boolean; readonly new_player_enable: boolean; readonly Legs: number; readonly AbilityDraftDisabled: boolean; readonly ARDMDisabled: boolean; } // // Others // ------------------------------------------------------------ export interface OtherData { readonly gibType: string; readonly gibTintColor?: string; readonly glowColor?: string; } // // Aggregation // ------------------------------------------------------------ import { ModelBase } from './base'; /** * Data structure for heroes. */ export interface Hero extends ModelBase { readonly team: Team; readonly alias: string[]; readonly roles: RoleData; readonly abilities: string[]; readonly talents: string[]; readonly defense: DefenseData; readonly attack: AttackData; readonly attributes: AttributeData; readonly mobility: MobilityData; readonly status: StatusData; readonly vision: VisionData; readonly gameMode: GameModeData; readonly others: OtherData; } export interface HeroGroup { primary: string; heroes: ReadonlyArray<Hero>; }
Python
UTF-8
2,727
2.828125
3
[]
no_license
#!/usr/local/bin/python #Warren Reed #Principles of Urban Informatics #Assignment 5, Exercise 3 #Dot Plot import pandas as pd from scipy import * import numpy as np import matplotlib.pyplot as plt from matplotlib import * import pylab from pylab import * from matplotlib.dates import MonthLocator, DateFormatter, YearLocator from matplotlib.ticker import FixedLocator, FixedFormatter from pandas.tools.plotting import scatter_matrix from numpy import polyval, polyfit os.environ['PATH'] = os.environ['PATH'] + ':/usr/texbin/latex' #Clearing plot figure and setting pylab formatting pyrameters clf() params = {'axes.labelsize': 10, 'text.fontsize': 10, 'legend.fontsize': 13, 'xtick.labelsize': 6, 'ytick.labelsize': 6, 'xtick.direction': 'out', 'text.usetex': True} pylab.rcParams.update(params) def main(): processor = [] year = [] num_transistor = [] header = [] with open('microprocessors.dat','r') as myFile3: header = myFile3.readline().strip().split(',') for line in myFile3: processor.append(line.strip().split(',')[0]) year.append(line.strip().split(',')[1]) num_transistor.append(log10(int(line.strip().split(',')[2]))) #creating dataframe df3 = pd.DataFrame({str(header[0]):processor, str(header[1]):year, str(header[2]):num_transistor}) df3['Processor'] = df3['Processor'].map(lambda x: x.rstrip(' processor')) df3.sort(['Year of Introduction'], ascending=True, inplace=True) df3 = df3.reset_index(drop=False) fig, (ax1, ax2) = plt.subplots(1,2, sharey=True) #setting 1st subplot format ax1.plot(df3['Transistors'],range(1,len(df3['Transistors'])+1),'o') ticklist = range(1,14) ticknums = FixedLocator((range(1,14))) ax1.yaxis.set_major_locator(ticknums) ticknames = FixedFormatter(df3['Processor']) ax1.yaxis.set_major_formatter(ticknames) ax1.set_title('Transistors Count (Log Scale)') ax1.set_ylim(0,14) ax1.spines['top'].set_visible(False) ax1.xaxis.set_ticks_position('bottom') ax1.spines['right'].set_visible(False) ax1.spines['left'].set_visible(False) ax1.yaxis.set_ticks_position('none') ax1.yaxis.grid(b=True, which='major', linestyle='--') #Setting 2nd subplot format ax2.plot(df3['Year of Introduction'],range(1,len(df3['Year of Introduction'])+1),'o') ax2.set_ylim(0,14) ax2.set_title('Year of Introduction') ax2.set_yticklabels(df3['Processor']) ax2.spines['top'].set_visible(False) ax2.xaxis.set_ticks_position('bottom') ax2.spines['right'].set_visible(False) ax2.spines['left'].set_visible(False) ax2.yaxis.set_ticks_position('none') ax2.yaxis.grid(b=True, which='major', linestyle='--') plt.savefig('Problem3.png',dpi=200) if __name__ == "__main__": main()
TypeScript
UTF-8
1,142
2.515625
3
[]
no_license
import { instruct } from 'myr'; import fs from 'fs'; import { ReflNode, ReflProgram } from "./ReflNode"; import { StringLiteral } from './StringLiteral'; import { Refl } from '../Refl'; import { Program } from './Program'; export class UsingExpression extends ReflNode { constructor(public path: ReflNode) { super();} get instructions(): ReflProgram { let ext = Refl.fileExtension let given = (this.path as StringLiteral).value; if (!given.endsWith(ext)) { given += ext; } let paths = [ __dirname + "\\..\\lib\\" + given, // given, process.cwd() + "\\" + given, ]; let path = paths.find(p => fs.existsSync(p)) if (path) { let contents: string = fs.readFileSync(path).toString(); let ast = Refl.tree(contents); return [ instruct('mark'), ...(new Program(ast)).instructions, instruct('sweep'), ]; } else { console.debug("checked paths", { paths, given }) throw new Error("Could not find " + given) } } }
Markdown
UTF-8
2,724
3.125
3
[ "MIT" ]
permissive
# MySQL常见操作 重点: ## 数据库增删改查 [具体操作](https://blog.csdn.net/qq_38345598/article/details/79416578) [select操作](https://www.cnblogs.com/gates/p/3936974.html) [SQL面试题](https://www.cnblogs.com/diffrent/p/8854995.html) ### SELECT(重点) select * from tablename where 条件 ### DELETE 删除一行数据 ```SQL delete from Employees where EmployeeID=32 /*删除EmployeeID=32的数据*/ ``` 删除所有行数据 ```SQL delete from Employees ``` ### UPDATE 更新单个列 ```SQL update Employees set LastName='hello world' where EmployeeID=30 ``` 更新多个列数据 ```SQL update Employees where EmployeeID=30 set LastName='helloworld1',FirstName='ECJTU' ``` ### INSERT ```SQL INSERT INTO table_name (列1,列2,......) VALUES (值1,值2,.....) ``` ## 1、数据库操作 ### 创建名为demo的数据库 格式:create database demo; 使用数据库:use demo; ### 删除数据库 格式:drop database demo; ### 展示所有数据库: show databases; ## 2、表的操作 ### 创建表 ```SQL CREATE TABLE student( id INT, NAME VARCHAR(20) ); ``` 上面创建表的时候涉及到一个完整性约束条件,下面就列出一个完整性约束条件表: |约束条件|说明| |---|---| |PRIMARY KEY|标识该属性为该表的主键,可以唯一的标识对应的元组| | FOREIGN KEY | 标识该属性为该表的外键,是与之联系某表的主键 | | NOT NULL | 标识该属性不能为空 | | UNIQUE | 标识该属性的值是唯一的 | |AUTO_INCREMENT|自增1 标识该属性的值是自动增加,这是MySQL的SQL语句的特色 | | DEFAULT| 为该属性设置默认值 | ### 表的查询 #### 查看表的结构 格式: desc student; ### 修改表 #### 修改表名 格式:ALTER TABLE 旧表名 RENAME 新表名; ALTER TABLE student RENAME student4; #### 修改字段的数据类型 格式:ALTER TABLE 表名 MODIFY 属性名 数据类型; ALTER TABLE student1 MODIFY name varchar(30); #### 修改字段名 格式:ALTER TABLE 表名 CHANGE 旧属性名 新属性名 新数据类型; ALTER TABLE student1 CHANGE name stu_name varchar(40); #### 增加字段 格式:ALTER TABLE 表名 ADD 属性名1 数据类型 [完整性约束条件] [FIRST | AFTER 属性名2]; ALTER TABLE student1 ADD teacher_name varchar(20) NOT NULL AFTER id; 注:上面一行的意思是在id属性之后添加一个非空的名为“stu_name”的字段 ### 删除操作 #### 删除表 格式:DROP TABLE 表名; #### 删除字段 格式:ALTER TABLE 表名 DROP 属性名; #### 删除外键 格式:ALTER TABLE 表名 DROP FOREIGN KEY 外键别名; [MYSQL常用命令](https://www.cnblogs.com/sqbk/p/5806797.html)
C#
UTF-8
655
3.15625
3
[]
no_license
using System; namespace KnightsTour { public class Knight { public struct Move { public int cols { get; set; } public int rows { get; set; } public Move(int cols, int rows) : this() { this.cols = cols; this.rows = rows; } } public static Move[] moves = { new Move(-1, -2), new Move(-2, -1), new Move(1, -2), new Move(2, -1), new Move(1, 2), new Move(2, 1), new Move(-1, 2), new Move(-2, 1), }; } }
C++
UTF-8
405
3.015625
3
[]
no_license
#include<iostream> using namespace std; class A{ public: A() { } virtual int getk() { return 1; } void setk(int kk) { k = kk; } void pp() { printf("%d\n", k); } private: int k; }; class B : public A{ public: B() { setk(6); } int getk() { return 5; } }; int main(void){ B b; A *p = &b; printf("%d\n", p->getk()); p->pp(); system("pause"); return 0; }
Markdown
UTF-8
982
2.515625
3
[]
no_license
<p align="center"> <img src="https://user-images.githubusercontent.com/85905805/121959526-346ece00-cd65-11eb-8456-17440c1e4559.jpg"> </p> <h2>Introduction</h2> </br> <p>You can download our Windows and Android applications and track your tokens and earnings in your wallet.</p> <ul> <li>Goatzilla Windows/Android: Provide informations for holders.</li> <li>Goatzilla QR Reader: Only available on Android.</li> <li>Goatzilla D3 Chart: D3 chart will be prepared before on next update(Windows & Android)</li> </ul> <h2>Downloads</h2> Github is the only source where you can get official Goatzilla downloads. <h3>Windows</h3> <a href="https://github.com/goatzillatoken/goatzilla/releases/download/1.0/goatzilla.msi">Windows App (MSI)</a> </br> <a href="https://github.com/goatzillatoken/goatzilla/releases/download/1.0/setup.exe">Windows App (setup.exe)</a> <h3>Android</h3> <a href="https://github.com/goatzillatoken/goatzilla/releases/download/1.0/goatzilla.apk">Android Apk</a>
Java
UTF-8
6,174
1.734375
2
[ "Apache-2.0" ]
permissive
package com.umiwi.ui.fragment; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.umeng.analytics.MobclickAgent; import com.umiwi.ui.R; import com.umiwi.ui.activity.UmiwiContainerActivity; import com.umiwi.ui.adapter.MineShakeCouponAdapter; import com.umiwi.ui.beans.MineShakeCouponBean; import com.umiwi.ui.fragment.course.CourseDetailPlayFragment; import com.umiwi.ui.main.BaseConstantFragment; import com.umiwi.ui.main.UmiwiAPI; import java.util.ArrayList; import cn.youmi.framework.http.AbstractRequest; import cn.youmi.framework.http.AbstractRequest.Listener; import cn.youmi.framework.http.GetRequest; import cn.youmi.framework.http.HttpDispatcher; import cn.youmi.framework.http.parsers.GsonParser; import cn.youmi.framework.util.ListViewScrollLoader; import cn.youmi.framework.util.ToastU; import cn.youmi.framework.view.LoadingFooter; /** * @author tjie00 * @version 2014年9月11日 下午2:17:59 * <p/> * 我摇到的页面 */ public class ShakeCoupondFragment extends BaseConstantFragment { private ListView mListView; private MineShakeCouponAdapter mAdapter; private LoadingFooter mLoadingFooter; private ListViewScrollLoader mScrollLoader; @SuppressLint("InflateParams") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_frame_listview_layout, null); mActionBarToolbar = (Toolbar) view.findViewById(R.id.toolbar_actionbar); setSupportActionBarAndToolbarTitle(mActionBarToolbar, "我摇到的"); mListView = (ListView) view.findViewById(R.id.listView); mAdapter = new MineShakeCouponAdapter(); mLoadingFooter = new LoadingFooter(getActivity());// 加载更多的view mListView.addFooterView(mLoadingFooter.getView()); mScrollLoader = new ListViewScrollLoader(this, mLoadingFooter);// 初始化加载更多监听 mListView.setAdapter(mAdapter); mListView.setOnScrollListener(mScrollLoader);// 添加加载更多到listveiw mScrollLoader.onLoadFirstPage();// 初始化接口,加载第一页 mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { MineShakeCouponBean coupon = (MineShakeCouponBean) mAdapter.getItem(position); switch (Integer.parseInt(coupon.getType())) { case MineShakeCouponBean.TYPE_COUPON: ToastU.showShort(getActivity(), "优惠券购买时使用"); break; case MineShakeCouponBean.TYPE_HUODONG: ToastU.showShort(getActivity(), "若未领取请联系客服"); break; case MineShakeCouponBean.TYPE_GIFT: ToastU.showShort(getActivity(), "当前版本过低,请升级最新版本"); break; case MineShakeCouponBean.TYPE_BOOK: ToastU.showShort(getActivity(), "若未领取请联系客服"); break; case MineShakeCouponBean.TYPE_LEAKS: ToastU.showShort(getActivity(), "当前版本过低,请升级最新版本"); break; case MineShakeCouponBean.TYPE_COURSE: case MineShakeCouponBean.TYPE_COURSEFREE: Intent intent = new Intent(getActivity(), UmiwiContainerActivity.class); intent.putExtra(UmiwiContainerActivity.KEY_FRAGMENT_CLASS, CourseDetailPlayFragment.class); intent.putExtra(CourseDetailPlayFragment.KEY_DETAIURL, coupon.getDetailurl()); startActivity(intent); if (!"1".equalsIgnoreCase(coupon.getStatus())) { ToastU.showShort(getActivity(), "课程已过期,请重新购买!"); } break; default: ToastU.showShort(getActivity(), "当前版本过低,请升级最新版本"); break; } } }); return view; } @Override public void onLoadData() { super.onLoadData(); GetRequest<MineShakeCouponBean> mineCouponRequest = new GetRequest<MineShakeCouponBean>( UmiwiAPI.MINE_SHAKE_COUPONS, GsonParser.class, MineShakeCouponBean.class, mineCouponListener); HttpDispatcher.getInstance().go(mineCouponRequest); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(fragmentName); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(fragmentName); } private Listener<MineShakeCouponBean> mineCouponListener = new Listener<MineShakeCouponBean>() { @Override public void onResult(AbstractRequest<MineShakeCouponBean> request, MineShakeCouponBean t) { if (t == null) {// 主要用于防止服务器数据出错 mScrollLoader.showLoadErrorView("未知错误,请重试"); return; } final ArrayList<MineShakeCouponBean> coupons = t.getRecord(); mAdapter.setCoupons(coupons); mScrollLoader.setEnd(true); } @Override public void onError(AbstractRequest<MineShakeCouponBean> requet, int statusCode, String body) { mScrollLoader.showLoadErrorView(); } }; }
Java
UTF-8
15,130
1.976563
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 tallervistas; import java.util.logging.Level; import java.util.logging.Logger; import tallerdereparaciones.Conexion; import tallerdereparaciones.Servicio; import tallerdereparaciones.ServicioData; /** * * @author SilZitoS */ public class JIFServicio extends javax.swing.JInternalFrame { /** * Creates new form JIFServicio */ private ServicioData servicioData; private Conexion conexion; public JIFServicio() { initComponents(); try { conexion = new Conexion(); } catch (ClassNotFoundException ex) { Logger.getLogger(JIFServicio.class.getName()).log(Level.SEVERE, null, ex); } servicioData = new ServicioData(conexion); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); tCodigo = new javax.swing.JTextField(); tId = new javax.swing.JTextField(); tCosto = new javax.swing.JTextField(); tDescripcion = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jbBuscar = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); jbActualizar = new javax.swing.JButton(); jbGuardar = new javax.swing.JButton(); jbBorrar = new javax.swing.JButton(); jbLimpiar = new javax.swing.JButton(); jbSalir = new javax.swing.JButton(); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(102, 0, 102)); jLabel1.setText("SERVICIOS"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setText("CÓDIGO:"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("ID:"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("DESCRIPCIÓN:"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel5.setText("COSTO:"); tCodigo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tCodigoActionPerformed(evt); } }); tId.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tIdActionPerformed(evt); } }); tCosto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tCostoActionPerformed(evt); } }); tDescripcion.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tDescripcionActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel6.setText("$"); jbBuscar.setText("Buscar"); jbBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbBuscarActionPerformed(evt); } }); jLabel7.setFont(new java.awt.Font("Tahoma", 2, 10)); // NOI18N jLabel7.setText("(Buscar servicio por ID)"); jbActualizar.setText("Actualizar Datos"); jbActualizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbActualizarActionPerformed(evt); } }); jbGuardar.setText("Guardar"); jbGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbGuardarActionPerformed(evt); } }); jbBorrar.setText("Borrar"); jbBorrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbBorrarActionPerformed(evt); } }); jbLimpiar.setText("Limpiar"); jbLimpiar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbLimpiarActionPerformed(evt); } }); jbSalir.setText("Salir"); jbSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbSalirActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(165, 165, 165) .addComponent(jLabel1)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jbBorrar) .addGap(43, 43, 43) .addComponent(jbLimpiar) .addGap(44, 44, 44) .addComponent(jbSalir) .addGap(16, 16, 16)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jbGuardar))) .addGap(29, 29, 29) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(tDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(tId, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jbBuscar) .addGap(18, 18, 18) .addComponent(jLabel7)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tCosto, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbActualizar) .addGap(27, 27, 27)))))) .addContainerGap(25, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(tId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbBuscar) .addComponent(jLabel7)) .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(tCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(tDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(tCosto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(jbActualizar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbGuardar) .addComponent(jbBorrar) .addComponent(jbLimpiar) .addComponent(jbSalir)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void tCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tCodigoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tCodigoActionPerformed private void tIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tIdActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tIdActionPerformed private void tCostoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tCostoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tCostoActionPerformed private void tDescripcionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tDescripcionActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tDescripcionActionPerformed private void jbGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbGuardarActionPerformed int codigo=Integer.parseInt(tCodigo.getText()); String descripcion = tDescripcion.getText(); Double costo = Double.parseDouble(tCosto.getText()); Servicio servicio = new Servicio(codigo, descripcion, costo); servicioData.guardarServicio(servicio); tId.setText(servicio.getIdServicio()+""); }//GEN-LAST:event_jbGuardarActionPerformed private void jbBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBorrarActionPerformed int id=Integer.parseInt(tId.getText()); servicioData.borrarServicio(id); }//GEN-LAST:event_jbBorrarActionPerformed private void jbLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbLimpiarActionPerformed tId.setText(""); tCodigo.setText(""); tDescripcion.setText(""); tCosto.setText(""); }//GEN-LAST:event_jbLimpiarActionPerformed private void jbSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSalirActionPerformed dispose(); }//GEN-LAST:event_jbSalirActionPerformed private void jbActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbActualizarActionPerformed if (tId.getText() != null){ int id=Integer.parseInt(tId.getText()); int codigo=Integer.parseInt(tCodigo.getText()); String descripcion = tDescripcion.getText(); Double costo = Double.parseDouble(tCosto.getText()); Servicio servicio = new Servicio(id, codigo, descripcion, costo); servicioData.actualizarServicio(servicio); } }//GEN-LAST:event_jbActualizarActionPerformed private void jbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBuscarActionPerformed int id=Integer.parseInt(tId.getText()); Servicio servicio = servicioData.buscarServicio(id); if (servicio != null){ tCodigo.setText(servicio.getCodigo()+""); tDescripcion.setText(servicio.getDescripcion()); tCosto.setText(servicio.getCosto()+""); } else { tCodigo.setText(""); tDescripcion.setText(""); tCosto.setText(""); } }//GEN-LAST:event_jbBuscarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JButton jbActualizar; private javax.swing.JButton jbBorrar; private javax.swing.JButton jbBuscar; private javax.swing.JButton jbGuardar; private javax.swing.JButton jbLimpiar; private javax.swing.JButton jbSalir; private javax.swing.JTextField tCodigo; private javax.swing.JTextField tCosto; private javax.swing.JTextField tDescripcion; private javax.swing.JTextField tId; // End of variables declaration//GEN-END:variables }
PHP
UTF-8
340
2.5625
3
[]
no_license
<?php $famille=["Maman","Papa","Petit frère","Moi"]; print_r($famille); $plats=["pizza","hamburger"]; print_r($plats); $films=["Monstre et companie","Seigneur des anneaux"]; echo $films[0]; $moi= array( 'prenom' => 'Antoine', 'nom' => "Gjeloshaj", 'ville' => "bruxelles", 'age'=> 21, 'aime_le_foot'=>false ); echo $moi["ville"]; ?>
Python
UTF-8
1,280
3.515625
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Jan 07 11:17:20 2011 @author: RDC """ import unittest class MyClass: def __init__(self, value): self.value = value def my_method(self): if self.value < 0 : result = self.value else: result = False raise myError return result class myError(Exception): "this is the error text" class my_method_tester(unittest.TestCase): def test_my_function_neg(self): self.myclass = MyClass(-3) self.assertEqual(-3, self.myclass.my_method(), 'with negative values myclass.my_method() \ should give input value as result') def test_my_method_pos_workaround(self): self.myclass = MyClass(4) error_occurred = False try: self.myclass.my_method() except myError: error_occurred = True self.assertTrue(error_occurred, 'with positive values myclass.my_method() \ should raise myError') def test_my_method_pos(self): self.myclass = MyClass(4) self.assertRaises(myError, self.myclass.my_method) if __name__ == '__main__': unittest.main()
Markdown
UTF-8
24,737
2.890625
3
[ "CC-BY-NC-SA-4.0", "CC-BY-NC-ND-4.0", "MIT" ]
permissive
在分布式系统中,为了保证数据的可靠性与性能,我们不可避免的对数据进行复制与多节点存储,而数据一致性主要为了解决分布式多个存储节点情况下怎么保证逻辑上相同的副本能够返回相同的数据。 > [保证分布式系统数据一致性的 6 种方案 ](http://mp.weixin.qq.com/s?__biz=MzAwMDU1MTE1OQ==&mid=2653546976&idx=1&sn=c3fb2338389a41e7ab998c0c21bd3e5d&scene=23&srcid=0419TGxOI4Nac6fHhWRNDeR0#rd) 分布式系统常常通过数据的复制来提高系统的可靠性和容错性,并且将数据的副本存放到不同的机器上,由于多个副本的存在,使得维护副本一致性的代价很高。因此,许多分布式系统都采用弱一致性或者是最终一致性,来提高系统的性能和吞吐能力,这样不同的一致性模型也相继被提出。 强一致性要求无论数据的更新操作是在哪个副本上执行,之后所有的读操作都要能够获取到更新的最新数据。对于单副本的数据来说,读和写都是在同一份数据上执行,容易保证强一致性,但对于多副本数据来说,若想保障强一致性,就需要等待各个副本的写入操作都执行完毕,才能提供数据的读取,否则就有可能数据不一致,这种情况需要通过分布式事务来保证操作的原子性,并且外界无法读到系统的中间状态。 弱一致性指的是系统的某个数据被更新后,后续对该数据的读取操作,取到的可能是更新前的值,也可能是更新后的值,全部用户完全读取到更新后的数据,需要经过一段时间,这段时间称作“不一致性窗口”。 最终一致性是弱一致性的一种特殊形式,这种情况下系统保证用户最终能够读取到某个操作对系统的更新,“不一致性窗口”的时间依赖于网络的延迟、系统的负载以及副本的个数。 分布式系统中采用最终一致性的例子很多,如 MySQL 数据库的主/从数据同步,ZooKeeper 的 Leader Election 和 Atomic Broadcas 等。 # 数据一致性模型 - [分布式系统一致性的发展历史](http://36kr.com/p/5037166.html) [严格一致性](http://www.sigma.me/2011/05/6/strict-consistency.html)其实从物理定律上来说就是不能实现的(它要求写操作能够瞬间传播出去)。 [顺序一致性](http://www.sigma.me/2011/05/6/sequential-consistency.html)是可行的,在编程人员中很流行且广泛应用。但是它的性能很差。解决这个问题的方法是放宽一致性的模型。下表以限制程度递减的顺序给出了几种可能的模型。 | 一致性 | 说明 | | ------ | ------------------------------------------------------------------------------------------------ | | 严格 | 所有的共享访问事件都有绝对时间顺序 | | 顺序 | 所有进程都以相同的顺序检测到所有的共享访问事件 | | 因果 | 所有进程都以相同的顺序检测到所有因果联系的事件 | | 处理器 | PRAM 一致性+存储相关性 | | PRAM | 所有的进程按照预定的顺序检测到来自一个处理器的写操作,来自其他处理器的写操作不必以相同的顺序出现 | 另一措施是引入了明确的同步变量,正如[弱一致性](http://www.sigma.me/2011/05/6/weak-consistency.html),[释放一致性](http://www.sigma.me/2011/05/6/release-consistency.html)和[入口一致性](http://www.sigma.me/2011/05/6/entry-consistency.html)所做的那样。下表总结了这三种模式。当进程对普通共享数据变量执行操作时,不能保证它们何时对于其他进程是可见的。只有当访问同步变量后,变化才能传播出去。 | 一致性 | 说明 | | ------ | ------------------------------------------------ | | 弱 | 同步完成后,共享数据才可能保持一致 | | 释放 | 当离开临界区时,共享数据就保持一致 | | 入口 | 当进入临界区时,和该临界区相关的共享数据保持一致 | 这三种模型的不同在于其同步机制如何工作。但在这三种情况中,它们都可在一个临界区中执行多重的读写操作,而不引起数据传输。当临界区的操作完成后,最后结果或者广播发送给其他进程或准备就绪在其他进程需要时再发送出去。 ## 数据为中心的一致性模型 为了讨论的方便,下面先规定一下两个有关读写的表示法: 1. Write(y,a)表示向变量 y 写入数据 a; 2. Read(x,b)表示从变量 x 读出数据 b; ### 强一致性/原子一致性/线性一致性 所谓的强一致性(strict consistency),也称为原子一致性(atomic consistency)或者线性(Linearizability)。 它对一致性的要求两个: 1. 任何一次读都能读到某个数据的最近一次写的数据。 2. 系统中的所有进程,看到的操作顺序,都和全局时钟下的顺序一致。 显然这两个条件都对全局时钟有非常高的要求。强一致性,只是存在理论中的一致性模型,比它要求更弱一些的,就是顺序一致性。 ### 顺序一致性 顺序一致性(Sequential Consistency),也同样有两个条件,其一与前面强一致性的要求一样,也是可以马上读到最近写入的数据,然而它的第二个条件就弱化了很多,它允许系统中的所有进程形成自己合理的统一的一致性,不需要与全局时钟下的顺序都一致。 这里的第二个条件的要点在于: 1. 系统的所有进程的顺序一致,而且是合理的,就是说任何一个进程中,这个进程对同一个变量的读写顺序要保持,然后大家形成一致。 2. 不需要与全局时钟下的顺序一致。 可见,顺序一致性在顺序要求上并没有那么严格,它只要求系统中的所有进程达成自己认为的一致就可以了,即错的话一起错,对的话一起对,同时不违反程序的顺序即可,并不需要个全局顺序保持一致。 以下面的图来看看这两种一致性的对比: ![](http://mmbiz.qpic.cn/mmbiz/vxCq1iahXotiaFs84SvDRF5U3gefsfA2F8XDuktqj8WCQ2ohQW1lFia0b8UrMXgYySHibAPGatSIKa4avl9N4Z4lfA/640?wx_fmt=png&wxfrom=5&wx_lazy=1) (出自《分布式计算-原理、算法与系统》) 1. 图 a 是满足顺序一致性,但是不满足强一致性的。原因在于,从全局时钟的观点来看,P2 进程对变量 X 的读操作在 P1 进程对变量 X 的写操作之后,然而读出来的却是旧的数据。但是这个图却是满足顺序一致性的,因为两个进程 P1,P2 的一致性并没有冲突。从这两个进程的角度来看,顺序应该是这样的:Write(y,2) , Read(x,0) , Write(x,4), Read(y,2),每个进程内部的读写顺序都是合理的,但是显然这个顺序与全局时钟下看到的顺序并不一样。 2. 图 b 满足强一致性,因为每个读操作都读到了该变量的最新写的结果,同时两个进程看到的操作顺序与全局时钟的顺序一样,都是 Write(y,2) , Read(x,4) , Write(x,4), Read(y,2)。 3. 图 c 不满足顺序一致性,当然也就不满足强一致性了。因为从进程 P1 的角度看,它对变量 Y 的读操作返回了结果 0。那么就是说,P1 进程的对变量 Y 的读操作在 P2 进程对变量 Y 的写操作之前,这意味着它认为的顺序是这样的:write(x,4) , Read(y,0) , Write(y,2), Read(x,0),显然这个顺序又是不能被满足的,因为最后一个对变量 x 的读操作读出来也是旧的数据。因此这个顺序是有冲突的,不满足顺序一致性。 ### 因果一致性 因果一致性(Casual Consistency)在一致性的要求上,又比顺序一致性降低了:它仅要求有因果关系的操作顺序得到保证,非因果关系的操作顺序则无所谓。 因果相关的要求是这样的: 1. 本地顺序:本进程中,事件执行的顺序即为本地因果顺序。 2. 异地顺序:如果读操作返回的是写操作的值,那么该写操作在顺序上一定在读操作之前。 3. 闭包传递:和时钟向量里面定义的一样,如果 a->b,b->c,那么肯定也有 a->c。 以下面的图来看看这两种一致性的对比: ![](http://mmbiz.qpic.cn/mmbiz/vxCq1iahXotiaFs84SvDRF5U3gefsfA2F820z5wc1aTap2rbuoaicibD2NOLbxdxiczANICF3upelico3emmn93IwnGQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1) (出自《分布式计算-原理、算法与系统》) 1. 图 a 满足顺序一致性,因此也满足因果一致性,因为从这个系统中的四个进程的角度看,它们都有相同的顺序也有相同的因果关系。 2. 图 b 满足因果一致性但是不满足顺序一致性,这是因为从进程 P3、P4 看来,进程 P1、P2 上的操作因果有序,因为 P1、P2 上的写操作不存在因果关系,所以它们可以任意执行。不满足一致性的原因,同上面一样是可以推导出冲突的情况来。 在 infoq 分享的腾讯朋友圈的设计中,他们在设计数据一致性的时候,使用了因果一致性这个模型。用于保证对同一条朋友圈的回复的一致性,比如这样的情况: 1. A 发了朋友圈内容为梅里雪山的图片。 2. B 针对内容 a 回复了评论:“这里是哪里?” 3. C 针对 B 的评论进行了回复:”这里是梅里雪山“。 那么,这条朋友圈的显示中,显然 C 针对 B 的评论,应该在 B 的评论之后,这是一个因果关系,而其他没有因果关系的数据,可以允许不一致。 微信的做法是: 1. 每个数据中心,都自己生成唯一的、递增的数据 ID,确保能排重。在下图的示例中,有三个数据中心,数据中心 1 生成的数据 ID 模 1 为 0,数据中心 1 生成的数据 ID 模 2 为 0,数据中心 1 生成的数据 ID 模 3 为 0,这样保证了三个数据中心的数据 ID 不会重复全局唯一。 2. 每条评论都比本地看到所有全局 ID 大,这样来确保因果关系,这部分的原理前面提到的向量时钟一样。 ![](http://mmbiz.qpic.cn/mmbiz/vxCq1iahXotiaFs84SvDRF5U3gefsfA2F8cp2O082gPUZEbkiawXfogQ3DI8ghhhtFZqicbatRvrklGwxe8JlmrlOw/640?wx_fmt=png&wxfrom=5&wx_lazy=1) 有了这个模型和原理,就很好处理前面针对评论的评论的顺序问题了。 1. 假设 B 在数据中心 1 上,上面的 ID 都满足模 1 为 0,那么当 B 看到 A 的朋友圈时,发表了评论,此时给这个评论分配的 ID 是 1,因此 B 的时钟向量数据是[1]。 2. 假设 C 在数据中心 2 上,上面的 ID 都满足模 2 为 0,当 C 看到了 B 的评论时,针对这个评论做了评论,此时需要给这个评论分配的 ID 肯定要满足模 2 为 0 以及大于 1,评论完毕之后 C 上面的时钟向量是[1,2]。 3. 假设 A 在数据中心 3 上,上面的 ID 都满足模 3 为 0,当 A 看到 B、C 给自己的评论时,很容易按照 ID 进行排序和合并--即使 A 在收到 C 的数据[1,2]之后再收到 B 的数据[1],也能顺利的完成合并。 1.严格一致性(strict consistency) 对于数据项 x 的任何读操作将返回最近一次对 x 进行写操作的结果所对应的值。 严格一致性是限制性最强的模型,但是在分布式系统中实现这种模型代价太大,所以在实际系统中运用有限。 2.顺序一致性 任何执行结果都是相同的,就好像所有进程对数据存储的读、写操作是按某种序列顺序执行的,并且每个进程的操作按照程序所制定的顺序出现在这个序列中。 也就是说,任何读、写操作的交叉都是可接受的,但是所有进程都看到相同的操作交叉。顺序一致性由 Lamport(1979)在解决多处理器系统的共享存储器时首次提出的。 3.因果一致性 所有进程必须以相同的顺序看到具有潜在因果关系的写操作。不同机器上的进程可以以不同的顺序看到并发的写操作(Hutto 和 Ahamad 1990)。 假设 P1 和 P2 是有因果关系的两个进程,例如 P2 的写操作信赖于 P1 的写操作,那么 P1 和 P2 对 x 的修改顺序,在 P3 和 P4 看来一定是一样的。但如果 P1 和 P2 没有关系,那么 P1 和 P2 对 x 的修改顺序,在 P3 和 P4 看来可以是不一样的。 下表列出一些一致性模型,以限制性逐渐降低的顺序排列。 | 一致性 | 描述 | | ------ | ------------------------------------------------------------------------------------------------------ | | 严格 | 所有共享访问按绝对时间排序 | | 线性化 | 所有进程以相同的顺序看到所有的共享访问。而且,访问是根据(非唯一的)全局时间戮排序的 | | 顺序 | 所有进程以相同顺序看到所有的共享访问。访问不是按时间排序的 | | 因果 | 所有的进程以相同的顺序看到困果相关的共享访问 | | FIFO | 所有进程以不同的进程提出写操作的顺序相互看到写操作。来自不同的进程的写操作可以不必总是以同样的顺序出现 | 另一种不同的方式是引入显式的同步变量,下表是这样的一致性模型的总结。 | 一致性 | 描述 | | ------ | ------------------------------------------------ | | 弱 | 只有在执行一次同步后,共享数据才被认为是一致的 | | 释放 | 退出临界区时,使共享数据成为一致 | | 入口 | 进入临界区时,使属于一个临界区的共享数据成为一致 | 以客户为中心的一致性模型 1.最终一致性 最终一致性指的是在一段时间内没有数据更新操作的话,那么所有的副本将逐渐成为一致的。例如 OpenStack Swift 就是采用这种模型。以一次写多次读的情况下,这种模型可以工作得比较好。 2.单调读 如果一个进程读取数据项 x 的值,那么该进程对 x 执行的任何后续读操作将总是得到第一次读取的那个值或更新的值 3.单调写 一个进程对数据 x 执行的写操作必须在该进程对 x 执行任何后续写操作之前完成。 4.写后读 一个进程对数据 x 执行一次写操作的结果总是会被该进程对 x 执行的后续读操作看见。 5.读后写 同一个进程对数据项 x 执行的读操作之后的写操作,保证发生在与 x 读取值相同或比之更新的值上。 # Distributed Transcation:分布式事务 ``` 分布式事务往往和本地事务进行对比分析,以支付宝转账到余额宝为例,假设有: 支付宝账户表:A(id,userId,amount)   ``` 余额宝账户表:B(id,userId,amount) 用户的 userId=1; 从支付宝转账 1 万块钱到余额宝的动作分为两步: 1)支付宝表扣除 1 万:update A set amount=amount-10000 where userId=1; 2)余额宝表增加 1 万:update B set amount=amount+10000 where userId=1; ```sql Begin transaction update A set amount=amount-10000 where userId=1; update B set amount=amount+10000 where userId=1; End transaction commit; ``` ``` 在Spring中使用一个@Transactional事务也可以搞定上述的事务功能: ``` ```java @Transactional(rollbackFor=Exception.class) public void update() { updateATable(); //更新A表 updateBTable(); //更新B表 } ``` ``` 如果系统规模较小,数据表都在一个数据库实例上,上述本地事务方式可以很好地运行,但是如果系统规模较大,比如支付宝账户表和余额宝账户表显然不会在同一个数据库实例上,他们往往分布在不同的物理节点上,这时本地事务已经失去用武之地。 ``` ## 两阶段提交协议 ``` 两阶段提交协议(Two-phase Commit,2PC)经常被用来实现分布式事务。一般分为协调器C和若干事务执行者Si两种角色,这里的事务执行者就是具体的数据库,协调器可以和事务执行器在一台机器上。 ``` ![](http://images0.cnblogs.com/blog2015/522490/201508/091642197846523.png) 1. 我们的应用程序(client)发起一个开始请求到 TC; 2. TC 先将<prepare>消息写到本地日志,之后向所有的 Si 发起<prepare>消息。以支付宝转账到余额宝为例,TC 给 A 的 prepare 消息是通知支付宝数据库相应账目扣款 1 万,TC 给 B 的 prepare 消息是通知余额宝数据库相应账目增加 1w。为什么在执行任务前需要先写本地日志,主要是为了故障后恢复用,本地日志起到现实生活中凭证 的效果,如果没有本地日志(凭证),容易死无对证; 3) Si 收到<prepare>消息后,执行具体本机事务,但不会进行 commit,如果成功返回<yes>,不成功返回<no>。同理,返回前都应把要返回的消息写到日志里,当作凭证。 4) TC 收集所有执行器返回的消息,如果所有执行器都返回 yes,那么给所有执行器发生送 commit 消息,执行器收到 commit 后执行本地事务的 commit 操作;如果有任一个执行器返回 no,那么给所有执行器发送 abort 消息,执行器收到 abort 消息后执行事务 abort 操作。 注:TC 或 Si 把发送或接收到的消息先写到日志里,主要是为了故障后恢复用。如某一 Si 从故障中恢复后,先检查本机的日志,如果已收到<commit >,则提交,如果<abort >则回滚。如果是<yes>,则再向 TC 询问一下,确定下一步。如果什么都没有,则很可能在<prepare>阶段 Si 就崩溃了,因此需要回滚。 现如今实现基于两阶段提交的分布式事务也没那么困难了,如果使用 java,那么可以使用开源软件 atomikos([http://www.atomikos.com/](http://www.atomikos.com/))来快速实现。 不过但凡使用过的上述两阶段提交的同学都可以发现性能实在是太差,根本不适合高并发的系统。为什么? 1)两阶段提交涉及多次节点间的网络通信,通信时间太长! 2)事务时间相对于变长了,锁定的资源的时间也变长了,造成资源等待时间也增加好多! ## 消息队列方式 ``` 比如在北京很有名的姚记炒肝点了炒肝并付了钱后,他们并不会直接把你点的炒肝给你,往往是给你一张小票,然后让你拿着小票到出货区排队去取。为什么他们要将付钱和取货两个动作分开呢?原因很多,其中一个很重要的原因是为了使他们接待能力增强(并发量更高)。 ``` 还是回到我们的问题,只要这张小票在,你最终是能拿到炒肝的。同理转账服务也是如此,当支付宝账户扣除 1 万后,我们只要生成一个凭证(消息)即可,这个凭证(消息)上写着“让余额宝账户增加 1 万”,只要这个凭证(消息)能可靠保存,我们最终是可以拿着这个凭证(消息)让余额宝账户增加 1 万的,即我们能依靠这个凭证(消息)完成最终一致性。 ### 业务与消息耦合的方式 ``` 支付宝在完成扣款的同时,同时记录消息数据,这个消息数据与业务数据保存在同一数据库实例里(消息记录表表名为message); ``` ```sql Begin transaction update A set amount=amount-10000 where userId=1; insert into message(userId, amount,status) values(1, 10000, 1); End transaction commit; ``` ``` 上述事务能保证只要支付宝账户里被扣了钱,消息一定能保存下来。当上述事务提交成功后,我们通过实时消息服务将此消息通知余额宝,余额宝处理成功后发送回复成功消息,支付宝收到回复后删除该条消息数据。 ``` ### 业务与消息解耦方式 ``` 上述保存消息的方式使得消息数据和业务数据紧耦合在一起,从架构上看不够优雅,而且容易诱发其他问题。为了解耦,可以采用以下方式。 ``` 1)支付宝在扣款事务提交之前,向实时消息服务请求发送消息,实时消息服务只记录消息数据,而不真正发送,只有消息发送成功后才会提交事务; 2)当支付宝扣款事务被提交成功后,向实时消息服务确认发送。只有在得到确认发送指令后,实时消息服务才真正发送该消息; 3)当支付宝扣款事务提交失败回滚后,向实时消息服务取消发送。在得到取消发送指令后,该消息将不会被发送; 4)对于那些未确认的消息或者取消的消息,需要有一个消息状态确认系统定时去支付宝系统查询这个消息的状态并进行更新。为什么需要这一步骤,举个例子:假设在第 2 步支付宝扣款事务被成功提交后,系统挂了,此时消息状态并未被更新为“确认发送”,从而导致消息不能被发送。 优点:消息数据独立存储,降低业务系统与消息系统间的耦合; 缺点:一次消息发送需要两次请求;业务处理服务需要实现消息状态回查接口。 ### 消息重复投递 ``` 还有一个很严重的问题就是消息重复投递,以我们支付宝转账到余额宝为例,如果相同的消息被重复投递两次,那么我们余额宝账户将会增加2万而不是1万了。 为什么相同的消息会被重复投递?比如余额宝处理完消息msg后,发送了处理成功的消息给支付宝,正常情况下支付宝应该要删除消息msg,但如果支付宝这时候悲剧的挂了,重启后一看消息msg还在,就会继续发送消息msg。 解决方法很简单,在余额宝这边增加消息应用状态表(message_apply),通俗来说就是个账本,用于记录消息的消费情况,每次来一个消息,在真正执行之前,先去消息应用状态表中查询一遍,如果找到说明是重复消息,丢弃即可,如果没找到才执行,同时插入到消息应用状态表(同一事务)。 ``` \``` sql list for each msg in queue Begin transaction ``` select count(*) as cnt from message_apply where msg_id=msg.msg_id; if cnt==0 then update B set amount=amount+10000 where userId=1; insert into message_apply(msg_id) values(msg.msg_id); ``` End transaction commit; ``` # 流处理方案 当系统变得越来越复杂,数据库会被拆分为多个更小的库,如果借助这些衍生库实现像全文搜索这样的功能,那么如何保证所有的数据保持同步就是一项很有挑战性的任务了。使用多个数据库时,最大的问题在于它们并不是互相独立的。相同的数据会以不同的形式进行存储,所以当数据更新的时候,具有对应数据的所有数据库都需要进行更新。保证数据同步的最常用方案就是将其视为应用程序逻辑的责任,通常会对每个数据库进行独立的写操作。这是一个脆弱的方案,如果发生像网络故障或服务器宕机这样的失败场景,那么对一些数据库的更新可能会失败,从而导致这些数据库之间出现不一致性。Kleppmann 认为这并不是能够进行自我纠正的最终一致性,至少相同的数据再次进行写操作之前,无法实现一致性。 在 leader(主)数据库中,同时会将所有的写入操作按照处理的顺序存储为流,然后一个或多个 follower 数据库就能读取这个流并按照完全相同的顺序执行写入。这样的话,这些数据库就能更新自己的数据并成为 leader 数据库的一致性备份。对于 Kleppmann 来说,这是一个非常具有容错性的方案。每个 follower 都遵循它在流中的顺序,在出现网络故障或宕机时,follower 数据库能够从上一次的保存点开始继续进行处理。Kleppmann 还提到在实现上述场景时,使用 Kafka 作为工具之一。目前,他正在编写一个实现,Bottled Water,在这个实现中,他使用了 PostgreSQL 来抽取数据变化,然后将其中继到 Kafka 中,代码可以在[GitHub](https://github.com/confluentinc/bottledwater-pg) 上获取到。 ```
Java
UTF-8
420
1.867188
2
[]
no_license
package com.hacademy.macro; import java.awt.event.KeyEvent; import javax.swing.KeyStroke; import com.tulskiy.keymaster.common.Provider; public class Test06KeyboardHook { public static void main(String[] args) { Provider provider = Provider.getCurrentProvider(false); provider.register(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), e->{ System.out.println("close operation"); provider.close(); }); } }
SQL
UTF-8
3,854
2.953125
3
[]
no_license
CREATE DATABASE IF NOT EXISTS `fseletro` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; USE `fseletro`; CREATE TABLE `comentarios` ( `id` int(11) NOT NULL, `nome` varchar(200) DEFAULT NULL, `mensagem` varchar(255) DEFAULT NULL, `data_publicada` datetime DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO `comentarios` (`id`, `nome`, `mensagem`, `data_publicada`) VALUES (10, 'Caio Rodrigues Barbosa', 'Produto incrível', '2020-10-31 10:43:46'), (12, 'Ana', 'Meu pedido chegou certinho!', '2020-11-07 09:21:20'); CREATE TABLE `pedidos` ( `id_pedido` int(11) NOT NULL, `produto_id` int(11) DEFAULT NULL, `quantidade` int(11) DEFAULT NULL, `nome_cliente` varchar(200) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO `pedidos` (`id_pedido`, `produto_id`, `quantidade`, `nome_cliente`) VALUES (1, 10, 88, 'Caio'), (2, 3, 55, 'Erica'), (3, 5, 11, 'Guilherme'), (4, 9, 25, 'Vanessa'); CREATE TABLE `produto` ( `idproduto` int(11) NOT NULL, `categoria` varchar(45) NOT NULL, `descricao` varchar(150) NOT NULL, `preco` decimal(8,2) DEFAULT NULL, `precofinal` decimal(8,2) DEFAULT NULL, `imagem` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO `produto` (`idproduto`, `categoria`, `descricao`, `preco`, `precofinal`, `imagem`) VALUES (3, 'geladeira', 'Geladeira Frost Free Brastemp Side Inverse 540 litros', '6389.00', '5019.00', './imagens/geladeira_brastemp.jpeg'), (4, 'geladeira', 'Geladeira Frost Free Brastemp Branca 375 litros', '2068.60', '1910.90', './imagens/refrigerador_brastemp.jpeg'), (5, 'geladeira', 'Geladeira Frost Free Consul Prata 340 litros', '2199.90', '2069.00', './imagens/refrigerador_consul.jpeg'), (6, 'fogao', 'Fogão 4 Bocas Consul Inox com Mesa de Vidro', '1209.90', '1129.00', './imagens/fogao_consul.jpeg'), (7, 'fogao', 'Fogão de Piso 4 Bocas Atlas Monaco com Atendimento Automático', '609.90', '519.70', './imagens/fogao_monaco.jpeg'), (8, 'microondas', 'Micro-ondas Consul 32 Litros Inox 220V', '580.90', '409.88', './imagens/microondas_consul.jpeg'), (9, 'microondas', 'Microondas 25L Espelhado Philco 220V', '508.70', '464.53', './imagens/microondas_philco.jpeg'), (10, 'microondas', 'Forno de Microondas Electrolux 20L Branco', '459.90', '436.05', './imagens/microondas_eletrolux.jpeg'), (11, 'lavalouca', 'Lava-Louça Electrolux Inox com 10 Serviços, 06 Programas de Lavagens.', '3599.00', '2799.90', './imagens/lava_loucas_eletrolux.jpeg'), (12, 'lavalouca', 'Lava Louça Compacta 8 Serviços Branca 127V Brastemp', '1970.50', '1730.61', './imagens/lava_loucas.jpeg'), (13, 'lavadora', 'Lavadora de Roupas Brastemp 11 kg com Turbo Perfomance Branca', '1699.00', '1214.00', './imagens/lavadora_brastemp.jpeg'), (14, 'lavadora', 'Lavadora de Roupas Philco Inverter 12KG', '2399.90', '2179.90', './imagens/lavadora_philco.jpeg'); --- JOIN ENTRE A TABELA PEDIDOS E PRODUTOS SELECT * FROM pedidos JOIN produto ON pedidos.produto_id = produto.idproduto; --- BUSCANDO CAMPOS ESPECÍFICOS COM JOIN SELECT id_pedido, nome_cliente, quantidade, descricao from pedidos JOIN produto on pedidos.produto_id; ------------------------------ ALTER TABLE `comentarios` ADD PRIMARY KEY (`id`); ALTER TABLE `pedidos` ADD PRIMARY KEY (`id_pedido`), ADD KEY `FK_pedido` (`produto_id`); ALTER TABLE `produto` ADD PRIMARY KEY (`idproduto`), ADD UNIQUE KEY `imagem` (`imagem`); ALTER TABLE `comentarios` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; ALTER TABLE `pedidos` MODIFY `id_pedido` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; ALTER TABLE `produto` MODIFY `idproduto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; ALTER TABLE `pedidos` ADD CONSTRAINT `FK_pedido` FOREIGN KEY (`produto_id`) REFERENCES `produto` (`idproduto`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT;
C#
UTF-8
1,179
3.46875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; namespace Maximus.Library.Helpers { /// <summary> /// Compare machine names taking domain suffix in account. If both names are FQDN or NetBIOS names, then literal comparison /// applied, otherwise either name reduced to NetBIOS format. /// </summary> public class MachineNameComparer : IComparer<string> { public int Compare(string x, string y) { bool isXfull = (x.IndexOf(".") > 0); // cannot be 0, as ".dnssuffix.name" is invalid. bool isYfull = (y.IndexOf(".") > 0); if (isXfull && isYfull) return StringComparer.OrdinalIgnoreCase.Compare(x, y); if (!isXfull && !isYfull) return StringComparer.OrdinalIgnoreCase.Compare(x, y); if (isXfull) return StringComparer.OrdinalIgnoreCase.Compare(x.Substring(0, x.IndexOf(".")), y); if (isYfull) return StringComparer.OrdinalIgnoreCase.Compare(x, y.Substring(0, y.IndexOf("."))); throw new Exception("It's impossible to get here. Suppressing compiler error."); } public static MachineNameComparer OrdinalIgnoreCase { get { return new MachineNameComparer(); } } } }
Java
UTF-8
972
1.875
2
[]
no_license
package mum.edu.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Propagation; import mum.edu.dao.RegistrationDao; import mum.edu.domain.Block; import mum.edu.domain.Course; import mum.edu.domain.Registration; import mum.edu.domain.User; @Transactional(propagation = Propagation.REQUIRES_NEW) public class RegistrationService { @Autowired private RegistrationDao registrationDao; @Autowired // private PendingCourseSwitch pendingCourse; // @Autowired // private BlockDAO blockDao; // @Autowired // private CourseDAO courseDao; // @Autowired // private UserDAO userDao; public void register(User user, Block block, Course course, List<Course> preferedCourses) { registrationDao.save(new Registration(user,course,block )); } }
TypeScript
UTF-8
27,573
2.53125
3
[]
no_license
import { ZODIACTIME } from '../departure/departure-zodiactimestorage'; import { Hour } from './departure-hour'; import { HUONGXUATHANH } from './interface/huong_xuat_hanh'; import { TNBINFO } from './interface/tnb_Info'; import { DanhNgon } from './interface/danhngon'; export class DepartureUtils { static GMT: number = 7; static JANUARY: number = 1; static FEBRUARY: number = 2; static MARCH: number = 3; static APRIL: number = 4; static MAY: number = 5; static JUNE: number = 6; static JULY: number = 7; static AUGUST: number = 8; static SEPTEMBER: number = 9; static OCTORBER: number = 10; static NOVEMBER: number = 11; static DECEMBER: number = 12; static CANS: Array<string> = ["Giáp", "Ất", "Bính", "Đinh", "Mậu", "Kỷ", "Canh", "Tân", "Nhâm", "Quý"]; static CHIS: Array<string> = ["Tý", "Sửu", "Dần", "Mão", "Thìn", "Tỵ", "Ngọ", "Mùi", "Thân", "Dậu", "Tuất", "Hợi"]; static day_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; static day_in_months_nhuan = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; /**Trả về số ngày trong 1 tháng của 1 năm. * @argument mm : Kiểu số, tháng cần tính, bắt đầu từ 0 (cho tháng 1). * @argument yy : Kiểu số, năm cần tính. * * @author dinhanh */ public static getDaysInMonth(mm: number, yy: number): number { if (mm < 0) mm = 0; if (mm >= this.day_in_months.length) mm = this.day_in_months.length - 1; if (yy % 4 == 0) { return this.day_in_months_nhuan[mm]; } return this.day_in_months[mm]; } public static getDaysPassInYear(mm: number, yy: number){ var sum = 0; if(mm==1){ return 0; } if( yy%4 == 0){ for(let i = 0 ; i < mm -1; i++){ sum+= this.day_in_months_nhuan[i]; } }else{ for(let i = 0 ; i < mm -1; i++){ sum+= this.day_in_months[i]; } } return sum; } public static convertDDMMYYToJulius(solarDay: number, solarMonth: number, solarYear: number) { // Tính số ngày Julius var monthDistance, yearJulius, monthJulius; var juliusDate = 0; monthDistance = Math.floor((14 - solarMonth) / 12); yearJulius = solarYear + 4800 - monthDistance; monthJulius = solarMonth + 12 * monthDistance - 3; let dayDistance = solarDay + Math.floor((153 * monthJulius + 2) / 5) + 365 * yearJulius + Math.floor(yearJulius / 4); juliusDate = dayDistance - Math.floor(yearJulius / 100) + Math.floor(yearJulius / 400) - 32045; if (juliusDate < 2299161) { juliusDate = dayDistance - 32083; } return juliusDate; } public static convertJuliusToDDMMYY(juliusDate: number){ var aNumber, bNumber, cNumber, dNumber, eNumber, mNumber; var day, month, year; if (juliusDate > 2299161) { // Gregorian calendar aNumber = juliusDate + 32044; bNumber = Math.floor((4 * aNumber + 3) / 146097); cNumber = aNumber - Math.floor((bNumber * 146097) / 4); } else { // Julius calendar bNumber = 0; cNumber = juliusDate + 32082; } dNumber = Math.floor((4 * cNumber + 3) / 1461); eNumber = cNumber - Math.floor((1461 * dNumber) / 4); mNumber = Math.floor((5 * eNumber + 2) / 153); day = eNumber - Math.floor((153 * mNumber + 2) / 5) + 1; month = mNumber + 3 - 12 * Math.floor(mNumber / 10); year = bNumber * 100 + dNumber - 4800 + Math.floor(mNumber / 10); return new Array(day,month,year); } public static getNewMoonDay(k: number, timeZone?: number): number { // Tính ngày đầu tháng âm lịch chứa ngày N let T, T2, T3, dr, Jd1, M, Mpr, F, C1, deltat, JdNew; var GMT: number; GMT = this.GMT; if (timeZone) { GMT = timeZone; } T = k / 1236.85; // Time in Julian centuries from 1900 January 0.5 T2 = T * T; T3 = T2 * T; dr = Math.PI / 180; Jd1 = 2415020.75933 + 29.53058868 * k + 0.0001178 * T2 - 0.000000155 * T3; Jd1 = Jd1 + 0.00033 * Math.sin((166.56 + 132.87 * T - 0.009173 * T2) * dr); // Mean new moon M = 359.2242 + 29.10535608 * k - 0.0000333 * T2 - 0.00000347 * T3; // Sun's mean anomaly Mpr = 306.0253 + 385.81691806 * k + 0.0107306 * T2 + 0.00001236 * T3; // Moon's mean anomaly F = 21.2964 + 390.67050646 * k - 0.0016528 * T2 - 0.00000239 * T3; // Moon's argument of latitude C1 = (0.1734 - 0.000393 * T) * Math.sin(M * dr) + 0.0021 * Math.sin(2 * dr * M); C1 = C1 - 0.4068 * Math.sin(Mpr * dr) + 0.0161 * Math.sin(dr * 2 * Mpr); C1 = C1 - 0.0004 * Math.sin(dr * 3 * Mpr); C1 = C1 + 0.0104 * Math.sin(dr * 2 * F) - 0.0051 * Math.sin(dr * (M + Mpr)); C1 = C1 - 0.0074 * Math.sin(dr * (M - Mpr)) + 0.0004 * Math.sin(dr * (2 * F + M)); C1 = C1 - 0.0004 * Math.sin(dr * (2 * F - M)) - 0.0006 * Math.sin(dr * (2 * F + Mpr)); C1 = C1 + 0.0010 * Math.sin(dr * (2 * F - Mpr)) + 0.0005 * Math.sin(dr * (2 * Mpr + M)); if (T < -11) { deltat = 0.001 + 0.000839 * T + 0.0002261 * T2 - 0.00000845 * T3 - 0.000000081 * T * T3; } else { deltat = -0.000278 + 0.000265 * T + 0.000262 * T2; }; JdNew = Jd1 + C1 - deltat; return Math.floor((JdNew + 0.5 + GMT / 24)); } public static getSunLongitude(jdn: number, timeZone?: number): number { // Tính tọa độ mặt trời var GMT: number = this.GMT; if (timeZone) { GMT = timeZone; } let T, T2, dr, M, L0, DL, L; T = (jdn - 2451545.5 - GMT / 24) / 36525; // Time in Julian centuries from 2000-01-01 12:00:00 GMT T2 = T * T; dr = Math.PI / 180; // degree to radian M = 357.52910 + 35999.05030 * T - 0.0001559 * T2 - 0.00000048 * T * T2; // mean anomaly, degree L0 = 280.46645 + 36000.76983 * T + 0.0003032 * T2; // mean longitude, degree DL = (1.914600 - 0.004817 * T - 0.000014 * T2) * Math.sin(dr * M); DL = DL + (0.019993 - 0.000101 * T) * Math.sin(dr * 2 * M) + 0.000290 * Math.sin(dr * 3 * M); L = L0 + DL; // true longitude, degree L = L * dr; L = L - Math.PI * 2 * (Math.floor(L / (Math.PI * 2))); // Normalize to (0, 2*PI) return Math.floor((L / Math.PI * 6)); } public static getLunarMonth11(yy: number, timeZone?: number): number { // Tính ngày bắt đầu tháng 11 âm lịch var GMT: number = this.GMT; if (timeZone) { GMT = timeZone; } var k, off, sunLong; var nm: number = 0; off = this.convertDDMMYYToJulius(31, 12, yy) - 2415021; k = Math.floor(off / 29.530588853); nm = this.getNewMoonDay(k, GMT); sunLong = this.getSunLongitude(nm, GMT); // sun longitude at local midnight if (sunLong >= 9) { nm = this.getNewMoonDay(k - 1, GMT); } return nm; } public static getLeapMonthOffset(a11: number, timeZone?: number): number { // Xác định tháng nhuận var GMT: number = this.GMT; if (timeZone) { GMT = timeZone; } var k, last, arc, i; k = Math.floor((a11 - 2415021.076998695) / 29.530588853 + 0.5); last = 0; i = 1; // We start with the month following lunar month 11 arc = this.getSunLongitude(this.getNewMoonDay(k + i, GMT), GMT); do { last = arc; i++; arc = this.getSunLongitude(this.getNewMoonDay(k + i, GMT), GMT); } while (arc != last && i < 14); return i - 1; } public static convertSolarToLunar(dd: number, mm: number, yy: number, timeZone?: number) { // Chuyển ngày dương sang âm lịch var GMT: number = this.GMT; if (timeZone) { GMT = timeZone; } let k, dayNumber, monthStart, a11, b11, lunarDay, lunarMonth, lunarYear, lunarLeap; dayNumber = this.convertDDMMYYToJulius(dd, mm, yy); k = Math.floor(((dayNumber - 2415021.076998695) / 29.530588853)); monthStart = this.getNewMoonDay(k + 1, GMT); if (monthStart > dayNumber) { monthStart = this.getNewMoonDay(k, GMT); } a11 = this.getLunarMonth11(yy, GMT); b11 = a11; if (a11 >= monthStart) { lunarYear = yy; a11 = this.getLunarMonth11(yy - 1, GMT); } else { lunarYear = yy + 1; b11 = this.getLunarMonth11(yy + 1, GMT); } lunarDay = dayNumber - monthStart + 1; let diff = Math.floor(((monthStart - a11) / 29)); lunarLeap = 0; lunarMonth = diff + 11; if (b11 - a11 > 365) { let leapMonthDiff = this.getLeapMonthOffset(a11, GMT); if (diff >= leapMonthDiff) { lunarMonth = diff + 10; if (diff == leapMonthDiff) { lunarLeap = 1; } } } if (lunarMonth > 12) { lunarMonth = lunarMonth - 12; } if (lunarMonth >= 11 && diff < 4) { lunarYear -= 1; } return new Array(lunarDay,lunarMonth,lunarYear); } public static convertLunarToSolar(lunarDay: any, lunarMonth: any, lunarYear: any, timeZone?: number) { // Chuyển ngày âm sang dương lịch var GMT: number = this.GMT; if (timeZone) { GMT = timeZone; } let k, a11, b11, off, leapOff, leapMonth, monthStart; if (lunarMonth < 11) { a11 = this.getLunarMonth11(lunarYear - 1, GMT); b11 = this.getLunarMonth11(lunarYear, GMT); } else { a11 = this.getLunarMonth11(lunarYear, GMT); b11 = this.getLunarMonth11(lunarYear + 1, GMT); } off = lunarMonth - 11; if (off < 0) { off += 12; } if (b11 - a11 > 365) { leapOff = this.getLeapMonthOffset(a11, GMT); leapMonth = leapOff - 2; if (leapMonth < 0) { leapMonth += 12; } if (off >= leapOff) { off += 1; } } k = Math.floor((0.5 + (a11 - 2415021.076998695) / 29.530588853)); monthStart = this.getNewMoonDay(k + off, GMT); return this.convertJuliusToDDMMYY(monthStart + lunarDay - 1); } //Tính Can Chi Theo Năm (đầu vào theo dương lịch) public static getSexagesimalCycleByYear(date: number, month: number, year: number) { let x: number[] = this.convertSolarToLunar(date, month, year); let canIndex: number = Math.floor(((x[2] + 6) % 10)); let chiIndex: number = Math.floor(((x[2] + 8) % 12)); return this.CANS[canIndex] +" "+ this.CHIS[chiIndex]; } //tính can chi theo tháng (đầu vào theo dương lịch) public static getSexagesimalCycleByMonth(dd: any, mm: any, yy: any): string{ let result: string; let chi: string; let y: number[] = this.convertSolarToLunar(dd, mm, yy); let month: number = y[1]; if (month == 1) { chi = "Dần" } if (month == 2) { chi = "Mão" } if (month == 3) { chi = "Thìn" } if (month == 4) { chi = "Tỵ" } if (month == 5) { chi = "Ngọ" } if (month == 6) { chi = "Mùi" } if (month == 7) { chi = "Thân" } if (month == 8) { chi = "Dậu" } if (month == 9) { chi = "Tuất" } if (month == 10) { chi = "Hợi" } if (month == 11) { chi = "Tý" } if (month == 12) { chi = "Sửu" } let z: number[] = this.convertSolarToLunar(dd, mm, yy); let x: number = (z[2] * 12 + z[1] + 3) % 10; let can: string; if (x == 0) { can = "Giáp" } if (x == 1) { can = "Ất" } if (x == 2) { can = "Bính" } if (x == 3) { can = "Đinh" } if (x == 4) { can = "Mậu" } if (x == 5) { can = "Kỷ" } if (x == 6) { can = "Canh" } if (x == 7) { can = "Tân" } if (x == 8) { can = "Nhâm" } if (x == 9) { can = "Quý" } result = can+" "+chi; return result; } //Tính Can Chi theo Ngày (đầu vào theo dương lịch) public static getSexagesimalCycleByDay(date: number, month: number, year: number): string{ let can: string; let chi: string; let result: string; let N: number = Math.floor(this.convertDDMMYYToJulius(date, month, year)); if (Math.floor(((N + 9) % 10)) == 0) { can = "Giáp" } if (Math.floor(((N + 9) % 10)) == 1) { can = "Ất" } if (Math.floor(((N + 9) % 10)) == 2) { can = "Bính" } if (Math.floor(((N + 9) % 10)) == 3) { can = "Đinh" } if (Math.floor(((N + 9) % 10)) == 4) { can = "Mậu" } if (Math.floor(((N + 9) % 10)) == 5) { can = "Kỷ" } if (Math.floor(((N + 9) % 10)) == 6) { can = "Canh" } if (Math.floor(((N + 9) % 10)) == 7) { can = "Tân" } if (Math.floor(((N + 9) % 10)) == 8) { can = "Nhâm" } if (Math.floor(((N + 9) % 10)) == 9) { can = "Quý" } if (Math.floor(((N + 1) % 12)) == 0) { chi = "Tý" } if (Math.floor(((N + 1) % 12)) == 1) { chi = "Sửu" } if (Math.floor(((N + 1) % 12)) == 2) { chi = "Dần" } if (Math.floor(((N + 1) % 12)) == 3) { chi = "Mão" } if (Math.floor(((N + 1) % 12)) == 4) { chi = "Thìn" } if (Math.floor(((N + 1) % 12)) == 5) { chi = "Tỵ" } if (Math.floor(((N + 1) % 12)) == 6) { chi = "Ngọ" } if (Math.floor(((N + 1) % 12)) == 7) { chi = "Mùi" } if (Math.floor(((N + 1) % 12)) == 8) { chi = "Thân" } if (Math.floor(((N + 1) % 12)) == 9) { chi = "Dậu" } if (Math.floor(((N + 1) % 12)) == 10) { chi = "Tuất" } if (Math.floor(((N + 1) % 12)) == 11) { chi = "Hợi" } result = can+" "+ chi; return result; } //Tính ngày hoàng đạo, hắc đạo public static getZodiacDay(date: number, month: number, year: number): number { let lunarmonth: number = this.convertSolarToLunar(date, month, year)[1]; let temp: string= this.getSexagesimalCycleByDay(date, month, year); let can = temp.split(" ")[0]; let chi = temp.split(" ")[1]; if (lunarmonth == 1 || lunarmonth == 7) { if (chi == "Tý" || chi == "Sửu" || chi == "Tỵ" || chi == "Mùi") { return 1; } else if (chi == "Ngọ" || chi == "Mão" || chi == "Hợi" || chi == "Dậu") { return 2; } else { return 0; } } if (lunarmonth == 2 || lunarmonth == 8) { if (chi == "Dần" || chi == "Mão" || chi == "Mùi" || chi == "Dậu") { return 1; } else if (chi == "Thân" || chi == "Tỵ" || chi == "Hợi" || chi == "Sửu") { return 2; } else { return 0; } } if (lunarmonth == 3 || lunarmonth == 9) { if (chi == "Thìn" || chi == "Tỵ" || chi == "Dậu" || chi == "Hợi") { return 1; } else if (chi == "Tuất" || chi == "Mùi" || chi == "Mão" || chi == "Sửu") { return 2; } else { return 0; } } if (lunarmonth == 4 || lunarmonth == 10) { if (chi == "Ngọ" || chi == "Sửu" || chi == "Hợi" || chi == "Mùi") { return 1; } else if (chi == "Tý" || chi == "Dậu" || chi == "Tỵ" || chi == "Mão") { return 2; } else { return 0; } } if (lunarmonth == 5 || lunarmonth == 11) { if (chi == "Thân" || chi == "Sửu" || chi == "Dậu" || chi == "Mão") { return 1; } else if (chi == "Dần" || chi == "Mùi" || chi == "Hợi" || chi == "Tỵ") { return 2; } else { return 0; } } if (lunarmonth == 6 || lunarmonth == 12) { if (chi == "Tuất" || chi == "Hợi" || chi == "Tỵ" || chi == "Mão") { return 1; } else if (chi == "Thìn" || chi == "Sửu" || chi == "Mùi" || chi == "Dậu") { return 2; } else { return 0; } } } //tính can của ngày public static getCanDay(date: number, month: number, year: number): string { let result: string; let N: number = Math.floor(this.convertDDMMYYToJulius(date, month, year)); let tempCalculation: number = Math.floor(((N + 9) % 10)); switch (tempCalculation) { case 0: result = "Giáp"; break; case 1: result = "Ất"; break; case 2: result = "Bính"; break; case 3: result = "Đinh"; break; case 4: result = "Mậu"; break; case 5: result = "Kỷ"; break; case 6: result = "Canh"; break; case 7: result = "Nhâm"; break; case 8: result = "Tân"; break; case 9: result = "Quý"; break; default: break; } return result; } //quy đổi giờ sang 12 canh public static exchangetoZodiacTime(hour: number): string { let result: string; if (hour >= 1 && hour < 3) { result = "Sửu" } else if (hour >= 3 && hour < 5) { result = "Dần" } else if (hour >= 5 && hour < 7) { result = "Mão" } else if (hour >= 7 && hour < 9) { result = "Thìn" } else if (hour >= 9 && hour < 11) { result = "Tỵ" } else if (hour >= 11 && hour < 13) { result = "Ngọ" } else if (hour >= 13 && hour < 15) { result = "Mùi" } else if (hour >= 15 && hour < 17) { result = "Thân" } else if (hour >= 17 && hour < 19) { result = "Dậu" } else if (hour >= 19 && hour < 21) { result = "Tuất" } else if (hour >= 21 && hour < 23) { result = "Hợi" } else if (hour >= 23 && hour <= 24) { result = "Tý" } else if (hour >= 0 && hour < 1) { result = "Tý" } return result; } //lấy dữ liệu từ bảng dữ liệu can của giờ public static getDataFromZodiacTime(can: String, canh: String): string { let result: string; for (let x of ZODIACTIME) { for (let y of x.can) { if (can == y) { if (canh == "Tý") { result = x.ti; } else if (canh == "Sửu") { result = x.suu; } else if (canh == "Dần") { result = x.dan; } else if (canh == "Mão") { result = x.mao; } else if (canh == "Thìn") { result = x.thin; } else if (canh == "Tỵ") { result = x.ty; } else if (canh == "Ngọ") { result = x.ngo; } else if (canh == "Mùi") { result = x.mui; } else if (canh == "Thân") { result = x.than; } else if (canh == "Dậu") { result = x.dau; } else if (canh == "Tuất") { result = x.tuat; } else if (canh == "Hợi") { result = x.hoi; } } } } return result; } //tính can chi cho giờ public static getSexagesimalCycleByTime(dd: any, mm: any, yy: any, hour: number): string { let result: string; let can: string = this.getCanDay(dd, mm, yy); let canh: string = this.exchangetoZodiacTime(hour); result = this.getDataFromZodiacTime(can, canh); return result; } //Tính năm nhuận. Trả về số ngày nhuận public static isLeap(year) { if ((year % 4) || ((year % 100 === 0) && (year % 400))) return 0; else return 1; } //Tính số ngày của một tháng public static daysInMonth(month, year) { return (month === 2) ? (28 + this.isLeap(year)) : 31 - (month - 1) % 7 % 2; } public static getTrucDay(lunarMonth: number, chi: string, data: any) { for (let i = (lunarMonth - 1) * 12; i < (lunarMonth - 1) * 12 + 12; i++) { if (chi == data[i].ngay_chi) { return data[i].name; } } } public static getTietDay(date: number, solarMonth: number, data: any) { let dateNumber = []; for (let j = ((solarMonth - 1) * 2); j < ((solarMonth - 1) * 2) + 2; j++) { dateNumber.push(parseInt(data[j].date)); } if (date < dateNumber[0] && solarMonth == 1) { return data[data.length - 1].name; } if (date < dateNumber[0]) { return data[(solarMonth - 1) * 2 - 1].name; } else if (date >= dateNumber[0] && date < dateNumber[1]) { return data[(solarMonth - 1) * 2].name; } else if (date >= dateNumber[1]) { return data[(solarMonth - 1) * 2 + 1].name; } } public static getHourDay() { return Hour; } public static getHoursBetterAndBad(chi: string) { let result = [[], []]; let hourdata = this.getHourDay(); let check: boolean = false; for (let k = 0; k < hourdata.length; k++) { let chi_array = hourdata[k].chi.split(","); chi_array.forEach(element => { if (chi.toLowerCase() == element.toLowerCase()) { result[0].push(hourdata[k].gio_tot); result[1].push(hourdata[k].gio_xau); check = true; } }); if (check) { break; } } return result; } public static getTaiThanHyThan(canchi: string, data: any) { let can = canchi.split(" ")[0]; let chi = canchi.split(" ")[1]; let taiThan_hyThan_data = data.taithan_hythan; let hac_than_data = data.hac_than; let result = []; for (let i = 0; i < taiThan_hyThan_data.length; i++) { if (can == taiThan_hyThan_data[i].can) { let huong_xuat_hanh: HUONGXUATHANH = { huong_id: taiThan_hyThan_data[i].huong_id, huong_name: taiThan_hyThan_data[i].taithan_hythan } result.push(huong_xuat_hanh); } } for (let j = 0; j < hac_than_data.length; j++) { if (can == hac_than_data[j].can && chi == hac_than_data[j].chi) { let huong_xuat_hanh: HUONGXUATHANH = { huong_id: hac_than_data[j].huong_id, huong_name: "Hắc Thần" } result.push(huong_xuat_hanh); break; } } return result; } public static getTuoiXungKhac(canchi: string, data: any) { let tuoi_xung_khac_data = data.tuoi_xung_khac; for (let t = 0; t < tuoi_xung_khac_data.length; t++) { if (canchi.toLowerCase() == tuoi_xung_khac_data[t].canchi.toLowerCase()) { return tuoi_xung_khac_data[t].tuoi_xung_khac; } } } public static getSaoTot(chi: string, lunarMonth: number, data: any) { let result = []; let data_sao_tot = data.sao_tot; for (let i = 0; i < data_sao_tot.length; i++) { if (chi.toLowerCase() == data_sao_tot[i].chi.split(", ")[lunarMonth - 1].toLowerCase()) { result.push(data_sao_tot[i].name); } } return result; } public static getSaoXau(can: string, chi: string, lunarMonth: number, data: any) { let result = []; let data_sao_xau = data.sao_xau; for (let i = 0; i < data_sao_xau.length; i++) { if (i < data_sao_xau.length - 2 && chi.toLowerCase() == data_sao_xau[i].chi.split(", ")[lunarMonth - 1].toLowerCase()) { result.push(data_sao_xau[i].name); } if (i >= data_sao_xau.length - 2 && can.toLowerCase() == data_sao_xau[i].chi.split(", ")[lunarMonth - 1].toLowerCase()) { result.push(data_sao_xau[i].name); } } return result; } public static GetTNBINFO(dd: number, mm: number, yy: number, data) { let detailData = data.DayDetail; var idNUmber = this.getIDStar(dd, mm, yy); let tnb_info: TNBINFO = { thapnhibat_ten: data[idNUmber - 1].thapnhibat_ten, nguhanh_id: data[idNUmber - 1].nguhanh_id, thapnhibat_tho: data[idNUmber - 1].thapnhibat_tho, nen_lam: data[idNUmber - 1].nen_lam, kieng_ky: data[idNUmber - 1].kieng_ky } return tnb_info; } public static getIDStar(dd: number, mm: number, yy: number) { // moc la ngay 1-1-1900 id sao la 5 ; var number1 = (yy - 1900) + Math.floor((yy - 1900) / 4); let number2 = dd; for (let i = 0; i < mm - 1; i++) { number2 += this.day_in_months[i]; } let number = 0; if (mm < 2 && yy % 4 == 0) { number = number1 + number2 - 1; } if (yy % 4 != 0) { number = number1 + number2; } let number_day_more = 0; number_day_more = (number % 28); if (number_day_more <= 23) { return number_day_more + 4; } else { return (5 + number_day_more) % 28; } } }
C++
UTF-8
1,734
2.609375
3
[]
no_license
#include<iostream> #include<fstream> #include<string> #include<cstring> #include<cmath> #include<vector> #include<algorithm> #include<queue> #include<deque> #include<limits> #include<bitset> #include<map> using namespace std; #pragma warning (disable:4996) ifstream in("input.txt"); const int INF = 987654321; struct bst{ int leftindex = 0; int rightindex = 0; int key = -1; }; vector<bool> visit; vector<bst> nodes; int binary(int rootind){ if (rootind == 0) return 1; if (visit[rootind]) return INF; int ret = 1; visit[rootind] = true; int rootkey = nodes[rootind].key; int leftkey = nodes[nodes[rootind].leftindex].key; int rightkey = nodes[nodes[rootind].rightindex] .key; if (leftkey < rootkey) ret+=binary(nodes[rootind].leftindex); if (rightkey == -1 || rightkey > rootkey) ret += binary(nodes[rootind].rightindex); return ret; } int main(){ #ifdef _HONG freopen("input.txt", "r", stdin); // freopen("output.txt","w+", stdout); #endif int tc; cin >> tc; while (tc--){ nodes.clear(); vector<bool> keys(1001, false); bool overlap = false; int n; cin >> n; bst node; nodes.push_back(node); int a, b, c; for (int i = 0; i < n; i++){ cin >> a >> b >> c; node.leftindex = a; node.rightindex = b; node.key = c; if (!keys[c]) keys[c] = true; else overlap = true; nodes.push_back(node); } int allnode = n * 2 + 1; bool flg = false; //int ch; for (int i = 1; i <= n; i++){ visit = vector<bool>(n + 1, false); if (allnode == binary(i)){ //ch = i; flg = true; break; } } if (!overlap && flg){ //cout << ch << endl; cout << "YES" << endl; } else cout << "NO" << endl; } return 0; }
C#
UTF-8
263
2.71875
3
[]
no_license
using System; namespace Calc.SingleCalculators { public class Tan : ISingleOperation { public double Calculation(double firstArgument) { double result = Math.Tan(firstArgument); return result; } } }
Shell
UTF-8
783
3.609375
4
[]
no_license
#!/usr/bin/env bash REG="reg.qiniu.com/ava-os" TAG="latest" PUSH=false CONTROLLER=false WORKER=false if [[ $# -lt 1 ]]; then echo "usage: $0 <controller|worker|all> [--push]" fi case $1 in controller) CONTROLLER=true ;; worker) WORKER=true ;; all) CONTROLLER=true WORKER=true ;; esac if [ $# -gt 1 ]; then if [ $2=="--push" ]; then PUSH=true fi fi if $CONTROLLER; then echo "building container snapshot-operator..." docker build -t $REG/snapshot-operator:$TAG -f tmp/build/operator.Dockerfile . if $PUSH; then docker push $REG/snapshot-operator:$TAG fi fi if $WORKER; then echo "building container snapshot-worker..." docker build -t $REG/snapshot-worker:$TAG -f tmp/build/worker.Dockerfile . if $PUSH; then docker push $REG/snapshot-worker:$TAG fi fi
PHP
UTF-8
607
2.65625
3
[]
no_license
<?php session_start(); function alertSet($msg, $flag = 0){ $types = array('success', 'info', 'warning', 'danger'); $_SESSION['alert'] = array('flag' => $types[$flag], 'msg' => $msg); } function alertGet(){ $alert = $_SESSION['alert']; unset($_SESSION['alert']); return $alert; } function go($url, $msg = NULL, $msgFlag = 0){ if ($url == -1) { $url = $_SERVER['HTTP_REFERER']; } if(empty($msg) == false){ if (is_array($msg)) { $msgFlag = $msgFlag OR (count($msg) > 1 ? $msg[1] : 0); $msg = $msg[0]; } alertSet($msg, $msgFlag); } header("Location: $url"); }
C#
UTF-8
690
2.84375
3
[]
no_license
using MvpTest.Models; using MvpTest.Views; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MvpTest.Presenters { public class RectanglePresenter { private readonly IRectangle view; public RectanglePresenter(IRectangle view) { this.view = view; } public void ClaculateArea() { Rectangle rectangle = new Rectangle(); rectangle.Breadth = double.Parse(view.BreadthText); rectangle.Lenght = double.Parse(view.LengthText); view.AreaText = rectangle.CalculateArea().ToString(); } } }
Python
UTF-8
693
2.734375
3
[]
no_license
from collections import deque N,M = raw_input().split() n = int(N) m = int(M) cut = 0 A = [[0, 0] for i in xrange(m)] count = [1 for i in xrange(n + 2)] count[0] = 0 for i in xrange(m): x, y = raw_input().split() A[i][0] = int(x) A[i][1] = int(y) for i in xrange(m): count[A[i][1]] = 0 q = deque() for i in xrange(n + 1, 0, -1): if count[i] == 0: q.append(i) total = 0 while len(q) > 0: elem = q.popleft() f = 0 if count[elem] != 0: total += count[elem] f = 1 else: total += 1 if f == 0: for j in xrange(m): if A[j][1] == elem: q.append(A[j][0]) count[i]= total; for i in xrange(2, n): if count[i] % 2 == 0: cut += 1 print cut
C++
UTF-8
1,663
2.609375
3
[]
no_license
#ifndef VACCINES_MODEL_H #define VACCINES_MODEL_H #include "vaccine.h" #include <QAbstractTableModel> #include <QFile> #include <QDomDocument> #include <QTextStream> class VaccinesModel: public QAbstractTableModel { Q_OBJECT QFile *file_vaccines_repository; QList<Vaccine> *vaccines_repository; public: explicit VaccinesModel(QObject *parent = nullptr); VaccinesModel(VaccinesModel const &) = delete; VaccinesModel(VaccinesModel &&) = delete; VaccinesModel & operator=(VaccinesModel const &) = delete; virtual ~VaccinesModel(); //return count of vaccines int rowCount(QModelIndex const &parent = QModelIndex()) const; //return count of columns for table (matches vaccine fields) int columnCount(QModelIndex const &parent = QModelIndex()) const; //headers for table QVariant headerData(int, Qt::Orientation, int) const; //return data for each field of vaccine QVariant data(QModelIndex const &, int role = Qt::DisplayRole) const; //set data for each field of vaccine bool setData(QModelIndex const &, QVariant const &, int role = Qt::EditRole); //remove vaccine from vaccines repository bool removeRows(int, int, QModelIndex const &); //return itemflags for table view Qt::ItemFlags flags(QModelIndex const &) const; //insert vaccine in vaccines repository void insertData(Vaccine &); private: //parse xml domdocmodel and fill field each vaccine void fillVaccinesRepository(QDomDocument const &); private slots: //load data from file void loadData(); //save data to file void saveVaccines() const; }; #endif // VACCINES_MODEL_H
TypeScript
UTF-8
1,698
2.515625
3
[]
no_license
export interface User { user_id?: number, username?: string, password?: string, email?: string } export interface Animal { animal_id?: number, birthday?: string, age?: string, spezies?: string, name?: string, image?: string, weight?: string, target_weight?: string, aktivity?: 'low' | 'normal' | 'high', user_id?: number, setting_id?: number } export interface Component { component_id?: number, categorie?: string, animal_sort?: string, name?: string, info?: string, user_id?: number, wiki_id?: number } export interface FeedList { feed_part_id?: number, feed_part?: string, schedult_id?: number, amount?: number } export interface Nutrition { nutrition_id?: number, nutrition?: string, component_id?: number, value?: number } export type OuchieType = 'poo' |'rash'| 'heartburn'| 'itch'| 'puke'| 'others' export interface Ouchie { ouchie_id?: number, types?: OuchieType[] day_date?: string, animal_id?: number, } export interface PlanSetting { setting_id?: number, animal_amount?: number, fet_per_day?: number, protein_per_day?: number, plant_amount?: number, factor?: number, fullfil_demant?: 1 | 2 | 3 | 4, intervall?: 1 | 2 | 3 | 4, own_component?: boolean, plan_view?: 'basic' | 'detail', } export type Weekday = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun' export interface ScheduleDay { schedult_id?: number, weekday?: Weekday, week?: number, ouchie_id?: number, setting_id?: number } export interface WikiEntry { wiki_id?: number, title?: string, content?: any }
C++
UTF-8
709
3.484375
3
[]
no_license
#include <iostream> using namespace std; void afficher(int T[], int N) { int i; for (i = 0;i < N; i++) cout << T[i] << ' '; cout << endl; } void inserer(int T[], int n) { int i, v; cout << endl; afficher(T,n + 1); i = n - 1; v = T[n]; while (i >= 0 && T[i] > v) { T[i + 1] = T[i]; i--; } T[i + 1] = v; afficher(T,n + 1); cout << endl; } void trier(int T[], int n) { if (n == 0) return; trier(T, n - 1); inserer(T, n); } int main() { const int N = 10; int i; int Tab[N]; while (true) { cout << "Entrer " << N << " valeurs :" << endl; for (i = 0;i < N; i++) cin >> Tab[i]; trier(Tab, N - 1); afficher(Tab,N); } }
C#
UTF-8
10,525
3
3
[]
no_license
using System; using System.Drawing; using System.Windows.Forms; namespace Amethyst.Input { /// <summary> /// Class representing the Mouse /// </summary> public class Mouse { private MouseState m_MouseState; private bool m_MoveEventFiredSinceUpdated = false; private bool m_WheelEventFiredSinceUpdated = false; /// <summary> /// The control that is bounded by the mouse /// </summary> public Control Control { get; private set; } /// <summary> /// Get the current mouse state /// </summary> public MouseState MouseState => m_MouseState; /// <summary> /// Instantiate a new Mouse /// </summary> /// <param name="control">The control that is bounded by the mouse</param> public Mouse(Control control) { m_MouseState = new MouseState(); Control = control; Point p = Control.PointToClient(Cursor.Position); m_MouseState.X = p.X; m_MouseState.Y = p.Y; m_MouseState.DeltaX = 0; m_MouseState.DeltaY = 0; m_MouseState.Wheel = 0; m_MouseState.Left = false; m_MouseState.Right = false; m_MouseState.Middle = false; m_MouseState.XButton1 = false; m_MouseState.XButton2 = false; Control.MouseMove += new MouseEventHandler(Control_MouseMove); Control.MouseDown += new MouseEventHandler(Control_MouseDown); Control.MouseUp += new MouseEventHandler(Control_MouseUp); Control.MouseWheel += new MouseEventHandler(Control_MouseWheel); Control.MouseClick += new MouseEventHandler(Control_MouseClick); Control.MouseDoubleClick += new MouseEventHandler(Control_MouseDoubleClick); Control.MouseEnter += new EventHandler(Control_MouseEnter); } private void Control_MouseMove(object sender, MouseEventArgs e) { if ((m_MouseState.X == e.X) && (m_MouseState.Y == e.Y)) { return; } m_MoveEventFiredSinceUpdated = true; m_MouseState.DeltaX = e.X - m_MouseState.X; m_MouseState.DeltaY = e.Y - m_MouseState.Y; m_MouseState.X = e.X; m_MouseState.Y = e.Y; Move?.Invoke(m_MouseState); } private void Control_MouseDown(object sender, MouseEventArgs e) { switch (e.Button) { case MouseButtons.Left: m_MouseState.Left = true; break; case MouseButtons.Right: m_MouseState.Right = true; break; case MouseButtons.Middle: m_MouseState.Middle = true; break; case MouseButtons.XButton1: m_MouseState.XButton1 = true; break; case MouseButtons.XButton2: m_MouseState.XButton2 = true; break; } ButtonDown?.Invoke(m_MouseState); } private void Control_MouseUp(object sender, MouseEventArgs e) { switch (e.Button) { case MouseButtons.Left: m_MouseState.Left = false; break; case MouseButtons.Right: m_MouseState.Right = false; break; case MouseButtons.Middle: m_MouseState.Middle = false; break; case MouseButtons.XButton1: m_MouseState.XButton1 = false; break; case MouseButtons.XButton2: m_MouseState.XButton2 = false; break; } ButtonUp?.Invoke(m_MouseState); } private void Control_MouseWheel(object sender, MouseEventArgs e) { if (e.Delta == 0) { return; } m_WheelEventFiredSinceUpdated = true; m_MouseState.Wheel += e.Delta; Wheel?.Invoke(m_MouseState); } private void Control_MouseClick(object sender, MouseEventArgs e) { switch (e.Button) { case MouseButtons.Left: LeftClick?.Invoke(m_MouseState); break; case MouseButtons.Right: RightClick?.Invoke(m_MouseState); break; case MouseButtons.Middle: MiddleClick?.Invoke(m_MouseState); break; case MouseButtons.XButton1: XButton1Click?.Invoke(m_MouseState); break; case MouseButtons.XButton2: XButton2Click?.Invoke(m_MouseState); break; } } private void Control_MouseDoubleClick(object sender, MouseEventArgs e) { switch (e.Button) { case MouseButtons.Left: LeftDoubleClick?.Invoke(m_MouseState); break; case MouseButtons.Right: RightDoubleClick?.Invoke(m_MouseState); break; case MouseButtons.Middle: MiddleDoubleClick?.Invoke(m_MouseState); break; case MouseButtons.XButton1: XButton1DoubleClick?.Invoke(m_MouseState); break; case MouseButtons.XButton2: XButton2DoubleClick?.Invoke(m_MouseState); break; } } private void Control_MouseEnter(object sender, EventArgs e) { Point p = Control.PointToClient(Cursor.Position); m_MouseState.X = p.X; m_MouseState.Y = p.Y; m_MouseState.DeltaX = 0; m_MouseState.DeltaY = 0; } /// <summary> /// Update the current mouse state /// </summary> public void Update() { #region ZERO MOVE DELTA IF NO MOVE EVENT FIRED if (!m_MoveEventFiredSinceUpdated) { m_MouseState.DeltaX = 0; m_MouseState.DeltaY = 0; } else { m_MoveEventFiredSinceUpdated = false; } #endregion #region ZERO MOVE WHEEL IF NO MOVE EVENT FIRED if (!m_WheelEventFiredSinceUpdated) { m_MouseState.Wheel = 0; } else { m_WheelEventFiredSinceUpdated = false; } #endregion } /// <summary> /// Force a new position for the mouse /// </summary> /// <param name="x">The new X coordinate</param> /// <param name="y">The new Y coordinate</param> public void SetPosition(int x, int y) { m_MouseState.X = x; m_MouseState.Y = y; Cursor.Position = Control.PointToScreen(new Point(m_MouseState.X, m_MouseState.Y)); m_MouseState.DeltaX = 0; m_MouseState.DeltaY = 0; } /// <summary> /// Force a new position for the mouse /// </summary> /// <param name="p">The new coordinates</param> public void SetPosition(Math.Point p) { SetPosition((int)p.X, (int)p.Y); } /// <summary> /// Make the mouse invisible /// </summary> public void Hide() { Cursor.Hide(); } /// <summary> /// Make the mouse visible /// </summary> public void Show() { Cursor.Show(); } /// <summary> /// An event that is fired when the mouse moves /// </summary> public event MouseEvent Move; /// <summary> /// An event that is fired when a mouse button is just down /// </summary> public event MouseEvent ButtonDown; /// <summary> /// An event that is fired when a mouse button is just released /// </summary> public event MouseEvent ButtonUp; /// <summary> /// An event that is fired when the mouse wheel is rolled /// </summary> public event MouseEvent Wheel; /// <summary> /// An event that is fired when a left click occurs /// </summary> public event MouseEvent LeftClick; /// <summary> /// An event that is fired when a left double click occurs /// </summary> public event MouseEvent LeftDoubleClick; /// <summary> /// An event that is fired when a right click occurs /// </summary> public event MouseEvent RightClick; /// <summary> /// An event that is fired when a right double click occurs /// </summary> public event MouseEvent RightDoubleClick; /// <summary> /// An event that is fired when a middle click occurs /// </summary> public event MouseEvent MiddleClick; /// <summary> /// An event that is fired when a middle double click occurs /// </summary> public event MouseEvent MiddleDoubleClick; /// <summary> /// An event that is fired when a XButton1 click occurs /// </summary> public event MouseEvent XButton1Click; /// <summary> /// An event that is fired when a XButton1 double click occurs /// </summary> public event MouseEvent XButton1DoubleClick; /// <summary> /// An event that is fired when a XButton2 click occurs /// </summary> public event MouseEvent XButton2Click; /// <summary> /// An event that is fired when a XButton2 double click occurs /// </summary> public event MouseEvent XButton2DoubleClick; } /// <summary> /// Represent the method that will handle an event that has a mouse state for parameter /// </summary> /// <param name="mouseState">The mouse state when the event was triggered</param> public delegate void MouseEvent(MouseState mouseState); }
Markdown
UTF-8
3,398
3.796875
4
[ "MIT" ]
permissive
--- title: Dynamic Relationships on Laravel Models description: How to add dynamic relationships on Laravel models. permalink: articles/dynamic-relationships-on-laravel-models date: 2020-05-10 image: /covers/dynamic-relationships-on-laravel-models.png tags: - php - laravel --- Learn how to add dynamic relationships on Laravel models. <!-- more --> Normally you can't extend a model without creating a lot of overhead. Also I learned the hard way, that it seems impossible to somehow use the Macroable trait on models ... 😞 But the following package can change all this with a similar approach, like the macroable trait uses. * [i-rocky/eloquent-dynamic-relation](https://github.com/i-rocky/eloquent-dynamic-relation) This package will provide a simple trait for your model so you can then extend it in other places without having to touch the model. This makes it perfect for connecting models that are distributed over multiple packages. The magic lays in the following trait. ```php <?php namespace Rocky\Eloquent; trait HasDynamicRelation { /** * Store the relations * * @var array */ private static $dynamic_relations = []; /** * Add a new relation * * @param $name * @param $closure */ public static function addDynamicRelation($name, $closure) { static::$dynamic_relations[$name] = $closure; } /** * Determine if a relation exists in dynamic relationships list * * @param $name * * @return bool */ public static function hasDynamicRelation($name) { return array_key_exists($name, static::$dynamic_relations); } /** * If the key exists in relations then * return call to relation or else * return the call to the parent * * @param $name * * @return mixed */ public function __get($name) { if (static::hasDynamicRelation($name)) { // check the cache first if ($this->relationLoaded($name)) { return $this->relations[$name]; } // load the relationship return $this->getRelationshipFromMethod($name); } return parent::__get($name); } /** * If the method exists in relations then * return the relation or else * return the call to the parent * * @param $name * @param $arguments * * @return mixed */ public function __call($name, $arguments) { if (static::hasDynamicRelation($name)) { return call_user_func(static::$dynamic_relations[$name], $this); } return parent::__call($name, $arguments); } } ``` You cann install the package through composer. ```bash composer require i-rocky/eloquent-dynamic-relation ``` Then you can apply it to your model like so. ```php <?php use Rocky\Eloquent\HasDynamicRelation; // ... class User extends Model { use HasDynamicRelation; // ... } ``` Then, for example in the service provider of your package, you can call the `addDynamicRelation` method to assign a new relationship method to the model. ```php User::addDynamicRelation('payments', function (User $User) { return $User->hasMany(Payment::class); }); ``` And thats it! You have added the `payments` method on the User model. Nice right? 😁
Java
UTF-8
697
1.75
2
[]
no_license
package com.bc.test; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.bc.frame.logger.Log4jManager; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:/spring/applicationContext-*.xml") public class LogTs extends AbstractJUnit4SpringContextTests { Logger logger = Log4jManager.get(); @Test public void saveTest() { logger.info("...start test..."); System.out.println(".. ok .."); } }
Java
UTF-8
261
1.6875
2
[]
no_license
package com.erp.repo; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.erp.classes.BillOfMaterial; @Repository public interface BOMRepo extends CrudRepository<BillOfMaterial, Integer> { }
Java
UTF-8
455
2.625
3
[]
no_license
package steve.jpong.specs; public abstract class Player { protected Paddle player_paddle; public abstract boolean check_collisions(Ball b); public abstract void initialize_paddle(); public Player(){ player_paddle = new Paddle( 15, 10, 75 ); initialize_paddle(); } public Paddle getPaddle(){ return player_paddle; } protected boolean in_range(int x, int low, int high){ if( x >= low && x <= high ){ return true; } return false; } }
Python
UTF-8
595
2.515625
3
[]
no_license
from django.db import models # Create your models here. class Programming_Authors(models.Model): programming_languages = models.CharField(max_length=20) authors = models.CharField(max_length=100) date_of_birth = models.DateField() def __str__(self): return self.authors class ProgrammingFramework(models.Model): framework_name = models.CharField(max_length=40) framework_type = models.CharField(max_length=40) programming_authors = models.ForeignKey(Programming_Authors,on_delete=models.CASCADE) def __str__(self): return self.framework_name
C
GB18030
1,816
3.6875
4
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { /* */ if (l1 == NULL || l2 == NULL) { return l1 != NULL ? l1 : l2; } /* ȡϲ֮ͷڵ */ struct ListNode* mergeHead = l1->val > l2->val ? l2 : l1; /* ¼нڵֵСĽڵ㣬ڱ */ struct ListNode* cur1 = mergeHead == l1 ? l1 : l2; struct ListNode* cur2 = mergeHead == l1 ? l2 : l1; /* ¼ϴαȽʱڵֵСĽڵ */ struct ListNode* pre = NULL; /* ¼ǰڵֵĽڵһڵ㣬ֹϿ֮޷ҵĽڵ */ struct ListNode* next = NULL; while (cur1 != NULL && cur2 != NULL) { if (cur1->val <= cur2->val) { pre = cur1; cur1 = cur1->next; } else { next = cur2->next; /* ǰڵֵСĽڵӵһнڵֵĽڵ */ pre->next = cur2; /* һнڵֵĽڵӵǰڵֵСĽڵһڵ */ cur2->next = cur1; pre = cur2; cur2 = next; } } /* ϲ l1 l2 ֻһδϲֱ꣬ӽĩβָδϲ */ pre->next = cur1 == NULL ? cur2 : cur1; return mergeHead; } struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { /* */ if (l1 == NULL || l2 == NULL) { return l1 != NULL ? l1 : l2; } struct ListNode* mergeHead = NULL; if (l1->val < l2->val) { /* ȡϲ֮ͷڵ */ mergeHead = l1; /* ϲ֮ҽͷڵ֮ */ mergeHead->next = mergeTwoLists(l1->next, l2); } else { mergeHead = l2; mergeHead->next = mergeTwoLists(l1, l2->next); } return mergeHead; }
Markdown
UTF-8
6,405
3.046875
3
[]
no_license
## Building Multi-tenant applications on MongoDB 20140812 https://web.archive.org/web/20140812091703/http://support.mongohq.com/use-cases/multi-tenant.html MongoDB is very popular for SaaS applications, and we are frequently asked "how should I build an application that can handle multiple customers?" We have two good answers. One database for all customers It's reasonably easy (conceptually) to put all customer database in a single database with a single set of collections. Each document needs a customer_id field. Queries and updates should use that field to restrict the scope of documents they're working with. Most web apps start with this method, and have for quite some time. Application frameworks, object mappers, and other toolkits generally have built in methods of handling customer segmentation at the field level. This makes development straightforward, though there's more pressure on the application to ensure security. This setup also allows queries across data from multiple customers. "Global" views of data are very easy to generate from the application, so leaderboards, popularity feeds and other widgets are quick to implement. From a scaling perspective, this works well with MongoDB sharding since you can keep customer data grouped together and do efficient range queries. If you do go this route, make sure you use a customer_id that's reasonably random. Incrementing customer_ids don't work as well for scale as values with a high cardinality. MongoDB's new hashed shard keys can help with scale, even when customer_id values are incremental. This does require an additional index, though, and it's always better to minimize redundant indexes. One database per customer This is a good strategy, with some basic rules. First, each database in Mongo adds operational complexity and requires a minimum of 32MB of disk space. Freemium applications with many, many small customers may not be financially viable with this method. We have a few large customers who have implemented this strategy well. On the application side, they route account data to the appropriate replica set and database name based on the customer. Operationally, it's best to only have a few hundred DBs per Mongo process (for a lot of reasons) so scaling becomes a matter of adding replica sets as the app gets more popular, with enough app logic to move new DBs to the new sets. Exporting or deleting a customer's data is simple, and MongoDB will do a good job of reclaiming disk space when customers churn (which, hopefully, doesn't happen ...). Optimizing larger customers' databases is, likewise, pretty straightforward. Customers can even have different indexing strategies if their use case calls for it. If you do go this route, make sure you run MongoDB with smallfiles=true and pay careful attention to how well balanced customer DBs are between replica sets. One collection per customer It is very tempting to isolate customer data by prefixing collection names with a customer identifier and cramming them all in a single database. Please do not do this, it will end up hurting your application if you have any kind of success. MongoDB is not meant to scale at the collection level and you will quickly run into namespace limits. Even worse, data management tools have a very difficult time handling more than 100 collections or so. This is a very sharp edge case that it's best to avoid. When to use what? A single database is preferrable for ease of initial development and lowest operational overhead. It can be painful, though, if queries vary substantially between customers and aren't easy to speed up via shared indexes. Slow queries (especially table scans) on large customers can hurt performance for everyone else. A typical use case is a multi-tenant advertising platform. When looking for the ability to measure impact from a single customer, like a CRM system, then the database per customer route is likely a better option. CRMs require very flexible query / search capabilities and have customers with very diverse data sizes. Running Multi-tenant on MongoHQ With MongoHQ's dedicated platforms, we have the options to support either multi-tenant single databases or the one-database-per-customer. One-database-per-customer is implemented on dedicated servers by giving the customer administrative access to the database. From there, the customer can create databases on the fly for customers. When outgrowing the single server, MongoHQ can add more MongoDB processes to the same server, or scale out to multiple servers. Single database solutions should start on our Replica Set SSD plans. As the app scales, we will help you take advantage of MongoDBs auto sharding to keep up with your customer growth. Still Need Help? If this article didn't solve things, summon a human and get some help! ## https://stackoverflow.com/questions/2748825/what-is-the-recommended-approach-towards-multi-tenant-databases-in-mongodb https://stackoverflow.com/questions/46439677/mongodb-different-collection-per-tenant ## Multi-tenant MongoDB + mongo-native driver + connection pooling https://stackoverflow.com/questions/57345147/multi-tenant-mongodb-mongo-native-driver-connection-pooling It's a shame since till this day, in Mongo, "connection" (network stuff, SSL, cluster identification) and authentication are 2 separate actions. Think about when you run mongo shell, you provide the host, port, replica set if any, and your in, connected! But not authenticated. You can then authenticate to user1, do stuff, and then authenticate to user2 and do stuff only user2 can do. And this is done on the same connection! without going thru the overhead creating the channel again, SSL handshake and so on... https://www.slideshare.net/mongodb/securing-mongodb-to-serve-an-awsbased-multitenant-securityfanatic-saas-application?from_action=save 多个租户共享一个数据库,每个租户一个文档,问题在于 每个租户使用不同的身份密码取访问数据库,使用同一个线程池,每个线程采用不同的密码取访问数据库。 但是在前端,每个租户 通过认证获取令牌,取访问获取线程池, 线程里却要使用不同的密码去访问数据库。 ## Guide to multi-tenancy with Spring Boot and MongoDB https://medium.com/@alexantaniuk/guide-to-multi-tenancy-with-spring-boot-and-mongodb-78ea5ef89466
Markdown
UTF-8
1,361
2.734375
3
[]
no_license
Solution ======== First Step: Image Overlay ------------------------- The first task is to develop an algorithm that take two images of the same thing captured at different times, and to generate a single transformation that will map the gross features of the second image onto the first. The images may have different lighting, and be taken at a slightly different position. As an example, we will take the following two images. The second (B) was taken some time later than the first (A) and it can be seen that some of the detailed features are different, and the camera position is obviously slightly offset compared to the first. However we can see that the large-scale features of the sample (the brown blob) are more-or-less unchanged. ![Crystal before](https://github.com/DiamondLightSource/CrystalMatch/blob/master/docs/img/brown_crystal1.jpg) \s ![Crystal After](https://github.com/DiamondLightSource/CrystalMatch/blob/master/docs/img/brown_crystal2.jpg) The goal here is to figure out the transformation that will map image B onto image A. This will be a translation of the form (-x um, -y um). The following approach for solving this problem was originally developed by Nic Bricknell. First we define a metric, metric(imageA, imageB, transformation), that quantifies how closely image B matches image A when the transformation is applied to image B.
JavaScript
UTF-8
701
3.453125
3
[]
no_license
let year = +prompt('Введите свой возраст'); let age; if (isNaN(year)){ age = 'Нужно ввести цифрами! Перезагрузите страницу!'; } else if (0 >= year){ age = 'Загрузка: подождите пока родитесь!'; } else if (year <= 10){ age = 'Привет малой!'; } else if (year <= 18){ age = 'Здарова братан!'; } else if (year <= 50){ age = 'Дядя напиши мне сайт'; } else if (year <= 80){ age = 'Вам пора в пенсию'; } else if (year <= 110){ age = 'Вы еще живы?'; } else{ age = 'Помним и вспоминаем :(' } alert(age);
Ruby
UTF-8
303
3.46875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def count_strings(array) total = 0 array.count do |element| if element.class == String total += 1 end end total end def count_empty_strings(array) total = 0 array.count do |element| if element == "" total += 1 end end total end
C
UTF-8
2,461
3.296875
3
[]
no_license
#include <stdio.h> #include "my_functions.h" #include <string.h> int is_separator(int c) { char separator[] = " ,;:-.!?"; for (int i = 0; separator[i] != '\0'; i++) { if (c == separator[i]) return YES; } return NO; } int str_equality(const char *str1, const char *str2) { while (*str1 != '\0' && *str2 != '\0' && (*str1 == *str2)) { str1++; str2++; } return *str1 == *str2; } int my_split(const char *str, char words[][MAX_LETTERS]) { char word[MAX_LETTERS]; int i = 0, j = 0, letter_counter = 0; while (str[i] != '\0') { if (letter_counter > MAX_LETTERS) return WORD_LEN_ERR; if (!is_separator(str[i])) { word[letter_counter] = str[i]; letter_counter++; } if (is_separator(str[i++]) && letter_counter != 0) { word[letter_counter] = '\0'; letter_counter = 0; strcpy(words[j++], word); } } if (letter_counter != 0) { word[letter_counter] = '\0'; strcpy(words[j++], word); } return j; } void shift(char *str, int pos) { int i = pos; while ((str[i] = str[i + 1]) != '\0') i++; str[i + 1] = '\0'; } void delete_symbols(char *str, char symbol) { for (int i = 1; str[i] != '\0'; i++) { if (str[i] == symbol) { shift(str, i); i--; } } } void form_string(char *result_str, char words[][MAX_LETTERS], int words_count) { for (int i = words_count - 1; i >= 0; i--) { if (strcmp(words[words_count - 1], words[i])) { delete_symbols(words[i], words[i][0]); strcat(result_str, words[i]); i != 0 ? strcat(result_str, " ") : 0; } } } int errors_check(const int rc) { if (rc == LEN_LINE_ERR) { fprintf(stderr, LEN_LINE_MSG); return LEN_LINE_ERR; } if (rc == NO_WORDS_ERR) { fprintf(stderr, NO_WORDS_MSG); return NO_WORDS_ERR; } if (rc == CANNOT_READ_ERR) { fprintf(stderr, FIND_EOF_MSG); return CANNOT_READ_ERR; } if (rc == EMPTY_ERR) { fprintf(stderr, EMPTY_LINE_MSG); return EMPTY_ERR; } if (rc == WORD_LEN_ERR) { fprintf(stderr, LEN_WORD_MSG); return WORD_LEN_ERR; } return rc; }
Java
UTF-8
1,839
3
3
[ "Apache-2.0" ]
permissive
import java.sql.*; import java.util.ArrayList; import java.util.TreeSet; //Driver drv = new com.mysql.cj.jdbc.Driver(); ????? public class SqlApp { public static void main(String[] args) throws ClassNotFoundException, SQLException { String userName = "root"; String password = ""; String connectUrl = "jdbc:mysql://localhost/test"; Class.forName("com.mysql.jdbc.Driver"); try (Connection connection = DriverManager.getConnection(connectUrl, userName, password)) { // System.out.println("We're connected"); Statement stm = connection.createStatement(); // stm.executeUpdate("CREATE TABLE `worker` (`id` MEDIUMINT NOT NULL AUTO_INCREMENT,`first name` VARCHAR(30) NOT NULL," // + "`last name` VARCHAR(30) NOT NULL,`position` VARCHAR(30) NOT NULL, PRIMARY KEY(`id`));"); ArrayList<Worker> arr = new ArrayList<>(); TreeSet<Worker> tree = new TreeSet<>(); for(int i = 0;i<5;i++) { tree.add(Worker.getRandomWorker()); } for(Worker w:tree) { arr.add(w); } for (int i = 0; i<10; i++) { String fn = arr.get(i).getFirstName(); String ln = arr.get(i).getLastName(); String p = arr.get(i).getPosition(); String insrtSQL = "INSERT INTO worker(`first name`,`last name`,`position`) VALUES ('" + arr.get(i).getFirstName() + "','" + arr.get(i).getLastName() + "','" + arr.get(i).getPosition() + "');"; System.out.println(insrtSQL); stm.executeUpdate(insrtSQL); // stm.executeUpdate("DROP TABLE `worker`;"); } } } } //ResultSet rs = stm.executeQuery("SELECT * FROM tbl_books"); //while (rs.next()) { // String str = rs.getString("b_author") + ":" + rs.getString(5); // System.out.println("Author:" + str); //}
Python
UTF-8
257
3.34375
3
[]
no_license
x=raw_input().split(' ') a=int(x[0]) b=int(x[1]) sm=0 if a>=b: while b!=0: sm=sm+a/b temp=a a=b b=temp%b else: while a!=0: sm=sm+b/a temp=b b=a a=temp%a print sm
C++
UTF-8
7,017
2.65625
3
[]
no_license
#include "pch.h" #include "Camera.h" #include "ResourceManager.h" static auto TiledF = [](float& a, float imageSize, float count) { if (a > imageSize * (count / 2)) { while (a > imageSize* (count / 2)) { a -= imageSize * count; } } else if (a < -imageSize * (count / 2)) { while (a < -imageSize * (count / 2)) { a += imageSize * count; } } }; static auto TiledI = [](int& a, int imageSize, int count) { if (a > imageSize * (count / 2)) { while (a > imageSize * (count / 2)) { a -= imageSize * count; } } else if (a < -imageSize * (count / 2)) { while (a < -imageSize * (count / 2)) { a += imageSize * count; } } }; Vec2DF Camera::CameraTransform(const Vec2DF& transform) const { return Vec2DF(transform.x - position.x, transform.y - position.y); } void Camera::Lerp(Vec2DF other, float t) { this->minPosition.x = this->position.x; this->position = this->position.Lerp(other, t); clamp(); } void Camera::Move(Vec2DF vec) { this->position += vec; clamp(); } void Camera::Teleport(Vec2DF vec) { this->position = vec; clamp(); } void Camera::clamp() { this->position.x = Utill::clamp(this->position.x, this->minPosition.x, this->maxPosition.x); this->position.y = Utill::clamp(this->position.y, this->minPosition.y, this->maxPosition.y); } void Camera::BackDraw(PaintInfo info) const { { auto& backImg = ResourceManager::GetImages("bg-drago-n-back")->at(0).img; float scale = info.DrawSize.y / static_cast<float>(backImg->GetHeight()) * 1.05; Vec2DF imageSize = Vec2DF { ResourceManager::GetImages("bg-drago-n-back")->at(0).img->GetWidth() * scale, ResourceManager::GetImages("bg-drago-n-back")->at(0).img->GetHeight() * scale }; float xNum = 0.15; float yNum = 0.05; float cnt = 3; for (size_t i = 0; i < cnt; i++) { float firstX = -position.x * xNum + (imageSize.x - 1) * i; TiledF(firstX, (imageSize.x - 1), cnt); backImg->Draw(info.hdc, firstX, position.y * yNum, imageSize.x, imageSize.y); } } { float scale = info.DrawSize.y / static_cast<float>(ResourceManager::GetImages("bg-drago-n-tile")->at(0).img->GetHeight()) * 0.9; Vec2DF imageSize = Vec2DF { ResourceManager::GetImages("bg-drago-n-tile")->at(0).img->GetWidth() * scale, ResourceManager::GetImages("bg-drago-n-tile")->at(0).img->GetHeight() * scale }; float xNum = 1; float yNum = 1; float cnt = 16; int idx[16] = { 4,1,4,0, 4,3,4,0, 4,2,4,3, 4,5,4,1 }; for (size_t i = 0; i < cnt; i++) { auto& backImg = ResourceManager::GetImages("bg-drago-n-tile")->at(idx[i]).img; float firstX = -position.x * xNum + (imageSize.x - 1) * i; TiledF(firstX, (imageSize.x - 1), cnt); backImg->Draw(info.hdc, firstX, -position.y * yNum + 100, imageSize.x, imageSize.y); } } } void Camera::Draw(PaintInfo info) const { if (true) { { auto& backImg = ResourceManager::GetImages("bg-drago-n-mid")->at(0).img; //float scale = info.DrawSize.y / static_cast<float>(backImg->GetHeight()) * 0.9; float scale = 1; Vec2DF imageSize = Vec2DF { ResourceManager::GetImages("bg-drago-n-mid")->at(0).img->GetWidth() * scale, ResourceManager::GetImages("bg-drago-n-mid")->at(0).img->GetHeight() * scale }; float xNum = 1; float yNum = 1; float cnt = 6; for (size_t i = 0; i < cnt; i++) { float firstX = -position.x * xNum + (imageSize.x - 0.9) * i; TiledF(firstX, (imageSize.x - 0.9), cnt); backImg->Draw(info.hdc, firstX, -position.y * yNum + 630, imageSize.x, imageSize.y); } } { auto& backImg = ResourceManager::GetImages("bg-drago-n-mid")->at(1).img; //float scale = info.DrawSize.y / static_cast<float>(backImg->GetHeight()) * 0.9; float scale = 1; Vec2DF imageSize = Vec2DF { ResourceManager::GetImages("bg-drago-n-mid")->at(1).img->GetWidth() * scale, ResourceManager::GetImages("bg-drago-n-mid")->at(1).img->GetHeight() * scale }; float xNum = 1; float yNum = 1; float cnt = 6; for (size_t i = 0; i < cnt; i++) { float firstX = -position.x * xNum + (imageSize.x - 0.9) * i; TiledF(firstX, (imageSize.x - 0.9), cnt); backImg->Draw(info.hdc, firstX, -position.y * yNum - 5, imageSize.x, imageSize.y); } } } } /* void Camera::BackDraw(PaintInfo info) const { { auto& backImg = ResourceManager::GetImages("bg-drago-back")->at(0).img; float scale = info.DrawSize.y / static_cast<float>(backImg->GetHeight()) * 1.05; Vec2DF imageSize = Vec2DF { ResourceManager::GetImages("bg-drago-back")->at(0).img->GetWidth() * scale, ResourceManager::GetImages("bg-drago-back")->at(0).img->GetHeight() * scale }; float xNum = 0.5; float yNum = 0.15; float cnt = 3; for (size_t i = 0; i < cnt; i++) { float firstX = -position.x * xNum + (imageSize.x - 1) * i; TiledF(firstX, (imageSize.x - 1), cnt); backImg->Draw(info.hdc, firstX, position.y * yNum, imageSize.x, imageSize.y); } } { auto& backImg = ResourceManager::GetImages("bg-drago-tile")->at(4).img; float scale = info.DrawSize.y / static_cast<float>(backImg->GetHeight()) * 0.9; Vec2DF imageSize = Vec2DF { ResourceManager::GetImages("bg-drago-tile")->at(0).img->GetWidth() * scale, ResourceManager::GetImages("bg-drago-tile")->at(0).img->GetHeight() * scale }; float xNum = 1; float yNum = 1; float cnt = 16; for (size_t i = 0; i < cnt; i++) { float firstX = -position.x * xNum + (imageSize.x - 0.9) * i; TiledF(firstX, (imageSize.x - 0.9), cnt); backImg->Draw(info.hdc, firstX, -position.y * yNum + 100, imageSize.x, imageSize.y); } } } void Camera::Draw(PaintInfo info) const { if (true) { { auto& backImg = ResourceManager::GetImages("bg-drago-mid")->at(0).img; //float scale = info.DrawSize.y / static_cast<float>(backImg->GetHeight()) * 0.9; float scale = 1; Vec2DF imageSize = Vec2DF { ResourceManager::GetImages("bg-drago-mid")->at(0).img->GetWidth() * scale, ResourceManager::GetImages("bg-drago-mid")->at(0).img->GetHeight() * scale }; float xNum = 1; float yNum = 1; float cnt = 5; for (size_t i = 0; i < cnt; i++) { float firstX = -position.x * xNum + (imageSize.x - 0.9) * i; TiledF(firstX, (imageSize.x - 0.9), cnt); backImg->Draw(info.hdc, firstX, -position.y * yNum + 510, imageSize.x, imageSize.y); } } { auto& backImg = ResourceManager::GetImages("bg-drago-mid")->at(1).img; //float scale = info.DrawSize.y / static_cast<float>(backImg->GetHeight()) * 0.9; float scale = 1; Vec2DF imageSize = Vec2DF { ResourceManager::GetImages("bg-drago-mid")->at(1).img->GetWidth() * scale, ResourceManager::GetImages("bg-drago-mid")->at(1).img->GetHeight() * scale }; float xNum = 1; float yNum = 1; float cnt = 5; for (size_t i = 0; i < cnt; i++) { float firstX = -position.x * xNum + (imageSize.x - 0.9) * i; TiledF(firstX, (imageSize.x - 0.9), cnt); backImg->Draw(info.hdc, firstX, -position.y * yNum, imageSize.x, imageSize.y); } } } } */
C
UTF-8
1,540
2.765625
3
[ "MIT" ]
permissive
#include "simd.h" #include <stdio.h> #include <stdlib.h> void solve(int W, int H, int N, float *input, float *output) { const int CHUNK_SIZE = 64; #pragma omp parallel for for (int i = 0; i < H; i += CHUNK_SIZE) { float *tmp_buf = (float *)malloc(sizeof(float) * W * (CHUNK_SIZE + N - 1)); for (int ii = 0; ii < CHUNK_SIZE + N - 1 && i + ii < H + N - 1; ++ii) { float tmp = 0; for (int jj = 0; jj < N; ++jj) tmp += input[(i + ii) * (W + N - 1) + jj]; tmp_buf[ii * W] = tmp; for (int j = 1; j < W; ++j) tmp_buf[ii * W + j] = tmp_buf[ii * W + (j - 1)] - input[(i + ii) * (W + N - 1) + (j - 1)] + input[(i + ii) * (W + N - 1) + j + N - 1]; for (int j = 0; j < W; ++j) tmp_buf[ii * W + j] /= N; } for (int j = 0; j < W; ++j) { float tmp = 0; for (int jj = 0; jj < N; ++jj) tmp += tmp_buf[jj * W + j]; output[i * W + j] = tmp / N; } for (int ii = 1; ii < CHUNK_SIZE && i + ii < H; ++ii) for (int j = 0; j < W; ++j) output[(i + ii) * W + j] = (output[(i + ii - 1) * W + j] * N - tmp_buf[(ii - 1) * W + j] + tmp_buf[(ii + N - 1) * W + j]) / N; free(tmp_buf); } }
Python
UTF-8
343
3.03125
3
[]
no_license
import pickle import numpy as np model = pickle.load(open('model.pkl','rb')) # prediccion de un nuevo dato nuevo_dato1 = np.array([[0.199713, 4.323565]]) # Ahora encontramos la etiqueta o clase de este nuevo individuo label_pred_load21 = model.predict(nuevo_dato1) #etiqueta_nueva_dato1 = print("Etiqueta nuevo dato: ", label_pred_load21)
PHP
UTF-8
338
3.421875
3
[]
no_license
<?php $student_array[0] = "Angelina"; $student_array[1] = "Edwin"; $student_array[2] = "Lavanya"; $student_array[3] = "Syafiqah"; echo "The student with second index is ".$student_array[1]."<br>"; echo "The student with fourth index is ".$student_array[3]."<br>"; echo "My class has a total of ".count($student_array)." students<br>"; ?>
Markdown
UTF-8
2,112
2.953125
3
[ "MIT" ]
permissive
--- title: 以哥念 date: 15/08/2018 --- 在安提阿犹太领袖的煽动下,地方当局鼓动一个暴徒起来反对保罗和巴拿巴,并将他们赶出城(徒13:50)。然而,门徒满心喜乐又被圣灵充满(徒13:52)。然后传道士们到以哥念城去了。 `阅读徒14:1-7。保罗与巴拿巴在以哥念做工的结果是什么?` 在以哥念,保罗和巴拿巴持续着他们先向犹太人然后再向外邦人传讲的习惯。保罗在安提阿的讲道(徒13:16-41)指出了在他们传道中犹太人优先背后的主要原因:以色列的被拣选,及其所包含的一切(罗3:2;9:4,5),以及上帝实现了祂从戴维子孙中、出一位救主的应许。尽管许多犹太人拒绝福音,但保罗从未失去大批犹太人悔改的希望。 在罗9-11章,保罗说的很清楚「从以色列生的,不都是以色列人」(罗9:6),只是因为上帝的怜悯,才有些犹太人完全相信。上帝没有拒绝祂的子民,但是「如今也是这样,照着拣选的恩典,还有所留的余数」(罗11:5)。保罗继续向外邦人传福音,尽管他相信有一天更多的犹太人会相信耶稣。 「保罗在罗9-11章的论述进一步解释了在使徒行传中记述、他所追求的传道策略,而且使每一代基督徒认识到,向不信的犹太人作见证具有神学上的重要性。」──戴维.彼得森,《使徒行传》大急流城:贝克,2009),第401页。 这里的情况和安提阿没有很大区别。犹太人和外邦人对保罗的福音,其第一反应都是非常赞同的,但是不信的犹太人,可能是当地犹太团体的领袖,又鼓动外邦人、使他们仇视传教士们,他们的行为在人群中造成了分裂。由于敌对者们计划攻击并以私刑处死保罗和巴拿巴,两个传教士决定离开这城到下一个城去。 `犹太人需要的不只是单单听到福音,而是看见那些宣扬耶稣之名的人活出福音。如果你有犹太朋友,你给他们什么见证呢?`
C++
UTF-8
1,879
3.203125
3
[]
no_license
#include <cstdlib> #include<stdlib.h> #include<iostream> #include<fstream> #include<math.h> /* Tarea 02 Ayudantia Paralela Kevin Gatica Oportus 19.034.012-0 */ using namespace std; /* void escribirArchivo(){ ofstream f; f.open("archivo.txt",ios::out);//crear archivo.txt int num=0; for (int i=0;i<100000;i++){//escribe los 100k random num = rand(); f<<num<<endl; } } void leerArchivo(){ ifstream f("archivo.txt"); int arreglo[100000]; char aux[100]; int auxx=0; int i=0; //leer archivo while(!f.eof()){ //getline(f,aux); f >> aux; arreglo[i]=atoi(aux); if(i<10) { cout << arreglo[i] << endl; } i++; } f.close(); } */ void arregloRandom(int arreglo[]){ for(int i=0;i<100000;i++){ arreglo[i] =rand(); //cout<<arreglo[i]<<endl; } } float prom(int arreglo[], float promedio){ for (int i=0;i<100000;i++){ promedio = promedio + arreglo[i]; } promedio = promedio/100000; //cout << "El promedio11 es= " << promedio << endl; return promedio; } float var(int arreglo[], float promedio){ double varianza = 0; double sumatoria = 0; for (int i=0;i<100000;i++){ sumatoria = sumatoria + pow(arreglo[i] - promedio,2); } varianza = sumatoria / 100000; return varianza; } int main(int argc, char** argv) { //escribirArchivo(); //leerArchivo(); int arreglo[100000]; float promedio = 0; double varianza = 0; double desviacion = 0; arregloRandom(arreglo); promedio = prom(arreglo,promedio); cout << "El promedio es= " << promedio << endl; varianza = var(arreglo,promedio); cout << "La varianza es= " << varianza << endl; desviacion = sqrt(varianza); cout << "La desviacion es= " << desviacion << endl; return 0; }
Python
UTF-8
1,246
3.578125
4
[]
no_license
import openpyxl from pprint import pprint plik = openpyxl.load_workbook("example2.xlsx") # print(plik) arkusze = plik.sheetnames print(arkusze) aktywny_arkusz = plik.get_sheet_by_name("Owoce") print(f"Aktywny arkusz: {aktywny_arkusz.title}") # kokórki komorka = aktywny_arkusz["A1"] print(komorka) print(komorka.value) # from openpyxl.cell.cell import Cell # assert isinstance(komorka, Cell.) # wspolrzedne print(f"Adres komorki: {komorka.coordinate}") print(f"Kolumna komorki: {komorka.column}") print(f"Wiersz komorki {komorka.row}") print(aktywny_arkusz.cell(row=2, column=2)) # zmiana liter kolumn na liczbe i vive wersa from openpyxl.utils import get_column_letter, column_index_from_string print(get_column_letter(123)) print(column_index_from_string("DS")) # (wspolrzedne) dolnego prawego rogu arkusza dokad sa dane print("Ostatnia koluna to:") print(aktywny_arkusz.max_column) print(get_column_letter(aktywny_arkusz.max_column)) print("Ostatni wiersz to;") print(aktywny_arkusz.max_row) pprint(aktywny_arkusz["A1":"C7"], indent=4) for wiersz in aktywny_arkusz["A1":"C9"]: for kom in wiersz: print(kom.value, end=' ') print() aktywny_arkusz["B9"] = "wpis z Pythona" plik.save("example2.xlsx") plik.close()
SQL
UTF-8
2,650
4.21875
4
[]
no_license
-- 写法1 select level, count(distinct video_id) as video_num, sum(vv) as vv_num, sum(vv)/count(distinct video_id) avg_vv from ( select case when vv>=100000 then "10w+" when vv>=50000 then "5w+" when vv>=20000 then "2w+" when vv>=10000 then "1w+" when vv>=8000 then "8k+" when vv>=5000 then "5k+" when vv>=2000 then "2k+" when vv>=1000 then "1k+" else "0~1k" end as level, video_id, vv from ( select --owner_id, video_id, sum(play_vv) as vv from wesee::fact_event_action_mix_day b where dt between 20200521 and 20200629 and is_recommend = 1 and play_vv != 0 and exists(select pid from wesee::20200630_pid a where a.pid = b.owner_id) group by video_id ) ) group by level -- 写法2 select level, count(distinct video_id) as video_num, sum(vv) as vv_num, sum(vv)/count(distinct video_id) avg_vv from ( select pid from wesee::20200630_pid ) a join ( select *, case when vv>=100000 then "10w+" when vv>=50000 then "5w+" when vv>=20000 then "2w+" when vv>=10000 then "1w+" when vv>=8000 then "8k+" when vv>=5000 then "5k+" when vv>=2000 then "2k+" when vv>=1000 then "1k+" else "0~1k" end as level from ( select owner_id, video_id, sum(play_vv) as vv from wesee::fact_event_action_mix_day where dt between 20200521 and 20200629 and is_recommend = 1 group by owner_id, video_id ) ) b on a.pid = b.owner_id group by level; -- 5月31日-6月29日 违规账号每天推荐总VV select dt, count(distinct video_id) as video_num, sum(vv) as vv_num, sum(vv)/count(distinct video_id) avg_vv from ( select pid from wesee::20200630_pid ) a join ( select dt, owner_id, video_id, sum(play_vv) as vv from wesee::fact_event_action_mix_day where dt between 20200531 and 20200629 and is_recommend = 1 group by dt, owner_id, video_id ) b on a.pid = b.owner_id group by dt; -- 5月31日-6月29日 大盘每天推荐总VV select dt, count(distinct video_id), sum(play_vv) from wesee::fact_event_action_mix_day where dt between 20200531 and 20200629 and is_recommend = 1 and play_vv != 0 group by dt
C++
UTF-8
17,487
3.21875
3
[]
no_license
#include "Camera.h" Camera::Camera(const size_t width, const size_t height, const dvec3& eye) : _eye_point(eye), _camera_film(width, height), _scene(nullptr), _distribution(std::uniform_real_distribution<double>(0.0, 1.0)) { setupCameraMatrix(); computePixelWidth(); } void Camera::loadScene(Scene* scene) { _scene = scene; } void Camera::render(const int& num_samples) { // Image dimensions const size_t height = _camera_film.height; const size_t width = _camera_film.width; // Number of ray reflections to trace const int max_reflections = 7; // Samples per pixel for (int n = 0; n < num_samples; ++n) { // Print out the progress in percentage float progress = (float)n / (float)num_samples; std::cout << "Progress: " << progress * 100.0 << " %" << std::endl; // Parallization with OpenMP #pragma omp parallel for schedule(dynamic) for (int pixel_y = 0; pixel_y < height; ++pixel_y) { for (int pixel_x = 0; pixel_x < width; ++pixel_x) { // Normalize coordinates by transforming from [0 : width/height] to the range [-1.0 : 1.0] dvec2 pixel_normalized = normalizedPixelCoord(pixel_x, pixel_y); // Generate a random offset in the pixel plane (used for ray randomization to reduce aliasing) double dx = _distribution(_generator) * _pixel_width - (0.5 * _pixel_width); double dy = _distribution(_generator) * _pixel_width - (0.5 * _pixel_width); // Replace aliasing with noise by adding the random offset to the pixel dvec4 pixel_sample(pixel_normalized.x + dx, pixel_normalized.y + dy, 1.0, 1.0); // Transform screen coordinates to world coordinates dvec3 pixel_world(_transform_matrix * pixel_sample); // Define the ray from camera eye to pixel Ray ray(_eye_point, normalize(pixel_world)); // Compute the incoming radiance dvec3 final_color = tracePath(ray, max_reflections); // Clamp the values between [0.0, 1.0] clamp(final_color, 0.0, 1.0); // Save pixel color _camera_film.addPixelData(pixel_x, pixel_y, final_color / (double)num_samples); } } } } void Camera::createImage(const char* file_name) { size_t image_width = _camera_film.width; size_t image_height = _camera_film.height; // Allocate memory for the bitmap file Bitmap image(image_width, image_height); int index = 0; for (int j = 0; j < image_height; ++j) { for (int i = 0; i < image_width; ++i) { // Fetch current pixel intensity dvec3 pixel = _camera_film.pixel_data[index++]; // Convert color values to unsigned char uint8_t r = uint8_t(min(pixel.x, 1.0) * 255); uint8_t g = uint8_t(min(pixel.y, 1.0) * 255); uint8_t b = uint8_t(min(pixel.z, 1.0) * 255); // Set pixel color in the bitmap image image.setPixelColor(i, j, r, g, b, 255); } } // Write data to a bitmap file image.writeToFile(file_name); } //***************** PRIVATE ****************// dvec3 Camera::tracePath(const Ray& ray, const int reflection_count) { // Base case (if reflection count is zero end recursion) if (reflection_count == 0) return dvec3(0.0); // The closest intersection for current ray IntersectionPoint surface_point; // Test the ray against all geometries in the scene (function returns true if valid intersection is found) if (geometryIntersectionTest(ray, surface_point) == false) { return dvec3(0.0); } // Light source if (surface_point.material->surface_type == Material::SurfaceType::LightSource) { return surface_point.material->color; } // Specular surface else if (surface_point.material->surface_type == Material::SurfaceType::Specular) { // Compute reflected ray dvec3 reflect_direction = reflect(ray.direction, surface_point.normal); // Add bias to offset ray origin from surface //dvec3 bias = ray.direction * EPSILON; Ray reflected_ray(surface_point.position, reflect_direction); // Recursive path tracing (perfect reflection) return tracePath(reflected_ray, reflection_count - 1); } // Transparent surface else if (surface_point.material->surface_type == Material::SurfaceType::Transparent) { // Refractive indices //*** This should probably be apart of the material class ***// double n_1 = 1.0; // Air double n_2 = 1.5; // Glass // Check the current medium the ray is traveling in double cos_theta = dot(surface_point.normal, ray.direction); dvec3 surface_normal = surface_point.normal; // If theta < 0.0, the normal is facing the opposite direction from incoming ray (current medium is air) if (cos_theta < 0.0) { cos_theta = -cos_theta; } else { // Current medium is glass std::swap(n_1, n_2); surface_normal = -surface_normal; } // Compute Fresnel's equation for radiance distribution over reflected and refracted ray double reflection_ratio = fresnelsEquation(n_1, n_2, cos_theta); // If the current medium is thicker than the outgoing medium and refraction ratio == 1, we have total reflection and no refraction dvec3 refracted_light(0.0); if (reflection_ratio < 1.0) { // Compute the refracted ray double n_1_div_n_2 = n_1 / n_2; double A = 1.0 - (n_1_div_n_2 * n_1_div_n_2) * (1.0 - cos_theta * cos_theta); dvec3 refracted_direction( ray.direction * n_1_div_n_2 + surface_normal * (n_1_div_n_2 * cos_theta - sqrt(A)) ); // Add bias to offset ray origin from the surface dvec3 bias = refracted_direction * EPSILON; Ray refracted_ray(surface_point.position + bias, refracted_direction); // Recursion (multiplied with the refraction distribution coefficient) refracted_light = tracePath(refracted_ray, reflection_count - 1) * (1.0 - reflection_ratio); } // Compute reflected ray dvec3 reflect_direction = reflect(ray.direction, surface_normal); // Add bias to offset ray origin from surface dvec3 bias = reflect_direction * EPSILON; Ray reflected_ray(surface_point.position + bias, reflect_direction); // Recursion (multiplied with the reflection distribution coefficient) dvec3 reflected_light = tracePath(reflected_ray, reflection_count - 1) * reflection_ratio; // Final light return refracted_light + reflected_light; } // Diffuse surface else if (surface_point.material->surface_type == Material::SurfaceType::Diffuse) { // Let the first random number be equal to cos(theta) double cos_theta = _distribution(_generator); // Apply Russian roulette to terminate rays. double phi = (cos_theta * 2.0 * PI) / surface_point.material->reflection_coefficient; if (phi > 2.0 * PI) { return dvec3(0.0); } // Generate and compute a random direction in the hemisphere (note that cos theta is randomly generated) dvec3 sample_direction = hemisphereSampleDirection(cos_theta, surface_point.normal); // Create a ray from the sample direction //dvec3 bias = sample_direction * EPSILON; Ray sample_ray(surface_point.position, sample_direction); // Bidirectional Reflectance Distribution Function dvec3 brdf = surface_point.material->brdf(surface_point.normal, ray.direction, sample_ray.direction); // Recursion for the sample ray // First note: the variable phi contains the same parts given by dividing with pdf, multiplying with cos(theta), // and also division by the reflection coefficient to compensate for the probability of the russian roulette termination. // Second note: the pdf is constant (1.0 / (2.0 * PI)) in this case because all of the random directions share the same probability (equiprobability) dvec3 indirect_light = tracePath(sample_ray, reflection_count - 1) * brdf * phi; // Compute direct light from light source dvec3 direct_light = computeDirectLight(surface_point, brdf, 20); // Combine the direct and indirect light and multiply with surface color return (direct_light + indirect_light); } else { return dvec3(0.0); } } bool Camera::shadowRay(const dvec3& surface_point, const dvec3& point_to_light, const double& light_distance) { // Define a ray pointing towards the light source Ray light_ray(surface_point, point_to_light); // Only check shadow ray on the tetrahedron (last item in the triangle_objects array) auto tetrahedron = _scene->triangle_objects.back(); for (Triangle triangle : tetrahedron->triangles) { double t, u, v = -1.0; bool intersection_found = triangle.rayIntersection(light_ray, t, u, v); // Shadow if (intersection_found && t < light_distance && (tetrahedron->material->surface_type != Material::SurfaceType::Transparent)) { return true; } } for (Sphere* sphere : _scene->spheres) { double d_near, d_far = -1.0; bool intersection_found = sphere->rayIntersection(light_ray, d_near, d_far); // Shadow if (intersection_found && (d_near < light_distance) && (sphere->material->surface_type != Material::SurfaceType::Transparent)) { return true; } } // No shadow return false; } dvec3 Camera::computeDirectLight(const IntersectionPoint& surface_point, const dvec3& brdf, const size_t sample_ray_count) { dvec3 total_light(0.0); // Sum the direct light from all light sources for (auto light_source : _scene->light_sources) { dvec3 direct_light(0.0); std::vector<dvec3> light_sample_points; // Generate sample points on the area light for (size_t i = 0; i < sample_ray_count; i++) { light_sample_points.push_back(light_source->generateRandomSamplePoint()); } // Cast a shadow ray for each sample point for (auto sample_point : light_sample_points) { dvec3 point_to_light_direction = normalize(sample_point - surface_point.position); double point_to_light_distance = distance(sample_point, surface_point.position); if (!shadowRay(surface_point.position, point_to_light_direction, point_to_light_distance)) { double cos_theta_out = max(dot(surface_point.normal, point_to_light_direction), 0.0); double cos_theta_in = dot(-point_to_light_direction, light_source->triangle.normal); direct_light += brdf * cos_theta_out * cos_theta_in / (point_to_light_distance * point_to_light_distance); } } // Average the light direct_light *= (light_source->material->color * light_source->intensity / (double)sample_ray_count); total_light += direct_light; } return total_light; } void Camera::createLocalCoordinateSystem(const dvec3& normal, dvec3& local_x_axis, dvec3& local_z_axis) { // If the normals y-coordinate is smaller than the x-coordinate, next axis should lie in the y-plane (y = 0) if (abs(normal.x) > abs(normal.y)) { local_x_axis = dvec3(normal.z, 0.0, -normal.x) / sqrt(normal.x * normal.x + normal.z * normal.z); } else { local_x_axis = dvec3(0.0, -normal.z, normal.y) / sqrt(normal.y * normal.y + normal.z * normal.z); } local_z_axis = cross(normal, local_x_axis); } dvec3 Camera::hemisphereSampleDirection(const double &cos_theta, const dvec3& surface_normal) { // Theta is the inclination angle double sin_theta = sqrt(1 - cos_theta * cos_theta); // Phi is the azimuth angle double phi = 2 * PI * _distribution(_generator); // Second random number double x = sin_theta * cos(phi); double z = sin_theta * sin(phi); // We assume that the first random value is cos(theta), which is equal to the y-coordiante dvec3 sample_direction_local(x, cos_theta, z); // Create a local coordinate system for the hemisphere of the intersection point with the surface normal as the y-axis dvec3 local_x_axis(0.0); dvec3 local_z_axis(0.0); createLocalCoordinateSystem(surface_normal, local_x_axis, local_z_axis); // Transform direction from local to world by multiplying with the local coordinate system matrix // Note that we only transform the direction so the translation part is not needed (in that case we would use a 4x4 matrix) return dvec3( sample_direction_local.x * local_z_axis.x + sample_direction_local.y * surface_normal.x + sample_direction_local.z * local_x_axis.x, sample_direction_local.x * local_z_axis.y + sample_direction_local.y * surface_normal.y + sample_direction_local.z * local_x_axis.y, sample_direction_local.x * local_z_axis.z + sample_direction_local.y * surface_normal.z + sample_direction_local.z * local_x_axis.z ); } bool Camera::geometryIntersectionTest(const Ray& ray, IntersectionPoint& surface_point) { // Test the ray against all triangle objects triangleIntersectionTests(ray, surface_point); // Test the ray against the sphere sphereIntersectionTests(ray, surface_point); // If distance is negative, no intersection was found in the ray direction return !(surface_point.distance < 0.0); } void Camera::triangleIntersectionTests(const Ray& ray, IntersectionPoint& closest_point) { // Check triangle objects for (TriangleObject* object : _scene->triangle_objects) { for (Triangle triangle : object->triangles) { double t, u, v = -1.0; if (triangle.rayIntersection(ray, t, u, v) == true) { // Depth test (if we have multiple intersections, save the closest) if (closest_point.distance < 0.0 || closest_point.distance > t) { // Save closest distance closest_point.distance = t; // Compute world coordinates from barycentric triangle coordinates closest_point.position = barycentricToWorldCoordinates(triangle, u, v); closest_point.normal = triangle.normal; closest_point.material = object->material; } } } } // Area Light Source for (auto light_source : _scene->light_sources) { double t, u, v = -1.0; if (light_source->triangle.rayIntersection(ray, t, u, v) == true) { // Depth test (if we have multiple intersections, save the closest) if (closest_point.distance < 0.0 || closest_point.distance > t) { // Save closest distance closest_point.distance = t; // Compute world coordinates from barycentric triangle coordinates closest_point.position = barycentricToWorldCoordinates(light_source->triangle, u, v); closest_point.normal = light_source->triangle.normal; closest_point.material = light_source->material; } } } } void Camera::sphereIntersectionTests(const Ray& ray, IntersectionPoint& closest_point) { for (Sphere* sphere : _scene->spheres) { double d_near, d_far = -1.0; if (sphere->rayIntersection(ray, d_near, d_far) == true) { // Depth test (if we have multiple intersections, save the closest) if (closest_point.distance < 0.0 || closest_point.distance > d_near) { // Save closest distance closest_point.distance = d_near; // Compute the intersection point world coordinate position closest_point.position = ray.start_point + dvec3(d_near) * ray.direction; // Set attributes closest_point.normal = normalize(closest_point.position - sphere->center); closest_point.material = sphere->material; } } } } void Camera::setupCameraMatrix() { // Perspective projection matrix double projection_matrix[16] = { 0 }; double aspect_ratio = (double)_camera_film.width / (double)_camera_film.height; double fov = 75.0 * pi<double>() / 180.0; // 75 degrees for the field of view Transform::perspective(projection_matrix, fov, aspect_ratio, 1.0, 1000.0); // Camera view transform Transform camera_view; camera_view.setPosition(_eye_point.x, _eye_point.y, _eye_point.z); camera_view.setRotation(0.0, 90.0, -90.0); // Invert the view matrix since it's a camera view Transform::invertMatrix(camera_view.matrix, camera_view.matrix); // Combine perspective projection and camera view double combined_matrix[16] = { 0.0 }; // Combine the transform matrix for perspective and camera view Transform::multiply(projection_matrix, camera_view.matrix, combined_matrix); // Invert the transform matrix since we are reversing the process (from normalized device coordinates to world coordinates) Transform::invertMatrix(combined_matrix, combined_matrix); // Final transform that can be used to convert pixel coordinates to world coordinates _transform_matrix = make_mat4(combined_matrix); } void Camera::computePixelWidth() { dvec2 p_1 = normalizedPixelCoord(0, 0); dvec2 p_2 = normalizedPixelCoord(1, 0); _pixel_width = glm::distance(dvec3(_transform_matrix * vec4(p_1.x, p_1.y, 1.0, 1.0)), dvec3(_transform_matrix * vec4(p_2.x, p_2.y, 1.0, 1.0))); } inline dvec3 Camera::barycentricToWorldCoordinates(const Triangle& triangle, const double& u, const double& v) { dvec3 u_vec(u); dvec3 v_vec(v); dvec3 one_vec(1.0); return ((one_vec - u_vec - v_vec) * triangle.vertices[0]) + (u_vec * triangle.vertices[1]) + (v_vec * triangle.vertices[2]); } inline dvec2 Camera::normalizedPixelCoord(const int& x, const int& y) { return dvec2(1.0 - (x / (_camera_film.width * 0.5)), (y / (_camera_film.height * 0.5)) - 1.0); } inline double Camera::fresnelsEquation(const double& n_1, const double& n_2, const double& cos_theta1) { // Compute sin_theta2 using Snell's law double sin_theta2 = n_1 / n_2 * sqrt(max(0.0, 1.0 - cos_theta1 * cos_theta1)); // If larger or equal to one, we have total reflection (internal reflection inside a thicker medium compared to outside) if (sin_theta2 >= 1.0) { return 1.0; } // Compute cos_theta2 (derived from cos_theta^2 + sin_theta^2 = 1) double cos_theta2 = sqrt(max(0.0, 1.0 - sin_theta2 * sin_theta2)); // Calculate the square roots of the Fresnel equations double Rs_sqroot = ((n_1 * cos_theta1) - (n_2 * cos_theta2)) / ((n_1 * cos_theta1) + (n_2 * cos_theta2)); double Rp_sqroot = ((n_2 * cos_theta1) - (n_1 * cos_theta2)) / ((n_2 * cos_theta1) + (n_1 * cos_theta2)); // The reflection ratio is given by the average of the two equations return (Rs_sqroot * Rs_sqroot + Rp_sqroot * Rp_sqroot) * 0.5; }
Java
UTF-8
952
3.03125
3
[]
no_license
package cz.cvut.cizpelant.engine.commands; import cz.cvut.cizpelant.engine.abstraction.GameCommand; import cz.cvut.cizpelant.engine.abstraction.GameCommandResult; import cz.cvut.cizpelant.engine.model.Game; public class HelpCommand implements GameCommand { private String helpMessage; public HelpCommand() { StringBuilder sb = new StringBuilder(); sb.append("Available commands:\n"); sb.append("move [room name] - Move to another specified room.\n"); sb.append("pick [item name] - Pick item with specified name in current room.\n"); sb.append("drop [item name] - Drop item with specified name in current room.\n"); sb.append("use [item name] - Use item with specified name.\n"); sb.append("help - Show this help.\n"); sb.append("exit - Exits the game.\n"); this.helpMessage = sb.toString(); } @Override public GameCommandResult Execute(Game game) { return GameCommandResult.UnsuccessfulResult(helpMessage); } }
Java
UTF-8
16,976
1.734375
2
[]
no_license
package com.bluewhite.product.product.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.persistence.criteria.Predicate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.bluewhite.base.BaseServiceImpl; import com.bluewhite.basedata.dao.BaseDataDao; import com.bluewhite.basedata.entity.BaseData; import com.bluewhite.common.Constants; import com.bluewhite.common.SessionManager; import com.bluewhite.common.entity.CurrentUser; import com.bluewhite.common.entity.PageParameter; import com.bluewhite.common.entity.PageResult; import com.bluewhite.common.utils.NumUtils; import com.bluewhite.common.utils.StringUtil; import com.bluewhite.ledger.entity.PutStorage; import com.bluewhite.ledger.service.PutStorageService; import com.bluewhite.product.primecost.cutparts.dao.CutPartsDao; import com.bluewhite.product.primecost.cutparts.entity.CutParts; import com.bluewhite.product.primecost.embroidery.dao.EmbroideryDao; import com.bluewhite.product.primecost.embroidery.entity.Embroidery; import com.bluewhite.product.primecost.machinist.dao.MachinistDao; import com.bluewhite.product.primecost.machinist.entity.Machinist; import com.bluewhite.product.primecost.materials.dao.ProductMaterialsDao; import com.bluewhite.product.primecost.materials.entity.ProductMaterials; import com.bluewhite.product.primecost.needlework.dao.NeedleworkDao; import com.bluewhite.product.primecost.needlework.entity.Needlework; import com.bluewhite.product.primecost.pack.dao.PackDao; import com.bluewhite.product.primecost.pack.entity.Pack; import com.bluewhite.product.primecost.primecost.dao.PrimeCostDao; import com.bluewhite.product.primecost.primecost.entity.PrimeCost; import com.bluewhite.product.primecost.tailor.dao.TailorDao; import com.bluewhite.product.primecost.tailor.entity.Tailor; import com.bluewhite.product.product.dao.ProductDao; import com.bluewhite.product.product.entity.Product; import com.bluewhite.production.procedure.dao.ProcedureDao; import com.bluewhite.production.procedure.entity.Procedure; @Service public class ProductServiceImpl extends BaseServiceImpl<Product, Long> implements ProductService { @Autowired private ProductDao productDao; @Autowired private ProcedureDao procedureDao; @Autowired private PrimeCostDao primeCostDao; @Autowired private CutPartsDao cutPartsDao; @Autowired private ProductMaterialsDao productMaterialsDao; @Autowired private TailorDao tailorDao; @Autowired private MachinistDao machinistDao; @Autowired private EmbroideryDao embroideryDao; @Autowired private NeedleworkDao needleworkDao; @Autowired private PackDao packDao; @Autowired private BaseDataDao baseDataDao; @Autowired private PutStorageService putStorageService; @Override public PageResult<Product> findPages(Product param, PageParameter page) { CurrentUser cu = SessionManager.getUserSession(); // 试制部 if (cu.getRole().contains(Constants.TRIALPRODUCT)) { param.setOriginDepartment(Constants.TRIALPRODUCT); } // 质检 if (cu.getRole().contains(Constants.PRODUCT_FRIST_QUALITY)) { param.setOriginDepartment(Constants.PRODUCT_FRIST_QUALITY); } // 包装 if (cu.getRole().contains(Constants.PRODUCT_FRIST_PACK) || cu.getRole().contains("packScene") || cu.getRole().contains("stickBagAccount") || cu.getRole().contains("stickBagStick")) { param.setOriginDepartment(Constants.PRODUCT_FRIST_PACK); } // 针工 if (cu.getRole().contains(Constants.PRODUCT_TWO_DEEDLE)) { param.setOriginDepartment(Constants.PRODUCT_TWO_DEEDLE); } // 机工 if (cu.getRole().contains(Constants.PRODUCT_TWO_MACHINIST)) { param.setOriginDepartment(Constants.PRODUCT_TWO_MACHINIST); } // 裁剪 if (cu.getRole().contains(Constants.PRODUCT_RIGHT_TAILOR)) { param.setOriginDepartment(Constants.PRODUCT_RIGHT_TAILOR); } Page<Product> pages = productDao.findAll((root, query, cb) -> { List<Predicate> predicate = new ArrayList<>(); // 按id过滤 if (param.getId() != null) { predicate.add(cb.equal(root.get("id").as(Long.class), param.getId())); } // 按部门展示出共同的产品 和 自身部门添加的产品 // 按编号过滤 if (!StringUtils.isEmpty(param.getOriginDepartment())) { Predicate p1 = cb.isNotNull(root.get("number").as(String.class)); Predicate p2 = cb.equal(root.get("originDepartment").as(String.class), param.getOriginDepartment()); predicate.add(cb.or(p1, p2)); } else { predicate.add(cb.isNotNull(root.get("number").as(String.class))); } // 按部门产品编号过滤 if (!StringUtils.isEmpty(param.getDepartmentNumber())) { predicate.add(cb.equal(root.get("departmentNumber").as(String.class), param.getDepartmentNumber())); } // 按编号过滤 if (!StringUtils.isEmpty(param.getNumber())) { predicate.add(cb.equal(root.get("number").as(String.class), param.getNumber())); } // 按产品名称过滤 if (!StringUtils.isEmpty(param.getName())) { predicate.add(cb.like(root.get("name").as(String.class), "%" + StringUtil.specialStrKeyword(param.getName()) + "%")); } Predicate[] pre = new Predicate[predicate.size()]; query.where(predicate.toArray(pre)); return null; }, page); // 展示外发单价和当部门预计生产单价,针工价格 if (param.getOriginDepartment() != null) { for (Product pro : pages.getContent()) { List<Procedure> procedureList = procedureDao.findByProductIdAndTypeAndFlag(pro.getId(), param.getType(), 0); if (procedureList != null && procedureList.size() > 0) { if (param.getType() != null && param.getType() == 5) { List<Procedure> procedureList1 = procedureList.stream() .filter(Procedure -> Procedure.getSign() == 0).collect(Collectors.toList()); if (procedureList1.size() > 0) { pro.setHairPrice(procedureList1.get(0).getHairPrice()); pro.setDepartmentPrice(procedureList1.get(0).getDepartmentPrice()); } List<Procedure> procedureList2 = procedureList.stream() .filter(Procedure -> Procedure.getSign() == 1).collect(Collectors.toList()); if (procedureList2.size() > 0) { pro.setPuncherHairPrice(procedureList2.get(0).getHairPrice()); pro.setPuncherDepartmentPrice(procedureList2.get(0).getDepartmentPrice()); } } else { if (procedureList.size() > 0) { pro.setHairPrice(procedureList.get(0).getHairPrice()); pro.setDepartmentPrice(procedureList.get(0).getDepartmentPrice()); } } if (param.getType() == 3) { pro.setDeedlePrice(procedureList.get(0).getDeedlePrice()); } } } } PageResult<Product> result = new PageResult<>(pages, page); return result; } @Override public PrimeCost getPrimeCost(PrimeCost primeCost) { // 自动将类型为null的属性赋值为0 NumUtils.setzro(primeCost); // 面料价格(含复合物料和加工费) List<CutParts> cutPartsList = cutPartsDao.findByProductId(primeCost.getProductId()); double batchMaterialPrice = cutPartsList.stream().filter(CutParts -> CutParts.getBatchMaterialPrice() != null) .mapToDouble(CutParts::getBatchMaterialPrice).sum(); double batchComplexMaterialPrice = cutPartsList.stream() .filter(CutParts -> CutParts.getBatchComplexMaterialPrice() != null) .mapToDouble(CutParts::getBatchComplexMaterialPrice).sum(); double batchComplexAddPrice = cutPartsList.stream() .filter(CutParts -> CutParts.getBatchComplexAddPrice() != null) .mapToDouble(CutParts::getBatchComplexAddPrice).sum(); primeCost.setCutPartsPrice(batchMaterialPrice + batchComplexMaterialPrice + batchComplexAddPrice); // 单只 primeCost.setOneCutPartsPrice(NumUtils.division(primeCost.getCutPartsPrice() / primeCost.getNumber())); double cutPartsPriceInvoice = primeCost.getCutPartsInvoice() == 1 ? (primeCost.getCutPartsPriceInvoice() * primeCost.getOneCutPartsPrice()) : 0; // 除面料以外的其他物料价格 List<ProductMaterials> productMaterialsList = productMaterialsDao.findByProductId(primeCost.getProductId()); double batchMaterialPrice1 = productMaterialsList.stream() .filter(ProductMaterials -> ProductMaterials.getBatchMaterialPrice() != null) .mapToDouble(ProductMaterials::getBatchMaterialPrice).sum(); primeCost.setOtherCutPartsPrice(batchMaterialPrice1); primeCost.setOneOtherCutPartsPrice(NumUtils.division((batchMaterialPrice1) / primeCost.getNumber())); double otherCutPartsPriceInvoice = primeCost.getOtherCutPartsPriceInvoice() == 1 ? (primeCost.getOtherCutPartsPriceInvoice() * primeCost.getOneOtherCutPartsPrice()) : 0; // 裁剪 List<Tailor> tailorList = tailorDao.findByProductId(primeCost.getProductId()); double allCostPriceTailor = tailorList.stream().filter(Tailor -> Tailor.getAllCostPrice() != null) .mapToDouble(Tailor::getAllCostPrice).sum(); primeCost.setCutPrice(allCostPriceTailor); primeCost.setOneCutPrice(NumUtils.division((allCostPriceTailor) / primeCost.getNumber())); double cutPriceInvoice = primeCost.getCutPriceInvoice() == 1 ? (primeCost.getCutPriceInvoice() * primeCost.getOneCutPrice()) : 0; // 机工 List<Machinist> machinistList = machinistDao.findByProductId(primeCost.getProductId()); double allCostPriceMachinist = machinistList.stream().filter(Machinist -> Machinist.getAllCostPrice() != null) .mapToDouble(Machinist::getAllCostPrice).sum(); primeCost.setMachinistPrice(allCostPriceMachinist); primeCost.setOneMachinistPrice(NumUtils.division((allCostPriceMachinist) / primeCost.getNumber())); double machinistPriceInvoice = primeCost.getMachinistPriceInvoice() == 1 ? (primeCost.getMachinistPriceInvoice() * primeCost.getOneMachinistPrice()) : 0; // 绣花 List<Embroidery> embroideryList = embroideryDao.findByProductId(primeCost.getProductId()); double allCostPriceEmbroidery = embroideryList.stream() .filter(Embroidery -> Embroidery.getAllCostPrice() != null).mapToDouble(Embroidery::getAllCostPrice) .sum(); primeCost.setEmbroiderPrice(allCostPriceEmbroidery); primeCost.setOneEmbroiderPrice(NumUtils.division((allCostPriceEmbroidery) / primeCost.getNumber())); double embroiderPriceInvoice = primeCost.getEmbroiderPriceInvoice() == 1 ? (primeCost.getEmbroiderPriceInvoice() * primeCost.getOneEmbroiderPrice()) : 0; // 针工 List<Needlework> needleworkList = needleworkDao.findByProductId(primeCost.getProductId()); double allCostPriceNeedlework = needleworkList.stream() .filter(Needlework -> Needlework.getAllCostPrice() != null).mapToDouble(Needlework::getAllCostPrice) .sum(); primeCost.setNeedleworkPrice(allCostPriceNeedlework); primeCost.setOneNeedleworkPrice(NumUtils.division((allCostPriceNeedlework) / primeCost.getNumber())); double needleworkPriceInvoice = primeCost.getNeedleworkPriceInvoice() == 1 ? (primeCost.getNeedleworkPriceInvoice() * primeCost.getOneNeedleworkPrice()) : 0; // 包装 List<Pack> packList = packDao.findByProductId(primeCost.getProductId()); double allCostPricePack = packList.stream().filter(Pack -> Pack.getAllCostPrice() != null) .mapToDouble(Pack::getAllCostPrice).sum(); primeCost.setPackPrice(allCostPricePack); primeCost.setOnePackPrice(NumUtils.division((allCostPricePack) / primeCost.getNumber())); double packPriceInvoice = primeCost.getPackPriceInvoice() == 1 ? (primeCost.getPackPriceInvoice() * primeCost.getOnePackPrice()) : 0; // 批成本 primeCost.setBacthPrimeCost(primeCost.getCutPartsPrice() + primeCost.getOtherCutPartsPrice() + primeCost.getCutPrice() + primeCost.getMachinistPrice() + primeCost.getEmbroiderPrice() + primeCost.getNeedleworkPrice() + primeCost.getPackPrice()); // 单只成本 primeCost.setOnePrimeCost(NumUtils.division(primeCost.getBacthPrimeCost() / primeCost.getNumber())); // 实战单只成本 primeCost.setOneaAtualPrimeCost(primeCost.getCutPartsPricePricing() + primeCost.getCutPricePricing() + primeCost.getEmbroiderPricePricing() + primeCost.getMachinistPricePricing() + primeCost.getEmbroiderPricePricing() + primeCost.getPackPricePricing() + primeCost.getFreightPricePricing()); // 预计运费价 primeCost.setFreightPrice(primeCost.getAdjustNumber() * primeCost.getOneFreightPrice()); // 付上游开票点() primeCost.setUpstream(cutPartsPriceInvoice + otherCutPartsPriceInvoice + cutPriceInvoice + machinistPriceInvoice + embroiderPriceInvoice + needleworkPriceInvoice + packPriceInvoice); // 付国家的 primeCost.setState(NumUtils.division(primeCost.getInvoice() == 1 ? primeCost.getState() / 1.17 * 0.17 - (primeCost.getOneCutPartsPrice() + primeCost.getOneOtherCutPartsPrice() + primeCost.getOneCutPrice() + primeCost.getOneMachinistPrice() + primeCost.getOneEmbroiderPrice() + primeCost.getOnePackPrice() + primeCost.getOneNeedleworkPrice() + primeCost.getOnePrimeCost()) : 0.0)); // 预计多付国家的 primeCost.setExpectState(primeCost.getInvoice() == 1 ? primeCost.getState() - (primeCost.getSale() * primeCost.getTaxes()) : 0.0); // 考虑多付国家的不付需要的进项票点 primeCost.setNoState( NumUtils.division(primeCost.getInvoice() == 1 ? primeCost.getState() / 0.17 * 1.17 * 0.08 : 0.0)); // 付返点和版权点 primeCost.setRecidivate( (primeCost.getSale() * primeCost.getRebateRate()) + (primeCost.getSale() * primeCost.getRebateRate())); // 付运费 primeCost.setFreight(primeCost.getFreightPrice()); // 剩余到手的 primeCost.setSurplus(primeCost.getSale() - primeCost.getState() - primeCost.getUpstream() - primeCost.getRecidivate() - primeCost.getFreight() - primeCost.getNoState()); // 实际加价率 primeCost.setMakeRate(NumUtils.division(primeCost.getSurplus() / primeCost.getOnePrimeCost())); // 目前综合税负加所得税负比 primeCost.setTaxesRate( NumUtils.division((primeCost.getState() - primeCost.getExpectState()) / (primeCost.getSale() / 1.17))); // 预算成本 primeCost.setBudget(primeCost.getOnePrimeCost() - primeCost.getFreight()); // 预算成本加价率 primeCost.setBudgetRate(NumUtils.division(primeCost.getSurplus() / primeCost.getBudget())); // 实战成本 primeCost.setActualCombat(primeCost.getOneaAtualPrimeCost() - primeCost.getFreight()); // 实战成本加价率 primeCost.setActualCombatRate(NumUtils.division(primeCost.getSurplus() / primeCost.getActualCombat())); return primeCostDao.save(primeCost); } @Override public List<Product> getAllProduct() { return productDao.findByNumberNotNull(); } @Override public PageResult<Product> inventoryFindPages(Product param, PageParameter page) { Page<Product> pages = productDao.findAll((root, query, cb) -> { List<Predicate> predicate = new ArrayList<>(); // 按id过滤 if (param.getId() != null) { predicate.add(cb.equal(root.get("id").as(Long.class), param.getId())); } // 按部门展示出共同的产品 和 自身部门添加的产品 // 按编号过滤 if (!StringUtils.isEmpty(param.getOriginDepartment())) { Predicate p1 = cb.isNotNull(root.get("number").as(String.class)); Predicate p2 = cb.equal(root.get("originDepartment").as(String.class), param.getOriginDepartment()); predicate.add(cb.or(p1, p2)); } else { predicate.add(cb.isNotNull(root.get("number").as(String.class))); } // 按部门产品编号过滤 if (!StringUtils.isEmpty(param.getDepartmentNumber())) { predicate.add(cb.equal(root.get("departmentNumber").as(String.class), param.getDepartmentNumber())); } // 按编号过滤 if (!StringUtils.isEmpty(param.getNumber())) { predicate.add(cb.equal(root.get("number").as(String.class), param.getNumber())); } // 按产品名称过滤 if (!StringUtils.isEmpty(param.getName())) { predicate.add(cb.like(root.get("name").as(String.class), "%" + StringUtil.specialStrKeyword(param.getName()) + "%")); } Predicate[] pre = new Predicate[predicate.size()]; query.where(predicate.toArray(pre)); return null; }, page); // 获取所有的仓库类型 List<BaseData> baseDataList = baseDataDao.findByParentId(param.getWarehouse()); pages.getContent().forEach(p -> { baseDataList.forEach(b -> { Map<String, Object> map = new HashMap<>(); //获取该产品该仓库的所有入库单 List<PutStorage> putStorageList = putStorageService.detailsInventory(b.getId(),p.getId()); int number = 0; if(putStorageList.size()>0){ number = putStorageList.stream().mapToInt(PutStorage::getSurplusNumber).sum(); } map.put("warehouseTypeId", b.getId()); map.put("number", number); p.getMapList().add(map); }); }); PageResult<Product> result = new PageResult<>(pages, page); return result; } }
Shell
UTF-8
3,794
3.53125
4
[]
no_license
#!/bin/bash # This scrip should set up st terminal emulator if [[ $EUID -ne 0 ]]; then echo -e "\n\x1b[31;01m Run this script with 'sudo -E' \x1b[39;49;00m\n" exit 1 fi if [ $HOME = '/root' ]; then echo -e "\n\x1b[31;01m Run this script with 'sudo -E' \x1b[39;49;00m\n" exit 1 fi if [ -z ${SUDO_USER} ]; then echo -e "\n\x1b[31;01m No \$SUDO_USER available, quiting ... \x1b[39;49;00m\n" exit 1 fi # !!! Font size: # is set in ~/redmoo/setupworkenv/i3wm/config_beakl.conf # with line: # bindsym $mod+Return exec /usr/local/bin/st -f "consolas:size=18:autohint=true:atialias=true" SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" ST_INSTALL_DIR=${HOME}/.local/share/ ST_DIR=${ST_INSTALL_DIR}/st # git clone and install the 'st' terminal emulator if [ ! -d "$ST_DIR" ] || [ "$1" == "reinstall" ]; then apt-get -y install libx11-dev libxft-dev sudo -u ${SUDO_USER} mkdir -p $ST_INSTALL_DIR cd $ST_INSTALL_DIR sudo -u ${SUDO_USER} git clone git://git.suckless.org/st cd "$ST_DIR" # sudo -u ${SUDO_USER} git checkout -b master sudo -u ${SUDO_USER} git checkout 041912a sudo -u ${SUDO_USER} git checkout -b custom # make clean config.h make config.h # ignore files created by 'make' sudo -u ${SUDO_USER} echo -e "st\n*.o" > .gitignore sudo -u ${SUDO_USER} git add --all sudo -u ${SUDO_USER} git commit -m 'Copied config, Added gitignore file' # build patches on a separate branch sudo -u ${SUDO_USER} git checkout master sudo -u ${SUDO_USER} git checkout 041912a sudo -u ${SUDO_USER} git checkout -b patched sudo -u ${SUDO_USER} mkdir -p "$ST_DIR/patches" cd "$ST_DIR/patches" # sudo -u ${SUDO_USER} curl https://st.suckless.org/patches/scrollback/st-scrollback-0.8.diff -O sudo -u ${SUDO_USER} curl https://st.suckless.org/patches/solarized/st-no_bold_colors-0.8.1.diff -O sudo -u ${SUDO_USER} curl https://st.suckless.org/patches/solarized/st-solarized-dark-20180411-041912a.diff -O cd .. # apply 1st patch echo -e "\n\x1b[33;01m Applying 1st patch ... \x1b[39;49;00m\n" && sleep 1 sudo -u ${SUDO_USER} git apply "$ST_DIR/patches/st-no_bold_colors-0.8.1.diff" # echo -e "\n\x1b[33;01m \t running make clean config.h ... \x1b[39;49;00m\n" && sleep 1 make clean config.h # echo -e "\n\x1b[33;01m \t running git add --all ... \x1b[39;49;00m\n" && sleep 1 sudo -u ${SUDO_USER} git add --all # echo -e "\n\x1b[33;01m \t commiting changes ... \x1b[39;49;00m\n" && sleep 1 sudo -u ${SUDO_USER} git commit -m 'patched st-no_bold_colors-0.8.1.diff' # echo -e "\n\x1b[33;01m \t rebasing ... \x1b[39;49;00m\n" && sleep 1 sudo -u ${SUDO_USER} git checkout custom sudo -u ${SUDO_USER} git rebase patched # apply 2nd patch echo -e "\n\x1b[33;01m Applying 2nd patch ... \x1b[39;49;00m\n" && sleep 1 sudo -u ${SUDO_USER} git checkout patched sudo -u ${SUDO_USER} git apply "$ST_DIR/patches/st-solarized-dark-20180411-041912a.diff" rm config.h make clean config.h sudo -u ${SUDO_USER} git add --all sudo -u ${SUDO_USER} git commit -m 'patched st-solarized-dark-20180411-041912a.diff' sudo -u ${SUDO_USER} git checkout custom sudo -u ${SUDO_USER} git rebase patched make clean install echo -e "\n\x1b[32;01m Built patch ... success ... \x1b[39;49;00m\n" else echo -e "\n\x1b[33;01m Dir $ST_INSTALL_DIR already exits, not installing 'st' \x1b[39;49;00m\n" fi # FONTS_SOURCE_DIR="${SCRIPT_DIR}/../fonts" # FONTS_DEST_DIR="${HOME}/.local/share/fonts" # # install fonts # sudo -u ${SUDO_USER} mkdir -p $FONTS_DEST_DIR # sudo -u ${SUDO_USER} cp -a "${FONTS_SOURCE_DIR}/." $FONTS_DEST_DIR # echo -e "\n\x1b[33;01m Copying $FONTS_SOURCE_DIR to $FONTS_DEST_DIR ... \x1b[39;49;00m\n"
Swift
UTF-8
2,074
2.609375
3
[]
no_license
// // ItemViewController.swift // imdbClient // // Created by TONY on 17/05/2019. // Copyright © 2019 TONY. All rights reserved. // import UIKit class ItemView: UIView { var posterImage: UIImageView! var titleLabel: UILabel! var topInfoLabel: UILabel! var ratingLabel: UILabel! var otherInfoLabel: UILabel! let lineSize = 25 var contentHeight: CGFloat! override init(frame: CGRect) { super.init(frame: frame) posterImage = UIImageView(frame: CGRect(x: frame.midX - 120, y: 10, width: 240, height: 360)) posterImage.backgroundColor = .black self.addSubview(posterImage) titleLabel = UILabel(frame: CGRect(x: 10, y: Int(posterImage.frame.maxY + 10), width: Int(frame.width - 20), height: lineSize*3)) titleLabel.textAlignment = .center titleLabel.font = .preferredFont(forTextStyle: .title1) titleLabel.numberOfLines = 2 titleLabel.text = "Title" self.addSubview(titleLabel) topInfoLabel = UILabel(frame: CGRect(x: 10, y: Int(titleLabel.frame.maxY + 10), width: Int(frame.width - 20), height: lineSize*2)) topInfoLabel.numberOfLines = 2 topInfoLabel.text = "Year, Runtime, Genre" self.addSubview(topInfoLabel) ratingLabel = UILabel(frame: CGRect(x: 10, y: Int(topInfoLabel.frame.maxY + 10), width: Int(frame.width - 20), height: lineSize*5)) ratingLabel.numberOfLines = 5 ratingLabel.text = "Ratings" self.addSubview(ratingLabel) otherInfoLabel = UILabel(frame: CGRect(x: 10, y: Int(ratingLabel.frame.maxY - 90), width: Int(frame.width - 20), height: lineSize*20)) otherInfoLabel.numberOfLines = 20 otherInfoLabel.text = "Released, Rated, Plot, Actors, Director, Writer" self.addSubview(otherInfoLabel) contentHeight = otherInfoLabel.frame.maxY + 10 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
Markdown
UTF-8
6,993
3.3125
3
[ "MIT" ]
permissive
--- layout: post title: "Multiple Layouts Made Easy with CSS Grid" category: fpx --- The software we develop at [Revalize](https://www.revalizesoftware.com) serves a wide range of customers from a wide range of industries. Designing for so many different types of users can be daunting&mdash;what works for a group of users from one company won't necessarily work for another. The most challenging problem to solve in our designs is the application's various layout requirements. Thanks to CSS Grid Layout, creating multiple layouts from a single source of markup has been made, dare I say, trivial. > **N.B.**: This post references [CSS Grid > Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout), but > is not intended to be an introductory tutorial to the technology. If you're > new to CSS Grid Layout, consider the following resources before reading this > article: > > - [CSS Tricks guide](https://css-tricks.com/snippets/css/complete-guide-grid/) > - Rachel Andrew's [Grid by Example](https://gridbyexample.com/) > - Jen Simmons' [Learn CSS > Grid](http://jensimmons.com/post/feb-27-2017/learn-css-grid) post {% include toc.md %} ## The old days Let's focus on the dashboard for a fictitious application, **Super App 3000**&reg;. Prior to CSS Grid Layout, you might have reached for **Perfect Grid System**&trade; to handle your layouts. Such a system typically results in markup that looks like this: ```html <main> <div class="row"> <div id="module_1" class="col col-md-4"> <!-- module 1 content --> </div> <div id="module_2" class="col col-md-4"> <!-- module 2 content --> </div> <div id="module_3" class="col col-md-4"> <!-- module 3 content --> </div> </div> </main> ``` Great! With **Perfect Grid System**&trade;, this gives us a layout that displays as a single column on smaller screens, then switches to three columns at our medium breakpoint. Everyone is happy. But then, someone sends in some feedback. Turns out that `#module_1` is way more important to them than `#module_2` or `#module_3`, so they'd like that to be in the middle column, and made larger. Easy enough: ```html <main> <div class="row"> <div id="module_2" class="col col-md-3"> <!-- module 2 content --> </div> <div id="module_1" class="col col-md-6"> <!-- module 1 content --> </div> <div id="module_3" class="col col-md-3"> <!-- module 3 content --> </div> </div> </main> ``` Cool. We addressed the feedback! Except, as would be expected, other users are writing in with their own priorities. Some need `#module_3` in the middle. Some want the original, three column layout back. Still others are asking for even more arrangements. Chaos! **Perfect Grid System**&trade; wasn't really made to handle this. It's time for a different approach. ## The new school CSS Grid Layout is a layout engine baked right into your browser&mdash;no third party dependencies required. Let's revisit our dashboard, but with a couple of important modifications. First, we can remove all **Perfect Grid System**&trade;-specific classes. We also no longer need its wrapper `<div>`, as we can apply our CSS Grid Layout styles directly to the parent `<main>` element. ```html <main class="grid"> <div id="module_1"> <!-- module 1 content --> </div> <div id="module_2"> <!-- module 2 content --> </div> <div id="module_3"> <!-- module 3 content --> </div> </main> ``` With this simplified markup, we can now deploy our CSS Grid Styles. Here's our original three column layout in CSS Grid: ```css .grid { display: grid; grid-column-gap: 1rem; grid-template-columns: repeat(3, 1fr); } ``` Notice that we defined the grid at the top-level `.grid` element, and didn't define any explicit styles for our modules. CSS Grid is pretty smart, and knows to place our three `#module_` elements within the three columns without any further input from us. What about switching `#module_1` and `#module_2` like before? ```css .grid { display: grid; grid-column-gap: 1rem; grid-template-columns: 1fr 2fr 1fr; } #module_1 { order: 2; } #module_2 { order: 1; } #module_3 { order: 3; } ``` We increased the size of the middle column to be twice as large as the other two. We also explicitly defined the `order` of our `#module_`s, which can be used to tell CSS Grid how to visually order the elements without affecting their source order. This is all fine and dandy, but how do we handle the case where multiple users or organizations want their own layout flavor? At Revalize, we tackled this problem with a `data-layout` attribute on the parent grid element, and a simple user account setting to change it. Here's an interactive example (best viewed [directly on CodePen](https://codepen.io/bobbyshowalter/pen/e645405042d329ebbf904ed286c661e8?editors=0100)): {% include embed-codepen.html slug-hash='e645405042d329ebbf904ed286c661e8' default-tabs='css,result' pen-title='bshow multiple layouts with css grid' preview='true' %} First, let's examine the markup. ```html <main class="grid js-grid" data-layout="1"> <div id="module_1"> <span>1</span> </div> <div id="module_2"> <span>2</span> </div> <div id="module_3"> <span>3</span> </div> </main> ``` Just as before, our markup is lean and straightforward, free of any intent-obscuring layout information. And here's the CSS Grid magic that drives the multiple layout examples: ```css @media screen and (min-width: 60rem) { /* parent grid settings */ .grid { display: grid; align-items: start; grid-column-gap: 1rem; } /* layout 1 styles */ .grid[data-layout="1"] { grid-template: min-content / 15rem 1fr 15rem; } /* layout 2 styles */ .grid[data-layout="2"] { grid-template: repeat(2, min-content) / 1fr 15rem; } .grid[data-layout="2"] #module_1 { grid-area: 1 / 1 / 2 / 2; } .grid[data-layout="2"] #module_2 { grid-area: 2 / 1 / 3 / 2; } .grid[data-layout="2"] #module_3 { grid-area: 1 / 2 / 3 / 3; } /* layout 3 styles */ .grid[data-layout="3"] { grid-template: repeat(3, min-content) / 100%; } } ``` Once the screen is larger than our prescribed breakpoint (`60rem`, in this case), we turn on the grid. Then, in just a few lines of CSS and scoped to the various `data-layout` options, we can present our content in multiple layouts without having to touch the markup source. Where possible, we let the browser do the heavy lifting and place the `#module_`s on its own; otherwise, we use the `grid-area` property to explicitly place our `#module_`s. This approach is a marked improvement over the "old" way because it better separates our concerns, and makes further updates more seamless. Now, instead of chasing markup templates or crazy `if / else if / else` statements all over our content, we can capture layout information alongside the rest of our org- or user-specific presentation styles, where it belongs.
Java
UTF-8
1,100
2.125
2
[]
no_license
package com.softnexos.back.rest; import com.softnexos.back.model.Cargos; import com.softnexos.back.service.CargosService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/cargos/") public class CargosRest { @Autowired private CargosService cargosService; @GetMapping public ResponseEntity<List<Cargos>> getAllCargos (){ return ResponseEntity.ok(cargosService.findAll()); } @GetMapping("{id}") public ResponseEntity<?> read(@PathVariable Integer id) { Optional<Cargos> oCargos = cargosService.findById(id); if(!oCargos.isPresent()) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(oCargos); } }
Java
UTF-8
2,732
2.578125
3
[]
no_license
package zztest.view.recyclerview.recyclerview; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import com.turui.yuncheng.R; import java.util.ArrayList; import activity.base.BaseActivity; import view.recyclerview.recyclerview.SimpleDecoration; /** * Created by Zzz on 2017/7/3. */ //相同的adapter,不同的LaqyoutManager public class TestRecyclerviewActivity extends BaseActivity { RecyclerView recycler1,recycler2,recycler3; ArrayList<String> data1,data2,data3; TestAdapter2 adapter2; LinearLayoutManager linearLayoutManager1; GridLayoutManager linearLayoutManager; StaggeredGridLayoutManager linearLayoutManager3; @Override protected void initView() { super.initView(); setContentView(R.layout.test_activity_recyclerview); data1 = new ArrayList<>(); data2 = new ArrayList<>(); data3 = new ArrayList<>(); for(int a=0;a<10;a++){ data1.add("one"+a); } for(int b=0;b<60;b++){ data2.add("two"+b); } for(int c=0;c<10;c++){ data3.add("three"+c); } adapter2 = new TestAdapter2(activity); adapter2.setData(data2); linearLayoutManager1 = new LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false); //表格:不同宽高的item也会保持对齐,同一使用较大的尺度 linearLayoutManager = new GridLayoutManager(context,2,GridLayoutManager.HORIZONTAL,false); //瀑布流:不同宽高的item,会保持自己原有的尺度,这就是跟GridLayoutManager的区别 linearLayoutManager3 = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL); recycler1 = (RecyclerView)findViewById(R.id.recycler1); recycler1.setLayoutManager(linearLayoutManager1); recycler1.addItemDecoration(new SimpleDecoration(context,LinearLayoutManager.VERTICAL)); recycler1.setAdapter(adapter2); recycler2 = (RecyclerView)findViewById(R.id.recycler2); recycler2.setLayoutManager(linearLayoutManager); recycler2.addItemDecoration(new SimpleDecoration(context,SimpleDecoration.HORIZONTAL_LIST)); recycler2.setAdapter(adapter2); recycler3 = (RecyclerView)findViewById(R.id.recycler3); recycler3.setLayoutManager(linearLayoutManager3); recycler3.addItemDecoration(new SimpleDecoration(context,SimpleDecoration.VERTICAL_LIST)); recycler3.setAdapter(adapter2); } @Override protected void control() { super.control(); } }
Java
UTF-8
2,126
2.53125
3
[]
no_license
package kict.edu.my.cheapr; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Space; import android.widget.TextView; import java.util.ArrayList; /** * Created by User on 17/4/2018. */ public class ItemAdapter extends ArrayAdapter { LayoutInflater layoutInflater; String[] values; String key; Context context; public ItemAdapter(@NonNull Context context, int resource, String[] objects, String key) { super(context, resource, objects); Log.e("msg1", "itemadapter"); layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.values = objects; this.context = context; this.key = key; } @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View view = layoutInflater.inflate(R.layout.listview_item, null); TextView tv = (TextView)view.findViewById(R.id.tv); Log.e("msg1", key.isEmpty()?"empty":"not empty"); Log.e("msg1",values[position]); // if(position==0) { // tv.setBackgroundColor(getContext().getResources().getColor(R.color.darker_purple));} // else if(position==1) { // tv.setBackgroundColor(getContext().getResources().getColor(R.color.maroon));} if (!key.isEmpty()) { // tv.setBackgroundColor(getContext().getResources().getColor(R.color.darker_purple)); if(values[position].toLowerCase().contains(key)) { tv.setText(values[position]); } else { view = new Space(context); } } else { tv.setText(values[position]); } return view; } public void setKey(String key){ this.key = key; } public void updateData(String[] strings) { this.values = values; } }
C++
UTF-8
447
3.09375
3
[]
no_license
#ifndef Shape_h #define Shape_h #include <iostream> #include <string> class Shape { public: Shape(const std::string& name) { name_ = name; } virtual void draw() const = 0; //virtual void move() = 0; // add also move() function virtual std::string name() const { return name_; } virtual void print() const { std::cout << "Shape with name " << name_ << std::endl; } virtual ~Shape() {} private: std::string name_; }; #endif
Ruby
UTF-8
1,992
2.859375
3
[ "WTFPL" ]
permissive
require File.join(File.dirname(__FILE__), "..", "test_helper.rb") class AlignerTest < Test::Unit::TestCase class TestClass attr_accessor :cells include Aligner end def setup Petri.stubs(:image_dimensions).returns(Point.new(640, 480)) Petri.stubs(:num_genes).returns(3) Petri.stubs(:num_points).returns(3) @test_class = TestClass.new end def test_true assert true end def test_align_crossover_for @test_class.cells = [ Cell.new do gene_0 &three_points_at(0, 0) gene_1 &three_points_at(10, 0) gene_2 &three_points_at(20, 0) end, Cell.new do gene_0 &three_points_at(10, 0) gene_1 &three_points_at(20, 0) gene_2 &three_points_at(30, 0) end ] optimal_alignment = @test_class.align_crossover assert_equal [0, 1, 2], optimal_alignment[:cell_1] assert_equal [1, 0, 2], optimal_alignment[:cell_2] end def test_crossover_map Petri.stubs(:num_genes).returns(2) @test_class.cells = [ Cell.new do gene_0 &three_points_at(0, 0) gene_1 &three_points_at(15, 0) end, Cell.new do gene_0 &three_points_at(10, 0) gene_1 &three_points_at(22.5, 0) end ] assert_equal [[10, 22.5], [5, 7.5]], @test_class.send(:crossover_map) end def test_middle_point_of Petri.stubs(:num_points).returns(4) gene = Gene.new do point_0 0, 0 point_1 30, 0 point_2 0, 15 point_3 30, 15 end middle_point = @test_class.send(:middle_point_of, gene) assert_equal 15, middle_point.x assert_equal 7.5, middle_point.y end def test_distance_between point_1 = Point.new(0, 0) point_2 = Point.new(3, 4) assert_equal 5, @test_class.send(:distance_between, point_1, point_2) end protected def three_points_at(x, y) lambda do point_0 x, y point_1 x, y point_2 x, y end end end
C
UTF-8
8,015
2.734375
3
[]
no_license
/* * main.c * * Created on: Jan 15, 2020 * Author: micheal_onsy */ #include "E2PROM.h" #include "UART.h" #include "Timer1.h" #define M2_READY 0x10 /*Prototype*/ void APP_VidTIMER(void); /*global variable */ uint8 g_flag=0; uint8 g_flag1=0; int main (void) { /* * Local Variables used In Project * 1- Counter To Count In Loop * 2- Count To Count Data From Array * 3-Receive Data From Uart * 4-Arrays To Save Data * */ uint8 LOC_u8Counter=0 ; uint8 LOC_u8ToCountData=0 ; uint8 LOC_U8Flag=0; uint8 LOC_u8BuzzerFlag=0; uint8 Receive_Data_From_Uart; uint8 First_Buffer_From_Uart [5]; uint8 Second_Buffer_From_Uart [5]; uint8 Third_Buffer_From_Uart[8]; /***************************Configuration*********************************/ SET_BIT(DDRB,PB7); /*Timer*/ TIM1_Config Config={CTC,F_CLK_1024,OC1A_OFF}; TIMER1_VidInit(&Config ,0,62500); TIMER1_CTC_SetCallBack(APP_VidTIMER); DDRA|=(1<<PA0)|(1<<PA1); /*LCD*/ // LCD_VidInit(); /*E2prom*/ E2PROM_VidInit(); /*UART*/ UART_Config config={UART_2StopBit,UART_8Bit,UART_AsyncDouble,UART_Disable}; UART_VidInit(&config,9600); /*Send Data To MC1 To Know i am Ready To Work */ UART_VidSend(M2_READY); while(1) { /* * 1-Receive Data From UART * 2-Write Data In EEPROM * 3-Save Data In Array * */ while(LOC_U8Flag==0) { LOC_U8Flag=1; for(LOC_u8Counter=0;LOC_u8Counter<5;LOC_u8Counter++) { Receive_Data_From_Uart =UART_u8Recive();//1LOOP E2PROM_VidWrite((0x0211 & 0x0210)|(LOC_u8Counter+1), Receive_Data_From_Uart); First_Buffer_From_Uart[LOC_u8Counter]=Receive_Data_From_Uart; _delay_ms(20); } } /* * 1-Receive Data From UART * 2-Save Data In Array * */ while(LOC_U8Flag==1) { LOC_U8Flag=2; for(LOC_u8Counter=0; LOC_u8Counter<5;LOC_u8Counter++) { Receive_Data_From_Uart=UART_u8Recive();//2 LOOP Second_Buffer_From_Uart[LOC_u8Counter]=Receive_Data_From_Uart; } } /* * 1-Check Data * 2-if True Send 25 By UART * 3-Else False send 10 By UART * 4-Receive Data From UART * 5-if true Go Next Step * 6-else False Return To Enter Password * */ while(LOC_U8Flag==2) { for(LOC_u8Counter=0 ;LOC_u8Counter<5;LOC_u8Counter++) { if(First_Buffer_From_Uart[LOC_u8Counter]==Second_Buffer_From_Uart[LOC_u8Counter]) LOC_u8ToCountData+=5; else LOC_u8ToCountData+=20; } if(LOC_u8ToCountData==25) { UART_VidSend(25);//3 LOC_u8ToCountData=0; } else if(LOC_u8ToCountData!=25) { UART_VidSend(10);//3 LOC_u8ToCountData=0; } Receive_Data_From_Uart=UART_u8Recive();//4 if(Receive_Data_From_Uart==1) LOC_U8Flag=3; else LOC_U8Flag=0; } /* * 1-Receive Data From UART * 2-if Enter '*' * 3-else Enter '#' */ while(LOC_U8Flag==3) { Receive_Data_From_Uart=UART_u8Recive();//5 if(Receive_Data_From_Uart=='*') { /* * 1-Receive Data From UART * 2-Save Data In Array * */ for(LOC_u8Counter=0;LOC_u8Counter<5;LOC_u8Counter++) { Receive_Data_From_Uart=UART_u8Recive();//6LOOP Second_Buffer_From_Uart[LOC_u8Counter]=Receive_Data_From_Uart; } /* * 1-Check Data By Two Array * 2-If Array Equal Send 25 * 3-Else Array Equal Send 10 * 4-Receive Data From UARt * 5-if True Go Next Step * 6-Else False repeat * */ for(LOC_u8Counter=0 ;LOC_u8Counter<5;LOC_u8Counter++) { if(First_Buffer_From_Uart[LOC_u8Counter]==Second_Buffer_From_Uart[LOC_u8Counter]) LOC_u8ToCountData+=5; else LOC_u8ToCountData+=20; } if(LOC_u8ToCountData==25) { UART_VidSend(25);//7 LOC_u8ToCountData=0; } else if(LOC_u8ToCountData!=25) { UART_VidSend(10);//7 LOC_u8ToCountData=0; } Receive_Data_From_Uart=UART_u8Recive();//8 if(Receive_Data_From_Uart==1) LOC_U8Flag=4; else LOC_U8Flag=3; } else if (Receive_Data_From_Uart=='#') { /* * 1-Receive Data From Uart * 2-Save Data In Array * */ for(LOC_u8Counter=0;LOC_u8Counter<5;LOC_u8Counter++) { Receive_Data_From_Uart=UART_u8Recive();//10LOOP Third_Buffer_From_Uart[LOC_u8Counter]=Receive_Data_From_Uart; } /* * 1-Check Data By Two Array * 2-If Array Equal Send 25 * 3-Else Array Equal Send 10 * 4-Receive Data From UARt * 5-if True Go Next Step * 6-Else False repeat And When the counter is to 3 make the alarm * */ for(LOC_u8Counter=0 ;LOC_u8Counter<5;LOC_u8Counter++) { if(First_Buffer_From_Uart[LOC_u8Counter]==Third_Buffer_From_Uart[LOC_u8Counter]) LOC_u8ToCountData+=5; else LOC_u8ToCountData+=20; } if(LOC_u8ToCountData==25) { UART_VidSend(25);//11 LOC_u8ToCountData=0; } else if(LOC_u8ToCountData!=25) { UART_VidSend(10);//11 LOC_u8ToCountData=0; } Receive_Data_From_Uart=UART_u8Recive();//12 if(Receive_Data_From_Uart==1) { LOC_U8Flag=5; LOC_u8BuzzerFlag=0; } else { LOC_U8Flag=3; LOC_u8BuzzerFlag++; } if(LOC_u8BuzzerFlag==3) { SET_BIT(PORTB,PB7); for(LOC_u8Counter=1;LOC_u8Counter<=10;LOC_u8Counter++) _delay_ms(6000); LOC_u8BuzzerFlag=0; CLEAR_BIT(PORTB,PB7); } } } /******************Start Timer***************B*********************/ /*1-Clear TCNT1 In Beginning *2-Clear g_flag In Beginning *3-Set I_Bit *4-In While Check Time IS Finish Or Not IF Finish Clear The Flags And I_Bit * */ while(LOC_U8Flag==4) { TCNT1=0; SET_BIT(PORTA,PA0); CLEAR_BIT(PORTA,PA1); g_flag=0; sei(); while(g_flag1==0) { } LOC_U8Flag=3; g_flag1=0; CLEAR_BIT(SREG,7); } /* * 1-Receive Data From UART * 2-Save Data In Array * */ while(LOC_U8Flag==5) { LOC_U8Flag=6; while(LOC_U8Flag==6) { LOC_U8Flag=7; for(LOC_u8Counter=0;LOC_u8Counter<5;LOC_u8Counter++) { Receive_Data_From_Uart =UART_u8Recive();//13LOOP Third_Buffer_From_Uart[LOC_u8Counter]=Receive_Data_From_Uart; _delay_ms(20); } } /* * 1-Receive Data From UART * 2-Save Data In Array * */ while(LOC_U8Flag==7) { LOC_U8Flag=2; for(LOC_u8Counter=0; LOC_u8Counter<5;LOC_u8Counter++) { Receive_Data_From_Uart=UART_u8Recive();//14 LOOP Second_Buffer_From_Uart[LOC_u8Counter]=Receive_Data_From_Uart; } } /* * 1-Check Data * 2-if True Send 25 By UART And Save Data In EEPROM * 3-Else False send 10 By UART * 4-Receive Data From UART * 5-if true Go Next Step * 6-else False Return To Enter Password * */ while(LOC_U8Flag==2) { for(LOC_u8Counter=0 ;LOC_u8Counter<5;LOC_u8Counter++) { if(Third_Buffer_From_Uart[LOC_u8Counter]==Second_Buffer_From_Uart[LOC_u8Counter]) LOC_u8ToCountData+=5; else LOC_u8ToCountData+=20; } if(LOC_u8ToCountData==25) { UART_VidSend(25);//15 LOC_u8ToCountData=0; for(LOC_u8Counter=0;LOC_u8Counter<5;LOC_u8Counter++) { Receive_Data_From_Uart=Third_Buffer_From_Uart[LOC_u8Counter]; E2PROM_VidWrite((0x0211 & 0x0210)|(LOC_u8Counter+1), Receive_Data_From_Uart); First_Buffer_From_Uart[LOC_u8Counter]=Receive_Data_From_Uart; _delay_ms(20); } } else if(LOC_u8ToCountData!=25) { UART_VidSend(10);//15 LOC_u8ToCountData=0; } Receive_Data_From_Uart=UART_u8Recive();//16 if(Receive_Data_From_Uart==1) LOC_U8Flag=3; else { LOC_U8Flag=3; } } } } } /*Function To Count Timer*/ /* *1-if Count==5 Clear Two Bit Connected to Motor *2-Else Count ==1 Run Motor Clock Wise *3- Else count ==3 Run Motor AntiClock Wise **/ void APP_VidTIMER(void) { g_flag++; if(g_flag==5) { g_flag=0; CLEAR_BIT(PORTA,PA0); CLEAR_BIT(PORTA,PA1); g_flag1=1; } if(g_flag==1) { SET_BIT(PORTA,PA0); CLEAR_BIT(PORTA,PA1); } else if (g_flag==3) { SET_BIT(PORTA,PA1); CLEAR_BIT(PORTA,PA0); } }
Markdown
UTF-8
12,669
2.578125
3
[]
no_license
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <html xmlns="http://www.w3.org/1999/xhtml"><head><meta name="generator" content="DocBook XSL Stylesheets V1.76.1"/></head><body><div class="section" title="A wumpus világ"><div class="titlepage"><div><div><h1 class="title"><a id="id576362"/>A wumpus világ </h1></div></div></div><p>A <span class="strong"><strong>wumpus világ</strong></span> (<span class="strong"><strong>wumpus world</strong></span>) egy barlang, amely szobákból és az ezeket összekötő átjárókból áll. A wumpus egy szörnyeteg, aki mindenkit megesz, ha a szobájába lép, a barlangban lapul valahol. Az ágens le tudja lőni a wumpust, de csak egyetlen nyila van ehhez. Néhány szoba feneketlen csapdát tartalmaz, amely mindenkit csapdába ejt, aki belép a szobába (kivéve a wumpust, aki túl nagy ahhoz, hogy beleessen). A wumpus környezetében az egyetlen csábító lehetőség, hogy egy halom aranyat lehet találni. Habár a wumpus világ meglehetősen unalmas a modern számítógépes játékokhoz képest, azonban a játék kiváló tesztkörnyezet az intelligens ágensek számára. Michael Genesereth volt az első, aki javasolta ennek a környezetnek az alkalmazását. </p><p>Egy példa wumpus világ látható a 7.2. ábrán. A példakörnyezet pontos definícióját, ahogy a 2. fejezetben javasoltuk, a TKCSÉ-leírással adjuk meg: </p><div class="itemizedlist"><ul class="itemizedlist"><li class="listitem"><p><span class="strong"><strong>Teljesítménymérték:</strong></span> +1000 az arany felvétele, –1000 a csapdába esés vagy ha a wumpus felfal, –1 minden végrehajtott cselekvés, –10 a nyíl használata.</p></li></ul></div><div class="figure"><a id="id576391"/><p class="title"><strong>7.2. ábra - Egy tipikus wumpus világ. Az ágens a bal alsó sarokban van.</strong></p><div class="figure-contents"><div class="mediaobject"><img src="kepek/07-02.png" alt="Egy tipikus wumpus világ. Az ágens a bal alsó sarokban van."/></div></div></div><div class="itemizedlist"><ul class="itemizedlist"><li class="listitem"><p> <span class="strong"><strong>Környezet:</strong></span> Egy szobákból álló 4 × 4-es háló. Az ágens mindig az [1, 1]-gyel jelölt négyzetből indul, arccal jobbra nézve. Az arany és a wumpus elhelyezkedése véletlenszerűen, a kiinduló négyzeten kívüli négyzetek közül egyenletes eloszlás szerint van megválasztva. Ezen kívül még bármely, a kiinduló négyzeten kívüli négyzet 0,2 valószínűséggel lehet csapda. </p></li><li class="listitem"><p> <span class="strong"><strong>Cselekvések:</strong></span> Az ágens mozoghat előre, fordulhat balra 90°-kal, vagy fordulhat jobbra 90°-kal. Az ágens szörnyűséges halált hal, ha belép egy négyzetbe, ahol csapda van vagy egy élő wumpus található. (Biztonságos, habár meglehetősen rossz illatú egy olyan négyzetbe belépni, amelyben egy halott wumpus van.) Az előrelépésnek nincs hatása, ha egy fal van az ágens előtt. A <span class="emphasis"><em>Megragad</em></span> cselekvést lehet arra használni, hogy az ágens felvegyen egy tárgyat, amely vele azonos szobában van. A <span class="emphasis"><em>Lövés</em></span> cselekvést lehet használni egy nyílnak abban az irányban történő kilövésére, amerre az ágens éppen áll. A nyíl addig repül, amíg el nem találja (és egyben meg nem öli) a wumpust, vagy falnak nem ütközik. Az ágensnek csak egy nyila van, így csak egy <span class="emphasis"><em>Lövés</em></span> cselekvésnek van hatása.</p></li><li class="listitem"><p><span class="strong"><strong>Érzékelők:</strong></span> Az ágensnek öt érzékelője van, mindegyik egyetlen bitnyi információt ad:</p><div class="itemizedlist"><ul class="itemizedlist"><li class="listitem"><div class="itemizedlist"><ul class="itemizedlist"><li class="listitem"><p class="List Paragraph">A wumpust tartalmazó négyzetben és a közvetlenül (nem átlósan) szomszédos négyzetekben az ágens bűzt érez.</p></li></ul></div></li><li class="listitem"><p class="List Paragraph">A csapdával közvetlenül szomszédos négyzetekben az ágens szellőt érzékel.</p></li><li class="listitem"><p class="List Paragraph">A négyzetben, ahol az arany található, az ágens csillogást érzékel.</p></li><li class="listitem"><p class="List Paragraph">Ha az ágens falnak megy, akkor ütést érzékel.</p><div class="itemizedlist"><ul class="itemizedlist"><li class="listitem"><p class="List Paragraph">Ha a wumpust megölték, akkor egy elkeseredett sikolyt hallat, amit a barlangban bárhol hallani lehet.</p></li></ul></div></li></ul></div></li></ul></div><p>Az érzeteket az ágens egy öt szimbólumot tartalmazó lista formájában kapja meg; például ha bűz és szellő van egy négyzetben, de nincs ütés, csillogás vagy sikoly, akkor az ágens egy [<span class="emphasis"><em>Bűz</em></span>,<span class="emphasis"><em> Szellő</em></span>,<span class="emphasis"><em> Nincs</em></span>,<span class="emphasis"><em> Nincs</em></span>,<span class="emphasis"><em> Nincs</em></span>] érzetet kap.</p><p>A 7.1. feladatban definiálni kell egy wumpus környezetet a 2. fejezetben megadott különböző dimenziók mentén. Az alapvető nehézség az ágens számára, hogy kezdetben semmit sem tud a környezet konfigurációjáról. Úgy tűnik, hogy logikai következtetésre van szüksége az ágensnek ahhoz, hogy felülkerekedhessen a tudatlanság okozta hátrányon. A wumpus világok legtöbb példányában az ágens számára lehetséges az arany biztonságos megszerzése. Néhány környezetben azonban az ágensnek választania kell, hogy hazamegy-e üres kézzel, vagy kockázatot vállal, ami vagy az aranyhoz vagy a halálhoz vezet. És a környezetek 21%-a teljesen tisztességtelen (mivel az arany egy csapdában van vagy csapdákkal körülvett mezőben).</p><p>Nézzünk meg egy tudásbázisú wumpus ágenst, hogy hogyan fedezi fel a 7.2. ábrán látható környezetet. Az ágens kezdeti tudásbázisa a környezetet leíró, az előzőkben felsorolt szabályokat tartalmazza. Nevezetesen tudja, hogy az [1, 1 ]-ben tartózkodik és hogy az [1, 1] biztonságos hely. Látni fogjuk, hogy hogyan bővül az ágens tudása, amint új érzékelések érkeznek és cselekvések történnek.</p><p>Az első érzékelés a [<span class="emphasis"><em>Nincs</em></span>, <span class="emphasis"><em>Nincs</em></span>,<span class="emphasis"><em> Nincs</em></span>,<span class="emphasis"><em> Nincs</em></span>,<span class="emphasis"><em> Nincs</em></span>], amiből az ágens arra tud következtetni, hogy a szomszédos négyzetek biztonságosak. A 7.3. (a) ábra mutatja az ágens tudásának állapotát ezen a ponton. Az ábrán a tudásbázis néhány mondatát soroljuk fel, betűket használva a megfelelő négyzetekben, mint az Sz (szellő) és az <span class="emphasis"><em>OK</em></span> (biztonságos, nincs se csapda, se wumpus). A 7.2. ábra ezzel szemben magát a világot írja le.</p><p>Abból a tényből, hogy nem volt se bűz, se szellő az [1, 1]-ben, az ágens kikövetkeztetheti, hogy az [1, 2] és [2, 1] négyzetek veszélytelenek. Ennek jelzésére a megfelelő négyzetekbe <span class="emphasis"><em>OK</em></span>-t írunk. Egy óvatos ágens csak olyan négyzetbe lép, amelyről tudja, hogy <span class="emphasis"><em>OK</em></span>. Feltételezzük, hogy az ágens úgy dönt, hogy a [2, 1]-be megy, előállítva a 7.3. (b) ábrán látható helyzetet.</p><p>Az ágens detektálja a szellőt a [2, 1]-ben, tehát egy csapdának kell lennie valamelyik szomszédos négyzetben. A csapda nem lehet az [1, 1]-ben a játék szabályai szerint, így csapdának kell lennie a [2, 2]-ben vagy a [3, 1]-ben vagy mindkettőben. A <span class="emphasis"><em>Cs</em></span>? jelölés egy lehetséges csapdát jelez a mezőkben a 7.3. (b) ábrán. Ezen a ponton csak egy olyan ismert négyzet van, ami <span class="emphasis"><em>OK</em></span>, és amit még nem látogatott meg. Így a megfontolt ágens visszafordul, visszamegy az [1, 1]-be és az [1, 2]-be halad tovább.</p><div class="figure"><a id="id579089"/><p class="title"><strong>7.3. ábra - Az ágens első lépése a wumpus világban. (a) A kezdeti helyzet a [<span class="emphasis"><em>Nincs</em></span>, <span class="emphasis"><em>Nincs</em></span>, <span class="emphasis"><em>Nincs</em></span>, <span class="emphasis"><em>Nincs</em></span>, <span class="emphasis"><em>Nincs</em></span>] érzékelése után. (b) Az első lépés után, érzékelve a [<span class="emphasis"><em>Nincs</em></span>, <span class="emphasis"><em>Szellő</em></span>, <span class="emphasis"><em>Nincs</em></span>, <span class="emphasis"><em>Nincs</em></span>, <span class="emphasis"><em>Nincs</em></span>]-et.</strong></p><div class="figure-contents"><div class="mediaobject"><img src="kepek/07-03.png" alt="Az ágens első lépése a wumpus világban. (a) A kezdeti helyzet a [Nincs, Nincs, Nincs, Nincs, Nincs] érzékelése után. (b) Az első lépés után, érzékelve a [Nincs, Szellő, Nincs, Nincs, Nincs]-et."/></div></div></div><p class="Képalá">Az új érzet az [1, 2, ]-ben a [<span class="emphasis"><em>Bűz</em></span>,<span class="emphasis"><em> Nincs</em></span>,<span class="emphasis"><em> Nincs</em></span>,<span class="emphasis"><em> Nincs, Nincs</em></span>], ami a 7.4. (a) ábrán látható helyzetet eredményezi. A bűz az [1, 2]-ben azt jelenti, hogy a wumpusnak a közelben kell lennie. De a wumpus a játék szabályai szerint nem lehet az [1, 1]-ben és nem lehet a [2, 2]-ben sem (mert akkor az ágens érezte volna a bűzt, amikor a [2, 1]-ben járt). Így az ágens kikövetkeztetheti, hogy a wumpus az [1, 3]-ban van. A <span class="emphasis"><em>W</em></span>! jelölés ezt mutatja. Még érdekesebb, hogy a <span class="emphasis"><em>Szellő</em></span> érzet hiánya az [1, 2]-ben azt jelenti, hogy nincs csapda a [2, 2]-ben. De mi már kikövetkeztettük, hogy vagy a [2, 2]-ben, vagy a [3,1]-ben van egy csapda, ami tehát azt jelenti, hogy a csapdának a [3, 1]-ben kell lennie. Ez egy viszonylag nehéz következtetés, mivel különböző időpontokban és különböző helyeken gyűjtött tudást használ fel, és egy érzet hiányára támaszkodva végez el egy fontos lépést. Ez a következtetés meghaladja a legtöbb állat képességeit, de tipikusan jellemzi azt a fajta következtetést, amit egy logikai ágens végez.</p><p class="Képalá">Az ágens így bebizonyította maga számára, hogy nincs se csapda, se wumpus a [2, 2]-ben, így a mozgás ebbe a négyzetbe <span class="emphasis"><em>OK</em></span>. Nem mutatjuk be az ágens tudását a [2, 2]-ben, csak feltételezzük, hogy fordul és átlép a [2, 3]-ba, ami a 7.4. (b) ábrán látható. A [2, 3]-ban az ágens detektálja a csillogást, így megragadja az aranyat, és ezzel véget ér a játék.</p><div class="figure"><a id="id579167"/><p class="title"><strong>7.4. ábra - Két későbbi helyzet az ágens előrehaladása során. (a) A harmadik lépést követően, miután [<span class="emphasis"><em>Bűz</em></span>,<span class="emphasis"><em> Nincs</em></span>,<span class="emphasis"><em> Nincs</em></span>,<span class="emphasis"><em> Nincs</em></span>,<span class="emphasis"><em> Nincs</em></span>]-et érzékelt. (b) Az ötödik lépés és a [<span class="emphasis"><em>Bűz</em></span>,<span class="emphasis"><em> Szellő</em></span>,<span class="emphasis"><em> Csillogás</em></span>,<span class="emphasis"><em> Nincs</em></span>,<span class="emphasis"><em> Nincs</em></span>] érzékelése után</strong></p><div class="figure-contents"><div class="mediaobject"><img src="kepek/07-04.png" alt="Két későbbi helyzet az ágens előrehaladása során. (a) A harmadik lépést követően, miután [Bűz, Nincs, Nincs, Nincs, Nincs]-et érzékelt. (b) Az ötödik lépés és a [Bűz, Szellő, Csillogás, Nincs, Nincs] érzékelése után"/></div></div></div><div class="important" title="Fontos" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Fontos</h3><p><span class="emphasis"><em>Bármely esetben, amikor az ágens következtetéseket von le a rendelkezésre álló információkból, a következmény garantáltan helyes lesz, ha a rendelkezésre álló információk helyesek</em></span>. Ez alapvető jellegzetessége a logikai következtetéseknek. A fejezet hátralevő részében megmutatjuk, hogyan építhetünk olyan logikai ágenseket, amelyek képesek reprezentálni a szükséges információkat, és következtetéseket vonnak le, ahogy azt az eddigi fejezetekben leírtuk.</p></div></div></body></html>
Python
UTF-8
421
3.359375
3
[]
no_license
class Singleton: """Singleton a simple Singleton class decorator """ # on @ decoration def __init__(self, aClass): self.__aClass = aClass self.__instance = None # on instance creation def __call__(self, *args, **kargs): if self.__instance is None: self.__instance = self.__aClass(*args, **kargs) return self.__instance
C#
UTF-8
4,377
2.875
3
[]
no_license
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using ModelService; namespace UtilityService { public class Internet { private static readonly HttpClient HttpClient = new HttpClient(); private static bool _hasInternetAccess = false; static Internet() { HttpClient.Timeout = TimeSpan.FromSeconds(3); } /// <summary> /// Check if System has internet access /// </summary> /// <param name="address">default: https://www.google.com </param> /// <returns>True if connected to VPN</returns> public static async Task<ResponseEntity<bool>> IsInternetConnected(string address = @"https://www.google.com") { try { HttpResponseMessage response = await HttpClient.GetAsync(new Uri(address)); if(response.StatusCode == HttpStatusCode.OK) { _hasInternetAccess = true; return new ResponseEntity<bool>() { Data = true, StatusCode = StatusCode.InternetConnected }; } else { _hasInternetAccess = false; return new ResponseEntity<bool>() { Data = false, StatusCode = StatusCode.InternetNotConnected }; } } catch { _hasInternetAccess = false; return new ResponseEntity<bool>() { Data = false, StatusCode = StatusCode.InternetNotConnected }; } } /// <summary> /// Check if Vpn is connected /// </summary> /// <param name="address">default: http://jobstestuser:KnanUCQJqVP5Mxl@solrqalb.livecareer.com:8983/solr/resumesv3/admin/ping </param> /// <returns>True if connected to VPN</returns> public static async Task<ResponseEntity<bool>> IsOfficeVpnConnected(string address = @"http://jobstestuser:KnanUCQJqVP5Mxl@solrqalb.livecareer.com:8983/solr/resumesv3/admin/ping") { if (_hasInternetAccess) try { HttpResponseMessage response = await HttpClient.GetAsync(new Uri(address)); if (response.StatusCode == HttpStatusCode.OK) { return new ResponseEntity<bool>() { Data = true, StatusCode = StatusCode.VpnConnected }; } return new ResponseEntity<bool>() { Data = false, StatusCode = (StatusCode)Enum.Parse(typeof(StatusCode), response.StatusCode.ToString()), Error = new ErrorResponse() { UiSafeMessage = "VPN Not Connected", DeveloperMessage = "VPN Not Connected", ErrorCode = StatusCode.Error.ToString() } }; } catch (Exception e) { return new ResponseEntity<bool>() { Data = false, StatusCode = StatusCode.VpnNotConnected, Error = new ErrorResponse() { UiSafeMessage = "VPN Not Connected", DeveloperMessage = e.Message, ExceptionStackTrace = e.StackTrace, ExceptionMessage = e.Message, InnerException = e.InnerException?.StackTrace, InnerExceptionMessage = e.InnerException?.StackTrace, ErrorCode = StatusCode.Error.ToString() } }; } return new ResponseEntity<bool>() { Data = false, StatusCode = StatusCode.VpnNotConnected }; } } }
C++
UTF-8
1,408
3.171875
3
[]
no_license
/** * HC-12 + Hardware Serial * * Receiver * Capture HC-12 serial transmissions, parse the value, and transmit to servo */ #include <Servo.h> #define SERVO_PIN 3 const int rxDelayMs = 10; const float angleValMin = 1; const float angleValMax = 179; const char delimiterStart = '['; const char delimiterEnd = ']'; float angleVal = angleValMin; byte incomingByte; Servo servo; void setup() { // put your setup code here, to run once: Serial.begin(9600); servo.attach(SERVO_PIN); servo.write(angleValMin); } void loop() { // put your main code here, to run repeatedly: // char readStr[11]; // Serial.readBytes(readStr, 11); // Serial.println(readStr); // delay(1000); String readBuffer = ""; boolean start = false; while(Serial.available()){ incomingByte = Serial.read(); delay(5); // Serial.print(char(incomingByte)); if (start == true){ if (incomingByte == delimiterStart){ start = true; readBuffer = ""; } else if (incomingByte == delimiterEnd){ start = false; // Serial.println(readBuffer); } else { readBuffer += char(incomingByte); } } else if (incomingByte == delimiterStart) { start = true; readBuffer = ""; } } angleVal = readBuffer.toFloat(); if (angleVal >= angleValMin && angleVal <= angleValMax){ servo.write(angleVal); } // delay(rxDelayMs); }
Python
UTF-8
409
3.75
4
[]
no_license
# returns the sum of all the numbers that can be written as # the sum of fifth powers of their digits def getAnswer(): s=0 for i in range(600000): # upper bound on the possible answers num = "{0:06d}".format(i) p=0 for ch in num: p += int(ch)**5 if p==i: print(i) s+=i return s-1 if __name__=="__main__": print(getAnswer())
Python
UTF-8
7,179
2.625
3
[]
no_license
import numpy as np import cv2 import glob import os import pickle import time from sklearn.svm import LinearSVC from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from skimage.feature import hog from config import * # Define a function to return HOG features and visualization def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True): # Call with two outputs if vis==True if vis == True: features, hog_image = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=False, visualise=vis, feature_vector=feature_vec) return features, hog_image # Otherwise call with one output else: features = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=False, visualise=vis, feature_vector=feature_vec) return features # Define a function to compute binned color features def bin_spatial(img, size=(32, 32)): # Use cv2.resize().ravel() to create the feature vector color1 = cv2.resize(img[:,:,0], size).ravel() color2 = cv2.resize(img[:,:,1], size).ravel() color3 = cv2.resize(img[:,:,2], size).ravel() return np.hstack( (color1, color2, color3) ) # Define a function to compute color histogram features def color_hist(img, nbins=32):#, bins_range=(0, 256)): # Compute the histogram of the color channels separately channel1_hist = np.histogram(img[:,:,0], bins=nbins)#, range=bins_range) channel2_hist = np.histogram(img[:,:,1], bins=nbins)#, range=bins_range) channel3_hist = np.histogram(img[:,:,2], bins=nbins)#, range=bins_range) # Concatenate the histograms into a single feature vector hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0])) return hist_features # Define a function to extract features from a list of images # Have this function call bin_spatial() and color_hist() def extract_features(imgs, color_space='YCrCb', spatial_size=(32, 32), hist_bins=32, orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0, spatial_feat=True, hist_feat=True, hog_feat=True): # Create a list to append feature vectors to features = [] # Iterate through the list of images for file in imgs: file_features = [] # Read in each one by one #image = mpimg.imread(file) image = cv2.imread(file) # apply color conversion if other than 'RGB' if color_space == 'RGB': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) elif color_space == 'HSV': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) elif color_space == 'LUV': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2LUV) elif color_space == 'HLS': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2HLS) elif color_space == 'YUV': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2YUV) elif color_space == 'YCrCb': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb) if spatial_feat == True: spatial_features = bin_spatial(feature_image, size=spatial_size) file_features.append(spatial_features) if hist_feat == True: # Apply color_hist() hist_features = color_hist(feature_image, nbins=hist_bins) file_features.append(hist_features) if hog_feat == True: # Call get_hog_features() with vis=False, feature_vec=True if hog_channel == 'ALL': hog_features = [] for channel in range(feature_image.shape[2]): hog_features.append(get_hog_features(feature_image[:,:,channel], orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True)) hog_features = np.ravel(hog_features) else: hog_features = get_hog_features(feature_image[:,:,hog_channel], orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True) # Append the new feature vector to the features list file_features.append(hog_features) features.append(np.concatenate(file_features)) # Return list of feature vectors return features if __name__ == '__main__': cars = glob.glob(car_folder) notcars = glob.glob(notcar_folder) print('Num cars: ',len(cars)) print('Num notcars: ', len(notcars)) car_features = extract_features(cars, color_space=color_space, spatial_size=spatial_size, hist_bins=hist_bins, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel, spatial_feat=spatial_feat, hist_feat=hist_feat, hog_feat=hog_feat) notcar_features = extract_features(notcars, color_space=color_space, spatial_size=spatial_size, hist_bins=hist_bins, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel, spatial_feat=spatial_feat, hist_feat=hist_feat, hog_feat=hog_feat) X = np.vstack((car_features, notcar_features)).astype(np.float64) #Fit a per-column scaler X_scaler = StandardScaler().fit(X) # Apply the scaler to X scaled_X = X_scaler.transform(X) # Define the labels vector y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features)))) # Split up data into randomized training and test sets #and_state = np.random.randint(0, 100) rand_state = 10 X_train, X_test, y_train, y_test = train_test_split( scaled_X, y, test_size=0.1, random_state=rand_state) print('Train on {0} samples'.format(len(y_train))) print('Using:',orient,'orientations',pix_per_cell, 'pixels per cell and', cell_per_block,'cells per block') print('Feature vector length:', len(X_train[0])) # Use a linear SVC svc = LinearSVC() # Check the training time for the SVC t=time.time() svc.fit(X_train, y_train) t2 = time.time() print(round(t2-t, 2), 'Seconds to train SVC...') # Check the score of the SVC print('Test on {0} samples'.format(len(y_test))) print('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4)) svc_dict = {'svc':svc, 'scaler': X_scaler, 'color_space': color_space, 'orient':orient, 'pix_per_cell':pix_per_cell, 'cell_per_block': cell_per_block, 'hog_channel':hog_channel, 'spatial_size':spatial_size, 'hist_bins':hist_bins, 'spatial_feat':spatial_feat, 'hist_feat':hist_feat, 'hog_feat':hog_feat} pickle.dump(svc_dict, open("svc_pickle.p", "wb" ))
Markdown
UTF-8
2,136
2.9375
3
[]
no_license
## Netty ByteBuf > 参考链接: https://skyao.gitbooks.io/learning-netty/content/buffer/inheritance.html ### ByteBuf 模块 ![ByteBuf 类结构图](../pic/ByteBuf.png) #### ByteBuf基础实现类 按照是否支持池共享分为( `PooledByteBuf`是4.x之后的新特性, netty3.*和之前版本并不支持): - `PooledByteBuf` - `UnpooledByteBuf` 区别在于使用 UnPooled Buffer 时每次都会分配一个新的缓冲区, 而当使用 Pooled buffer 时,Netty 会尝试将缓冲区池化,从而最小化分配和释放缓冲区的开销 按照内存分配方式可分为: - `HeapByteBuf`:直接使用堆内存 - `DirectByteBuf`: 使用 Java NIO 提供的直接内存,体现为使用 nio ByteBuffer - `UnsafeDirectByteBuf`: DirectByteBuf的特殊情况,如果当前系统提供了sun.misc.Unsafe #### ByteBuf衍生类 DerivedByteBuf是在ByteBuf的基本实现基础上衍生出来的: 包装其他ByteBuf,然后增加一些特别的功能, 基类为抽象类 `AbstractDerivedByteBuf` ![DerivedByteBuf 类结构图](../pic/DerivedBuffer.png) - `PooledDuplicatedByteBuf`: 简单的将所有的请求都委托给包装的ByteBuf - `PooledSlicedByteBuf`: 将原有ByteBuf的部分内容拆分出来的ByteBuf,主要是为了实现zero-copy特性 ##### CompositeByteBuf/FixedCompositeByteBuf - `CompositeByteBuf` 是一个虚拟的buffer,将多个buffer展现为一个简单合并的buffer,以便实现netty最重要的特性之一: zero copy - `FixedCompositeByteBuf` 功能类似`CompositeByteBuf`, 以只读的方式包装一个ByteBuf数组,通常用于写入一组ByteBuf的内容 #### 特殊的ByteBuf类 - `EmptyByteBuf`: 空的 ByteBuf, capacity 和 maximum capacity 都被设置为0. - `SwappedByteBuf`: Swap/交换指的是`LITTLE_ENDIAN/BIG_ENDIAN`之间的交换, `SwappedByteBuf`用于包装一个ByteBuf,内容相同但是`ByteOrder`相反.它的子类`UnsafeDirectSwappedByteBuf`支持`memoryAddress`. - `WrappedByteBuf`: `WrappedByteBuf`顾名思义是用来包装其他`ByteBuf`的,代码实现也简单: 包装一个`ByteBuf`,然后所有方法调用委托给被包装的`ByteBuf` ### ByteBuf 原理
Markdown
UTF-8
3,463
2.9375
3
[ "MIT" ]
permissive
# fdir - a 4DOS Dir command recreation in Swift ## What? In the old days of MSDOS existed a shell replacement called [4DOS](https://www.4dos.info/). One of the best features was the ability to annotate files and folders with comments, so while listing a directory wth `dir` you could see directly there what a folder contained. The idea is simple: you have a text file called `descript.ion` with the names of all files & folders. You can then add a description to each one that will be listed to the right of the file name. A simple way to catalog and know what's inside your directories! ## An Example, please? Sure, you'll go from this: ```bash $ ls -l total 16 drwx------@ 3 dfreniche staff 96 Sep 17 18:00 Applications drwxr-xr-x 29 dfreniche staff 928 Oct 20 16:55 Code drwx------@ 16 dfreniche staff 512 Oct 25 12:09 Desktop drwx------+ 13 dfreniche staff 416 Oct 6 08:48 Documents drwx------@ 45 dfreniche staff 1440 Oct 25 12:30 Downloads lrwx------ 1 dfreniche staff 20 Oct 22 09:03 Google Drive -> /Volumes/GoogleDrive drwx------@ 82 dfreniche staff 2624 Sep 22 13:01 Library drwx------+ 4 dfreniche staff 128 May 10 16:46 Movies drwx------+ 6 dfreniche staff 192 Aug 27 16:43 Music drwx------+ 5 dfreniche staff 160 May 31 16:56 Pictures drwxr-xr-x+ 4 dfreniche staff 128 May 10 16:16 Public -rw-r--r--@ 1 dfreniche staff 5652 Aug 6 16:33 common-aliases-bash-zsh.sh drwxr-xr-x 15 dfreniche staff 480 Oct 4 12:00 scripts drwxr-xr-x@ 22 dfreniche staff 704 May 18 10:04 zsh-autosuggestions ``` to this: ```bash $ fdir fdir - [13] folders, [1] files [D] Applications : all my Apps outside of /Applications [D] Code : here is my code [D] Desktop : my Desktop. Keep it clean [D] Documents : Documents, although everything should be in Google Drive [D] Downloads : Cleaned from time to time, don't leave important stuff here! [D] Google Drive : Work files [D] Library : Config files for everything [D] Movies : Presentations and Talks being edited [D] Music : No music, just UNICODE U00D1 Podcast [D] Pictures : Well, images [D] Public : Publicly shared folder from macOS [D] scripts : my scripts [D] zsh-autosuggestions : for ZSH plugins ``` ## How to install You need: - macOS (or maybe Linux + Swift, haven't tried) - Xcode 13 Clone this repo: ``` git clone ``` Then, open Xcode. In the scheme fdir there's a Build Post-Action copying the binary to a folder. Change it to suit your setup. Build. Done. ## How to use it ### Get help ``` fdir --help USAGE: fdir [--init] [--update] [--edit] [--all] OPTIONS: -i, --init Creates a new hidden .descript.ion file -u, --update Updates existing .descript.ion file with contents of folder -e, --edit Opens existing .descript.ion file with VS Code -a, --all Includes all files -h, --help Show help information. ``` ### Create a new .descript.ion file ``` fdir --init ``` This creates a new `.descript.ion` file with all files and folders in current directory. If a `.descript.ion` file already exists, ask before overwriting. Once you have the `.descript.ion` you can open it with your favorite editor and add any descriptions you like
Java
UTF-8
521
1.726563
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 Inf; import java.util.ArrayList; import Inf.Ubi_Silla; /** * * @author anpip */ public class Datos_Pers { public static ArrayList<Ubi_Silla> list = new ArrayList<Ubi_Silla>(); //double total = 0; //for(Ubi_Silla list : ArrayListUbi_Silla){ // total +list.getPrecio(); //} }
Java
UTF-8
1,416
2.671875
3
[ "MIT" ]
permissive
package com.direwolf20.buildinggadgets.common.util.spliterator; import com.direwolf20.buildinggadgets.common.building.BlockData; import net.minecraft.util.math.BlockPos; import javax.annotation.Nullable; import java.util.Spliterator; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; public final class PositionValidatingSpliterator extends DelegatingSpliterator<BlockPos, BlockPos> { private final BiPredicate<BlockPos, BlockData> predicate; private final Function<BlockPos, BlockData> dataExtractor; public PositionValidatingSpliterator(Spliterator<BlockPos> other, BiPredicate<BlockPos, BlockData> predicate, Function<BlockPos, BlockData> dataExtractor) { super(other); this.predicate = predicate; this.dataExtractor = dataExtractor; } @Override public boolean advance(BlockPos object, Consumer<? super BlockPos> action) { BlockData data = dataExtractor.apply(object); if (predicate.test(object, data)) { action.accept(object); return true; } return false; } @Nullable @Override public Spliterator<BlockPos> trySplit() { Spliterator<BlockPos> split = getOther().trySplit(); if (split != null) return new PositionValidatingSpliterator(split, predicate, dataExtractor); return null; } }
Java
UTF-8
4,256
2.703125
3
[]
no_license
package com.examplemodel.examplemodel; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class DictionaryDB extends SQLiteOpenHelper{ private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "DictionaryDB"; private static final String DATABASE_TABLE = "DictionaryTable"; public static final String KEY_ROWID = "_id"; public static final String KEY_EN_WORD = "en_word"; public static final String KEY_BG_WORD = "bg_word"; public DictionaryDB(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_CONTACTS_TABLE = "CREATE TABLE " + DATABASE_TABLE + "(" + KEY_ROWID + " INTEGER PRIMARY KEY," + KEY_EN_WORD + " TEXT," + KEY_BG_WORD + " TEXT" + ")"; db.execSQL(CREATE_CONTACTS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); // Create tables again onCreate(db); } void addWords(Words words) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_EN_WORD, words.getEn_word()); // Contact Name values.put(KEY_BG_WORD, words.getBg_word()); // Contact Phone // Inserting Row db.insert(DATABASE_TABLE, null, values); //2nd argument is String containing nullColumnHack db.close(); // Closing database connection } public List<Words> getAllWords() { List<Words> wordsList = new ArrayList<Words>(); String selectQuery = "SELECT * FROM " + DATABASE_TABLE; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { Words words = new Words(); words.setId(Integer.parseInt(cursor.getString(0))); words.setEn_word(cursor.getString(1)); words.setBg_word(cursor.getString(2)); wordsList.add(words); } while (cursor.moveToNext()); } return wordsList; } public List<Words> getAllWordsNew() { //List<Words> wordsList = new ArrayList<Words>(); String [] columns = new String [] {KEY_ROWID, KEY_EN_WORD, KEY_BG_WORD}; SQLiteDatabase db = this.getWritableDatabase(); Cursor c = db.query(DATABASE_TABLE, columns, null, null, null, null, null); int iRowID = c.getColumnIndex(KEY_ROWID); Log.i("NAME", "Name " + c.getColumnName(1)); int iEnWord = c.getColumnIndex(KEY_EN_WORD); //int iBgWord = c.getColumnIndex(KEY_BG_WORD); //Log.i("ROW", "Row " + iBgWord); //Map<String, List<String>> expandableListDetail = new TreeMap<String, List<String>>(); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){ Log.i("NAME", "Name" + c.getString(iEnWord)); } c.close(); return null; } /* public void getAndInsertDataFromFireBase(){ final DatabaseReference senderDb = FirebaseDatabase.getInstance().getReference().child("Items"); senderDb.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) { //Log.i("Testing", "DATA: "+ childDataSnapshot.child("bg_word").getValue().toString()); createEntry(childDataSnapshot.child("en_word").getValue().toString(), childDataSnapshot.child("bg_word").getValue().toString()); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } */ }
C++
UTF-8
1,286
2.53125
3
[ "MIT" ]
permissive
// // Created by Battary on 26.03.2020. // #pragma once #include <map> #include <memory> #include <string> #include "game/lib/ECS/ECS.h" // Components #include "game/components/ControlComponent.h" #include "game/components/LocationComponent.h" #include "game/components/PreviousLocationComponent.h" #include "game/components/DirectionComponent.h" #include "game/components/StatisticsComponent.h" // Commands #include "commandsPlayerMovementSystem/MoveDownCommand.h" #include "commandsPlayerMovementSystem/MoveLeftCommand.h" #include "commandsPlayerMovementSystem/MoveRightCommand.h" #include "commandsPlayerMovementSystem/MoveUpCommand.h" #include "commandsPlayerMovementSystem/NothingCommand.h" //Система, контролирующая передвижение относительно нажатых клавиш на клавиатуре class PlayerMovementSystem : public ecs::System { private: std::map<std::string, std::shared_ptr<ICommand>> storage_ {}; std::shared_ptr<NothingCommand> nothing_ = std::make_shared<NothingCommand>(); void fillStorage(); std::shared_ptr<ICommand> findCommand(const std::string); public: PlayerMovementSystem(); void updateSystem(ecs::World&) override; ~PlayerMovementSystem() override { storage_.clear(); } };
Python
UTF-8
435
3.421875
3
[]
no_license
def calculate_change(money, idx): if money < 10: return while money >= unit[idx]: money -= unit[idx] change[idx] += 1 calculate_change(money, idx+1) return for tc in range(1, int(input())+1): money = int(input()) change = [0] * 8 unit = [50000, 10000, 5000, 1000, 500, 100, 50, 10] calculate_change(money, 0) print('#{}'.format(tc)) print(" ".join(map(str, change)))
C#
UTF-8
1,255
2.703125
3
[]
no_license
using GalexyOnlineStore.Application.Interface.Contexts; using GalexyOnlineStore.Common; using System; using System.Collections.Generic; using System.Linq; namespace GalexyOnlineStore.Application.Services.Users.Queries.GetUsers { public class GetUsersService : IGetUsersService { private readonly IDatabaseContext context; public GetUsersService(IDatabaseContext databaseContext) { context = databaseContext; } public GetUsersResultDto Execute(GetUsertsRequestDto request) { var users = context.Users.AsQueryable(); if (!string.IsNullOrEmpty(request.SearchKey) && !string.IsNullOrWhiteSpace(request.SearchKey)) { users = users.Where(u => u.Name.Contains(request.SearchKey)); } int rowCnt = 0; var getUsers = users.ToPaged(request.Page, 10, out rowCnt).Select(u => new GetUsersDto { Id = u.Id, Name = u.Name, Email = u.Email }); GetUsersResultDto usersResultDto = new GetUsersResultDto { Users = getUsers, UsersRowCount = getUsers.Count() }; return usersResultDto; } } }
C
UTF-8
1,754
4.5625
5
[]
no_license
/* You are given two array, first array contain integer which represent heights of persons and second array contain how many persons in front of him are standing who are greater than him in term of height and forming a queue. Ex A: 3 2 1 B: 0 1 1 It means in front of person of height 3 there is no person standing, person of height 2 there is one person in front of him who has greater height then he, similar to person of height 1. Your task to arrange them Ouput should be. 3 1 2 Here - 3 is at front, 1 has 3 in front ,2 has 1 and 3 in front. */ # include <stdio.h> # define N 5 void print(int* height, int* count, int n) { int i; printf("\nHeight :\t"); for(i=0; i<n; i++) printf("%d\t", height[i]); printf("\n Count :\t"); for(i=0; i<n; i++) printf("%d\t", count[i]); printf("\n"); } void swap(int* x, int* y) { int z; z = *x; *x = *y; *y = z; } void desc_quick_sort(int* a, int* b, int n) { if(n<2) return; int pivot = 0; int start = 0, end = n-1; while(start <= end) { while(a[start] > a[pivot]) start++; while(a[end] < a[pivot]) end--; if(start <= end) { swap(&a[start], &a[end]); swap(&b[start], &b[end]); start++; end--; } } desc_quick_sort(a, b, end); desc_quick_sort(&a[start], &b[start], n-start); } void arrange(int* height, int* count, int n) { int i, j, shiftCnt; desc_quick_sort(height, count, n); for (i=0; i<n; i++) { shiftCnt = i - count[i]; for(j=i; shiftCnt>0; j--, shiftCnt--) { swap(&height[j], &height[j-1]); swap(&count[j], &count[j-1]); } } } void main() { int height[N] = {5,1,2,3,4}; int count[N] = {1,3,2,0,0}; arrange(height, count, N); print(height, count, N); }
Python
UTF-8
3,587
3.0625
3
[]
no_license
######### # Authors: Kyle Nielsen John Drake TODO add your name if you edit this file # For: CIS 433 at UOregon # Date of creation: February 6, 2019 # Last update: March 7, 2019 TODO keep updated # Language: Python 3 # Credit: TODO credit outside sources if applicable # Program state: Basic check for name-email combo. Functions for adding and deleting name-email pairs. Can check if an email is in a list of confirmed phishers, as well as add and delete entries from the list. Only a few combos in database # Hypothetical future improvement: Accounts, and either: each account has seperate datafiles, or only confirmed accounts can modify the datafiles ######### import flask from flask import Flask, request import json app = Flask(__name__) with open("data.json", "r") as data_file: data = json.load(data_file) # load the file with name-email combos with open("phishers.json", "r") as phishers_file: phishers = json.load(phishers_file) # load the file with confirmed phishing emails @app.route("/api/check-pair") def check(): if not (request.args.get("name") and request.args.get("email")): return "error" # return error if not all args were provided name = request.args.get("name") email = request.args.get("email") if name not in data: return "unknown" # return unknown if name not in database if email in data[name]: return "valid" # return valid if the pair matches return "invalid" # otherwise, the pair didn't match. Invalid @app.route("/api/add-pair") def add(): if not (request.args.get("name") and request.args.get("email")): return "error" name = request.args.get("name") email = request.args.get("email") if name in data: # If the name is already in the data, append it to the existing list data[name].append(email) else: # otherwise, create a key data[name] = [email] update_data_file() return "success" @app.route("/api/del-pair") def delete(): if not (request.args.get("name") and request.args.get("email")): return "error" name = request.args.get("name") email = request.args.get("email") if name in data: # no need to remove the email if the name doesn't exist while email in data[name]: # remove duplicates, or don't try to remove if it isn't there data[name].remove(email) update_data_file() return "success" @app.route("/api/check-phish") def check_phish(): if not request.args.get("email"): return "error" email = request.args.get("email") if email in phishers["phishers"]: return "confirmed" return "unconfirmed" @app.route("/api/add-phish") def add_phish(): if not request.args.get("email"): return "error" email = request.args.get("email") phishers["phishers"].append(email) update_phishers_file() return "success" @app.route("/api/del-phish") def del_phish(): if not request.args.get("email"): return "error" email = request.args.get("email") while email in phishers["phishers"]: phishers["phishers"].remove(email) update_phishers_file() return "success" def update_data_file(): with open("data.json", "w") as df: # open data file with write permission json.dump(data, df) # write json data to file def update_phishers_file(): with open("phishers.json", "w") as pf: json.dump(phishers, pf) if __name__ == "__main__": # passes if running on personal machine, but not on python anywhere app.run(debug=False, port=5001, host="0.0.0.0")
Java
UTF-8
1,763
2.78125
3
[]
no_license
package info.timgraves.higherorlower; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import java.util.Random; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private int num; private int userNum; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); num = newNum(); } public int newNum() { Random r = new Random(); return r.nextInt(20) + 1; } public void newNum(View view) { num = newNum(); } public void guessNumber(View view) { Log.i(TAG, "num = " + num); EditText guessEditText = (EditText) findViewById(R.id.guessEditText); if (guessEditText.getText().toString().isEmpty()) { Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_SHORT).show(); } else { userNum = Integer.parseInt(guessEditText.getText().toString()); if (userNum == num) { Toast.makeText(MainActivity.this, "You guessed it, try again!", Toast.LENGTH_LONG).show(); num = newNum(); } else if (userNum > num) { Toast.makeText(MainActivity.this, "Lower!", Toast.LENGTH_SHORT).show(); } else if (userNum < num) { Toast.makeText(MainActivity.this, "Higher!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "WTF DID YOU DO?!", Toast.LENGTH_LONG).show(); } } } }
Java
UTF-8
1,226
2.09375
2
[]
no_license
package com.cmpay.lww.service; import com.cmpay.lww.bo.MenuInfoBO; import com.cmpay.lww.bo.RoleInfoBO; import com.cmpay.lww.bo.RoleMenuInsertBO; import com.cmpay.lww.dto.MenuInfoDTO; import com.cmpay.lww.entity.MenuDO; import java.util.List; /** * 菜单服务类 * * @author lww * @since 2020-06-21 */ public interface MenuService { List<MenuDO> selectByCondition(); /** * 递归删除菜单 * @param id */ void removeChildById(Long id); /** * 获取全部菜单(递归 层级) * @return */ List<MenuInfoDTO> queryAllMenu(); /** * 为角色添加权限(批量) * @param insertBO */ void saveRoleMenuRalation(RoleMenuInsertBO insertBO); /** * 插入菜单 * @param menuInfoBO */ void saveMenu(MenuInfoBO menuInfoBO); /** * 修改菜单 根据id * @param menuInfoBO */ void updateMenu(MenuInfoBO menuInfoBO); /** * 根据id获取菜单 * @param menuInfoBO * @return */ MenuInfoBO getRoleInfoById(MenuInfoBO menuInfoBO); /** * 根据角色id获取菜单 * @param roleId * @return */ List<MenuInfoDTO> getMenuInfoByRoleId(Long roleId); }
Markdown
UTF-8
1,427
3.65625
4
[]
no_license
# 2. Making Your Codes Smarter Now that you've learned **the primary data types, ways to manipulate to them, and how to express and combine them through methods**, let's dive a bit deeper into methods. Remember from section 1.9, when we mentioned the concept of **functional abstraction**, methods allow us to simplify the program and structure our logic. By definition, function abstraction means that every time every time you declare a **function** \(in ruby, a method\), you are creating an **abstraction** by giving a name to a piece of code. In this chapter, we will talk about some of the more **important and common techniques** we use in programming to improve the flexibility and responsiveness of our program. Specifically, we will address the **following several concepts**: 1. Logic Operations 2. Control Flow 3. Conditional Loop \(while ... loop\) 4. Anonymous Functions \(Procs v. Lambdas\) 5. Scopes 6. Introduction to Recursive Programming In addition to these topics, we will also provide **two extra supplementary sections** for students who are interested in learning more about **logic operators and scopes:** 1. Introduction to Logics 1. Logic Operators 2. Truth Table 3. Binary Operations in Computer Circuits 4. Hexadecimal and Why It Matters 2. Scopes and Availability 1. Local Scope 2. Variable Accessibility 3. Environment Diagrams 4. How to Better Trace Your Programs
Markdown
UTF-8
13,041
2.9375
3
[ "MIT" ]
permissive
#Using the new Tutum Stream API ## Part Two: Practical Use Cases of the Tutum Stream API ##Introduction Tutum recently introduced its new [Tutum Stream API](http://blog.tutum.co/2015/04/07/presenting-tutum-stream-api/). This is a great new feature that allows you to use WebSockets to monitor Events from your Tutum account. WebSockets are a big improvement over long-polling and other conventional HTTP-based methods to stay informed of changes to your application. This is part two of a two-part tutorial will show you how to use the Tutum Stream API. This part will show how to use the Tutum Stream API for some common use cases, such as integrations with Slack, Pagerduty, and others. It shows how you can retrieve additional information from the Tutum API to provide richer detail to your monitoring tools. Finally, we'll see how to deploy a service on Tutum that is always connected to the Tutum Stream API to keep you apprised of changes to your deployments. To follow along with this tutorial, clone [this GitHub repo](https://github.com/alexdebrie/tutum-stream). It has a few sample client files as well as Python modules with code to interact with Pagerduty, Slack, and Tutum. It also has a Dockerfile that you can use to build a Docker image to deploy as a service on Tutum. ##The Four WebSocket Events As noted in the previous tutorial, there are four event handlers you need to set up with your WebSocket connection. These event handlers are: on_open: for when the connection to the WebSocket is opened; on_close: for when the connection to the WebSocket is closed; on_message: for when your WebSocket client receives a message; on_error: for when you receive an error These four handlers will be the key to interacting with the Tutum Stream API. ##First Steps with the Tutum Stream Client To get started with the Tutum Stream API, let's just run the basic example client that Tutum showed in its [initial blog post]((http://blog.tutum.co/2015/04/07/presenting-tutum-stream-api/) on the Tutum Stream API. If you cloned my GitHub repo, it is listed as `tutum-sample.py`. You'll need to set two environment variables in your terminal before running it. export TUTUM_TOKEN=<your_Tutum_token> export TUTUM_USERNAME=<your_Tutum_username> These will be used to authenticate your WebSocket client with the Tutum Stream server. Once you've set these, run: python tutum-sample.py You should see the following output in your terminal: Connected Auth completed If you look at the source code for `tutum-sample.py`, you see that that "Connected" is printed when the `on_open` event handler is triggered. The "Auth completed" statement was printed when the `on_message` event handler was triggered and the message type was "auth". If you want to play around further, keep the connection in your terminal and use your web browser to navigate to Tutum. Redeploy one of your current services or launch a new service (the tutum/hello-world service is an easy sample). Your terminal should post a number of messages relating to the creation of a new service and other updates. ##Monitoring your Tutum Stream client with Pagerduty By the end of this tutorial, we'll have a service deployed on Tutum that is connected to the Tutum Stream API and handling events as we desire. However, we'll want to make sure our client is properly connected to the Stream API at all times. After all, you can't send messages about your events if your client is down. To monitor our Stream client, we'll use [Pagerduty](http://www.pagerduty.com/). Pagerduty allows you to get notifications if portions of your infrastructure go down. You can send emails, text messages, or notifications through mobile apps. You can trigger notifications using the Pagerduty [Integration API](https://developer.pagerduty.com/documentation/integration/events). In the repo for this project, I've written a function to post an event to Pagerduty. Look at the `pagerduty_event()` function in `integrations/pagerduty.py`. The important part of the function is as follows: def pagerduty_event(event_type="trigger", incident_key=None, description=None, client=None, client_url=None, service_key=PAGERDUTY_KEY): if not service_key: raise Exception("Please provide a Pagerduty Service Key") if not description: description = "Tutum Stream Issue" data = { "service_key": service_key, "incident_key": incident_key, "event_type": event_type, "description": description, "client": client, "client_url": client_url } headers = {'Content-type': 'application/json'} r = requests.post(PAGERDUTY_URL, headers=headers, data=json.dumps(data)) The function puts together some JSON and posts it to the Pagerduty endpoint. By default, it sends a 'trigger' event to Pagerduty, which sends an alert to the proper person. Note that you can also send a 'resolve' event to Pagerduty, which indicates that a previously triggered issue has been resolved. Let's see how this works in action. In the git repo, check out `pagerduty-client.py`. It is the same as the `tutum-sample.py` script, with two changes. First, the `on_close` handler has been changed: def on_close(ws): pagerduty_event(event_type='trigger', incident_key='tutum-stream', description='Tutum Stream connection closed.') print "### closed ###" Once the WebSocket closes its connection, it sends a trigger event to Pagerduty. This way, you'll be alerted when you are no longer connected to the Tutum Stream API. Similarly, look at the `on_open` handler: def on_open(ws): pagerduty_event(event_type='resolve', incident_key='tutum-stream', description='Tutum Stream connection open.') print "Connected" This handler mirrors the `on_close` handler, as it sends a resolve event to Pagerduty. If you previously sent a trigger event signaling that your Stream API client is down, this will send a message that the problem has been fixed. You could use this Pagerduty integration for all kinds of alerts. Another common use case would be to use the `pagerduty_event` function in the `on_message` handler when certain Services, Stacks, or Nodes are deleted. We'll investigate the `on_message` handler more in the next section. As a final note, if you want to use the `pagerduty_event()` function, you'll need to set your PAGERDUTY_KEY as an environment variable. In your terminal, run: export PAGERDUTY_KEY=<your_Pagerduty_key> ##Posting Update Messages to Slack Monitoring errors is responsible and all, but sometimes it's more fun to see the good things your team is doing. This section will show you how to post messages to [Slack](https://slack.com/) whenever you create a new Container on Tutum. Again, let's look to the source code. Check out `integrations/slack.py`. There are two functions: def post_slack(text=None, slack_url=SLACK_URL): if not SLACK_URL: raise Exception('Please provide a Slack URL') if not text: text = "You received a message from Tutum Stream!" data = {"text": text} r = requests.post(slack_url, data=json.dumps(data)) return r def generic_slack(message): msg_as_JSON = json.loads(message) text = ("Your {} was {}d on Tutum!\n" "Check {} to see more details.".format(msg_as_JSON.get('type'), msg_as_JSON.get('action'), msg_as_JSON.get('resource_uri'))) post_slack(text=text) The first function, `post_slack()`, is an implementation of the method to post messages to Slack using the [Incoming Webhooks](https://api.slack.com/incoming-webhooks) integration. To use this function, you'll need to register for a Webhook URL to send POST requests. The second function, `generic_slack()`, is a simple wrapper function around `post_slack`. It takes a message from the Tutum Stream API, and it will post information about that update to your Slack channel. Let's put this into action. Check out `client.py`. This will be our actual client script that we end up deploying on Tutum. In particular, check out the last two lines of the following: def on_message(ws, message): msg_as_JSON = json.loads(message) type = msg_as_JSON.get("type") if type: if type == "auth": print("Auth completed") elif type == "container": generic_slack(message) This same checks to see if the `type` of event from the Tutum Stream is a "container" event. If so, it posts a message to Slack using the `generic_slack` function. Test it out yourself. In your terminal, set your SLACK_URL environment variable, then run the client. export SLACK_URL=<your_Slack_url> python client.py Navigate to the Tutum Dashboard with your browser. Deploy a new service or redeploy an existing service. In your Slack channel, you should see a message like the following: Your container was created on Tutum! Check /api/v1/container/df3eb045-8bb9-46c1-ac59-a67ce0f4d875/ to see more details. Congratulations! You've sent your first Tutum Stream event to Slack! ##Advanced Message Handling with Tutum Stream The example above is nice, but it'd be nice to provide a little more info about Tutum events. As discussed in part one of this tutorial, a message from the Tutum Stream API includes a `resource_uri` and the resource_uri of any `parents` of the event object. We can use these resource_uri's to add additional information to our notifications. The source code in `integrations/utilities.py` includes a helper function called `get_resource()`. This function takes a resource_uri and returns the text response from the Tutum API for that resource. Look at the `on_message` handler in the `client.py` script. It has the following code that is executed when the event type is "service": elif type == "service": parents = msg_as_JSON.get("parents") if parents: stack = get_resource(parents[0]) stack_as_JSON = json.loads(stack) text = ("A Service on Tutum was {}d.\nIt belonged to the " "{} Stack.\nThe Stack state is: {}".format(msg_as_JSON.get('action'), stack_as_JSON.get('name'), stack_as_JSON.get('state'))) post_slack(text=text) This handler grabs the information about the Service's parent Stack. It then posts a message to Slack about the status of the Stack with a recently deployed Service. This is a simple example, but you can use the `resource_uri` of both the object and its parents to do some powerful stuff. For the ambitious, you could parse the resource_uri of each and every event that is triggered and post the information to ElasticSearch for later analysis. ##Deploying your Tutum Stream Client as a Tutum Service So far, we've been running the Tutum Stream WebSockets client in our local terminal. However, we'll want something that's always running to make sure we're always tracking our Tutum events. To do this, we'll deploy the WebSockets client as a service on Tutum in a Docker container. In the git repo, I've provided a Dockerfile to get you started. It is based on the [Alpine Linux image](https://github.com/gliderlabs/docker-alpine) from the Gilder Labs team. Alpine Linux is a minimalist Linux distribution with a pretty good package repository. The Dockerfile installs Python and Pip, `pip installs` the required Python packages, and adds the code from your repo. To get the image on Tutum, run: docker build -t tutum.co/<username>/stream-client . docker push tutum.co/<username>/stream-client In your Tutum browser, set up a Stack file with Stream: stream: image: 'tutum.co/<username>/tutum-stream:latest' environment: - PAGERDUTY_KEY=<your_Pagerduty_key> - SLACK_URL=<your_Slack_url> roles: - global We're giving the "global" API role to the service so that it has full access to the Tutum API. You can read about API roles [here](https://support.tutum.co/support/solutions/articles/5000524639-api-roles). Hit "Create and Deploy" and you're done! You'll be receiving Slack messages and Pagerduty alerts with updates to your Tutum infrastructure! ##Conclusion This tutorial has walked through integrating the Tutum Steam API into your monitoring and communications systems. We learned how to send Pagerduty triggers and Slack messages on specified Tutum events, as well as how to deploy a minimal Docker image that monitors your Tutum Stream. Please let me know of any questions or comments on this tutorial in the comment box below. Interested in adding additional integrations? Feel free to fork the repo for this tutorial and create a pull request with your new tool!
C++
UTF-8
4,135
2.625
3
[]
no_license
#include "database.h" DataBase::DataBase(QString time, int temperature, int humidite, QString user, QString four, double CO2, int chute, QString tv) { try { sql::Driver *driver; sql::Connection *con; //sql::ResultSet *res; //sql::PreparedStatement *pstmt; int id_sensor; int num; QString car; QString dtime; driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", "equipe", "toor"); con->setSchema("isen_lab"); //stmt = con->createStatement(); //res = stmt->executeQuery("INSERT INTO `VALUE` (`DTIME`, `CAR`, `NUM`, `ID_VALUE`, `TYPE`) VALUES (\'dtime\', \'car\', \'num\', NULL, \'id_sensor\');"); for (int i = 1; i < 8; i++) { //Selection progressive des valeurs //remplissage des car ou num nulls if (i < 5) { car = "NULL"; } else { num = 0; } //remplissage des valeurs transcrites switch(i) { case 1: num = chute; break; case 2: num = CO2; break; case 3: num = humidite; break; case 4: num = temperature; break; case 5: car = user; break; case 6: car = tv; break; case 7: car = four; break; } //le temps est le même dans tous les cas dtime = time; id_sensor = i; QString qsid_sensor = QString::number(id_sensor); QString qsnum = QString::number(num); //on execute la requete QString test = "INSERT INTO `VALUE` (`DTIME`, `CAR`, `NUM`, `ID_VALUE`, `TYPE`) VALUES (\'"+dtime+"\', \'"+car+"\', \'"+qsnum+"\', NULL, \'"+qsid_sensor+"\');"; //string test2 = test.toStdString(); qDebug() << test << endl; //pstmt = con->prepareStatement(test.toStdString()); //res = pstmt->executeQuery(); //delete pstmt; } //delete res; delete con; //delete pstmt; } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << __LINE__ << endl; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } } //aller dans la bdd pour récuperer les seuils //les comparer avec nos valeurs //si depassement ==> createAlert() /*void DataBase::Comparaison(QString time, int temperature, int humidite, QString user, QString four, double CO2, int chute, QString tv) { try { sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", "equipe", "toor"); con->setSchema("isen_lab"); int value; for (int i = 1; i < 5; i++) { QString request_high = "SELECT `THRESHOLD_HIGH` FROM `SENSOR` WHERE `TYPE` = \'"+i+"\' AND `ROOM` = 1;"; QString request_low = "SELECT `THRESHOLD_LOW` FROM `SENSOR` WHERE `TYPE` = \'"+i+"\' AND `ROOM` = 1;"; switch (i) { case 1: value = chute; break; case 2; value = CO2; break; case 3: value = humidite; break; case 4: value = temperature; break; } res = stmt->executeQuery(request_high); if (value >= res) { createAlert(); } res = stmt->executeQuery(request_low); if (value <= res) { createAlert(); } } } delete res; delete con; delete stmt; catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << __LINE__ << endl; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } } void DataBase::createAlert() { /*envoyer le mail : https://curl.haxx.se/libcurl/c/smtp-mail.html*/ //}
Markdown
UTF-8
1,596
3.015625
3
[]
no_license
--- title: Data Files --- # Data Files At the time of writing, there are only two data files the site draws from. 1. data/westlaw/settings.yml 2. data/checkpoint/settings.yml The settings file makes it possible to share the majority of code. For example the 'Application Frame' draws its top menu navigation from a partial: ``` src/includes/common/menus/top_menu.html ``` That partial is then able to access Checkpoint **or** Westlaw data and render the menu based on the values. The data looks like this: ```yaml top_menu: - title: Dashboard url: /pages/checkpoint/ icon: fi-home visibility: - title: Research url: /pages/checkpoint/research/search-templates/basic/ icon: fi-magnifying-glass visibility: - title: Workflow url: /pages/checkpoint/workflow/ icon: fi-graph-bar visibility: show-for-large-up etc... ``` The template logic is then able to loop through these values like so: ``` {% raw %} {% assign settings = site.data.checkpoint.settings %} {% for item in settings.top_menu %} <a href="{{ item.url }}">{{ item.title }}</a> {% endfor %} {% endraw %} ``` This would then output: ``` <a href="/pages/checkpoint/">Dashboard</a> <a href="/pages/checkpoint/research/search-templates/basic/">Research</a> <a href="/pages/checkpoint/workflow/">Workflow</a> ``` Most of the partials that make up the 'Application Frame' work this way with the exception of the **header.html** which is too specific to be shared. <br> <p class="text-center medium-text-right"> <a href="/docs/basics/assets/"><b>Next Up:</b> Assets →</a> </p>
Java
UTF-8
3,735
2.84375
3
[]
no_license
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ForgotPassword extends JFrame { private JPanel contentPane; private JTextField tfUserName; private JTextField tfAnswer; public ForgotPassword() { setTitle("Forgot Password"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 900, 700); contentPane = new JPanel(); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblForgetPassword = new JLabel("Forgot Password"); lblForgetPassword.setBounds(300, 58, 332, 58); lblForgetPassword.setFont(new Font("Times New Roman", Font.BOLD, 45)); contentPane.add(lblForgetPassword); JLabel lblEncryptPass = new JLabel(""); lblEncryptPass.setBounds(354, 449, 300, 36); lblEncryptPass.setForeground(Color.BLACK); lblEncryptPass.setFont(new Font("Times", Font.BOLD, 25)); contentPane.add(lblEncryptPass); JLabel lblUserName = new JLabel("Username:"); lblUserName.setBounds(232, 149, 152, 36); lblUserName.setFont(new Font("Times", Font.BOLD, 30)); contentPane.add(lblUserName); tfUserName = new JTextField(); tfUserName.setBounds(423, 149, 252, 36); tfUserName.setFont(new Font("Times", Font.PLAIN, 22)); tfUserName.setColumns(10); contentPane.add(tfUserName); JLabel lblSecQueMsg = new JLabel("Answer your security question (EXACT):"); lblSecQueMsg.setBounds(66, 228, 313, 36); lblSecQueMsg.setFont(new Font("Times", Font.BOLD, 17)); contentPane.add(lblSecQueMsg); JLabel lblSecQueAns = new JLabel("Answer:"); lblSecQueAns.setBounds(310, 306, 74, 41); lblSecQueAns.setForeground(Color.RED); lblSecQueAns.setFont(new Font("Lucida Grande", Font.BOLD, 18)); contentPane.add(lblSecQueAns); JLabel lblSecQue = new JLabel("What is the name of your pet?"); lblSecQue.setBounds(300, 273, 354, 28); contentPane.add(lblSecQue); lblSecQue.setFont(new Font("Lucida Grande", Font.BOLD, 23)); lblSecQue.setForeground(Color.RED); tfAnswer = new JTextField(); tfAnswer.setBounds(396, 307, 252, 42); tfAnswer.setForeground(Color.BLACK); tfAnswer.setFont(new Font("Lucida Grande", Font.BOLD, 17)); contentPane.add(tfAnswer); tfAnswer.setColumns(10); JButton btnRetPass = new JButton("Retrieve Password"); btnRetPass.setBounds(433, 360, 188, 36); btnRetPass.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String un = tfUserName.getText(); String ans = tfAnswer.getText(); if(un.equals("admin") && ans.equals("bruno")) { lblEncryptPass.setText("PASSWORD: Test1234$$"); } else { lblEncryptPass.setText("ERROR: Invalid Entries !"); } } }); btnRetPass.setBackground(Color.WHITE); btnRetPass.setFont(new Font("Lucida Grande", Font.PLAIN, 15)); btnRetPass.setForeground(Color.BLUE); contentPane.add(btnRetPass); JButton btnGoBack = new JButton("GO BACK to LOGIN"); btnGoBack.setBounds(396, 573, 175, 49); btnGoBack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { LoginMain lm = new LoginMain(); lm.setVisible(true); } }); btnGoBack.setFont(new Font("Lucida Grande", Font.PLAIN, 16)); contentPane.add(btnGoBack); JPanel pnlRetPass = new JPanel(); pnlRetPass.setBounds(310, 424, 383, 90); pnlRetPass.setBackground(Color.WHITE); contentPane.add(pnlRetPass); JLabel lblBackImg = new JLabel(""); lblBackImg.setBounds(0, 0, 900, 678); lblBackImg.setIcon(new ImageIcon("/Users/siddharth_agarwal/Desktop/java_eclipse/Horoscope_GUI/src/back1.jpg")); contentPane.add(lblBackImg); } public static void main(String[] args) { ForgotPassword frame = new ForgotPassword(); frame.setVisible(true); } }
Java
UTF-8
1,793
2.21875
2
[ "MIT" ]
permissive
package com.tikal.jenkins.plugins.multijob; import hudson.EnvVars; import hudson.Extension; import hudson.model.*; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import javax.annotation.Nonnull; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; @Restricted(NoExternalUse.class) public class MultiJobParametersAction extends ParametersAction { private List<ParameterValue> parameters; public MultiJobParametersAction(@Nonnull List<ParameterValue> parameters) { super(parameters); this.parameters = parameters; } public MultiJobParametersAction(ParameterValue... parameters) { this(Arrays.asList(parameters)); } @Override public List<ParameterValue> getParameters() { return Collections.unmodifiableList(parameters); } @Override public ParameterValue getParameter(String name) { for (ParameterValue parameter : parameters) { if (parameter != null && parameter.getName().equals(name)) { return parameter; } } return null; } @Extension public static final class MultiJobParametersActionEnvironmentContributor extends EnvironmentContributor { @Override public void buildEnvironmentFor(@Nonnull Run r, @Nonnull EnvVars envs, @Nonnull TaskListener listener) throws IOException, InterruptedException { MultiJobParametersAction action = r.getAction(MultiJobParametersAction.class); if (action != null) { for (ParameterValue p : action.getParameters()) { envs.putIfNotNull(p.getName(), String.valueOf(p.getValue())); } } } } }
Java
UTF-8
3,051
2.0625
2
[]
no_license
package cn.com.trade365.sxca_proxy_exchange.handler.impl; import cn.com.trade365.sxca_proxy_exchange.core.ObjectTypeEnum; import cn.com.trade365.sxca_proxy_exchange.core.Repositories; import cn.com.trade365.sxca_proxy_exchange.core.RestComponent; import cn.com.trade365.sxca_proxy_exchange.entity.RelationEntity; import cn.com.trade365.sxca_proxy_exchange.entity.ResultData; import cn.com.trade365.sxca_proxy_exchange.exception.ExchangeException; import cn.com.trade365.sxca_proxy_exchange.handler.MessageHandler; import cn.com.trade365.sxca_proxy_exchange.handler.MsgEvent; import cn.com.trade365.platform.project.dto.PrjTenderFileDto; import cn.com.trade365.sxca_proxy_exchange.service.IdRelationService; import cn.com.trade365.sxca_proxy_exchange.service.TenderFileService; import com.alibaba.fastjson.JSON; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.stereotype.Component; import java.util.Map; /** * 招标项目数据同步 */ @Component public class TenderFileMessageHandler implements MessageHandler{ @Autowired private RestComponent restComponent; @Autowired private TenderFileService tenderFileService; @Autowired private IdRelationService idRelationService; @Override public void handleMessage(MsgEvent msgEvent) throws ExchangeException { try { Map<String, String> data = msgEvent.getData(); String tenderFileSectionId = data.get("tenderFileSectionId"); if (idRelationService.isExitDataId(ObjectTypeEnum.TENDER_FILE, tenderFileSectionId)) { throw new ExchangeException(ObjectTypeEnum.TENDER_FILE.getCode() + "重复推送数据"); } PrjTenderFileDto prjTenderFile = tenderFileService.getTenderFileData(tenderFileSectionId); prjTenderFile.setPlatformCode(msgEvent.getPlatformCode()); prjTenderFile.setSourceId(tenderFileSectionId); ResultData<Long> resultData = restComponent.post( Repositories.COMM_PREFIX + Repositories.TENDER_FILE_SAVE_URL, prjTenderFile, new ParameterizedTypeReference<ResultData<Long>>() { }); //关系表存储 if(null == resultData.getData()) { throw new ExchangeException("推送失败; " + resultData.getMessage()); } RelationEntity relationEntity = new RelationEntity(); relationEntity.setCode(ObjectTypeEnum.TENDER_FILE.getCode()); relationEntity.setTradeId(tenderFileSectionId); relationEntity.setDataId(resultData.getData()); relationEntity.setData(JSON.toJSONString(prjTenderFile)); idRelationService.relation(relationEntity); }catch (Exception ex){ throw new ExchangeException("调用失败",ex); } } @Override public String getHandleName() { return MsgEvent.TENDER_FILE_MESSAGE_EVENT; } }
C#
UTF-8
8,292
2.5625
3
[ "BSD-3-Clause", "CC-BY-3.0", "FTL", "Zlib", "Bitstream-Vera", "MPL-2.0", "curl", "MIT", "OFL-1.1", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; // TODO: Add comments describing what this class does. It is not obvious. namespace Godot { public static partial class GD { public static object Bytes2Var(byte[] bytes, bool allowObjects = false) { return godot_icall_GD_bytes2var(bytes, allowObjects); } public static object Convert(object what, VariantType type) { return godot_icall_GD_convert(what, type); } public static float Db2Linear(float db) { return (float)Math.Exp(db * 0.11512925464970228420089957273422); } public static float DecTime(float value, float amount, float step) { float sgn = Mathf.Sign(value); float val = Mathf.Abs(value); val -= amount * step; if (val < 0) val = 0; return val * sgn; } public static int Hash(object var) { return godot_icall_GD_hash(var); } public static Object InstanceFromId(ulong instanceId) { return godot_icall_GD_instance_from_id(instanceId); } public static float Linear2Db(float linear) { return (float)(Math.Log(linear) * 8.6858896380650365530225783783321); } public static Resource Load(string path) { return ResourceManager.Load(path); } public static T Load<T>(string path) where T : class { return ResourceManager.Load<T>(path); } public static void PushError(string message) { godot_icall_GD_pusherror(message); } public static void PushWarning(string message) { godot_icall_GD_pushwarning(message); } public static void Print(params object[] what) { godot_icall_GD_print(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null")); } public static void PrintStack() { Print(System.Environment.StackTrace); } public static void PrintErr(params object[] what) { godot_icall_GD_printerr(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null")); } public static void PrintRaw(params object[] what) { godot_icall_GD_printraw(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null")); } public static void PrintS(params object[] what) { godot_icall_GD_prints(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null")); } public static void PrintT(params object[] what) { godot_icall_GD_printt(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null")); } public static float Randf() { return godot_icall_GD_randf(); } public static uint Randi() { return godot_icall_GD_randi(); } public static void Randomize() { godot_icall_GD_randomize(); } public static double RandRange(double from, double to) { return godot_icall_GD_rand_range(from, to); } public static uint RandSeed(ulong seed, out ulong newSeed) { return godot_icall_GD_rand_seed(seed, out newSeed); } public static IEnumerable<int> Range(int end) { return Range(0, end, 1); } public static IEnumerable<int> Range(int start, int end) { return Range(start, end, 1); } public static IEnumerable<int> Range(int start, int end, int step) { if (end < start && step > 0) yield break; if (end > start && step < 0) yield break; if (step > 0) { for (int i = start; i < end; i += step) yield return i; } else { for (int i = start; i > end; i += step) yield return i; } } public static void Seed(ulong seed) { godot_icall_GD_seed(seed); } public static string Str(params object[] what) { return godot_icall_GD_str(what); } public static object Str2Var(string str) { return godot_icall_GD_str2var(str); } public static bool TypeExists(StringName type) { return godot_icall_GD_type_exists(StringName.GetPtr(type)); } public static byte[] Var2Bytes(object var, bool fullObjects = false) { return godot_icall_GD_var2bytes(var, fullObjects); } public static string Var2Str(object var) { return godot_icall_GD_var2str(var); } public static VariantType TypeToVariantType(Type type) { return godot_icall_TypeToVariantType(type); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_GD_bytes2var(byte[] bytes, bool allowObjects); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_GD_convert(object what, VariantType type); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_GD_hash(object var); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static Object godot_icall_GD_instance_from_id(ulong instanceId); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_print(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_printerr(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_printraw(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_prints(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_printt(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static float godot_icall_GD_randf(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static uint godot_icall_GD_randi(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_randomize(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static double godot_icall_GD_rand_range(double from, double to); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static uint godot_icall_GD_rand_seed(ulong seed, out ulong newSeed); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_seed(ulong seed); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_GD_str(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_GD_str2var(string str); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static bool godot_icall_GD_type_exists(IntPtr type); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static byte[] godot_icall_GD_var2bytes(object what, bool fullObjects); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_GD_var2str(object var); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_pusherror(string type); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_pushwarning(string type); [MethodImpl(MethodImplOptions.InternalCall)] private static extern VariantType godot_icall_TypeToVariantType(Type type); } }
Java
UTF-8
2,347
3.1875
3
[ "MIT" ]
permissive
/* * 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 keyboardhero; import java.awt.Color; import java.awt.Font; import java.io.IOException; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; /** * * @author Dank * This is the UI tab that shows the high scores */ public class HighScoreTab extends KeyboardHeroTab { // Constructor for the high score tab public HighScoreTab() { super(); // Set tab name this.tabName = "High Scores"; } @Override // Initially renders the tab public void initializeTabRendering() { // Clear the UI this.removeAll(); // Add an empty border to add padding around text this.setBorder(new EmptyBorder(0, Constants.WINDOW_WIDTH / 4, 0, Constants.WINDOW_WIDTH / 4)); this.setBackground(Color.decode(Constants.BACKGROUND_COLOR_RGB)); // Set up simple header JLabel header = new JLabel("High Scores"); header.setFont(new Font("Arial", Font.BOLD, 40)); this.add(header); // ADd a button to refresh high scores with the event listener JButton highScoreRefreshButton = new JButton("Refresh"); highScoreRefreshButton.addMouseListener(new HighScoreRefreshListener(this)); this.add(highScoreRefreshButton); // Read high scores from file and append to the end JTextArea textArea = new JTextArea(); textArea.setEditable(false); // Attempt to read high scores from CSV String highScoreText = ""; try { highScoreText = HighScoreReaderWriter.readHighScoresString(); } catch (IOException ex) { System.out.println("Could not read high scores"); } // set the high score tex area textArea.setText(highScoreText); textArea.setBackground(Color.decode(Constants.BACKGROUND_COLOR_RGB)); textArea.setFont(new Font("Arail", Font.PLAIN, 16)); // Add the text! this.add(textArea); } }
JavaScript
UTF-8
1,426
3.359375
3
[]
no_license
const form = document.querySelector("#contactForm"); const fName = document.querySelector("#fname"); const fNameError = document.querySelector(".fNameError"); const lName = document.querySelector("#lname"); const lNameError = document.querySelector(".lNameError"); const email = document.querySelector("#email"); const emailError = document.querySelector(".emailError"); const message = document.querySelector("#textarea"); const messageError = document.querySelector(".textError"); function validateForm(event) { event.preventDefault(); if (checkLength(fName.value, 2) === true ) { fNameError.style.display ="none"; } else { fNameError.style.display ="block"; } if (checkLength(lName.value, 4) === true ) { lNameError.style.display ="none"; } else { lNameError.style.display ="block"; } if (validateEmail(email.value) === true) { emailError.style.display ="none"; } else { emailError.style.display ="block"; } if (checkLength(message.value, 10) === true ) { messageError.style.display ="none"; } else { messageError.style.display ="block"; } } form.addEventListener("submit", validateForm); function checkLength(value, len) { if (value.trim().length >= len) { return true; } else { return false; } } function validateEmail(email) { const regEx = /\S+@\S+\.\S+/; const patternMatches = regEx.test(email); return patternMatches; }