language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
575
1.773438
2
[]
no_license
public ServiceDescription describe() { ServiceDescription.Builder sd = new ServiceDescription.Builder(NAME, Validate.class.getCanonicalName()); sd.classname(this.getClass().getCanonicalName()); sd.description("Validation service based on PngCheck."); sd.author("Fabian Steeg"); sd.inputFormats(PNG_PRONOM.toArray(new URI[] {})); sd.tool(Tool.create(null, "PngCheck", null, null, "http://www.libpng.org/pub/png/apps/pngcheck.html")); sd.serviceProvider("The Planets Consortium"); return sd.build(); }
C
UTF-8
246
2.703125
3
[]
no_license
#include <stdio.h> #include <string.h> int main(void){ char s[25]; int x,i; scanf("%s",s); x=strlen(s); FILE* f=fopen("/tmp/arq.txt","w"); for(i=0;i<x;i++){ fputc(s[i],f); } fclose(f); return 0; }
PHP
UTF-8
864
2.578125
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; class Cart extends Model { // protected $fillable = [ 'user_id', 'total' ]; public function cartItems() { return $this->hasMany(CartItem::class, 'cart_id','id'); } public static function getCartCount() { if (Auth::check()) { $cart = Cart::where('user_id', Auth::user()->id)->first(); if($cart){ $cartItems = CartItem::where('cart_id', $cart->id)->get(); $count = 0; foreach($cartItems as $cartItem) { $count += $cartItem->quantity; } if($count > 0) return $count; else return 0; } else return 0; } else { return 0; } } }
Python
UTF-8
9,966
2.59375
3
[]
no_license
import Phase3Task5 import numpy as np from scipy.spatial import distance import heapq import os def getNeighboursFromBucket(binned_values,hash_table,no_layers,no_hashes): neighbours = set() for i in range(no_layers): hash_key_list = binned_values[0,i*no_hashes:(i+1)*no_hashes].tolist() hash_key_str = ','.join(str(c) for c in hash_key_list) try: neighbours = neighbours.union(set(hash_table[i][hash_key_str])) # print(neighbours) except: #print("No such bucket") pop=1 return neighbours def getNeighbours(binned_values,hash_table,no_layers,no_hashes,layer_no): neighbours = set() hash_key_list = binned_values[0,layer_no*no_hashes:(layer_no+1)*no_hashes].tolist() hash_key_str = ','.join(str(c) for c in hash_key_list) try: neighbours = neighbours.union(set(hash_table[layer_no][hash_key_str])) # print(neighbours) except: #print("No such bucket") pop=1 return neighbours def getKNN(visual_vectors, t_neighbours_set, t, query_index, index_to_data_ids): distance_list=[] sorted_distance_IDs=[] for index in t_neighbours_set: key = str(index_to_data_ids[index]) dist = distance.euclidean(visual_vectors[index], visual_vectors[query_index]) distance_list.append([key,dist]) sorted_distances=sorted(distance_list,key =lambda k: k[1]) for item in sorted_distances[:t]: sorted_distance_IDs.append(item[0]) return sorted_distance_IDs def perturbationScores(projected_vector,no_layers,no_hashes,bin_size): not_floored_binned_values = np.divide(projected_vector,bin_size) binned_values = np.floor(not_floored_binned_values) one_minus =projected_vector - (binned_values * bin_size) one_plus = bin_size - one_minus perturbation_scores={} for i in range(no_layers): perturbation_scores[i] = [] for j in range(i*no_hashes,(i+1)*no_hashes): ## element = list(score,index in binned values, 1/-1, layerno) element = [one_minus[0,j], j, -1, i] perturbation_scores[i].append(element) element = [one_plus[0,j], j, 1, i] perturbation_scores[i].append(element) for i in range(no_layers): perturbation_scores[i] = sorted(perturbation_scores[i],key =lambda k: k[0]) return perturbation_scores def shiftOperation(minimum_perturb_indices,perturbation_scores): indices_list = minimum_perturb_indices[1].copy() indices_list[-1] = indices_list[-1] + 1 new_score = 0 layer_no = minimum_perturb_indices[2] for index in indices_list: new_score = new_score + perturbation_scores[layer_no][index][0] new_minimum_perturb_indices = (new_score, indices_list, layer_no) return new_minimum_perturb_indices def expandOperation(minimum_perturb_indices,perturbation_scores): indices_list = minimum_perturb_indices[1].copy() indices_list.append(indices_list[-1]+1) new_score = 0 layer_no = minimum_perturb_indices[2] for index in indices_list: new_score = new_score + perturbation_scores[layer_no][index][0] new_minimum_perturb_indices = (new_score, indices_list, layer_no) return new_minimum_perturb_indices def checkValidity(minimum_perturb_indices,bin_size,perturbation_scores,no_hashes): indices_list = minimum_perturb_indices[1] exist_set = set() for index in indices_list: if index>=2*no_hashes: #print("Invalid") return False layer = minimum_perturb_indices[2] if perturbation_scores[layer][index][1] in exist_set: #print("Invalid") return False exist_set.add(index) return True min_heap = [] heap_set = set() def generatePerturbationVectors(no_layers,no_hashes,perturbation_scores,bin_size): while (True): minimum_perturb_indices = heapq.heappop(min_heap) try: shifted_minimum_perturb_indices = shiftOperation(minimum_perturb_indices,perturbation_scores) key = str(shifted_minimum_perturb_indices[0])+"+"+str(shifted_minimum_perturb_indices[1])+"+"+str(shifted_minimum_perturb_indices[2]) if key not in heap_set: heapq.heappush(min_heap,shifted_minimum_perturb_indices) heap_set.add(key) except: #print("shift fail") loka=1 try: expanded_minimum_perturb_indices = expandOperation(minimum_perturb_indices,perturbation_scores) key = str(expanded_minimum_perturb_indices[0])+"+"+str(expanded_minimum_perturb_indices[1])+"+"+str(expanded_minimum_perturb_indices[2]) if key not in heap_set: heapq.heappush(min_heap,expanded_minimum_perturb_indices) heap_set.add(key) except: #print("expand fail") loka=1 heapq.heapify(min_heap) if checkValidity(minimum_perturb_indices,bin_size,perturbation_scores,no_hashes) == True: break; return minimum_perturb_indices def applyPerturbation(perturbation_indices,binned_values,perturbation_scores,no_hashes): indices = perturbation_indices[1] layer = perturbation_indices[2] for index in indices: index_in_binned_values = perturbation_scores[layer][index][1] binned_values[0,index_in_binned_values] = binned_values[0,index_in_binned_values] + perturbation_scores[layer][index][2] return binned_values def findSimilarHash(hash_table,binned_values, hash_keys,no_layers, no_hashes): similar_hashes = [] for i in range(no_layers): for hash_key in hash_keys[i]: #print("No of elements in hash table"+str(i)) #print(len(hash_keys[i])) if np.array_equal(np.array(hash_key), binned_values[0,i*no_hashes:(i+1)*no_hashes]) == False: sim = distance.euclidean(np.array(hash_key), binned_values[0,i*no_hashes:(i+1)*no_hashes]) ##### [similarity, key as a list, layer_no] similar_hashes.append([sim, np.array(hash_key), i]) similar_hashes = sorted(similar_hashes,key =lambda k: k[0]) return similar_hashes def findDirectory(imageID): path = "" for subdir, dirs, files in os.walk('../img'): for file in files: if imageID in file: path = os.path.join(subdir, file) break return path def visualize(query_ID, sorted_distance_IDs): page = open('task5Visualization.html','w') content = """<html><head></head><body>""" content += "<table style=\"border: 2px solid black; margin:10px;\">" \ "<tr><th style=\"border: 2px solid black; margin:10px;\">Query" + "</th>" \ "<th style=\"border: 2px solid black; margin:10px;\">Similar Images" + "</th></tr>" content += "<tr><td style=\"border: 2px solid black; margin:10px;vertical-align: top;\">" content += "<figure>" \ "<img src=\"" + findDirectory(str(query_ID)+".jpg") + "\"style=\"height:30%; width:30%;\"><br>" \ "<figcaption>" + str(query_ID) + "</figcaption>" \ "</figure>" content += "</td><td style=\"border: 2px solid black; margin:10px;vertical-align: top;\">" for i in range(len(sorted_distance_IDs)): content += "<figure>" \ "<img src=\"" + findDirectory(str(sorted_distance_IDs[i])+".jpg") + "\"style=\"height:30%; width:30%;\"><br>" \ "<figcaption>" + str(sorted_distance_IDs[i]) + "</figcaption>" \ "</figure>" content += "</td></tr>" content += "</table>" content += """</body></html>""" page.write(content) page.close() return def main(image_id,t,hash_table,data_ids_to_index,no_layers,no_hashes,rand_vectors,visual_vectors,bin_size, hash_keys): t_neighbours_set = set() index = data_ids_to_index[image_id] vector = np.reshape(visual_vectors[index][:],(1,-1)) total_images = 0 projected_vector = Phase3Task5.projectToVectors(rand_vectors,vector) perturbation_scores = perturbationScores(projected_vector,no_layers,no_hashes,bin_size) binned_values = Phase3Task5.putInBins(projected_vector,bin_size) for i in range(no_layers): #### heap contains the following tuple (score,[indices],layer_no) min_heap.append((perturbation_scores[i][0][0],[0],i)) heap_set.add(str(perturbation_scores[i][0][0])+"+"+str([0])+"+"+str(i)) heapq.heapify(min_heap) flag=0 while(len(t_neighbours_set) < int(t)): if flag == 0: neighbours_set = getNeighboursFromBucket(binned_values,hash_table,no_layers,no_hashes) flag=1 elif flag == 1: neighbours_set = getNeighbours(binned_values,hash_table,no_layers,no_hashes,layer_no) print("Found "+str(len(neighbours_set))+" neighbours in nearby bucket") total_images = len(neighbours_set) + total_images t_neighbours_set = t_neighbours_set.union(neighbours_set) perturbation_indices = generatePerturbationVectors(no_layers,no_hashes,perturbation_scores,bin_size) binned_values = applyPerturbation(perturbation_indices,binned_values,perturbation_scores,no_hashes) layer_no = perturbation_indices[2] # ####### Second Method # neighbours_set = getNeighboursFromBucket(binned_values,hash_table,no_layers,no_hashes) # t_neighbours_set = neighbours_set # total_images = len(t_neighbours_set) # if (len(neighbours_set) < int(t)): # print("Finding similar buckets") # similar_hashes = findSimilarHash(hash_table, binned_values, hash_keys, no_layers, no_hashes) # i=1 # while(len(t_neighbours_set) < int(t)): # print("New neighbours size"+str(len(t_neighbours_set))) # most_similar_hash = similar_hashes[i][1] # most_similar_hash_layer = similar_hashes[i][2] # new_binned_values = binned_values # new_binned_values[0,most_similar_hash_layer*no_hashes:(most_similar_hash_layer+1)*no_hashes] = most_similar_hash # neighbours_set = getNeighboursFromBucket(new_binned_values, hash_table, no_layers, no_hashes) # total_images = len(neighbours_set) + total_images # t_neighbours_set = t_neighbours_set.union(neighbours_set) # i = i+1 index_to_data_ids = {v: k for k, v in data_ids_to_index.items()} sorted_distance_IDs = getKNN(visual_vectors, t_neighbours_set, t, index, index_to_data_ids) print("Unique images searched through: "+str(len(t_neighbours_set))) print("Total images searched through: "+str(total_images)) print("Done") print("Writing to html file") visualize(image_id, sorted_distance_IDs)
C#
UTF-8
532
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PrOb3Music { class MusicPlayer { public List<Song> playlist = new List<Song>(); public void Add(Song song) { playlist.Add(song); } public void Remove(int songNumber) { playlist.RemoveAt(songNumber); } public void Play(int songNumber) { playlist[songNumber].Play(); } } }
C
GB18030
2,198
4
4
[]
no_license
/* ļ:ṹǶһָ ߣlqa ༭ʱ䣺20180125 */ #include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct Teacher { char name[64]; char* alisname; int age; int id; }Teacher; /* ӡ */ void PrintTeacher(Teacher* array, int num) { for (int i = 0; i < 3; i++) { printf("age : %d \n", array[i].age); } } /* */ void SortTeacher(Teacher* array, int num) { Teacher tmp; for (int i = 0; i < num; i++) { for (int j = i + 1; j < num; j++) { if (array[i].age > array[j].age) { tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } } } /* Ϸڴ */ Teacher* CreateTeacher01(int num) { Teacher* tmp = NULL; tmp = (Teacher*)malloc(sizeof(Teacher) * num);//൱Teacher Array[num] if (tmp == NULL) { return NULL; } return tmp; } int CreateTeacher(Teacher** pT, int num) { Teacher* tmp = NULL; tmp = (Teacher*)malloc(sizeof(Teacher) * num);//൱Teacher Array[num] if (tmp == NULL) { return -1; } memset(tmp, 0, sizeof(Teacher) * num); //ڴ for ( int i =0; i < num; i++ ) { tmp[i].alisname = (char *)malloc(60); } *pT = tmp;//ָβ ȥ޸ ʵεֵ return 0; } /* ͷڴ溯 */ void FreeTeacher(Teacher *p, int num) { if (p == NULL) { return; } for ( int i = 0; i < num; i++ ) { if ( p[i].alisname != NULL ) { free(p[i].alisname); } } free(p); } /* ṹ飬ʦ䣬 */ int main05() { int ret = 0; int i = 0; //Teacher Array[3];//ջϷڴ Teacher* pArray = NULL; int num = 3; ret = CreateTeacher(&pArray, num); if ( ret != 0 ) { printf("func createTeacher()error:%d\n", ret); } for (i = 0; i < num; i++) { printf("\nplease enter age:"); scanf("%d", &(pArray[i].age)); printf("\nplease enter name:"); scanf("%s", pArray[i].name);//ָָڴcopy printf("\nplease enter alias:"); scanf("%s", pArray[i].alisname); } PrintTeacher(pArray, num); SortTeacher(pArray, num); printf("֮\n"); PrintTeacher(pArray, num); FreeTeacher(pArray, num); system("pause"); return 0; }
Java
UTF-8
785
2.625
3
[]
no_license
package com.sattrak.rpi.serial; public class OrientationReadPacket extends SerialPacket { // =============================== // CONSTRUCTORS // =============================== public OrientationReadPacket() { setCommand(SerialCommand.READ_ORIENTATION); } public OrientationReadPacket(byte[] packetBytes) throws InvalidPacketException { fromBytes(packetBytes); } // =============================== // OVERRIDDEN METHODS // =============================== @Override protected byte[] argsToBytes() { // Return an empty byte array because there are no arguments return new byte[0]; } @Override protected void bytesToArgs(byte[] argBytes) { // Do nothing because there are no arguments } @Override protected String argsToString() { return ""; } }
C
UTF-8
1,959
2.953125
3
[]
no_license
// // Created by Dell on 2018/8/17. // #include "heuristic_func.h" #include "structure.h" struct activity min_sk(struct activity_set * set) { int min = INF; int index = 0; for (int i = 0; i < set->length; ++i) { int temp = set->queue[i].lft - set->queue[i].est - set->queue[i].durations; if (temp < min) { min = temp; index = i; } } return set->queue[index]; } struct activity min_lft(struct activity_set *set) { int min = INF; int index = 0; for (int i = 0; i < set->length; ++i) { int temp = set->queue[i].lft; if (temp < min) { min = temp; index = i; } } return set->queue[index]; } struct activity min_spt(struct activity_set *set) { int min = INF; int index = 0; for (int i = 0; i < set->length; ++i) { int temp = set->queue[i].durations; if (temp < min) { min = temp; index = i; } } return set->queue[index]; } struct activity min_lst(struct activity_set *set) { int min = INF; int index = 0; for (int i = 0; i < set->length; ++i) { int temp = set->queue[i].lft - set->queue[i].durations; if (temp < min) { min = temp; index = i; } } return set->queue[index]; } struct activity min_est(struct activity_set *set) { int min = INF; int index = 0; for (int i = 0; i < set->length; ++i) { int temp = set->queue[i].est; if (temp < min) { min = temp; index = i; } } return set->queue[index]; } struct activity min_eft( struct activity_set *set) { int min = INF; int index = 0; for (int i = 0; i < set->length; ++i) { int temp = set->queue[i].est + set->queue[i].durations; if (temp < min) { min = temp; index = i; } } return set->queue[index]; }
Shell
UTF-8
403
3.296875
3
[]
no_license
#!/bin/sh echo "*****SYSTEM ENVIRONMENT PROFILE INFORMATION *****" internalDirectory=$directory cd $directory touch systemenvironment.txt echo "*****SYSTEM ENVIRONMENT PROFILE INFORMATION *****">>systemenvironment.txt var1=`cat /etc/profile` if [ "$var1" = "" ];then echo "Error Detected" else echo "The local system environment iis as follows \n $var1" echo "$var1">>systemenvironment.txt fi
Markdown
UTF-8
624
3.078125
3
[ "MIT" ]
permissive
# gitem ## A command for git workflow automation ### Usage ##### Just type the following command in your terminal to automatically push all changes in your git project to the currently checked out branch of your local and remote repositories. ```shell gitem '<your commit message>' ``` ### Installation ##### Add the following code to the end of your ~/.bashrc file ```sh gitem () { git add -A git commit -m "$1" branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p') git push origin $branch } ``` ##### Then run the following in your terminal ```shell source ~/.bashrc ``` ### That's it! You're good to go!
PHP
UTF-8
9,810
2.515625
3
[]
no_license
<?php include 'engine.php'; $getDataCity = new getDataCity(); $reporting = new reporting(); if (isset($_POST['provincesId'])) { $decode = json_decode($_POST['provincesId'], true); $provincesId = $decode['post']['provincesId']; print_r($getDataCity->select($provincesId)); }elseif (isset($_POST['request'])) { $decode = json_decode($_POST['request'], true); $param=$decode['request']; //print_r($param); foreach ($param as $keyParam => $valueParam) { if ($valueParam['typeOfReportingId']==1) { $maxDate = $valueParam['maxDate']; $minDate = $valueParam['minDate']; $offset = $valueParam['offset']; $rows = $valueParam['rows']; //print_r(json_encode($valueParam['convertReporting']['convertReportingStat'])) ; if ($valueParam['convertReporting']['convertReportingStat']==true) { $result = $reporting->selectTrx($minDate,$maxDate,$offset,$rows); $decode = json_decode($result,true); $dataCell = $decode['response']['data']; if ($decode['response']['success']==true) { if ($valueParam['convertReporting']['typeReporting']=='pdf') { #setting judul laporan dan header tabel $judul = "LAPORAN DATA DATA TRANSAKSI IKLANIN AJA .COM"; $header = array( array("label"=>"NO", "length"=>30, "align"=>"C"), array("label"=>"CONTRACT ID", "length"=>50, "align"=>"C"), array("label"=>"PAYMENT DATE", "length"=>50, "align"=>"C"), array("label"=>"TOTAL PAYMENT", "length"=>50, "align"=>"C") ); #sertakan library FPDF dan bentuk objek require_once ("../fpdf/fpdf.php"); $pdf = new FPDF(); $pdf->AddPage(); #tampilkan judul laporan $pdf->SetFont('Arial','B','16'); $pdf->Cell(0,20, $judul, '0', 1, 'C'); #buat header tabel $pdf->SetFont('Arial','','10'); $pdf->SetFillColor(255,0,0); $pdf->SetTextColor(255); $pdf->SetDrawColor(128,0,0); foreach ($header as $valueHeader) { $pdf->Cell($valueHeader['length'], 5, $valueHeader['label'], 1, '0', $valueHeader['align'], true); } $pdf->Ln(); #tampilkan data tabelnya $pdf->SetFillColor(224,235,255); $pdf->SetTextColor(0); $pdf->SetFont(''); $fill=false; //print_r($dataCell); foreach ($dataCell as $keyCell => $cell) { //print_r($cell['id']); $pdf->Cell(30, 5, ($keyCell+1), 1, '0', 'L', $fill); $pdf->Cell(50, 5, $cell['contractId'], 1, '0', 'L', $fill); $pdf->Cell(50, 5, $cell['paymentDate'], 1, '0', 'L', $fill); $pdf->Cell(50, 5, $cell['totalPayment']." ".$cell['curencyCode'], 1, '0', 'L', $fill); $pdf->Ln(); } #output file PDF $pdf->Output('D','reporting.pdf'); }elseif ($valueParam['convertReporting']['typeReporting']=='excel') { function convertToExcel(){ include '../lib/Classes/PHPExcel.php'; /*start - BLOCK PROPERTIES FILE EXCEL*/ $file = new PHPExcel (); /*end - BLOCK PROPERTIES FILE EXCEL*/ /*start - BLOCK SETUP SHEET*/ $file->createSheet ( NULL,0); $file->setActiveSheetIndex ( 0 ); $sheet = $file->getActiveSheet ( 0 ); //memberikan title pada sheet $sheet->setTitle ( "Nilai" ); /*end - BLOCK SETUP SHEET*/ /*start - BLOCK HEADER*/ $sheet ->setCellValue ( "A1", "No" ) ->setCellValue ( "B1", "No. Peserta" ) ->setCellValue ( "C1", "Nama" ) ->setCellValue ( "D1", "Tempat Lahir" ) ->setCellValue ( "E1", "Tanggal Lahir" ) ->setCellValue ( "F1", "TS Awal" ) ->setCellValue ( "G1", "TS Akhir" ) ->setCellValue ( "H1", "Kaidah" ) ->setCellValue ( "I1", "Tradisional" ) ->setCellValue ( "J1", "Prasetya" ) ->setCellValue ( "K1", "Beladiri Praktis" ) ->setCellValue ( "L1", "Fisik Teknik" ) ->setCellValue ( "M1", "Aerobik Tes" ) ->setCellValue ( "N1", "Kuda-Kuda Dasar" ) ->setCellValue ( "O1", "Serang Hindar" ) ->setCellValue ( "P1", "Total" ); /*end - BLOCK HEADER*/ /* start - BLOCK MEMBUAT LINK DOWNLOAD*/ /* header ( 'Content-Type: application/vnd.ms-excel' ); //namanya adalah keluarga.xls header ( 'Content-Disposition: attachment;filename="nilai.xls"' ); //header ( 'Cache-Control: max-age=0' ); header ( 'Content-Transfer-Encoding: binary' ); header('Cache-Control: no-cache'); header('Pragma: no-cache'); header('Connection: close'); */ //header('Content-Type: application/x-download'); $writer = PHPExcel_IOFactory::createWriter ( $file, 'Excel5' ); //echo $writer; //exit; // var_dump($objWriter); header ( 'Content-Type: application/vnd.ms-excel' ); header('Content-Disposition: attachment; filename="nilai.xls"'); header('Cache-Control: private, max-age=0, must-revalidate'); $writer->save( 'php://output' ); /* start - BLOCK MEMBUAT LINK DOWNLOAD*/ //return false; } convertToExcel(); }else { $rows = $valueParam ['rows']; $result = $reporting->selectTrx($minDate,$maxDate,$offset,$rows); print_r($result); } } }elseif ($valueParam['convertReporting']['convertReportingStat']==false) { $rows = $valueParam ['rows']; $result = $reporting->selectTrx($minDate,$maxDate,$offset,$rows); print_r($result); } }elseif ($valueParam['typeOfReportingId']==2) { $maxDate = $valueParam['maxDate']; $minDate = $valueParam['minDate']; $offset = $valueParam['offset']; $rows = $valueParam['rows']; if ($valueParam['convertReporting']['convertReportingStat']==true) { $result = $reporting->selectClick($minDate,$maxDate,$offset,$rows); $decode = json_decode($result,true); if ($decode['response']['success']==true) { if ($valueParam['convertReporting']['typeReporting']=='pdf') { #setting judul laporan dan header tabel $judul = "LAPORAN DATA DATA TRANSAKSI IKLANIN AJA .COM"; $header = array( array("label"=>"NO", "length"=>30, "align"=>"C"), array("label"=>"ADS ID", "length"=>50, "align"=>"C"), array("label"=>"DATE", "length"=>50, "align"=>"C"), array("label"=>"TOTAL CLICK", "length"=>50, "align"=>"C") ); #sertakan library FPDF dan bentuk objek require_once ("../fpdf/fpdf.php"); $pdf = new FPDF(); $pdf->AddPage(); #tampilkan judul laporan $pdf->SetFont('Arial','B','16'); $pdf->Cell(0,20, $judul, '0', 1, 'C'); #buat header tabel $pdf->SetFont('Arial','','10'); $pdf->SetFillColor(255,0,0); $pdf->SetTextColor(255); $pdf->SetDrawColor(128,0,0); foreach ($header as $valueHeader) { $pdf->Cell($valueHeader['length'], 5, $valueHeader['label'], 1, '0', $valueHeader['align'], true); } $pdf->Ln(); #tampilkan data tabelnya $pdf->SetFillColor(224,235,255); $pdf->SetTextColor(0); $pdf->SetFont(''); $fill=false; $dataCell = $decode['response']['data']; //print_r($dataCell); foreach ($dataCell as $keyCell => $cell) { //print_r($cell); $pdf->Cell(30, 5, ($keyCell+1), 1, '0', 'L', $fill); $pdf->Cell(50, 5, $cell['adsId'], 1, '0', 'L', $fill); $pdf->Cell(50, 5, $cell['date'], 1, '0', 'L', $fill); $pdf->Cell(50, 5, $cell['totalClick'], 1, '0', 'L', $fill); $pdf->Ln(); } #output file PDF $pdf->Output('D','reporting.pdf'); }else { $rows = $valueParam ['rows']; $result = $reporting->selectClick($minDate,$maxDate,$offset,$rows); print_r($result); } } }elseif ($valueParam['convertReporting']['convertReportingStat']==false) { $rows = $valueParam ['rows']; $result = $reporting->selectClick($minDate,$maxDate,$offset,$rows); print_r($result); } } } } ?>
C#
UTF-8
1,767
2.765625
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using HOTELMANAGEMENTWEBAPI.Models; namespace HOTELMANAGEMENTWEBAPI.Controllers { public class ProductController : ApiController { ImageEntities db = new ImageEntities(); // POST api/<controller> [HttpPost] public HttpResponseMessage Post(Product p) { if (HttpContext.Current.Request.Files.Count == 0) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //Read the File data from Request.Form collection. HttpPostedFile postedFile = HttpContext.Current.Request.Files[0]; //Convert the File data to Byte Array. byte[] bytes; using (BinaryReader br = new BinaryReader(postedFile.InputStream)) { bytes = br.ReadBytes(postedFile.ContentLength); } //Insert the File to Database Table. //Product employee = new Product(); //Product img = new Product(); //img.ImageID = p.ImageID; // img.ImageName = Path.GetFileName(postedFile.FileName); // img.ImageSrc = bytes; // db.Products.Add(img); // db.SaveChanges(); Product img = new Product() { ImageName = Path.GetFileName(postedFile.FileName), ImageSrc = bytes, ImageID = p.ImageID }; db.Products.Add(img); db.SaveChanges(); return new HttpResponseMessage(HttpStatusCode.OK); } } }
Java
UTF-8
211
2.34375
2
[]
no_license
package package1; public class WrongLoginException extends RuntimeException { public WrongLoginException() { } public WrongLoginException(String message) { System.out.println(message); } }
Python
UTF-8
1,843
2.65625
3
[]
no_license
#!/usr/bin/env python import sys, glob allKeys = [] allVals = [] ignoreKeys = ["uid", "form_name"] if len(sys.argv) is 0: sys.exit(-1) def addVal(key, val): vals[key] = val.replace(",", "&#44;") try: allKeys.index(key) except ValueError: allKeys.append(key) def processFile(filename, key_pre = "", key_post = ""): """Reads in a file of key: value pairs and generates a hash from them.""" inFile = open(filename, 'r') for line in inFile: val = line.rstrip().split(": ") if len(val) > 1 or line.find(":") > -1: try: ignoreKeys.index(val[0]) except ValueError: currentKey = key_pre + val[0] + key_post try: addVal(currentKey, val[1]) except IndexError: pass else: vals[currentKey] += "&#10;" + val[0].replace(",", "&#44;") inFile.close() processedIds = {} for filename in sys.argv[1:]: vals = {} addVal("id", filename.split(" - ")[0]) if processedIds.has_key(vals["id"]): continue files = glob.glob("%s - *.txt" % vals['id']) for idFile in files: splitName = idFile.split(" - ") shortname = splitName[1].split(" ")[0] if len(splitName) > 3: trialId = "_" + splitName[2] else: trialId = "" processFile(idFile, shortname + "_", trialId) processedIds[vals["id"]] = True allVals.append(vals) allKeys.remove("id") allKeys.sort() allKeys.insert(0, "id") outStr = "" for key in allKeys: outStr += key + "," outStr = outStr[0:len(outStr) - 1] print outStr for vals in allVals: outStr = "" for key in allKeys: if vals.has_key(key): outStr += vals[key] outStr += "," outStr = outStr[0:len(outStr) - 1] print outStr
Java
UTF-8
2,772
2.15625
2
[]
no_license
package bustracking.model; import java.sql.Date; public class BusRegistration { private String org_id; public BusRegistration(String org_name, String branch, String vechicle_reg_no, String device_imei_number, String driver_name, String driver_licence_no, String driver_licence_exp_date) { super(); this.org_name = org_name; this.branch = branch; this.vechicle_reg_no = vechicle_reg_no; this.device_imei_number = device_imei_number; this.driver_name = driver_name; this.driver_licence_no = driver_licence_no; this.driver_licence_exp_date = driver_licence_exp_date; } private String org_name; private String branch; private String vechicle_reg_no; private String device_imei_number; private String driver_name; private String driver_licence_no; private String driver_licence_exp_date; private String route_no; public String getRoute_no() { return route_no; } public void setRoute_no(String route_no) { this.route_no = route_no; } public BusRegistration() { super(); // TODO Auto-generated constructor stub } public String getOrg_name() { return org_name; } public void setOrg_name(String org_name) { this.org_name = org_name; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public String getOrg_id() { return org_id; } public void setOrg_id(String org_id) { this.org_id = org_id; } public String getVechicle_reg_no() { return vechicle_reg_no; } public void setVechicle_reg_no(String vechicle_reg_no) { this.vechicle_reg_no = vechicle_reg_no; } public String getDevice_imei_number() { return device_imei_number; } public void setDevice_imei_number(String device_imei_number) { this.device_imei_number = device_imei_number; } public String getDriver_name() { return driver_name; } public void setDriver_name(String driver_name) { this.driver_name = driver_name; } public String getDriver_licence_no() { return driver_licence_no; } public void setDriver_licence_no(String driver_licence_no) { this.driver_licence_no = driver_licence_no; } public String getDriver_licence_exp_date() { return driver_licence_exp_date; } public void setDriver_licence_exp_date(String driver_licence_exp_date) { this.driver_licence_exp_date = driver_licence_exp_date; } public BusRegistration( String vechicle_reg_no, String driver_name, String driver_licence_no, String driver_licence_exp_date) { super(); this.vechicle_reg_no = vechicle_reg_no; this.driver_name = driver_name; this.driver_licence_no = driver_licence_no; this.driver_licence_exp_date = driver_licence_exp_date; } public BusRegistration(String route_no) { super(); this.route_no = route_no; } }
C++
SHIFT_JIS
33,883
2.609375
3
[]
no_license
/*! *@brief XLff[^B */ #include"fbstdafx.h" #include "SkinModelData.h" #include <iostream> #include <sstream> #include <iomanip> #include<shlwapi.h> //UINT g_NumBoneMatricesMax = 0; //D3DXMATRIXA16* g_pBoneMatrices = NULL; //CX^VOŕ`”\ȍő吔B const int MAX_INSTANCING_NUM = 100; namespace { /** * t@C. */ vector<string> FileNameSearch(const string& str) { std::stringstream ss(str); string buffer; vector<string> fileName; while (getline(ss, buffer, '.')) { fileName.push_back(buffer); } return fileName; } } //fFrameXV void UpdateFrameMatrices(LPD3DXFRAME pFrameBase, const D3DXMATRIX* pParentMatrix = nullptr) { D3DXFRAME_DERIVED* pFrame = (D3DXFRAME_DERIVED*)pFrameBase; D3DXMATRIX matrix = pFrame->TransformationMatrix; //]s񂪑݂Ă]. if (pFrame->RotationMatrix != nullptr) { D3DXMatrixMultiply(&matrix, pFrame->RotationMatrix, &matrix); } if (pParentMatrix != NULL) { //[hϊs쐬 D3DXMatrixMultiply(&pFrame->CombinedTransformationMatrix, &matrix, pParentMatrix); } else { //̂܂ pFrame->CombinedTransformationMatrix = matrix; } //ZXV if (pFrame->pFrameSibling != NULL) { //sn UpdateFrameMatrices(pFrame->pFrameSibling, pParentMatrix); } //qXV if (pFrame->pFrameFirstChild != NULL) { //e̍sōXV UpdateFrameMatrices(pFrame->pFrameFirstChild, &pFrame->CombinedTransformationMatrix); } } //bV_O[vɕ HRESULT GenerateSkinnedMesh( IDirect3DDevice9* pd3dDevice, D3DXMESHCONTAINER_DERIVED* pMeshContainer ) { HRESULT hr = S_OK; D3DCAPS9 d3dCaps; pd3dDevice->GetDeviceCaps(&d3dCaps); //{[񂪂ȂȂI if (pMeshContainer->pSkinInfo == NULL) return hr; SAFE_RELEASE(pMeshContainer->MeshData.pMesh); SAFE_RELEASE(pMeshContainer->pBoneCombinationBuf); { // Get palette size // First 9 constants are used for other data. Each 4x3 matrix takes up 3 constants. // (96 - 9) /3 i.e. Maximum constant count - used constants //̍ős //̐ςȂVF[_̕ς邱 UINT MaxMatrices = 50; pMeshContainer->NumPaletteEntries = min(MaxMatrices, pMeshContainer->pSkinInfo->GetNumBones()); DWORD Flags = D3DXMESHOPT_VERTEXCACHE; if (d3dCaps.VertexShaderVersion >= D3DVS_VERSION(1, 1)) { pMeshContainer->UseSoftwareVP = false; Flags |= D3DXMESH_MANAGED; } else { pMeshContainer->UseSoftwareVP = true; Flags |= D3DXMESH_SYSTEMMEM; } SAFE_RELEASE(pMeshContainer->MeshData.pMesh); //{[ƒ_̃uhCfbNXVbV쐬 hr = pMeshContainer->pSkinInfo->ConvertToIndexedBlendedMesh ( pMeshContainer->pOrigMesh, Flags, pMeshContainer->NumPaletteEntries, pMeshContainer->pAdjacency, NULL, NULL, NULL, &pMeshContainer->NumInfl, &pMeshContainer->NumAttributeGroups, &pMeshContainer->pBoneCombinationBuf, &pMeshContainer->MeshData.pMesh); if (FAILED(hr)) goto e_Exit; // FVF has to match our declarator. Vertex shaders are not as forgiving as FF pipeline DWORD NewFVF = (pMeshContainer->MeshData.pMesh->GetFVF() & D3DFVF_POSITION_MASK) | D3DFVF_NORMAL | D3DFVF_TEX1 | D3DFVF_LASTBETA_UBYTE4; if (NewFVF != pMeshContainer->MeshData.pMesh->GetFVF()) { LPD3DXMESH pMesh; hr = pMeshContainer->MeshData.pMesh->CloneMeshFVF(pMeshContainer->MeshData.pMesh->GetOptions(), NewFVF, pd3dDevice, &pMesh); if (!FAILED(hr)) { pMeshContainer->MeshData.pMesh->Release(); pMeshContainer->MeshData.pMesh = pMesh; pMesh = NULL; } } D3DVERTEXELEMENT9 pDecl[MAX_FVF_DECL_SIZE]; LPD3DVERTEXELEMENT9 pDeclCur; hr = pMeshContainer->MeshData.pMesh->GetDeclaration(pDecl); if (FAILED(hr)) goto e_Exit; // the vertex shader is expecting to interpret the UBYTE4 as a D3DCOLOR, so update the type // NOTE: this cannot be done with CloneMesh, that would convert the UBYTE4 data to float and then to D3DCOLOR // this is more of a "cast" operation pDeclCur = pDecl; while (pDeclCur->Stream != 0xff) { if ((pDeclCur->Usage == D3DDECLUSAGE_BLENDINDICES) && (pDeclCur->UsageIndex == 0)) pDeclCur->Type = D3DDECLTYPE_D3DCOLOR; pDeclCur++; } hr = pMeshContainer->MeshData.pMesh->UpdateSemantics(pDecl); if (FAILED(hr)) goto e_Exit; // allocate a buffer for bone matrices, but only if another mesh has not allocated one of the same size or larger //if (g_NumBoneMatricesMax < pMeshContainer->pSkinInfo->GetNumBones()) //{ // g_NumBoneMatricesMax = pMeshContainer->pSkinInfo->GetNumBones(); // // Allocate space for blend matrices // delete[] g_pBoneMatrices; // g_pBoneMatrices = new D3DXMATRIXA16[g_NumBoneMatricesMax]; // if (g_pBoneMatrices == NULL) // { // hr = E_OUTOFMEMORY; // goto e_Exit; // } //} } e_Exit: return hr; } HRESULT AllocateName(LPCSTR Name, LPSTR* pNewName) { UINT cbLength; if (Name != NULL) { cbLength = (UINT)strlen(Name) + 1; *pNewName = new CHAR[cbLength]; if (*pNewName == NULL) return E_OUTOFMEMORY; memcpy(*pNewName, Name, cbLength * sizeof(CHAR)); } else { *pNewName = NULL; } return S_OK; } //-------------------------------------------------------------------------------------- // Called to setup the pointers for a given bone to its transformation matrix //-------------------------------------------------------------------------------------- HRESULT SetupBoneMatrixPointersOnMesh(LPD3DXMESHCONTAINER pMeshContainerBase, LPD3DXFRAME rootFrame) { UINT iBone, cBones; D3DXFRAME_DERIVED* pFrame; //W̃bVReiŃJX^}CYbVReiɃLXg D3DXMESHCONTAINER_DERIVED* pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)pMeshContainerBase; //XL({[邩ǂ)mF if (pMeshContainer->pSkinInfo != NULL) { //{[̐擾 cBones = pMeshContainer->pSkinInfo->GetNumBones(); //{[̍s̔zm pMeshContainer->ppBoneMatrixPtrs = new D3DXMATRIX*[cBones]; //˂I if (pMeshContainer->ppBoneMatrixPtrs == NULL) return E_OUTOFMEMORY; for (iBone = 0; iBone < cBones; iBone++) { //[gt[{[̖OŌ,qt[擾 pFrame = (D3DXFRAME_DERIVED*)D3DXFrameFind(rootFrame, pMeshContainer->pSkinInfo->GetBoneName(iBone)); //ɑΉt[‚ȂEEE if (pFrame == NULL) return E_FAIL; //t[s擾,̍sƂ pMeshContainer->ppBoneMatrixPtrs[iBone] = &pFrame->CombinedTransformationMatrix; } } return S_OK; } //-------------------------------------------------------------------------------------- // Called to setup the pointers for a given bone to its transformation matrix //-------------------------------------------------------------------------------------- HRESULT SetupBoneMatrixPointers(LPD3DXFRAME pFrame, LPD3DXFRAME pRootFrame) { HRESULT hr; if (pFrame->pMeshContainer != NULL) { //̍sݒ hr = SetupBoneMatrixPointersOnMesh(pFrame->pMeshContainer, pRootFrame); if (FAILED(hr)) return hr; } //Z평(ċA) if (pFrame->pFrameSibling != NULL) { hr = SetupBoneMatrixPointers(pFrame->pFrameSibling, pRootFrame); if (FAILED(hr)) return hr; } //q(ċA) if (pFrame->pFrameFirstChild != NULL) { hr = SetupBoneMatrixPointers(pFrame->pFrameFirstChild, pRootFrame); if (FAILED(hr)) return hr; } return S_OK; } class CAllocateHierarchy : public ID3DXAllocateHierarchy { public: //t[ STDMETHOD(CreateFrame)(THIS_ LPCSTR Name, LPD3DXFRAME *ppNewFrame); //bVRei쐬 STDMETHOD(CreateMeshContainer)(THIS_ LPCSTR Name, CONST D3DXMESHDATA *pMeshData, CONST D3DXMATERIAL *pMaterials, CONST D3DXEFFECTINSTANCE *pEffectInstances, DWORD NumMaterials, CONST DWORD *pAdjacency, LPD3DXSKININFO pSkinInfo, LPD3DXMESHCONTAINER *ppNewMeshContainer); //t[폜 STDMETHOD(DestroyFrame)(THIS_ LPD3DXFRAME pFrameToFree); //bVRei폜 STDMETHOD(DestroyMeshContainer)(THIS_ LPD3DXMESHCONTAINER pMeshContainerBase); CAllocateHierarchy(SkinModelData* data): _SkinModelData(data) { } private: SkinModelData* _SkinModelData; }; //-------------------------------------------------------------------------------------- // Name: CAllocateHierarchy::CreateFrame() // Desc: //-------------------------------------------------------------------------------------- HRESULT CAllocateHierarchy::CreateFrame(LPCSTR Name, LPD3DXFRAME* ppNewFrame) { HRESULT hr = S_OK; D3DXFRAME_DERIVED* pFrame; *ppNewFrame = NULL; pFrame = new D3DXFRAME_DERIVED(); if (pFrame == NULL) { hr = E_OUTOFMEMORY; goto e_Exit; } hr = AllocateName(Name, &pFrame->Name); if (FAILED(hr)) goto e_Exit; // initialize other data members of the frame D3DXMatrixIdentity(&pFrame->TransformationMatrix); D3DXMatrixIdentity(&pFrame->CombinedTransformationMatrix); pFrame->pMeshContainer = NULL; pFrame->pFrameSibling = NULL; pFrame->pFrameFirstChild = NULL; pFrame->Original = pFrame; *ppNewFrame = pFrame; pFrame = NULL; e_Exit: delete pFrame; return hr; } //-------------------------------------------------------------------------------------- // Name: CAllocateHierarchy::CreateMeshContainer() // Desc: //-------------------------------------------------------------------------------------- //bVRei쐬 HRESULT CAllocateHierarchy::CreateMeshContainer( LPCSTR Name, CONST D3DXMESHDATA *pMeshData, CONST D3DXMATERIAL *pMaterials, CONST D3DXEFFECTINSTANCE *pEffectInstances, DWORD NumMaterials, CONST DWORD *pAdjacency, LPD3DXSKININFO pSkinInfo, LPD3DXMESHCONTAINER *ppNewMeshContainer) { HRESULT hr; D3DXMESHCONTAINER_DERIVED *pMeshContainer = NULL; UINT NumFaces; UINT iMaterial; UINT iBone, cBones; LPDIRECT3DDEVICE9 pd3dDevice = NULL; LPD3DXMESH pMesh = NULL; *ppNewMeshContainer = NULL; // this sample does not handle patch meshes, so fail when one is found if (pMeshData->Type != D3DXMESHTYPE_MESH) { hr = E_FAIL; goto e_Exit; } // get the pMesh interface pointer out of the mesh data structure pMesh = pMeshData->pMesh; // this sample does not FVF compatible meshes, so fail when one is found if (pMesh->GetFVF() == 0) { hr = E_FAIL; goto e_Exit; } // allocate the overloaded structure to return as a D3DXMESHCONTAINER pMeshContainer = new D3DXMESHCONTAINER_DERIVED; if (pMeshContainer == NULL) { hr = E_OUTOFMEMORY; goto e_Exit; } memset(pMeshContainer, 0, sizeof(D3DXMESHCONTAINER_DERIVED)); // make sure and copy the name. All memory as input belongs to caller, interfaces can be addref'd though hr = AllocateName(Name, &pMeshContainer->Name); if (FAILED(hr)) goto e_Exit; pMesh->GetDevice(&pd3dDevice); NumFaces = pMesh->GetNumFaces(); // if no normals are in the mesh, add them if (!(pMesh->GetFVF() & D3DFVF_NORMAL)) { pMeshContainer->MeshData.Type = D3DXMESHTYPE_MESH; // clone the mesh to make room for the normals hr = pMesh->CloneMeshFVF(pMesh->GetOptions(), pMesh->GetFVF() | D3DFVF_NORMAL, pd3dDevice, &pMeshContainer->MeshData.pMesh); if (FAILED(hr)) goto e_Exit; // get the new pMesh pointer back out of the mesh container to use // NOTE: we do not release pMesh because we do not have a reference to it yet pMesh = pMeshContainer->MeshData.pMesh; // now generate the normals for the pmesh D3DXComputeNormals(pMesh, NULL); } else // if no normals, just add a reference to the mesh for the mesh container { pMeshContainer->MeshData.pMesh = pMesh; pMeshContainer->MeshData.Type = D3DXMESHTYPE_MESH; pMesh->AddRef(); } //_`Ƃ쐬B { //CX^VO`p̏B D3DVERTEXELEMENT9 declElement[MAX_FVF_DECL_SIZE]; //fR[V擾B pMeshContainer->MeshData.pMesh->GetDeclaration(declElement); int elementIndex = 0; while (true) { //ݒ̏ꏊTB if (declElement[elementIndex].Type == D3DDECLTYPE_UNUSED) { //I[𔭌B //CX^VOp̒_CAEg𖄂ߍށB declElement[elementIndex] = { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }; // WORLD 1s declElement[elementIndex + 1] = { 1, 16, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }; // WORLD 2s declElement[elementIndex + 2] = { 1, 32, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }; // WORLD 3s declElement[elementIndex + 3] = { 1, 48, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }; // WORLD 4s declElement[elementIndex + 4] = D3DDECL_END(); break; } elementIndex++; } //_錾쐬B (*graphicsDevice()).CreateVertexDeclaration(declElement, &pMeshContainer->vertexDecl); //_obt@쐬B (*graphicsDevice()).CreateVertexBuffer( sizeof(D3DXMATRIX) *MAX_INSTANCING_NUM, 0, 0, D3DPOOL_MANAGED, &pMeshContainer->worldMatrixBuffer, 0); } // allocate memory to contain the material information. This sample uses // the D3D9 materials and texture names instead of the EffectInstance style materials //}eA̐ݒ pMeshContainer->NumMaterials = max(1, NumMaterials); pMeshContainer->pMaterials = new D3DXMATERIAL[pMeshContainer->NumMaterials]; pMeshContainer->material = new Material*[pMeshContainer->NumMaterials]; pMeshContainer->pAdjacency = new DWORD[NumFaces * 3]; if ((pMeshContainer->pAdjacency == NULL) || (pMeshContainer->pMaterials == NULL)) { hr = E_OUTOFMEMORY; goto e_Exit; } memcpy(pMeshContainer->pAdjacency, pAdjacency, sizeof(DWORD)* NumFaces * 3); //eNX`[0ŏ //memset(pMeshContainer->ppTextures, 0, sizeof(LPDIRECT3DTEXTURE9)* pMeshContainer->NumMaterials); //}eA̐摜ǂݍ݁ARs[ if (NumMaterials > 0) { memcpy(pMeshContainer->pMaterials, pMaterials, sizeof(D3DXMATERIAL)* NumMaterials); for (iMaterial = 0; iMaterial < NumMaterials; iMaterial++) { pMeshContainer->material[iMaterial] = nullptr; //t@Cw肪Ȃ if (pMeshContainer->pMaterials[iMaterial].pTextureFilename != NULL) { pMeshContainer->pMaterials[iMaterial].pTextureFilename = new CHAR[strlen(pMaterials[iMaterial].pTextureFilename) + 1]; strcpy(pMeshContainer->pMaterials[iMaterial].pTextureFilename, pMaterials[iMaterial].pTextureFilename); //摜̃pXlj char* baseDir = "Asset/Xfile/"; char filePath[64]; strcpy_s(filePath, baseDir); strcat_s(filePath, pMeshContainer->pMaterials[iMaterial].pTextureFilename); pMeshContainer->material[iMaterial] = new Material(pMeshContainer->pMaterials[iMaterial].pTextureFilename); //摜̏擾 D3DXIMAGE_INFO info; D3DXGetImageInfoFromFile( filePath, //eNX`pX &info //i[ ); LPDIRECT3DBASETEXTURE9 texture; //eNX`̃^Cvɍǂݍݕ@ switch (info.ResourceType) { case _D3DRESOURCETYPE::D3DRTYPE_TEXTURE: //ʏeNX`ǂݍ if (FAILED(D3DXCreateTextureFromFile( pd3dDevice, filePath, (LPDIRECT3DTEXTURE9*)&texture))) { //Ȃ pMeshContainer->material[iMaterial]->SetTexture(Material::TextureHandleE::DiffuseMap,nullptr); } else { // pMeshContainer->material[iMaterial]->SetTexture(Material::TextureHandleE::DiffuseMap, texture); _SkinModelData->AddMaterial(pMeshContainer->material[iMaterial]); } break; case _D3DRESOURCETYPE::D3DRTYPE_CUBETEXTURE: //L[ueNX`ǂݍ if (FAILED(D3DXCreateCubeTextureFromFile( pd3dDevice, filePath, (LPDIRECT3DCUBETEXTURE9*)&texture))) { //Ȃ pMeshContainer->material[iMaterial]->SetTexture(Material::TextureHandleE::DiffuseMap, nullptr); } else { // pMeshContainer->material[iMaterial]->SetTexture(Material::TextureHandleE::DiffuseMap, texture); _SkinModelData->AddMaterial(pMeshContainer->material[iMaterial]); } break; default: break; } vector<string> fileName = FileNameSearch(pMeshContainer->pMaterials[iMaterial].pTextureFilename); string normalFileName = baseDir + fileName[0] + "_Normal." + fileName[1]; if (PathFileExists(normalFileName.c_str())) { LPDIRECT3DBASETEXTURE9 nTexture; D3DXCreateTextureFromFile( pd3dDevice, normalFileName.c_str(), (LPDIRECT3DTEXTURE9*)&nTexture); pMeshContainer->material[iMaterial]->SetTexture(Material::TextureHandleE::NormalMap, nTexture); } string specularFileName = baseDir + fileName[0] + "_Specular." + fileName[1]; if (PathFileExists(specularFileName.c_str())) { LPDIRECT3DBASETEXTURE9 sTexture; D3DXCreateTextureFromFile( pd3dDevice, specularFileName.c_str(), (LPDIRECT3DTEXTURE9*)&sTexture); pMeshContainer->material[iMaterial]->SetTexture(Material::TextureHandleE::SpecularMap, sTexture); } // don't remember a pointer into the dynamic memory, just forget the name after loading //悭킩񂪃t@CpXĂB //pMeshContainer->pMaterials[iMaterial].pTextureFilename = NULL; } } } else //}eAȂ[ { pMeshContainer->pMaterials[0].pTextureFilename = NULL; memset(&pMeshContainer->pMaterials[0].MatD3D, 0, sizeof(D3DMATERIAL9)); pMeshContainer->pMaterials[0].MatD3D.Diffuse.r = 0.5f; pMeshContainer->pMaterials[0].MatD3D.Diffuse.g = 0.5f; pMeshContainer->pMaterials[0].MatD3D.Diffuse.b = 0.5f; pMeshContainer->pMaterials[0].MatD3D.Specular = pMeshContainer->pMaterials[0].MatD3D.Diffuse; } pMeshContainer->pOrigMesh = pMesh; pMesh->AddRef(); D3DVERTEXELEMENT9 AnimDecl[] = { { 0, 0 , D3DDECLTYPE_FLOAT4 , D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION , 0 }, { 0, 16, D3DDECLTYPE_FLOAT4 , D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT , 0 }, { 0, 32, D3DDECLTYPE_FLOAT4 , D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES , 0 }, { 0, 48, D3DDECLTYPE_FLOAT3 , D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL , 0 }, { 0, 60, D3DDECLTYPE_FLOAT3 , D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT , 0 }, { 0, 72, D3DDECLTYPE_FLOAT2 , D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD , 0 }, D3DDECL_END() }; int offset = 0; D3DVERTEXELEMENT9 NonAnimDecl[] = { { 0, 0 , D3DDECLTYPE_FLOAT3 , D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION , 0 }, { 0, 12, D3DDECLTYPE_FLOAT3 , D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL , 0 }, { 0, 24, D3DDECLTYPE_FLOAT3 , D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT , 0 }, { 0, 36, D3DDECLTYPE_FLOAT2 , D3DDECLMETHOD_UV, D3DDECLUSAGE_TEXCOORD , 0 }, { 0, 44, D3DDECLTYPE_D3DCOLOR , D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR , 0 }, D3DDECL_END() }; // if there is skinning information, save off the required data and then setup for HW skinning if (pSkinInfo != NULL) { // first save off the SkinInfo and original mesh data pMeshContainer->pSkinInfo = pSkinInfo; pSkinInfo->AddRef(); //{[̐{[̃ItZbgsm cBones = pSkinInfo->GetNumBones(); pMeshContainer->pBoneOffsetMatrices = new D3DXMATRIX[cBones]; if (pMeshContainer->pBoneOffsetMatrices == NULL) { hr = E_OUTOFMEMORY; goto e_Exit; } //{[̃ItZbgsZbg for (iBone = 0; iBone < cBones; iBone++) { pMeshContainer->pBoneOffsetMatrices[iBone] = *(pMeshContainer->pSkinInfo->GetBoneOffsetMatrix(iBone)); } //bV_O[vɕ hr = GenerateSkinnedMesh(pd3dDevice, pMeshContainer); if (FAILED(hr)) goto e_Exit; LPD3DXMESH pOutMesh, pTmpMesh; hr = pMeshContainer->MeshData.pMesh->CloneMesh( pMeshContainer->MeshData.pMesh->GetOptions(), AnimDecl, pd3dDevice, &pOutMesh); if (FAILED(hr)) goto e_Exit; //ꎞbVɑޔB pTmpMesh = pOutMesh; //D3DXComputeTangentFrameExsƑe[ȕ񂪎EEEB DWORD numAttributeTable; pMeshContainer->MeshData.pMesh->GetAttributeTable(NULL, &numAttributeTable); pMeshContainer->pAttributeTable = new D3DXATTRIBUTERANGE[numAttributeTable]; pMeshContainer->MeshData.pMesh->GetAttributeTable(pMeshContainer->pAttributeTable, NULL); hr = D3DXComputeTangentFrameEx( pTmpMesh, D3DDECLUSAGE_TEXCOORD, 0, D3DDECLUSAGE_TANGENT, 0, D3DX_DEFAULT, 0, D3DDECLUSAGE_NORMAL, 0, 0, NULL, 0.01f, //{P.lƂڂȂȂ 0.25f, 0.01f, &pOutMesh, NULL ); //ꎞbVjB SAFE_RELEASE(pTmpMesh); SAFE_RELEASE(pMeshContainer->MeshData.pMesh); pMeshContainer->MeshData.pMesh = pOutMesh; if (FAILED(hr)) { goto e_Exit; } } else { LPD3DXMESH pOutMesh, pTmpMesh; DWORD numVert = pMeshContainer->MeshData.pMesh->GetNumVertices(); hr = pMeshContainer->MeshData.pMesh->CloneMesh( pMeshContainer->MeshData.pMesh->GetOptions(), AnimDecl, pd3dDevice, &pOutMesh); DWORD numAttributeTable; pMeshContainer->MeshData.pMesh->GetAttributeTable(NULL, &numAttributeTable); pMeshContainer->pAttributeTable = new D3DXATTRIBUTERANGE[numAttributeTable]; pMeshContainer->MeshData.pMesh->GetAttributeTable(pMeshContainer->pAttributeTable, NULL); numVert = pMeshContainer->MeshData.pMesh->GetNumVertices(); //ꎞbVɑޔB pTmpMesh = pOutMesh; hr = D3DXComputeTangentFrameEx( pTmpMesh, D3DDECLUSAGE_TEXCOORD, 0, D3DDECLUSAGE_TANGENT, 0, D3DX_DEFAULT, 0, D3DDECLUSAGE_NORMAL, 0, 0, NULL, 0.01f, //{P.lƂڂȂȂ 0.25f, 0.01f, &pOutMesh, NULL ); //ꎞbVjB SAFE_RELEASE(pTmpMesh); numVert = pOutMesh->GetNumVertices(); SAFE_RELEASE(pMesh); pMeshContainer->MeshData.pMesh = pOutMesh; if (FAILED(hr)) goto e_Exit; } *ppNewMeshContainer = pMeshContainer; pMeshContainer = NULL; e_Exit: pd3dDevice->Release(); // call Destroy function to properly clean up the memory allocated if (pMeshContainer != NULL) { DestroyMeshContainer(pMeshContainer); } return hr; } //-------------------------------------------------------------------------------------- // Name: CAllocateHierarchy::DestroyFrame() // Desc: //-------------------------------------------------------------------------------------- HRESULT CAllocateHierarchy::DestroyFrame(LPD3DXFRAME pFrameToFree) { SAFE_DELETE_ARRAY(pFrameToFree->Name); SAFE_DELETE(pFrameToFree); return S_OK; } //-------------------------------------------------------------------------------------- // Name: CAllocateHierarchy::DestroyMeshContainer() // Desc: //-------------------------------------------------------------------------------------- HRESULT CAllocateHierarchy::DestroyMeshContainer(LPD3DXMESHCONTAINER pMeshContainerBase) { UINT iMaterial; D3DXMESHCONTAINER_DERIVED* pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)pMeshContainerBase; SAFE_DELETE_ARRAY(pMeshContainer->Name); SAFE_DELETE_ARRAY(pMeshContainer->pAdjacency); SAFE_DELETE_ARRAY(pMeshContainer->pBoneOffsetMatrices); // release all the allocated textures if (pMeshContainer->material != NULL) { for (iMaterial = 0; iMaterial < pMeshContainer->NumMaterials; iMaterial++) { //SAFE_RELEASE(pMeshContainer->material[iMaterial]); SAFE_DELETE_ARRAY(pMeshContainer->pMaterials[iMaterial].pTextureFilename); } } SAFE_DELETE_ARRAY(pMeshContainer->pMaterials); SAFE_DELETE_ARRAY(pMeshContainer->material); SAFE_DELETE_ARRAY(pMeshContainer->ppBoneMatrixPtrs); SAFE_RELEASE(pMeshContainer->pBoneCombinationBuf); SAFE_RELEASE(pMeshContainer->MeshData.pMesh); SAFE_RELEASE(pMeshContainer->pSkinInfo); SAFE_RELEASE(pMeshContainer->pOrigMesh); SAFE_DELETE(pMeshContainer); return S_OK; } /*! *@brief RXgN^B */ SkinModelData::SkinModelData(): _FrameRoot(nullptr), m_pAnimationController(nullptr), _Instancing(false) { } /*! *@brief fXgN^B */ SkinModelData::~SkinModelData() { _MeshList.clear(); _Materials.clear(); Release(); } /*! * @brief [XB */ void SkinModelData::Release() { if (_FrameRoot) { //N[ DeleteCloneSkeleton(_FrameRoot); _FrameRoot = nullptr; } SAFE_RELEASE(m_pAnimationController); } /*! * @brief ff[^[hB *@param[in] filePath t@CpXB */ bool SkinModelData::LoadModelData(const char* filePath) { CAllocateHierarchy alloc(this); HRESULT hr = D3DXLoadMeshHierarchyFromXA( filePath, D3DXMESH_VB_MANAGED, graphicsDevice(), &alloc, nullptr, &_FrameRoot, &m_pAnimationController ); if (_FrameRoot) { //ɍsZbg SetupBoneMatrixPointers(_FrameRoot, _FrameRoot); //bVXg쐬B _CreateMeshList(); //TCYB Measurement(); //IWiB _Original = this; return true; } return false; } //ff[^̃N[쐬 //ׂăN[ō쐬B void SkinModelData::CloneModelData(const SkinModelData* original, Animation* anim) { // //memcpy(this, original, sizeof(SkinModelData)); //t[V쐬 _FrameRoot = new D3DXFRAME_DERIVED; _FrameRoot->pFrameFirstChild = nullptr; _FrameRoot->pFrameSibling = nullptr; _FrameRoot->pMeshContainer = nullptr; //̃N[쐻 CloneSkeleton(_FrameRoot, original->_FrameRoot); //Aj[VRg[쐬āAXPgƊ֘AtsB if (original->m_pAnimationController) { original->m_pAnimationController->CloneAnimationController( original->m_pAnimationController->GetMaxNumAnimationOutputs(), original->m_pAnimationController->GetMaxNumAnimationSets(), original->m_pAnimationController->GetMaxNumTracks(), original->m_pAnimationController->GetMaxNumEvents(), &m_pAnimationController ); //EFCgݒH SetupOutputAnimationRegist(_FrameRoot, m_pAnimationController); //Ȃ珉 if (anim && m_pAnimationController) { anim->Initialize(m_pAnimationController); } } //̍XVB SetupBoneMatrixPointers(_FrameRoot, _FrameRoot); //}eARs[ this->_Materials = original->_Materials; //bVXgRs[ this->_MeshList = original->_MeshList; // this->_FrameList = original->_FrameList; // this->_TerrainSize = original->_TerrainSize; // this->_Size = original->_Size; // this->_Center = original->_Center; //IWiݒBB _Original = const_cast<SkinModelData*>(original); } //Rs[ void SkinModelData::CloneSkeleton(LPD3DXFRAME& dstFrame, LPD3DXFRAME srcFrame) { //OƍsRs[B dstFrame->TransformationMatrix = srcFrame->TransformationMatrix; //X^bNɐςށB auto derived = (D3DXFRAME_DERIVED*)dstFrame; auto source = (D3DXFRAME_DERIVED*)srcFrame; derived->CombinedTransformationMatrix = source->CombinedTransformationMatrix; derived->Original = source->Original; derived->Original->WorldMatrixStack.push_back(&derived->CombinedTransformationMatrix); //bVReiRs[BbV͎g܂킷B if (srcFrame->pMeshContainer) { dstFrame->pMeshContainer = new D3DXMESHCONTAINER_DERIVED(); memcpy(dstFrame->pMeshContainer, srcFrame->pMeshContainer, sizeof(D3DXMESHCONTAINER_DERIVED)); } else { dstFrame->pMeshContainer = NULL; } AllocateName(srcFrame->Name, &dstFrame->Name); if (srcFrame->pFrameSibling != nullptr) { //Z킪̂ŁAẐ߂̃mہB dstFrame->pFrameSibling = new D3DXFRAME_DERIVED(); dstFrame->pFrameSibling->pFrameFirstChild = nullptr; dstFrame->pFrameSibling->pFrameSibling = nullptr; dstFrame->pFrameSibling->pMeshContainer = nullptr; CloneSkeleton(dstFrame->pFrameSibling, srcFrame->pFrameSibling); } if (srcFrame->pFrameFirstChild != nullptr) { //q̂ŁAq̂߂̃mہB dstFrame->pFrameFirstChild = new D3DXFRAME_DERIVED(); dstFrame->pFrameFirstChild->pFrameFirstChild = nullptr; dstFrame->pFrameFirstChild->pFrameSibling = nullptr; dstFrame->pFrameFirstChild->pMeshContainer = nullptr; CloneSkeleton(dstFrame->pFrameFirstChild, srcFrame->pFrameFirstChild); } } void SkinModelData::DeleteCloneSkeleton(LPD3DXFRAME frame) { //X^bN폜B auto derived = (D3DXFRAME_DERIVED*)frame; auto& vec = derived->Original->WorldMatrixStack; vec.erase(remove(vec.begin(), vec.end(), &derived->CombinedTransformationMatrix), vec.end()); if (frame->pFrameSibling != nullptr) { //Z DeleteCloneSkeleton(frame->pFrameSibling); } if (frame->pFrameFirstChild != nullptr) { //qB DeleteCloneSkeleton(frame->pFrameFirstChild); } D3DXMESHCONTAINER_DERIVED* pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)(frame->pMeshContainer); if (pMeshContainer) { //SAFE_DELETE_ARRAY(pMeshContainer->ppBoneMatrixPtrs); SAFE_DELETE(pMeshContainer); } SAFE_DELETE_ARRAY(frame->Name); SAFE_DELETE(frame); } void SkinModelData::SetupOutputAnimationRegist(LPD3DXFRAME frame, ID3DXAnimationController* animCtr) { if (animCtr == nullptr) { return; } HRESULT hr = animCtr->RegisterAnimationOutput(frame->Name, &frame->TransformationMatrix, nullptr, nullptr, nullptr); if (frame->pFrameSibling != nullptr) { SetupOutputAnimationRegist(frame->pFrameSibling, animCtr); } if (frame->pFrameFirstChild != nullptr) { SetupOutputAnimationRegist(frame->pFrameFirstChild, animCtr); } } Material * SkinModelData::FindMaterial(const char * matName) { for (Material* mat : _Materials) { if (strcmp(mat->GetName(), matName) == 0) { return mat; } } return nullptr; } /*! * @brief {[sXVB */ void SkinModelData::UpdateBoneMatrix(const D3DXMATRIX& matWorld) { UpdateFrameMatrices(_FrameRoot, (const D3DXMATRIX*)&matWorld); } LPD3DXMESH SkinModelData::GetOrgMesh(LPD3DXFRAME frame) const { D3DXMESHCONTAINER_DERIVED* pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)(frame->pMeshContainer); //bVRei‚Ȃ烁bVԂ if (pMeshContainer != nullptr) { return pMeshContainer->pOrigMesh; } //‚ȂꍇZAqƃbVReiT if (frame->pFrameSibling != nullptr) { //Z LPD3DXMESH mesh = GetOrgMesh(frame->pFrameSibling); if (mesh) { return mesh; } } if (frame->pFrameFirstChild != nullptr) { //qB LPD3DXMESH mesh = GetOrgMesh(frame->pFrameFirstChild); if (mesh) { return mesh; } } return nullptr; } LPD3DXMESH SkinModelData::GetOrgMeshFirst() const { return GetOrgMesh(_FrameRoot); } void SkinModelData::Measurement() { //ꂽsB D3DXMATRIX iden; D3DXMatrixIdentity(&iden); //ړ0̍sŌvZčB UpdateBoneMatrix(iden); //ԕݒ Vector3 Min(FLT_MAX, FLT_MAX, FLT_MAX), Max(-FLT_MAX, -FLT_MAX, -FLT_MAX); // for(auto& frame:_FrameList) { D3DXFRAME_DERIVED* pFrame = (D3DXFRAME_DERIVED*)frame; auto container = pFrame->pMeshContainer; //Rei݂B while (container != nullptr) { //bV擾B auto& mesh = container->MeshData.pMesh; //_obt@擾B LPDIRECT3DVERTEXBUFFER9 vb; mesh->GetVertexBuffer(&vb); //_`擾B D3DVERTEXBUFFER_DESC desc; vb->GetDesc(&desc); //_XgCh擾B int stride = mesh->GetNumBytesPerVertex(); D3DXVECTOR3* vertexPos; vb->Lock(0, desc.Size, (void**)&vertexPos, D3DLOCK_READONLY); //_[v for (unsigned int i = 0; i < mesh->GetNumVertices(); i++) { //sŃXP[OB D3DXVECTOR4 vpos; D3DXVec3Transform(&vpos, vertexPos, &pFrame->CombinedTransformationMatrix); //ŏB Min.x = min(Min.x, vpos.x); Min.y = min(Min.y, vpos.y); Min.z = min(Min.z, vpos.z); //őB Max.x = max(Max.x, vpos.x); Max.y = max(Max.y, vpos.y); Max.z = max(Max.z, vpos.z); //̒_ցB char* p = (char*)vertexPos; p += stride; vertexPos = (D3DXVECTOR3*)p; } vb->Unlock(); vb->Release(); //̃Rei container = container->pNextMeshContainer; } } _TerrainSize.x = Min.x; _TerrainSize.y = Max.x; _TerrainSize.z = Min.z; _TerrainSize.w = Max.z; _Size = Max - Min; _Center = (Max + Min) / 2; } void SkinModelData::_CreateMeshList() { //ċA֐Ăяo _QueryMeshes(_FrameRoot); } void SkinModelData::_QueryMeshes(LPD3DXFRAME frame) { LPD3DXMESHCONTAINER pMeshContainer; pMeshContainer = frame->pMeshContainer; // _FrameList.push_back(frame); //SẴbVRei while (pMeshContainer != NULL) { //bVlj _MeshList.push_back(pMeshContainer->MeshData.pMesh); //̃bVRei擾 pMeshContainer = pMeshContainer->pNextMeshContainer; } //ċA if (frame->pFrameSibling != NULL) { _QueryMeshes(frame->pFrameSibling); } if (frame->pFrameFirstChild != NULL) { _QueryMeshes(frame->pFrameFirstChild); } }
C
ISO-8859-1
29,340
3.015625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <conio.h> #include <conio2.h> #include <string.h> #include <ctype.h> // estruturas struct Login { char usuario[15]; char senha[15]; }; struct CadastroAluno { char RGA [12]; char nome [50]; char usuarioL [10]; char senhaL [8]; }; void telaBasica() { textbackground(2); textcolor(15); clrscr(); } void telaLogin() { gotoxy(44,7); textbackground(0); printf(" "); gotoxy(44, 23); printf(" "); gotoxy(76, 7); printf(" "); gotoxy(76, 23); printf(" "); textbackground(2); textcolor(15); gotoxy(45,7); // canto superior esquerdo printf("%c", 201); gotoxy(45,23); // canto inferior esquerdo printf("%c", 200); gotoxy(75,7); // canto superior direito printf("%c", 187); gotoxy(75,23); // canto inferior direito printf("%c", 188); int c; textbackground(0); for (c=44; c<77; c++){ gotoxy(c, 6); printf(" "); } for (c=44; c<77; c++){ gotoxy(c, 24); printf(" "); } for (c= 8; c< 23; c++){ gotoxy(44, c); printf(" "); } for (c= 8; c< 23; c++){ gotoxy(76, c); printf(" "); } textbackground(2); textcolor(15); for (c=46; c<75; c++) // linha superior { gotoxy(c, 7); printf("%c", 205); } for (c=46; c<75; c++) // linha inferior { gotoxy(c, 23); printf("%c", 205); } for (c=8; c<23; c++) // linha lateral esquerda { if (c==9) { gotoxy(45, c); printf("%c", 204); } else { if (c==20) { gotoxy(45, c); printf("%c", 204); } else { gotoxy(45, c); printf("%c", 186); } } } for (c=8; c<23; c++) // linha lateral direita { if (c==9) { gotoxy(75, c); printf("%c", 185); } else { if (c==20) { gotoxy(75, c); printf("%c", 185); } else { gotoxy(75, c); printf("%c", 186); } } } for (c=46; c<75; c++) { gotoxy(c, 9); printf("%c", 205); gotoxy(c, 20); printf("%c", 205); } gotoxy(53, 8); printf("Logar no sistema"); gotoxy(47, 11); textcolor(15); printf("Usuario: "); for(c=47; c<57; c++) { textbackground(15); gotoxy(c, 12); printf(" "); } textbackground(2); gotoxy(47, 14); printf("Senha: "); for(c=47; c<55; c++) { textbackground(15); gotoxy(c, 15); printf(" "); } textbackground(2); gotoxy(49, 18); printf("%c", 179); gotoxy(50, 18); printf("ENTRAR"); gotoxy(56, 18); printf("%c", 179); gotoxy(60, 18); printf("%c", 179); gotoxy(61, 18); printf("CANCELAR"); gotoxy(69, 18); printf("%c", 179); gotoxy(50, 21); printf("%c", 179); gotoxy(52, 21); printf("%c", 179); gotoxy(48, 22); printf("1 acesso"); gotoxy(60, 22); printf("Ja cadastrado"); gotoxy(65, 21); printf("%c", 179); gotoxy(67, 21); printf("%c", 179); } void telaCadastroAluno() { gotoxy(50, 7); textcolor(15); textbackground(0); printf("CADASTRO DE ALUNOS"); } void telaCadastroProfessor(){ gotoxy(50, 7); textcolor(15); textbackground(0); printf("CADASTRO DE PROFESSORES"); } void telaCadastroDisciplina(){ gotoxy(50, 7); textcolor(15); textbackground(0); printf("CADASTRO DE DISCIPLINAS"); } void telaCadastroTurma(){ gotoxy(50, 7); textcolor(15); textbackground(0); printf("CADASTRO DE TURMAS"); } void telaListarAluno(){ gotoxy(45, 7); textcolor(15); textbackground(0); printf("LISTA DE ALUNOS CADASTRADOS"); } void telaListarProfessor(){ gotoxy(43, 7); textcolor(15); textbackground(0); printf("LISTA DE PROFESSORES CADASTRADOS"); } void telaListarDisciplinas(){ gotoxy(43, 7); textcolor(15); textbackground(0); printf("LISTA DE DISCIPLINAS CADASTRADAS"); } void telaListarTurmas(){ gotoxy(45, 7); textcolor(15); textbackground(0); printf("LISTA DE TURMAS CADASTRADAS"); } void telaBuscarAluno(){ gotoxy(53, 7); textcolor(15); textbackground(0); printf("BUSCAR ALUNO"); } void telaBuscarTurmas(){ gotoxy(53, 7); textcolor(15); textbackground(0); printf("BUSCAR TURMA"); } void telaBuscarProfessor(){ gotoxy(49, 7); textcolor(15); textbackground(0); printf("BUSCAR PROFESSOR"); } void telaAtualizarAluno(){ gotoxy(51, 7); textcolor(15); textbackground(0); printf("ATUALIZAR ALUNO"); } void telaAtualizarProfessor(){ gotoxy(51, 7); textcolor(15); textbackground(0); printf("ATUALIZAR PROFESSOR"); } int verificaUsuario(char nomeTemp[15]) { int tamanho = strlen(nomeTemp), i, contaEspecial=0; if (tamanho==10){ for (i=0; i<10; i++) { if (ispunct(nomeTemp[i])) { contaEspecial++; } } int contaNumero=0, contaLetra; for (i=0; i<10; i++) { if (isdigit(nomeTemp[i])) { contaNumero++; } } for (i=0; i<10; i++) { if (isalpha(nomeTemp[i])) { contaLetra++; } } if ((tamanho==10)&&(contaEspecial==0)&&(contaLetra>=1)&&(contaNumero>=1)) { return 1; } } else { return 0; } } int verificaSenha(char senhaTemp[15]){ int tamanho = strlen(senhaTemp), contaMaiuscula=0, contaEspecial=0, contaNumero=0, i; if (tamanho==8){ for (i=0; i<8; i++){ if (isupper(senhaTemp[i])){ contaMaiuscula++; } } for (i=0; i<8; i++){ if (ispunct(senhaTemp[i])){ contaEspecial++; } } for (i=0; i<8; i++){ if (isdigit(senhaTemp[i])){ contaNumero++; } } if ((tamanho==8)&&(contaMaiuscula>=1)&&(contaEspecial>=1)&&(contaNumero>=1)){ return 1; } } else{ return 0; } } void ddSair(){ textbackground(15); int i; for (i=95; i<112; i++) { gotoxy(i, 5); printf(" "); gotoxy(i, 6); printf(" "); gotoxy(i, 7); printf(" "); gotoxy(i, 8); printf(" "); gotoxy(i, 9); printf(" "); gotoxy(i, 10); printf(" "); gotoxy(i, 11); printf(" "); gotoxy(i, 12); printf(" "); } gotoxy(96, 6); printf("Deseja realmente"); gotoxy(101, 7); printf("sair?"); gotoxy(98, 9); printf("Sim | CTRL+S"); gotoxy(98, 11); printf("Nao | CTRL+N"); } void ddCadastro() { int i; for (i=4; i<23; i++) { gotoxy(i, 5); printf(" "); gotoxy(i, 6); printf(" "); gotoxy(i, 7); printf(" "); gotoxy(i, 8); printf(" "); gotoxy(i, 9); printf(" "); gotoxy(i, 10); printf(" "); gotoxy(i, 11); printf(" "); gotoxy(i, 12); printf(" "); gotoxy(i, 13); printf(" "); } gotoxy(7, 6); printf("Aluno | CTRL+A "); gotoxy(6, 8); printf("Professor | CTRL+P "); gotoxy(5, 10); printf("Disciplina | CTRL+D "); gotoxy(7, 12); printf("Turma | CTRL+T "); } void ddAtualizar(){ textbackground(15); int i; for (i=71; i<89; i++) { gotoxy(i, 5); printf(" "); gotoxy(i, 6); printf(" "); gotoxy(i, 7); printf(" "); gotoxy(i, 8); printf(" "); gotoxy(i, 9); printf(" "); } gotoxy(75, 6); printf("Aluno | CTRL+A "); gotoxy(72, 8); printf("Professor | CTRL+P "); } void ddListar() { textbackground(15); int i; for (i=25; i<44; i++) { gotoxy(i, 5); printf(" "); gotoxy(i, 6); printf(" "); gotoxy(i, 7); printf(" "); gotoxy(i, 8); printf(" "); gotoxy(i, 9); printf(" "); gotoxy(i, 10); printf(" "); gotoxy(i, 11); printf(" "); gotoxy(i, 12); printf(" "); gotoxy(i, 13); printf(" "); } gotoxy(28, 6); printf("Aluno | CTRL+A "); gotoxy(27, 8); printf("Professor | CTRL+P "); gotoxy(27, 10); printf("Disciplina | CTRL+D "); gotoxy(28, 12); printf("Turma | CTRL+T "); } void ddBuscar(){ textbackground(15); int i; for (i=47; i<65; i++) { gotoxy(i, 5); printf(" "); gotoxy(i, 6); printf(" "); gotoxy(i, 7); printf(" "); gotoxy(i, 8); printf(" "); gotoxy(i, 9); printf(" "); gotoxy(i, 10); printf(" "); gotoxy(i, 11); printf(" "); } gotoxy(50, 6); printf("Aluno | CTRL+A "); gotoxy(50, 8); printf("Turma | CTRL+T "); gotoxy(48, 10); printf("Professor | CTRL+P "); } void logadoTelaInicial() { int i; textbackground(0); clrscr(); gotoxy(1,1); textbackground(2); for (i=1; i<=120; i++) { textcolor(2); gotoxy(i,1); printf(" "); gotoxy(i, 2); printf(" "); gotoxy(i, 3); printf(" "); gotoxy(i, 4); printf(" "); } gotoxy(50, 2); textcolor(15); printf("Gerenciador escolar 1.0"); gotoxy(1, 4); textbackground(15); textcolor(12); printf(" C"); textcolor(0); printf("adastro "); textcolor(12); printf("L"); textcolor(0); printf("istar "); textcolor(12); printf("B"); textcolor(0); printf("uscar "); textcolor(12); printf("A"); textcolor(0); printf("tualizar "); textcolor(12); printf(" S"); textcolor(0); printf("air "); for (i=1; i<=120; i++) { textcolor(2); gotoxy(i,29); printf(" "); } textcolor(0); gotoxy(89, 29); printf("Desenvolvido por Igor Castilho"); } void efeitoBotaoEntrar (int coluna1, int coluna2, int linha, int flag) { int i; // se a flag for 0, faz o efeito // se a flag for 1, retira o efeito if (flag ==0) { for (i= coluna1; i<coluna2; i++) { gotoxy(i, linha); printf("%c", 219); } } else if (flag==1) { gotoxy(49, 18); printf("%c", 179); gotoxy(50, 18); printf("ENTRAR"); gotoxy(56, 18); printf("%c", 179); } } void efeitoBotaoCancelar (int coluna1, int coluna2, int linha, int flag) { int i; if (flag==0) { for (i=coluna1; i<coluna2; i++) { gotoxy(i, linha); printf("%c", 219); } } else if (flag==1) { gotoxy(60, 18); printf("%c", 179); gotoxy(61, 18); printf("CANCELAR"); gotoxy(69, 18); printf("%c", 179); } } int jaCadastrado() { FILE *fp; fp = fopen("C:/Sistema/Login/login.dat", "rb"); if (fp) { fclose(fp); return 1; } else { return 0; } } int verificaLogin(char user[15], char pass[15]) { struct Login log; FILE * arquivo; arquivo = fopen("C:/Sistema/Login/login.dat","rb"); fread(&log, sizeof(struct Login), 1, arquivo); fclose(arquivo); int logiN, senha; logiN = strcmp(user, log.usuario); senha = strcmp(pass, log.senha); if ((logiN == 0)&&(senha==0)) { return 1; } else { return 0; } } void erroLogar() { textbackground(4); textcolor(14); clrscr(); gotoxy(40,10); // canto superior esquerdo printf("%c", 201); gotoxy(40,20); // canto inferior esquerdo printf("%c", 200); gotoxy(80,10); // canto superior direito printf("%c", 187); gotoxy(80,20); // canto inferior direito printf("%c", 188); int c; for (c=41; c<80; c++) // linha superior { gotoxy(c, 10); printf("%c", 205); } for (c=41; c<80; c++) // linha inferior { gotoxy(c, 20); printf("%c", 205); } for (c=11; c<20; c++) // linha lateral esquerda { gotoxy(40, c); printf("%c", 186); } for (c=11; c<20; c++) // linha lateral direita { gotoxy(80, c); printf("%c", 186); } gotoxy(43, 13); textcolor(15); printf("Erro ao logar"); gotoxy(43, 15); printf("Verifique o usuario e senha"); gotoxy(43, 18); printf("Aperte ENTER para voltar"); int tecla; tecla = getch(); if (tecla == 13) // enter { telaBasica(); telaLogin(); } else { erroLogar(); } gotoxy(8, 30); } void fazCadastroSistema(char userTemp[15], char senhaTemp[15]) { struct Login login[1]; strcpy(login[0].usuario, userTemp); strcpy(login[0].senha, senhaTemp); int i =0; for (i=49; i<57; i++) { gotoxy(i, 18); printf("%c", 219); } // tecla 13= enter // tecla 115 = s int tecla; tecla = getch(); if (tecla == 13) // enter { if (jaCadastrado()==0) { FILE *cadastro; if (cadastro == NULL) { printf("Erro de abertura"); } else { cadastro = fopen("C:/Sistema/Login/login.dat", "wb"); fwrite(login, sizeof(struct CadastroAluno),1, cadastro); fclose(cadastro); logadoTelaInicial(); } } } else if (tecla == 100) // "s" { gotoxy(49, 18); printf("%c", 179); gotoxy(50, 18); printf("ENTRAR"); gotoxy(56, 18); printf("%c", 179); for (i=60; i<70; i++) { gotoxy(i, 18); printf("%c", 219); } gotoxy(100, 30); } } void erroCadastroSistema() { textbackground(4); textcolor(14); clrscr(); gotoxy(40,13); // canto superior esquerdo printf("%c", 201); gotoxy(40,23); // canto inferior esquerdo printf("%c", 200); gotoxy(80,13); // canto superior direito printf("%c", 187); gotoxy(80,23); // canto inferior direito printf("%c", 188); int c; for (c=41; c<80; c++) // linha superior { gotoxy(c, 13); printf("%c", 205); } for (c=41; c<80; c++) // linha inferior { gotoxy(c, 23); printf("%c", 205); } for (c=14; c<23; c++) // linha lateral esquerda { gotoxy(40, c); printf("%c", 186); } for (c=14; c<23; c++) // linha lateral direita { gotoxy(80, c); printf("%c", 186); } gotoxy(43, 16); textcolor(15); printf("Erro ao cadastrar"); gotoxy(43, 18); printf("Verifique as regras de cadastro"); gotoxy(43, 21); printf("Aperte ENTER para voltar"); int tecla; tecla = getch(); if (tecla == 13) // enter { telaBasica(); telaLogin(); } else { erroCadastroSistema(); } gotoxy(8, 30); } int main() { // configuraes da tela system("MODE con cols=120 lines=30 "); telaBasica(); telaLogin(); textcolor(0); // declarao de variveis temporrias char userTemp[15], senhaTemp[15]; // declarao das variveis normais int i, tecla, logou=0, moveu =0, controle1=0, controleMenu=0; // chamar funo para verificar se existe conta no banco de dados if (jaCadastrado()==1) { // se j tiver registro no sistema, ento: gotoxy(66, 21); printf("%c", 219); // recebendo o que usurio digitou para logar gotoxy(47,12); textbackground(15); textcolor(0); scanf("%s", &userTemp); fflush(stdin); gotoxy(47,15); scanf("%s", &senhaTemp); efeitoBotaoEntrar(49, 57, 18, 0); tecla = getch(); if (tecla == 13) // enter { do { if (verificaLogin(userTemp, senhaTemp)==1) { logadoTelaInicial(); logou = 1; do { tecla = getch(); if ((tecla == 67)||(tecla==99)) { ddCadastro(); tecla = getch(); if (tecla== 1) { logadoTelaInicial(); telaCadastroAluno(); tecla = getch(); if (tecla==27){ logadoTelaInicial(); } } else if(tecla==16){ logadoTelaInicial(); telaCadastroProfessor(); tecla = getch(); if (tecla==27){ logadoTelaInicial(); } } else if (tecla==4){ logadoTelaInicial(); telaCadastroDisciplina(); tecla = getch(); if (tecla==27){ logadoTelaInicial(); } } else if (tecla==20){ logadoTelaInicial(); telaCadastroTurma(); tecla = getch(); if (tecla==27){ logadoTelaInicial(); } } else if (tecla==27){ logadoTelaInicial(); } } else if((tecla== 76)||(tecla==108)) { logadoTelaInicial(); ddListar(); tecla = getch(); if (tecla==27){ logadoTelaInicial(); } else if (tecla==1){ logadoTelaInicial(); telaListarAluno(); tecla= getch(); if (tecla==27){ logadoTelaInicial(); } } else if (tecla==16){ logadoTelaInicial(); telaListarProfessor(); tecla= getch(); if (tecla==27){ logadoTelaInicial(); } } else if (tecla==4){ logadoTelaInicial(); telaListarDisciplinas(); tecla= getch(); if (tecla==27){ logadoTelaInicial(); } } else if (tecla==20){ logadoTelaInicial(); telaListarTurmas(); tecla= getch(); if (tecla==27){ logadoTelaInicial(); } } } else if((tecla==66)||(tecla==98)){ logadoTelaInicial(); ddBuscar(); tecla = getch(); if (tecla==27){ logadoTelaInicial(); } else if (tecla==1){ logadoTelaInicial(); telaBuscarAluno(); tecla= getch(); if (tecla==27){ logadoTelaInicial(); } } else if (tecla==20){ logadoTelaInicial(); telaBuscarTurmas(); tecla= getch(); if (tecla==27){ logadoTelaInicial(); } } else if(tecla==16){ logadoTelaInicial(); telaBuscarProfessor(); tecla= getch(); if (tecla==27){ logadoTelaInicial(); } } } else if ((tecla==65)||(tecla==97)){ logadoTelaInicial(); ddAtualizar(); tecla = getch(); if (tecla==27){ logadoTelaInicial(); } else if (tecla==1){ logadoTelaInicial(); telaAtualizarAluno(); tecla= getch(); if (tecla==27){ logadoTelaInicial(); } } else if (tecla==16){ logadoTelaInicial(); telaAtualizarProfessor(); tecla= getch(); if (tecla==27){ logadoTelaInicial(); } } } else if ((tecla==83)||(tecla==115)){ logadoTelaInicial(); ddSair(); tecla = getch(); if (tecla==27){ logadoTelaInicial(); } else if (tecla==19){ break; } else if (tecla==14){ logadoTelaInicial(); } } } while (controleMenu == 0); } else { erroLogar(); gotoxy(66, 21); printf("%c", 219); // recebendo o que usurio digitou para logar gotoxy(47,12); scanf("%s", &userTemp); fflush(stdin); gotoxy(47,15); scanf("%s", &senhaTemp); efeitoBotaoEntrar(49, 57, 18, 0); tecla = getch(); } } while (logou == 0); } else if (tecla==100) { do { if (tecla == 100) { efeitoBotaoEntrar(49, 57, 18, 1); efeitoBotaoCancelar(60, 70, 18, 0); tecla = getch(); if (tecla==13) // enter { telaBasica(); telaLogin(); gotoxy(66, 21); printf("%c", 219); // recebendo o que usurio digitou para logar gotoxy(47,12); scanf("%s", &userTemp); fflush(stdin); controle1=1; gotoxy(47,15); scanf("%s", &senhaTemp); efeitoBotaoEntrar(49, 57, 18, 0); tecla = getch(); } else if((tecla==13)&&(controle1==1)) { do { if (verificaLogin(userTemp, senhaTemp)==1) { logadoTelaInicial(); logou = 1; } else { erroLogar(); gotoxy(66, 21); printf("%c", 219); // recebendo o que usurio digitou para logar gotoxy(47,12); scanf("%s", &userTemp); fflush(stdin); gotoxy(47,15); scanf("%s", &senhaTemp); efeitoBotaoEntrar(49, 57, 18, 0); // tecla = getch(); } } while (logou == 0); } else if (tecla==97) { efeitoBotaoEntrar(49, 57, 18, 0); efeitoBotaoCancelar(60, 70, 18, 1); tecla = getch(); if (tecla==13) { if (verificaLogin(userTemp, senhaTemp)==1) { moveu=1; logadoTelaInicial(); logou = 1; } } } } } while (moveu == 0); } } else { // ento faz o cadastro pela primeira vez int liberaCadastro=0; do { gotoxy(51,21); printf("%c", 219); // Recebendo nome de usurio e senha para cadastrar gotoxy(47,12); textbackground(15); textcolor(0); gets(userTemp); fflush(stdin); gotoxy(47,15); gets(senhaTemp); efeitoBotaoEntrar(49, 57, 18, 0); tecla = getch(); if (tecla ==100) { efeitoBotaoEntrar(49, 57, 18, 1); efeitoBotaoCancelar(60, 70, 18, 0); } else if (tecla==13){ if (verificaUsuario(userTemp)&&(verificaSenha(senhaTemp))) { fazCadastroSistema(userTemp, senhaTemp); liberaCadastro = 1; } else { erroCadastroSistema(); } } } while (liberaCadastro == 0); } return 0; }
Markdown
UTF-8
2,450
2.96875
3
[]
no_license
# Lab 2 - Music Search ## Milestone 1 - Artists and Albums Demo: http://distracted-kirch-3f32c6.netlify.com/ Para este milestone debes crear una pagina para ver la información de un artista, y otra página para ver la información de un álbum. Las urls deben ser `/artists/:artistId` y `/albums/:albumId`, respectivamente. La página del artista debe mostrar una lista de álbums. Cada álbum es un link a su respectiva página. En la página del álbum, deben aparecer las canciones del álbum. En la url `/` debes añadir la página `Home`, que ya debes tener. ## Milestone 2 - Search Demo: https://awesome-hoover-ef692e.netlify.com/ Ahora debes reemplazar la página de `Home`, con un `Search` de artistas. Cada uno de los resultados te debe enlazar a la página de ese artista. ## Milestone 3 - Playlists Demo: https://reverent-visvesvaraya-810152.netlify.com/ Comienza añadiendo un link en el `Header` donde te lleve a la página de tu `Playlist`. El id del playlist lo debes añadir en el archivo `constants.js`. En esa página debes cargar todas las canciones que has guardado en el playlist. Para guardar una canción debes añadir un botón al lado de cada track en la página de un álbum. La canción se debe guardar en el playlist con el id que está en el archivo de constants. ### API Docs #### Search - GET `/search?query=KEYWORDS` Ejemplo: https://react-api-lab.herokuapp.com/search?query=pink+floyd #### Artist - GET `/artists/:artistId` Ejemplo: https://react-api-lab.herokuapp.com/artists/83d91898-7763-47d7-b03b-b92132375c47 #### Album - GET `/albums/:albumId` Ejemplo: https://react-api-lab.herokuapp.com/albums/a1a86e05-c23f-4a40-b50a-14dd7da379f2 #### Playlist - GET `/playlists/:playlistId` Ejemplo: https://react-api-lab.herokuapp.com/playlists/@sparragus #### Add Track to Playlist - POST `/playlists/:playlistId` Body: `{ track: TRACK_DATA }` TRACK_DATA es la información que recibes sobre cada track en un álbum. Ejemplo: `curl 'https://react-api-lab.herokuapp.com/playlists/@sparragus' -X POST -H 'Content-Type: application/json' -d '{"track":{"trackNumber":3,"name":"Wish You Were Here","durationInSeconds":325,"album":{"id":"a2f73eb8-eee6-3588-8909-9046058a468e","name":"Wish You Were Here"},"artist":{"id":"83d91898-7763-47d7-b03b-b92132375c47","name":"Pink Floyd"}}}'` ### Tips - Puedes usar de referencia los ejercicios que hicimos en la clase 8: https://codesandbox.io/s/52zz3lv47x
Python
UTF-8
2,344
2.53125
3
[]
no_license
from src.features.build_features import * import pytest def test_can_check_raw_data(train_data_sample): assert set(train_data_sample.columns) == { 'age','ca','chol','cp','exang','fbs','oldpeak', 'restecg','sex','slope','target','thal','thalach','trestbps' } RawDataPreprocessor.check_raw_data(train_data_sample) train_data_sample['new_feature_that_should_not_raise'] = 123 RawDataPreprocessor.check_raw_data(train_data_sample) def test_raise_if_bad_columns(train_data_sample): train_data_broken = train_data_sample.rename(columns={'age': 'birthdate'}) with pytest.raises(Exception) as e_info: RawDataPreprocessor.check_raw_data(train_data_broken) train_data_broken = train_data_sample.drop(columns={'target'}) with pytest.raises(Exception) as e_info: RawDataPreprocessor.check_raw_data(train_data_broken) def test_can_select_usefull_columns(train_data_sample): RawDataPreprocessor.select_needed_columns(train_data_sample) def test_can_rename_columns(train_data_sample): preprocessed = RawDataPreprocessor.select_needed_columns(train_data_sample) RawDataPreprocessor.rename_columns(preprocessed) def test_can_make_human_readable_categories(train_data_sample): preprocessed = RawDataPreprocessor.select_needed_columns(train_data_sample) preprocessed = RawDataPreprocessor.rename_columns(preprocessed) RawDataPreprocessor.make_human_readable_categories(preprocessed) def test_can_process_categorical_features(train_data_sample): preprocessed = RawDataPreprocessor.select_needed_columns(train_data_sample) preprocessed = RawDataPreprocessor.rename_columns(preprocessed) preprocessed = RawDataPreprocessor.make_human_readable_categories(preprocessed) RawDataPreprocessor.process_categorical_features(preprocessed) def test_can_preprocess_raw_data(train_data_sample, expected_columns): transformer = RawDataPreprocessor() train_data_transformed = transformer.fit_transform(train_data_sample) assert set(expected_columns) == set(train_data_transformed.columns) def test_can_preprocess_fake_data(fake_data, expected_columns): transformer = RawDataPreprocessor() train_data_transformed = transformer.fit_transform(fake_data) assert all([i in train_data_transformed.columns for i in expected_columns])
JavaScript
UTF-8
3,213
4.75
5
[]
no_license
// Problem #1 // We are creating the motivation function that takes in 2 parameters firstname and lastname. Inside the motivation function we // have a message function that returns the welcome tex plus the firstname and the last name the ' ' are just being used for spacing function motivation(firstname, lastname){ var welcomeText = 'Your doing awesome keep it up '; function message() { return welcomeText + firstname + lastname; } return message() } // This is a great example of using closure to only make the things public that we want public. // This is an example of the classic module pattern. var outerFunction = (function() { var personObj = { name: "Bob", age: 28, gender: "male" }; return { name: function () { return personObj.name; } } })(); outerFunction.name(); var module = (function() { var person = { name: "phillip", age: 29, location: 'Utah' }; var privateMethod = function(){ return person.name + ' ' + person.age + ' ' + person.location }; // Anything that is being returned is made public and can be invoked from outside our lexical scope return { publicMethod: function () { return privateMethod() } }; })(); module.publicMethod(); var module2 = (function() { var privateMethod = function(name, age, location){ return name + ' ' + age + ' ' + location }; // Anything that is being returned is made public and can be invoked from outside our lexical scope return { publicMethod: function (name,age,location) { return privateMethod(name,age,location) } }; })(); module2.publicMethod('ben', 29, 'UTAH'); var smoothy = (function() { var blend = function(name, age, location){ return name + ' ' + age + ' ' + location }; // Anything that is being returned is made public and can be invoked from outside our lexical scope return { makeSmoothy: function (name,age,location) { return blend(name,age,location) } }; })(); smoothy.makeSmoothy('ben', 29, 'UTAH'); //pass in a argument to the private function // Problem #5 // At first glance you might think that this would work, but it doesn't because we haven't given each iteration a scope //THIS WILL NOT WORK for(var i =1; i<=5; i++) { setTimeout(function() { console.log('i: ' + i); },i*1000) } // // // // ////THIS WILL WORK // //// this will work because of closure. //// Inside our for loop we have function that takes in i and then an IIFE at the end to invoke the function with the argument of i //// The reason that we did this was because we needed to create a new scope for every iteration // // // for(var i = 1; i<=5; i++) { (function(i) { setTimeout(function() { console.log('i: ' + i); },i*1000) })(i) } // Write a smoothy machine closure function blender(fruit) { var b = fruit; var y = 'yogurt'; function bs() { alert( b + ' and ' + y + ' makes ' + b + ' swirl'); } bs(); } blender('blueberry');
PHP
UTF-8
31,196
2.6875
3
[]
no_license
<?php /** * @file * Class to work with Culturefeeds Entry API. */ class CultureFeed_EntryApi implements CultureFeed_EntryApi_IEntryApi { /** * Status code when an item has been succesfully created. * @var string */ const CODE_ITEM_CREATED = 'ItemCreated'; /** * Status code when an item has been succesfully updated. * @var string */ const CODE_ITEM_MODIFIED = 'ItemModified'; /** * Status code when an item has bene succesfully deleted. * @var string */ const CODE_ITEM_DELETED = 'ItemWithdrawn'; /** * Status code when a translation has been succesfully created. * @var string */ const CODE_TRANSLATION_CREATED = 'TranslationCreated'; /** * Status code when a translation has been succesfully deleted/withdrawn. * @var string */ const CODE_TRANSLATION_WITHDRAWN = 'TranslationWithdrawn'; /** * Status code when a link has been succesfully created. * @var string */ const CODE_LINK_CREATED = 'LinkCreated'; /** * Status code when a link has been succesfully withdrawn. * @var string */ const CODE_LINK_WITHDRAWN = 'LinkWithdrawn'; /** * Status code when the keywords are succesfully updated. * @var string */ const CODE_KEYWORDS_CREATED = 'KeywordsCreated'; /** * Status code when the keyword is succesfully deleted. * @var string */ const CODE_KEYWORD_DELETED = 'KeywordWithdrawn'; /** * Status code when the keyword can only be used by admins. * @var string */ const CODE_KEYWORD_PRIVATE = 'PrivateKeyword'; /** * @var string */ private $cdbXmlVersion; /** * Constructor for a new CultureFeed_EntryApi instance. * * @param CultureFeed_OAuthClient $oauth_client * A OAuth client to make requests. * */ public function __construct( CultureFeed_OAuthClient $oauth_client, $cdbXmlVersion = '3.2' ) { $this->oauth_client = $oauth_client; $this->cdbXmlVersion = $cdbXmlVersion; } /** * Search events on the entry api. * * @param string $query * String to search for. * @param int $page * Page number to get. * @param int $page_length * Items requested for current page. * @param string $sort * Sort type. * @param string $updated_since * Correct ISO date format (yyyy-m-dTH): example 2012-12-20T12:21. * * @return CultureFeed_Cdb_List_Results */ public function getEvents($query, $page = NULL, $page_length = NULL, $sort = NULL, $updated_since = NULL) { return $this->search('event', $query, $page, $page_length, $sort, $updated_since); } /** * Search productions on the entry api. * * @param string $query * Query to search. * @param string $updated_since * Correct ISO date format (yyyy-m-dTH): example 2012-12-20T12:21. * @param int $page * Page number to get. * @param int $page_length * Items requested for current page. * @param string $sort * Sort type. * * @return CultureFeed_Cdb_List_Results */ public function getProductions($query, $page = NULL, $page_length = NULL, $sort = NULL, $updated_since = NULL) { return $this->search('production', $query, $page, $page_length, $sort, $updated_since); } /** * Search actors on the entry api. * * @param string $query * String to search for. * @param int $page * Page number to get. * @param int $page_length * Items requested for current page. * @param string $sort * Sort type. * @param string $updated_since * Correct ISO date format (yyyy-m-dTH): example 2012-12-20T12:21. * * @return CultureFeed_Cdb_List_Results */ public function getActors($query, $page = NULL, $page_length = NULL, $sort = NULL, $updated_since = NULL) { return $this->search('actor', $query, $page, $page_length, $sort, $updated_since); } /** * Get an event. * * @param string $id * ID of the event to load. * * @return CultureFeed_Cdb_Item_Event * @throws CultureFeed_ParseException */ public function getEvent($id) { $result = $this->oauth_client->authenticatedGetAsXml('event/' . $id); try { $xml = new CultureFeed_SimpleXMLElement($result); } catch (Exception $e) { throw new CultureFeed_ParseException($result); } if ($xml->event) { $eventXml = $xml->event; return CultureFeed_Cdb_Item_Event::parseFromCdbXml($eventXml); } throw new CultureFeed_ParseException($result); } /** * Create a new event. * * @param CultureFeed_Cdb_Item_Event $event * The event to create. * * @return string * The id from the newly created event. * */ public function createEvent(CultureFeed_Cdb_Item_Event $event) { $cdb = new CultureFeed_Cdb_Default($this->cdbXmlVersion); $cdb->addItem($event); $cdb_xml = $cdb->__toString(); $result = $this->oauth_client->authenticatedPostAsXml('event', array('raw_data' => $cdb_xml), TRUE); $xml = $this->validateResult($result, array(self::CODE_ITEM_CREATED, self::CODE_ITEM_MODIFIED)); return basename($xml->xpath_str('/rsp/link')); } /** * Update an event. * * @param CultureFeed_Cdb_Item_Event $event * The event to update. */ public function updateEvent(CultureFeed_Cdb_Item_Event $event) { $cdb = new CultureFeed_Cdb_Default($this->cdbXmlVersion); $cdb->addItem($event); $cdbXml = (string) $cdb; $result = $this->oauth_client->authenticatedPostAsXml('event/' . $event->getCdbId(), array('raw_data' => $cdbXml), TRUE); $xml = $this->validateResult($result, self::CODE_ITEM_MODIFIED); } /** * Delete an event. * * @param string $id * ID from the event. */ public function deleteEvent($id) { $result = $this->oauth_client->authenticatedDeleteAsXml('event/' . $id); $xml = $this->validateResult($result, self::CODE_ITEM_DELETED); } /** * Get an production. * * @param string $id * ID of the production to load. * * @return CultureFeed_Cdb_Item_Event * @throws CultureFeed_ParseException */ public function getProduction($id) { $result = $this->oauth_client->authenticatedGetAsXml('production/' . $id); try { $xml = new CultureFeed_SimpleXMLElement($result); } catch (Exception $e) { throw new CultureFeed_ParseException($result); } if ($xml->production) { $productionXml = $xml->production; return CultureFeed_Cdb_Item_Production::parseFromCdbXml($productionXml); } throw new CultureFeed_ParseException($result); } /** * Create a new production. * * @param CultureFeed_Cdb_Item_Production $production * The production to create. * * @return string * The id from the newly created production. */ public function createProduction(CultureFeed_Cdb_Item_Production $production) { $cdb = new CultureFeed_Cdb_Default($this->cdbXmlVersion); $cdb->addItem($production); $cdb_xml = $cdb->__toString(); $result = $this->oauth_client->authenticatedPostAsXml('production', array('raw_data' => $cdb_xml), TRUE); $xml = $this->validateResult($result, self::CODE_ITEM_CREATED); return basename($xml->xpath_str('/rsp/link')); } /** * Update an production. * * @param CultureFeed_Cdb_Item_Production $production * The production to update. */ public function updateProduction(CultureFeed_Cdb_Item_Production $production) { $cdb = new CultureFeed_Cdb_Default($this->cdbXmlVersion); $cdb->addItem($production); $result = $this->oauth_client->authenticatedPostAsXml('production/' . $production->getCdbId(), array('raw_data' => $cdb->__toString()), TRUE); $xml = $this->validateResult($result, self::CODE_ITEM_MODIFIED); } /** * Delete an production. * * @param string $id * ID from the production. */ public function deleteProduction($id) { $result = $this->oauth_client->authenticatedDeleteAsXml('production/' . $id); $xml = $this->validateResult($result, self::CODE_ITEM_DELETED); } /** * Get an actor. * * @param string $id * ID of the actor to load. * * @return CultureFeed_Cdb_Item_Actor * @throws CultureFeed_ParseException */ public function getActor($id) { $result = $this->oauth_client->authenticatedGetAsXml('actor/' . $id); try { $xml = new CultureFeed_SimpleXMLElement($result); } catch (Exception $e) { throw new CultureFeed_ParseException($result); } if ($xml->actor) { $actorXml = $xml->actor; return CultureFeed_Cdb_Item_Actor::parseFromCdbXml($actorXml); } throw new CultureFeed_ParseException($result); } /** * Create a new actor. * * @param CultureFeed_Cdb_Item_Actor $actor * The actor to create. * * @return string * The id from the newly created actor. */ public function createActor(CultureFeed_Cdb_Item_Actor $actor) { $cdb = new CultureFeed_Cdb_Default($this->cdbXmlVersion); $cdb->addItem($actor); $cdb_xml = $cdb->__toString(); $result = $this->oauth_client->authenticatedPostAsXml('actor', array('raw_data' => $cdb_xml), TRUE); $xml = $this->validateResult($result, self::CODE_ITEM_CREATED); return basename($xml->xpath_str('/rsp/link')); } /** * Update an actor. * * @param CultureFeed_Cdb_Item_Actor $actor * The actor to update. */ public function updateActor(CultureFeed_Cdb_Item_Actor $actor) { $cdb = new CultureFeed_Cdb_Default($this->cdbXmlVersion); $cdb->addItem($actor); $result = $this->oauth_client->authenticatedPostAsXml('actor/' . $actor->getCdbId(), array('raw_data' => $cdb->__toString()), TRUE); $xml = $this->validateResult($result, self::CODE_ITEM_MODIFIED); } /** * Delete an actor. * * @param string $id * ID from the actor. */ public function deleteActor($id) { $result = $this->oauth_client->authenticatedDeleteAsXml('actor/' . $id); $xml = $this->validateResult($result, self::CODE_ITEM_DELETED); } /** * Add tags to an event. * * @param CultureFeed_Cdb_Item_Event $event * Event where the tags will be added to. * @param string[]|CultureFeed_Cdb_Data_Keyword[] $keywords * Tags to add, each tag being either a scalar string or a * CultureFeed_Cdb_Data_Keyword object. */ public function addTagToEvent(CultureFeed_Cdb_Item_Event $event, $keywords) { $this->addTags('event', $event->getCdbId(), $keywords); } /** * Add tags to a production. * * @param CultureFeed_Cdb_Item_Production $production * Production where the tags will be added to. * @param array $keywords * Tags to add. */ public function addTagToProduction(CultureFeed_Cdb_Item_Production $production, $keywords) { $this->addTags('production', $production->getCdbId(), $keywords); } /** * Add tags to a actor. * * @param CultureFeed_Cdb_Item_Actor $actor * Actor where the tags will be added to. * @param array $keywords * Tags to add. */ public function addTagToActor(CultureFeed_Cdb_Item_Actor $actor, $keywords) { $this->addTags('actor', $actor->getCdbId(), $keywords); } /** * Add translation to an event. * * @param CultureFeed_Cdb_Item_Event $event * Event where the translation will be added to. * @param String $lang * Language to add. * @param String $title * Title of the translation. * @param String $shortDescription * Short description of the translation. * @param String $longDescription * Long description of the translation. */ public function addTranslationToEvent(CultureFeed_Cdb_Item_Event $event, $lang, $title = '', $shortDescription = '', $longDescription = '') { $this->addTranslation('event', $event->getCdbId(), $lang, $title, $shortDescription, $longDescription); } /** * Add translation to an actor. * * @param CultureFeed_Cdb_Item_Actor $actor * Actor where the translation will be added to. * @param String $lang * Language to add. * @param String $title * Title of the translation. * @param String $shortDescription * Short description of the translation. * @param String $longDescription * Long description of the translation. */ public function addTranslationToActor(CultureFeed_Cdb_Item_Actor $actor, $lang, $title = '', $shortDescription = '', $longDescription = '') { $this->addTranslation('actor', $actor->getCdbId(), $lang, $title, $shortDescription, $longDescription); } /** * Add translation to an production. * * @param CultureFeed_Cdb_Item_Production $production * Production where the translation will be added to. * @param String $lang * Language to add. * @param String $title * Title of the translation. * @param String $shortDescription * Short description of the translation. * @param String $longDescription * Long description of the translation. */ public function addTranslationToProduction(CultureFeed_Cdb_Item_Production $production, $lang, $title = '', $shortDescription = '', $longDescription = '') { $this->addTranslation('production', $production->getCdbId(), $lang, $title, $shortDescription, $longDescription); } /** * Add link to a production. * * @param CultureFeed_Cdb_Item_Production $production * Production where the link will be added to. * @param String $link * Link to add. * @param String $linkType * Link type.["video", "text", "imageweb", "webresource", "reservations"] * @param String $lang * Language of the link ["NL", "FR", "DE", "EN"] * @param string $title * @param string $copyright * @param string $subBrand * @param string $description */ public function addLinkToProduction( CultureFeed_Cdb_Item_Production $production, $link, $linkType = '', $lang = '', $title = '', $copyright = '', $subBrand = '', $description = '' ) { $this->addLink( 'production', $production->getCdbId(), $link, $linkType, $lang, $title, $copyright, $subBrand, $description ); } /** * @param CultureFeed_Cdb_Item_Production $production * @param string $lang * @param string $plainText * @param string $title * @param string $copyright * @param string $subBrand * @param string $description */ public function addCollaborationLinkToProduction( CultureFeed_Cdb_Item_Production $production, $lang, $plainText, $title = '', $copyright = '', $subBrand = '', $description = '' ) { $this->addCollaborationLink( 'production', $production->getCdbId(), $lang, $plainText, $title, $copyright, $subBrand, $description ); } /** * Add link to an event. * * @param CultureFeed_Cdb_Item_Event $event * Event where the link will be added to. * @param string $link * Link to add. * @param string $linkType * Link type.["video", "text", "imageweb", "webresource", "reservations"] * @param string $lang * Language of the link ["NL", "FR", "DE", "EN"] * @param string $title * Title of the link. * @param string $copyright * The image copyright (description). * @param string $subBrand * The consumer key. * @param string $description * The description. */ public function addLinkToEvent( CultureFeed_Cdb_Item_Event $event, $link, $linkType = '', $lang = '', $title = '', $copyright = '', $subBrand = '', $description = '' ) { $this->addLink( 'event', $event->getCdbId(), $link, $linkType, $lang, $title, $copyright, $subBrand, $description ); } /** * @param CultureFeed_Cdb_Item_Event $event * @param string $lang * @param string $plainText * @param string $title * @param string $copyright * @param string $subBrand * @param string $description */ public function addCollaborationLinkToEvent( CultureFeed_Cdb_Item_Event $event, $lang, $plainText, $title = '', $copyright = '', $subBrand = '', $description = '' ) { $this->addCollaborationLink( 'event', $event->getCdbId(), $lang, $plainText, $title, $copyright, $subBrand, $description ); } /** * Add link to an actor. * * @param CultureFeed_Cdb_Item_Actor $actor * Actor where the link will be added to. * @param string $link * Link to add. * @param string $linkType * Link type.["video", "text", "imageweb", "webresource", "reservations"] * @param string $lang * Language of the link ["NL", "FR", "DE", "EN"] * @param string $title * @param string $copyright * @param string $subBrand * @param string $description */ public function addLinkToActor( CultureFeed_Cdb_Item_Actor $actor, $link, $linkType = '', $lang = '', $title = '', $copyright = '', $subBrand = '', $description = '' ) { $this->addLink( 'actor', $actor->getCdbId(), $link, $linkType, $lang, $title, $copyright, $subBrand, $description ); } /** * @param CultureFeed_Cdb_Item_Actor $actor * @param string $lang * @param string $plainText * @param string $title * @param string $copyright * @param string $subBrand * @param string $description */ public function addCollaborationLinkToActor( CultureFeed_Cdb_Item_Actor $actor, $lang, $plainText, $title = '', $copyright = '', $subBrand = '', $description = '' ) { $this->addCollaborationLink( 'actor', $actor->getCdbId(), $lang, $plainText, $title, $copyright, $subBrand, $description ); } /** * Remove tags from an event. * * @param CultureFeed_Cdb_Item_Event $event * Event where the tags will be removed from. * @param string $keyword * Tag to remove. */ public function removeTagFromEvent(CultureFeed_Cdb_Item_Event $event, $keyword) { $this->removeTag('event', $event->getCdbId(), $keyword); } /** * Remove tags from an production. * * @param CultureFeed_Cdb_Item_Production $production * Event where the tags will be removed from. * @param string $keyword * Tag to remove. */ public function removeTagFromProduction(CultureFeed_Cdb_Item_Production $production, $keyword) { $this->removeTag('production', $production->getCdbId(), $keyword); } /** * Remove tags from an actor. * * @param CultureFeed_Cdb_Item_Actor $actor * Actor where the tags will be removed from. * @param string $keyword * Tag to remove. */ public function removeTagFromActor(CultureFeed_Cdb_Item_Actor $actor, $keyword) { $this->removeTag('actor', $actor->getCdbId(), $keyword); } /** * Withdraw translation for an event. * * @param CultureFeed_Cdb_Item_Event $event * Event where the translation will be removed for. * @param string $lang * Language of the translation to remove. */ public function removeTranslationFromEvent(CultureFeed_Cdb_Item_Event $event, $lang) { $this->removeTranslation('event', $event->getCdbId(), $lang); } /** * Withdraw translation for an actor. * * @param CultureFeed_Cdb_Item_Actor $actor * Actor where the translation will be removed for. * @param string $lang * Language of the translation to remove. */ public function removeTranslationFromActor(CultureFeed_Cdb_Item_Actor $actor, $lang) { $this->removeTranslation('actor', $actor->getCdbId(), $lang); } /** * Withdraw translation for an production. * * @param CultureFeed_Cdb_Item_Production $production * Production where the translation will be removed for. * @param string $lang * Language of the translation to remove. */ public function removeTranslationFromProduction(CultureFeed_Cdb_Item_Production $production, $lang) { $this->removeTranslation('production', $production->getCdbId(), $lang); } /** * Withdraw link for an event. * * @param CultureFeed_Cdb_Item_Event $event * Event where the translation will be removed for. * @param string $link * Link to remove. */ public function removeLinkFromEvent(CultureFeed_Cdb_Item_Event $event, $link) { $this->removeLink('event', $event->getCdbId(), $link); } /** * Withdraw link for an production. * * @param CultureFeed_Cdb_Item_Production $production * Production where the link will be removed for. * @param string $link * Link to remove. */ public function removeLinkFromProduction(CultureFeed_Cdb_Item_Production $production, $link) { $this->removeLink('production', $production->getCdbId(), $link); } /** * Withdraw link for an actor. * * @param CultureFeed_Cdb_Item_Actor $actor * Actor where the link will be removed for. * @param string $link * Link to remove. */ public function removeLinkFromActor(CultureFeed_Cdb_Item_Actor $actor, $link) { $this->removeLink('actor', $actor->getCdbId(), $link); } /** * Search items on the entry api. * * @param string $type * @param string $query * Query to search. * @param int $page * Page number to get. * @param int $page_length * Items requested for current page. * @param string $sort * Sort type. * @param string $updated_since * Correct ISO date format (yyyy-m-dTH): example 2012-12-20T12:21 * * @return CultureFeed_Cdb_List_Results * * @throws CultureFeed_ParseException */ private function search($type, $query, $page, $page_length, $sort, $updated_since) { $args = array( 'q' => $query ); if ($updated_since) { $args['updatedsince'] = $updated_since; } if ($page) { $args['page'] = $page; } if ($page_length) { $args['pagelength'] = $page_length; } if ($sort) { $args['sort'] = $sort; } $result = $this->oauth_client->authenticatedGetAsXml($type, $args); try { $xml = new CultureFeed_SimpleXMLElement($result); } catch (Exception $e) { throw new CultureFeed_ParseException($result); } return CultureFeed_Cdb_List_Results::parseFromCdbXml($xml); } /** * Add tags to an item. * * @param string $type * Type of item to update. * @param $id * Id from the event / actor / production to add keywords for. * @param string[]|CultureFeed_Cdb_Data_Keyword[] $keywords * Keywords to add. */ private function addTags($type, $id, $keywords) { $keywords = $this->keywordsAsObjects($keywords); $visibles = array(); $values = array(); foreach ($keywords as $keyword) { $values[] = $keyword->getValue(); $visibles[] = $keyword->isVisible() ? 'true' : 'false'; } $params = array( 'keywords' => implode(';', $values), ); // The default is true, so only add visibles if at least one is false. if (in_array('false', $visibles)) { $params['visibles'] = implode(';', $visibles); } $result = $this->oauth_client->authenticatedPostAsXml($type . '/' . $id . '/keywords', $params); $xml = $this->validateResult($result, self::CODE_KEYWORDS_CREATED); } /** * Returns an array of CultureFeed_Cdb_Data_Keyword objects, based on an array * of potentially mixed scalar string and CultureFeed_Cdb_Data_Keyword items. * * @param string[]|CultureFeed_Cdb_Data_Keyword[] $keywords * * @return CultureFeed_Cdb_Data_Keyword[] */ private function keywordsAsObjects($keywords) { return array_map( array($this, 'keywordAsObject'), $keywords ); } /** * Ensures a given keyword is transformed to a CultureFeed_Cdb_Data_Keyword * object. * * @param string|CultureFeed_Cdb_Data_Keyword $keyword * * @return CultureFeed_Cdb_Data_Keyword */ private function keywordAsObject($keyword) { $this->validateKeyword($keyword); if (is_string($keyword)) { $keyword = new CultureFeed_Cdb_Data_Keyword($keyword, TRUE); } return $keyword; } /** * Validates that the keyword is of a proper type. * * @param string|CultureFeed_Cdb_Data_Keyword $keyword * * @return void * @throws InvalidArgumentException */ private function validateKeyword($keyword) { if (!is_string($keyword) && !$keyword instanceof CultureFeed_Cdb_Data_Keyword) { throw new InvalidArgumentException('Unexpected value for keyword, given: ' . gettype($keyword)); } } /** * Remove tags from an item. * * @param string $type * Type of item to update. * @param string $id * Id from the event / actor / production to update. * @param string $keyword * Tag to remove. */ private function removeTag($type, $id, $keyword) { $result = $this->oauth_client->authenticatedDeleteAsXml($type . '/' . $id . '/keywords', array('keyword' => $keyword)); $xml = $this->validateResult($result, self::CODE_KEYWORD_DELETED); } /** * Add Translation for an item. * * @param string $type * Type of item to translate. * @param $id * Id of the CultureFeed_Cdb_Item_Base (E.g. event, actor, production) to update. * @param String $lang * Language to add. * @param String $title * Title of the translation. * @param String $shortDescription * Short description of the translation. * @param String $longDescription * Long description of the translation. */ private function addTranslation($type, $id, $lang, $title = '', $shortDescription = '', $longDescription = '') { $result = $this->oauth_client->authenticatedPostAsXml($type . '/' . $id . '/translations', array( 'lang' => $lang, 'title' => $title, 'shortdescription' => $shortDescription, 'longdescription' => $longDescription, )); $xml = $this->validateResult($result, self::CODE_TRANSLATION_CREATED); } /** * Remove Translation from an item. * * @param string $type * Type of item to update. * @param string $id * Id of the CultureFeed_Cdb_Item_Base to remove. * @param String $lang * Language to add. */ private function removeTranslation($type, $id, $lang) { $result = $this->oauth_client->authenticatedDeleteAsXml($type . '/' . $id . '/translations', array('lang' => $lang)); $xml = $this->validateResult($result, self::CODE_TRANSLATION_WITHDRAWN); } /** * Add Link for an item. * * @param string $type * Type of item to translate. * @param $id * Id of the CultureFeed_Cdb_Item_Base (E.g. event, actor, production) to update with a link. * @param String $link * Link itself. * @param String $linkType * Link type. * @param String $lang * Language to add. * @param String $title * Title of the link. * @param String $copyright * The image copyright (description). * @param String $subBrand * The consumer key. * @param String $description * The description. */ private function addLink( $type, $id, $link, $linkType, $lang, $title = '', $copyright = '', $subBrand = '', $description = '' ) { $result = $this->oauth_client->authenticatedPostAsXml($type . '/' . $id . '/links', array( 'link' => $link, 'linktype' => $linkType, 'lang' => $lang, 'title' => $title, 'copyright' => $copyright, 'subbrand' => $subBrand, 'description' => $description )); $this->validateResult($result, self::CODE_LINK_CREATED); } private function addCollaborationLink( $type, $id, $lang, $plainText, $title = '', $copyright = '', $subBrand = '', $description = '' ) { $result = $this->oauth_client->authenticatedPostAsXml($type . '/' . $id . '/links', array( 'plaintext' => $plainText, 'linktype' => 'collaboration', 'lang' => $lang, 'title' => $title, 'copyright' => $copyright, 'subbrand' => $subBrand, 'description' => $description )); $this->validateResult($result, self::CODE_LINK_CREATED); } /** * Remove Link from an item. * * @param string $type * Type of item to update. * @param string $id * Id of the CultureFeed_Cdb_Item_Base to remove. * @param String $link * Link itself. */ private function removeLink($type, $id, $link) { $result = $this->oauth_client->authenticatedDeleteAsXml($type . '/' . $id . '/links', array('link' => $link)); $xml = $this->validateResult($result, self::CODE_LINK_WITHDRAWN); } /** * Check the permission of a user to edit one or more items. * * @param string $userid * User id of the user. * @param string $email * Email address of that user * @param Array $ids * Array of ids to check. * @return CultureFeed_SimpleXMLElement * * @throws CultureFeed_ParseException */ public function checkPermission($userid, $email, $ids) { $params = array( 'user' => $userid, 'email' => $email, 'ids' => $ids, ); $result = $this->oauth_client->authenticatedGetAsXml('event/checkpermission', $params); try { $object = new CultureFeed_SimpleXMLElement($result); } catch (Exception $e) { throw new CultureFeed_ParseException($result); } return $object; } /** * Validate the request result. * * @param string $result * Result from the request. * @param string $valid_status_code * Status code if this is a valid request. * @return CultureFeed_SimpleXMLElement The parsed xml. * * @throws CultureFeed_ParseException * If the result could not be parsed. * @throws CultureFeed_InvalidCodeException * If no valid result status code. */ private function validateResult($result, $valid_status_code) { if (!is_array($valid_status_code)) { $valid_status_code = array($valid_status_code); } try { $xml = new CultureFeed_SimpleXMLElement($result); } catch (Exception $e) { throw new CultureFeed_ParseException($result); } $status_code = $xml->xpath_str('/rsp/code'); if (empty($status_code)) { $status_code = $xml->xpath_str('/response/code'); $status_message = $xml->xpath_str('/response/message'); } else { $status_message = $xml->xpath_str('/rsp/message'); } if (in_array($status_code, $valid_status_code)) { return $xml; } throw new CultureFeed_InvalidCodeException($status_message, $status_code); } }
PHP
UTF-8
1,508
2.765625
3
[]
no_license
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <link href="./buyagrade.css" type="text/css" rel="stylesheet" /> <?php $name = $_POST["name"]; $section = $_POST["section"]; $cardnumber = $_POST["cardnumber"]; $cardtype = $_POST["cardtype"]; $file = 'data.txt'; $info = "$name; $section; $cardnumber; $cardtype \n"; file_put_contents($file,$info, FILE_APPEND); if (!$_POST["name"]||!$_POST["section"]|| !$_POST["cardnumber"] || !$_POST["cardtype"]) { $msg_to_user = '<h1> Sorry</h1> <p> You did not fill out the form completely. <a href="https://codd.cs.gsu.edu/~dpatel160/WP/CW/5/cw5.php">Try again?</a> </p>'; echo $msg_to_user ; exit(); } ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Buy Your Way to a Better Education!</title> <link href="buyagrade.css" type="text/css" rel="stylesheet" /> </head> <body> <h1>Thanks, sucker!</h1> <p>Your information has been recorded.</p> <dl> <dt>Name</dt> <dd> <?php echo $name; echo "<br>"; ?> </dd> <dt>Section</dt> <dd> <?php echo $section; echo "<br>"; ?> </dd> <dt>Credit Card</dt> <dd> <?php echo "$cardnumber ($cardtype)"; echo "<br><br>"; ?> </dd> <dt> Here are all of the other suckers that have submitted here:</dt> <dd> <?php echo nl2br(file_get_contents('data.txt')) ; ?> </dd> </dl> </body> </html>
Python
UTF-8
362
2.734375
3
[]
no_license
class Solution: def partitionLabels(self, S: str) -> List[int]: _map = {c: i for i, c in enumerate(S)} _max = prevIndex = 0 res = [] for i, c in enumerate(S): _max = max(_max, _map[c]) if _max == i: res.append(i - prevIndex + 1) prevIndex = i + 1 return res
JavaScript
UTF-8
1,724
2.59375
3
[]
no_license
var player; var walls; var cursors; var wasd; var bullets; var fireRate = 400; var nextFire = 0; function create() { //game settings game.world.setBounds(-1000, -1000, 2000, 2000); game.physics.startSystem(Phaser.Physics.ARCADE); game.add.tileSprite(-1000, -1000, 2000, 2000, 'ground'); //walls walls = game.add.group(); walls.enableBody = true; var wall = walls.create(400, 400, 'wall'); wall.body.immovable = true; wall = walls.create(-150, 250, 'wall'); wall.body.immovable = true; //player player = game.add.sprite(0, 0, 'dude'); player.anchor.set(0.5); player.scale.setTo(1); player.animations.add('left', [22, 23, 24, 25, 26, 27, 28], 10, true); player.animations.add('right', [33, 34, 35, 36, 37, 38, 39], 10, true); player.animations.add('down', [0, 1, 2, 3, 4, 5, 6], 10, true); player.animations.add('up', [11, 12, 13, 14, 15, 16, 17], 10, true); game.camera.follow(player); game.physics.arcade.enable(player); player.body.collideWorldBounds = true; //bullets bullets = game.add.group(); bullets.enableBody = true; game.physics.arcade.enable(bullets); bullets.createMultiple(50, 'bullet'); bullets.setAll('anchor.x', 0.5); bullets.setAll('anchor.y', 0.5); bullets.setAll('checkWorldBounds', true); bullets.setAll('outOfBoundsKill', true); // Our controls. cursors = game.input.keyboard.createCursorKeys(); wasd = { up: game.input.keyboard.addKey(Phaser.Keyboard.W), down: game.input.keyboard.addKey(Phaser.Keyboard.S), left: game.input.keyboard.addKey(Phaser.Keyboard.A), right: game.input.keyboard.addKey(Phaser.Keyboard.D), }; }
Markdown
UTF-8
416
2.78125
3
[]
no_license
# TicTacToe TicTacToe Game in Python! # Download Game .exe [Download Game](http://www.mediafire.com/file/opvxpul6v7nrpyy/TicTacToeGame.rar) # The positions you type is equal to the numpad of a keyboard for example: ![alt text](https://i.imgur.com/5sdNOeb.png) Every number is a position where you can place 'X' or 'O'. # Run Game **1. Open CMD** **2. Cd 'location of this file'** **3. python TicTacToe.py**
Java
UTF-8
2,895
2.453125
2
[]
no_license
package com.example.yunihafsari.fypversion3.ui.adapters; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import com.example.yunihafsari.fypversion3.R; import com.example.yunihafsari.fypversion3.model.apps_model.Contact; import com.example.yunihafsari.fypversion3.sqlite.adapter.ItemClickListener; import java.util.ArrayList; /** * Created by yunihafsari on 02/05/2017. */ public class DuplicateNameAdapter extends RecyclerView.Adapter<DuplicateNameAdapter.Holder>{ private ArrayList<Contact> contacts; private ArrayList<Contact> checkedContact = new ArrayList<>(); public DuplicateNameAdapter(ArrayList<Contact> contacts) { this.contacts = contacts; } @Override public Holder onCreateViewHolder(ViewGroup parent, int viewType) { View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.duplicate_name_model, parent, false); return new Holder(row); } @Override public void onBindViewHolder(final Holder holder, final int position) { holder.duplicate_name.setText(contacts.get(position).getName()); holder.duplicate_phone_number.setText(contacts.get(position).getPhone_number()); holder.setItemClickListener(new ItemClickListener() { @Override public void onItemClickListener(View v, int pos) { CheckBox checkBox = (CheckBox)v; if(checkBox.isChecked()){ checkedContact.add(contacts.get(pos)); }else if(!(checkBox.isChecked())){ checkedContact.remove(contacts.get(pos)); } } }); } public ArrayList<Contact> getCheckedContact() { return checkedContact; } @Override public int getItemCount() { return contacts.size(); } public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener{ private TextView duplicate_name; private TextView duplicate_phone_number; private CheckBox checkBox; ItemClickListener itemClickListener; public Holder(View itemView) { super(itemView); duplicate_name = (TextView) itemView.findViewById(R.id.model_name); duplicate_phone_number = (TextView) itemView.findViewById(R.id.model_number); checkBox = (CheckBox) itemView.findViewById(R.id.checkBox); checkBox.setOnClickListener(this); } @Override public void onClick(View v) { this.itemClickListener.onItemClickListener(v, getLayoutPosition()); } public void setItemClickListener(ItemClickListener itemClickListener){ this.itemClickListener=itemClickListener; } } }
C
UTF-8
2,500
2.796875
3
[ "MIT-Modern-Variant", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#include "filesys/inode.h" #include <list.h> #include <debug.h> #include <round.h> #include <string.h> #include "filesys/filesys.h" #include "filesys/free-map.h" #include "threads/malloc.h" #include "filesys/cache.h" static struct cache_element cache[65]; static int clock; void cache_init() { int n; for(n = 0; n < 65; n++){ cache[n].sector = -1; } clock = 0; } int cache_evict() { int n = clock + 1; if(n == 65) n = 0; while(n != clock){ if(!cache[n].accessed && !cache[n].dirty){ clock = n; return n; } cache[n].accessed = 0; n += 1; if(n == 65) n = 0; } n += 1; if(n == 65) n = 0; while(n != clock){ if(!cache[n].accessed && !cache[n].dirty){ clock = 0; return n; } cache[n].dirty = 0; n += 1; if(n == 65) n = 0; } n += 1; if(n == 65) n = 0; clock = n; return n; } int cache_find(block_sector_t sector, struct block *fs_device) { //printf("finding sector %d ",sector); int n; for(n=0; n<65; n++){ if(cache[n].sector == sector){ //printf("found %d, %d\n",n,cache[n].sector); cache[n].sector = sector; return n; } } for(n=0; n<65; n++){ if(cache[n].sector == -1){ block_read (fs_device, sector, cache[n].data); cache[n].sector = sector; cache[n].dirty = 0; //printf("made %d\n",n); return n; } } n = cache_evict(); block_write (fs_device, cache[n].sector, cache[n].data); block_read (fs_device, sector, cache[n].data); cache[n].sector = sector; cache[n].dirty = 0; //printf("replaced %d\n",n); return n; } void cache_write (struct block *fs_device, void *buffer, block_sector_t sector_idx, int sector_ofs, int chunk_size) { //printf("cache write %d, %d\n", sector_idx, chunk_size); int n = cache_find(sector_idx, fs_device); memcpy (cache[n].data + sector_ofs, buffer, chunk_size); //hex_dump(cache[n].data + sector_ofs,cache[n].data + sector_ofs,16,0); cache[n].dirty = 1; cache[n].accessed = 1; } void cache_read (struct block *fs_device, void *buffer, block_sector_t sector, int sector_ofs, int chunk_size) { //printf("cache_read %d, %d\n", sector, chunk_size); int n = cache_find(sector, fs_device); memcpy (buffer, cache[n].data + sector_ofs, chunk_size); //hex_dump(buffer,buffer,16,0); cache[n].accessed = 1; } void cache_flush () { int n; for(n = 0; n < 65; n++){ block_write (fs_device, cache[n].sector, cache[n].data); } }
Ruby
UTF-8
279
3.515625
4
[]
no_license
class Hand #class factory method to create a hand def self.make_hand(deck) Hand.new(deck.take(7)) end #initialize def initialize(cards) @hand = cards end def count @hand.length end #empty? def empty? return true if count == 0 end end
Markdown
UTF-8
3,212
3.28125
3
[]
no_license
# portfolio-template A test version of this app is deployed on https://mypyanywhere.pythonanywhere.com/ ## Table of Content 1. [Running The App](#running-the-project) 2. [Setting Up A Test User](#setting-up-a-test-user) 3. [Adding Documentation](#adding-documentation) 4. [Known Bugs](#known-bugs) ## Running the Project 1. Make sure python is installed on your pc 2. Run: `git clone https://github.com/samsiaw/portfolio-template.git` 3. Move to the top level project folder *i.e the folder containing manage.py file* `cd portfolio-template` 4. Run `pip install -r requirements.txt` to install project dependencies 5. `python3 manage.py makemigrations portfolio` >> NOTE: Run all `python manage.py` cmds in the top-level folder 6. If a `no changes detected` message is printed, delete the files `./db.sqlite3 , myweb/__pycache__, portfolio/migrations ` and `portfolio/__pycache__` files/folders. Repeat step 5 6. Run `python3 manage.py migrate` 7. To run the web app, run `python manage.py runserver` 8. Visit `http://localhost:8000` or `http://127.0.0.1:8000/` to view app ## Setting Up A Test User You should notice an `Internal Server Error` message on first running the app. You would need to set-up a `superuser` to manage the back-end database. >>For the purpose of testing, we would use a generic user with username: `test` 1. Stop the server: `Use ctrl-C or cmd-C` whiles server is running in terminal 2. Run: `python manage.py createsuperuser` 3. Type `test` for username and a password and email of your choice. 4. Rerun the server with `python manage.py runserver` >> If you created the superuser with username `test`, you should notice the homepage no longer shows `Internal Server Error` 5. `http://localhost:8000/admin` or `http://127.0.0.1:8000/admin` to access the admin page 6. Type in the username and password used for `superuser` in step 3. You should now have access to the models defined for the project ## Adding Documentation The app's models are divided into: * Project * Tool * Concept * Owner ### Owner Owner defines the owner/user whose projects are going to be added. Multiple registered owners/users are allowed but projects displayed are those of the current owner only. #### Setting an owner To set the current owner: set the `USERNAME` in `portfolio/views.py` to your desired username ### Project The project's only required fields are the name of the project and the owner. The `show` field in the project determines whether or not a project is visible on the website or not, even if the project has been created. The default website also supports a project being *featured* or not. >> You could decide not to set any project as featured at all, and the projects page should adapt accordingly. *Try setting different values for the current user, (i.e first and last name, email,etc..), add a few projects and notice how things change* ## Known Bugs Deleting a project doesn't break the website. However, the navigation buttons *(i.e Prev and Next)* on single project pages wouldn't work properly. *User is expected to clear all items in the portfolio info or simply set `show` to False/Off*
Java
UTF-8
1,063
3.4375
3
[]
no_license
package binarytree.middle; import binarytree.TreeNode; import binarytree.TreeNodeUtils; /** * @author hawk * @package binarytree.middle * @desc 814. 二叉树剪枝 * 给定二叉树根结点root,此外树的每个结点的值要么是 0,要么是 1。 * <p> * 返回移除了所有不包含 1 的子树的原二叉树。 * <p> * ( 节点 X 的子树为 X 本身,以及所有 X 的后代。) * <p> * 说明: * <p> * 给定的二叉树最多有 100 个节点。 * 每个节点的值只会为 0 或 1 。 * <p> * 通过次数20,038提交次数28,571 * <p> * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/binary-tree-pruning * @date 2021/6/2 */ public class BinaryTreePruning { public TreeNode pruneTree(TreeNode root) { if (root == null) { return null; } root.left = pruneTree(root.left); root.right = pruneTree(root.right); if (root.left == null && root.right == null && root.val == 0) { return null; } return root; } }
C++
UTF-8
486
3.46875
3
[]
no_license
#include <iostream> #include <set> using namespace std; int main(){ set<char> goodnumbers; for(int i = 0; i < 8; ++i){ char c = char(i + 48); goodnumbers.insert(c); } string str; cin >> str; bool ok = true; if(str[0] == '0'){ ok= false; } else{ for(int i = 0; i < str.length(); ++i){ char c = str[i]; if(goodnumbers.find(c) == goodnumbers.end()){ ok = false; break; } } } if(ok){ cout << "YES"; }else{ cout << "NO"; } return 0; }
Markdown
UTF-8
7,805
4.0625
4
[]
no_license
# Classes vs. Constructors With the unveiling of ES2015 (often referred to as ES6) syntax, JavaScript made its way toward becoming a class based, object-oriented programming language, at least on the surface. Behind the scenes is a new method to create constructors using the `class` syntax. Let's take a look at some of the fundamental differences and similarities between `class` and constructor functions. ## What is a Constructor Function? We've already learned what constructor functions do and how they operate. Constructors allow us to create objects that will inherit methods and properties from parent objects using the prototypal chain. Recall the fruit example from earlier: ```javascript function Fruit() { this.sweet = true; this.hasSeeds = true; } function Apple() { } Apple.prototype = new Fruit(); let apple = new Apple(); console.log(apple.sweet); ``` We created a `Fruit` constructor function, defined an `Apple` constructor function and using the `Apple.prototype = new Fruit` allowed `Apple` to inherit from the prototypal chain of the `Fruit` constructor. ## What is a Class, and How Can it Help Us? Classes are syntactic sugar for JavaScript constructors. They provide a means to create objects and deal with inheritance. Classes are special functions that can be expressions or declarations as with any function. Let's take a look at a class declaration. Below is a list of keywords we'll need to know moving forward. * `class` * `constructor` * `extends` * `super` We'll also be taking note of JavaScript's hoisting properties and sub-classes ### Class Declaration Run the code below to see the expected output. ```javascript class Fruit { constructor(sweet, texture) { this.sweet = sweet; this.texture = texture; } } let apple = new Fruit(true, 'crunchy'); console.log(apple.sweet); console.log(apple.texture); ``` Above we've created the class `Fruit`. `Fruit` acts as our constructor function, and you'll see that we used the function `constructor` to set up how our constructor function would pass down properties. We left the `sweet` and `texture` properties empty and assigned each a value when we instantiated a `Fruit` instance with the variable `apple`. We passed the key value pairs to the `new Fruit` function and the result from the `console.log` statements reflect those values. ## Sub-Classes Classes provide us with an efficient and clean method to create inheritance. We can go even further by diving into the world of *sub-classes*. Let's take a look at sub-classes in action below. ```javascript //Let's create a class called Primate class Primate { constructor() { this.isMammal = true; this.isSmart = true; this.opposableThumbs = true; } } //Now let's create a SUB-CLASS called Monkey using the extends and super keywords class Monkey extends Primate { constructor(name, color, isMammal, isSmart, opposableThumbs) { super({isMammal, isSmart, opposableThumbs}); this.name = name; this.color = color; } } //Now let's create an instance of Monkey let spiderMonkey = new Monkey("Spider Monkey", "black and brown"); //We've given the Monkey constructor some key value pair information //Let's see if spiderMonkey inherited from the Primate constructor by using "super" console.log(spiderMonkey.isMammal); ``` Let's take a look at the `extends` keyword. We're able to create a `Monkey` sub-class by using `class Monkey extends Primate`. `extends` does what we'd expect and extends a constructor's inheritance to the new constructor or instance. Upon examining the `constructor` function in `Monkey`, you'll notice that we passed along several parameters. We gave `Monkey` new properties of `name` and `color` that weren't present in the `Primate` class and also passed along parameters we wanted carried from the `Primate` class, such as `isMammal`. If we tried to reference them as they are, we'd get a reference error. This is where the `super` function helps us with inheritance. Using `super` and passing properties and methods from the parent constructor class allows us to retrieve those inherited properties and methods. You'll see when we `console.log(spiderMonkey.isMammal)` or any of the other inherited traits the output we get in return is `true`. ### Static Methods on Classes The new `class` syntax also has access to `static` methods. Static methods are designed to live only on the constructor in which they are described and cannot be passed down to any children. We will also take a look at how to apply default properties to a constructor. ```javascript class Chameleon { static colorChange(newColor) { this.newColor = newColor; } //Let's set a default of green to the constructor constructor({ newColor = 'green'} = {}) { this.newColor = newColor; } } let pantherChameleon = new Chameleon({newColor: "purple"}); console.log(pantherChameleon.newColor); ``` Everything works as expected. However, if we try to use `pantherChameleon` to run the `colorChange` function it won't work because of the `static` method. ```javascript class Chameleon { static colorChange(newColor) { this.newColor = newColor; } //Let's set a default of green to the constructor constructor({ newColor = 'green'} = {}) { this.newColor = newColor; } } let pantherChameleon = new Chameleon({newColor: "purple"}); //Try calling the function colorChange from pantherChameleon. pantherChameleon.colorChange("orange"); console.log(pantherChameleon.newColor); ``` The `changeColor` function only works for the `Chameleon` object so we get a type error when trying to use it on the `pantherChameleon` instance. Instead if we use the `call` method to allow `pantherChameleon` to use the `colorChange` function we will get following: ```javascript class Chameleon { static colorChange(newColor) { this.newColor = newColor; } //Let's set a default of green to the constructor constructor({ newColor = 'green'} = {}) { this.newColor = newColor; } } let pantherChameleon = new Chameleon({newColor: "purple"}); //using the call function we can apply the colorChange function to the pantherChameleon Chameleon.colorChange.call(pantherChameleon, "orange"); console.log(pantherChameleon.newColor); ``` By using `call`, which we'll learn more about later, we can attach the `colorChange` function to `pantherChameleon`. This isn't ideal. Instead, let's rewrite our static method to allow children objects to use it and bypass the call method altogether. ```javascript class Chameleon { static colorChange(lizard, newColor) { lizard.newColor = newColor; } constructor({ newColor = 'green'} = {}) { this.newColor = newColor; } } var pantherChameleon = new Chameleon({newColor: "purple"}); Chameleon.colorChange(pantherChameleon, "neon blue"); console.log(pantherChameleon.newColor); ``` You can see the static method still keeps the function `colorChange` locally. By allowing the parameter `lizard` to take place of `this`, we can replace the `call` function and pass in `pantherChameleon` as an argument. ## Conclusion * Classes provide a clean method to use prototypal inheritance and create object constructors. * A `constructor` function must be used to determine what code will be run when creating a new instance of the constructor object. * Classes can make sub-classes and pass inheritance using the `extend` keyword and the `super` function. * The `super` function allows for a child object to inherit methods and properties from the parent object. * Classes are **not** hoisted and will throw a reference error if an instance is declared before the class. * Using the `static` method allows the parent `class` to retain the method or property and not pass it directly down through prototypal inheritance.
C#
UTF-8
1,674
3.796875
4
[ "MIT" ]
permissive
//Problem 15. Prime numbers //Write a program that finds all prime numbers in the range //[1...10 000 000]. Use the Sieve of Eratosthenes algorithm. using System; using System.Collections.Generic; using System.IO; using System.Text; class PrimeNumbers { static void Main() { int n = 10000001; int[] arr = new int[n]; var desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); var fullFileName = Path.Combine(desktopFolder, "PrimeNumbers.txt"); StreamWriter primes = new StreamWriter(fullFileName); for (int i = 0; i < n; i++) { arr[i] = i; } int prime = 2; Console.WriteLine("The prime numbers are priting, be patient!"); while (true) { int i = 2; while (prime * i < n) { arr[prime * i] = 0; i++; } bool finished = true; i = prime; while (i < n / 2) { i++; if (arr[i] != 0) { prime = i; finished = false; break; } } if (finished) { break; } } using (primes) { for (int i = 2; i < 10000000; i++) { if (arr[i] != 0) { primes.Write("{0}, ", i); } } } Console.WriteLine("Check your desktop, there should be a .txt file with the prime numbers!"); } }
Java
UTF-8
2,813
3.46875
3
[]
no_license
package com.cg.oopd.model; public class ComplexNumber { /* data members (or) fields */ private double realPart; // represent real part of the complex number private double imaginaryPart; // represent imaginary part /* default constructor */ public ComplexNumber() { realPart = -1; imaginaryPart = -1; // System.out.println("default constructor is called "); } /* parameter constructor */ public ComplexNumber(double realPart) { this.realPart = realPart; this.imaginaryPart = 0; // System.out.println("one-parameter constructor is called "); } /* parameter constructor */ public ComplexNumber(double realPart, double imaginaryPart) { this.realPart = realPart; this.imaginaryPart = imaginaryPart; // System.out.println("two-parameter constructor is called "); } /* copy constructor */ public ComplexNumber(ComplexNumber other) { this.realPart = other.realPart; this.imaginaryPart = other.imaginaryPart; } /* setters and getters */ // modify real part public void setRealPart(double realPart) { this.realPart = realPart; } // modify imaginary part public void setImaginaryPart(double imaginaryPart) { this.imaginaryPart = imaginaryPart; } // to retrieve real part public double getRealPart() { return realPart; } // to retrieve imaginary part public double getImaginaryPart() { return imaginaryPart; } // public ComplexNumber add(ComplexNumber other) { // ComplexNumber result = new ComplexNumber(); // result.realPart = this.realPart + other.realPart; // result.imaginaryPart = this.imaginaryPart + other.imaginaryPart; // return result; // } // // public ComplexNumber diff(ComplexNumber other) { // ComplexNumber result = new ComplexNumber(); // result.realPart = this.realPart - other.realPart; // result.imaginaryPart = this.imaginaryPart - other.imaginaryPart; // return result; // } public static ComplexNumber add(ComplexNumber first, ComplexNumber second) { ComplexNumber result = new ComplexNumber(); result.realPart = first.realPart + second.realPart; result.imaginaryPart = first.imaginaryPart + second.imaginaryPart; return result; } public static ComplexNumber diff(ComplexNumber first, ComplexNumber second) { ComplexNumber result = new ComplexNumber(); result.realPart = first.realPart - second.realPart; result.imaginaryPart = first.imaginaryPart - second.imaginaryPart; return result; } @Override public boolean equals(Object other) { ComplexNumber o = (ComplexNumber) other; return (this.realPart == o.realPart && this.imaginaryPart == o.imaginaryPart); } @Override public String toString() { return this.realPart + ", " + this.imaginaryPart; } }
Python
UTF-8
3,789
3.0625
3
[]
no_license
import numpy as np from itertools import product def sinusoid_data_generation_1D(n_Phi, n_T, omega): """ Creates n_Phi sinusoidal signals with n_T points per signal each with angular frequency of omega. :param n_Phi: number of partitions of phase interval :param n_T: number of partitions of time interval :param omega: angular frequency of sinusoids :return: phase_range::array, time_range:: array, sinusoids::array """ # Discretization of phase interval [0,2pi] phase_range = 2 * np.pi * np.linspace(0, 1, n_Phi) # Time range time_range = np.linspace(0, 1, n_T) # Signals sinusoids = np.sin(np.subtract.outer(phase_range, -(omega * time_range))) return phase_range, time_range, sinusoids def sinusoid_from_phase(phases, n_T, omega): time_range = np.linspace(0, 1, n_T) sinusoids = np.sin(np.subtract.outer(phases, -(omega * time_range))) return time_range, sinusoids def sinusoid_image_phase_combination(phases1, phases2, n_T, omega_values): """ This function produces an array where each row corresponds to a sinusoidal signal with a given phase and angular frequency omega. The columns represent the time sampling from the interval [0,1]. :param phases: Vector with the phases to be used :param n_T: Number of elements in the partition of the interval [0,1] :param omega: Angular frequency :return: np.array with shape (len(phases),n_T) """ # Sampling from phase and space space_linspace = np.linspace(0, 1, n_T) # Create all possible combinations of phi_1, phi_2 phase_combinations = np.array(list(product(phases1, phases2))) sinusoid_images = np.zeros((n_T, n_T, len(phase_combinations))) # Create spatial mesh spatial_mesh = np.meshgrid(space_linspace, space_linspace) # Generate signals for each combination for num_mesh, mesh_dimension in enumerate(spatial_mesh): # Omega*dimension mesh_expanded_dim = omega_values[num_mesh] * mesh_dimension[:, :, np.newaxis] repeated_volume = np.repeat(mesh_expanded_dim, repeats=len(phase_combinations), axis=2) # sine(Omega*dimension+phase) sinusoid_images += np.sin(np.add(repeated_volume, phase_combinations[:, num_mesh])) sinusoid_images = np.swapaxes(sinusoid_images, 2, 0) return phase_combinations, sinusoid_images def sinusoid_image_phase(phases1, phases2, n_T, omega_values): """ This function produces an array where each row corresponds to a sinusoidal signal with a given phase and angular frequency omega. The columns represent the time sampling from the interval [0,1]. :param phases: Vector with the phases to be used :param n_T: Number of elements in the partition of the interval [0,1] :param omega: Angular frequency :return: np.array with shape (len(phases),n_T) """ # Sampling from phase and space space_linspace = np.linspace(0, 1, n_T) # Create all possible combinations of phi_1, phi_2 phases1 = np.expand_dims(phases1, 1) phases2 = np.expand_dims(phases2, 1) phases = np.concatenate((phases1, phases2), axis=1) sinusoid_images = np.zeros((n_T, n_T, len(phases))) # Create spatial mesh spatial_mesh = np.meshgrid(space_linspace, space_linspace) # Generate signals for each combination for num_mesh, mesh_dimension in enumerate(spatial_mesh): # Omega*dimension mesh_expanded_dim = omega_values[num_mesh] * mesh_dimension[:, :, np.newaxis] repeated_volume = np.repeat(mesh_expanded_dim, repeats=len(phases), axis=2) # sine(Omega*dimension+phase) sinusoid_images += np.sin(np.add(repeated_volume, phases[:, num_mesh])) sinusoid_images = np.swapaxes(sinusoid_images, 2, 0) return phases, sinusoid_images
Ruby
UTF-8
3,124
4.1875
4
[]
no_license
Suits = ["Clubs","Hearts","Spades","Diamonds"] Ranks = ["1","2","3","4","5","6","7","8","9","10","11","12","13"] $d = [] class Card include Enumerable # class variables (private) @@suit_value = Hash[ Suits.each_with_index.to_a ] @@rank_value = Hash[ Ranks.each_with_index.to_a ] attr_reader :rank, :suit attr_accessor :value def initialize(rank, suit) @rank = rank @suit = suit end def value value = case @rank.to_i when 1 11 when 2..10 @rank when 11..13 10 else nil end end def display_rank case @rank when "11" "Jack" when "12" "Queen" when "13" "King" when "1" "Ace" else @rank end end def to_s "#{display_rank} of #{@suit}, value #{value}" end end # the below is my test # card = Card.new(12,"Spades") # puts card.to_s class Deck attr_accessor :cards def initialize @cards = [] Suits.each do |suit| Ranks.each do |rank| @cards << Card.new(rank, suit) end end end def shuffle! @cards.shuffle! end def draw @cards.pop end def remaining @cards.length end end # d.cards.each do |card| # puts card.to_s # end class Player attr_accessor :hand, :hand_value, :ace_count def initialize @hand = [] @hand_value = 0 @ace_count = ace_count 2.times do card = $d.draw @hand_value == 0 ? @hand_value = card.value.to_i : @hand_value += card.value.to_i @hand << card end end def hit card = $d.draw @hand_value == 0 ? @hand_value = card.value.to_i : @hand_value += card.value.to_i @hand << card end def switch_ace while @hand_value > 21 && @ace_count > 0 @ace_count -= 1 @hand_value -= 10 end end def to_s puts "#{@hand.to_s}, total value #{@hand_value}" end end ######################################################################### # Testing the code $d = Deck.new $d.shuffle! puts "A new deck has been shuffled and there are #{$d.remaining} cards" playah = Player.new puts "Player's hand:" puts playah.to_s dealah = Player.new if playah.hand_value == 21 puts "Player wins with BlackJack!" puts "Dealer's hand:" puts dealah.to_s else until playah.hand_value > 21 playah.switch_ace puts "Do you want to hit(h) or stay(s)?" action = $stdin.gets.chomp if action == "h" puts "You chose to hit, here's your new hand" playah.hit puts playah.to_s else puts "You chose to stay, here's your final hand" puts playah.to_s break end end puts "Dealer's hand:" puts dealah.to_s if playah.hand_value <= 21 if playah.hand_value > dealah.hand_value puts "Player wins" elsif playah.hand_value == dealah.hand_value puts "Dealer and Player tied" else puts "Dealer wins" end else puts "Player busts. Dealer wins" end end puts "There are #{$d.remaining} cards in the deck"
JavaScript
UTF-8
4,141
2.59375
3
[]
no_license
import logo from './logo.svg'; import './App.css'; import IdCard from './components/IdCard' import Greetings from './components/Greetings' import Random from './components/Random' import BoxColor from './components/BoxColor' import CreditCard from './components/CreditCard' import Rating from './components/Rating'; import DriverCard from './components/DriverCard'; function App() { const persons = [ { lastName: 'Doe', firstName: 'John', gender: 'male', height: 178, birth: new Date("1992-07-14"), picture: "https://randomuser.me/api/portraits/men/44.jpg" }, { lastName: 'Delores', firstName: 'Obrien', gender: 'female', height: 172, birth: new Date("1988-05-11"), picture: "https://randomuser.me/api/portraits/women/44.jpg" } ] const creditcard = [ { type: "Visa", number: "0123456789018845", expirationMonth: 3, expirationYear: 2021, bank: "BNP", owner: "Maxence Bouret", bgColor: "#11aa99", color: "white" }, { type: "Master Card", number: "0123456789010995", expirationMonth: 3, expirationYear: 2021, bank: "N26", owner: "Maxence Bouret", bgColor: "#eeeeee", color: "#222222", }, { type: "Visa", number: "0123456789016984", expirationMonth: 12, expirationYear: 2019, bank: "Name of the Bank", owner: "Firstname Lastname", bgColor: "#ddbb55", color: "white" } ] const drivercard = [ { name: "Travis Kalanick", rating: 4.2, img: "https://si.wsj.net/public/resources/images/BN-TY647_37gql_OR_20170621052140.jpg?width=620&height=428", car: { model: "Toyota Corolla Altis", licensePlate: "CO42DE" } }, { name: "Dara Khosrowshahi", rating: 4.9, img: "https://ubernewsroomapi.10upcdn.com/wp-content/uploads/2017/09/Dara_ELT_Newsroom_1000px.jpg", car: { model: "Audi A3", licensePlate: "BE33ER" } } ] return ( <section> <div> <h1>Cards</h1> { persons.map((card, index_card) => ( <IdCard key={index_card} lastname={card.lastName} firstname={card.firstName} gender={card.gender} height={card.height} birth={card.birth.toString().slice(0, 15)} picture={card.picture} /> )) } </div> <div> <Greetings lang="de">Ludwig</Greetings> <Greetings lang="fr">François</Greetings> <Greetings lang="es">Juanito</Greetings> </div> <div> <h1>Random</h1> <Random min={1} max={6} /> <Random min={1} max={100} /> </div> <div> <h1>Box Color</h1> <BoxColor r={255} g={0} b={0} /> <BoxColor r={128} g={255} b={0} /> </div> <div> <h1>Credit Card</h1> { creditcard.map((creditcard, index_idCard) => ( <CreditCard key={index_idCard} type={creditcard.type} number={creditcard.number} expirationMonth={creditcard.expirationMonth} expirationYear={creditcard.expirationYear} bank={creditcard.bank} owner={creditcard.owner} bgColor={creditcard.bgColor} color={creditcard.color} /> ))} </div> <div> <h1>Rating</h1> <Rating>0</Rating> <Rating>1.49</Rating> <Rating>1.5</Rating> <Rating>3</Rating> <Rating>4</Rating> <Rating>5</Rating> </div> <div> <h1>Driver Card</h1> { drivercard.map((drivercard, index_card) => ( <DriverCard key={index_card} name={drivercard.name} rating={drivercard.rating} img={drivercard.img} car={drivercard.car} /> ))} </div> </section> ); } export default App;
Python
UTF-8
1,734
2.59375
3
[ "MIT" ]
permissive
from flask import session, jsonify from flask_login import login_required, current_user from sixquiprend.models.game import Game from sixquiprend.models.user import User from sixquiprend.sixquiprend import app, admin_required @app.route('/games/<int:game_id>/columns') @login_required def get_game_columns(game_id): """Get columns for the given game""" game = Game.find(game_id) return jsonify(columns=game.columns.all()) @app.route('/games/<int:game_id>/users/<int:user_id>/status') @login_required def get_user_game_status(game_id, user_id): """Get user status (has or not chosen a card) for a given game, and specifies if he needs to choose a column for his card""" game = Game.find(game_id) user = game.get_user_status(user_id) return jsonify(user=user) @app.route('/games/<int:game_id>/users/<int:user_id>/heap') @login_required def get_user_game_heap(game_id, user_id): """Get a user's heap for a given game""" game = Game.find(game_id) heap = game.get_user_heap(user_id) return jsonify(heap=heap) @app.route('/games/<int:game_id>/users/current/hand') @login_required def get_current_user_game_hand(game_id): """Get your hand for a given game""" game = Game.find(game_id) hand = game.get_user_hand(current_user.id) return jsonify(hand=hand) @app.route('/games/<int:game_id>/chosen_cards') @login_required def get_game_chosen_cards(game_id): """Display chosen cards for a game. Only returns current user chosen card if not all users have chosen, or all chosen cards if a turn is being resolved""" game = Game.find(game_id) chosen_cards = game.get_chosen_cards_for_current_user(current_user.id) return jsonify(chosen_cards=chosen_cards)
Shell
UTF-8
808
3.078125
3
[]
no_license
#!/bin/bash set -e cd if [ -z "$SVNPOLY" ] then wget -q -O polyml5.5.1.tar.gz "http://downloads.sourceforge.net/project/polyml/polyml/5.5.1/polyml.5.5.1.tar.gz?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fpolyml%2Ffiles%2Fpolyml%2F5.5.1%2Fpolyml.5.5.1.tar.gz%2Fdownload&ts=1384728510&use_mirror=softlayer-dal" tar xzf polyml5.5.1.tar.gz cd polyml.5.5.1 if [ -z "$ROOTPOLY" ] then echo "*** Installing PolyML in home directory" ./configure --prefix=$HOME --enable-shared make make install else echo "*** Installing PolyML in root land directory" ./configure --prefix=/usr/ --enable-shared make sudo make install fi else svn checkout svn://svn.code.sourceforge.net/p/polyml/code/trunk/polyml polyml cd polyml ./configure --prefix=$HOME --enable-shared make make compiler make install fi
Java
UTF-8
2,031
2.59375
3
[]
no_license
package com.anurag.dao; import org.apache.log4j.Logger; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; public class BookShopDAOImpl extends JdbcDaoSupport implements BookShopDAO { private static Logger logger=Logger.getLogger(BookShopDAOImpl.class); private PlatformTransactionManager transactionManager; private static final String SQL_TO_GET_BOOK_PRICE= "select price from Book where ISBN=?"; private static final String SQL_DEDUCT_BALANCE= "UPDATE ACCOUNT SET BALANCE = BALANCE - ? WHERE Id = ?"; private static final String SQL_UPDATE_BOOK_STOCK= "UPDATE BOOK_STOCK SET STOCK = STOCK - ? WHERE ISBN = ?"; public void purchase(String isbn, int accountID, int noOfBooks) { TransactionDefinition definition=new DefaultTransactionDefinition(); TransactionStatus status=transactionManager.getTransaction(definition); try { double price=getJdbcTemplate().queryForObject (SQL_TO_GET_BOOK_PRICE,Double.class,isbn); double totalPrice = noOfBooks*price; getJdbcTemplate().update(SQL_DEDUCT_BALANCE, totalPrice,accountID); getJdbcTemplate().update(SQL_UPDATE_BOOK_STOCK, noOfBooks,isbn); transactionManager.commit(status); logger.info(noOfBooks+" No Of Book(s) Purchased SuccessFully"); logger.info(totalPrice+" Amount Is Deducted From your Account"); System.out.println("Ur Transaction Is Successfully Completed"); } catch (Exception e) { transactionManager.rollback(status); logger.error("Error Occured in Purchase Method Of BookShopImpl Class : "+e.getMessage()); }//catch }//method public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } }//class
Python
UTF-8
973
3.109375
3
[]
no_license
def match(string) -> int: pattern = "place:" arr = z(pattern+"/0"+string) for i in range(len(arr)): if arr[i] == len(pattern):return i - (len(pattern) + 1) -1 return -1 def z(string: str) -> list: z_val = [0] * len(string) i = left = right = 1 while i < len(string): if right <= i: left = right = i while right < len(string) and string[right] == string[right - left]: z_val[i] += 1 right += 1 if right == len(string):break i += 1 else: i = right j = left + 1 while j < right and j + z_val[j - left] < right: z_val[j] = z_val[j - left] j += 1 if j < right: left = j z_val[j] = right - j while string[right] == string[right - left]: z_val[j] += 1 right += 1 return z_val
Java
UTF-8
30,816
1.640625
2
[]
no_license
package com.yzlm.cyl.cfragment.Communication.CommProtocol.Modbus.Rtu; import com.yzlm.cyl.cfragment.Communication.Communication; import com.yzlm.cyl.cfragment.Communication.Thread.SendManager; import com.yzlm.cyl.cfragment.Config.Component.CfgTool.History; import com.yzlm.cyl.cfragment.R; import com.yzlm.cyl.clibrary.Util.DataUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import static com.yzlm.cyl.cfragment.Config.Component.CfgTool.Config.getConfigData; import static com.yzlm.cyl.cfragment.Config.Component.CfgTool.PublicConfig.getPublicConfigData; import static com.yzlm.cyl.cfragment.Content.Component.List2.List2_Content2.getModePermissions; import static com.yzlm.cyl.cfragment.DBConvert.BCDDeccode.str2Bcd; import static com.yzlm.cyl.cfragment.DBConvert.MDBConvert.floatToBytesBigs; import static com.yzlm.cyl.cfragment.DBConvert.MDBConvert.getSystemDateDay; import static com.yzlm.cyl.cfragment.DBConvert.MDBConvert.getSystemDateHour; import static com.yzlm.cyl.cfragment.DBConvert.MDBConvert.getSystemDateMin; import static com.yzlm.cyl.cfragment.DBConvert.MDBConvert.getSystemDateMonth; import static com.yzlm.cyl.cfragment.DBConvert.MDBConvert.getSystemDateSec; import static com.yzlm.cyl.cfragment.DBConvert.MDBConvert.getSystemDateYear; import static com.yzlm.cyl.cfragment.Global.IOBoardUsed; import static com.yzlm.cyl.cfragment.Global.context; import static com.yzlm.cyl.cfragment.Global.doControlJob; import static com.yzlm.cyl.cfragment.Global.doFlowing; import static com.yzlm.cyl.cfragment.Global.strComponent; import static com.yzlm.cyl.clibrary.Util.DataUtil.bytesToHexString; import static com.yzlm.cyl.clibrary.Util.DataUtil.copybyte; import static com.yzlm.cyl.clibrary.Util.DataUtil.crc16; import static java.lang.System.arraycopy; /** * Created by zwj on 2017/8/2. */ public class RtuProtocol { /** * MODBUSRTU1.0版本 */ public static void ParsingProtocolRtu(Communication port, int sCom, byte[] rs, String sProtocol) { if (rs != null && rs.length > 6) { byte[] crc = new byte[2]; arraycopy(rs, rs.length - 2, crc, 0, 2); byte[] RtuRs = new byte[rs.length - 2]; arraycopy(rs, 0, RtuRs, 0, RtuRs.length); //若校验模式是低位,则先进行反转 if ("2".equals(getPublicConfigData(sProtocol + "_CRC_MODE"))) { DataUtil.reverse(crc); } if (Arrays.equals(crc16(RtuRs, RtuRs.length), crc)) { int addr = 0; addr = Integer.parseInt(getPublicConfigData(sCom == 3 ? "RS485_DIGITAL_ADDR" : (sCom == 1 ? "DIGITAL_ADDR" : "PC_DIGITAL_ADDR"))); if (addr == RtuRs[0]) { switch (RtuRs[1]) { case 3: List<Map> list; History mHistory; mHistory = new History(context); byte[] dataBytes = new byte[256]; switch (RtuRs[2] * 0x100 + RtuRs[3]) { case 0x00: if (getModePermissions(strComponent.get(1)[0], "历史数据上传")) { if (getPublicConfigData("CAL_DATA_UPDATE").equals("true")) { list = mHistory.select(strComponent.get(1)[0], null, null, null, 0, 1); } else { list = mHistory.select(strComponent.get(1)[0], context.getString(R.string.ZY), null, null, 0, 1); } if (list.size() > 0) { float data = Float.parseFloat(list.get(0).get("C").toString()); dataBytes = copybyte(floatToBytesBigs(data)); arraycopy(dataBytes, 0, dataBytes, 0, dataBytes.length); ModbusSend(port, sCom, (byte) addr, dataBytes); } } break; case 0x02: if (getModePermissions(strComponent.get(1)[1], "历史数据上传")) { if (getPublicConfigData("CAL_DATA_UPDATE").equals("true")) { list = mHistory.select(strComponent.get(1)[1], null, null, null, 0, 1); } else { list = mHistory.select(strComponent.get(1)[1], context.getString(R.string.ZY), null, null, 0, 1); } if (list.size() > 0) { float data = Float.parseFloat(list.get(0).get("C").toString()); dataBytes = copybyte(floatToBytesBigs(data)); arraycopy(dataBytes, 0, dataBytes, 0, dataBytes.length); ModbusSend(port, sCom, (byte) addr, dataBytes); } } break; case 0x04: if (getModePermissions(strComponent.get(1)[2], "历史数据上传")) { if (getPublicConfigData("CAL_DATA_UPDATE").equals("true")) { list = mHistory.select(strComponent.get(1)[2], null, null, null, 0, 1); } else { list = mHistory.select(strComponent.get(1)[2], context.getString(R.string.ZY), null, null, 0, 1); } if (list.size() > 0) { float data = Float.parseFloat(list.get(0).get("C").toString()); dataBytes = copybyte(floatToBytesBigs(data)); arraycopy(dataBytes, 0, dataBytes, 0, dataBytes.length); ModbusSend(port, sCom, (byte) addr, dataBytes); } } break; case 0x06: if (getModePermissions(strComponent.get(1)[3], "历史数据上传")) { if (getPublicConfigData("CAL_DATA_UPDATE").equals("true")) { list = mHistory.select(strComponent.get(1)[3], null, null, null, 0, 1); } else { list = mHistory.select(strComponent.get(1)[3], context.getString(R.string.ZY), null, null, 0, 1); } if (list.size() > 0) { float data = Float.parseFloat(list.get(0).get("C").toString()); dataBytes = copybyte(floatToBytesBigs(data)); arraycopy(dataBytes, 0, dataBytes, 0, dataBytes.length); ModbusSend(port, sCom, (byte) addr, dataBytes); } } break; case 0x08: if (getModePermissions(strComponent.get(1)[4], "历史数据上传")) { if (getPublicConfigData("CAL_DATA_UPDATE").equals("true")) { list = mHistory.select(strComponent.get(1)[4], null, null, null, 0, 1); } else { list = mHistory.select(strComponent.get(1)[4], context.getString(R.string.ZY), null, null, 0, 1); } if (list.size() > 0) { float data = Float.parseFloat(list.get(0).get("C").toString()); dataBytes = copybyte(floatToBytesBigs(data)); arraycopy(dataBytes, 0, dataBytes, 0, dataBytes.length); ModbusSend(port, sCom, (byte) addr, dataBytes); } } break; case 0x63: dataBytes = copybyte(str2Bcd(String.valueOf((short) (getSystemDateYear() - 2000))), str2Bcd(String.valueOf((short) (getSystemDateMonth()))), str2Bcd(String.valueOf((short) (getSystemDateDay()))), str2Bcd(String.valueOf((short) (getSystemDateHour()))), str2Bcd(String.valueOf((short) (getSystemDateMin()))), str2Bcd(String.valueOf((short) (getSystemDateSec())))); arraycopy(dataBytes, 0, dataBytes, 0, dataBytes.length); ModbusSend(port, sCom, (byte) addr, dataBytes); break; } case 6: String compName = null; switch (RtuRs[2] * 0x100 + RtuRs[3]) { case 0x21: if (getModePermissions(strComponent.get(1)[0], "反控")) { compName = strComponent.get(1)[0]; } break; case 0x22: if (getModePermissions(strComponent.get(1)[1], "反控")) { compName = strComponent.get(1)[1]; } break; case 0x23: if (getModePermissions(strComponent.get(1)[2], "反控")) { compName = strComponent.get(1)[2]; } break; case 0x24: if (getModePermissions(strComponent.get(1)[3], "反控")) { compName = strComponent.get(1)[3]; } break; case 0x25: if (getModePermissions(strComponent.get(1)[4], "反控")) { compName = strComponent.get(1)[4]; } break; default: return; } if (compName != null) { List<String> flows = new ArrayList<>(); String[] flowStr = {"反控" + context.getString(R.string.SDZY), "反控" + context.getString(R.string.SDJZ)}; if (RtuRs[4] * 0x100 + RtuRs[5] < flowStr.length) { SendManager.SendCmd("IO" + "_" + (!IOBoardUsed ? "打印输出_0_0" : "ModbusRtu_09_" + (sCom == 3 ? "08" : (sCom == 1 ? "07" : "09"))), port, 1, 500, RtuRs); if (doFlowing.get(compName).equals(context.getString(R.string.waiting_for_instructions))) { doControlJob(compName, flowStr[RtuRs[4] * 0x100 + RtuRs[5]]); } } } else { SendManager.SendCmd("IO" + "_" + (!IOBoardUsed ? "打印输出_0_0" : "ModbusRtu_09_" + (sCom == 3 ? "08" : (sCom == 1 ? "07" : "09"))), port, 1, 500, RtuRs); } break; } } } } } /* * 通过接收到地址找到对应组份 */ public static String getCompName(int reAddr) { if (strComponent.get(1).length > 0) { for (String item : strComponent.get(1)) { if (getConfigData(item, "RTU_ID").equals("")) { continue; } if (getConfigData(item, "RTU_ID").equals(String.valueOf(reAddr))) { return item; } } if (getPublicConfigData("SYS_RTU_ID").equals(String.valueOf(reAddr))) { return "SYSTEM"; } } return ""; } public static String ModbusSend(Communication port, int sCom, byte addr, byte[] dataBytes) { String sendMsg = ""; byte[] head = new byte[3]; head[0] = addr; head[1] = 0x03; head[2] = (byte) dataBytes.length; byte[] sendBytes = copybyte(head, dataBytes); if (getPublicConfigData("Modbus_Rtu_CRC_MODE").equals("2")) { byte[] crc = crc16(sendBytes, sendBytes.length); DataUtil.reverse(crc); sendBytes = copybyte(sendBytes, crc); } else { sendBytes = copybyte(sendBytes, crc16(sendBytes, sendBytes.length)); } //SendManager.SendCmd("IO" + "_" + "ModbusRtu_09_" + (sCom == 3 ? "08" : (sCom == 1 ? "07" : "09")), S1, 1, 500, sendBytes); SendManager.SendCmd("IO" + "_" + (!IOBoardUsed ? "打印输出_0_0" : "ModbusRtu_09_" + (sCom == 3 ? "08" : (sCom == 1 ? "07" : "09"))), port, 1, 500, sendBytes); sendMsg = bytesToHexString(sendBytes, sendBytes.length); return sendMsg; } /* MODBUS 2.0 public static String ModbusSend(int scom, byte addr, byte[] dataBytes) { String sendMsg = ""; byte[] head = new byte[3]; head[0] = addr; head[1] = 0x03; head[2] = (byte) dataBytes.length; byte[] sendBytes = copybyte(head, dataBytes); sendBytes = copybyte(sendBytes, crc16(sendBytes, sendBytes.length)); SendManager.SendCmd("IO" + "_" + "ModbusRtu_09_" + (sCom == 3 ? "08" : (sCom == 1 ? "07" : "09")), S1, 1, 500, sendBytes); sendMsg = bytesToHexString(sendBytes, sendBytes.length); return sendMsg; } public static void ParsingProtocolRtu(int scom, byte[] rs) { if (rs != null && rs.length > 10) { byte[] crc = new byte[2]; arraycopy(rs, rs.length - 4, crc, 0, 2); byte[] RtuRs = new byte[rs.length - 8]; System.arraycopy(rs, 6, RtuRs, 0, RtuRs.length); if (Arrays.equals(crc16(RtuRs, RtuRs.length - 2), crc) == true) { int addr = (scom == 1 ? getPublicConfigData("DIGITAL_ADDR").toString().equals("") ? 0 : Integer.valueOf(getPublicConfigData("DIGITAL_ADDR").toString()) : getPublicConfigData("PC_DIGITAL_ADDR").toString().equals("") ? 0 : Integer.valueOf(getPublicConfigData("PC_DIGITAL_ADDR").toString())); byte[] codeByte = new byte[]{RtuRs[2], RtuRs[3]}; reverse(codeByte); int reReg = toInt(codeByte); int who = 0; for (int i = 0; i < strComponent.get(1).length; i++) { if (reReg < (400 + (i * 300))) { who = i; break; } } if (addr == RtuRs[0]) { switch (RtuRs[1]) { case 03: List<Map> list; History mHistory; mHistory = new History(context); byte[] allDataBytes = new byte[256]; int allDataCh = 0; byte[] dataBytes = new byte[0]; byte[] reRegNumCodeByte = new byte[]{RtuRs[4], RtuRs[5]}; reverse(reRegNumCodeByte); int reRegNum = toInt(reRegNumCodeByte); int copyFlag = 1; int startAddr = lRtuCmdData.get(RtuRs[1] == 3 ? "03" : "06").getRegObj((reReg - (who * 300))).getRegAddr(); int regAddr = startAddr; for (int i = 0; i < reRegNum; regAddr += lRtuCmdData.get((RtuRs[1] == 3 ? "03" : "06")).getRegObj((regAddr)).getDataLen()) { i += lRtuCmdData.get((RtuRs[1] == 3 ? "03" : "06")).getRegObj((regAddr)).getDataLen(); if (i > reRegNum) { return; } switch (lRtuCmdData.get((RtuRs[1] == 3 ? "03" : "06")).getRegObj((regAddr)).getDescribe()) { case "测量值": who = lRtuCmdData.get((RtuRs[1] == 3 ? "03" : "06")).getRegObj((regAddr)).getRegAddr() / 2; if (who < strComponent.get(1).length) { if (getConfigData(strComponent.get(1)[who] , "CAL_DATA_UPDATE").equals("true")) { list = mHistory.select(strComponent.get(1)[who], null, null, null, 0, 1); } else { list = mHistory.select(strComponent.get(1)[who], "做样", null, null, 0, 1); } if (list.size() > 0) { float data = Float.parseFloat(list.get(0).get("C").toString()); dataBytes = copybyte(floatToBytesBigs(data)); } else { *//*无数据不返回*//* return; } } else { return; } break; case "工作状态": int status = getCmds(strComponent.get(1)[who]).getCmd(51).getValue() == null ? 0 : Integer.parseInt((getCmds(strComponent.get(1)[who]).getCmd(51).getValue()).toString()); dataBytes = copybyte(shortToByteArray(status)); break; case "工作模式": break; case "量程低": dataBytes = copybyte(floatToBytesBigs(Float.valueOf(getConfigData(strComponent.get(1)[who] , "YBLCL").toString()))); break; case "量程高": dataBytes = copybyte(floatToBytesBigs(Float.valueOf(getConfigData(strComponent.get(1)[who] , "YBLCH").toString()))); break; case "当前报错": int errorNum = 0; if (hasDigit(workState.get(strComponent.get(1)[who])) == true) { errorNum = Integer.parseInt(getNumbers(workState.get(strComponent.get(1)[who]))); } dataBytes = copybyte(shortToByteArray(errorNum)); break; case "间隔做样小时": dataBytes = copybyte(shortToByteArray(Integer.parseInt(getConfigData(strComponent.get(1)[who] , "lxclh").toString()))); break; case "间隔做样分钟": dataBytes = copybyte(shortToByteArray(Integer.parseInt(getConfigData(strComponent.get(1)[who] , "lxclm").toString()))); break; case "整点测量0": case "整点测量1": case "整点测量2": case "整点测量3": case "整点测量4": case "整点测量5": case "整点测量6": case "整点测量7": case "整点测量8": case "整点测量9": case "整点测量10": case "整点测量11": case "整点测量12": case "整点测量13": case "整点测量14": case "整点测量15": case "整点测量16": case "整点测量17": case "整点测量18": case "整点测量19": case "整点测量20": case "整点测量21": case "整点测量22": case "整点测量23": int findTime = 0; String[] strzqclh = getConfigData(strComponent.get(1)[who] , "zqclh").toString().split("[,,]"); for (int j = 0; j < strzqclh.length; j++) { if (getNumbers(lRtuCmdData.get((RtuRs[1] == 3 ? "03" : "06")).getRegObj((regAddr)).getDescribe()).equals(strzqclh[j])) { findTime = 1; break; } } dataBytes = copybyte(shortToByteArray(findTime)); break; case "消解温度": dataBytes = copybyte(shortToByteArray(Integer.parseInt(getConfigData(strComponent.get(1)[who] , "xjwd").toString()))); break; case "消解时长": dataBytes = copybyte(shortToByteArray(Integer.parseInt(getConfigData(strComponent.get(1)[who] , "xjsc").toString()))); break; case "显色温度": dataBytes = copybyte(shortToByteArray(Integer.parseInt(getConfigData(strComponent.get(1)[who] , "xswd").toString()))); break; case "显示时长": dataBytes = copybyte(shortToByteArray(Integer.parseInt(getConfigData(strComponent.get(1)[who] , "xssc").toString()))); break; case "消解降温温度": dataBytes = copybyte(shortToByteArray(Integer.parseInt(getConfigData(strComponent.get(1)[who] , "xjjw").toString()))); break; case "显色降温温度": dataBytes = copybyte(shortToByteArray(Integer.parseInt(getConfigData(strComponent.get(1)[who] , "xsjw").toString()))); break; case "显色静置": dataBytes = copybyte(shortToByteArray(Integer.parseInt(getConfigData(strComponent.get(1)[who] , "xsjz").toString()))); break; case "量程1标1": dataBytes = copybyte(floatToBytesBigs(Float.parseFloat(getConfigData(strComponent.get(1)[who] , "C0").toString()))); break; case "量程2标1": dataBytes = copybyte(floatToBytesBigs(Float.parseFloat(getConfigData(strComponent.get(1)[who] , "C2").toString()))); break; case "量程3标1": dataBytes = copybyte(floatToBytesBigs(Float.parseFloat(getConfigData(strComponent.get(1)[who] , "C4").toString()))); break; case "量程1标2": dataBytes = copybyte(floatToBytesBigs(Float.parseFloat(getConfigData(strComponent.get(1)[who] , "C1").toString()))); break; case "量程2标2": dataBytes = copybyte(floatToBytesBigs(Float.parseFloat(getConfigData(strComponent.get(1)[who] , "C3").toString()))); break; case "量程3标2": dataBytes = copybyte(floatToBytesBigs(Float.parseFloat(getConfigData(strComponent.get(1)[who] , "C5").toString()))); break; case "量程1K": dataBytes = copybyte(floatToBytesBigs(getNewestKBF(strComponent.get(1)[who], "1", "K"))); break; case "量程2K": dataBytes = copybyte(floatToBytesBigs(getNewestKBF(strComponent.get(1)[who], "2", "K"))); break; case "量程3K": dataBytes = copybyte(floatToBytesBigs(getNewestKBF(strComponent.get(1)[who], "3", "K"))); break; case "量程1B": dataBytes = copybyte(floatToBytesBigs(getNewestKBF(strComponent.get(1)[who], "1", "B"))); break; case "量程2B": dataBytes = copybyte(floatToBytesBigs(getNewestKBF(strComponent.get(1)[who], "2", "B"))); break; case "量程3B": dataBytes = copybyte(floatToBytesBigs(getNewestKBF(strComponent.get(1)[who], "3", "B"))); break; default: copyFlag = 0; break; } if (copyFlag == 1) { System.arraycopy(dataBytes, 0, allDataBytes, allDataCh, dataBytes.length); allDataCh += dataBytes.length; } } if (allDataCh != 0) { byte[] sendData = new byte[allDataCh]; System.arraycopy(allDataBytes, 0, sendData, 0, allDataCh); ModbusSend(scom, (byte) addr, sendData); } break; case 06: int setAddr = lRtuCmdData.get(RtuRs[1] == 3 ? "03" : "06").getRegObj((reReg - (who * 300))).getRegAddr(); switch (lRtuCmdData.get((RtuRs[1] == 3 ? "03" : "06")).getRegObj((setAddr)).getDescribe()) { case "反控": who = lRtuCmdData.get((RtuRs[1] == 3 ? "03" : "06")).getRegObj((setAddr)).getRegAddr() - 33; if (who < strComponent.get(1).length) { List<String> flows = new ArrayList<>(); String[] flowStr = {"手动做样", "手动校准", "仪表清洗", "零样测量", "标样1测量", "标样2测量"}; byte[] reRegDataByte = new byte[]{RtuRs[4], RtuRs[5]}; reverse(reRegDataByte); int iRegData = toInt(reRegDataByte); if (iRegData == 0xFF) { stopWorking(strComponent.get(1)[who]); } else { if (iRegData < flowStr.length) { SendManager.SendCmd("IO" + "_" + "ModbusRtu_09_" + (sCom == 3 ? "08" : (sCom == 1 ? "07" : "09")), S1, 1, 500, RtuRs); flows.add(flowStr[iRegData]); runFlows(strComponent.get(1)[who], flows); } } } break; } break; } } } } }*/ }
C#
UTF-8
5,652
3.203125
3
[]
no_license
 namespace ProjetoPaises.Servicos { using System; using System.Collections.Generic; using System.Data.SQLite; using System.IO; using System.Threading.Tasks; using ProjetoPaises.Modelos; public class SecondDataService { #region Atributos /// <summary> /// Atributo que vai fazer a conexão /// </summary> private SQLiteConnection connection; /// <summary> /// Atributo onde vamos fazer os comandos /// </summary> private SQLiteCommand command; /// <summary> /// Atributo para termos acesso aos nossos dialog services /// </summary> private DialogService dialogService; private NetworkService networkService; #endregion #region Construtor /// <summary> /// Construtor da class /// </summary> public SecondDataService() { // vamos optar por na raiz criar uma pasta Data e vai ser nessa pasta que vamos criar a Base de Dados // se a pasta não existir ele vai criar dialogService = new DialogService(); networkService = new NetworkService(); var connection2 = networkService.CheckConnection(); if (!Directory.Exists("Data")) // se a pasta não existir vamos cria-la { Directory.CreateDirectory("Data"); // criamos a pasta } //if (File.Exists(@"Data\LinguaPaises.sqlite") && connection2.IsSucess) //{ // return; //} //else if (!File.Exists(@"Data\LinguaPaises.sqlite") && !connection2.IsSucess) //{ // return; //} var path = @"Data\LinguaPaises.sqlite"; //vai servir para o caminho da base de dados principal try { connection = new SQLiteConnection("DataSource=" + path); // na prática o que está dentro de () é a connection string connection.Open(); // abre a base de dados ou cria se ela não existir string sqlcommand = "create table if not exists linguapaises(Id int, Name varchar(60), Language varchar(50), Word varchar(50))"; // cria a tabela command = new SQLiteCommand(sqlcommand, connection); command.ExecuteNonQuery(); // na prática vai executar o comando que aqui está } catch (Exception e) { dialogService.ShowMessage("Erro", e.Message); } // aqui básicamente se não existir ele cria a base de dados e a tabela se existir ele vai abrir a base de dados } #endregion #region Métodos /// <summary> /// Metodo que vai preencher a tabela da base de dados com os valores /// </summary> /// <param name="Paises"></param> public async Task Savedata(List<LinguaPais> LinguaPais, IProgress<int> progress) { int cont = 0; try { foreach (var linguapais in LinguaPais) { string sql = string.Format("insert into linguapaises (Id, Name, Language, Word) values({0}, '{1}', '{2}', '{3}')", linguapais.Id, linguapais.Name.Replace("'", "''"), linguapais.Language.Replace("'", "''"), linguapais.Word); cont++; command = new SQLiteCommand(sql, connection); progress.Report(cont); await command.ExecuteNonQueryAsync(); } connection.Close(); } catch (Exception e) { dialogService.ShowMessage("Erro", e.Message); } } /// <summary> /// Metodo que retorna a lista de paises para fora já com os valores /// </summary> public List<LinguaPais> GetData() { List<LinguaPais> linguapais = new List<LinguaPais>(); try { string sql = "select Id, Name, Language, Word from linguapaises"; command = new SQLiteCommand(sql, connection); //Lê cada registo SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()) // o while vai à tabela ler registo a registo { linguapais.Add(new LinguaPais { Id = (int)reader["Id"], Name = (string)reader["Name"], Language = (string)reader["Language"], Word = (string)reader["Word"] //Aqui vai carregar da base de dados para dentro da lista }); } connection.Close(); return linguapais; } catch (Exception e) { dialogService.ShowMessage("Erro", e.Message); return null; } } /// <summary> /// Vai limpar a base de dados para ser atualizada com novos dados /// </summary> public void DeleteData() { try { string sql = "delete from linguapaises"; command = new SQLiteCommand(sql, connection); command.ExecuteNonQuery(); } catch (Exception e) { dialogService.ShowMessage("Erro", e.Message); } } #endregion } }
Java
UTF-8
27,683
1.90625
2
[]
no_license
package com.tripdazzle.daycation; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.os.AsyncTask; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.Tasks; import com.google.android.libraries.places.api.Places; import com.google.android.libraries.places.api.model.Place; import com.google.android.libraries.places.api.net.FetchPhotoRequest; import com.google.android.libraries.places.api.net.FetchPhotoResponse; import com.google.android.libraries.places.api.net.FetchPlaceRequest; import com.google.android.libraries.places.api.net.FetchPlaceResponse; import com.google.android.libraries.places.api.net.PlacesClient; import com.tripdazzle.daycation.models.BitmapImage; import com.tripdazzle.daycation.models.Profile; import com.tripdazzle.daycation.models.ProfilePicture; import com.tripdazzle.daycation.models.Review; import com.tripdazzle.daycation.models.Trip; import com.tripdazzle.daycation.models.User; import com.tripdazzle.daycation.models.feed.AddFavoriteEvent; import com.tripdazzle.daycation.models.feed.CreatedTripEvent; import com.tripdazzle.daycation.models.feed.FeedEvent; import com.tripdazzle.daycation.models.feed.ReviewEvent; import com.tripdazzle.daycation.models.location.LocationBuilder; import com.tripdazzle.server.ProxyServer; import com.tripdazzle.server.ServerError; import com.tripdazzle.server.datamodels.BitmapData; import com.tripdazzle.server.datamodels.ProfilePictureData; import com.tripdazzle.server.datamodels.ReviewData; import com.tripdazzle.server.datamodels.TripData; import com.tripdazzle.server.datamodels.feed.AddFavoriteEventData; import com.tripdazzle.server.datamodels.feed.CreatedTripEventData; import com.tripdazzle.server.datamodels.feed.FeedEventData; import com.tripdazzle.server.datamodels.feed.ReviewEventData; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; public class DataModel { private ProxyServer server = new ProxyServer(); private User currentUser; public PlacesClient placesClient; public PlacesManager placesManager; public LocationBuilder locationBuilder; // Makes blocking requests, only use in task context public void initialize(Context context) { String localFilesDir = context.getFilesDir().getAbsolutePath(); server.setDbLocation(localFilesDir); // add demo images to db Integer[] images = {R.drawable.mission_bay, R.drawable.balboa, R.drawable.lajolla, R.drawable.zoo, R.drawable.mscott, R.drawable.jhalpert}; for(Integer i: images){ InputStream in = context.getResources().openRawResource(i); try { server.addImage(new BitmapData(-1, in)); } catch (ServerError serverError) { serverError.printStackTrace(); throw new RuntimeException(serverError); } } // Set current User try { currentUser = new User(server.login("mscott", "password123")); } catch (ServerError serverError) { serverError.printStackTrace(); } // Initialize places SDK String apiKey = null; try { apiKey = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData.getString("com.google.android.geo.API_KEY"); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e); } Places.initialize(context, apiKey); placesClient = Places.createClient(context); placesManager = new PlacesManager(); locationBuilder = new LocationBuilder(placesManager); } // Call when the user's data changes private void refreshUser(){ try { this.currentUser = new User(server.login("mscott", "password123")); } catch (ServerError serverError) { serverError.printStackTrace(); } } /* Data getters/setters*/ public void getImageById(int imageId, ImagesSubscriber callback) { new GetImagesByIdsTask(callback).execute(Collections.singletonList(imageId)); } public void getImagesByIds(List<Integer> imageIds, ImagesSubscriber callback) { new GetImagesByIdsTask(callback).execute(imageIds); } public void getProfilePicturesByIds(List<String> userIds, ImagesSubscriber callback) { new GetProfilePicturesByUserIdsTask(callback).execute(userIds); } public void getTripById(int tripId, TripsSubscriber callback){ new GetTripsByIdsTask(callback).execute(Collections.singletonList(tripId)); } public void getTripsByIds(List<Integer> tripIds, TripsSubscriber callback){ new GetTripsByIdsTask(callback).execute(tripIds); } public void getReviewsByIds(List<Integer> reviewIds, ReviewsSubscriber callback){ new GetReviewsByIdsTask(callback).execute(reviewIds); } public void getProfileById(String userId, ProfilesSubscriber callback) { new GetProfileByIdTask(callback).execute(userId); } public void getNewsFeed(String userId, OnGetNewsFeedListener callback){ new GetNewsFeedTask(callback).execute(userId); } public void searchTrips(String query, OnSearchTripsListener callback) { new SearchTripsTask(callback).execute(query); } public User getCurrentUser(){ return currentUser; } public void getFavoritesByUserId(String userId, TripsSubscriber callback){ new GetFavoritesByUserIdTask(callback).execute(userId); } public void toggleFavorite(String userId, Integer tripId, Boolean addFavorite, TripsSubscriber callback){ new ToggleFavoriteTask(callback).execute(new ToggleFavoritesParams(userId, tripId, addFavorite)); } public Boolean inCurrentUsersFavorites(Integer tripId){ return currentUser.inFavorites(tripId); } public void getRecommendedTripsForUser(String userId, OnRecommendedTripsListener callback){ new GetRecommendedTripsByUserIdTask(callback).execute(userId); } public void createTrip(Trip trip, TaskContext context){ new CreateTripTask(context).execute(trip); } public void createReview(Review review, TaskContext context){ new CreateReviewTask(context).execute(review); } /* Places manager */ public class PlacesManager { private Map<String, Place> places = new HashMap<>(); List<Place.Field> standardFields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG, Place.Field.PHOTO_METADATAS); private OnSuccessListener<FetchPlaceResponse> addPlaceListener = new OnSuccessListener<FetchPlaceResponse>() { @Override public void onSuccess(FetchPlaceResponse fetchPlaceResponse) { Place place = fetchPlaceResponse.getPlace(); places.put(place.getId(), place); } }; public PlacesManager() {} public void addPlacesAsync(List<String> places){ for(String placeId: places){ FetchPlaceRequest request = FetchPlaceRequest.newInstance(placeId, standardFields); placesClient.fetchPlace(request).addOnSuccessListener(addPlaceListener); } } /* Returns place matching id, fetching it from the places API if necessary. Blocking.*/ public Place addAndGetPlaceById(String placeId){ Place place; if(places.containsKey(placeId)){ place = places.get(placeId); } else { FetchPlaceRequest request = FetchPlaceRequest.newInstance(placeId, standardFields); Task<FetchPlaceResponse> task = placesClient.fetchPlace(request).addOnSuccessListener(addPlaceListener); try { Tasks.await(task); } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); } place = task.getResult().getPlace(); } if(place == null){ throw new NullPointerException("Null place! Id " + placeId); } return place; } public Place getPlaceById(String id){ // may be null return places.get(id); } public void getPhoto(Place place, final OnGetPhotosListener callback) { if(place.getPhotoMetadatas() == null){ callback.onGetPhoto(null); // TODO replace with a place holder image return; } FetchPhotoRequest request = FetchPhotoRequest.builder(place.getPhotoMetadatas().get(0)).build(); placesClient.fetchPhoto(request).addOnSuccessListener(new OnSuccessListener<FetchPhotoResponse>() { @Override public void onSuccess(FetchPhotoResponse fetchPhotoResponse) { Bitmap photo = fetchPhotoResponse.getBitmap(); callback.onGetPhoto(new BitmapImage(photo, -1)); } }); } } /* * Asynchronous Tasks */ // Interfaces public interface DataManager { /* Implemented by the main activity that serves as the keeper of the data model */ public DataModel getModel(); } public interface TaskContext{ /** onSuccess: called on success of an async task * @param message Message to return*/ void onSuccess(String message); /** onSuccess: called on error of an async task * @param message Message to return*/ void onError(String message); } public interface TripsSubscriber extends TaskContext { /** called on fetch of a trip by id * @param trips Trip returned by query*/ void onGetTripsById(List<Trip> trips); void onGetFavoritesByUserId(List<Trip> favorites); } public interface ImagesSubscriber extends TaskContext { /** called on fetch of an image by id * @param images BitmapImage returned by query * */ void onGetImagesById(List<BitmapImage> images); void onGetProfilePicturesByUserIds(List<ProfilePicture> images); } public interface ProfilesSubscriber extends TaskContext { /** called on fetch of a profile by id * @param profile Profile fetched from server * */ void onGetProfileById(Profile profile); } public interface ReviewsSubscriber extends TaskContext { /** called on fetch of a list of reviews by id * @param reviews Reviews returned by query * */ void onGetReviewsByIds(List<Review> reviews); } public interface OnRecommendedTripsListener { void onRecommendedTrips(List<Trip> trips); } public interface OnSearchTripsListener { void onSearchTripsResults(List<Trip> trips); } public interface OnGetNewsFeedListener { void onGetNewsFeed(List<FeedEvent> feed); } public interface OnGetPhotosListener { void onGetPhoto(BitmapImage photo); } // Tasks private class GetTripsByIdsTask extends AsyncTask<List<Integer>, Void, List<Trip>> { /** Application Context*/ private TripsSubscriber context; private GetTripsByIdsTask(TripsSubscriber context) { this.context = context; } @Override protected List<Trip> doInBackground(List<Integer> ... tripIds) { if (tripIds.length > 1){ return null; } else { List<TripData> tripsData = server.getTripsById(tripIds[0]); List<Trip> trips = new ArrayList<>(); for (TripData t : tripsData) { trips.add(new Trip(t, locationBuilder)); } return trips; } } @Override protected void onPostExecute(List<Trip> result) { super.onPostExecute(result); if(result == null){ context.onError("No trip found with corresponding id"); } else { // onSuccess()? context.onGetTripsById(result); } } } private class CreateTripTask extends AsyncTask<Trip, Void, Boolean> { /** Application Context*/ private TaskContext context; private CreateTripTask(TaskContext context) { this.context = context; } @Override protected Boolean doInBackground(Trip ... trips) { if (trips.length > 1){ return false; } try { if(trips[0].mainImage.id == -1){ // Add the image if it doesn't exist yet Trip trip = trips[0]; int imgId = server.addImage(trip.mainImage.toData()); server.createTrip(trip.toDataNewImage(imgId)); } else { server.createTrip(trips[0].toData()); } refreshUser(); } catch (ServerError serverError) { serverError.printStackTrace(); return false; } return true; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if(result == false){ context.onError("No trip found with corresponding id"); } else { // onSuccess()? context.onSuccess("Trip successfully created"); } } } private class CreateReviewTask extends AsyncTask<Review, Void, Boolean> { /** Application Context*/ private TaskContext context; private CreateReviewTask(TaskContext context) { this.context = context; } @Override protected Boolean doInBackground(Review ... reviews) { if (reviews.length > 1){ return false; } try { server.createReview(reviews[0].toData()); } catch (ServerError serverError) { serverError.printStackTrace(); return false; } return true; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if(result == false){ context.onError("Review could not be created"); } else { context.onSuccess("Review successfully created"); } } } private class GetImagesByIdsTask extends AsyncTask<List<Integer>, Void, List<BitmapImage>> { /** Application Context*/ private ImagesSubscriber context; private GetImagesByIdsTask(ImagesSubscriber context) { this.context = context; } @Override protected List<BitmapImage> doInBackground(List<Integer> ... imageIds) { if (imageIds.length > 1){ return null; } else { try { List<BitmapData> imageData = server.getImagesById(imageIds[0]); List<BitmapImage> images = new ArrayList<>(); for(BitmapData bmp: imageData){ images.add(new BitmapImage(bmp)); } return images; } catch (ServerError serverError) { serverError.printStackTrace(); return null; } } } @Override protected void onPostExecute(List<BitmapImage> result) { super.onPostExecute(result); if(result == null || result.size() == 0){ context.onError("No images found"); } else { // onSuccess()? context.onGetImagesById(result); } } } private class GetProfilePicturesByUserIdsTask extends AsyncTask<List<String>, Void, List<ProfilePicture>> { /** * Application Context */ private ImagesSubscriber context; private GetProfilePicturesByUserIdsTask(ImagesSubscriber context) { this.context = context; } @Override protected List<ProfilePicture> doInBackground(List<String>... userIds) { if (userIds.length > 1){ return null; } else { try { List<ProfilePictureData> imageData = server.getProfilePicturesByUserIds(userIds[0]); List<ProfilePicture> images = new ArrayList<>(); for(ProfilePictureData bmp: imageData){ images.add(new ProfilePicture(bmp)); } return images; } catch (ServerError serverError) { serverError.printStackTrace(); return null; } } } @Override protected void onPostExecute(List<ProfilePicture> result) { super.onPostExecute(result); if(result == null || result.size() == 0) { context.onError("No images found"); } else { // onSuccess()? context.onGetProfilePicturesByUserIds(result); } } } private class GetReviewsByIdsTask extends AsyncTask<List<Integer>, Void, List<Review>> { /** Application Context*/ private ReviewsSubscriber context; private GetReviewsByIdsTask(ReviewsSubscriber context) { this.context = context; } @Override protected List<Review> doInBackground(List<Integer> ... reviewIds) { if (reviewIds.length > 1){ return null; } else { List<ReviewData> reviewsData; try { Thread.sleep(2000); reviewsData = server.getReviewsById(reviewIds[0]); } catch (InterruptedException | ServerError serverError) { serverError.printStackTrace(); return null; } List<Review> reviews = new ArrayList<>(); for (ReviewData r : reviewsData) { reviews.add(new Review(r)); } return reviews; } } @Override protected void onPostExecute(List<Review> result) { super.onPostExecute(result); if(result == null){ context.onError("Server Error"); } else { // onSuccess()? context.onGetReviewsByIds(result); } } } private class GetProfileByIdTask extends AsyncTask<String, Void, Profile> { /** Application Context*/ private ProfilesSubscriber context; private GetProfileByIdTask(ProfilesSubscriber context) { this.context = context; } @Override protected Profile doInBackground(String ... userIds) { if (userIds.length > 1){ return null; } else { try { return new Profile(server.getProfileById(userIds[0])); } catch (ServerError serverError) { serverError.printStackTrace(); return null; } } } @Override protected void onPostExecute(Profile result) { super.onPostExecute(result); if(result == null){ context.onError("Server Error"); } else { // onSuccess()? context.onGetProfileById(result); } } } private class GetFavoritesByUserIdTask extends AsyncTask<String, Void, List<Trip>> { /** Application Context*/ private TripsSubscriber context; private GetFavoritesByUserIdTask(TripsSubscriber context) { this.context = context; } @Override protected List<Trip> doInBackground(String ... userIds) { if (userIds.length > 1){ return null; } else { try { List<TripData> favoritesData = server.getFavoritesByUserId(userIds[0]); List<Trip> favorites = new ArrayList<>(); for(TripData t: favoritesData){ favorites.add(new Trip(t, locationBuilder)); } return favorites; } catch (ServerError serverError) { serverError.printStackTrace(); return null; } } } @Override protected void onPostExecute(List<Trip> result) { super.onPostExecute(result); if(result == null){ context.onError("No favorites found"); } else { // onSuccess()? context.onGetFavoritesByUserId(result); } } } private class GetRecommendedTripsByUserIdTask extends AsyncTask<String, Void, List<Trip>> { /** Application Context*/ private OnRecommendedTripsListener context; private GetRecommendedTripsByUserIdTask(OnRecommendedTripsListener context) { this.context = context; } @Override protected List<Trip> doInBackground(String ... userIds) { if (userIds.length > 1){ return null; } else { try { List<TripData> recommendationsData = server.getRecommendedTripsByUserId(userIds[0]); List<Trip> recommendedTrips = new ArrayList<>(); for(TripData t: recommendationsData){ recommendedTrips.add(new Trip(t, locationBuilder)); } return recommendedTrips; } catch (ServerError serverError) { serverError.printStackTrace(); return null; } } } @Override protected void onPostExecute(List<Trip> result) { super.onPostExecute(result); if(result == null){ // context.onError("No favorites found"); } else { // onSuccess()? context.onRecommendedTrips(result); } } } public class ToggleFavoritesParams{ public final String userId; public final Integer tripId; public final Boolean addFavorite; public ToggleFavoritesParams(String userId, Integer tripId, Boolean addFavorite) { this.userId = userId; this.tripId = tripId; this.addFavorite = addFavorite; } } private class ToggleFavoriteTask extends AsyncTask<ToggleFavoritesParams, Void, Boolean> { /** Application Context*/ private TripsSubscriber context; private ToggleFavoriteTask(TripsSubscriber context) { this.context = context; } @Override protected Boolean doInBackground(ToggleFavoritesParams ... params) { if (params.length > 1){ return false; } else { try { ToggleFavoritesParams params1 = params[0]; if(params1.userId.equals(currentUser.userId)){ currentUser.toggleFavorite(params1.tripId, params1.addFavorite); } server.toggleFavorite(params1.userId, params1.tripId, params1.addFavorite); } catch (ServerError err){ err.printStackTrace(); return false; } return true; } } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if(!result){ context.onError("No trip found with corresponding id"); } else { context.onSuccess("Favorite Toggled"); } } } private class SearchTripsTask extends AsyncTask<String, Void, List<Trip>> { /** Application Context*/ private OnSearchTripsListener context; private SearchTripsTask(OnSearchTripsListener context) { this.context = context; } @Override protected List<Trip> doInBackground(String ... params) { if (params.length > 1){ return null; } else { try { List<TripData> tripData = server.searchTrips(params[0]); List<Trip> trips = new ArrayList<>(); for(TripData trip: tripData){ trips.add(new Trip(trip, locationBuilder)); } return trips; } catch (ServerError err){ err.printStackTrace(); return null; } } } @Override protected void onPostExecute(List<Trip> results) { super.onPostExecute(results); if(results == null){ // context.onError("Error occurred"); } else { context.onSearchTripsResults(results); } } } private class GetNewsFeedTask extends AsyncTask<String, Void, List<FeedEvent>> { /** Application Context*/ private OnGetNewsFeedListener context; private GetNewsFeedTask(OnGetNewsFeedListener context) { this.context = context; } @Override protected List<FeedEvent> doInBackground(String ... params) { if (params.length > 1){ return null; } else { try { List<FeedEventData> feedData = server.getNewsFeed(params[0]); List<FeedEvent> feed = new ArrayList<>(); for(FeedEventData event: feedData){ if(event instanceof ReviewEventData){ feed.add(new ReviewEvent((ReviewEventData) event)); } else if(event instanceof AddFavoriteEventData){ feed.add(new AddFavoriteEvent((AddFavoriteEventData) event, locationBuilder)); } else if(event instanceof CreatedTripEventData){ feed.add(new CreatedTripEvent((CreatedTripEventData) event, locationBuilder)); } } return feed; } catch (ServerError serverError) { serverError.printStackTrace(); return null; } } } @Override protected void onPostExecute(List<FeedEvent> results) { super.onPostExecute(results); if(results == null){ // context.onError("Error occurred"); } else { context.onGetNewsFeed(results); } } } }
Markdown
UTF-8
1,669
2.5625
3
[ "MIT" ]
permissive
# CustomerShippingContactsResponse Contains the detail of the shipping addresses that the client has active or has used in Conekta ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **phone** | **str** | | [optional] **receiver** | **str** | | [optional] **between_streets** | **str** | | [optional] **address** | [**CustomerShippingContactsResponseAddress**](CustomerShippingContactsResponseAddress.md) | | [optional] **parent_id** | **str** | | [optional] **default** | **bool** | | [optional] **id** | **str** | | [optional] **created_at** | **int** | | [optional] **object** | **str** | | [optional] **deleted** | **bool** | | [optional] ## Example ```python from conekta.models.customer_shipping_contacts_response import CustomerShippingContactsResponse # TODO update the JSON string below json = "{}" # create an instance of CustomerShippingContactsResponse from a JSON string customer_shipping_contacts_response_instance = CustomerShippingContactsResponse.from_json(json) # print the JSON string representation of the object print CustomerShippingContactsResponse.to_json() # convert the object into a dict customer_shipping_contacts_response_dict = customer_shipping_contacts_response_instance.to_dict() # create an instance of CustomerShippingContactsResponse from a dict customer_shipping_contacts_response_form_dict = customer_shipping_contacts_response.from_dict(customer_shipping_contacts_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
Markdown
UTF-8
3,700
3.03125
3
[]
no_license
+-- {: .rightHandSide} +-- {: .toc .clickDown tabindex="0"} ### Context #### Category theory +-- {: .hide} [[!include category theory - contents]] =-- =-- =-- #Contents# * table of contents {:toc} ## Definition An **absolute coequalizer** in a [[category]] $C$ is a [[coequalizer]] which is preserved by *any* [[functor]] $F\colon C \to D$. This is a special case of an [[absolute colimit]]. ## Characterization Intuitively, an absolute coequalizer is a diagram that is a coequalizer "purely for diagrammatic reasons." The most common example is a [[split coequalizer]]. A trivial example of an absolute coequalizer that is not split is a diagram of the form $$ X \; \underoverset{f}{f}{\rightrightarrows}\; Y \overset{1_Y}{\to} Y $$ whenever $f$ is not a [[split epimorphism]]. In fact, split coequalizers and "trivial" absolute coequalizers are the cases $n=1$ and $0$ of a general characterization of absolute coequalizers, which we now describe. Suppose that $$ X\; \underoverset{f_1}{f_0}{\rightrightarrows}\; Y \overset{e}{\to} Z $$ is an absolute coequalizer. Then it must be preserved, in particular, by the hom-functor $hom(Z,-)\colon C \to Set$; that is, we have a coequalizer diagram $$ hom(Z,X)\; \underoverset{f_1\circ -}{f_0\circ -}{\rightrightarrows}\; hom(Z,Y) \overset{e\circ -}{\to} hom(Z,Z)$$ in $Set$. In particular, that means that $e\circ -$ is surjective, and so in particular there exists some $s\colon Z\to Y$ such that $e s = 1_Z$. In other words, $e$ is [[split epimorphism|split epic]]. Now the given coequalizer must also be preserved by the hom-functor $hom(Y,-)$, so we have another coequalizer diagram $$ hom(Y,X)\; \underoverset{f_1\circ -}{f_0\circ -}{\rightrightarrows}\; hom(Y,Y) \overset{e\circ -}{\to} hom(Y,Z)$$ in $Set$. We also have two elements $1_Y$ and $s e$ in $hom(Y,Y)$ with the property that $e \circ 1_Y = e = e \circ s e$ (since $e s = 1_Z$). However, a coequalizer of two functions $h_0,h_1\colon P\to Q$ in $Set$ is constructed as the [[quotient set]] of $Q$ by the [[equivalence relation]] generated by the image of $(h_0,h_1)\colon P\to Q\times Q$. That means that we set $q\sim q'$ iff there is a finite sequence $p_1,\dots, p_n$ of elements of $P$ and a finite sequence $\varepsilon_0,\dots,\varepsilon_n$ with $\varepsilon_i\in\{0,1\}$, such that $h_{\varepsilon_1}(p_1)=q$, $h_{1-\varepsilon_i}(p_i)=h_{\varepsilon_{i+1}}(p_{i+1})$, and $h_{1-\varepsilon_n}(p_n)=q'$. We consider $q=q'$ as the case $n=0$. Therefore, since $1_Y$ and $s e$ are in the same class of the equivalence relation on $hom(Y,Y)$ generated by $f_0$ and $f_1$, they must be related by such a finite chain of elements of $hom(Y,X)$. That is, we must have morphisms $t_1,\dots, t_n\colon Y\to X$ and a sequence of binary digits $\varepsilon_1,\dots,\varepsilon_n$ such that $f_{\varepsilon_1} t_1=1_Y$, $f_{1-\varepsilon_i} t_i = f_{\varepsilon_i} t_{i+1}$, and $f_{1-\varepsilon_n}t_n=s e$. (Note that if $n=1$ then this says precisely that we have a split coequalizer, and if $n=0$ it is the trivial case above.) Conversely, it is easy to check that given $s$ and $t_1,\dots, t_n$ satisfying these equations, the given fork must be a coequalizer, for essentially the same reason that any split coequalizer is a coequalizer. Thus we have a complete characterization of absolute coequalizers. This characterization is essentially a special case of the characterization of [[absolute colimits]] (in unenriched categories). ## Examples * [[Beck coequalizer]] ## References * [[Robert Pare]], *Absolute coequalizers*, Lecture Notes in Math. 86 (1969), 132-145. [[!redirects absolute coequalizers]]
C++
UTF-8
430
3.046875
3
[]
no_license
// queue.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "queue.h" #include <iostream> using namespace std; int main() { queue q; cout << "please enter your data to stop it enter a Negative number:\n"; int x=-1; cin >> x; while(x>0 && !q.isFull()) { q.push(x); cin >> x; } q.displayQueue(); while (!q.isEmpty()) { q.pop(); q.displayQueue(); } return 0; }
C#
UTF-8
830
3.171875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace hlassistant { class Fileworks { public string ReadStr(string filename) { StreamReader sr = new StreamReader(filename); return sr.ReadToEnd().ToString(); } public int ReadInt(string filename) { StreamReader sr = new StreamReader(filename); return Int32.Parse(sr.ReadToEnd()); } public void WriteString(string filename, string content) { FileStream aFile = new FileStream(filename, FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(aFile); // aFile.Seek(0, SeekOrigin.End); sw.Write(content); sw.Close(); } } }
Java
UTF-8
7,182
1.84375
2
[]
no_license
package com.framework.webClient.schedulerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSONObject; import com.framework.entity.input.HeartbeatEntity; import com.framework.entity.input.UserLoginEntity; import com.framework.entity.output.DZOutputEntity; import com.framework.entity.output.KLOutputEntity; import com.framework.entity.output.LZOutPutEntity; import com.framework.entity.output.PlaceOutputEntity; import com.framework.entity.output.PlanToStartOutputEntity; import com.framework.jt808.common.DataCache; import com.framework.jt808.thread.ReBackMsgThread; import com.framework.jt808.thread.ZFMsgThread; import com.framework.jt808.vo.BusState; import com.framework.jt808.vo.StationInfo; import com.framework.redis.SerializeUtil; import com.framework.util.DateUtils; import com.framework.webClient.service.ICommon808Service; import com.framework.webClient.util.CommonFunc; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @Component public class InstallSocket extends Thread { private Logger logger = LoggerFactory.getLogger(this.getClass()); private ICommon808Service common808Service; InputStream inputStream = null; public static ConcurrentHashMap<String, PlaceOutputEntity> busMapTemp = new ConcurrentHashMap<String, PlaceOutputEntity>(); public static Socket socket; private String serverIp; private String serverPort; private String loginUser; private String loginPassWord; public static volatile boolean runFlg = true; public InstallSocket(ICommon808Service common808Service) { this.common808Service = common808Service; runFlg = true; } public void init() throws IOException { serverIp = CommonFunc.getConfigString("forward_socket_server_ip"); serverPort = CommonFunc.getConfigString("forward_socket_server_port"); loginUser = CommonFunc.getConfigString("forward_socket_login_user"); loginPassWord = CommonFunc.getConfigString("forward_socket_login_password"); connect(); refreshTimer(); ZFMsgThread dealQueue = new ZFMsgThread(busMapTemp); new Thread(dealQueue).start(); } public void connect() throws IOException { socket = new Socket(); socket.connect(new InetSocketAddress(serverIp, Integer.parseInt(serverPort))); UserLoginEntity ul = new UserLoginEntity(); ul.setUserame(loginUser); ul.setPasswd(loginPassWord); socket.getOutputStream().write(SerializeUtil.serialize(ul)); inputStream = socket.getInputStream(); } public void refreshTimer() { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { if (runFlg) { HeartbeatEntity heartbeatEntity = new HeartbeatEntity(); heartbeatEntity.setTimestamp(String.valueOf(System.currentTimeMillis())); logger.info("发送心跳"); if (socket == null || !socket.isConnected() || socket.isClosed()) { connect(); } socket.getOutputStream().write(SerializeUtil.serialize(heartbeatEntity)); }else { timer.cancel(); socket.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); socket = null; } } }, 0, 1000 * 30); } public void run() { logger.info("开始执行线程"); while (runFlg) { try { if (socket == null || !socket.isConnected() || socket.isClosed()) connect(); // logger.info("接收数据{}"); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); Object object = objectInputStream.readObject(); // gps if (object instanceof PlaceOutputEntity) { // common808Service.insertGPSLog((PlaceOutputEntity) object); // 数据类型转换 PlaceOutputEntity gpsData = (PlaceOutputEntity) object; if(gpsData.getLinename()!= null && "56".equals(gpsData.getLinename())) { busMapTemp.put(gpsData.getBusnumber(), gpsData); }else { if (gpsData.getBusstatus() != null && "0".equals(gpsData.getBusstatus())) { // 代表车在终点,可以删除数据 busMapTemp.put(gpsData.getBusnumber(), gpsData); } } } // 客流 if (object instanceof KLOutputEntity) { // 数据类型转换 KLOutputEntity klData = (KLOutputEntity) object; // 老拥挤度 用车牌号存的 //if ( klData.getCongestion()!= null && !"".equals(klData.getCongestion())&& klData.getBusnumber() != null && !"".equals(klData.getBusnumber())) { if ( klData.getCongestion()!= null && !"".equals(klData.getCongestion())&& klData.getBusname() != null && !"".equals(klData.getBusname())) { /*String busname1=klData.getBusname(); String congestion1= klData.getCongestion(); System.out.println("busname:"+busname1); System.out.println("congestion:"+congestion1);*/ Integer congestion = Integer.parseInt(klData.getCongestion()) - 1; // 老拥挤度 用车牌号存的 //DataCache.yjdMap.put(klData.getBusnumber(), congestion); DataCache.yjdMap.put(klData.getBusname(), congestion); } } // 计划发车 if (object instanceof PlanToStartOutputEntity) { // 数据类型转换 PlanToStartOutputEntity data = (PlanToStartOutputEntity) object; DataCache.readySendBusMap.put(data.getLinename() + "-" + data.getDirection(), data.getEntitys()); } } catch (Exception e) { logger.error("转发服务异常", e); socket = null; // ZFMsgThread.runFlg = false; } } } /** * 得到当前时间 yyyy-MM-dd HH:mm:ss格式 * * @return 当前时间 */ private String currTime() throws Exception { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String currTime = df.format(date); return currTime; } /** * 计算时间差(单位:分钟) * * @param lastReceiveTime * @return */ private long dateMethod(String gpsTime) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date1 = df.parse(currTime()); Date date2 = df.parse(gpsTime); long diff = date1.getTime() - date2.getTime(); // 计算两个时间之间差了多少分钟 long minutes = diff / (1000 * 60); return minutes; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } }
SQL
UTF-8
11,523
3.09375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.6.5.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jul 08, 2017 at 09:54 AM -- Server version: 10.1.21-MariaDB -- PHP Version: 5.6.30 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `hospital_management_system` -- CREATE DATABASE IF NOT EXISTS `hospital_management_system` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; USE `hospital_management_system`; -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `admin_id` int(100) NOT NULL, `username` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `status` varchar(100) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`admin_id`, `username`, `password`, `status`) VALUES (3, 'tahsina', '123', 'active'); -- -------------------------------------------------------- -- -- Table structure for table `appointment` -- CREATE TABLE `appointment` ( `id` int(11) NOT NULL, `patient_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `doctors_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `patient_phone` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `time` time NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `appointment` -- INSERT INTO `appointment` (`id`, `patient_name`, `doctors_name`, `patient_phone`, `time`) VALUES (4, 'Afsu', 'Hasina', '673738', '14:02:00'), (5, 'Anika', 'Hasan', '223232', '17:04:00'); -- -------------------------------------------------------- -- -- Table structure for table `bill_info` -- CREATE TABLE `bill_info` ( `bill_id` int(11) NOT NULL, `pres_id` int(11) NOT NULL, `reg_fee` float NOT NULL, `cabin` float NOT NULL, `medicine` float NOT NULL, `doctor` float NOT NULL, `meal` float NOT NULL, `other` float NOT NULL, `total` float NOT NULL, `service_charge` float NOT NULL, `vat` float NOT NULL, `gross_amount` float NOT NULL, `date` datetime NOT NULL, `is_trashed` varchar(20) NOT NULL DEFAULT 'No' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `bill_info` -- INSERT INTO `bill_info` (`bill_id`, `pres_id`, `reg_fee`, `cabin`, `medicine`, `doctor`, `meal`, `other`, `total`, `service_charge`, `vat`, `gross_amount`, `date`, `is_trashed`) VALUES (9, 19, 200, 200, 4000, 5000, 200, 100, 9700, 50, 0, 9750, '0000-00-00 00:00:00', 'No'), (10, 20, 200, 200, 4343, 2222, 200, 100, 7265, 50, 0, 7315, '0000-00-00 00:00:00', '2017-07-08 10:04:16'), (11, 21, 200, 200, 2000, 4500, 200, 100, 7200, 50, 0, 7250, '0000-00-00 00:00:00', '2017-07-05 23:20:55'), (13, 32, 200, 200, 500, 2000, 200, 100, 3200, 50, 120, 3370, '2017-07-04 22:55:51', '2017-07-04 23:09:02'), (14, 33, 300, 250, 1000, 2000, 200, 50, 3800, 200, 120, 4120, '2017-07-04 22:56:53', 'No'), (15, 23, 200, 250, 1000, 5000, 250, 100, 6800, 50, 0, 6850, '2017-07-06 23:11:52', 'No'), (16, 5, 76, 68, 88, 77, 76, 66, 451, 87, 7878, 8416, '2017-07-07 16:09:41', 'No'); -- -------------------------------------------------------- -- -- Table structure for table `doctors_info` -- CREATE TABLE `doctors_info` ( `id` int(11) NOT NULL, `doctor_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(300) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(300) COLLATE utf8_unicode_ci NOT NULL, `type` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `status` varchar(300) COLLATE utf8_unicode_ci NOT NULL, `mobile` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `address` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `available_time` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `image` varchar(300) COLLATE utf8_unicode_ci NOT NULL, `join_date` date NOT NULL, `join_time` time NOT NULL, `is_trashed` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `doctors_info` -- INSERT INTO `doctors_info` (`id`, `doctor_name`, `email`, `password`, `type`, `status`, `mobile`, `address`, `available_time`, `image`, `join_date`, `join_time`, `is_trashed`) VALUES (22, 'sanjana', 'sanjana@gmail.com', '123', 'Pediatric', 'cmc', '88345', 'ctg', '3', '14994981812108428-1474108438.png', '2017-07-08', '01:16:00', 'no'); -- -------------------------------------------------------- -- -- Table structure for table `doctors_reply` -- CREATE TABLE `doctors_reply` ( `reply_no` int(11) NOT NULL, `doctor-id` int(100) NOT NULL, `patient_id` int(100) NOT NULL, `reply` varchar(255) NOT NULL, `read_unread_status` varchar(100) NOT NULL, `reply_date` date NOT NULL, `reply_time` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `medicine` -- CREATE TABLE `medicine` ( `id` int(11) NOT NULL, `medicine_name` varchar(1000) COLLATE utf8_unicode_ci NOT NULL, `price` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `category` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `is_trashed` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'No' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `medicine` -- INSERT INTO `medicine` (`id`, `medicine_name`, `price`, `category`, `is_trashed`) VALUES (3, 'xxxsx', 'xsssxx', 'sxsx', '2017-07-07 11:39:59'), (4, 'Omep(20mg)', '4tk/Capsule', 'Omeprazole(PPI)', 'No'), (5, 'Xeldrin(20mg)', '6tk/Capsule', 'Omeprazole(PPI)', 'No'), (6, 'Seclo(20mg)', '5tk/Capsule', 'Omeprazole(PPI)', 'No'), (7, 'Pantobex(20mg)', '5tk/Capsule', 'Pantonix(PPI)', 'No'), (8, 'Pantonix(20mg)', '4tk/Capsule', 'Pantoprazole(PPI)', 'No'), (9, 'Lantid(15mg)', '6tk/Capsule', 'Lansoprazole(PPI)', 'No'), (10, 'Maxpro(20mg)', '6tk/Capsule', 'Esomeprazole(PPI)', 'No'), (11, 'Nexum(20mg)', '5tk/Capsule', 'Esomeprazole(PPI)', 'No'), (12, 'Esonix(20mg)', '6tk/Capsule', 'Esomeprazole(PPI)', 'No'), (13, 'Finix(20mg)', '7tk/Capsule', 'Rabeprazole(PPI)', 'No'); -- -------------------------------------------------------- -- -- Table structure for table `patient_info` -- CREATE TABLE `patient_info` ( `id` int(10) NOT NULL, `first_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(1000) COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `address` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `is_trashed` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `patient_info` -- INSERT INTO `patient_info` (`id`, `first_name`, `last_name`, `email`, `password`, `phone`, `address`, `is_trashed`) VALUES (13, 'shamim', 'kafi', 'shamimkafi123@gmail.com', 'bbcf249c93285cb6ebd164984ff3aac7', '01876667377', 'kutubdia', 'no'), (14, 'nila', 'islam', 'tahsina@gmail.com', '202cb962ac59075b964b07152d234b70', '8845778', 'ctg', 'no'), (15, 'hosna', 'ara', 'hosna@gmail.com', '202cb962ac59075b964b07152d234b70', '881233', 'ctg', 'no'), (16, 'humi', 'anjum', 'humi@gmail.com', '202cb962ac59075b964b07152d234b70', '88655', 'ctg', 'no'); -- -------------------------------------------------------- -- -- Table structure for table `patient_msg` -- CREATE TABLE `patient_msg` ( `message_no` int(11) NOT NULL, `patient_id` int(100) NOT NULL, `doctor_id` int(100) NOT NULL, `diseaseName` varchar(100) NOT NULL, `sms` varchar(255) NOT NULL, `read_unread_status` varchar(100) NOT NULL, `message_date` date NOT NULL, `message_time` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `patient_msg` -- INSERT INTO `patient_msg` (`message_no`, `patient_id`, `doctor_id`, `diseaseName`, `sms`, `read_unread_status`, `message_date`, `message_time`) VALUES (1, 12, 18, 'fgh', 'fhfh', '', '2017-07-08', '5:37 am'), (2, 14, 18, 'fever', 'vjhbkjm', '', '2017-07-08', '8:48 am'), (3, 15, 18, 'fdfdf', 'dfdfd', '', '2017-07-08', '9:41 am'); -- -------------------------------------------------------- -- -- Table structure for table `payment` -- CREATE TABLE `payment` ( `pay_id` int(11) NOT NULL, `bill_id` int(11) NOT NULL, `discount` varchar(10) NOT NULL, `net_amount` varchar(10) NOT NULL, `paid_amount` varchar(10) NOT NULL, `due_amount` varchar(10) NOT NULL, `date` date NOT NULL, `is_trashed` varchar(20) NOT NULL DEFAULT 'No' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `payment` -- INSERT INTO `payment` (`pay_id`, `bill_id`, `discount`, `net_amount`, `paid_amount`, `due_amount`, `date`, `is_trashed`) VALUES (5, 21, '500', '300', '250', '50', '2017-07-04', '2017-07-06 19:29:37'), (6, 147, '129', '-129', '4500', '-4629', '2017-07-06', '2017-07-07 16:15:14'), (7, 97, '2507', '-2507', '400', '-2907', '2017-07-06', '2017-07-07 16:33:03'), (8, 87, '87', '-87', '878', '-965', '2017-07-07', 'No'); -- -- Indexes for dumped tables -- -- -- Indexes for table `appointment` -- ALTER TABLE `appointment` ADD PRIMARY KEY (`id`); -- -- Indexes for table `bill_info` -- ALTER TABLE `bill_info` ADD PRIMARY KEY (`bill_id`); -- -- Indexes for table `doctors_info` -- ALTER TABLE `doctors_info` ADD PRIMARY KEY (`id`); -- -- Indexes for table `doctors_reply` -- ALTER TABLE `doctors_reply` ADD PRIMARY KEY (`reply_no`); -- -- Indexes for table `medicine` -- ALTER TABLE `medicine` ADD PRIMARY KEY (`id`); -- -- Indexes for table `patient_info` -- ALTER TABLE `patient_info` ADD PRIMARY KEY (`id`); -- -- Indexes for table `patient_msg` -- ALTER TABLE `patient_msg` ADD PRIMARY KEY (`message_no`); -- -- Indexes for table `payment` -- ALTER TABLE `payment` ADD PRIMARY KEY (`pay_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `appointment` -- ALTER TABLE `appointment` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `bill_info` -- ALTER TABLE `bill_info` MODIFY `bill_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; -- -- AUTO_INCREMENT for table `doctors_info` -- ALTER TABLE `doctors_info` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23; -- -- AUTO_INCREMENT for table `doctors_reply` -- ALTER TABLE `doctors_reply` MODIFY `reply_no` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `medicine` -- ALTER TABLE `medicine` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT for table `patient_info` -- ALTER TABLE `patient_info` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; -- -- AUTO_INCREMENT for table `patient_msg` -- ALTER TABLE `patient_msg` MODIFY `message_no` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `payment` -- ALTER TABLE `payment` MODIFY `pay_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C#
UTF-8
3,391
2.53125
3
[ "FTL", "Zlib", "LGPL-2.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-protobuf", "Apache-2.0", "LGPL-2.1-only", "LGPL-3.0-only", "MIT", "BSD-2-Clause", "GPL-3.0-only", "OFL-1.1" ]
permissive
using Fusee.Math.Core; using System.Collections.Generic; using Xunit; namespace Fusee.Tests.Math.Core { public class AABBfTest { [Fact] public void Constructor_MinMax() { var actual = new AABBf(new float3(0, 0, 0), new float3(1, 1, 1)); Assert.Equal(new float3(0, 0, 0), actual.min); Assert.Equal(new float3(1, 1, 1), actual.max); } [Fact] public void Center_Is1() { var aabbf = new AABBf(new float3(0, 0, 0), new float3(2, 2, 2)); var actual = aabbf.Center; Assert.Equal(new float3(1, 1, 1), actual); } [Fact] public void Size_Is1() { var aabbf = new AABBf(new float3(0, 0, 0), new float3(1, 1, 1)); var actual = aabbf.Size; Assert.Equal(new float3(1, 1, 1), actual); } [Theory] [MemberData(nameof(GetUnion))] public void Union_IsUnion(AABBf a, AABBf b, AABBf expected) { var actual = AABBf.Union(a, b); Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(GetTransform))] public void Transform_IsTransform(float4x4 m, AABBf box, AABBf expected) { var actual = m * box; Assert.Equal(expected, actual); } [Fact] public void IntersectRay_Simple() { RayF ray = new(new float3(0, 0, 0), new float3(1, 0, 0)); AABBf box = new(new float3(2, -1, -1), new float3(4, 1, 1)); Assert.True(box.IntersectRay(ray)); } [Fact] public void IntersectRay_AlongEdge() { RayF ray = new(new float3(0, 0, 0), new float3(1, 0, 0)); AABBf box = new(new float3(2, 0, 0), new float3(4, 1, 1)); Assert.True(box.IntersectRay(ray)); } [Fact] public void IntersectRay_Outside() { RayF ray = new(new float3(0, -1, -1), new float3(1, 0, 0)); AABBf box = new(new float3(2, 0, 0), new float3(4, 1, 1)); Assert.False(box.IntersectRay(ray)); } #region IEnumerables public static IEnumerable<object[]> GetUnion() { var a = new AABBf(new float3(0, 0, 0), new float3(1, 1, 1)); var b = new AABBf(new float3(1, 1, 1), new float3(2, 2, 2)); yield return new object[] { a, b, new AABBf(new float3(0, 0, 0), new float3(2, 2, 2)) }; yield return new object[] { b, a, new AABBf(new float3(0, 0, 0), new float3(2, 2, 2)) }; } public static IEnumerable<object[]> GetTransform() { var a = new AABBf(new float3(0, 0, 0), new float3(1, 1, 1)); var xRot = new float4x4(1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1); var yRot = new float4x4(0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 1); var zRot = new float4x4(0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); yield return new object[] { xRot, a, new AABBf(new float3(0, -1, 0), new float3(1, 0, 1)) }; yield return new object[] { yRot, a, new AABBf(new float3(0, 0, -1), new float3(1, 1, 0)) }; yield return new object[] { zRot, a, new AABBf(new float3(-1, 0, 0), new float3(0, 1, 1)) }; } #endregion } }
PHP
UTF-8
809
2.640625
3
[ "Apache-2.0" ]
permissive
<?php namespace app\common\library; /** * Created by PhpStorm. * User: wangcailin * Date: 2017/11/13 * Time: 下午3:43 */ use alidayu\Sms; class Alidayu { /** * 发送验证码 * @param $mobile 手机号 * @param $code 验证码 * @param $signName 短信模板 * @return bool */ public static function send($mobile, $code, $signName) { $alidayu = new Sms; $response = $alidayu::sendSms( "中华消防网校", // 短信签名 $signName, // 短信模板编号 $mobile, // 短信接收者 Array( // 短信模板中字段的值 "code"=> $code, ) ); if ($response->Code != '0'){ return false; } return true; } }
Java
UTF-8
2,270
2.203125
2
[]
no_license
package com.crm.service.imp; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import com.crm.beans.Customer; import com.crm.beans.LinkMan; import com.crm.dao.CustomerDao; import com.crm.dao.LinkmanDao; import com.crm.service.LinkmanService; import com.crm.utils.PageBean; public class LinkmanServiceImp implements LinkmanService { private LinkmanDao linkmanDao; private CustomerDao customerDao; @Override public LinkMan findlikman(Long id) { LinkMan linkMan = linkmanDao.findById(id); return linkMan; } @Override public void modifyLinkman(LinkMan linkman, Long old_lkm_id, Long cust_id) { linkmanDao.modify(linkman); Customer customer = customerDao.findById(cust_id); LinkMan old_linkman = linkmanDao.findById(old_lkm_id); customer.getLinkmen().add(old_linkman); old_linkman.setCustomer(customer); old_linkman.setLkm_email(linkman.getLkm_email()); old_linkman.setLkm_gender(linkman.getLkm_gender()); old_linkman.setLkm_memo(linkman.getLkm_email()); old_linkman.setLkm_mobile(linkman.getLkm_mobile()); old_linkman.setLkm_name(linkman.getLkm_name()); old_linkman.setLkm_phone(linkman.getLkm_phone()); old_linkman.setLkm_position(linkman.getLkm_position()); old_linkman.setLkm_qq(linkman.getLkm_qq()); } @Override public void deleteLinkmanById(Long id) { linkmanDao.remove(id); } @Override public void add(Long cust_id, LinkMan linkman) { Customer customer = customerDao.findById(cust_id); customer.getLinkmen().add(linkman); linkman.setCustomer(customer); linkmanDao.save(linkman); } @Override public PageBean<LinkMan> findAllLinkManByPageBean(DetachedCriteria dc, int currentPage, int pageSize) { int totalCount = linkmanDao.findTatalCount(dc); PageBean<LinkMan> pageBean = new PageBean<LinkMan>(currentPage,pageSize,totalCount); List<LinkMan> list = linkmanDao.finAllByPageBean(dc,pageBean.getPageSize(),pageBean.getCurrentPage()); pageBean.setList(list); return pageBean; } public LinkmanDao getLinkmanDao() { return linkmanDao; } public void setLinkmanDao(LinkmanDao linkmanDao) { this.linkmanDao = linkmanDao; } }
JavaScript
UTF-8
468
2.703125
3
[]
no_license
class App { constructor() { this.firestore = firebase.firestore(); this.auth = firebase.auth(); } authInstance() { return this.auth; } } let instance = new App(); let authObject; instance.authInstance().onAuthStateChanged(firebaseUser => { if (firebaseUser) { authObject = new AuthObject(firebaseUser); authObject.isUser(firebaseUser.email); } else { console.log('Not logged in'); } });
C++
UTF-8
593
2.59375
3
[]
no_license
#include<stdio.h> #include<algorithm> using namespace std; int ans[10010]; int n; int dfs(int k,int c) { if(k == 0) { return c; } if(c > 20) return 0; ans[c + 1] = 0; int len = dfs((k * 10) % n,c + 1); if(len) return len; ans[c + 1] = 1; len = dfs((k * 10 + 1) % n,c + 1); if(len) return len; } int main() { while(~scanf("%d",&n)) { if(n == 0) return 0; int len; if(n == 1) { printf("1\n"); continue; } ans[1] = 1; len = dfs(1,1); for(int i = 1;i <= len;i++) printf("%d",ans[i]); printf("\n"); } return 0; }
C#
UTF-8
1,306
2.5625
3
[]
no_license
public class FocusHighlightBehavior : Behavior<Path> { public FrameworkElement FocusElement { get { return (FrameworkElement)GetValue(FocusElementProperty); } set { SetValue(FocusElementProperty, value); } } // Using a DependencyProperty as the backing store for FocusElement. public static readonly DependencyProperty FocusElementProperty = DependencyProperty.Register("FocusElement", typeof(FrameworkElement), typeof(FocusHighlightBehavior), new PropertyMetadata(null, (o,e) => { //this is the property changed event for the dependency property! (o as FocusHighlightBehavior).UpdateFocusElement(); })); private void UpdateFocusElement() { if (FocusElement != null) { FocusElement.GotFocus += FocusElement_GotFocus; FocusElement.LostFocus += FocusElement_LostFocus; } } private void FocusElement_LostFocus(object sender, RoutedEventArgs e) { AssociatedObject.Fill = Brushes.Gray; } private void FocusElement_GotFocus(object sender, RoutedEventArgs e) { AssociatedObject.Fill = Brushes.Orange; } }
Java
UTF-8
2,064
3.46875
3
[]
no_license
import java.util.Random; public class EmpWageComputation{ public static final int IS_EMP_FULL_TIME = 1; public static final int IS_EMP_PART_TIME = 2; public static final int EMP_RATE_PER_HOUR = 10; public static final int WORKING_DAYS_IN_MONTH = 20; public static final int MAXIMUM_WORK_HOURS = 100; public static int totalEmpHours = 0; public static int totalSalary = 0; public static int totalWorkingDays = 0; public static int empHours = 0; public static int dailyWage = 0; public static int getWorkingHours(int empCheck){ switch (empCheck){ case IS_EMP_FULL_TIME: empHours = 8; break ; case IS_EMP_PART_TIME: empHours = 4 ; break ; default: empHours=0 ; } return empHours; } public static int getCalculationDailyWage(int empHours){ dailyWage = empHours * EMP_RATE_PER_HOUR; return dailyWage; } public static void getMonthlyWage(){ int empDailyWage[] = new int[21]; while (totalEmpHours <= MAXIMUM_WORK_HOURS && totalWorkingDays < WORKING_DAYS_IN_MONTH){ Random random = new Random(); int empCheck = random.nextInt()%3; empHours = getWorkingHours(empCheck); totalEmpHours = totalEmpHours + empHours; totalWorkingDays++; empDailyWage[totalWorkingDays]=getCalculationDailyWage(empHours); } System.out.println("Day No. DailyWage TotalWage"); for (int i = 0; i < empDailyWage.length; i++) { int x= empDailyWage[i]; totalSalary +=x; System.out.println( "day : "+ i + " " + x + " " + totalSalary ); } System.out.println("Total salary of employee= " + totalSalary); } public static void main(String args[]){ System.out.println("Welcome to Employee Wage Problem"); EmpWageComputation employee= new EmpWageComputation(); employee.getMonthlyWage(); } }
Ruby
UTF-8
2,751
2.859375
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
require 'active_support/all' require 'yaml' require 'csv' require 'securerandom' class Generator def initialize(question_file, base_path, cache_bust = 0) @questions = question_file['questions'] @base_path = base_path @cache_bust = cache_bust.to_i generate_possible_values generate_paths write_paths end private attr_reader :questions, :base_path, :cache_bust attr_accessor :possible_values, :chosen_values def chosen_values @chosen_values ||= [] end def possible_values @possible_values ||= [] end def generate_possible_values questions.each_with_index do |question, index| values = question['options'].flat_map { |op| op['value'] } case question['question_type'] when 'single' possible_values.insert(index, values) when 'multiple' all_combinations = (0..values.count).flat_map{|size| values.combination(size).to_a } possible_values.insert(index, all_combinations) end end end def write_paths paths = %w[questions results email-signup] headers = %w[base_path hits] CSV.open("#{base_path.delete('\/')}_paths.csv", "wb", write_headers: true, headers: headers) do |csv| chosen_values.each do |vs| paths.each do |path| query_string = "#{base_path}/#{path}?#{vs.to_query('c')}" csv << [query_string, 1] end query_string = "#{base_path}/questions?#{vs.to_query('c')}" questions.length.times do |page_number| csv << ["#{query_string}&page=#{page_number + 1}", 1] end cache_bust.times do csv << ["#{query_string}&cache_bust=#{SecureRandom.uuid}", 1] end end end end def generate_paths all_permutations = [] possible_values[0].map do |first_value| all_permutations << [first_value] possible_values[1].map do |second_value| question = questions[1] if !question['depends_on'] || first_value == question['depends_on'] all_permutations << [second_value] all_permutations << [first_value, second_value] end possible_values[2].map do |third_value| all_permutations << [third_value] all_permutations << [first_value, third_value] all_permutations << [second_value, third_value] all_permutations << [first_value, second_value, third_value] end end end all_permutations.each_with_object({choice: []}) do |perm, chosen| chosen[:choice] = [perm].flatten chosen_values << chosen[:choice] end end end file_path = ARGV[0] base_path = ARGV[1] cache_bust = ARGV[2] loaded_file = YAML.load_file(file_path) Generator.new(loaded_file, base_path, cache_bust)
Java
UTF-8
12,625
1.820313
2
[]
no_license
package com.sendish.api.web.controller.api.v1; import java.net.URI; import java.util.List; import javax.validation.Valid; import com.sendish.api.dto.*; import com.sendish.api.service.impl.PhotoServiceImpl; import com.sendish.api.web.controller.validator.ReportPhotoReplyValidator; import com.sendish.repository.model.jpa.Photo; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.sendish.api.security.userdetails.AuthUser; import com.sendish.api.service.impl.PhotoReplyServiceImpl; import com.sendish.api.store.FileStore; import com.sendish.api.store.exception.ResourceNotFoundException; import com.sendish.api.web.controller.validator.NewPhotoReplyMessageValidator; import com.sendish.api.web.controller.validator.PhotoReplyFileUploadValidator; import com.sendish.repository.model.jpa.ChatThread; import com.sendish.repository.model.jpa.PhotoReply; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import org.springframework.web.util.UriComponentsBuilder; @RestController @RequestMapping("/api/v1.0/photo-replies") @Api(value = "photo-replies", description = "Reply with photo to received photo") public class PhotoReplyController { @Autowired private PhotoReplyServiceImpl photoReplyService; @Autowired private FileStore fileStore; @Autowired private PhotoServiceImpl photoService; @Autowired private PhotoReplyFileUploadValidator photoReplyFileUploadValidator; @Autowired private NewPhotoReplyMessageValidator newPhotoReplyMessageValidator; @Autowired private ReportPhotoReplyValidator reportPhotoReplyValidator; @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "Reply with photo", notes = "If all si OK and you get code 201 check Location header to point you to the newly created photo comment") @ApiResponses({ @ApiResponse(code = 200, message = "NOT USED! 201 will be returned"), @ApiResponse(code = 201, message = "Photo reply created") }) public ResponseEntity<Void> postNewPhotoReply(@ModelAttribute @Valid PhotoReplyFileUpload photoReplyFileUpload, BindingResult result, MultipartFile image, AuthUser user) throws BindException { // FIXME: MultipartFile image is also specified here because of swagger! photoReplyFileUpload.setUserId(user.getUserId()); photoReplyFileUploadValidator.validate(photoReplyFileUpload, result); if (result.hasErrors()) { throw new BindException(result); } PhotoReply photoReply = photoReplyService.processNew(photoReplyFileUpload); final URI location = ServletUriComponentsBuilder .fromCurrentServletMapping().path("/api/v1.0/photo-replies/{photoReplyId}").build() .expand(photoReply.getId()).toUri(); HttpHeaders headers = new HttpHeaders(); headers.setLocation(location); return new ResponseEntity<>(headers, HttpStatus.CREATED); } @RequestMapping(method = RequestMethod.GET) @ApiOperation(value = "List of all photo replies", notes = "All received and sent photo replies orderd by last activity") @ApiResponses({ @ApiResponse(code = 200, message = "OK") }) public List<PhotoReplyDto> findAll(@RequestParam(defaultValue = "0") Integer page, AuthUser user) { return photoReplyService.findAll(user.getUserId(), page); } @RequestMapping(value = "/photo/{photoId}/photo-replies", method = RequestMethod.GET) @ApiOperation(value = "List of all photo replies on a photo", notes = "Only photo owner can see all the replies") @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Photo not found") }) public ResponseEntity<List<PhotoReplyDto>> findByPhoto(@PathVariable Long photoId, @RequestParam(defaultValue = "0") Integer page, AuthUser user) { Photo photo = photoService.findByIdAndUserId(photoId, user.getUserId()); if (photo == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else { List<PhotoReplyDto> photoReplies = photoReplyService.findByPhotoId(photoId, user.getUserId(), page); return new ResponseEntity<>(photoReplies, HttpStatus.OK); } } @RequestMapping(value = "/{photoReplyId}", method = RequestMethod.GET) @ApiOperation(value = "Chat details with messages for photo reply") @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Photo reply not found") }) public ResponseEntity<ChatThreadDetailsDto> getChatThreadForPhotoReply(@PathVariable Long photoReplyId, AuthUser user) { ChatThreadDetailsDto chatThread = photoReplyService.findChatThreadWithFirstPageByPhotoReplyIdAndUserId(photoReplyId, user.getUserId()); if (chatThread == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else { chatThread.getMessages().stream().forEach(this::addPhotoUrl); return new ResponseEntity<>(chatThread, HttpStatus.OK); } } @RequestMapping(value = "/{photoReplyId}", method = RequestMethod.DELETE) @ApiOperation(value = "Delete photo reply") @ApiResponses({ @ApiResponse(code = 204, message = "Deleted"), @ApiResponse(code = 404, message = "Photo reply not found") }) public ResponseEntity<ChatThreadDetailsDto> delete(@PathVariable Long photoReplyId, AuthUser user) { if (photoReplyService.removeUserFromChatThread(photoReplyId, user.getUserId())) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @RequestMapping(value = "/{photoReplyId}/messages", method = RequestMethod.GET) @ApiOperation(value = "Get messages for photo reply", notes = "NOTE: In photo reply details you already get the first page!") @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Photo reply not found") }) public ResponseEntity<List<ChatMessageDto>> getChatMessagesForPhotoReply(@PathVariable Long photoReplyId, @RequestParam(defaultValue = "0") Integer page, AuthUser user) { ChatThread chatThread = photoReplyService.findThreadByPhotoReplyIdAndUserId(photoReplyId, user.getUserId()); if (chatThread == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else { List<ChatMessageDto> msgs = photoReplyService.findChatMessagesByChatThreadId(chatThread.getId(), user.getUserId(), page); msgs.stream().forEach(this::addPhotoUrl); return new ResponseEntity<>(msgs, HttpStatus.OK); } } @RequestMapping(value = "/new-messages", method = RequestMethod.POST) @ApiOperation(value = "Post new message") @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 400, message = "Validation errors") }) public ResponseEntity<ChatMessageDto> postNewMessage(@RequestBody @Valid NewPhotoReplyMessageDto newMessage, BindingResult result, AuthUser user) throws BindException { newMessage.setUserId(user.getUserId()); newPhotoReplyMessageValidator.validate(newMessage, result); if (result.hasErrors()) { throw new BindException(result); } ChatMessageDto chatMessageDto = photoReplyService.newMessage(newMessage); addPhotoUrl(chatMessageDto); return new ResponseEntity<>(chatMessageDto, HttpStatus.OK); } @RequestMapping(value = "/report", method = RequestMethod.POST) @ApiOperation(value = "Report photo reply") @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 400, message = "Validation errors") }) public ResponseEntity<Void> report(@RequestBody @Valid ReportPhotoReplyDto reportDto, BindingResult result, AuthUser user) throws BindException { reportDto.setUserId(user.getUserId()); reportPhotoReplyValidator.validate(reportDto, result); if (result.hasErrors()) { throw new BindException(result); } photoReplyService.report(reportDto); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @RequestMapping(value = "/{photoReplyUUID}/view", method = RequestMethod.GET) @ApiOperation(value = "View photo reply") @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 403, message = "Not reply or photo owner"), @ApiResponse(code = 404, message = "Not found") }) public ResponseEntity<InputStreamResource> viewPhotoReply(@PathVariable String photoReplyUUID, WebRequest webRequest, AuthUser user) { PhotoReply photoReply = photoReplyService.findByUuid(photoReplyUUID); if (photoReply == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else if (photoReply.getUser().getId().equals(user.getUserId()) || photoReply.getPhoto().getUser().getId().equals(user.getUserId())) { return viewPhotoReply(webRequest, photoReply.getCreatedDate(), photoReply.getContentType(), photoReply.getSize(), photoReply.getStorageId()); } else { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } } @RequestMapping(value = "/{photoReplyUUID}/view/{sizeKey}", method = RequestMethod.GET) @ApiOperation(value = "View photo reply in different size") @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 403, message = "Not reply or photo owner"), @ApiResponse(code = 404, message = "Not found") }) public ResponseEntity<InputStreamResource> viewPhotoReply(@PathVariable String photoReplyUUID, @PathVariable String sizeKey, WebRequest webRequest, AuthUser user) { // TODO: If needed return resized photo and call different service method return viewPhotoReply(photoReplyUUID, webRequest, user); } private ResponseEntity<InputStreamResource> viewPhotoReply(WebRequest webRequest, DateTime createdDate, String contentType, Long size, String storageId) { if (webRequest.checkNotModified(createdDate.getMillis())) { return new ResponseEntity<>(HttpStatus.NOT_MODIFIED); } try { InputStreamResource isr = new InputStreamResource(fileStore.getAsInputStream(storageId)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.valueOf(contentType)); headers.setContentLength(size); return new ResponseEntity<>(isr, headers, HttpStatus.OK); } catch (ResourceNotFoundException e) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } private void addPhotoUrl(ChatMessageDto chatMessageDto) { if (chatMessageDto.getType().equals(ChatMessageDto.ChatMessageDtoType.IMG)) { ChatMessageImageDto img = chatMessageDto.getImage(); switch ( img.getType() ) { case IMAGE_PHOTO: img.setRelativePath(UriComponentsBuilder.fromPath("/api/v1.0/photos/{photoUUID}/view") .buildAndExpand(img.getUuid()) .toUriString()); break; case IMAGE_PHOTO_REPLY: img.setRelativePath(UriComponentsBuilder.fromPath("/api/v1.0/photo-replies/{photoReplyUUID}/view") .buildAndExpand(img.getUuid()) .toUriString()); break; default: break; } } } }
C#
UTF-8
685
2.640625
3
[]
no_license
using System.Collections.Generic; namespace VendingMachine { public class PaymentEvent : IPaymentSubscriber, IPaymentNotifier { private List<IPaymentListener> paymentListeners = new List<IPaymentListener>(); public void Subscribe(IPaymentListener listeners) { paymentListeners.Add(listeners); } public void Unsubscribe(IPaymentListener listeners) { paymentListeners.Remove(listeners); } public void Notify(int Id) { foreach (var Listener in paymentListeners) { Listener.Update(Id); } } } }
C
UTF-8
716
2.84375
3
[]
no_license
/* * db.h */ #include <stdbool.h> //Structure for a log item typedef struct { int day; char message[140]; //tweet length } Log; //Structure for a single task typedef struct { char name[32]; int streak; //days consecutively completed bool active; int logc; //total amount of log items Log *logs; } Task; void complete(char *name, char *message); void uncomplete(char *name); void start(char *name); void stop(char *name); void addTask(char *name); void removeTask(char *name); //read and write tasks int writeTask(Task *t); Task *readTask(char *n); //clean it up void freeTask(Task *t); //Task overview void printTask(Task *t); //Most recent n log items (0 for all) void printLog(Task *t, int n);
Java
UTF-8
3,405
2.5625
3
[]
no_license
/* * Copyright (c) 2017 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.stdext.credential.pass; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Map; import java.util.Random; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.generators.SCrypt; import org.bouncycastle.util.Arrays; /** * Low level password handling. * Allows for initial obfuscation of a given password (PasswordInfo is generated, * ready to be stored in DB) and for checking a given password against the one loaded. * * @author K. Benedyczak */ public class PasswordEngine { private static final int SALT_LENGTH = 32; private Random random = new SecureRandom(); public PasswordInfo prepareForStore(PasswordCredential credentialSettings, String password) { byte[] salt = genSalt(); ScryptParams scryptParams = credentialSettings.getScryptParams(); byte[] hash = scrypt(password, salt, scryptParams); return new PasswordInfo(PasswordHashMethod.SCRYPT, hash, salt, scryptParams.toMap(), System.currentTimeMillis()); } public boolean verify(PasswordInfo stored, String password) { PasswordHashMethod method = stored.getMethod(); switch (method) { case SCRYPT: return verifySCrypt(stored, password); case SHA256: return verifySHA2(stored, password); } throw new IllegalStateException("Shouldn't happen: " + "unsupported password hash method: " + method); } private boolean verifySHA2(PasswordInfo stored, String password) { Map<String, Object> methodParams = stored.getMethodParams(); int rehashNumber = (Integer)methodParams.getOrDefault("rehashNumber", 1); String salt = stored.getSalt() == null ? "" : new String(stored.getSalt(), StandardCharsets.UTF_8); byte[] interim = (salt+password).getBytes(StandardCharsets.UTF_8); SHA256Digest digest = new SHA256Digest(); int size = digest.getDigestSize(); for (int i=0; i<rehashNumber; i++) interim = sha2hash(interim, size, digest); return Arrays.areEqual(interim, stored.getHash()); } private boolean verifySCrypt(PasswordInfo stored, String password) { ScryptParams params = new ScryptParams(stored.getMethodParams()); byte[] testedHash = scrypt(password, stored.getSalt(), params); return Arrays.areEqual(testedHash, stored.getHash()); } public boolean checkParamsUpToDate(PasswordCredential credentialSettings, PasswordInfo stored) { if (stored.getMethod() != PasswordHashMethod.SCRYPT) return credentialSettings.isAllowLegacy(); ScryptParams params = new ScryptParams(stored.getMethodParams()); return credentialSettings.getScryptParams().equals(params); } private byte[] scrypt(String password, byte[] salt, ScryptParams params) { return SCrypt.generate(password.getBytes(StandardCharsets.UTF_8), salt, 1 << params.getWorkFactor(), params.getBlockSize(), params.getParallelization(), params.getLength()); //Memory use = 128 bytes × cost × blockSize } private byte[] genSalt() { byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); return salt; } private byte[] sha2hash(byte[] current, int size, SHA256Digest digest) { digest.update(current, 0, current.length); byte[] hashed = new byte[size]; digest.doFinal(hashed, 0); return hashed; } }
C++
UTF-8
829
2.546875
3
[]
no_license
#include"Header.h" SinhVien danhSachSV[1000]; int soSv=0; void docFile() { fstream file; file.open("data2.bin", ios::binary | ios::in); if (!file.is_open()) { cout << "ERROR!!!!!"; } else { file.seekg(soSv * sizeof(SinhVien), ios::beg); while (!file.eof()) { file.read(reinterpret_cast<char*>(&danhSachSV[soSv]), sizeof(SinhVien)); if (file.eof()) { break; } soSv++; } danhSachSV; cout << "Thanh cong\n"; } file.close(); } void luuSv(SinhVien sv) { fstream file; file.open("data2.bin", ios::binary | ios::out | ios::app); if (!file.is_open()) { cout << "ERROR!!!!!"; } else { file.write(reinterpret_cast<char*>(&sv), sizeof(SinhVien)); cout << "Thanh Cong\n"; cout << sv.hoVaTen << endl; } file.close(); }
Java
UTF-8
2,829
2.0625
2
[]
no_license
package com.eol; import org.datanucleus.store.types.wrappers.ArrayList; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class MaxComputeLocal { private static final String DRIVER_NAME ="com.aliyun.odps.jdbc.OdpsDriver"; private static ResultSet rs=null; public static void main(String[] args) throws SQLException, ParseException { try { Class.forName(DRIVER_NAME); } catch (ClassNotFoundException e) { e.printStackTrace(); System.exit(1); } Connection conn = DriverManager.getConnection( "jdbc:odps:http://service.cn-beijing.maxcompute.aliyun.com/api?project=CHENGZI", "LTAI4Fx2ojCF41FVAr8JtsoA", "LT0uMQSeP0gGIAACme07XesSksLd4d"); Statement stmt = conn.createStatement(); stmt.execute("drop table if exists railway_od"); stmt.execute("create table if not exists railway_in " + "as SELECT id,riqi,stations,recivetime,beforbanlance " + "FROM railway_10 WHERE trade='进站' "); stmt.execute("create table if not exists railway_out " + "as SELECT id,stations,recivetime,beforbanlance " + "FROM railway_10 WHERE trade='出站' "); stmt.execute("create table if not exists railway_od " + "as SELECT railway_in.id as id1,railway_in.stations as station1," + "railway_in.recivetime as recivetime1," + "railway_out.stations as station2,railway_out.recivetime as recivetime2 " + "From railway_in join railway_out on railway_in.id=railway_out.id " + "AND railway_in.beforbanlance=railway_out.beforbanlance and railway_in.recivetime< railway_out.recivetime "); //stmt.execute("DROP TABLE IF EXISTS " + "railway_in"); //stmt.execute("DROP TABLE IF EXISTS " + "railway_out"); rs=stmt.executeQuery("select * from railway_od limit 5"); ResultSetMetaData rsm=rs.getMetaData(); long in_time = rsm.getColumnType(4); long out_ime=in_time+00000000040000; SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); Date date=new Date(in_time); Date date1=new Date(out_ime); String intime=sdf.format(date1); String outime=sdf.format(date); String testOD="create table if not exists od_10" + " as select id1,kind1,station1,recivetime1,station2,recivetime2 from railway_od " + "where recivetime2 between unix_timestamp('"+intime+"','yyyy-MM-dd HH:mm:ss') and" + " unix_timestamp('"+outime+"','yyyy-MM-dd HH:mm:ss')"; stmt.execute(testOD); } }
Java
UTF-8
490
2.21875
2
[]
no_license
package com.samAndDan.modTest.utils; import net.minecraft.util.text.translation.I18n; public class StringUtils { public static String localize(String string) { return I18n.translateToLocal(string); } public static boolean canLocalize(String string) { return I18n.canTranslate(string); } public static String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } }
Python
UTF-8
2,978
2.71875
3
[]
no_license
""" POLL APP This module provides an interface into the poll and answer forms. Classes: PollAnswerForm Functions: n/a Created on 26 Mar 2013 @author: michael """ from django import forms from django.contrib import messages from django.conf import settings class PollAnswerForm(forms.Form): """Form for handling Poll answers.""" multiple_answers = forms.BooleanField( widget=forms.HiddenInput, required=False ) def __init__(self, *args, **kwargs): """Add poll to initialised variables.""" self.poll = kwargs.pop('poll', None) self.multiple_answers = kwargs.pop('multiple_answers', False) self.randomize_answers = kwargs.pop('randomize_answers', False) super(PollAnswerForm, self).__init__(*args, **kwargs) if self.poll is not None: queryset = self.poll.answers.permitted() if self.randomize_answers: queryset = queryset.order_by('?') if self.poll.multiple_choice: self.fields['answers'] = forms.ModelMultipleChoiceField( queryset=queryset, widget=forms.CheckboxSelectMultiple ) else: self.fields['answers'] = forms.ModelChoiceField( queryset=queryset, widget=forms.RadioSelect, empty_label=None ) self.fields['answers'].widget.attrs.update({'class': 'required'}) if self.multiple_answers: self.fields['multiple_answers'].initial = self.multiple_answers def increment_vote_count(self, answer): """Increment a vote on a poll.""" answer.vote_count += 1 answer.save() def save(self, request, cookie_name, pk): """ Handle saving of a vote on a poll. Ensure the user hasn't previously voted on the same poll. """ if request.user.is_authenticated(): user = request.user else: user = None multiple_answers_allowed = getattr( settings, 'ALLOW_CERTAIN_POLL_MULTIPLE_ANSWERS', False ) if multiple_answers_allowed and self.cleaned_data['multiple_answers']: poll_voted = False elif user is None: poll_voted = request.COOKIES.get(cookie_name, False) else: poll_voted = user.polls_answered.filter(pk=pk).exists() if poll_voted: messages.error(request, 'You have already voted in this poll.') else: answers = self.cleaned_data['answers'] if isinstance(answers, (list, tuple)): for answer in answers: self.increment_vote_count(answer) else: self.increment_vote_count(answers) if user is not None: self.poll.users_answered.add(user) messages.success(request, 'You have voted.')
C#
UTF-8
5,938
2.6875
3
[]
no_license
using System.Text; using Api.BusinessLogicLayer.Requests; using NUnit.Framework; namespace Api.BusinessLogicLayer.UnitTests.Requests { [TestFixture] public class RegisterRequestTests { private const string ValidEmail = "abc@gmail.com"; private const string ValidPassword = "Qwer111!"; private const string ValidName = "Michael Moeller"; private const string ValidPhoneNumber = "28515359"; //Source for most test cases: https://blogs.msdn.microsoft.com/testing123/2009/02/06/email-address-test-cases/ [TestCase("a.gmail.com", 1)] [TestCase("plaintext", 1)] [TestCase("#@%^%#$@#$@#.com", 1)] [TestCase("Michael Moeller <email@domain.com>", 1)] [TestCase("email.domain.com", 1)] [TestCase("email@domain@domain.com", 1)] [TestCase(".email@domain.com", 1)] [TestCase("email.@domain.com", 1)] [TestCase("email..email@domain.com", 1)] [TestCase("あいうえお@domain.com", 1)] [TestCase("email@domain.com (Joe Smith)", 1)] [TestCase("email@domain", 1)] [TestCase("email@-domain.com", 1)] [TestCase("email@domain..com", 1)] [TestCase("", 1)] [TestCase("email@domain.com", 0)] [TestCase("firstname.lastname@domain.com", 0)] [TestCase("email@subdomain.domain.com", 0)] [TestCase("firstname+lastname@domain.com", 0)] [TestCase("email@123.123.123.123", 0)] [TestCase("email@[123.123.123.123]", 0)] [TestCase("\"email\"@domain.com", 0)] [TestCase("1234567890@domain.com", 0)] [TestCase("email@domain-one.com", 0)] [TestCase("email@domain.name", 0)] [TestCase("email@domain.co.jp", 0)] [TestCase("firstname-lastname@domain.com", 0)] public void Email_WhenSet_ValidatesInput(string email, int numberOfErrors) { var request = new RegisterRequest { Email = email, Password = ValidPassword, PasswordRepeated = ValidPassword, Name = ValidName, PhoneNumber = ValidPhoneNumber }; Assert.That(ValidateModelHelper.ValidateModel(request).Count, Is.EqualTo(numberOfErrors)); } //Remember: The data annotations set on the two password attributes is only checking if the passwords are present and equal //Identity framework is used to define requirements for the actual password. This is not tested. [TestCase("", "", 2)] [TestCase("", "a", 2)] //two errors because the "compare" data annotation is only put on the repeated password [TestCase("a", "", 1)] [TestCase("a", "a", 0)] [TestCase("abc", "qwe", 1)] public void Password_WhenSet_ValidatesThatBothPasswordsIsPresentAndThatTheyAreEqual(string first, string second, int numberOfErrors) { var request = new RegisterRequest { Email = ValidEmail, Password = first, PasswordRepeated = second, Name = ValidName, PhoneNumber = ValidPhoneNumber }; Assert.That(ValidateModelHelper.ValidateModel(request).Count, Is.EqualTo(numberOfErrors)); } [TestCase(0, 1)] [TestCase(1, 1)] [TestCase(2, 1)] [TestCase(3, 0)] [TestCase(4, 0)] [TestCase(254, 0)] [TestCase(255, 0)] [TestCase(256, 1)] [TestCase(1000, 1)] public void Name_WhenSet_ValidatesLengthIsMin3Max255(int numberOfCharsInName, int numberOfErrors) { var name = GenerateString(numberOfCharsInName); var request = new RegisterRequest { Email = ValidEmail, Password = ValidPassword, PasswordRepeated = ValidPassword, Name = name.ToString(), PhoneNumber = ValidPhoneNumber }; Assert.That(ValidateModelHelper.ValidateModel(request).Count, Is.EqualTo(numberOfErrors)); } [TestCase(" ", 1)] [TestCase(null, 1)] public void Name_WhenSetToWhiteSpaceOrNull_ValidationFails(string name, int numberOfErrors) { var request = new RegisterRequest { Email = ValidEmail, Password = ValidPassword, PasswordRepeated = ValidPassword, Name = name, PhoneNumber = ValidPhoneNumber }; Assert.That(ValidateModelHelper.ValidateModel(request).Count, Is.EqualTo(numberOfErrors)); } [TestCase("01234567", 1)] [TestCase("00000000", 1)] [TestCase("", 1)] [TestCase("1111111", 1)] [TestCase("111111111", 1)] [TestCase("12345678", 0)] [TestCase("23242526", 0)] [TestCase("99999999", 0)] [TestCase("19181716", 0)] [TestCase("-12345678", 1)] [TestCase("asdfasdf", 1)] [TestCase("a", 1)] [TestCase("a1a2a3a4", 1)] public void PhoneNumber_WhenSet_ValidatesInput(string phoneNumber, int numberOfErrors) { var request = new RegisterRequest { Email = ValidEmail, Password = ValidPassword, PasswordRepeated = ValidPassword, Name = ValidName, PhoneNumber = phoneNumber }; Assert.That(ValidateModelHelper.ValidateModel(request).Count, Is.EqualTo(numberOfErrors)); } /// <summary> /// Generates a string with the specified number of characters. /// </summary> /// <param name="numberOfCharsInString">The number of characters in the returned string</param> /// <returns>A string with the specified numbers of characters.</returns> private string GenerateString(int numberOfCharsInString) { var str = new StringBuilder(); for (int i = 0; i < numberOfCharsInString; i++) { str.Append("A"); } return str.ToString(); } } }
Go
UTF-8
303
3.1875
3
[]
no_license
package golang import "net/http" // RoundTripperFunc converts a function into a Transport. type RoundTripperFunc func(*http.Request) (*http.Response, error) // RoundTrip calls the underlying function func (rt RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { return rt(req) }
PHP
UTF-8
7,762
2.53125
3
[ "Apache-2.0", "MIT" ]
permissive
<?php namespace Aws\Test\Arn\S3; use Aws\Arn\S3\AccessPointArn; use Aws\Arn\Exception\InvalidArnException; use Aws\Arn\S3\OutpostsAccessPointArn; use Aws\Arn\S3\OutpostsBucketArn; use PHPUnit\Framework\TestCase; /** * @covers \Aws\Arn\S3\OutpostsBucketArn */ class OutpostsBucketArnTest extends TestCase { /** * @dataProvider parsedArnProvider * * @param $string * @param $expected * @param $expectedString */ public function testParsesArnString($string, $expected, $expectedString) { $arn = new OutpostsBucketArn($string); $this->assertEquals($expected, $arn->toArray()); $this->assertEquals($expected['arn'], $arn->getPrefix()); $this->assertEquals($expected['partition'], $arn->getPartition()); $this->assertEquals($expected['service'], $arn->getService()); $this->assertEquals($expected['region'], $arn->getRegion()); $this->assertEquals($expected['account_id'], $arn->getAccountId()); $this->assertEquals($expected['resource'], $arn->getResource()); $this->assertEquals($expected['resource_id'], $arn->getResourceId()); $this->assertEquals($expected['resource_type'], $arn->getResourceType()); $this->assertEquals($expected['outpost_id'], $arn->getOutpostId()); $this->assertEquals($expected['bucket_name'], $arn->getBucketName()); $this->assertEquals($expectedString, (string) $arn); } public function parsedArnProvider() { return [ // Colon delimiters [ 'arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket', [ 'arn' => 'arn', 'partition' => 'aws', 'service' => 's3-outposts', 'region' => 'us-west-2', 'account_id' => '123456789012', 'resource_type' => 'outpost', 'resource_id' => 'op-01234567890123456:bucket:mybucket', 'resource' => 'outpost:op-01234567890123456:bucket:mybucket', 'outpost_id' => 'op-01234567890123456', 'bucket_name' => 'mybucket', 'bucket_label' => 'bucket' ], 'arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket', ], // Slash delimiters [ 'arn:aws:s3-outposts:us-west-2:123456789012:outpost/op-01234567890123456/bucket/mybucket', [ 'arn' => 'arn', 'partition' => 'aws', 'service' => 's3-outposts', 'region' => 'us-west-2', 'account_id' => '123456789012', 'resource_type' => 'outpost', 'resource_id' => 'op-01234567890123456/bucket/mybucket', 'resource' => 'outpost/op-01234567890123456/bucket/mybucket', 'outpost_id' => 'op-01234567890123456', 'bucket_name' => 'mybucket', 'bucket_label' => 'bucket' ], 'arn:aws:s3-outposts:us-west-2:123456789012:outpost/op-01234567890123456/bucket/mybucket', ], // Mixed colon & slash delimiters [ 'arn:aws:s3-outposts:us-west-2:123456789012:outpost/op-01234567890123456:bucket/mybucket', [ 'arn' => 'arn', 'partition' => 'aws', 'service' => 's3-outposts', 'region' => 'us-west-2', 'account_id' => '123456789012', 'resource_type' => 'outpost', 'resource_id' => 'op-01234567890123456:bucket/mybucket', 'resource' => 'outpost/op-01234567890123456:bucket/mybucket', 'outpost_id' => 'op-01234567890123456', 'bucket_name' => 'mybucket', 'bucket_label' => 'bucket' ], 'arn:aws:s3-outposts:us-west-2:123456789012:outpost/op-01234567890123456:bucket/mybucket', ], // Minimum inputs [ 'arn:aws:s3-outposts:us-west-2:1:outpost:2:bucket:3', [ 'arn' => 'arn', 'partition' => 'aws', 'service' => 's3-outposts', 'region' => 'us-west-2', 'account_id' => '1', 'resource_type' => 'outpost', 'resource_id' => '2:bucket:3', 'resource' => 'outpost:2:bucket:3', 'outpost_id' => '2', 'bucket_name' => '3', 'bucket_label' => 'bucket' ], 'arn:aws:s3-outposts:us-west-2:1:outpost:2:bucket:3', ], ]; } /** * @dataProvider badArnProvider * * @param $string * @param \Exception $expected */ public function testThrowsForBadArn($string, \Exception $expected) { try { $arn = new OutpostsBucketArn($string); $this->fail('This was expected to fail with: ' . $expected->getMessage()); } catch (\Exception $e) { $this->assertTrue($e instanceof $expected); $this->assertSame( $expected->getMessage(), $e->getMessage() ); } } public function badArnProvider() { return [ [ 'arn:aws:s3:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket', new InvalidArnException("The 3rd component of an S3 Outposts" . " bucket ARN represents the service and must be 's3-outposts'.") ], [ 'arn:aws:s3-outposts::123456789012:outpost:op-01234567890123456:bucket:mybucket', new InvalidArnException("The 4th component of a S3 Outposts" . " bucket ARN represents the region and must not be empty.") ], [ 'arn:aws:s3-outposts:us-west-2:%$#:outpost:op-01234567890123456:bucket:mybucket', new InvalidArnException("The 5th component of a S3 Outposts" . " bucket ARN is required, represents the account ID, and" . " must be a valid host label.") ], [ 'arn:aws:s3-outposts:us-west-2:123456789012:someresource:op-01234567890123456:bucket:mybucket', new InvalidArnException("The 6th component of an S3 Outposts" . " bucket ARN represents the resource type and must be" . " 'outpost'.") ], [ 'arn:aws:s3-outposts:us-west-2:123456789012:outpost:!!!:bucket:mybucket', new InvalidArnException("The 7th component of an S3 Outposts" . " bucket ARN is required, represents the outpost ID, and" . " must be a valid host label.") ], [ 'arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:foo:mybucket', new InvalidArnException("The 8th component of an S3 Outposts" . " bucket ARN must be 'bucket'") ], [ 'arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:', new InvalidArnException("The 9th component of an S3 Outposts" . " bucket ARN represents the bucket name and must not be empty.") ], ]; } }
Java
UTF-8
4,158
2.046875
2
[]
no_license
package com.akul.chatzone; //Created by AkulSrivastava //May 2019 import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; //Created by AkulSrivastava //May 2019 import com.bumptech.glide.Glide; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class FindFriendsAdapter extends RecyclerView.Adapter<FindFriendsAdapter.FFviewholder> { Context context; List<UserInfo> usersList; private ItemClickListener itemClickListener; public void setItemClickListener(ItemClickListener itemClickListener){ this.itemClickListener = itemClickListener; } public FindFriendsAdapter(Context context, List<UserInfo> usersList) { this.context = context; this.usersList = usersList; } @NonNull @Override public FFviewholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(context).inflate(R.layout.layout_user,viewGroup,false); FFviewholder holder = new FFviewholder(view); return holder; } @Override public void onBindViewHolder(@NonNull final FFviewholder fFviewholder, int i) { UserInfo user = usersList.get(i); String uid1 = usersList.get(i).getUid(); FirebaseDatabase mDatabase = FirebaseDatabase.getInstance(); DatabaseReference userReference = mDatabase.getReference("Users/"+uid1+"/"); userReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.child("seenstatus").exists()){ if(dataSnapshot.child("seenstatus").getValue().toString().equals("online")){ fFviewholder.seenstatus.setImageResource(R.drawable.online); } else { fFviewholder.seenstatus.setImageResource(0); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); fFviewholder.userfullname.setText(user.getFullname()); setItemClickListener(new ItemClickListener() { @Override public void onClick(View view, int position, Boolean isLongClick) { String uid = usersList.get(position).getUid(); Intent i = new Intent(context, FriendProfile.class); i.putExtra("uid",uid); context.startActivity(i); } }); Glide.with(context).load(user.getDisplayimage()).into(fFviewholder.userDP); } @Override public int getItemCount() { return usersList.size(); } public void filterList(ArrayList<UserInfo> filteredList) { usersList = filteredList; notifyDataSetChanged(); } class FFviewholder extends RecyclerView.ViewHolder{ ImageView userDP, seenstatus; TextView userfullname; public FFviewholder(@NonNull final View itemView) { super(itemView); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { itemClickListener.onClick(itemView, getAdapterPosition(), false); } }); seenstatus = itemView.findViewById(R.id.seenstatus); userDP = itemView.findViewById(R.id.ffuserdp); userfullname = itemView.findViewById(R.id.ffuserfullname); } } } //Created by AkulSrivastava //May 2019
PHP
UTF-8
4,416
2.515625
3
[]
no_license
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\Work; use Illuminate\Support\Facades\Storage; class WorkController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $works = Work::all(); return view('admin.works.works-index', compact('works')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.works.works-create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $request->validate([ 'author'=>'required', 'name'=>'required', 'date'=>'required', 'page'=>'integer', ], [ 'author.required' => 'Поле автор является обязательным!', 'name.required' => 'Поле название является обязательным!', 'image.image' => 'Поле изображение должно быть в формате jpeg, png, bmp, gif или svg!', 'page.integer' => 'Поле количество страниц должно быть числовым' ]); $path = $request->file('image')->store('works'); $work = new Work([ 'author' => $request->get('author'), 'name' => $request->get('name'), 'description' => $request->get('description'), 'house' => $request->get('house'), 'date' => $request->get('date'), 'page' => $request->get('page'), 'image' => $path, ]); $work->save(); return redirect('/admin/work')->with('success', 'Публикация сохранена!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $works = Work::find($id); return view('admin.works.works-edit', compact('works')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $request->validate([ 'author'=>'required', 'name'=>'required', 'date'=>'required', 'page'=>'integer', ], [ 'author.required' => 'Поле автор является обязательным!', 'name.required' => 'Поле название является обязательным!', 'image.image' => 'Поле изображение должно быть в формате jpeg, png, bmp, gif или svg!', 'page.integer' => 'Поле количество страниц должно быть числовым' ]); $work = Work::find($id); Storage::disk('public')->delete($work->image); $path = $request->file('image')->store('works'); $work->author = $request->get('author'); $work->name = $request->get('name'); $work->description = $request->get('description'); $work->house = $request->get('house'); $work->date = $request->get('date'); $work->page = $request->get('page'); $work->image = $path; $work->save(); return redirect('/admin/work')->with('success', 'Публикация обновлена!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $work = Work::find($id); $work->delete(); return redirect('/admin/work')->with('delete', 'Вы удалили публикацию!'); } }
Java
UTF-8
459
2.546875
3
[]
no_license
package de.coiaf.footballprediction.sharedkernal.domain.model.buildingblocks; /** * An instance representing a DDD entity building block * @param <T> the entity type */ public interface Entity<T extends Entity<T>> { /** * * @param otherEntity the entity to be compared * @return <code>true</code> if <code>otherEntity</code> is not null and has the same identity as this instance. */ boolean hasSameIdentity(T otherEntity); }
Python
UTF-8
2,204
2.78125
3
[]
no_license
import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms import torchvision from torch.utils.data import DataLoader from customDataset import CharlieDataset device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') in_channel = 3 num_classes = 10 learning_rate = 1e-3 batch_size = 32 num_epochs = 1 # data loading dataset = CharlieDataset(csv_file = 'customDataset.csv', root_dir = 'charlies', transform = transforms.ToTensor()) print('taille : ', len(dataset)) train_set, test_set = torch.utils.data.random_split(dataset, [2, 2]) train_loader = DataLoader(dataset = train_set, batch_size = batch_size, shuffle = True) test_loader = DataLoader(dataset = test_set, batch_size = batch_size, shuffle = True) # model model = torchvision.models.googlenet(pretrained=True) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=learning_rate) #training for epoch in range(num_epochs): losses=[] for batch_idx, (data, targets) in enumerate(train_loader): data = data.to(device=device) targets = targets.to(device=device) scores = model(data) loss = criterion(scores, targets) losses.append(loss.item()) optimizer.zero_grad() loss.backward() optimizer.step() #print(f'Cost at epoch {epoch} is {sum(losses).len(Losses)}') def check_accuracy(loader, model): num_correct = 0 num_samples = 0 model.eval() with torch.no_grad(): for x, y in loader: x = x.to(device=device) y = y.to(device=device) scores = model(x) _, predictions = scores.max(1) num_correct += (predictions == y).sum() num_samples += predictions.size(0) print(f'Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100}') model.train() print("checking accuracy on Training Set") check_accuracy(train_loader, model) print("Checking accuracy on test Set") check_accuracy(test_loader, model)
C
UTF-8
2,053
2.9375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <stdbool.h> #include <string.h> #include "analyse_input_stream.h" #include "file.h" int findInstancesInFile(char* path, char* instance); int main(int argc, char* argv[]) { ssize_t numberOfChars = 0; size_t size = 0; FILE* file = NULL; char* buffer = NULL;// getline variables char* path=NULL; char *StdinWords[MAX_STDIN_ARGUMENTS]; char* wantedInstance = NULL; int stdinWordsCount = 0, i = 0; Matchers matchers = {false, 0, false, false, false, false, false, false, false}; if (!IsStdin(argc)){// get ARGV path = argv[argc-1]; wantedInstance =argv[argc-2]; file = fopen(path, "r"); assert(file != NULL); numberOfChars = getline(&buffer, &size, file); } else{// get STDIN numberOfChars = analyzeStdin(&buffer, &size, StdinWords, &stdinWordsCount); file = fopen(StdinWords[stdinWordsCount-1], "r"); SetNecessaryMatchers(StdinWords, &matchers, stdinWordsCount); IsMatchInFile(StdinWords[0], &matchers, StdinWords[stdinWordsCount-1]); } //findInstancesInFile(path, wantedInstance); //for (i = 0; i<stdinWordsCount; i++) // TEST //printf("word %d: %s\n", i, StdinWords[i]); //printf("is_A: %d, A_value: %d, is_b: %d, is_c: %d, is_i: %d, is_n: %d, is_v: %d, is_x: %d, is_E: %d\n", matchers.is_A, matchers.A_value, matchers.is_b, matchers.is_c, matchers.is_i, matchers.is_n, matchers.is_v, matchers.is_x, matchers.is_E); // PRINT MATCHERS STRUCT free(buffer); return 0; } int findInstancesInFile(char* path, char* instance){ FILE* targetText = fopen(path, "r"); char* lineBuffer = NULL; size_t lineSize = 0; if (targetText == NULL) return -1; ssize_t numberOfChars = 0; while(numberOfChars!=-1){ numberOfChars=getline(&lineBuffer, &lineSize, targetText); if(strstr(lineBuffer, instance)!=NULL) printf("%s\n", lineBuffer); } return 0; }
Java
UTF-8
933
2.78125
3
[]
no_license
package com.hfm.internationalization; import java.util.Locale; import java.util.ResourceBundle; /** * @author hfming2016@163.com * @version 1.01 2020-09-01 10:57 * @Description 国际化类的使用 * @date 2020/9/1 */ public class ResourceBundleTest { public static void main(String[] args) { // 调用 ResourceBundle 静态方法 创建 ResourceBundle 对象 // 使用 ResourceBundle 类加载资源包 // 参数一:资源包的名称 默认直接指向类路径根目录 // 参数二:国家 Local ResourceBundle bundle = ResourceBundle.getBundle("message", Locale.UK); // 获取资源包中的数据 String username = bundle.getString("username"); String password = bundle.getString("password"); String login = bundle.getString("login"); System.out.println(username); System.out.println(password); System.out.println(login); } }
Markdown
UTF-8
931
2.640625
3
[]
no_license
## 7天无理由退款 如果您购买的云开发资源包未被使用,可在购买7天内申请退款,超出7天或已使用过的资源包(不论已用多少)不支持退款。 ## 退款规则 - 云开发资源包未被使用,可在购买7天内申请退款。 - 一经使用,概不退还。 - 如出现疑似异常或恶意退款,腾讯云有权拒绝您的退款申请。 - 符合7天无理由退款场景的订单,退款金额为购买时花费的全部消耗金额,包括现金账户金额、收益转入账户金额以及赠送账户金额。 >! > - 抵扣或代金券不予以退还。 > - 退还金额将全部原路退回到您的腾讯云账户。 ## 退款流程 进入 [云开发控制台](https://console.cloud.tencent.com/tcb/env/resource),在需要操作的满足条件的资源包处单击**申请退款**即可。 ![](https://main.qcloudimg.com/raw/7d4a723ab17c6caa720b6b6927acc092.png)
C#
UTF-8
2,534
2.53125
3
[ "MIT" ]
permissive
using System; using System.Net; using System.Net.Http; using System.Security; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using TheWheel.ETL.Contracts; using TheWheel.ETL.Providers; namespace TheWheel.ETL.CyberArk { public class Credentials { private readonly Uri endpoint; private readonly string applicationId; public Credentials(Uri endpoint, string applicationId) { this.endpoint = endpoint; this.applicationId = applicationId; } public Credentials(string endpoint, string applicationId) : this(new Uri(endpoint), applicationId) { } public async Task<ICredentials> Use(string userName, string safe, CancellationToken token = default(CancellationToken)) { var provider = await Json.From<Http>(endpoint.ToString(), token, new System.Collections.Generic.KeyValuePair<string, object>("safe", safe), new System.Collections.Generic.KeyValuePair<string, object>("appId", applicationId), new System.Collections.Generic.KeyValuePair<string, object>("UserName", userName)); await provider.QueryAsync(new TreeOptions().AddMatch( "json:///", "Content/text()", "UserName/text()" ), System.Threading.CancellationToken.None); var reader = provider.ExecuteReader(); return new NetworkCredential(reader.GetString(reader.GetOrdinal("json:///UserName/text()")), reader.GetString(reader.GetOrdinal("json:///Content/text()"))); } public async Task<ICredentials> Use(string userName, CancellationToken token) { var provider = await Json.From<Http>(endpoint.ToString(), token, new System.Collections.Generic.KeyValuePair<string, object>("appId", applicationId), new System.Collections.Generic.KeyValuePair<string, object>("UserName", userName)); await provider.QueryAsync(new TreeOptions().AddMatch( "json:///", "Content/text()", "UserName/text()" ), System.Threading.CancellationToken.None); var reader = provider.ExecuteReader(); if (reader.Read()) return new NetworkCredential(reader.GetString(reader.GetOrdinal("json:///UserName/text()")), reader.GetString(reader.GetOrdinal("json:///Content/text()"))); return null; } } }
C++
UTF-8
1,816
3.515625
4
[]
no_license
#include <cmath> #include <iostream> #include "vector.h" using namespace std; void Vector::set_mag() { mag = sqrt(x*x+y*y); } void Vector::set_ang() { if((x == 0)&&(y == 0)) angle = 0; else angle = atan2(y,x); } void Vector::set_x() { x = mag * cos(angle); } void Vector::set_y() { y = mag * sin(angle); } Vector::Vector() { x = y = 0; mag = angle = 0; mode = Rect; } Vector::Vector(double n1, double n2, Mode form) { mode = form; if( mode == Rect) { x = n1; y = n2; set_mag(); set_ang(); } else if( mode == Pol) { mag = n1; angle = n2 / 57.3; set_x(); set_y(); } else { cout << "Please choose the right mode.\n"; x = y = mag = angle =0; mode = Rect; } } Vector::~Vector() { // TO DO } void Vector::Reset(double n1, double n2, Mode form) { mode = form; if( mode == Rect) { x = n1; y = n2; set_mag(); set_ang(); } else if( mode == Pol) { mag = n1; angle = n2/57.3; set_x(); set_y(); } else { cout << "It is wrong"; x = y = mag = angle = 0; mode = Rect; } } void Vector::polar_mode() { mode = Pol; } void Vector::rect_mode() { mode = Rect; } Vector Vector::operator+(const Vector & t) const { return Vector(x + t.x, y + t.y); } Vector Vector::operator-(const Vector & t) const { return Vector(x - t.x, y- t.y); } Vector Vector::operator-() const { return Vector(-x,-y); } Vector Vector::operator*(double n) const { return Vector(x*n,y*n); } Vector operator*(double n, const Vector & t) { return t*n; } std::ostream & operator<<(std::ostream & os ,const Vector & t) { if(t.mode == Vector::Rect) { os << "(x,y) = (" << t.x << ", " << t.y << "). \n"; } else if(t.mode == Vector::Pol) { os << "(mag,angle) = (" << t.mag << ", " << t.angle*57.3 << ") .\n"; } else os << "Vector object mode is invalid"; return os; }
Markdown
UTF-8
3,125
3.25
3
[]
no_license
--- layout: post title: MySQL 中 Int 列插入字符串变为 '0' date: 2017-07-20 categories: Notes tags: [MySQL] --- 今天在听课过程中遇到了这样一个问题:`grade` 表中的 `gradeid` 字段为 `INT` 类型,但是在执行插入一个字符串时,只是出现了警告,但是插入成功,而且插入的结果为 `0` ```sql # 执行语句 INSERT INTO grade(gradeid) VALUES('test') # grade 表结果 # --------- # gradeid # 0 ``` 这是由于数据库的 SQL 模式导致的结果,在 `C:\ProgramData\MySQL\MySQL Server 5.7\my.ini` 配置文件中配置 `sql-mode` 参数 ```shell # Set the SQL mode to strict sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" ``` 上述设置中 `STRICT_TRANS_TABLES` 为对事务表启用严格模式, 与这个设置相关的还有 `STRICT_ALL_TABLES`,是对所有表启用严格模式。 > 严格模式控制MySQL如何处理非法或丢失的输入值。有几种原因可以使一个值为非法。例如,数据类型错误,不适合列,或超出范围。当新插入的行不包含某列的没有显示定义DEFAULT子句的值,则该值被丢失。 > > 对于事务表,当启用STRICT_ALL_TABLES或STRICT_TRANS_TABLES模式时,如果语句中有非法或丢失值,则会出现错误。语句被放弃并滚动。 > > 对于非事务表,如果插入或更新的第1行出现坏值,两种模式的行为相同。语句被放弃,表保持不变。如果语句插入或修改多行,并且坏值出现在第2或后面的行,结果取决于启用了哪个严格选项: > > 对于STRICT_ALL_TABLES,MySQL返回错误并忽视剩余的行。但是,在这种情况下,前面的行已经被插入或更新。这说明你可以部分更新,这可能不是你想要的。要避免这点,最好使用单行语句,因为这样可以不更改表即可以放弃。 > > 对于STRICT_TRANS_TABLES,MySQL将非法值转换为最接近该列的合法值并插入调整后的值。如果值丢失,MySQL在列中插入隐式 默认值。在任何情况下,MySQL都会生成警告而不是给出错误并继续执行语句。 我的 `grade` 表的存储引擎是 `InnoDB`,应该是属于事务表, 但是在执行语句时没有报错只是出现了警告, 当然我是在 SQLyog 中执行的 SQL 语句, 可能是由于默认以非事务的方式执行 SQL 语句,所以会插入默认值, 但是如果以事务的方式执行,就会抛出错误,在 MySQL Workbench 中执行: ```sql begin; # 抛出错误 # Error Code: 1366. Incorrect integer value: 'test' for column 'id' at row 1 INSERT INTO grade(gradeid) VALUES('test'); commit; ``` 严格模式的设置主要是对于 SQL 语句的执行方式,是否在事务中执行 SQL 语句,一般单独语句的执行都默认使用非事务方式执行 > 参考链接: > <https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict> > <http://blog.sina.com.cn/s/blog_53b13d950100x2ok.html> > <http://www.2cto.com/database/201207/139809.html> > <https://my.oschina.net/wojibuzhu/blog/511104>
Markdown
UTF-8
2,452
3.9375
4
[]
no_license
## ✅ 구조체 (a) 두 점의 좌표가 일치하면 1을 반환하고 그렇지 않으면 0을 반환 // 구조체 2개 ```C #include <stdio.h> int fun(struct point point1,struct point point2); struct point { int x; int y; }; int main(void) { struct point point1; struct point point2; scanf_s("%d %d %d %d", &point1.x, &point1.y, &point2.x, &point2.y); fun(point1,point2); return 0; } int fun(struct point point1,struct point point2) { if (point1.x == point2.x && point1.y == point2.y) { printf("1"); } else { printf("0"); } return 0; } ``` ![jiwoo8-(a)](https://user-images.githubusercontent.com/81032690/127164896-a3cdf29f-6eff-4068-a55b-b6b552bdb5c9.png) (b) 점의 좌표를 받아서 어느 사분면에 속하는 지를 반환 // 구조체 1개 ```C #include <stdio.h> int fun(struct point point1); struct point { int x; int y; }; int main(void) { struct point point1; scanf_s("%d %d", &point1.x, &point1.y); fun(point1); return 0; } int fun(struct point point1) { if (point1.x > 0) { if (point1.y > 0) { printf("제1사분면"); } else { printf("제4사분면"); } } else { if (point1.y > 0) { printf("제2사분면"); } else { printf("제3사분면"); } } return 0; } ``` ![jiwoo8-(b)](https://user-images.githubusercontent.com/81032690/127164998-f0521858-a992-46f8-aed4-8530a0e5e71c.png) ## ✅ 포인터 포인터를 이용해 배열 원소의 최댓값과 최솟값을 가지는 인덱스를 찾아라. ```C #include <stdio.h> int main(void) { int i; int arr[5]; scanf_s("%d %d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]); int max = arr[0]; int num1 = 0; int* numPtr1 = &num1; for (i = 0; i < 5; i++) { if (max < arr[i]) { max = arr[i]; *numPtr1 = i; } } printf("최댓값 인덱스 : %d\n", *numPtr1); int min = arr[0]; int num2 = 0; int* numPtr2 = &num2; for (i = 0; i < 5; i++) { if (min > arr[i]) { min = arr[i]; *numPtr2 = i; } } printf("최솟값 인덱스 : %d\n", *numPtr2); return 0; } ``` ![jiwoo8-2](https://user-images.githubusercontent.com/81032690/127165090-22bcd893-b5b0-41e3-b7f7-0c0cc7d44cd2.png)
PHP
UTF-8
3,840
2.671875
3
[]
no_license
<?php /** * Default implementation of user roles for ACL. * * Includes role for visitor, extending roles. * * @author Dmitry Kurinskiy * * @table o_acl_role * @field parent -has one {classnames/acl_role} -inverse childs * @field childs -has many {classnames/acl_role} -inverse parent * @field name varchar(64) not null * @field users -has many {classnames/user} -inverse role * @field actions -has many {classnames/acl_action} -inverse roles * @field visitor_role tinyint default 0 * @index name * @index visitor_role */ class O_Acl_Role extends O_Dao_ActiveRecord { /** * Cached visitor role * * @var O_Acl_Role */ protected static $visitor_role = null; /** * Roles by its names * * @var O_Acl_Role[] */ protected static $objs = Array (); /** * Checks role access. Returns null if no rules is set for role, bool otherwise * * @param string $action * @return bool or null */ public function can( $action ) { foreach ($this->actions as $act) { if ($act->name == $action) { return $act->getAccess(); } } if ($this->parent) return $this->parent->can( $action ); O_Acl_Action::getByRule( $action ); return null; } /** * Allows the action for role * * @param string $action */ public function allow( $action ) { $this->clear( $action ); $this->actions[] = O_Acl_Action::getByRule($action, O_Acl_Action::TYPE_ALLOW); } /** * Denies the action for role * * @param string $action */ public function deny( $action ) { $this->clear( $action ); $this->actions[] = O_Acl_Action::getByRule($action, O_Acl_Action::TYPE_DENY ); } /** * Remove information about action from role (inherit access rule for it from parent role) * * @param string $action */ public function clear( $action ) { foreach ($this->actions as $act) { if ($act->name == $action) { $this->actions->remove( $act ); } } $this->actions->reload(); } /** * Returns action status for current role (without parents) * * @param string $action * @return const */ public function getActionStatus( $action ) { foreach ($this->actions as $act) { if ($act->name == $action) { return $act->type; } } return "clear"; } /** * Set current role as visitor's role * */ public function setAsVisitorRole() { O_Dao_Query::get( self::getClassName() )->field( "visitor_role", 0 )->update(); $this->visitor_role = 1; $this->save(); self::$visitor_role = $this; } /** * Returns visitor role object * * @return O_Acl_Role */ static public function getVisitorRole() { if (!self::$visitor_role) { self::$visitor_role = O_Dao_Query::get( self::getClassName() )->test( "visitor_role", 1 )->getOne(); } return self::$visitor_role; } /** * Creates new role * * @param string $name */ public function __construct( $name ) { $this->name = $name; parent::__construct(); } /** * Returns role by its name, creates it on demand * * @param string $name * @return O_Acl_Role */ static public function getByName( $name ) { $class = self::getClassName(); if(!count(self::$objs)) { foreach(O_Dao_Query::get($class) as $role) { self::$objs[$role->name] = $role; } } if (!isset( self::$objs[ $name ] )) { self::$objs[ $name ] = O_Dao_Query::get($class)->test("name", $name)->limit(1)->getOne(); if (!self::$objs[ $name ]) { self::$objs[ $name ] = new $class( $name ); } } return self::$objs[ $name ]; } /** * Returns current classname of roles DAO * * @return string */ static public function getClassName() { return O_Registry::get( "app/classnames/acl_role" ); } }
Java
UTF-8
2,539
2.140625
2
[]
no_license
package com.ai.yc.ucenter.constants.eunm; /** * Created by astraea on 2015/7/27. */ public final class Constants { private Constants() { // non } /** * 注册方式 * to UcMembersServiceAtomImpl.getUsername * @author Administrator * */ public final static class LoginWayConstant { private LoginWayConstant() { } //邮箱密码 public final static String EMAIL_PASS = "1"; //手机密码 public final static String MOBILE_PASS = "2"; //手机动态密码 public final static String MOBILE_DYNA = "3"; //用户名密码 public final static String USER_PASS = "4"; } /** * 操作码生成 移动电话/邮件 * to UcMembersBusinessService.insertMember * @author Administrator * */ public final static class UserInfoConstant { private UserInfoConstant() { } //邮箱 public final static String EMAIL_INFO= "1"; //手机 public final static String MOBILE_INFO = "2"; } /** * 获取用户信息返回结果 * to UcMembersBusinessService.insertMember * @author Administrator * */ public final static class GetUcMembersResultConstants { private GetUcMembersResultConstants() { } //成功 public final static int SUCCESS_CODE= 1; //失败 public final static int FAIL_CODE = -1; //未激活 public final static int NO_ACTIV = -12; //输入信息不能为空 public final static int NOT_EMPTY= -16; } /** * 码类型 * to UcMembersBusinessService.insertMember * @author Administrator * */ public final static class OperationtypeConstants { private OperationtypeConstants(){} /** * 手机激活码 */ public static final String MOBILE_ACTIV= "1"; /** * 手机验证码 */ public static final String MOBILE_VALI= "2"; /** * 手机动态密码 */ public static final String DYN_PASS= "3"; /** * 邮箱激活码 */ public static final String EMAIL_ACTIV= "4"; /** * 邮箱验证码 */ public static final String EMAIL_VALI= "5"; /** * 密码操作验证码 */ public static final String PASS_VALI= "6"; } }
Python
UTF-8
3,620
3.640625
4
[]
no_license
""" For sampling epoch data. General Notes -- Shirakawa introduces three sampling strategies: left, right, both. On the convention that we have two columns, U -> V, where U is the hyponym and V the hypernym: - left sampling considers all hyponyms, excluding those hyponyms of U. Overall it therefore considers all nodes except the root of the tree. - right sampling considers all hypernyms, excluding hypernyms of U. Overall it therefore considers all nodes except the leaves of the tree. - both considers all words, except hypo- or hypernyms of U. Considering the layout of the following diagrams: https://github.com/qiangsiwei/poincare_embedding I hypothesize that excluding words from negative sampling reduces the amount of gradient they receive each epoch, meaning they don't move as far. This may explain why right sampling appears less spread out than left sampling, and why both sampling is more spread out than the other two. I intend to quantify this with an experiment to test it. Implementation Notes -- For memory's sake, the data is stored in bins indexed by the first two letters of the words. In each bin we have a record looking like: {'word': {'up': [ixs of word's hypernyms]}, {'down': [ixs of word's hyponyms]}} Our algorithm is then as follows. For each U: neg_ixs = [u_ix] ruled_out = get_ruled_out(u, sampling_strategy) # looks up bin num_negs = min(num_negs, len(vocab) - len(ruled_out)) while len(neg_ixs) != num_negs: neg_ix = random.choice(all_ixs) if neg_ix not in ruled_out: neg_ixs.append(neg_ix) return neg_ixs I believe the purpose of adding u to the N(u) set is to ensure it isn't an empty set and therefore the loss function in the paper doesn't encounter a divide by zero. """ from data import preprocess import random class Sampler: """For getting negative samples.""" def __init__(self, dataset_name, mode, num_negs): """Create a new Sampler. Args: dataset_name: String. mode: String in {up, down, both}. num_negs: Integer, the number of negatives to sample for each word. """ self.dataset_name = dataset_name self.vocab = preprocess.get_vocab(dataset_name) self.mode = mode self.num_negs = num_negs self.all_ixs = list(range(len(self.vocab))) def __call__(self, u): return self.sample_neg_ixs(u) def get_ruled_out(self, word): """Get list of positive ixs ruled out for negative sampling. Args: word: String. Returns: List of integers. """ word_bin = preprocess.get_bin(self.dataset_name, word) relatives = word_bin[word] if self.mode == 'up': return relatives['up'] elif self.mode == 'down': return relatives['down'] elif self.mode == 'both': return list(relatives['up']) + list(relatives['down']) else: raise ValueError('Unrecognized mode: %r' % self.mode) def sample_neg_ixs(self, u): """Get negative sample ixs. Args: u: String, the word in position u. Returns: List of integer indices representing negative samples. """ neg_ixs = [] ruled_out = self.get_ruled_out(u) num_negs = min(self.num_negs, len(self.vocab) - len(ruled_out)) while len(neg_ixs) != num_negs: neg_ix = random.choice(self.all_ixs) if neg_ix not in ruled_out and neg_ix not in neg_ixs: neg_ixs.append(neg_ix) return neg_ixs
JavaScript
UTF-8
5,898
3.734375
4
[]
no_license
// 这里只讨论有序二叉树,如果无序,二叉树无法手动建立,并且只能通过轮询检索 class tree{ constructor(){ //初始化二叉树 this.tree = {}; } // 对二叉树插入节点 insert(data){ let root = this.tree; if(root.hasOwnProperty('value') == false || root.value == null){ this.root = data; return root.value = data; } var current = root; while (current){ if(data < current.value){ if(current.left){ current = current.left }else{ current.left = {value:data}; break; } } if(data > current.value){ if(current.right){ current = current.right; }else{ current.right = {value:data}; break; } } if(data === current.value){ console.log('Each node of the binary tree must be diffent.'); break; } } } // 寻找最小值的节点 min(){ let tree = this.tree; let node = tree; let parent; while(node.value){ parent = node; node = node.left; if(!node){ return parent.value; } } } // 寻找最大值节点 max(){ let tree = this.tree; let node = tree; let parent; while(node.value){ parent = node; node = node.right; if(!node){ return parent.value; } } } // 查找指定值的节点 find(data){ let tree = this.tree; let node = tree; while(node.value){ if(data < node.value && node.left){ node = node.left; }else if(data > node.value && node.right){ node = node.right; }else if(data === node.value){ return node; }else{ console.log('Data no found'); break; } } } // 先序递归遍历 preTraverse(){ let tree = this.tree; let root = this.root; let nodeArray = []; let traverse = function(tree){ if(tree && tree.value !== null){ nodeArray.push(tree.value); traverse(tree.left); traverse(tree.right); } return nodeArray; }; return traverse(tree); } // 中序递归遍历(正序排列) orderTraverse(){ let tree = this.tree; let root = this.root; let nodeArray = []; let traverse = function(tree){ if(tree && tree.value !== null){ traverse(tree.left); nodeArray.push(tree.value); traverse(tree.right); if(tree.value === root){ return nodeArray; } } }; return traverse(tree); } // 后序递归遍历(倒序排列) afterTraverse(){ let tree = this.tree; let root = this.root; let nodeArray = []; let traverse = function(tree){ if(tree && tree.value !== null){ traverse(tree.left); traverse(tree.right); nodeArray.push(tree.value); if(tree.value === root){ return nodeArray; } } }; return traverse(tree); } // 使用栈进行非递归深度遍历,(非递归广度使用队列),使用该方法时很消耗内存 // 先序 noRecPreTra(){ let root = this.root; let tree = this.tree; let nodeArray = []; let stact = []; stact.push(tree); while(stact.length){ let node = stact.pop(); nodeArray.push(node.value); node.right && stact.push(node.right); node.left && stact.push(node.left); } return nodeArray; } // 中序 noRecOrdTra(){ let root = this.root; let tree = this.tree; let nodeArray = []; let stact = []; var node = tree; if(tree.hasOwnProperty('value')===false){ return 'tree is null'; } while (node || stact.length){ while(node){ stact.push(node); node = node.left; } if(stact.length){ node = stact.pop(); nodeArray.push(node.value); node = node.right; } } return nodeArray; } // 后续非递归遍历 nodeRecAferTra(){ let tree = this.tree; let nodeArray = []; let stact = []; let node = tree; if(tree.hasOwnProperty('value')===false){ return 'tree is null'; } stact.push(node); let tmp = null; while(stact.length){ tmp = stact[stact.length - 1]; if(tmp.left && node.value !== tmp.left.value && ((tmp.right && node.value !== tmp.right.value) || !tmp.right)){ stact.push(tmp.left); }else if(tmp.right && node.value !== tmp.right.value){ stact.push(tmp.right); }else{ nodeArray.push(stact.pop().value); node = tmp; } } return nodeArray; } // 双栈后序方法 twoStactAfterTra(){ const tree = this.tree; let node = null; let nodeArray = []; let stact1 = []; let stact2 = []; stact1.push(tree); while(stact1.length){ node = stact1.pop(); stact2.push(node); if(node.left){ stact1.push(node.left); } if(node.right){ stact1.push(node.right); } } while(stact2.length){ nodeArray.push(stact2.pop().value); } return nodeArray; } } var myTree = new tree(); myTree.insert(10); myTree.insert(5); myTree.insert(7); myTree.insert(6); myTree.insert(11); myTree.insert(15); myTree.insert(4); myTree.insert(3); myTree.insert(13); myTree.insert(14); var nodeArr = myTree.nodeRecAferTra(); console.log(nodeArr); // 数据格式 // var myTree = { // value:10, // left:{ // value:5, // left:{ // value:4, // left:{ // value:3, // } // }, // right:{ // value:7, // left:{ // value:6 // }, // right:{ // value:9 // } // } // }, // right:{ // value:11, // right:{ // value:15, // left:{ // value:13, // right:{ // value:14 // } // } // } // } // };
C#
UTF-8
5,246
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web; using E_CommerceDbFirst.Models; using System.Data.Entity; using System.IO; using System.Threading.Tasks; using System.Diagnostics; namespace E_CommerceDbFirst.Controllers.Api { public class ItemsController : ApiController { //Initializing DataBase Nd Constructor Initializing data_Base db; public ItemsController() { db = new data_Base(); } //Get All The Items From DataBase [HttpGet] public IHttpActionResult get() { var data = db.getItems(); if (data == null) { return BadRequest(); } return Ok(data); } //[HttpGet] //public IHttpActionResult getByItemsId(string itemsId) //{ // var items = db.Items.Where(m => itemsId.Contains(m.ItemId)); //} //Get THe Items from DataBase On The Base of Choosen CatName [HttpGet] public IHttpActionResult getByCat(string categories) { if (categories == null) { return Redirect("/items/index"); } var data = db.getItemByCatName(categories); if (data != null) { return Ok(data); } return Redirect("/items/index"); } //Get THe Items from DataBase On The Base of Choosen CatName [HttpGet] public IHttpActionResult getByIngredient(string ingredients) { if (ingredients == null) { return Redirect("/items/idex"); } var data = db.getItemsByIngredientName(ingredients); if (data != null) { return Ok(data); } return Redirect("/items/index"); } //Get The Specific Item on the base of ItemId [HttpGet] public IHttpActionResult GetById(int id) { if (id < 1) { return Redirect("/items/index"); } var data = db.getItemById(id); if (data == null) { return Content(HttpStatusCode.BadRequest, "Data DoesNot Exist"); } return Ok(data); } //Saving New Item in DataBase public Task<IHttpActionResult> Post() { Item item = new Item(); string[] array = new string[3]; List<string> savedFilePath = new List<string>(); string rootPath = HttpContext.Current.Server.MapPath("~/Images"); var provider = new MultipartFormDataStreamProvider(rootPath); var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith<IHttpActionResult>(t => { int i = 0; foreach (var key in provider.FormData.AllKeys) { foreach (var val in provider.FormData.GetValues(key)) { array[i] = val; i++; } } foreach (MultipartFileData file in provider.FileData) { try { string name = file.Headers.ContentDisposition.FileName.Replace("\"", ""); string newFileName = Guid.NewGuid() + Path.GetExtension(name); File.Move(file.LocalFileName, Path.Combine(rootPath, newFileName)); Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty)); string fileRelativePath = "~/Images/" + newFileName; Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath)); savedFilePath.Add(fileFullPath.ToString()); item.ImageUrl = fileFullPath.ToString(); item.Name = array[0]; item.Price = Convert.ToDecimal(array[1]); item.CategoriesId = Convert.ToInt32(array[2]); db.saveItem(item.Name, item.Price, item.ImageUrl, item.CategoriesId); db.SaveChanges(); } catch (Exception ex) { string message = ex.Message; } } return Ok("Succeeded"); }); return task; } //Deleting The Item From DataBase [HttpPut] public IHttpActionResult deleteItem(int id) { try { db.deleteItem(id); return Ok(); } catch (Exception e) { return BadRequest(); } } } }
Java
UTF-8
1,232
1.960938
2
[ "Apache-2.0" ]
permissive
/** * Copyright (c) 2015, www.cubbery.com. All rights reserved. */ package com.cubbery.event.conf; public interface ConfigureKeys { /**总线消费者数量**/ String BUS_CONSUME_COUNT = "bus.consume.count"; /**总线分发者数量**/ String BUS_DISPATCH_COUNT = "bus.dispatch.count"; /**总线时间单位**/ String BUS_TIME_UNIT = "bus.time.unit"; /**渠道默认超时时间**/ String CHANNEL_OFFER_EXPIRE = "channel.offer.expire"; /**通道类型**/ String CHANNEL_TYPE = "channel.type"; /**通道大小**/ String CHANNEL_SIZE = "channel.size"; /**重试服务master优先权,单位为秒(s)**/ String RETRY_MASTER_PRIORITY = "retry.master.priority"; /**重试并发处理数**/ String RETRY_PARALLEL_COUNT = "retry.parallel.count"; /**事件最大重试次数**/ String EVENT_MAX_RETRY_COUNT = "event.maxRetry.count"; /**新master上线等待时间**/ String RETRY_MASTER_WAIT = "retry.master.wait"; /**是否开启确认下线功能**/ String RETRY_MAKESURE_OFFLINE = "retry.makeSure.offline"; /**租约周期**/ String RETRY_LEASE_PERIOD = "retry.lease.period"; }
Java
UTF-8
483
2.15625
2
[]
no_license
package com.project.teamup.mapper; import com.project.teamup.dto.CompanyDTO; import com.project.teamup.model.Company; import org.mapstruct.Mapper; import java.util.List; @Mapper public abstract class CompanyMapper { public abstract Company toEntity(CompanyDTO dto); public abstract List<Company> toEntityList(List<CompanyDTO> entityDTOS); public abstract CompanyDTO toDto(Company entity); public abstract List<CompanyDTO> toDtoList(List<Company> entityList); }
Java
UTF-8
2,462
2.5
2
[]
no_license
package com.loosu.sample.adapter.base.listview; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.loosu.sample.adapter.base.IAViewHolder; /** * Created by LuWei on 2018/7/30/030. */ /** * 主要处理{@link BaseAdapter#getView(int, View, ViewGroup)} 减少findView的次数, 封装模板代码。 * <p> * 模仿 {@link android.support.v7.widget.RecyclerView.Adapter} 增加 * {@link AbsListAdapter#createViewHolder(int, View)}、 * {@link AbsListAdapter#onBindViewData(ViewHolder, int)} 方法。 * * @param <VH> ViewHolder */ public abstract class AbsListAdapter<VH extends AbsListAdapter.ViewHolder> extends BaseAdapter { @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { VH holder = null; if (convertView == null) { convertView = LayoutInflater.from(parent.getContext()) .inflate(getItemViewLayoutId(position), parent, false); holder = createViewHolder(position, convertView); convertView.setTag(holder); } else { holder = (VH) convertView.getTag(); } onBindViewData(holder, position); return convertView; } /** * 根据position获取Itemt的layoutId * * @param position position * @return layoutId */ protected abstract int getItemViewLayoutId(int position); /** * 创建ViewHolder * * @param position position * @param convertView itemView * @return holder */ protected abstract VH createViewHolder(int position, @NonNull View convertView); /** * 视图和数据绑定,相当于{@link android.support.v7.widget.RecyclerView.Adapter#onBindViewHolder(RecyclerView.ViewHolder, int)} * * @param holder holder * @param position position */ protected abstract void onBindViewData(VH holder, int position); public static abstract class ViewHolder implements IAViewHolder { public View itemView; public ViewHolder(View itemView) { this.itemView = itemView; } @Override public View getItemView() { return itemView; } } }
JavaScript
UTF-8
656
3.515625
4
[ "MIT" ]
permissive
function mergeSort(arr){ if(arr.length===1){ return arr } let center=Math.round(arr.length/2) let left=arr.slice(0,center); let right=arr.slice(center); return merge(mergeSort(left),mergeSort(right)) } function merge(left,right){ let result=[]; while(left.length && right.length){ if(left[0]<right[0]) { result.push(left.shift()) } else { result.push(right.shift()) } } console.log([...result,...right,...left]) return [...result,...right,...left] } let arr=[3,2,4,5,1] console.log(mergeSort(arr))
Java
UTF-8
805
2.75
3
[]
no_license
package domain.datamappers; import domain.Eigenaar; import exceptions.eigenexcepties.DatabaseFoutException; import java.sql.*; public class EigenaarDataMapper { public Eigenaar mapResultSetToDomain(ResultSet resultSet) { if (resultSet != null) { try { while (resultSet.next()) { Eigenaar eigenaar = new Eigenaar(); eigenaar.setGebruikersnaam(resultSet.getString("gebruikersnaam")); eigenaar.setWachtwoord(resultSet.getString("wachtwoord")); return eigenaar; } } catch(SQLException e){ throw new DatabaseFoutException("Er is heeft een fout opgetreden bij het omzetten van resultset naar Eigenaar"); } } return null; } }
Python
UTF-8
2,616
2.6875
3
[]
no_license
from steem import Steem from steem.post import Post from steem.amount import Amount from steem.account import Account from dateutil.parser import parse from datetime import timedelta, datetime steem = Steem() post = Post("@steempytutorials/part-12-how-to-estimate-curation-rewards") # Everything we need to calculate the reward reward_fund = steem.get_reward_fund() reward_balance = Amount(reward_fund["reward_balance"]).amount recent_claims = float(reward_fund["recent_claims"]) reward_share = reward_balance / recent_claims base = Amount(steem.get_current_median_history_price()["base"]).amount ### Curation reward penalty def curation_penalty(post, vote): post_time = post["created"] vote_time = parse(vote["time"]) time_elapsed = vote_time - post_time reward = time_elapsed / timedelta(minutes=30) * 1.0 if reward > 1.0: reward = 1.0 return reward ### Calculating curation reward per vote curation_pct = 0.25 def curation_reward(post, vote): rshares = float(vote["rshares"]) base_share = reward_share * base return (rshares * curation_penalty(post, vote) * curation_pct) * base_share ### Calculating beneficiary shares def beneficiaries_pct(post): weight = sum([beneficiary["weight"] for beneficiary in post["beneficiaries"]]) return weight / 10000.0 ### Calculating author and beneficiary rewards def estimate_rewards(post): votes = [vote for vote in post["active_votes"]] total_share = sum([float(vote["rshares"]) * reward_share * base for vote in votes]) curation_share = sum([curation_reward(post, vote) for vote in votes]) author_share = (total_share - curation_share) * (1.0 - beneficiaries_pct(post)) beneficiary_share = (total_share - curation_share) * beneficiaries_pct(post) print(f"Estimated total reward for this post is ${total_share:.2f}") print(f"Estimated author reward for this post is ${author_share:.2f}") print(f"Estimated beneficiary reward for this post is ${beneficiary_share:.2f}") print(f"Estimated curation reward for this post is ${curation_share:.2f}\n") ### Estimating rewards in last `N` days account = "steempytutorials" time_period = timedelta(days=3) posts = set() for post in Account(account).history_reverse(filter_by="comment"): try: post = Post(post) if post.time_elapsed() < time_period: if post.is_main_post() and not post["title"] in posts: posts.add(post["title"]) print(post["title"]) estimate_rewards(post) else: break except Exception as error: continue
JavaScript
UTF-8
1,393
3.15625
3
[]
no_license
const { sumArr } = require('../helper-methods/helper-methods'); const parsePsw = (inputString) => { const [occurString, letter, psw] = inputString.split(' '); const [firstCondition, secondCondition] = occurString.split('-'); return { firstCondition, secondCondition, letter: letter.replace(':', ''), psw } } const meetsPt1Criteria = pswObj => { const {firstCondition: minOccur, secondCondition: maxOccur, letter, psw} = pswObj; const letterArr = psw.split(''); const filteredArr = letterArr.filter(l => letter === l); const occuranceInPsw = filteredArr.length; return occuranceInPsw >= minOccur && occuranceInPsw <= maxOccur }; const meetsPt2Criteria = pswObj => { const {firstCondition: firstIndex, secondCondition: secondIndex, letter, psw} = pswObj; const letterArr = psw.split(''); const firstLetter = letterArr[firstIndex - 1]; const secondLetter = letterArr[secondIndex - 1]; return (firstLetter !== letter && secondLetter !== letter) ? false : !(firstLetter === letter && secondLetter === letter); } const day2Solution = (inputArr, criteraMethod) => { const arr = inputArr.map(inputString => criteraMethod(parsePsw(inputString)) ? 1 : 0); return arr.reduce(sumArr); } module.exports = { parsePsw, day2Solution, meetsPt2Criteria, meetsPt1Criteria };
Markdown
UTF-8
824
3.109375
3
[]
no_license
# Personal Blog Tutorial This project is used in my [Make A Personal Blog](https://gitauharrison-blog.herokuapp.com/personal-blog) tutorial series. Intentionally, I embark on showing how building a personal blog can be a fun side project to learn Flask and web development in general. If you can build your own blog from scratch, why use a template? To run the application on your machine, clone this project: ```python $ git clone git@github.com:GitauHarrison/personal-blog-tutorial-project.git ``` Create and activate your virtual environment: ```python $ mkvirtualenv personal_blog # I am using a virtualenv wrapper ``` Install the dependancies used: ```python $ pip3 install -r requirements.txt ``` Run the application: ```python $ flask run ``` Paste http://127.0.0.1:5000/ on your browser's address bar to see the output.
Java
UTF-8
3,373
2.734375
3
[]
no_license
package com.ex.dao; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import com.ex.pojos.Artist; import com.ex.util.ConnectionFactory; import oracle.jdbc.internal.OracleTypes; public class ArtistDAOImpl implements ArtistDAO{ //STATEMENT @Override public ArrayList<Artist> getAll() { ArrayList<Artist> artists = new ArrayList<Artist>(); try(Connection conn = ConnectionFactory.getInstance().getConnection();){ String query = "select * from artist"; Statement statement = conn.createStatement(); ResultSet rs = statement.executeQuery(query); while(rs.next()) { Artist temp = new Artist(); temp.setId(rs.getInt("ARTISTID")); //can access by name or index(starts with 1) temp.setName(rs.getString(2)); artists.add(temp); } } catch (SQLException e) { e.printStackTrace(); } return artists; } @Override public Artist getById(int id) { Artist artist = new Artist(); try(Connection conn = ConnectionFactory.getInstance().getConnection()){ String query = "select * from artist where artistid = ?"; PreparedStatement ps = conn.prepareStatement(query); ps.setInt(1, id); ResultSet info = ps.executeQuery(); while(info.next()) { artist.setId(info.getInt(1)); artist.setName(info.getString(2)); } } catch (SQLException e) { e.printStackTrace(); } return artist; } @Override public Artist addArtist(String name) { Artist art = new Artist(); try(Connection conn = ConnectionFactory.getInstance().getConnection();){ conn.setAutoCommit(false); String query = "insert into artist (NAME) values (?)"; String[] keys = new String[1]; keys[0] = "artistid"; PreparedStatement ps = conn.prepareStatement(query, keys); ps.setString(1, name); int rows = ps.executeUpdate(); if(rows != 0) { ResultSet pk = ps.getGeneratedKeys(); while(pk.next()) { art.setId(pk.getInt(1)); } art.setName(name); conn.commit(); } } catch (SQLException e) { e.printStackTrace(); } return art; } @Override public void updateArtist(int id, String name) { try(Connection conn = ConnectionFactory.getInstance().getConnection();){ conn.setAutoCommit(false); String query = "update artist set name = ? where artistid = ?"; PreparedStatement ps = conn.prepareStatement(query); ps.setString(1, name); ps.setInt(2, id); System.out.println( ps.executeUpdate()) ; // System.out.println(row + "rows affected"); conn.commit(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public ArrayList<Artist> getAllStoredProc() { ArrayList<Artist> artists = new ArrayList<Artist>(); try(Connection conn = ConnectionFactory.getInstance().getConnection();){ String query = "{call get_all_artists(?) }"; CallableStatement cs = conn.prepareCall(query); cs.registerOutParameter(1, OracleTypes.CURSOR); cs.execute(); ResultSet rs = (ResultSet) cs.getObject(1); while(rs.next()) { artists.add(new Artist(rs.getInt(1), rs.getString(2))); } } catch (SQLException e) { e.printStackTrace(); } return artists; } }
C++
UTF-8
4,661
2.578125
3
[ "MIT" ]
permissive
#pragma once #include <polyfem/utils/Types.hpp> #include <polyfem/solver/forms/parametrization/Parametrization.hpp> #include <polyfem/solver/forms/adjoint_forms/AdjointForm.hpp> namespace polyfem { class State; } namespace polyfem::solver { class ParametrizationForm : public AdjointForm { public: ParametrizationForm(const CompositeParametrization &parametrizations) : AdjointForm({}), parametrizations_(parametrizations) {} virtual ~ParametrizationForm() {} virtual void init(const Eigen::VectorXd &x) final override { init_with_param(apply_parametrizations(x)); } virtual double value_unweighted(const Eigen::VectorXd &x) const override { Eigen::VectorXd y = apply_parametrizations(x); return value_unweighted_with_param(y); } virtual void first_derivative_unweighted(const Eigen::VectorXd &x, Eigen::VectorXd &gradv) const override { Eigen::VectorXd y = apply_parametrizations(x); first_derivative_unweighted_with_param(y, gradv); gradv = parametrizations_.apply_jacobian(gradv, x); } virtual bool is_step_valid(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const final override { return is_step_valid_with_param(apply_parametrizations(x0), apply_parametrizations(x1)); } virtual double max_step_size(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const final { return max_step_size_with_param(apply_parametrizations(x0), apply_parametrizations(x1)); } virtual void line_search_begin(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) final override { line_search_begin_with_param(apply_parametrizations(x0), apply_parametrizations(x1)); } virtual void line_search_end() final override { line_search_end_with_param(); } virtual void post_step(const int iter_num, const Eigen::VectorXd &x) final override { post_step_with_param(iter_num, apply_parametrizations(x)); } virtual void solution_changed(const Eigen::VectorXd &new_x) final override { solution_changed_with_param(apply_parametrizations(new_x)); } virtual void update_quantities(const double t, const Eigen::VectorXd &x) final override { update_quantities_with_param(t, apply_parametrizations(x)); } virtual void init_lagging(const Eigen::VectorXd &x) final override { init_lagging_with_param(apply_parametrizations(x)); } virtual void update_lagging(const Eigen::VectorXd &x, const int iter_num) final override { update_lagging_with_param(apply_parametrizations(x), iter_num); } virtual void set_apply_DBC(const Eigen::VectorXd &x, bool apply_DBC) final override { set_apply_DBC_with_param(apply_parametrizations(x), apply_DBC); } virtual bool is_step_collision_free(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const final override { return is_step_collision_free_with_param(apply_parametrizations(x0), apply_parametrizations(x1)); } virtual Eigen::MatrixXd compute_adjoint_rhs_unweighted(const Eigen::VectorXd &x, const State &state) const override; virtual void init_with_param(const Eigen::VectorXd &x) {} virtual bool is_step_valid_with_param(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const { return true; } virtual double max_step_size_with_param(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const { return 1; } virtual void line_search_begin_with_param(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) {} virtual void line_search_end_with_param() {} virtual void post_step_with_param(const int iter_num, const Eigen::VectorXd &x) {} virtual void solution_changed_with_param(const Eigen::VectorXd &new_x) {} virtual void update_quantities_with_param(const double t, const Eigen::VectorXd &x) {} virtual void init_lagging_with_param(const Eigen::VectorXd &x) {} virtual void update_lagging_with_param(const Eigen::VectorXd &x, const int iter_num) {} virtual void set_apply_DBC_with_param(const Eigen::VectorXd &x, bool apply_DBC) {} virtual bool is_step_collision_free_with_param(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const { return true; } virtual void first_derivative_unweighted_with_param(const Eigen::VectorXd &x, Eigen::VectorXd &gradv) const {} virtual double value_unweighted_with_param(const Eigen::VectorXd &x) const { return 0; } protected: virtual void compute_partial_gradient_unweighted(const Eigen::VectorXd &x, Eigen::VectorXd &gradv) const override { first_derivative_unweighted(x, gradv); } private: CompositeParametrization parametrizations_; Eigen::VectorXd apply_parametrizations(const Eigen::VectorXd &x) const { return parametrizations_.eval(x); } }; } // namespace polyfem::solver
C++
UTF-8
2,028
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; using edge = tuple<int, int, int>; const int oo { 2000000010 }; class UnionFind { vector<int> parent, rank; public: UnionFind(int N) : parent(N + 1), rank(N + 1, 0) { iota(parent.begin(), parent.end(), 0); } bool same_set(int i, int j) { return find_set(i) == find_set(j); } void union_set(int i, int j) { if (same_set(i, j)) return; int p = find_set(i); int q = find_set(j); if (rank[p] > rank[q]) parent[q] = p; else if (rank[q] > rank[p]) parent[p] = q; else { parent[q] = p; ++rank[p]; } } int find_set(int i) { return parent[i] == i ? i : (parent[i] = find_set(parent[i])); } }; pair<int, vector<int>> kruskal(int N, vector<edge>& es, int blocked = -1) { vector<int> mst; UnionFind ufds(N); int cost = 0; for (int i = 0; i < (int) es.size(); ++i) { auto [w, u, v] = es[i]; if (i != blocked and not ufds.same_set(u, v)) { cost += w; ufds.union_set(u, v); mst.emplace_back(i); } } return { (int) mst.size() == N - 1 ? cost : oo, mst }; } pair<int, int> solve(int N, vector<edge>& es) { sort(es.begin(), es.end()); auto [best, mst] = kruskal(N, es); int _2nd_best = oo; for (auto blocked : mst) { auto [cost, __] = kruskal(N, es, blocked); _2nd_best = min(_2nd_best, cost); } return { best, _2nd_best }; } int main() { ios::sync_with_stdio(false); int T; cin >> T; while (T--) { int N, M; cin >> N >> M; vector<edge> es(M); for (int i = 0; i < M; ++i) { int u, v, w; cin >> u >> v >> w; es[i] = edge(w, u, v); } auto [x, y] = solve(N, es); cout << x << ' ' << y << '\n'; } return 0; }
Java
UTF-8
1,802
2.109375
2
[]
no_license
package com.device.business.equip.dao; import java.math.BigDecimal; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.springframework.beans.factory.annotation.Autowired; import com.device.business.equip.bean.PperdeepBean; import com.device.business.equip.bean.PperdeepBeanExample; import com.device.business.equip.dao.mapper.PperdeepBeanMapper; public class PileDeepDao { @Autowired PperdeepBeanMapper mapper; public Map<String, Object> selectMachineInfo(String pileNumber) { List<Map<String, Object>> list = mapper.selectMachineInfo(pileNumber,new RowBounds(1,1)); if(null!=list&&list.size()>0){ return list.get(0); }else{ return null; } } public List<PperdeepBean> selectByDown(String pileNumber){ PperdeepBeanExample example = new PperdeepBeanExample(); example.or().andPileNumberEqualTo(pileNumber).andPileDeepLessThanOrEqualTo(new BigDecimal(0)); example.setOrderByClause("Pile_Deep"); return mapper.selectByExample(example); }; public List<PperdeepBean> selectByUP(String pileNumber){ PperdeepBeanExample example = new PperdeepBeanExample(); example.or().andPileNumberEqualTo(pileNumber).andPileDeepGreaterThanOrEqualTo(new BigDecimal(0)); example.setOrderByClause("Pile_Deep DESC"); return mapper.selectByExample(example); }; public List<PperdeepBean> selectByAll(String pileNumber){ PperdeepBeanExample example = new PperdeepBeanExample(); example.or().andPileNumberEqualTo(pileNumber); example.setOrderByClause("Pile_Deep"); return mapper.selectByExample(example); }; public List<PperdeepBean> selectByAbs(String pileNumber){ PperdeepBeanExample example = new PperdeepBeanExample(); example.or().andPileNumberEqualTo(pileNumber); return mapper.selectByABS(example); }; }
C++
UTF-8
818
3.09375
3
[]
no_license
#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { double amount, principal, rate, compounded, interest; cout << "What's the principal? "; cin >> principal; cout << "What's the interest rate? "; cin >> rate; cout << "How many times is interest compounded? "; cin >> compounded; cout << " Interest Rate: " << rate << "%\n"; cout << " Times Compounded: " << compounded << endl; cout << " Principal: $ " << setprecision(2) << fixed << principal << endl; interest=principal*(pow((1+(rate/compounded)/100),compounded))-principal; cout << " Interest: $ " << setprecision(2) << fixed << interest << endl; amount=interest+principal; cout << " Amount in Savings: $ " << setprecision(2) << fixed << amount << endl; }
Java
UTF-8
1,423
3.21875
3
[]
no_license
/* ID: Jaeshi LANG: JAVA TASK: beads */ import java.io.*; public class beads { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("beads.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("beads.out"))); int n = Integer.parseInt(in.readLine()); String s = in.readLine(); int max = 0; for (int i = 0; i < n; i++) { // go right int rShift = 0; int rStart = 0; while ((s.charAt((i + rStart) % n) == s.charAt((i + rShift) % n) || s.charAt((i + rShift) % n) == 'w') && rShift < n) { while (s.charAt((i + rStart) % n) == 'w' && rStart < n) rStart++; rShift++; } // go left int lShift = 0; int lStart = 0; while ((s.charAt((((i - lStart - 1) % n) + n) % n) == s.charAt((((i - lShift - 1) % n) + n) % n) || s.charAt((((i - lShift - 1) % n) + n) % n) == 'w') && lShift < n - rShift) { while (s.charAt((((i - lStart - 1) % n) + n) % n) == 'w' && lStart < n) lStart++; lShift++; } // set max if (rShift + lShift > max) { max = rShift + lShift; } } out.println(max); out.close(); } }
JavaScript
UTF-8
406
3.0625
3
[]
no_license
//Create a react app from scratch. //It should display a h1 heading. //It should display an unordered list (bullet points). //It should contain 3 list elements. var React = require("react"); var ReactDOM = require("react-dom"); ReactDOM.render( <div> <h1>Hello World</h1> <ul> <li>Food</li> <li>Milk</li> <li>Vodka</li> </ul> </div>, document.getElementById("root") );