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
C++
UTF-8
2,759
2.84375
3
[]
no_license
#include <iostream> #include <vector> #include <utility> #include <queue> #include <ctype.h> #include<string.h> #include <fstream> using namespace std; struct functie { char nodinitial; char nodfinal; char muchie; } v[30]; int main() { int n, m, i, j, dim, tip, numar, k=0;//TAB!!! char st; char l, s[100]; char x; ifstream fin("afd.txt"); //cout<<" nr de elem in multimea de stari"<<endl; fin>>n; //cout<<"dati elem din multimea de stari"<<endl; for(i=0; i<n; i++) fin>>st; //cout<<"dati nr de stari finale "; //cout<<endl; fin>>m; char f[20]; for (i=0; i<m; i++) f[i]='0'; for(i=0; i<m; i++) { //cout<<" o stare finala"<<endl; fin>>x; f[i]=x; } //cout<<"dati cardinalul functiei de tranzitie"<<endl; fin>>n; for(i=0; i<n; i++) { fin >> v[i].nodinitial >> v[i].nodfinal >> v[i].muchie; if(v[i].nodinitial >= 'a' && v[i].nodinitial <= 'z') tip = 1; else tip = 0 ; } int ok; int nr; char c; if(tip == 0)//nodurile sunt cifre { cout << "dati un nr care sa repr starea initiala q0"<<endl; cin >> nr; } else { cout << "dati o litera care sa repr starea initiala q0"<<endl; cin >> c; } cout << "dati cuvantul de verificat"<<endl; cin >> s; for(i=0; i < strlen(s); i++) { ok = 0; l = s[i]; if(l=='*') { cout << "cuvantul vid nu este acceptat"; return 0; } for(j=0; j< n; j++)//verific toate "perechile" din functie if(tip == 0)//nodurile sunt cifre { if(v[j].nodinitial-'0' == nr && v[j].muchie == l) { nr = v[j].nodfinal-'0';//actualizez punctul de inceput al urmatorului pas j = n; ok = 1; } } else //nodurile sunt litere if(v[j].nodinitial == c && v[j].muchie == l) { c = v[j].nodfinal; j = n; ok = 1; } if(ok == 0 ) { cout << "cuvant neacceptat, din cauza unei litere care nu se verifica"; return 0; } } for(i = 0; i < m; i++) if(tip == 0) if(nr == f[i]-'0') { cout << "cuvant acceptat"; return 0; } else if(c == f[i]) { cout << "cuvant acceptat"; return 0; } cout << "cuvant neacceptat, nu exista starea finala dorita"; fin.close(); return 0; }
C
UTF-8
461
2.609375
3
[]
no_license
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> struct sockaddr_in ip,ip2; int main() { char str[INET_ADDRSTRLEN]; inet_pton(AF_INET,"127.0.0.1",&ip.sin_addr); inet_ntop(AF_INET,&ip.sin_addr,str,INET_ADDRSTRLEN); printf("%s\n",str); ip2.sin_addr.s_addr = inet_addr("127.0.0.1"); printf("%d\n",ip.sin_addr.s_addr); inet_ntop(AF_INET,&ip2.sin_addr,str,INET_ADDRSTRLEN); printf("%s\n",str); }
TypeScript
UTF-8
6,090
2.515625
3
[]
no_license
import { ImageDataAccess } from "../dataAccess/imageAccess"; import { FeedDataAccess } from "../dataAccess/feedAccess"; import { FeedItem } from "../models/FeedItem"; import { CreateFeedItemRequest } from "../requests/CreateFeedItemRequest"; import { UpdateFeedItemRequest } from "../requests/UpdateFeedItemtRequest"; import { Comment } from "../models/Comment"; import { CommentDataAccess } from "../dataAccess/commentAccess"; import { CreateCommentRequest } from "../requests/CreateCommentRequest"; import { UpdateCommentRequest } from "../requests/UpdateCommentRequest"; import { LikeDataAccess } from "../dataAccess/likeAccess"; import { LikeRequest } from "../requests/LikeRequest"; import { Like } from "../models/Like"; const uuid = require('uuid'); const feedItemAccess = new FeedDataAccess(); const commentAccess = new CommentDataAccess(); const imageAccess = new ImageDataAccess(); const likeAccess = new LikeDataAccess(); export async function getAllFeedItems(userId: string): Promise<FeedItem[]> { var items = await feedItemAccess.getAllFeedItems(userId); items.map((item) => { if (item.url) { item.url = imageAccess.getGetSignedUrl(item.url); } }); return items; } export async function createFeedItem(userId: string, createFeedItemRequest: CreateFeedItemRequest): Promise<FeedItem> { const feedItemId = uuid.v4(); const feedItem: FeedItem = { userId: userId, feedItemId: feedItemId, likesCount: 0, commentsCount: 0, createdAt: new Date().toISOString(), ...createFeedItemRequest, }; const savedItem = await feedItemAccess.createFeedItem(feedItem); savedItem.url = imageAccess.getGetSignedUrl(feedItem.url); return savedItem; } export async function updateFeedItem(feedItemId: string, updateFeedItemRequest: UpdateFeedItemRequest): Promise<FeedItem> { const feedItem = await feedItemAccess.getFeedItemById(feedItemId); if (feedItem) { feedItem.caption = updateFeedItemRequest.caption; if (updateFeedItemRequest.url) { feedItem.url = updateFeedItemRequest.url; } feedItem.updatedAt = new Date().toISOString(); const updatedItem = await feedItemAccess.updateFeedItem(feedItem); updatedItem.url = imageAccess.getGetSignedUrl(feedItem.url); return updatedItem; } return feedItem; } export function getImageUploadUrl(fileName: string) { return imageAccess.getUploadUrl(fileName); } export async function deleteFeedItemById(feedItemId): Promise<boolean> { const feedItem = await feedItemAccess.getFeedItemById(feedItemId); if (!feedItem) { return false; } return await feedItemAccess.deleteFeedItem(feedItem); } export async function createComment(userId: string, commentRequest: CreateCommentRequest): Promise<FeedItem> { const feedItem = await feedItemAccess.getFeedItemById(commentRequest.feedItemId); if (feedItem) { const dateTimeNow = new Date().toISOString(); // Add comment const comment: Comment = { commentId: uuid.v4(), userId: userId, createdAt: dateTimeNow, ...commentRequest, } await commentAccess.createComment(comment); // Update comments count feedItem.commentsCount += 1; feedItem.updatedAt = dateTimeNow; return await feedItemAccess.updateFeedItem(feedItem); } return feedItem; } export async function getAllComments(feedItemId: string): Promise<Comment[]> { return await commentAccess.getAllComments(feedItemId); } export async function updateComment(commentId: string, updateCommentRequest: UpdateCommentRequest): Promise<Comment> { const comment = await commentAccess.getCommentById(commentId); if (comment) { comment.commentText = updateCommentRequest.commentText; comment.updatedAt = new Date().toISOString(); const updatedItem = await commentAccess.updateComment(comment); return updatedItem; } return comment; } export async function deleteCommentById(commentId): Promise<boolean> { // Get comment const comment = await commentAccess.getCommentById(commentId); if (comment) { // Delete comment await commentAccess.deleteComment(comment); const feedItem = await feedItemAccess.getFeedItemById(comment.feedItemId); if (feedItem) { // Update comments count feedItem.commentsCount -= 1; feedItem.updatedAt = new Date().toISOString();; await feedItemAccess.updateFeedItem(feedItem); return true; } } return false; } export async function createLike(userId: string, likeRequest: LikeRequest): Promise<FeedItem> { const feedItem = await feedItemAccess.getFeedItemById(likeRequest.feedItemId); if (feedItem) { const dateTimeNow = new Date().toISOString(); // Add like const like: Like = { userId: userId, likeId: uuid.v4(), createdAt: dateTimeNow, ...likeRequest }; await likeAccess.createLike(like); // Update likes count feedItem.likesCount += 1; feedItem.updatedAt = dateTimeNow; return await feedItemAccess.updateFeedItem(feedItem); } return feedItem; } export async function deleteLikeById(likeId): Promise<boolean> { // Get like const like = await likeAccess.getLikeById(likeId); if (like) { // Delete like await likeAccess.deleteLike(like); const feedItem = await feedItemAccess.getFeedItemById(like.feedItemId); if (feedItem) { // Update likes count feedItem.likesCount -= 1; feedItem.updatedAt = new Date().toISOString();; await feedItemAccess.updateFeedItem(feedItem); return true; } } return false; } export async function getAllLikes(feedItemId: string): Promise<Like[]> { return await likeAccess.getAllLikes(feedItemId); }
PHP
UTF-8
79
2.65625
3
[]
no_license
<?php require 'point.php'; $point = new Point(); $point = 3; echo $point; // 3
C#
UTF-8
1,294
2.65625
3
[]
no_license
using System; using System.Threading; using System.Threading.Tasks; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; using CloudMemos.Logic.Models; namespace CloudMemos.Logic.DataAccess { public class MemoRepository : IMemoRepository { private readonly IAmazonDynamoDB _dynamoDbClient; public MemoRepository(IAmazonDynamoDB dynamoDbClient) { _dynamoDbClient = dynamoDbClient; } public async Task<TextPieceEntity> Get(string id) { TextPieceEntity result; using (var context = new DynamoDBContext(_dynamoDbClient)) { var dbOperationConfig = new DynamoDBOperationConfig { ConsistentRead = true }; using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5))) { result = await context.LoadAsync<TextPieceEntity>(id, null, dbOperationConfig, cancellationTokenSource.Token); } } return result; } public async Task SaveAsync(TextPieceEntity entity) { using (var context = new DynamoDBContext(_dynamoDbClient)) { await context.SaveAsync(entity); } } } }
Java
ISO-8859-1
638
3.59375
4
[]
no_license
package br.edu.univas; import java.util.Scanner; public class Questao04 { public static void main(String[] args) { Scanner leia = new Scanner(System.in); System.out.println("Digite o 1 valor: "); int valor1 = leia.nextInt(); System.out.println("Digite o 2 valor: "); int valor2 = leia.nextInt(); int resto = valor1 % valor2; if(resto == 0) { System.out.println("A diviso de " + valor1 + " por " + valor2 + " perfeita"); }else { System.out.println("A diviso de " + valor1 + " por " + valor2 + " no perfeita, pos sobra " + resto); } leia.close(); } }
C#
UTF-8
488
3
3
[]
no_license
using System; namespace AbstractClass { class Program { /* abstract modifer -> indicate that class or member is missing implementation, Sealse modifer -> prrevent derivation of class and override of methhod. // on derived class like the circle */ static void Main(string[] args) { var circle = new Circle(); circle.Draw(); circle.Reset(); } } }
Markdown
UTF-8
857
2.625
3
[]
no_license
## 1. 全局安装 docsify-cli 工具 ``` npm i docsify-cli -g ``` ## 2. 初始化项目 ``` docsify init ./docs ``` ## 3. 本地预览 ``` docsify serve docs ``` ## 4. 手动初始化 - 如果不喜欢 npm 或者觉得安装工具太麻烦,我们可以直接手动创建一个 index.html 文件。 ```html <!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta charset="UTF-8"> <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/docsify/themes/vue.css"> </head> <body> <div id="app"></div> <script> window.$docsify = { //... } </script> <script src="//cdn.jsdelivr.net/npm/docsify/lib/docsify.min.js"></script> </body> </html> ``` 参考链接:[快速开始](https://docsify.js.org/#/zh-cn/quickstart)
Markdown
UTF-8
541
2.890625
3
[]
no_license
#### 1 组件创建 组件两种创建方式 1.函数创建 无状态 props通过参数形式接收 内部this undefined 没有生命周期 ```js function Xuxiaobing(){ return <div>徐晓冰</div> } ``` 2.类创建 有状态 属性通过 this.props 访问 内部this 指向当前组件 有生命周期 ```js class Xuxiaobing extends Component{ render(){ return <div>徐晓冰</div> } } ``` #### 2.组件关系 1.父子关系 2.子父关系 3.兄弟(并列关系) 4.嵌套关系
Shell
UTF-8
2,106
3.609375
4
[]
no_license
#!/bin/bash # Jacob Eaton - Dec 13th 2020 # Based on a script by James Chambers: https://github.com/TheRemote/RaspberryPiMinecraft # Terraria Server Stop Script # Check if server is running if ! screen -list | grep -q "terraria"; then echo "Server is not currently running!" exit 1 fi # Stop the server echo "Preparing to stop Terraria server..." screen -Rd terraria -X stuff "say Stopping the server in 1 minute...^M" echo "Stopping in 1 minute." sleep 50; screen -Rd terraria -X stuff "say Stopping the server in 10 seconds...^M" echo "Stopping in 10 seconds." sleep 1; screen -Rd terraria -X stuff "say Stopping the server in 9 seconds...^M" echo "Stopping in 9 seconds." sleep 1; screen -Rd terraria -X stuff "say Stopping the server in 8 seconds...^M" echo "Stopping in 8 seconds." sleep 1; screen -Rd terraria -X stuff "say Stopping the server in 7 seconds...^M" echo "Stopping in 7 seconds." sleep 1; screen -Rd terraria -X stuff "say Stopping the server in 6 seconds...^M" echo "Stopping in 6 seconds." sleep 1; screen -Rd terraria -X stuff "say Stopping the server in 5 seconds...^M" echo "Stopping in 5 seconds." sleep 1; screen -Rd terraria -X stuff "say Stopping the server in 4 seconds...^M" echo "Stopping in 4 seconds." sleep 1; screen -Rd terraria -X stuff "say Stopping the server in 3 seconds...^M" echo "Stopping in 3 seconds." sleep 1; screen -Rd terraria -X stuff "say Stopping the server in 2 seconds...^M" echo "Stopping in 2 seconds." sleep 1; screen -Rd terraria -X stuff "say Stopping the server in 1 second...^M" echo "Stopping in 1 second." sleep 1; screen -Rd terraria -X stuff "say Stopping the server now...^M" screen -Rd terraria -X stuff "off^M" # Wait up to 30 seconds for server to close StopChecks=0 while [ $StopChecks -lt 30 ]; do if ! screen -list | grep -q "terraria"; then break fi sleep 1; StopChecks=$((StopChecks+1)) done # Force quit if server is still open if screen -list | grep -q "terraria"; then echo "Terraria server still hasn't closed after 30 seconds, closing screen manually" screen -S minecraft -X quit fi echo "Terraria server stopped."
Python
UTF-8
2,617
2.625
3
[ "MIT" ]
permissive
# !/usr/bin/env python # -*- coding: utf-8 -*- """Define non-SI-units. This module provides for now 2 dictionnaries of units : - custom_units : for user-defined units - imperial_units : retard units TODO : - create a function wrapper for dict creation ? - Should custom units and constants be in the same module ? """ # setupe from math import pi from .quantity import make_quantity from .quantity import m, kg, s, A, K, cd, mol, rad, sr, SI_units, SI_units_prefixed, SI_derived_units, other_units, units cm = SI_units_prefixed["cm"] g = units['g'] h = units["h"] J = units["J"] W = units["W"] kJ = J * 1000 kJ.symbol = 'kJ' liter = units["L"] # Define here you custom units : key=symbol and value=quantity raw_custom_units = { } # imperial units from astropy. This is ridiculous... raw_imperial_units = { # LENGTHS "in": 2.54 * cm, "ft": 12 * 2.54 * cm, "yd": 3 * 12 * 2.54 *cm, "mi": 5280 * 12* 2.54*cm, "mil": 0.001 * 2.54 * cm, "NM": 1852 * m, "fur": 660 * 12 * 2.54 * cm, # AREAS "ac": 43560 * (12 * 2.54*cm)**2, # VOLUMES 'gallon': liter / 0.264172052, 'quart': (liter / 0.264172052) / 4, 'pint': ((liter / 0.264172052) / 4) / 2, 'cup': (((liter / 0.264172052) / 4) / 2) / 2, 'foz': ((((liter / 0.264172052) / 4) / 2) / 2) / 8, 'tbsp': (((((liter / 0.264172052) / 4) / 2) / 2) / 8) / 2, 'tsp': ((((((liter / 0.264172052) / 4) / 2) / 2) / 8) / 2) / 3, # MASS 'oz': 28.349523125 * g, 'lb': 16 * 28.349523125 * g, 'st': 14 * 16 * 28.349523125 * g, 'ton': 2000 * 16 * 28.349523125 * g, 'slug': 32.174049 * 16 * 28.349523125 * g, # SPEED 'kn': 1852 * m / h, # FORCE 'lbf': (32.174049 * 16 * 28.349523125 * g) * (12 * 2.54 * cm) * s**(-2), 'kip': 1000 * (32.174049 * 16 * 28.349523125 * g) * (12 * 2.54 * cm) * s**(-2), # ENERGY 'BTU': 1.05505585 * kJ, 'cal': 4.184 * J, 'kcal': 1000 * 4.184 * J, # PRESSURE 'psi': (32.174049 * 16 * 28.349523125 * g) * (12 * 2.54 * cm) * s**(-2) * (2.54 * cm) ** (-2), # POWER 'hp': W / 0.00134102209, # TEMPERATURE # not dealing with farheneiht unit } # custom units dict custom_units = {} for key, value in raw_custom_units.items(): custom_units[key] = make_quantity(value, symbol=key) # imperial unit dict imperial_units = {} for key, value in raw_imperial_units.items(): imperial_units[key] = make_quantity(value, symbol=key) # cleanup del pi del m, kg, s, A, K, cd, mol, rad, sr, SI_units, SI_units_prefixed, SI_derived_units, other_units, units del cm, g, h, J, W, kJ
Java
UTF-8
1,485
2.625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rs.ac.bg.fon.silab.gui.example1.components.table.model; import java.util.List; import javax.swing.table.AbstractTableModel; import rs.ac.bg.fon.silab.jdbc.example1.domen.TipProizvodaEntity; /** * * @author FON */ public class TipProizvodaTableModel extends AbstractTableModel { private final List<TipProizvodaEntity> lista; private String[] columnNames = new String[]{"ID", "Naziv tipa proizvoda"}; public TipProizvodaTableModel(List<TipProizvodaEntity> lista) { this.lista = lista; } @Override public int getRowCount() { return lista == null ? 0 : lista.size(); } @Override public int getColumnCount() { return 2; } @Override public Object getValueAt(int rowIndex, int columnIndex) { TipProizvodaEntity city = lista.get(rowIndex); switch (columnIndex) { case 0: return city.getIdTipaProizvoda(); case 1: return city.getNazivTipaProizvoda(); default: return "N/A"; } } @Override public String getColumnName(int column) { return columnNames[column]; } public void osvezi() { fireTableDataChanged(); } }
JavaScript
UTF-8
3,328
3.15625
3
[]
no_license
'use strict'; import {mapWith, compose} from '../../js-allonge/unsorted/unsorted' export default (() => { const filterPunctuation = str => str.replace(/[^0-9a-z]/gi, '') const reverse = function reverse(str) { return str .split('') .reverse() .join('') } const factorialize = function factorialize (num) { if (!num) return 1 else return num * factorialize(num - 1) } const palindrome = function palindrome (str) { let getRawChars = str => filterPunctuation(str).toLowerCase() return getRawChars(str) === getRawChars(reverse(str)) } const findLongestWord = function findLongestWord (str) { let sorted = str .split(' ') .map(filterPunctuation) .sort((a, b) => b.length - a.length) return sorted[0] ? sorted[0].length : 0 } const titleCase = function titleCase (str) { return str .toLowerCase() .split(' ') .map(w => { let firstLetter = w.length ? w[0].toUpperCase() : '' return w.replace(/^./, firstLetter) }) .join(' ') } const getLargestNum = (arr) => arr.reduce((p, n) => p > n ? p : n) const largestOfFour = mapWith(getLargestNum) const end = function end(str, ending) { return new RegExp(`${ending}$`, 'gi').test(str) } const repeat = function repeat(str, times) { if (times > 0) { return new Array(times+1).join(str) } else if (times < 0) { return '' } else { return str } } const truncate = function trunkate(str, limit, ending = '...') { if (str.length <= limit) return str return str .split('') .slice(0, limit > ending.length ? limit - ending.length : limit) .concat([ending]) .join('') } const chunk = function chunk (arr, size) { let result = [] let i = 0 while(true) { if (i > arr.length - 1) return result result.push(arr.slice(i, i+size)) i += size } } const slasher = function slasher(arr, startPoint) { return arr.slice(startPoint) } const mutation = function mutation([orig, test]) { let [lOrig, lTest] = [orig, test].map(x => x.toLowerCase()) return !lTest .split('') .filter(x => lOrig.indexOf(x) === -1) .length } const bouncer = function bouncer(arr) { return arr.filter(x => !!x) } const destroyer = function destroyer (arr, ...toRemove) { return arr.filter(x => toRemove.indexOf(x) === -1) } const where = function where (arr, val) { return arr .concat([val]) .sort((a,b) => a - b) .indexOf(val) } const rot13 = function rot13(str) { const ciphedChars = {start: 65, end: 90} //from A to Z const shift = 13 const {start, end} = ciphedChars let getChiphedFrom = (n) => { return n + shift > end ? n + shift - end + start - 1 : n + shift } return str .split('') .map(x => { let code = x.charCodeAt(0) return code >= start && code <= end ? String.fromCharCode(getChiphedFrom(code)) : x }) .join('') } return { reverse ,factorialize ,palindrome ,findLongestWord ,titleCase ,largestOfFour ,end ,repeat ,truncate ,chunk ,slasher ,mutation ,bouncer ,destroyer ,where ,rot13 } })()
C++
UTF-8
2,322
2.765625
3
[]
no_license
#include <iostream> #include <GL\freeglut.h> #include <glm\gtc\type_ptr.hpp> #include "Mesh.h" void Mesh::draw(glm::mat4& localToWorldMatrix) { if (vertices.size() == 0) { std::cout << "Mesh has no vertices!" << std::endl; return; } bool useColours = colours.size() > 0 ? true : false; bool useUVs = textureCoordinates.size() > 0 ? true : false; bool useNormals = normals.size() > 0 ? true : false; if (useUVs) if (textureCoordinates.size() != vertices.size()) { std::cout << "Number of texture coordinates does not match number of vertices!" << std::endl; return; } if (useColours) if (colours.size() != vertices.size()) { std::cout << "Number of vertex colours does not match number of vertices!" << std::endl; return; } if (useNormals) if (normals.size() != vertices.size()) { std::cout << "Number of vertex normals does not match number of vertices!" << std::endl; return; } glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1); glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 32); float dim[] = { 0.5F, 0.5F, 0.5F, 1 }; glLightfv(GL_LIGHT0, GL_DIFFUSE, dim); glLightfv(GL_LIGHT0, GL_DIFFUSE, dim); glLightfv(GL_LIGHT0, GL_SPECULAR, dim); float zero[] = { 0, 0, 0, 1 }; float amb[] = { 0.15, 0.15, 0.15, 1 }; float spec[] = { 0.2, 0.2, 0.2, 1 }; glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, zero); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, amb); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, spec); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(glm::value_ptr(localToWorldMatrix)); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD); if (primitiveType == PrimitiveType::Quads) glBegin(GL_QUADS); else glBegin(GL_TRIANGLES); for (unsigned int i = 0; i < vertices.size(); i++) { if (useUVs) glTexCoord2f(textureCoordinates[i].x, textureCoordinates[i].y); if (useColours) glColor4fv(&colours[i][0]); else glColor4f(0.8, 0.8, 0.8, 1.0); if (useNormals) glNormal3fv(&normals[i][0]); glVertex3fv(&vertices[i][0]); } glEnd(); glPopMatrix(); glDisable(GL_BLEND); glDisable(GL_LIGHTING); } void Mesh::setAllColours(glm::vec4 c) { for (auto& colour : colours) colour = c; }
Shell
UTF-8
1,895
2.890625
3
[]
no_license
#!/bin/bash LOG=/home/oracle/ilegra/scripts/dgdc2/logs/rebuild_dg_`date +%Y%m%d%H%M`.log echo "Starting Rebuild Standby Database for Dataguard at "`date +'%d/%m/%Y %H:%M'` >> $LOG echo "Shutdown Standby Varejo" >> $LOG . /home/oracle/varejo.env sqlplus -S / as sysdba <<EOF >> $LOG shutdown immediate; exit EOF echo "Shutdown Standby Orarec" >> $LOG . /home/oracle/orarec.env sqlplus -S / as sysdba <<EOF >>$LOG shutdown immediate; exit EOF echo "Dropping Standby Databases" >> $LOG . /home/oracle/crs.env asmcmd rm -rf '+ARCH/varejodc2/onlinelog/*' >> $LOG asmcmd rm -rf '+ARCH/varejodc2/archivelog/*' >> $LOG asmcmd rm -rf '+DATA/varejodc2/tempfile/*' >> $LOG asmcmd rm -rf '+DATA/varejodc2/controlfile/*' >> $LOG asmcmd rm -rf '+DATA/varejodc2/datafile/*' >> $LOG asmcmd rm -rf '+ARCH/orarecdc2/onlinelog/*' >> $LOG asmcmd rm -rf '+ARCH/orarecdc2/archivelog/*' >> $LOG asmcmd rm -rf '+DATA/orarecdc2/tempfile/*' >> $LOG asmcmd rm -rf '+DATA/orarecdc2/controlfile/*' >> $LOG asmcmd rm -rf '+DATA/orarecdc2/datafile/*' >> $LOG echo "Rebuilding Spfiles" asmcmd rm -rf '+DATA/orarecdc2/spfileorarecdc2.ora' >> $LOG . /home/oracle/orarec.env sqlplus -S / as sysdba <<EOF >> $LOG create spfile='+DATA/orarecdc2/spfileorarecdc2.ora' from pfile='/home/oracle/ilegra/files/initorarecdc2.ora'; exit EOF . /home/oracle/crs.env asmcmd rm -rf '+DATA/varejodc2/spfilevarejodc2.ora' >> $LOG . /home/oracle/varejo.env sqlplus -S / as sysdba <<EOF >> $LOG create spfile='+DATA/varejodc2/spfilevarejodc2.ora' from pfile='/home/oracle/ilegra/files/initvarejodc2.ora'; exit EOF echo "Putting standby databases in nomount" >> $LOG . /home/oracle/varejo.env sqlplus -S / as sysdba <<EOF >> $LOG startup nomount; exit EOF . /home/oracle/orarec.env sqlplus -S / as sysdba <<EOF >> $LOG startup nomount; exit EOF echo "Stopping Rebuild Standby Database for Dataguard at "`date +'%d/%m/%Y %H:%M'` >> $LOG
C++
UTF-8
751
3.203125
3
[]
no_license
#include <iostream> #include <vector> #include <cmath> int lengthOfCycle(int denom) { int rem = 1; std::vector<bool> rems(denom, false); rems[0] = true; int length = 0; while (true) { rem %= denom; if (rems[rem]) break; rems[rem] = true; rem *= 10; length++; } return length; } int main(int argc, char const *argv[]) { int maxLen = 0; int maxPos = 0; int limit = 1000; int tmpLen = 0; for (int i = 1; i < limit; ++i) { tmpLen = lengthOfCycle(i); if (tmpLen > maxLen) { maxPos = i; maxLen = tmpLen; } } std::cout << "Solution to PE 26: " << maxPos << std::endl; return 0; }
Python
UTF-8
2,144
2.546875
3
[]
no_license
import praw import datetime from praw.models import MoreComments import csv reddit = praw.Reddit(client_id = '1epYXaQUEU0ayA', client_secret = 'T7-VTUva1G-E_kGa8yHKZBOKJNvlpg', username = 'Saurabh_Joshi_24', password = 'your_password', user_agent = 'scrapper' ) # print(reddit.user.me()) subreddit = reddit.subreddit('wallstreetbets') hot_wallstreetbets = subreddit.hot(limit=15) data_lists = [] for posts in hot_wallstreetbets: if not posts.stickied: time = str(datetime.datetime.fromtimestamp(posts.created)) Author = str(posts.author) Title = str(posts.title) message = str(posts.media) replies = str(message) upvotes = str(posts.ups) downvotes = str(posts.downs) data = [time, Author, Title, message, upvotes, downvotes] data_lists.append(data) print('Inserting POST Records....') for comment in subreddit.comments(limit=None): time = str(datetime.datetime.fromtimestamp(comment.created_utc)) Author = str(comment.author) message = str(comment.body) replies = str(message) upvotes = str(comment.score) downvotes = str(comment.downs) data = [time, Author, Title, message, upvotes, downvotes] data_lists.append(data) print('|---------------------------------------------------------|') print('Inserting all the individual replies....') print('|---------------------------------------------------------|') with open('./Dataset/raw_dataset.csv', 'w', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(['Time', 'Author', 'Title', 'Replies', 'upvotes', 'downvotes']) #header for row in data_lists: writer.writerow(row) # with open('./Dataset/raw_dataset.txt', 'w', encoding='utf-8') as f: # writer = csv.writer(f) # writer.writerow(['Time', 'Author', 'Title', 'Replies\n', 'upvotes', 'downvotes']) #header # for row in data_lists: # f.write(" ".join(row))
TypeScript
UTF-8
1,933
2.609375
3
[]
no_license
import request from 'supertest'; import { app } from '../../app'; it('fails when an email that does not exist is supplied', async () => { await request(app) .post('/api/users/updatepassword') .set('Cookie', global.signin()) .send({ email: 'test@test.com', oldPassword: 'password', newPassword: '1234', }) .expect(400); }); it('fails when a different user tries change a password', async () => { const user = await request(app) .post('/api/users/signup') .send({ email: 'test@test.com', password: 'password', }) .expect(201); // console.log(user.get('Set-Cookie')); await request(app) .post('/api/users/updatepassword') .set('Cookie', global.signin()) .send({ email: 'test@test.com', password: 'asdfasdfasdfsdf', }) .expect(400); }); it('fails when insuffcient body parameters are provided', async () => { const user = await request(app) .post('/api/users/signup') .send({ email: 'test@test.com', password: 'password', }) .expect(201); // console.log(user.get('Set-Cookie')); await request(app) .post('/api/users/updatepassword') .set('Cookie', user.get('Set-Cookie')) .send({ email: 'test@test.com', password: 'asdfasdfasdfsdf', }) .expect(400); }); it('succeeds when changing the password', async () => { const user = await request(app) .post('/api/users/signup') .send({ email: 'test@test.com', password: 'password', }) .expect(201); // console.log(user.get('Set-Cookie')); await request(app) .post('/api/users/updatepassword') .set('Cookie', user.get('Set-Cookie')) .send({ email: 'test@test.com', oldPassword: 'password', newPassword: '1234', }) .expect(200); await request(app) .post('/api/users/signin') .send({ email: 'test@test.com', password: '1234', }) .expect(200); });
Java
UTF-8
2,819
2.640625
3
[]
no_license
package com.gupao.edu.vip.netty; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; /** * Created by QuZheng on 2018/11/9. */ public class NettyClient { private static final int nettyPort = 6666; private static final String nettyServer = "127.0.0.1"; public static Bootstrap bootstrap = getBootstrap(); public static Channel channel = getChannel(nettyServer, nettyPort); private static Bootstrap getBootstrap() { EventLoopGroup work = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(work) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8)); pipeline.addLast("edcoder", new StringEncoder(CharsetUtil.UTF_8)); pipeline.addLast("clientHandler", new TcpClientHanlder()); } }); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); return bootstrap; } private static Channel getChannel(String nettyServer, int nettyPort) { Channel channel = null; try { channel = bootstrap.connect(nettyServer, nettyPort).sync().channel(); } catch (InterruptedException e) { e.printStackTrace(); System.out.println(String.format("连接Server(IP[%s],PORT[%s])失败", nettyServer, nettyPort) + e.getLocalizedMessage()); return null; } return channel; } public static void sendMsg(String message) throws InterruptedException { if (channel != null) { channel.writeAndFlush(message).sync(); } else { System.out.println("连接尚未建立!"); } } public static void main(String[] args) { try { for (int i = 0; i < 1000; i++) { NettyClient.sendMsg(i + "你好1"); } } catch (Exception e) { e.printStackTrace(); } } }
SQL
UTF-8
2,298
4.125
4
[]
no_license
Create Database If Not Exists story_reading_website; use story_reading_website; Drop Table `account`; Create Table If Not Exists `account`( email nvarchar(50) primary key, `password` nvarchar(30) not null, last_name nvarchar(50), first_name nvarchar(50) ); Create Table If Not Exists `role`( email nvarchar(50), `role` nvarchar(50) check (`role` in ("admin", "user")) default "user", primary key(email, `role`), foreign key(email) references `account`(email) ); Drop Table genre; Create Table If Not Exists genre( id smallint primary key auto_increment, `name` nvarchar(100), `description` text ); Insert Into genre(`name`, `description`) Values("Other", "The genre that the story is not belong to any specific genre else!"); Create Table If Not Exists story( id varchar(36) primary key, `name` nvarchar(100), `description` text, author nvarchar(100), upload_time datetime, last_modified datetime, image_path varchar(100), num_chapters integer, genre_id smallint, rating float default 0 ); -- Drop table comment; -- Drop table reading_history; -- Drop table rating; -- Drop table story_chapter; -- drop table story; Create Table If Not Exists story_chapter( story_id varchar(36), title nvarchar(100), `index` integer, file_name varchar(50), -- format: <story id>_<chapter index>.pdf start_page integer, end_page integer, primary key(story_id, `index`), foreign key(story_id) references story(id) ); Create Table If Not Exists reading_history( story_id varchar(36), email nvarchar(50), reading_time datetime, chapter integer, primary key(story_id, email), foreign key(story_id) references story(id), foreign key(email) references `account`(email) ); Create table if not exists rating( story_id varchar(36), rate integer, email nvarchar(50), primary key(story_id, email), foreign key(story_id) references story(id), foreign key(email) references `account`(email) ); Create table if not exists `comment`( story_id varchar(36), chapter integer, `time` datetime, content text, email nvarchar(50) );
C++
BIG5
1,977
2.8125
3
[]
no_license
/** This source file is part of Forever * Copyright(c) 2012-2013 The DCI's Forever Team * * @file CActionEventHandler.h * @author Darren Chen (a) * @email darren.z32@msa.hinet.net * @date 2012/12/20 */ #ifndef _CACTIONEVENTHANDLER_H_ #define _CACTIONEVENTHANDLER_H_ #include "Common.h" #include "CActionEvent.h" /** @brief IJoʧ@ܪƥ */ class CActionEventHandler { public: CActionEventHandler(); ~CActionEventHandler(); /** @brief l * @param pTriggerEvent IJoʧ@ƥ * @param nextActionID U@Ӱʧ@ */ void init(CActionEvent *pTriggerEvent, int nextActionID); /** @brief oU@Ӱʧ@s * @return ʧ@s */ int getNextActionID(); /** @brief ˬdIJoƥO_PHandler۲ŦX * @param fPreTime W@ɶ * @param fCurTime ثeɶ * @param pEvent IJoʧ@ƥ * @param pKeyDownSet UC * @return true - ۲ŦXʧ@ * false - ŦXʧ@ */ bool check(float fPreTime, float fCurTime, CActionEvent *pEvent, std::set<int> *pKeyDownSet); void setUID(long long uid); void setMachineName(std::string machineName); /** @brief s * @param pFile ɮ */ void write(FILE *pFile); /** @brief Ū * @param pFile ɮ */ void read(FILE *pFile); private: friend class CActionEditorDlg; // \ʧ@s边Ӧs std::string m_machineName; // W (ΨѧOOP, ex: Client1 / Client2 / Client3 / GameServer1 / GameServer2 / WorldServer1) CActionEvent *m_pTriggerEvent; // IJoT int m_iNextActionID; // IJonYӰʧ@ long long m_uid; // aBǪBNPCߤ@s }; #endif // #ifndef _CACTIONEVENTHANDLER_H_
Java
UTF-8
2,535
3.5
4
[ "MIT" ]
permissive
import org.junit.Test; import java.util.Stack; import java.util.StringTokenizer; /** * Created by earayu on 2017/6/26. */ public class test { @Test public void test1() { System.out.println(infix2Pos("(a.b)|c")); } public static String infix2Pos(String exp) { StringBuffer postfix = new StringBuffer(); //�洢��������ջ Stack<Character> operatorStack = new Stack<Character>(); // ����������������ֿ� StringTokenizer tokens = new StringTokenizer(exp, "()*|.", true); // �׶�1: ɨ����Ŵ� while(tokens.hasMoreTokens()) { String token = tokens.nextToken(); if(token.charAt(0) == '|') { // Process all * , . in the top of the operator stack while(!operatorStack.isEmpty() && (operatorStack.peek() == '*' || operatorStack.peek() == '.')) { postfix.append(operatorStack.pop()); } // Push the | operator into the operator stack operatorStack.push(token.charAt(0)); } else if(token.charAt(0) == '.') { // Process all . in the top of the operator stack while (!operatorStack.isEmpty() && operatorStack.peek().equals('.')) { postfix.append(operatorStack.pop()); } // Push the . operator into the operator stack operatorStack.push(token.charAt(0)); } else if(token.charAt(0) == '*') { postfix.append(token.charAt(0)); } else if(token.charAt(0) == '(') { operatorStack.push(new Character('(')); // Push '(' to stack } else if(token.charAt(0) == ')') { // Process all the operators in the stack until seeing '(' while (!operatorStack.peek().equals('(')) { postfix.append(operatorStack.pop()); } operatorStack.pop(); } else { postfix.append(token); } } // �׶� 2: process all the remaining operators in the stack while(!operatorStack.isEmpty()) { postfix.append(operatorStack.pop()); } return postfix.toString(); } @Test public void testChar() { for(int i=0;i<255;i++) { System.out.print((char) i); } } }
Python
UTF-8
6,318
2.59375
3
[]
no_license
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # ============================================ # @Time : 2020/02/08 19:24 # @Author : WanDaoYi # @FileName : cnn_mnist_train.py # ============================================ from datetime import datetime import tensorflow as tf from config import cfg from core.common import Common from core.model_net import ModelNet class CnnMnistTrain(object): def __init__(self): # 模型保存路径 self.model_save_path = cfg.TRAIN.MODEL_SAVE_PATH self.log_path = cfg.LOG.LOG_SAVE_PATH self.learning_rate = cfg.TRAIN.LEARNING_RATE self.batch_size = cfg.TRAIN.BATCH_SIZE self.n_epoch = cfg.TRAIN.N_EPOCH self.data_shape = cfg.COMMON.DATA_RESHAPE self.data_resize = cfg.COMMON.DATA_RESIZE self.common = Common() self.model_net = ModelNet() # 读取数据和 维度 self.mnist_data, self.n_feature, self.n_label = self.common.read_data() # 创建设计图 with tf.name_scope(name="input_data"): self.x = tf.placeholder(dtype=tf.float32, shape=(None, self.n_feature), name="input_data") self.y = tf.placeholder(dtype=tf.float32, shape=(None, self.n_label), name="input_labels") with tf.name_scope(name="input_shape"): # 784维度变形为图片保持到节点 # -1 代表进来的图片的数量、28,28是图片的高和宽,1是图片的颜色通道 image_shaped_input = tf.reshape(self.x, self.data_shape) # 将 输入 图像 resize 成 网络所需要的大小 image_resize = tf.image.resize_images(image_shaped_input, self.data_resize) tf.summary.image('input', image_resize, self.n_label) self.keep_prob_dropout = cfg.TRAIN.KEEP_PROB_DROPOUT self.keep_prob = tf.placeholder(tf.float32) # 获取最后一层 lenet_5 的返回结果 self.result_info = self.model_net.lenet_5(image_resize, n_label=self.n_label, keep_prob=self.keep_prob_dropout) # 计算损失 with tf.name_scope(name="train_loss"): # 定义损失函数 self.cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.y * tf.log(self.result_info), reduction_indices=[1])) tf.summary.scalar("train_loss", self.cross_entropy) pass with tf.name_scope(name="optimizer"): self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.train_op = self.optimizer.minimize(self.cross_entropy) pass with tf.name_scope(name="accuracy"): self.correct_pred = tf.equal(tf.argmax(self.result_info, 1), tf.argmax(self.y, 1)) self.acc = tf.reduce_mean(tf.cast(self.correct_pred, tf.float32)) tf.summary.scalar("accuracy", self.acc) pass # 因为我们之前定义了太多的tf.summary汇总操作,逐一执行这些操作太麻烦, # 使用tf.summary.merge_all()直接获取所有汇总操作,以便后面执行 self.merged = tf.summary.merge_all() self.sess = tf.InteractiveSession() # 保存训练模型 self.saver = tf.train.Saver() # 定义两个tf.summary.FileWriter文件记录器再不同的子目录,分别用来存储训练和测试的日志数据 # 同时,将Session计算图sess.graph加入训练过程,这样再TensorBoard的GRAPHS窗口中就能展示 self.train_writer = tf.summary.FileWriter(self.log_path + 'train', self.sess.graph) self.test_writer = tf.summary.FileWriter(self.log_path + 'test') pass # 灌入数据 def feed_dict(self, train_flag=True): # 训练样本 if train_flag: # 获取下一批次样本 x_data, y_data = self.mnist_data.train.next_batch(self.batch_size) keep_prob = self.keep_prob_dropout pass # 验证样本 else: x_data, y_data = self.mnist_data.test.images, self.mnist_data.test.labels keep_prob = 1.0 pass return {self.x: x_data, self.y: y_data, self.keep_prob: keep_prob} pass def do_train(self): # 定义初始化 init = tf.global_variables_initializer() self.sess.run(init) test_acc = None for epoch in range(self.n_epoch): # 获取总样本数量 batch_number = self.mnist_data.train.num_examples # 获取总样本一共几个批次 size_number = int(batch_number / self.batch_size) for number in range(size_number): summary, _ = self.sess.run([self.merged, self.train_op], feed_dict=self.feed_dict()) # 第几次循环 i = epoch * size_number + number + 1 self.train_writer.add_summary(summary, i) if number == size_number - 1: # 获取下一批次样本 x_batch, y_batch = self.mnist_data.train.next_batch(self.batch_size) acc_train = self.acc.eval(feed_dict={self.x: x_batch, self.y: y_batch}) print("acc_train: {}".format(acc_train)) # 验证 方法二 两个方法,随便挑一个都可以的。 test_summary, acc_test = self.sess.run([self.merged, self.acc], feed_dict=self.feed_dict(False)) print("epoch: {}, acc_test: {}".format(epoch + 1, acc_test)) self.test_writer.add_summary(test_summary, epoch + 1) test_acc = acc_test pass save_path = self.model_save_path + "acc={:.6f}".format(test_acc) + ".ckpt" # 保存模型 self.saver.save(self.sess, save_path, global_step=self.n_epoch) self.train_writer.close() self.test_writer.close() pass if __name__ == "__main__": # 代码开始时间 start_time = datetime.now() print("开始时间: {}".format(start_time)) demo = CnnMnistTrain() demo.do_train() # 代码结束时间 end_time = datetime.now() print("结束时间: {}, 训练模型耗时: {}".format(end_time, end_time - start_time))
PHP
UTF-8
1,619
2.734375
3
[]
no_license
<?php namespace Framework\Controller; use Framework\Manager\TokenManager; class TokenController { private $tokendb; public function __construct() { $this->tokendb = new TokenManager; } public function __invoke() { // Generate token $token = uniqid(rand(), true); // Send token with Swiftmailer // // Get mailer informations $data = require __DIR__ . './../../config/mailer.php'; // Create the Transport $transport = (new \Swift_SmtpTransport($data['smtp'], 465, 'ssl')) ->setUsername($data['username']) ->setPassword($data['password']) ; // Create the Mailer $mailer = new \Swift_Mailer($transport); // Create a message $contact = 'Nouveau message du blog: le lien suivant vous permettra de réinitialiser votre mot de passe:' . ' <a href="http://blog/admin/forget/pswd?token=' . $token . '">Cliquez ici !</a></br> <p>Attention: lien valable pendant 15 minutes.</p>'; $message = (new \Swift_Message('Nouveau message')) ->setFrom([$data['from'] => 'Mon site-blog']) ->setTo($data['to']) ->setSubject('Réinitialisation mot-de-passe') ->setBody($contact, 'text/html'); // Send the message $result = $mailer->send($message); // Insert token in database $this->tokendb->createToken($token); header("refresh:3;url=/"); echo 'Courriel pour réinitialiser mot de passe envoyé. Redirection automatique vers l\'accueil.'; } }
Markdown
UTF-8
5,582
2.796875
3
[]
no_license
## How to Connect to an OpenvCloud Environment ### Introduction ![](AdminArchitecture.png) The core of an OpenvCloud environment is the **master cloud space**, which consist of the following virtual machines or Docker containers: - **ovc_git** holding all configuration of your environment - **ovc_master** controlling the environment based on information from **ovc_git** - **ovc_reflector** provides [reverse SSH connections](https://en.wikipedia.org/wiki/Reverse_connection) to the physical nodes - **ovc_proxy** running NGINX as a proxy for all port 80 and port 443 communications The master cloud space and its containers/virtual machines can run locally, close to the actual OpenvCloud physical nodes it controls or remotely, for instance in another OpenvCloud environment, such as at Mothership1.com. For each environment managed by Green IT Globe a master repository is maintained in the [github.com/0-complexity](https://github.com/0-complexity) or [github.com/gig-projects](https://github.com/gig-projects) GitHub organization. Access is of course restricted.As a partner or customer of Green IT Globe you might want to setup your own master repository, only accessible to your organization. On **ovc_git** the master repository is cloned, holding all configuration information, including all the keys in order to access all other Docker containers and/or virtual machines of the master cloud space of your OpenvCloud environment. So in order to access your OpenvCloud environment your GitHub user account should be granted access to the master repository in order to first clone the Git repository of your local machine, providing you the keys to access **ovc_git** and all other Docker containers and/or virtual machines in the master cloud space, and update the configuration, which you will be pushing back to the central GitHub repository, from where it gets in turn pulled to **ovc_git**, making your changes effective. ### Accessing ovc_git There are some prerequisites, all documented [here](preparing_before_connecting.md), explaining: - How to get access to GitHub - How to configure your GitHub accounts to use your personal SSH keys for authentication - How to install and configure git on your personal computer Your first step will be to clone the repository from GitHub to your local (virtual) machine: ``` git clone git@github.com:0-complexity/be-scale-1.git ``` If the repository was already cloned previously on your machines, pull the latest update from the directory where it was cloned previously: ``` git pull ``` Make sure the cloned keys file is protected, not accessible to other users, it should be ``-rw --- ---`` (600), not ``rw- r-- r--`` (644) for instance: ``` chmod 600 be-scale-1/keys/git_root ``` So you have the keys. Next you will need the IP address of **ovc_git**. The ip address (instance.param.ip) is typically (but not always) the same as the one that can be found in the **service.hrd** of `$name-of-your-env-repository$/services/openvcloud__git_vm__main`. Or in case **ovc_git** runs in a Docker container check the **service.hrd** of `$name-of-your-env-repository$/services/jumpscale__docker_client__main`. Since this address could be different, it's recommended to check with the administrator. So, for instance for an environment with the name `poc`: ``` cd poc/services/openvcloud__git_vm__main cat service.hrd instance.param.ip = '185.69.164.120' instance.param.recovery.passwd = '1piQpVVt6z4U' service.domain = 'openvcloud' service.installed.checksum = '87c2cf956d752bb9f9a8e485c383c39a' service.instance = 'main' service.name = 'git_vm' ``` In order to connect to **ovc_git**, using the **git_root** identity file (-i) for this environment, and including the -A option (best practice): ``` ssh root@185.69.164.120 -A -i keys/git_root root@ovcgit:~# ``` Or in case **ovc_git** runs in a Docker container: ``` ssh 10.54.16.7 -l root -A -p 2202 -i keys/git_root root@ovcgit:~# ``` Now that you are on **ovc_git** you can access **ovc_master** and the physical nodes from there, both discussed below. ### Accessing ovc_master from ovc_git Connecting to **ovc_master** from **ovc_git** is simple: ``` ssh master -A ``` ### Accessing physical nodes from ovc_git All IP addresses (instance.ip) of the physical nodes can be found on **ovc_git** in `$name-of-your-env-repository$/services/jumpscale__node.ssh__$name-of-physical-node$/service.hrd`. For instance for an physical node with the name `be-scale-1-01` in an environment with name `be-scale-1`: ``` cd /opt/code/git/openvcloudEnvironments/be-scale-1/services/jumpscale__node.ssh__be-scale-1-01 cat service.hrd instance.ip = '192.168.103.218' instance.jumpscale = 'False' instance.login = 'root' instance.password = instance.ssh.port = '21001' instance.ssh.shell = '/bin/bash -l -c' instance.sshkey = 'nodes' #optional category of service, default = app service.category = 'node' service.description = 'is a node running linux os' service.domain = 'jumpscale' service.installed.checksum = '85a4417a78f8acd43669a1f479bb17b0' service.instance = 'be-scale-1-01' service.name = 'node.ssh'root@ovcgit:/opt/code/git/openvcloudEnvironments/be-scale-1/services/jumpscale__node.ssh__be-scale-1-01# ``` Connecting from **ovc_git** to physical node be-scale-1-01 is as simple as: ``` ssh 192.168.103.218 ```
Java
UTF-8
767
1.835938
2
[]
no_license
package com.eleganzit.msafiridriver.activity; import android.graphics.Path; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.eleganzit.msafiridriver.R; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; public class DemoScreen extends AppCompatActivity implements OnMapReadyCallback{ MapView map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_screen); map=findViewById(R.id.map); } @Override public void onMapReady(GoogleMap googleMap) { } }
Go
UTF-8
1,586
2.828125
3
[]
no_license
package spider import( "bytes" "strings" "net/http" "strconv" "errors" "math/rand" "container/list" "golang.org/x/net/html" ) func autoID() string { prefix := "spider" id := prefix + strconv.Itoa(rand.Int()) return id } func IsHtml(data []byte) bool{ contentType := strings.ToLower(http.DetectContentType(data)) if strings.Index(contentType,"html" ) == -1 { return false } return true } func GetRedirectURL(data []byte) (redirects []string, err error) { if !IsHtml(data) { err = errors.New("it is not html") return } doc, err := html.Parse(bytes.NewReader(data)) if err != nil { return } q := list.New() q.PushBack(doc) for { if q.Len() == 0 { break } e := q.Front() q.Remove(e) node := e.Value.(*html.Node) for c := node.FirstChild; c != nil; c = c.NextSibling { if c.Type == html.ElementNode { q.PushBack(c) } } if node.Type == html.ElementNode{ if node.Data == "a" { for _,a := range node.Attr { if a.Key == "href" { redirects = append(redirects, a.Val) } } } else if node.Data == "img" { for _,a := range node.Attr { if a.Key == "src" { redirects = append(redirects, a.Val) } } } } } return }
Java
UTF-8
1,176
2.375
2
[]
no_license
package com.eniso.FileType; import com.eniso.Utils.Trait; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFShape; import org.apache.poi.xslf.usermodel.XSLFSlide; import org.apache.poi.xslf.usermodel.XSLFTextShape; /** * * @author Nasreddine */ public class CSVFiles implements MailList { protected File workFile; public CSVFiles() { workFile = null; } @Override public void setWorkFile(File newFile) { workFile = newFile; } @Override public Set<String> getList() { String line = ""; try { BufferedReader br = new BufferedReader(new FileReader(workFile)); Trait newTrait = new Trait(); while ((line = br.readLine()) != null) { newTrait.extractMails(line); } return newTrait.getEmails(); } catch (Exception e) { e.printStackTrace(); } return new HashSet<>(); } }
Python
UTF-8
1,396
4.25
4
[]
no_license
#subroutine to calculate number of stops between two stops on the victoria line def victoria_line(): victoria = ["Brixton", "Stockwell", "Vauxhall", "Pimlico", "Victoria", "Green Park", "Oxford Circus","Warren Street", "Euston","King's Cross","Highbury & Islington", "Finsbury Park","Seven Sisters","Tottenham Hale", "Blackhorse Road and Walthamstow Central"] #outputs all the stations for station in victoria: print("- " + station + "\n",end="") print() #validates station while True: start = input("Please enter your start station.\n> ") if start in victoria: break else: print("Please enter a valid station.") #validates station and makes sure it is not the same while True: end = input("Please enter your final station.\n> ") if end in victoria and end != start: break else: print("Please enter a valid station.") start_num = victoria.index(start) + 1 end_num = victoria.index(end) + 1 total_stops = 0 #calculates station difference if it goes past the end of the loop if end_num < start_num: total_stops = 15-start_num total_stops += end_num #subtracts the final stop total_stops -= 1 #calculates difference normally else: total_stops = end_num - start_num - 1 print("Total number of stops between {} and {} is {}".format(start,end,total_stops)) #main program victoria_line()
Python
UTF-8
347
2.515625
3
[]
no_license
#!/usr/bin/python import gi gi.require_version('Notify', '0.7') from gi.repository import Notify Notify.init("Hello world") tytul ="Cześć" zawart = "Cześć pytonie" #Hello = Notify.Notification.new("Hello world", "This is an example notification.", "dialog-information") Hello = Notify.Notification.new(tytul, zawart, "dialog-information") Hello.show()
C#
UTF-8
2,077
3.8125
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exception_Handling { class Program { static void Main(string[] args) { try { List<int> numbers = new List<int> {55, 42, 23, 60, 42, 20, 52, 6004}; Console.WriteLine("We have a list of numbers!\nPlease enter a number to divide each list item by:"); int divisor = Convert.ToInt32(Console.ReadLine()); foreach (int x in numbers) { int result = x / divisor; Console.WriteLine(x + " divided by " +divisor+ " equals " + result); } Console.ReadLine(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } finally { Console.WriteLine("\nWe have exited the try/catch block!"); Console.ReadLine(); } //try //{ // Console.WriteLine("Pick a number."); // int numberOne = Convert.ToInt32(Console.ReadLine()); // Console.WriteLine("Pick a second number"); // int numberTwo = Convert.ToInt32(Console.ReadLine()); // int numberThree = numberOne / numberTwo; // Console.WriteLine(numberOne + " divided by " + numberTwo + " is " + numberThree); // Console.ReadLine(); //} //catch (FormatException ex) //{ // Console.WriteLine("Please type a whole number"); //} //catch (DivideByZeroException ex) //{ // Console.WriteLine("Please don't divide by zero"); //} //catch (Exception) //{ // Console.WriteLine(ex.Message); //} //finally //{ // Console.ReadLine(); //} } } }
Java
UTF-8
504
1.851563
2
[]
no_license
package com.dao; import com.po.Good; import com.po.Good_tag; import com.po.Good_type; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; @Mapper public interface GoodDaos { List<Good> listGood(Map<String, Object> map); Integer CountGood(); Good ById(Integer id); Boolean upDate(Good good); List<Good> findAll(); Integer delete(Integer id); Integer addGood(Map<String, Object> map); }
Python
UTF-8
13,953
2.9375
3
[ "MIT" ]
permissive
# This is a work in progress and to hell with your warranty! # I wanted to use a Korg nanoKontrol2 as a joystick. Why? 'Cause buttons, dials & sliders for cheaper ($80 CDN). # This: http://www.korg.com/caen/products/computergear/nanokontrol2/ # To make this work we need to monitor the midi from the nanoKontrol2 and convert them in real time to a joystick output. # We can do that with FreePIE (Programmable Input Emulator): http://andersmalmgren.github.io/FreePIE/ # FreePIE converts that to an output for a virtual joystick. # For this we're using vJoy: http://vjoystick.sourceforge.net/site/ # vJoy only supports a limited number of axis which we want to use as sliders/dials and other inputs to games. # To make this all work, we're going to have to split layout of the nanoKontrol2 into multiple virtual joysticks. # 4 dials and 4 sliders on the left as a joystick (with some buttons?), 4 dials and 4 sliders on the right as a second joystick (with some buttons?). # A 3rd joystick could be used for all the "transport" buttons (forward, back, play, record, next track, etc). # All of this was coded in a brute force way because I am a noob at this. # Install vJoy. # Install FreePIE. # Install Korg Kontrol Editor. https://www.korg.com/us/support/download/software/0/159/1354/ # Starting with Korg Kontrol Editor. Run it and see if you can connect to the nanoKontrol2. This should bring up a "map" of the nanoKontrol2 and the Control Channels (CC#)'s. # Open vJoyConf. Create 2 joysticks. 1 has all the axis enables with 36 buttons. 2 has all the exis enabled with any number of buttons since they won't be used. # Open vJoy Monitor. # Copy/paste or open this code in/into FreePIE. Save it as a script, then press run. If it all works, you should be able to monitor the joystick outuput with vJoy's monitor program. def update(): diagnostics.watch(midi[0].data.channel) diagnostics.watch(midi[0].data.status) diagnostics.watch(midi[0].data.buffer[0]) diagnostics.watch(midi[0].data.buffer[1]) # Sliders and Dials and buttons on the left side of the nanoKontrol2 # Change the value after == to the Control Channel (CC#) you want as input from the nanoKontrol2 # Change the value after vJoy[0]. you want to be the button on your virtual joystick. # Change the value after vJoy[ for the virtual joystick you want to use [0] or [1] for example. #slider_1 if midi[0].data.buffer[0] == 0:#CC0 slide_1 = midi[0].data.buffer[0] == 0 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[0].x = slide_1; #dial_1 if midi[0].data.buffer[0] == 16:#CC16 dial_1 = midi[0].data.buffer[0] == 16 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[0].rx = dial_1; #Button S1 CC#32 if (midi[0].data.buffer[0] == 32) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(14,True) if (midi[0].data.buffer[0] == 32) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(14,False) #Button M1 CC#45 if (midi[0].data.buffer[0] == 48) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(13,True) if (midi[0].data.buffer[0] == 48) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(13,False) #Button R1 CC#64 if (midi[0].data.buffer[0] == 64) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(12,True) if (midi[0].data.buffer[0] == 64) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(12,False) #slider_2 if midi[0].data.buffer[0] == 1:#CC1 slide_2 = midi[0].data.buffer[0] == 1 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[0].y = slide_2; #dial_2 if midi[0].data.buffer[0] == 17:#CC17 dial_2 = midi[0].data.buffer[0] == 17 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[0].ry = dial_2; #Button S2 CC#33 if (midi[0].data.buffer[0] == 33) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(17,True) if (midi[0].data.buffer[0] == 33) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(17,False) #Button M3 CC#49 if (midi[0].data.buffer[0] == 49) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(16,True) if (midi[0].data.buffer[0] == 49) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(16,False) #Button R3 CC#65 if (midi[0].data.buffer[0] == 65) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(15,True) if (midi[0].data.buffer[0] == 65) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(15,False) #slider_3 if midi[0].data.buffer[0] == 2:#CC2 slide_3 = midi[0].data.buffer[0] == 2 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[0].z = slide_3; #dial_3 if midi[0].data.buffer[0] == 18:#CC18 dial_3 = midi[0].data.buffer[0] == 18 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[0].rz = dial_3; #Button S3 CC#34 if (midi[0].data.buffer[0] == 34) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(20,True) if (midi[0].data.buffer[0] == 34) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(20,False) #Button M3 CC#50 if (midi[0].data.buffer[0] == 50) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(19,True) if (midi[0].data.buffer[0] == 50) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(19,False) #Button R3 CC#66 if (midi[0].data.buffer[0] == 66) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(18,True) if (midi[0].data.buffer[0] == 66) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(18,False) #slider_4 if midi[0].data.buffer[0] == 3:#CC3 slide_4 = midi[0].data.buffer[0] == 3 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[0].slider = slide_4; #dial_4 if midi[0].data.buffer[0] == 19:#CC19 dial_4 = midi[0].data.buffer[0] == 19 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[0].dial = dial_4; #Button S4 CC#35 if (midi[0].data.buffer[0] == 35) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(23,True) if (midi[0].data.buffer[0] == 35) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(23,False) #Button M4 CC#51 if (midi[0].data.buffer[0] == 51) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(22,True) if (midi[0].data.buffer[0] == 51) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(22,False) #Button R4 CC#67 if (midi[0].data.buffer[0] == 67) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(21,True) if (midi[0].data.buffer[0] == 67) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(21,False) # Because vJoy only supports a total of 8 axis per joystick, we have to split up the slider and dials section into two halves. The second half will be on the second virtual joystick vJoy[1]. # Sliders and Dials and buttons on the right side of the nanoKontrol2 #slider_5 if midi[0].data.buffer[0] == 4:#CC4 slide_1 = midi[0].data.buffer[0] == 4 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[1].x = slide_1; #dial_5 if midi[0].data.buffer[0] == 20:#CC20 dial_1 = midi[0].data.buffer[0] == 20 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[1].rx = dial_1; # Since vJoy can handle 128 buttons, we'll keep all the mashable buttons on the nanoKontrol2 to virtual joystick 1 vJoy[0] #Button S5 CC#36 if (midi[0].data.buffer[0] == 36) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(26,True) if (midi[0].data.buffer[0] == 36) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(26,False) #Button M5 CC#52 if (midi[0].data.buffer[0] == 52) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(25,True) if (midi[0].data.buffer[0] == 52) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(25,False) #Button R5 CC#66 if (midi[0].data.buffer[0] == 68) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(24,True) if (midi[0].data.buffer[0] == 68) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(24,False) #slider_6 if midi[0].data.buffer[0] == 5:#CC5 slide_2 = midi[0].data.buffer[0] == 5 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[1].y = slide_2; #dial_6 if midi[0].data.buffer[0] == 21:#CC21 dial_2 = midi[0].data.buffer[0] == 21 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[1].ry = dial_2; #Button S6 CC#37 if (midi[0].data.buffer[0] == 37) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(29,True) if (midi[0].data.buffer[0] == 37) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(29,False) #Button M6 CC#53 if (midi[0].data.buffer[0] == 53) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(28,True) if (midi[0].data.buffer[0] == 53) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(28,False) #Button R6 CC#69 if (midi[0].data.buffer[0] == 69) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(27,True) if (midi[0].data.buffer[0] == 69) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(27,False) #slider_7 if midi[0].data.buffer[0] == 6:#CC6 slide_3 = midi[0].data.buffer[0] == 6 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[1].z = slide_3; #dial_7 if midi[0].data.buffer[0] == 22:#CC22 dial_3 = midi[0].data.buffer[0] == 22 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[1].rz = dial_3; #Button S7 CC#38 if (midi[0].data.buffer[0] == 38) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(32,True) if (midi[0].data.buffer[0] == 38) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(32,False) #Button M7 CC#54 if (midi[0].data.buffer[0] == 54) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(31,True) if (midi[0].data.buffer[0] == 54) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(31,False) #Button R7 CC#70 if (midi[0].data.buffer[0] == 70) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(30,True) if (midi[0].data.buffer[0] == 70) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(30,False) #slider_8 if midi[0].data.buffer[0] == 7:#CC7 slide_4 = midi[0].data.buffer[0] == 7 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[1].slider = slide_4; #dial_8 if midi[0].data.buffer[0] == 23:#CC23 dial_4 = midi[0].data.buffer[0] == 23 and filters.mapRange(midi[0].data.buffer[1], 0, 127, -17873, 17873) vJoy[1].dial = dial_4; #Button S8 CC#39 if (midi[0].data.buffer[0] == 39) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(35,True) if (midi[0].data.buffer[0] == 39) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(35,False) #Button M8 CC#55 if (midi[0].data.buffer[0] == 55) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(34,True) if (midi[0].data.buffer[0] == 55) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(34,False) #Button R8 CC#71 if (midi[0].data.buffer[0] == 71) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(33,True) if (midi[0].data.buffer[0] == 71) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(33,False) # the Korg nanoKontrol2 includes some transport buttons as well so we'll give them some allocations on virtual joystick 1 vJoy[0] as well # We'll leave virtual joystick button 12 ( vJoy[0].11 ) as a gap to keep the deliniation between trasnport buttons and the slider area clear. In truth, I'm too lazy to fix it now. # Button last Track CC#58 if (midi[0].data.buffer[0] == 58) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(0,True) if (midi[0].data.buffer[0] == 58) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(0,False) # Button next Track CC#59 if (midi[0].data.buffer[0] == 59) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(1,True) if (midi[0].data.buffer[0] == 59) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(1,False) # Button cycle CC#46 if (midi[0].data.buffer[0] == 46) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(2,True) if (midi[0].data.buffer[0] == 46) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(2,False) # Button set CC#60 if (midi[0].data.buffer[0] == 60) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(3,True) if (midi[0].data.buffer[0] == 60) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(3,False) # Button Left Marker CC#61 if (midi[0].data.buffer[0] == 61) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(4,True) if (midi[0].data.buffer[0] == 61) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(4,False) # Button Right Marker CC#62 if (midi[0].data.buffer[0] == 62) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(5,True) if (midi[0].data.buffer[0] == 62) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(5,False) # Button Rewind CC#43 if (midi[0].data.buffer[0] == 43) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(6,True) if (midi[0].data.buffer[0] == 43) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(6,False) # Button Fast Forward CC#44 if (midi[0].data.buffer[0] == 44) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(7,True) if (midi[0].data.buffer[0] == 44) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(7,False) # Button Stop CC#42 if (midi[0].data.buffer[0] == 42) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(8,True) if (midi[0].data.buffer[0] == 42) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(8,False) # Button Play CC#41 if (midi[0].data.buffer[0] == 41) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(9,True) if (midi[0].data.buffer[0] == 41) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(9,False) # Button Record CC#45 if (midi[0].data.buffer[0] == 45) and (midi[0].data.buffer[1] > 0): vJoy[0].setButton(10,True) if (midi[0].data.buffer[0] == 45) and (midi[0].data.buffer[1] < 127): vJoy[0].setButton(10,False) if starting: midi[0].update += update
JavaScript
UTF-8
1,332
3.265625
3
[]
no_license
function getData(countryname) { console.log(countryname.value) const url='https://restcountries.eu/rest/v2/name/'.concat(countryname.value); document.getElementById("container").innerHTML=''; fetch(url) .then(data => data.json()) .then(res =>{ console.log(res); res.forEach(temp=>{ let card = document.createElement("div"); let flag=document.createElement("img") flag.setAttribute('src',temp.flag); flag.setAttribute('height', '100px'); flag.setAttribute('width', '100px'); card.appendChild(flag); let name = document.createTextNode('Name:' + temp.name + ', '); card.appendChild(name); let nativeName = document.createTextNode('nativeName:' + temp.nativeName + ', '); card.appendChild(nativeName); let capital = document.createTextNode('capital:' + temp.capital+ ', '); card.appendChild(capital); let numericCode = document.createTextNode('numericCode:' + temp.numericCode+ ', '); card.appendChild(numericCode); let population = document.createTextNode('population:' + temp.population); card.appendChild(population); let container = document.querySelector("#container"); container.appendChild(card); }); }) .catch(err => console.log("Error:", err)); }
Python
UTF-8
2,198
2.5625
3
[ "BSD-3-Clause" ]
permissive
# -*- coding: utf-8 -*- ''' Xml data source ==================== Loads data from xml file. Usage : baf = bakfu.Chain().load('data.xml', file='./data.xml', query='//answer', processor=lambda x:x.text, targets_processor=lambda x:x.attrib['label'] ) .. automodule:: .. autoclass:: .. autoexception:: .. inheritance-diagram:: SimpleDataSource :parts: 5 :private-bases: ''' import codecs try: import lxml.etree except: pass import six from six.moves import cStringIO from bakfu.core.routes import register from bakfu.data.base import BaseDataSource @register('data.xml') class XmlDataSource(BaseDataSource): ''' Xml loader. ''' init_kwargs = ('file', 'query', 'processor', 'target_processor') def __init__(self, *args, **kwargs): super(XmlDataSource, self).__init__() filename = kwargs.get('file',None) if filename is None: raise Exception('No file specified') #parse file if six.PY2: text = open(filename).read() parser = lxml.etree.XMLParser(recover=True, encoding='utf-8') #xml = etree.fromstring(text, parser) xml = lxml.etree.parse(cStringIO(text)) else: text = open(filename).read().encode('utf-8') parser = lxml.etree.XMLParser(recover=True, encoding='utf-8') xml = lxml.etree.XML(text) #find data elements query_result = xml.xpath(kwargs['query']) processor = kwargs['processor'] self.data = [ (idx,processor(elt)) for idx,elt in enumerate(query_result) ] self._data = {'main_data':self.data,'data':self.data, 'data_source':self} if kwargs.get('target_processor', None) is not None: target_processor = kwargs['target_processor'] self.targets = [ target_processor(elt) for elt in query_result ] self._data['targets'] = self.targets self._data['labels'] = self.targets def run(self, caller, *args, **kwargs): return self
C++
UTF-8
9,270
2.546875
3
[]
no_license
#define _USE_MATH_DEFINES #include "opencv2/opencv.hpp" #include <iostream> #include <cstdlib> #include <cmath> #include <vector> #include <algorithm> #include <numeric> #include <map> #include <tuple> #define Inf 100000000 #ifndef NEW_SMC #define NEW_SMC namespace common { template<typename V> cv::Mat Img2Mat(std::vector<std::vector <std::vector <V> > > image, int height, int width) { cv::Mat output_color(height, width, CV_8UC3); for (int i = 0; i < 3; i++) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { output_color.at<cv::Vec3b>(y, x)[i] = cv::saturate_cast<uchar>(image[i][y][x]); } } } return output_color; } template<typename V> cv::Mat Img2Mat(std::vector<std::vector <V> > image, int height, int width) { cv::Mat output_color(height, width, CV_8UC1); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { output_color.at<uchar>(y, x) = cv::saturate_cast<uchar>(image[y][x]); } } return output_color; } template<typename V> void Mat2Img(cv::Mat mat, std::vector<std::vector <std::vector <V> > > &image) { for (int i = 0; i < 3; i++) { for (int y = 0; y < mat.size().height; y++) { for (int x = 0; x < mat.size().width; x++) { image[i][y][x] = cv::saturate_cast<uchar>(mat.at<cv::Vec3b>(y, x)[i]); } } } } template<typename V> void Mat2Img(cv::Mat mat, std::vector<std::vector <V> > &image) { for (int y = 0; y < mat.size().height; y++) { for (int x = 0; x < mat.size().width; x++) { image[y][x] = cv::saturate_cast<uchar>(mat.at<uchar>(y, x)); } } } /* -- WRITE function -- */ template<typename V> void write_img(char* name, std::vector<std::vector <std::vector <V> > > image, int height, int width) { cv::Mat output(height, width, CV_8UC3); printf("***** write function *****\n"); printf("HEIGHT %d, WIDTH %d, NAME %s\n", height, width, name); printf("\n"); output = Img2Mat(image, height, width); cv::imwrite(name, output); std::cout << "Write Success!" << std::endl; } template<typename V> void write_img(char* name, std::vector<std::vector <V> > image, int height, int width) { cv::Mat output(height, width, CV_8UC1); printf("***** write function *****\n"); printf("HEIGHT %d, WIDTH %d, NAME %s\n", height, width, name); printf("\n"); output = Img2Mat(image, height, width); cv::imwrite(name, output); std::cout << "Write Success!" << std::endl; } /* -- リサイズ -- */ template<typename V, typename H> void resize(std::vector<V>& vec, const H head) { vec.resize(head); } template<typename V, typename H, typename ... T> void resize(std::vector<V>& vec, const H& head, const T ... tail) { vec.resize(head); for (auto& v : vec) resize(v, tail...); } /* -- 最小値選択 -- */ template<typename T> int minidx(int num, std::vector<T> date, T *cost) { int idx; *cost = Inf; for (int i = 0; i < num; i++) { if (*cost>date[i]) { idx = i; *cost = date[i]; } } return idx; } template<typename V> std::vector<V> transposition(std::vector<V> image, int height, int width) { cv::Mat t = Img2Mat(image, height, width), temp; cv::transpose(t, temp); Mat2Img(temp, image); return image; } }; class PARAMETER { public: char *name; /* -- 入力画像の名前 -- */ char *Seam; /* -- 合計削除数 -- */ char *Cost; /* -- 使用したコスト関数 -- */ char *dir_img; /* -- 入力画像のディレクトリ -- */ char dir_res[100]; /* -- リサイズ画像のディレクトリ -- */ int seam_band; /* -- 帯状シーム幅(現状,水平方向,垂直方向ともに同一のパラメータに設定) -- */ int seam_x; /* -- 水平方向に何画素抜くか -- */ int seam_y; /* -- 垂直方向に何画素抜くか -- */ int band_cut; /* -- 帯状シーム縮小幅 -- */ int reduction_band_size; /* -- 帯状シーム縮小後の幅 -- */ int xy_max; /* -- 合計削除回数 -- */ int band_num; /* -- 現在の削除回数 -- */ int selected_y = 0; /* -- 縦方向の選択回数 -- */ int selected_x = 0; /* -- 横方向の選択回数 -- */ double fe_weight; /* -- FEの重み -- */ double re_weight; /* -- REの重み -- */ bool SEAMCARVING = false; PARAMETER() { std::cout << "PARAMETER Allocate!" << std::endl; } virtual ~PARAMETER() { std::cout << "PARAMETER Release!" << std::endl; } void write_param() { std::cout << "DIR_IMG : " << dir_img << std::endl; std::cout << "Seam : " << Seam << std::endl; std::cout << "Cost : " << Cost << std::endl; std::cout << "band : " << seam_band << " , cut : " << band_cut << " , reduction : " << reduction_band_size << std::endl; std::cout << "x : " << seam_x << " , y : " << seam_y << " , x + y : " << xy_max << std::endl; std::cout << "DCT_seam" << std::endl; } }; class IMG{ public: int channels; int org_width, r_width; int org_height, r_height; int size; std::vector<std::vector <std::vector <int> > > r_image, band_image; std::vector<std::vector <int> > process_image; IMG(PARAMETER *param){ cv::Mat img = cv::imread(param->dir_img, cv::IMREAD_UNCHANGED); if (img.data == NULL) { std::cerr << "Can\'t open !" << std::endl; exit(1); } printf("read image : rows = %d, cols = %d, channels = %d\n", img.rows, img.cols, img.channels()); r_height = org_height = img.rows; r_width = org_width = img.cols; channels = img.channels(); size = org_height > org_width ? org_height : org_width; common::resize(r_image, channels, size, size); common::resize(process_image, size, size); common::resize(band_image, channels, size, size); common::Mat2Img(img, r_image); printf("Read Success!\n"); } virtual ~IMG() { printf(" ------------------------------ Make Seam End! ------------------------------ \n\n"); } /* -- 3色を輝度値に変換 -- */ void convert(PARAMETER *param) { cv::Mat output_gray(r_height, r_width, CV_8U); cv::Mat output_color(r_height, r_width, CV_8UC3); output_color = common::Img2Mat(r_image, r_height, r_width); cv::cvtColor(output_color, output_gray, CV_BGR2GRAY); common::Mat2Img(output_gray, process_image); channels = 1; } }; class ENERGY { public: /* -- 帯状シーム領域のコスト -- */ std::vector<std::vector <std::vector <int> > > idct_luminance; /* -- 1次元DCTの計算用係数 -- */ std::vector<std::vector <double> > dct_coeff; std::vector<std::vector <double> > idct_coeff; /* -- 削除方向 -- */ int direction; // 1 : 縦方向,0 : 横方向 /* -- FE -- */ std::vector<std::vector <std::vector <double> > > fe; /* -- costmap -- */ std::vector<std::vector <double> > dpmap; std::vector<std::vector <double> > remap; std::vector<std::vector <double> > femap; std::vector<std::vector <int> > seam_path, seam_path_map, seam_pos_log; int cost[2]; ENERGY(PARAMETER *param, IMG *img) { common::resize(idct_luminance, img->size, img->size, param->reduction_band_size); common::resize(dct_coeff, param->seam_band, param->seam_band); common::resize(idct_coeff, param->reduction_band_size, param->reduction_band_size); common::resize(fe, img->size, img->size, 4); common::resize(dpmap, img->size, img->size); common::resize(femap, img->size, img->size); common::resize(remap, img->size, img->size); common::resize(seam_path, 2, img->size); common::resize(seam_path_map, img->size, img->size); common::resize(seam_pos_log, param->xy_max, img->size); std::cout << "ENERGY Allocate!" << std::endl; for (int u = 0; u < param->seam_band; u++) { for (int i = 0; i < param->seam_band; i++) { if (u == 0) { dct_coeff[u][i] = cos(M_PI * (2.0 * i + 1.0) * u / (2.0 * param->seam_band)) / sqrt(param->seam_band); if (u < param->reduction_band_size && i < param->reduction_band_size) idct_coeff[u][i] = cos(M_PI * (2.0 * i + 1.0) * u / (2.0 * param->reduction_band_size)) / sqrt(param->seam_band); } else { dct_coeff[u][i] = cos(M_PI * (2.0 * i + 1.0) * u / (2.0 * param->seam_band)) * sqrt(2.0) / sqrt(param->seam_band); if (u < param->reduction_band_size && i < param->reduction_band_size) idct_coeff[u][i] = cos(M_PI * (2.0 * i + 1.0) * u / (2.0 * param->reduction_band_size)) * sqrt(2.0) / sqrt(param->seam_band); } } } std::cout << "DCT coefficient Allocate" << std::endl; } virtual ~ENERGY() { std::cout << "ENERGY Release!" << std::endl; } }; template<typename V> std::vector<V> DCT_IDCT(std::vector<std::vector <V> > image, PARAMETER *param, ENERGY *emap, const int x, const int y) { // DCT double temp = 0.0; std::vector<double> RE_coeff(param->seam_band, 0.0); std::vector<V> IDCT_luminance; for (int u = 0; u < param->seam_band; u++) { //DCT係数 for (int i = 0; i < param->seam_band; i++) { RE_coeff[u] += image[y][x + i] * emap->dct_coeff[u][i]; } } for (int i = 0; i < param->reduction_band_size; i++) { //IDCTで帯状シームの縮小 for (int u = 0; u < param->reduction_band_size; u++) { temp += RE_coeff[u] * emap->idct_coeff[u][i]; } if (temp < 0) temp = 0.0; if (temp > 255) temp = 255; IDCT_luminance.push_back(temp + 0.5); //四捨五入 temp = 0.0; } return IDCT_luminance; } #endif
Python
UTF-8
679
2.765625
3
[]
no_license
from sklearn.tree import DecisionTreeClassifier import numpy as np from sklearn.datasets import load_digits digits = load_digits() X=digits.data Y=digits.target X_train = X[0:1200, :] X_test = X[1200:, :] Y_train = Y[0:1200] Y_test = Y[1200:] classifier = DecisionTreeClassifier(max_depth=20, min_samples_split=5, #random_state=123, max_features=None) classifier.fit(X_train, Y_train) prediction = classifier.predict(X_test) match = sum(prediction == Y_test) print("Classification rate: {0}/{1} ({2:.1f}%)".format(match, Y_test.shape[0], match/Y_test.shape[0]*100))
C++
UTF-8
2,917
3.671875
4
[]
no_license
/*职责链:使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合 关系,将这些对象形成一条链,并沿着这条链传递该请求,知道有一个对象处理它 为止*/ #include <iostream> using namespace std; typedef int Topic; const Topic NO_HELP_TOPIC = -1; const Topic PRINT_TOPIC = 1; const Topic PAPER_ORIENTATION_TOPIC = 2; const Topic APPLICATION_TOPIC = 3; //处理帮助请求的接口,维护一个帮助请求(缺省为空), //并保持对请求链中后继者的请求 class HelpHandler { public: HelpHandler(HelpHandler* h = 0, Topic t = NO_HELP_TOPIC) : _successor(h), _topic(t) { } virtual bool HasHelp() { return _topic != NO_HELP_TOPIC; } virtual void SetHandler(HelpHandler* h, Topic t) { _successor = h; _topic = t; } //处理请求,可被子类重定义 virtual void HandleHelp() { if (_successor != 0) _successor->HandleHelp(); } private: HelpHandler *_successor; Topic _topic; }; //窗口组件的基类,所有的用户界面元素都可有相关的帮助 class Widget : public HelpHandler { protected: Widget(Widget* parent, Topic t = NO_HELP_TOPIC) : HelpHandler(parent, t) { _parent = parent; } private: Widget* _parent; }; //按钮是链上的第一个请求者 class Button : public Widget { public: //一个是包含它的窗口的组件的引用和其自身的帮助请求 Button(Widget* d, Topic t = NO_HELP_TOPIC) : Widget(d, t) {} //重写该函数:如果本身有help,则直接演示,否则调用HelpHandler //的操作将该请求转发给它的后继者 void HandleHelp() { if (HasHelp()) cout << "Button Help" << endl; else HelpHandler::HandleHelp(); } }; class Dialog : public Widget { public: //后继者不是一个窗口组件而是任意的帮助请求处理对象 Dialog(HelpHandler* h, Topic t = NO_HELP_TOPIC) : Widget(0) { SetHandler(h, t); } void HandleHelp() { if (HasHelp()) cout << "Dialog Help" << endl; else HelpHandler::HandleHelp(); } }; //链的末端是Application的实例 class Application : public HelpHandler { public: Application(Topic t) : HelpHandler(0, t) {} void HandleHelp() { cout << "剩下所有的帮助主题" << endl; } }; int main() { Application* app = new Application(APPLICATION_TOPIC); Dialog* dialog = new Dialog(app, PRINT_TOPIC); Button* button = new Button(dialog, PAPER_ORIENTATION_TOPIC); button->HandleHelp(); button = new Button(dialog); button->HandleHelp(); dialog = new Dialog(app); button = new Button(dialog); button->HandleHelp(); return 0; }
JavaScript
UTF-8
1,299
3.109375
3
[]
no_license
/* Swich'as panasu kaip if'as tik jis lygina: tik lygu/nelygu. (Tuo metu if gali palyginti ir dar daugiau/maziau)*/ /* Console visada spausdina atsakyma iki kol pasiekia break */ const darzove = 'morka'; switch(darzove) { case 'morka': console.log('Labai gerai tavo regejimui'); break; case 'bulve': console.log('Darzoviu duona?..'); break; case 'pomidoras': console.log('Stroraraudonaskruostis'); break; default: console.log("Neatitiko jokios darzoves"); break; } /* KADA SWICH'e NEREIKIA KAS KIEKVIENU CASE NAUDOTI BREAK. Kai uzdavinys yra apie darbo procesa ir galimybe ji perrimti kazkuriame proceso zingsnyje */ /* PROCESAS: rytinio gerimo gamyba. -pasiimti puodeli -isideti kavos -isideti saldiklio -ipilti karsto vandens -ismaisyti -gerti */ const etapas = 'puodelis'; switch (etapas) { case 'puodelis': console.log('1) pasiimti puodeli'); case 'puodelis': console.log('2) isideti kavos'); case 'puodelis': console.log('3) isideti saldiklio'); case 'puodelis': console.log('4) isipilti karsto vandens'); case 'puodelis': console.log('5) issimaisyti'); case 'puodelis': console.log('6) galima gerti'); break; default: console.log('nezinomas veiksmas'); }
C++
UTF-8
2,015
3.75
4
[]
no_license
#include <iostream> using namespace std; struct stack{ int element[50]; int size; int top; }; void push(int x,struct stack &S){ if(S.top == S.size){cout << "The stack is full." << endl;} else{ S.top++; S.element[S.top] = x; } } int pop(struct stack &S){ if(S.top == -1){cout } << "The stack is empty" << endl;return -1;} else{ return S.element[S.top--]; } } int peek(struct stack &S){ if(S.top == -1){cout << "The stack is empty" << endl;return -1;} else{ return S.element[S.top]; } } int main(){ struct stack S1; S1.top = -1; S1.size = 50; struct stack S2; S2.top = -1; S2.size = 50; cout << "Enter the number of elements." << endl; int n; cin >> n; cout << "Enter the value of elements." << endl; int a[n]; for(int i=0;i<n;i++){ cin >> a[i]; push(a[i],S1); } int flag =0; for(int i=0;i<n;i++){ if(i%2 == 0){ while(S1.top != -1){ int x = pop(S1); if(S2.top == -1){push(x,S2);} else{ if(peek(S2) > x){ int t = pop(S2); push(x,S2); push(t,S2); } else{push(x,S2);} } } a[n-1-i] = pop(S2); } else{ while(S2.top != -1){ int x = pop(S2); if(S1.top == -1){push(x,S1);} else{ if(peek(S1) > x){ int t = pop(S1); push(x,S1); push(t,S1); } else{push(x,S1);} } } a[n-1-i] = pop(S1); } } for(int i=0;i<n;i++){ cout << a[i] << " " ; } return 0; }
JavaScript
UTF-8
2,601
3.359375
3
[]
no_license
import React, { useState, useEffect } from 'react'; import shuffle from 'lodash.shuffle'; import './App.css'; // image for the pokemon // https://pokeres.bastionbot.org/images/pokemon/${pokemon.id}.png const pokemon = [ { id: 4, name: 'charizard' }, { id: 10, name: 'caterpie' }, { id: 77, name: 'ponyta' }, { id: 108, name: 'lickitung' }, { id: 132, name: 'ditto' }, { id: 133, name: 'eevee' }, ]; const doublePokemon = shuffle([...pokemon, ...pokemon]); export default function App() { const [opened, setOpened] = useState([]); // using index const [matched, setMatched] = useState([]); // pokemon.id const [moves, setMoves] = useState(0); // check if there is a match // if there are 2 in the opened array, check if they match useEffect(() => { if (opened.length < 2) return; const firstPokemon = doublePokemon[opened[0]]; const secondPokemon = doublePokemon[opened[1]]; if (firstPokemon.name === secondPokemon.name) setMatched((matched) => [...matched, firstPokemon.id]); }, [opened]); // clear cards after 2 have been selected useEffect(() => { if (opened.length === 2) setTimeout(() => setOpened([]), 800); }, [opened]); // check if there is a winner useEffect(() => { if (matched.length === pokemon.length) alert('you won!'); }, [matched]); function flipCard(index) { setMoves((moves) => moves + 1); setOpened((opened) => [...opened, index]); } return ( <div className="app"> <p> {moves} <strong>moves</strong> </p> <div className="cards"> {doublePokemon.map((pokemon, index) => { let isFlipped = false; // do some logic to check if flipped if (opened.includes(index)) isFlipped = true; if (matched.includes(pokemon.id)) isFlipped = true; return ( <PokemonCard key={index} index={index} pokemon={pokemon} isFlipped={isFlipped} flipCard={flipCard} /> ); })} </div> </div> ); } function PokemonCard({ index, pokemon, isFlipped, flipCard }) { return ( <button className={`pokemon-card ${isFlipped ? 'flipped' : ''}`} onClick={() => flipCard(index)} > <div className="inner"> <div className="front"> <img src={`https://pokeres.bastionbot.org/images/pokemon/${pokemon.id}.png`} alt={pokemon.name} width="100" /> </div> <div className="back">?</div> </div> </button> ); }
Java
UTF-8
743
3.59375
4
[]
no_license
package java2blog.DynamicProgramming; import java.util.Scanner; public class LongestCommonSubs { public static void main(String[] args) { Scanner scn = new Scanner(System.in); System.out.println("Enter the 1st word: "); String A = scn.nextLine(); System.out.println("Enter the 2nd word: "); String B = scn.nextLine(); System.out.println(LCS(A, B)); } public static int LCS(String A, String B) { if(A.length()==0||B.length()==0) { return 0; } String remA = A.substring(1); String remB = B.substring(1); if(A.charAt(0)==B.charAt(0)) { int remRes = LCS(remA, remB); return 1 + remRes; } else { int remRes = Math.max(LCS(remA, B), LCS(A, remB)); return remRes; } } }
Java
UTF-8
4,020
3.46875
3
[]
no_license
import java.util.Scanner; public class HW_Edition { // Design a program for a grocery store. Ask at least 3 items id and quantity to user public static void main(String[] args) { Scanner myCart = new Scanner(System.in); System.out.println("\t \t id prices: \n"); System.out.println("\t \t 123:$2.49 \n"); System.out.println("\t \t 124:$4.79 \n"); System.out.println("\t \t 125:$1.65 \n"); System.out.println("\t \t 126:$7.88 \n"); System.out.println("\t \t 127:$0.99 \n"); System.out.println("Please enter item ID of the 1st item:\n"); int itemId1; itemId1 = myCart.nextInt(); System.out.println("Please enter quantity:\n"); int quantity1; quantity1 = myCart.nextInt(); System.out.println("Please enter item ID of the 2nd item:\n"); int itemId2; itemId2 = myCart.nextInt(); System.out.println("Please enter quantity:\n"); int quantity2; quantity2 = myCart.nextInt(); System.out.println("Please enter item ID of the 3rd item:\n"); int itemId3; itemId3 = myCart.nextInt(); System.out.println("Please enter quantity:\n"); int quantity3; quantity3 = myCart.nextInt(); // Cost double cost123 = 2.49; double cost124 = 4.79; double cost125 = 1.65; double cost126 = 7.88; double cost127 = 0.99; double result123; double result124; double result125; double result126; double result127; double result223; double result224; double result225; double result226; double result227; double result323; double result324; double result325; double result326; double result327; System.out.println("item id \t quantity \t price"); System.out.println("------------------------------"); System.out.println(itemId1); System.out.println(itemId2); System.out.println(itemId3); System.out.println(quantity1); System.out.println(quantity2); System.out.println(quantity3); //itemId1 if (itemId1 == 123) { System.out.println(result123 = quantity1*cost123); } if (itemId1 == 124) { System.out.println(result124 = quantity1*cost124); } if (itemId1 == 125) { System.out.println(result125 = quantity1*cost125); } if (itemId1 == 125) { System.out.println(result125 = quantity1*cost125); } if (itemId1 == 126) { System.out.println(result126 = quantity1*cost126); } if (itemId1 == 127) { System.out.println(result127 = quantity1*cost127); } //itemId2 if (itemId2 == 123) { System.out.println(result223 = quantity2*cost123); } if (itemId2 == 124) { System.out.println(result224 = quantity2*cost124); } if (itemId2 == 125) { System.out.println(result225 = quantity2*cost125); } if (itemId2 == 126) { System.out.println(result226 = quantity2*cost126); } if (itemId2 == 127) { System.out.println(result227 = quantity2*cost127); } //itemId3 if (itemId3 == 123) { System.out.println(result323 = quantity3*cost123); } if (itemId3 == 124) { System.out.println(result324 = quantity3*cost124); } if (itemId3 == 125) { System.out.println(result325 = quantity3*cost125); } if (itemId3 == 126) { System.out.println(result326 = quantity3*cost126); } if (itemId3 == 127) { System.out.println(result327 = quantity3*cost127); } } }
Ruby
UTF-8
1,642
2.65625
3
[]
no_license
# == Schema Information # # Table name: sales # # id :bigint not null, primary key # created_at :datetime not null # updated_at :datetime not null # pos_datetime :datetime not null # pos_total :float not null # pos_fiscal_number :string not null # class Sale < ApplicationRecord def self.amount_in_last_days(num) Sale.where('pos_datetime > ?', num.days.ago).sum(:pos_total) end def self.uah_per_day Sale.group_by_day(:pos_total).count end def self.per_day Sale.group_by_day(:pos_datetime).count end def self.per_hour Sale.group_by_hour(:pos_datetime).count.select { |_, v| v.positive? } end def self.per_week Sale.group_by_week(:pos_datetime).count end def self.day_count unique_dates = Set.new Sale.distinct(:pos_datetime).pluck(:pos_datetime).each do |date| unique_dates.add(date.to_s.split(' ')[0]) end unique_dates.size end def self.average_sale_during_time total_hours = Sale.group_by_day(:pos_datetime).count.length / 8 sales_per_day = SaleItem.joins(:sale).group_by_hour_of_day(:pos_datetime, series: false).count sales_per_day.map {|k, v| [k, v / total_hours]}.to_h.reject {|k, v| v < 1} end has_many :sale_items, dependent: :destroy validates :pos_total, presence: true validates :pos_datetime, presence: true validates :pos_fiscal_number, presence: true, uniqueness: true def final_sale_price recipe.sale_price - discounted_amount end def discounted_amount (discount_percentage || 0) * recipe.sale_price end end
PHP
UTF-8
2,653
2.875
3
[]
no_license
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of sweetDB * * @author Paula */ class sweetDB { public static function get_sweetTypes(){ $db = DatabaseConnection::getDB(); $query = 'SELECT * from sweetstype'; $statement = $db->prepare($query); $statement->execute(); $results = $statement->fetchAll(); $statement->closeCursor(); if(!empty($results)) { foreach($results as $result) { $s = new sweetType; $s->setSweetTypeID($result['sweetTypeID']); $s->setSweetTypeName($result['sweetTypeName']); $sweetType[] = $s; } return $sweetType; } else { return null; } } public static function get_sweetsType($sweetTypeID){ $db = DatabaseConnection::getDB(); $query = ' SELECT * FROM sweets INNER JOIN sweetstype ON sweets.sweetTypeID = sweetstype.sweetTypeID WHERE sweets.sweetTypeID = :sweetTypeID'; $statement = $db->prepare($query); $statement->bindValue(':sweetTypeID', $sweetTypeID); $statement->execute(); $result = $statement->fetchAll(); $statement->closeCursor(); return $result; } public static function getSweetView($sweetsID) { $db = DatabaseConnection::getDB(); $query = 'SELECT * FROM sweets Where sweetsID = :sweetsID'; $statement = $db->prepare($query); $statement->bindValue(':sweetsID', $sweetsID); $statement->execute(); $result = $statement->fetch(); $statement->closeCursor(); return $result; } public static function getAllEvents() { $db = DatabaseConnection::getDB(); $query = 'SELECT * FROM events'; $statement = $db->prepare($query); $statement->execute(); $results = $statement->fetchAll(); $statement->closeCursor(); return $results; } public static function getEvent($event_id) { $db = DatabaseConnection::getDB(); $query = 'SELECT * FROM events Where eventID = :eventID'; $statement = $db->prepare($query); $statement->bindValue(':eventID', $event_id); $statement->execute(); $result = $statement->fetch(); $statement->closeCursor(); return $result; } }
Python
UTF-8
820
3
3
[]
no_license
from __future__ import print_function from hamming_distance.hamming_distance import hamming_distance def approx_pattern_count(text, pattern, d): count = 0 pattern_len = len(pattern) for i in range(len(text) - (pattern_len-1)): substr = text[i:i+pattern_len] if hamming_distance(pattern, substr) <= d: count += 1 return count if __name__ == '__main__': p = 'TACAG' t = 'GAATCCGCCAAGTACCAAGATGTAAGTGAGGAGCGCTTAGGTCTGTACTGCGCATAAGCCTTAACGCGAAGTATGGATATGCTCCCCGGATACAGGTTTGGGATTTGGCGGTTACCTAAGCTAACGGTGAGACCGATATGACGAGGTTCCTATCTTAATCATATTCACATACTGAACGAGGCGCCCAGTTTCTTCTCACCAATATGTCAGGAAGCTACAGTGCAGCATTATCCACACCATTCCACTTATCCTTGAACGGAAGTCTTATGCGAAGATTATTCTGAGAAGCCCTTGTGCCCTGCATCACGATTTGCAGACTGACAGGGAATCTTAAGGCCACTCAAA' d = 2 print(approx_pattern_count(t, p, d))
Java
UTF-8
878
3.0625
3
[]
no_license
import static java.lang.Character.toUpperCase; public enum Command { MOVE_BACKWARDS { @Override Rover executeOn(Rover rover) { return rover.moveBackward();} }, TURN_RIGHT { @Override Rover executeOn(Rover rover) { return rover.turnRight(); }}, TURN_LEFT { @Override Rover executeOn(Rover rover) { return rover.turnLeft(); } }, MOVE_FORWARD { @Override Rover executeOn(Rover rover) { return rover.moveForward(); } }, UNKNOWN { @Override Rover executeOn(Rover rover) { return rover; } }; abstract Rover executeOn(Rover rover); public static Command fromChar(char commandChar) { switch(toUpperCase(commandChar)){ case 'F' : return MOVE_FORWARD; case 'B' : return MOVE_BACKWARDS; case 'L' : return TURN_LEFT; case 'R' : return TURN_RIGHT; default : return UNKNOWN; } } }
TypeScript
UTF-8
1,904
3.09375
3
[]
no_license
// #region TYPES export const PUSH_ERROR = 'error/push'; export const SHIFT_ERROR = 'error/shift'; export interface Error { name: string; message: string; type: string; } export type ErrorState = Error[]; export interface ErrorPushAction { type: typeof PUSH_ERROR; payload: Error; } export interface ErrorShiftAction { type: typeof SHIFT_ERROR; payload: never; } // #endregion const initialSate: ErrorState = []; function normalize(payload: Error): Error { switch (payload.type) { case 'timeout': case 'syncError': return { ...payload, name: 'Timeout Error', message: 'Our server has closed the connection. You can not continue.', }; case 'wrong-protocol': case 'wrong-subprotocol': return { ...payload, name: 'Protocol Error', message: 'Saving is not working. Please reload the page.', }; case 'denied': case 'wrong-credentials': return { ...payload, name: 'Access Denied', message: 'Our server has rejected your request.', }; case 'bruteforce': case 'error': case 'wrong-format': case 'unknown-message': return { ...payload, name: 'Server error', message: 'Sorry, we have not saved your changes.', }; default: return payload; } } function concat(state: ErrorState, action: ErrorPushAction): ErrorState { const nextError = normalize(action.payload); return state.filter(({ message }) => message !== nextError.message).concat(nextError); } export default function error( state: ErrorState = initialSate, action: ErrorPushAction | ErrorShiftAction, ): ErrorState { switch (action.type) { case PUSH_ERROR: return concat(state, action); case SHIFT_ERROR: { const [, ...nextState] = state; return nextState; } default: return state; } }
Markdown
UTF-8
1,987
3.59375
4
[]
no_license
# problem >Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times. Example 1: ``` Input: s = "aaabb", k = 3 Output: 3 The longest substring is "aaa", as 'a' is repeated 3 times. ``` Example 2: ``` Input: s = "ababbc", k = 2 Output: 5 The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times. ``` # codes ``` class Solution { public: int longestSubstring(string s, int k) { int hash[26]={0}; int res=0; unordered_set<char> filter; for(auto c:s){ hash[c-'a']++; } for(int i=0;i<26;i++){ if(hash[i]>0&&hash[i]<k){ filter.insert(i+'a'); } } if(filter.empty()){ return s.size(); } if(filter.size()==s.length()){ return 0; } int left=0; int right=0; int n=s.length(); while(left<n&&right<n){ while(left<n&&filter.find(s[left])!=filter.end()){ left++; } right=left+1; while(right<n&&filter.find(s[right])==filter.end()){ right++; } res=max(res,longestSubstring(s.substr(left,right-left),k)); left=right; } return res; } }; ``` # analysis >这道题目用了filter集合用来存储频率<k的字符,这样我们就判断一个子字符串里面是否包含这些字符来判断是否是合法的,如果包含,则不合法,如果不包含,则合法。为什么需要递归呢? 看看下面的样例,如果递归的话,则长度为5,实际上为0,这是因为有c字符干扰的缘故。 ``` ababacb 3 ``` # reference [395. Longest Substring with At Least K Repeating Characters][1] [1]: https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/122969/C++-4ms
Java
UTF-8
415
2.203125
2
[]
no_license
package com.teamtrouble.choresapplication.web.service; import org.springframework.stereotype.Service; @Service public class LoginService { public boolean validateUser(String userId, String password) { // TODO: Validate against database with hashed password // For now, userId = admin and password = password return userId.equalsIgnoreCase("admin") && password.equalsIgnoreCase("password"); } }
C#
UTF-8
684
3.296875
3
[]
no_license
using System; using System.Collections.Generic; namespace Homework_Class05.Classes { public class Car { public string Model { get; set; } public int Speed { get; set; } public Driver Driver { get; set; } public Car(string model, int speed) { Model = model; Speed = speed; } public Car(string model, int speed, Driver driver) { Model = model; Speed = speed; Driver = driver; } public int CalculateSpeed(Driver input) { int result = Speed * input.Skill; return result; } } }
Swift
UTF-8
1,142
3.03125
3
[ "MIT" ]
permissive
// // StubRequest.swift // Spider // // Created by Harry Tran on 7/16/19. // Copyright © 2019 Harry Tran. All rights reserved. // import Foundation public struct StubRequest: Equatable { public enum HTTPMethod: String { case GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH } public let method: HTTPMethod public let matcher: Matcher public let response: StubResponse /// Initialize a request with method and url /// /// - Parameters: /// - method: The `HTTPMethod` to match /// - url: The `URL` to match public init(method: HTTPMethod, matcher: Matcher, response: StubResponse) { self.method = method self.matcher = matcher self.response = response } public func matchesRequest(_ request: URLRequest) -> Bool { return HTTPMethod(rawValue: request.httpMethod!) == method && matcher.matches(string: request.url?.absoluteString) } public static func == (lhs: StubRequest, rhs: StubRequest) -> Bool { return lhs.method == rhs.method && lhs.matcher.isEqual(to: rhs.matcher) } }
C#
UTF-8
3,238
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using UnitTestingTask; namespace TriangleXUnitTests { public class XUnitTests : IDisposable { static Logger logger = new Logger("xUnit"); readonly int Equilateral = 1; readonly int Isosceles = 2; readonly int Scalene = 3; public XUnitTests() { logger.Log("Test initialization"); } public void Dispose() { logger.Log("Test cleanup"); } [Fact] [Trait("Category", "Smoke")] public void DetectEquilateralTest() { Triangle t = new Triangle(2, 2, 2); Assert.Equal(Equilateral, t.DetectTriangle()); } [Fact] [Trait("Category", "Smoke")] public void DetectIsoscelesTest() { Triangle t = new Triangle(2, 2, 1); Assert.Equal(Isosceles, t.DetectTriangle()); } [Fact] [Trait("Category", "Smoke")] public void DetectScaleneTest() { Triangle t = new Triangle(2, 3, 4); Assert.Equal(Scalene, t.DetectTriangle()); } [Fact] [Trait("Category", "Smoke")] public void GetSquareTest() { double a = 2, b = 3, c = 4; Triangle t = new Triangle(a, b, c); double p = (a + b + c) / 2; Assert.Equal(Math.Sqrt(p * (p - a) * (p - b) * (p - c)), t.GetSquare()); } [Fact(Skip = "This test isn't necessary.")] [Trait("Category", "Daily")] public void CheckTriangleExistenceTest() { Triangle t = new Triangle(1, 1, 1); Assert.True(t.CheckTriangle()); } [Theory] [InlineData(0,1,1)] [InlineData(-1,1,1)] [InlineData(2,2,6)] [Trait("Category", "Daily")] public void CheckTriangleNonExistenceTest(double a, double b, double c) { Triangle t = new Triangle(a, b, c); Assert.False(t.CheckTriangle()); } [Fact] [Trait("Category", "Daily")] public void DetectIncorrectEquilateralTest() { Triangle t = new Triangle(0, 0, 0); Assert.Equal(0, t.DetectTriangle()); } [Fact] [Trait("Category", "Daily")] public void DetectIncorrectIsoscelesTest() { Triangle t = new Triangle(-2, -2, 1); Assert.Equal(0, t.DetectTriangle()); } [Fact] [Trait("Category", "Daily")] public void DetectIncorrectScaleneTest() { Triangle t = new Triangle(-2, 2, 1); Assert.Equal(0, t.DetectTriangle()); } [Fact] [Trait("Category", "Daily")] public void GetSquareOfIncorrectTriangleTest() { double a = 0, b = 3, c = 4; Triangle t = new Triangle(a, b, c); double p = (a + b + c) / 2; Assert.Throws<ArithmeticException>(() => t.GetSquare()); //Assert.AreEqual(Math.Sqrt(p * (p - a) * (p - b) * (p - c)), t.GetSquare()); } } }
Markdown
UTF-8
6,165
2.515625
3
[]
no_license
--- description: "Easiest Way to Make Perfect Spinach, Pork, Hijiki Seaweed Rice Bowl" title: "Easiest Way to Make Perfect Spinach, Pork, Hijiki Seaweed Rice Bowl" slug: 2584-easiest-way-to-make-perfect-spinach-pork-hijiki-seaweed-rice-bowl date: 2020-12-07T13:12:03.355Z image: https://img-global.cpcdn.com/recipes/4505065818685440/751x532cq70/spinach-pork-hijiki-seaweed-rice-bowl-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/4505065818685440/751x532cq70/spinach-pork-hijiki-seaweed-rice-bowl-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/4505065818685440/751x532cq70/spinach-pork-hijiki-seaweed-rice-bowl-recipe-main-photo.jpg author: Lucille Harrington ratingvalue: 4 reviewcount: 23599 recipeingredient: - "1 dash Sesame oil" - "1/2 tbsp Grated garlic" - "1/2 tbsp Grated ginger" - "200 grams Ground pork" - "1 bunch Spinach" - "15 grams Hijiki seaweed dried" - "40 grams Cellophane noodles" - "2 tsp Chicken soup stock granules" - "1 tbsp Sake" - "2 tbsp Oyster sauce" - "2 tbsp Soy sauce" - "1 Pepper" - "1 Toasted white sesame seeds" - "1 Rayu" - "4 Onsen or poached eggs" recipeinstructions: - "Rehydrate the harusame glass noodles following the package instructions (by boiling briefly or soaking in boiling water), drain and cut into 3 cm long pieces. (I do this in a colander or sieve with kitchen scissors.)" - "Prepare the main ingredients. Cut the spinach into 3 cm long pieces. Rehydrate the hijiki seaweed by soaking in water until soft, then drain." - "Heat some sesame oil in a frying pan, then add the grated ginger and garlic. When it starts to smell good, add the ground pork." - "Stir fry while breaking up the pork until it&#39;s crumbly." - "When the ground pork has changed color and is just about cooked through, add the spinach and stir-fry until it&#39;s limp and reduced in volume." - "Add the drained hijiki seaweed and harusame noodles, and mix everything together well while stir frying. Add the ingredients marked ★, mix so that everything is distributed evenly and continue cooking." - "Adjust the seasoning with pepper and turn off the heat. Add the sesame seeds and stir in, and it&#39;s done." - "I doubled the recipe in the photo above." - "When you are serving this as a side dish, it will be more substantial if you use coarsely chopped pork instead of ground pork." - "Please see the related recipe &#34;Cabbage x Pork x Chinese chives: Gyoza dumpling-like Don Rice Bowl&#34;." - "Mako-san added some carrots to the recipe. It looks colorful, nutritious, and well-balanced." categories: - Recipe tags: - spinach - pork - hijiki katakunci: spinach pork hijiki nutrition: 162 calories recipecuisine: American preptime: "PT32M" cooktime: "PT50M" recipeyield: "2" recipecategory: Dinner --- ![Spinach, Pork, Hijiki Seaweed Rice Bowl](https://img-global.cpcdn.com/recipes/4505065818685440/751x532cq70/spinach-pork-hijiki-seaweed-rice-bowl-recipe-main-photo.jpg) Hey everyone, I hope you're having an incredible day today. Today, we're going to prepare a distinctive dish, spinach, pork, hijiki seaweed rice bowl. One of my favorites. For mine, I will make it a little bit tasty. This will be really delicious. Spinach, Pork, Hijiki Seaweed Rice Bowl is one of the most well liked of current trending foods on earth. It is easy, it is fast, it tastes yummy. It is appreciated by millions daily. They are fine and they look fantastic. Spinach, Pork, Hijiki Seaweed Rice Bowl is something that I've loved my whole life. To get started with this recipe, we must prepare a few ingredients. You can have spinach, pork, hijiki seaweed rice bowl using 15 ingredients and 11 steps. Here is how you can achieve that. <!--inarticleads1--> ##### The ingredients needed to make Spinach, Pork, Hijiki Seaweed Rice Bowl: 1. Take 1 dash Sesame oil 1. Take 1/2 tbsp ☆ Grated garlic 1. Prepare 1/2 tbsp ☆ Grated ginger 1. Get 200 grams Ground pork 1. Take 1 bunch Spinach 1. Take 15 grams Hijiki seaweed (dried) 1. Get 40 grams Cellophane noodles 1. Get 2 tsp ★ Chicken soup stock granules 1. Prepare 1 tbsp ★ Sake 1. Make ready 2 tbsp ★ Oyster sauce 1. Take 2 tbsp ★ Soy sauce 1. Get 1 Pepper 1. Get 1 Toasted white sesame seeds 1. Prepare 1 ※ Ra-yu 1. Get 4 ※ Onsen or poached eggs <!--inarticleads2--> ##### Steps to make Spinach, Pork, Hijiki Seaweed Rice Bowl: 1. Rehydrate the harusame glass noodles following the package instructions (by boiling briefly or soaking in boiling water), drain and cut into 3 cm long pieces. (I do this in a colander or sieve with kitchen scissors.) 1. Prepare the main ingredients. Cut the spinach into 3 cm long pieces. Rehydrate the hijiki seaweed by soaking in water until soft, then drain. 1. Heat some sesame oil in a frying pan, then add the grated ginger and garlic. When it starts to smell good, add the ground pork. 1. Stir fry while breaking up the pork until it&#39;s crumbly. 1. When the ground pork has changed color and is just about cooked through, add the spinach and stir-fry until it&#39;s limp and reduced in volume. 1. Add the drained hijiki seaweed and harusame noodles, and mix everything together well while stir frying. Add the ingredients marked ★, mix so that everything is distributed evenly and continue cooking. 1. Adjust the seasoning with pepper and turn off the heat. Add the sesame seeds and stir in, and it&#39;s done. 1. I doubled the recipe in the photo above. 1. When you are serving this as a side dish, it will be more substantial if you use coarsely chopped pork instead of ground pork. 1. Please see the related recipe &#34;Cabbage x Pork x Chinese chives: Gyoza dumpling-like Don Rice Bowl&#34;. 1. Mako-san added some carrots to the recipe. It looks colorful, nutritious, and well-balanced. So that's going to wrap it up with this exceptional food spinach, pork, hijiki seaweed rice bowl recipe. Thanks so much for your time. I'm sure you will make this at home. There is gonna be more interesting food in home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your family, colleague and friends. Thanks again for reading. Go on get cooking!
Java
UTF-8
455
2.109375
2
[]
no_license
package studio7i.negocio; import studio7i.modelo.Persona; public class GestionCliente { public void RegistrarCliente(int id, String usuario, String clave, String dni, String nombres, String fechanacimiento, String email){ Persona ClienteNuevo = new Persona(); ClienteNuevo.setClave(clave); ClienteNuevo.setDni(dni); ClienteNuevo.setEmail(email); ClienteNuevo.setFechaNacimiento(fechanacimiento); } }
C#
UTF-8
15,597
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Ink; using System.Windows.Input; using Windows.Foundation; using Priority_Queue; namespace CLP.InkInterpretation { public class ClusterPoint : PriorityQueueNode { public const double UNDEFINED = -1.0; public ClusterPoint(StylusPoint p) { _point = p; CoreDistanceSquared = UNDEFINED; ReachabilityDistanceSquared = UNDEFINED; IsProcessed = false; } public StylusPoint _point; public double X { get { return _point.X; } } public double Y { get { return _point.Y; } } public double CoreDistanceSquared { get; set; } public double ReachabilityDistanceSquared { get; set; } public double ReachabilityDistance { get { return Math.Sqrt(ReachabilityDistanceSquared); } } public bool IsProcessed { get; set; } // Distance squared is faster to calculate (by an order of magnitude) and is still accurate as a comparison of distance. public double EuclideanDistanceSquared(ClusterPoint p) { var diffX = p.X - X; var diffY = p.Y - Y; return diffX * diffX + diffY * diffY; } public double ManhattanDistance(ClusterPoint p) { var diffX = p.X - X; var diffY = p.Y - Y; return diffX + diffY; } public bool IsEqualToStylusPoint(StylusPoint p) { return p.X == X && p.Y == Y; } } public static class InkClustering { // TODO: ignore strokes that were used to highlight the entire page, or more than half? public static List<StrokeCollection> ClusterStrokes(StrokeCollection strokes) { var allStrokePoints = strokes.SelectMany(s => s.StylusPoints).ToList(); var processedPoints = OPTICS_Clustering(allStrokePoints, 1000, 2); if (!processedPoints.Any()) { //ERROR? return new List<StrokeCollection>(); } var normalizedReachabilityPlot = processedPoints.Select(p => new Point(0, p.ReachabilityDistance)).Skip(1).ToList(); var rawData = new double[normalizedReachabilityPlot.Count][]; for (var i = 0; i < rawData.Length; i++) { rawData[i] = new[] { 0.0, normalizedReachabilityPlot[i].Y}; } var clustering = K_MEANS_Clustering(rawData, 3); var zeroCount = 0; var zeroTotal = 0.0; var oneCount = 0; var oneTotal = 0.0; var twoCount = 0; var twoTotal = 0.0; for (var i = 0; i < clustering.Length; i++) { if (clustering[i] == 0) { zeroCount++; zeroTotal += normalizedReachabilityPlot[i].Y; } if (clustering[i] == 1) { oneCount++; oneTotal += normalizedReachabilityPlot[i].Y; } if (clustering[i] == 2) { twoCount++; twoTotal += normalizedReachabilityPlot[i].Y; } } var zeroMean = zeroTotal / zeroCount; var oneMean = oneTotal / oneCount; var twoMean = twoTotal / twoCount; var clusterWithHighestMean = -1; if (zeroMean > oneMean) { clusterWithHighestMean = zeroMean > twoMean ? 0 : 2; } else { clusterWithHighestMean = oneMean > twoMean ? 1 : 2; } var pointClusters = new List<List<ClusterPoint>>(); var currentCluster = new List<ClusterPoint> { processedPoints.First() }; for (var i = 0; i < clustering.Length; i++) { if (clustering[i] != clusterWithHighestMean) { currentCluster.Add(processedPoints[i + 1]); continue; } var fullCluster = currentCluster.ToList(); currentCluster.Clear(); currentCluster.Add(processedPoints[i + 1]); pointClusters.Add(fullCluster); } if (currentCluster.Any()) { currentCluster.Add(processedPoints.Last()); var finalCluster = currentCluster.ToList(); pointClusters.Add(finalCluster); } var strokeClusters = pointClusters.Select(pointCluster => new StrokeCollection()).ToList(); foreach (var stroke in strokes) { var strokePoints = stroke.StylusPoints; var highestPercentageClusterID = 0; var percentageOfStrokeInHighestMatchingCluster = 0.0; for (var i = 0; i < pointClusters.Count; i++) { var clusterPoints = pointClusters[i]; var numberOfSharedPoints = (from pointCluster in clusterPoints from strokePoint in strokePoints where pointCluster.IsEqualToStylusPoint(strokePoint) select pointCluster).Count(); var percentageOfStrokeInCurrentCluster = numberOfSharedPoints / strokePoints.Count; if (percentageOfStrokeInCurrentCluster > percentageOfStrokeInHighestMatchingCluster) { percentageOfStrokeInHighestMatchingCluster = percentageOfStrokeInCurrentCluster; highestPercentageClusterID = i; } } strokeClusters[highestPercentageClusterID].Add(stroke); } return strokeClusters; } // https://en.wikipedia.org/wiki/OPTICS_algorithm // https://github.com/Euphoric/OpticsClustering // epsilon needs to be figured out experimentally. It is the maximum distance (radius) away from a point to consider another point part of the current cluster. // probably needs to be adjusted based on average properties of the current page, or possibly the current student. epsilon could be infinity, meant to limit // complexity of the scan, should be called max_epsilon. set to width/heigh of page? // // min cluster size should be the number of points in the shortest stroke public static List<ClusterPoint> OPTICS_Clustering(List<StylusPoint> points, double epsilon, int minClusterSize = 1) { var clusterPoints = points.Select(p => new ClusterPoint(p)).ToList(); var epsilonSquared = epsilon * epsilon; //Squared to correctly compare against EuclideanDistanceSquared. var seeds = new HeapPriorityQueue<ClusterPoint>(clusterPoints.Count); var processedClusterPoints = new List<ClusterPoint>(); foreach (var p in clusterPoints) { if (p.IsProcessed) { continue; } p.ReachabilityDistanceSquared = ClusterPoint.UNDEFINED; var neighborhood = GetNeighbors(p, epsilonSquared, clusterPoints, minClusterSize); p.IsProcessed = true; processedClusterPoints.Add(p); if (p.CoreDistanceSquared == ClusterPoint.UNDEFINED) { continue; } seeds.Clear(); Update(p, neighborhood, seeds); var innerNeighborhood = new List<ClusterPoint>(); while (seeds.Count > 0) { var pInner = seeds.Dequeue(); innerNeighborhood = GetNeighbors(pInner, epsilonSquared, clusterPoints, minClusterSize); pInner.IsProcessed = true; processedClusterPoints.Add(pInner); if (pInner.CoreDistanceSquared != ClusterPoint.UNDEFINED) { Update(pInner, innerNeighborhood, seeds); } } } return processedClusterPoints; } private static void Update(ClusterPoint p1, List<ClusterPoint> neighborhood, HeapPriorityQueue<ClusterPoint> seeds) { foreach (var p2 in neighborhood) { if (p2.IsProcessed) { continue; } var newReachabilityDistanceSquared = Math.Max(p1.CoreDistanceSquared, p1.EuclideanDistanceSquared(p2)); if (p2.ReachabilityDistanceSquared == ClusterPoint.UNDEFINED) { p2.ReachabilityDistanceSquared = newReachabilityDistanceSquared; seeds.Enqueue(p2, newReachabilityDistanceSquared); } else if (newReachabilityDistanceSquared < p2.ReachabilityDistanceSquared) { p2.ReachabilityDistanceSquared = newReachabilityDistanceSquared; seeds.UpdatePriority(p2, newReachabilityDistanceSquared); } } } // See github Optics Clustering for better optimization. private static List<ClusterPoint> GetNeighbors(ClusterPoint p1, double epsilonSquared, List<ClusterPoint> points, int minClusterSize) { var neighborhood = new List<ClusterPoint>(); foreach (var p2 in points) { var distanceSquared = p1.EuclideanDistanceSquared(p2); if (distanceSquared <= epsilonSquared) { neighborhood.Add(p2); } } if (neighborhood.Count < minClusterSize) { p1.CoreDistanceSquared = ClusterPoint.UNDEFINED; return neighborhood; } var orderedNeighborhood = neighborhood.OrderBy(p1.EuclideanDistanceSquared).ToList(); p1.CoreDistanceSquared = orderedNeighborhood[minClusterSize - 1].EuclideanDistanceSquared(p1); return orderedNeighborhood; } // https://visualstudiomagazine.com/articles/2013/12/01/k-means-data-clustering-using-c.aspx public static int[] K_MEANS_Clustering(double[][] rawData, int numberOfClusters) { var k = numberOfClusters; var random = new Random(); var clustering = new int[rawData.Length]; for (var i = 0; i < k; i++) { clustering[i] = i; // guarantees at least one data point is assigned to each cluster } for (var i = k; i < clustering.Length; i++) { clustering[i] = random.Next(0, k); // assigns rest of the data points to a random cluster. } var means = new double[k][]; for (var i = 0; i < k; i++) { means[i] = new double[rawData[0].Length]; } var maxIterations = rawData.Length * 10; var iteration = 0; var clusteringSuccessful = true; var clusteringChanged = true; while (clusteringSuccessful && clusteringChanged && iteration < maxIterations) { ++iteration; clusteringSuccessful = UpdateMeans(rawData, clustering, ref means); clusteringChanged = UpdateClustering(rawData, clustering, means); } return clustering; } private static bool UpdateMeans(double[][] data, int[] clustering, ref double[][] means) { var numberOfClusters = means.Length; var clusterCounts = new int[numberOfClusters]; for (var i = 0; i < data.Length; i++) { var cluster = clustering[i]; ++clusterCounts[cluster]; } for (var i = 0; i < numberOfClusters; i++) { if (clusterCounts[i] == 0) { return false; } } for (var i = 0; i < means.Length; i++) { for (var j = 0; j < means[i].Length; j++) { means[i][j] = 0.0; } } for (var i = 0; i < data.Length; i++) { var cluster = clustering[i]; for (var j = 0; j < data[i].Length; j++) { means[cluster][j] += data[i][j]; // accumulate sum } } for (var i = 0; i < means.Length; i++) { for (var j = 0; j < means[i].Length; j++) { means[i][j] /= clusterCounts[i]; // danger of div by 0 } } return true; } private static bool UpdateClustering(double[][] data, int[] clustering, double[][] means) { var numberOfClusters = means.Length; var changed = false; var newClustering = new int[clustering.Length]; Array.Copy(clustering, newClustering, clustering.Length); var distances = new double[numberOfClusters]; for (var i = 0; i < data.Length; i++) { for (var j = 0; j < numberOfClusters; j++) { distances[j] = Distance(data[i], means[j]); } int newClusterID = MinIndex(distances); if (newClusterID == newClustering[i]) { continue; } changed = true; newClustering[i] = newClusterID; } if (changed == false) { return false; } var clusterCounts = new int[numberOfClusters]; for (var i = 0; i < data.Length; i++) { var cluster = newClustering[i]; ++clusterCounts[cluster]; } for (var i = 0; i < numberOfClusters; i++) { if (clusterCounts[i] == 0) { return false; } } Array.Copy(newClustering, clustering, newClustering.Length); return true; // no zero-counts and at least one change } private static double Distance(double[] tuple, double[] mean) { var sumSquaredDiffs = tuple.Select((t, i) => Math.Pow(t - mean[i], 2)).Sum(); return Math.Sqrt(sumSquaredDiffs); } private static int MinIndex(double[] distances) { var indexOfMin = 0; var smallDist = distances[0]; for (var i = 0; i < distances.Length; i++) { if (distances[i] < smallDist) { smallDist = distances[i]; indexOfMin = i; } } return indexOfMin; } } }
Python
UTF-8
2,313
2.921875
3
[ "MIT" ]
permissive
#Connect to ArchivesSpace database through SSH Tunnel import pymysql import yaml import csv import pandas as pd #add error handling, logging #don't forget to close the connection class DBConn(): """Class to connect to ArchivesSpace database via SSH and run queries.""" def __init__(self, config_file=None): self.config_file = self._get_config(config_file) self.sql_hostname = self.config_file['local_sql_hostname'] self.sql_username = self.config_file['local_sql_username'] self.sql_password = self.config_file['local_sql_password'] self.sql_database = self.config_file['local_sql_database'] self.sql_port = self.config_file['local_sql_port'] self.conn = self._start_conn() #looks for user-provided config file. If not present looks in cwd def _get_config(self, cfg): """Gets config file""" if cfg != None: return cfg else: cfg = yaml.load(open('config.yml', 'r', encoding='utf-8')) return cfg def _start_conn(self): """Starts the connection.""" connect = pymysql.connect(host=self.sql_hostname, user=self.sql_username, passwd=self.sql_password, db=self.sql_database, port=self.sql_port) return connect #what is the point of creating a pandas dataframe and then converting to a list? wouldn't that take longer?? def run_query(self, query): """Runs a query.""" data = pd.read_sql_query(query, self.conn) return data # def run_query(self, query): # cursor = self.conn.cursor() # cursor.execute(query) # data = cursor.fetchall() # for i in data: # yield data def close_conn(self): """Close both db connection and ssh server. Must do this before quitting Python. Need to find a way to do this even if user does not call method.""" self.conn.close() #This works well, but not if the query data requires additional processing def write_output(self, query_data, output_dir, filename): """Writes the query output to a CSV file.""" column_list = list(query_data.columns) datalist = query_data.values.tolist() newfile = open(output_dir + '/' + filename + '_results.csv', 'a', encoding='utf-8', newline='') writer = csv.writer(newfile) writer.writerow(column_list) writer.writerows(datalist) newfile.close() #Should do the cgi thing to process HTML tags and remove
C#
UTF-8
1,694
3.046875
3
[ "MIT" ]
permissive
using System; namespace sudokusolver.Solver { public class GridSolver { private readonly Grid _grid; public GridSolver(Grid grid) { _grid = grid; } public bool Solve() { var enumerator = new FrozenCellSkippingGridEnumerator(this._grid.GetEnumerator()); var cellSets = CellSetCollection.For(this._grid); if (!enumerator.MoveNext()) return false; // can't even start while (true) { var newValue = enumerator.Current.Value + 1; while (newValue < 10) { enumerator.Current.Value = newValue; if (cellSets.AggregatedState != CellSet.StateValue.Invalid) break; newValue++; } switch (cellSets.AggregatedState) { case CellSet.StateValue.Invalid: { do { enumerator.Current.Restart(); if (!enumerator.MoveBack()) return false; } while (enumerator.Current.Value == 9); break; } case CellSet.StateValue.Complete: return true; case CellSet.StateValue.Partial when !enumerator.MoveNext(): return false; } } throw new InvalidOperationException("reached an unexpected grid state"); } } }
Java
UTF-8
1,095
3.5
4
[]
no_license
// Zachary Price //Chapter 9, #7 import java.io.*; import javax.swing.*; import java.util.*; public class Chap9_7 { public static void main(String[] args) throws FileNotFoundException { Scanner inFile = new Scanner(new FileReader("Chap9_7Data.txt")); PrintWriter outFile = new PrintWriter("Chap9_7Output.txt"); int winnerCount = 0, i = 0; double total = 0; String winner = ""; String[] name = new String[5]; int[] votes = new int[5]; while(inFile.hasNext()) { name[i] = inFile.next(); votes[i] = inFile.nextInt(); if(votes[i] > winnerCount) { winnerCount = votes[i]; winner = name[i]; }//end if total = total + votes[i]; i++; }//end while outFile.printf("%-20s%-20s%-20s\n", "Candidate", "Votes Received", "% of Total Votes"); for (i = 0; i < 5; i++) outFile.printf("%-20s%-20d%-20.2f\n", name[i], votes[i], (votes[i] / total) * 100); outFile.printf("%-20s%-20.0f\n", "Total", total); outFile.printf("%-20s%s.\n", "The Winner of the Election is ", winner); outFile.close(); }//end method main }//end class Chap9_7
Java
UTF-8
787
2.859375
3
[]
no_license
package ru.cetelem.com.patterns; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; public class TemplateMethod { public static void main(String[] args) { new BankWebSite().showPage(); } } class NewsWebSite extends WebSiteTemplate{ @Override protected void showPageBody() { System.out.println("NEWS"); } } class BankWebSite extends WebSiteTemplate{ @Override protected void showPageBody() { System.out.println("BANK INFO"); } } abstract class WebSiteTemplate{ protected final void showPage(){ System.out.println("HEADER"); showPageBody(); System.out.println("FOOTER"); } protected void showPageBody(){ System.out.println("PAGE BODY"); } }
JavaScript
UTF-8
2,113
2.546875
3
[]
no_license
import React from "react"; import "./table-rows.css"; const TableRows = ({ list, deleteBtn, onSort }) => { const renderList = () => { if (list.length > 0) { return list.map((item, index) => { return ( <tr key={item.id}> <th scope="row">{index + 1}</th> <td>{item.firstName}</td> <td>{item.lastName}</td> <td>{item.phone}</td> <td>{item.gender}</td> <td>{item.age}</td> <td> <button onClick={() => deleteBtn(item.id)} className="btn btn-danger" type="button" > Delete </button> </td> </tr> ); }); } else { return null; } }; const tableList = renderList(); return ( <table className=" table custom-table table-hover table-borderless"> <thead className="thead-light"> <tr> <th scope="col">#</th> <th onClick={e => { onSort("firstName"); }} scope="col" className="table-header" > Name </th> <th onClick={e => { onSort("lastName"); }} scope="col" className="table-header" > Lastname </th> <th onClick={e => { onSort("phone"); }} scope="col" className="table-header" > Phone </th> <th onClick={e => { onSort("gender"); }} scope="col" className="table-header" > Gender </th> <th onClick={e => { onSort("age"); }} scope="col" className="table-header" > Age </th> <th></th> </tr> </thead> <tbody>{tableList}</tbody> </table> ); }; export default TableRows;
Shell
UTF-8
203
2.65625
3
[]
no_license
#!/bin/sh set -e xwininfo | awk -F: ' /Absolute upper-left X/{x=$2} /Absolute upper-left Y/{y=$2} /Width/{w=$2} /Height/{h=$2} END{ printf "-s %dx%d -i %s.0+%d,%d", w, h, ENVIRON["DISPLAY"], x, y } '
Java
UTF-8
3,274
2.109375
2
[]
no_license
package com.extrabux.tests.daigou; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.openqa.selenium.WebDriver; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.extrabux.pages.daigou.CartSummarySection; import com.extrabux.pages.daigou.ProductInfo; import com.extrabux.pages.daigou.ProductInfoSection; import com.extrabux.pages.daigou.Verify; public class ProductInfoTests extends DaigouBaseTest { String productUrl = "http://usc-magento.extrabux.net/banana.html"; String storeName = "USC Magento"; String productName = "Banana"; String price = "0.01"; @Test(dataProvider = "getWebDriver") public void getProductInfo(WebDriver driver) { login(driver, config.getString("daigou.productInfoUserEmail"), config.getString("daigou.productInfoUserPassword")); CartSummarySection cartSummary = new CartSummarySection(driver); ProductInfoSection productInfo = new ProductInfoSection(driver); List<ProductInfo> expectedProducts = new ArrayList<ProductInfo>(); ProductInfo product1 = new ProductInfo(storeName, productName, "", "1", price); expectedProducts.add(product1); cartSummary.waitForCartSpinnerNotPresent(); selectStoreAndEnterUrl(driver, storeName, productUrl, false); productInfo.waitForProductInfoSpinner(); Verify verify = productInfo.verifyProductInfo(storeName, productName, price); assertTrue(verify.isVerified(), verify.getError()); } @Test(dataProvider = "getWebDriver") public void invalidProduct(WebDriver driver) { login(driver, config.getString("daigou.productInfoUserEmail"), config.getString("daigou.productInfoUserPassword")); CartSummarySection cartSummary = new CartSummarySection(driver); ProductInfoSection productInfo = new ProductInfoSection(driver); cartSummary.waitForCartSpinnerNotPresent(); selectStoreAndEnterUrl(driver, storeName, productUrl.replace("banana", "orange"), false); productInfo.waitForProductInfoSpinner(); List<String> expectedErrors = Arrays.asList(config.getStringArray("daigou.productInfo.error.notFound")); assertTrue(productInfo.verifyErrorsOnPage(expectedErrors), "errors mismatch. expected: " + expectedErrors + " actual: " + productInfo.getErrors()); } @Test(dataProvider = "getWebDriver") public void outOfStock(WebDriver driver) { login(driver, config.getString("daigou.productInfoUserEmail"), config.getString("daigou.productInfoUserPassword")); CartSummarySection cartSummary = new CartSummarySection(driver); ProductInfoSection productInfo = new ProductInfoSection(driver); cartSummary.waitForCartSpinnerNotPresent(); selectStoreAndEnterUrl(driver, storeName, config.getString("daigou.product1.outOfStockUrl"), false); productInfo.waitForProductInfoSpinner(); List<String> expectedErrors = Arrays.asList(config.getStringArray("daigou.productInfo.error.outOfStock")); assertTrue(productInfo.verifyErrorsOnPage(expectedErrors), "errors mismatch. expected: " + expectedErrors + " actual: " + productInfo.getErrors()); } @Override @BeforeMethod public void cleanup() { clearCartCleanup(config.getString("daigou.productInfoUserEmail"), config.getString("daigou.productInfoUserPassword")); } }
C++
UTF-8
7,809
3.21875
3
[ "MIT" ]
permissive
// // Created by Tom on 04/12/2017. // #include "SpinState.h" /** Constructor for the SpinState class where the number of nuclear spins on both radicals are specified. * * @param [in] num_nuc_spins_1_in number of nuclear spins on radical 1 * @param [in] num_nuc_spins_2_in number of nuclear spins on radical 2 */ SpinState::SpinState( int const num_nuc_spins_1_in, int const num_nuc_spins_2_in ) { // read in the number of nuc spins num_nuc_spins_1_ = num_nuc_spins_1_in ; num_nuc_spins_2_ = num_nuc_spins_2_in ; // assumes the degeneracy is 2 - i.e. all spin 1/2 nuc_spin_degeneracies_1_ = 2 * ArrayXi::Ones(num_nuc_spins_1_) ; nuc_spin_degeneracies_2_ = 2 * ArrayXi::Ones(num_nuc_spins_2_) ; // set vector lenghts nuc_spin_lengths_1_ = generateSpinLengths( nuc_spin_degeneracies_1_ ) ; nuc_spin_lengths_2_ = generateSpinLengths( nuc_spin_degeneracies_2_ ) ; // create electronic state variables - 16 of them in total electron_spin_variables_ = VectorXd::Zero( 16 ) ; // create nuc spin variables nuc_spins_1_ = MatrixXd::Zero( 3, num_nuc_spins_1_ ) ; nuc_spins_2_ = MatrixXd::Zero( 3, num_nuc_spins_2_ ) ; } /** Generates an array of spin vector lengths from an array of spin degeneracies. * * @param spin_degeneracies the quantum degeneracy of each spin state (2I_k +1) . * @return an array of spin vector lengths sqrt( I_k (I_k+1) ). */ ArrayXd SpinState::generateSpinLengths( ArrayXi const spin_degeneracies ) { ArrayXd spin_lengths_out = ArrayXd::Zero( spin_degeneracies.size() ) ; double x ; for (int i = 0 ; i < spin_lengths_out.size() ; i++) { x = (double) spin_degeneracies(i) ; x = 0.5*(x - 1.0 ) ; x = sqrt(x*(x+1.0)) ; spin_lengths_out(i) = x ; } return spin_lengths_out; } /** Default constructor for SpinState class. * */ SpinState::SpinState() { } /** Returns the singlet probability for the state P_S = unit/4 - (T_11 + T_22 + T_33) * * @return singlet probability P_S for the state */ double SpinState::calculateSingletProbability() { return electron_spin_variables_(15) // unit/4 - ( electron_spin_variables_(6) // T_11 + electron_spin_variables_(10) // T_22 + electron_spin_variables_(14) // T_33 ) ; } /** Returns the singlet probability for the state P_T = 3 * unit/4 + (T_11 + T_22 + T_33) * * @return triplet probability P_T for the state */ double SpinState::calculateTripletProbability() { return (3.0 * electron_spin_variables_(15)) + ( electron_spin_variables_(6) + electron_spin_variables_(10) + electron_spin_variables_(14) ); } /** Returns the total survival probability i.e. the unit operator. * * @return the unit operator i.e. survival probabilty for the state. */ double SpinState::calculateSurvivalProbability() { return 4.0 * electron_spin_variables_(15) ; } /** Returns the index in the electron spin variable vector corresponding to T_ij. * * @param [in] i electron spin 1 component index * @param [out] j electron spin 2 component index * @return index corresponding to T_ij in the electron spin variable vector */ int SpinState::getTensorIndex( int const i, int const j ) { return (3*i) + j + 6; } /** Returns the a vector of tensor components correspond to a row of the tensor (T_i1, T_i2, T_i3) = S_1i (S_2x, S_2y, S_2z) * * @param [in] i the row index to be returned. * @return row of the electron spin tensor (T_i1, T_i2, T_i3) = S_1i (S_2x, S_2y, S_2z) */ Vector3d SpinState::getTensorRow( int const i ) { // index of first element is at ( 3*i +6 ) returns this segment of the vector return electron_spin_variables_.segment(getTensorIndex(i,0),3) ; } // returns the (T_1i, T_2i, T_3i) /** Returns a column of the electron spin tensor (T_1i, T_2i, T_3i) = (S_1x, S_1y, S_1z) S_2i. * * @param [in] i column index to be returned. * @return column of the electron spin tensor (T_1i, T_2i, T_3i) = (S_1x, S_1y, S_1z) S_2i */ Vector3d SpinState::getTensorCol( int const i ) { // returns the 3-vector. return Vector3d( electron_spin_variables_(getTensorIndex(0,i)), electron_spin_variables_(getTensorIndex(1,i)), electron_spin_variables_(getTensorIndex(2,i))) ; } /** Sets a row of the electron spin tensor to a new value (T_i1, T_i2, T_i3) * * @param [in] i the row index that is to be re-assigned. * @param new_row the new value of the row (T_i1, T_i2, T_i3) */ void SpinState::setTensorRow( int i, const Vector3d &new_row ) { electron_spin_variables_.segment(getTensorIndex(i,0),3) = new_row ; } /** Sets a electron spin tensor column (T_1i, T_2i, T_3i) to a new value. * * @param [in] i the index of the column to be re-assigned. * @param new_col the new values for the column (T_1i, T_2i, T_3i) */ void SpinState::setTensorCol( int const i, Vector3d const &new_col ) { electron_spin_variables_(getTensorIndex(0,i)) = new_col(0) ; electron_spin_variables_(getTensorIndex(1,i)) = new_col(1) ; electron_spin_variables_(getTensorIndex(2,i)) = new_col(2) ; } /** Returns the electron spin vector i normalized to its physical vector length sqrt(3/4) * * @param [in] i the electron spin index 1 or 2 * @return the electron spin vector normalized to its semi-classical length */ Vector3d SpinState::getNormedSpinVector( int const i ) { Vector3d normed_spin_vec ; normed_spin_vec = electron_spin_variables_.segment( 3*(i-1) , 3); normed_spin_vec = (HALF_SQRT3 / normed_spin_vec.norm()) * normed_spin_vec ; return normed_spin_vec ; // return HALF_SQRT3 * (electron_spin_variables_.segment(3*(i-1) , 3).normalized()) ; } /** Returns the value of the electron spin vector i. * * @param [in] i the index of the spin vector to be obtained. * @return the value of this spin vector (S_ix, S_iy, S_iz) */ Vector3d SpinState::getSpinVector( int const i ) { return 2.0 * electron_spin_variables_.segment(3*(i-1),3) ; } /** Returns the value of the unit operator. * * @return the value of the electron spin unit operator. */ double SpinState::getUnitOperator() { return 4.0 * electron_spin_variables_(15) ; } void SpinState::printInfo() { cout << "Num nuc 1: " << num_nuc_spins_1_ << endl ; cout << "Num nuc 2: " << num_nuc_spins_2_ << endl ; cout << "Lengths 1 :" << endl ; cout << nuc_spin_lengths_1_.transpose() << endl ; cout << "Lengths 2 :" << endl ; cout << nuc_spin_lengths_2_.transpose() << endl ; cout << "Nuc spins 1 dims: " << nuc_spins_1_.rows() << " x " << nuc_spins_1_.cols() << endl ; cout << "Nuc spins 2 dims: " << nuc_spins_2_.rows() << " x " << nuc_spins_2_.cols() << endl ; } void SpinState::setNucSpinLengths( ArrayXd const nuc_spin_lengths_1, ArrayXd const nuc_spin_lengths_2 ) { double x ; nuc_spin_lengths_1_ = nuc_spin_lengths_1 ; nuc_spin_lengths_2_ = nuc_spin_lengths_2 ; for (int k = 0 ; k< num_nuc_spins_1_ ; k++) { x = nuc_spin_lengths_1_(k) ; x = x*x ; x = 0.5 + sqrt(x + 0.25) ; x = 2.0*x+1.0 ; nuc_spin_degeneracies_1_(k) = (int) x; } for (int k = 0 ; k< num_nuc_spins_2_ ; k++) { x = nuc_spin_lengths_2_(k) ; // x = sqrt(I_k(I_k+1)) x = x*x ; // x = I_k(I_k+1) x = -0.5 + sqrt(x + 0.25) ; // x = I_k x = 2.0*x+1.0 ; // x = 2*I_k+1 nuc_spin_degeneracies_2_(k) = (int) x; } return ; } double SpinState::calculateSingletProbabilityVectorOnly() { return 0.25 - 4.0 * ( electron_spin_variables_(0)*electron_spin_variables_(3) + electron_spin_variables_(1)*electron_spin_variables_(4) + electron_spin_variables_(2)*electron_spin_variables_(5) ) ; } double SpinState::calculateTripletProbabilityVectorOnly() { return 0.75 + 4.0 * ( electron_spin_variables_(0)*electron_spin_variables_(3) + electron_spin_variables_(1)*electron_spin_variables_(4) + electron_spin_variables_(2)*electron_spin_variables_(5) ) ; }
Java
UTF-8
585
3.40625
3
[]
no_license
package Contructor; public class RctangleHW2 { int length; int breadth; public RctangleHW2() { length=0; breadth=0; } RctangleHW2(int num1, int num2) { length=num1; breadth=num2; } RctangleHW2(int num1) { length=breadth=num1; } void area() { System.out.println(" Area "+ length*breadth); } public static void main(String[] args) { RctangleHW2 s1= new RctangleHW2(); s1.area(); RctangleHW2 s2= new RctangleHW2(5,6); s2.area(); RctangleHW2 s3= new RctangleHW2(5); s3.area(); } }
PHP
UTF-8
515
2.796875
3
[]
no_license
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="/PHP/style.css"> <title>php-ex-2</title> </head> <body> <?php $password= $_GET['password']; var_dump($password); ?> <?php if ($password == 'Boolean') {?> <h1 class ='correct'><?php echo 'Password corretta';?></h1> <?php } else {?> <h1 class ='wrong'><?php echo 'Password non corretta';?></h1> <?php }?> </body> </html>
C++
UTF-8
2,289
2.703125
3
[]
no_license
#pragma once #include <windows.h> //#define YIELD_CPU SwitchToThread() //#define YIELD_CPU Sleep(0) //#define YIELD_CPU YieldProcessor() #define YIELD_CPU template<class T, size_t LEN> class RingQueueMT { public: RingQueueMT(void) { m_in = m_out = m_len = 0; #ifdef PROFILING m_ignorePopSpinning = false; #endif } ~RingQueueMT() { } template<typename prep> void prepare(prep pr) { for(size_t i = 0; i < LEN; i++) { pr(i, m_queue + i); } } T* beginPush(void) { #ifdef PROFILING m_counters.beginPushCalled++; #endif while(true) { if(LEN == m_len) { #ifdef PROFILING m_counters.beginPushSpinned++; #endif // friendly spin around YIELD_CPU; } else { // stop spinning break; } } return m_queue + m_in; } void endPush(void) { if(LEN == ++m_in) { m_in = 0; } InterlockedIncrement(&m_len); } T* beginPop(void) { #ifdef PROFILING m_counters.beginPopCalled++; #endif while(true) { if(0 == m_len) { #ifdef PROFILING if(!m_ignorePopSpinning) { m_counters.beginPopSpinned++; } #endif // friendly spin around YIELD_CPU; } else { // stop spinning break; } } return m_queue + m_out; } void endPop(void) { if(LEN == ++m_out) { m_out = 0; } InterlockedDecrement(&m_len); } size_t size(void) const { return m_len; } bool pollEmpty(void) const { while(true) { if(0 == m_len) { return true; } YIELD_CPU; } return false; } bool pollEmpty_busy(void) const { while(true) { if(0 == m_len) { return true; } } return false; } private: T m_queue[LEN]; size_t m_out; size_t m_in; volatile size_t m_len; // debuggabilities #ifdef PROFILING public: struct COUNTERS { volatile unsigned int beginPopCalled; volatile unsigned int beginPopSpinned; volatile unsigned char filling[56]; volatile unsigned int beginPushCalled; volatile unsigned int beginPushSpinned; } m_counters; bool m_ignorePopSpinning; void resetCounters(void) { InterlockedExchange(&m_counters.beginPopCalled, 0); InterlockedExchange(&m_counters.beginPopSpinned, 0); InterlockedExchange(&m_counters.beginPushCalled, 0); InterlockedExchange(&m_counters.beginPushSpinned, 0); } #endif };
PHP
UTF-8
670
2.53125
3
[ "MIT" ]
permissive
<?php namespace QuarkCMS\QuarkAdmin\Models; use Illuminate\Database\Eloquent\Model; class File extends Model { /** * 该模型是否被自动维护时间戳 * * @var bool */ public $timestamps = true; protected $casts = [ 'created_at' => 'datetime:Y-m-d H:i:s', 'updated_at' => 'datetime:Y-m-d H:i:s', ]; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'obj_type', 'obj_id', 'file_category_id', 'ext', 'sort', 'name', 'path', 'md5', 'size', 'status' ]; }
Markdown
UTF-8
2,404
2.671875
3
[ "MIT", "CC-BY-4.0", "CC-BY-NC-SA-4.0", "CC-BY-SA-4.0" ]
permissive
--- sidebar_position: 7 id: plugin-google-gtag title: '📦 plugin-google-gtag' slug: '/api/plugins/@docusaurus/plugin-google-gtag' --- The default [Global Site Tag (gtag.js)](https://developers.google.com/analytics/devguides/collection/gtagjs/) plugin. It is a JavaScript tagging framework and API that allows you to send event data to Google Analytics, Google Ads, and Google Marketing Platform, **in the production build**. This section describes how to configure a Docusaurus site to enable global site tag for Google Analytics. :::tip You can use [Google's Tag Assistant](https://tagassistant.google.com/) tool to check if your gtag is set up correctly! ::: ## Installation {#installation} ```bash npm2yarn npm install --save @docusaurus/plugin-google-gtag ``` :::tip If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. ::: ## Configuration {#configuration} Accepted fields: <small> | Name | Type | Default | Description | | --- | --- | --- | --- | | `trackingID` | `string` | **Required** | The tracking ID of your gtag service. | | `anonymizeIP` | `boolean` | `false` | Whether the IP should be anonymized when sending requests. | </small> ## Example configuration {#ex-config} Here's an example configuration object. You can provide it as [preset options](#ex-config-preset) or [plugin options](#ex-config-plugin). :::tip Most Docusaurus users configure this plugin through the [preset options](#ex-config-preset). ::: ```js const config = { trackingID: 'UA-141789564-1', anonymizeIP: true, }; ``` ### Preset options {#ex-config-preset} If you use a preset, configure this plugin through the [preset options](presets.md#docusauruspreset-classic): ```js title="docusaurus.config.js" module.exports = { presets: [ [ '@docusaurus/preset-classic', { // highlight-start gtag: { trackingID: 'UA-141789564-1', anonymizeIP: true, }, // highlight-end }, ], ], }; ``` ### Plugin options {#ex-config-plugin} If you are using a standalone plugin, provide options directly to the plugin: ```js title="docusaurus.config.js" module.exports = { plugins: [ [ '@docusaurus/plugin-google-gtag', // highlight-start { trackingID: 'UA-141789564-1', anonymizeIP: true, }, // highlight-end ], ], }; ```
Java
UTF-8
373
2.03125
2
[]
no_license
package com.ms.env; import org.springframework.core.env.Environment; import com.system.comm.utils.FrameSpringBeanUtil; public class EnvUtil { /** * 获取属性的值 * @param env * @return */ public static String get(Env env) { Environment environment = FrameSpringBeanUtil.getBean(Environment.class); return environment.getProperty(env.getCode()); } }
C#
UTF-8
3,676
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using SecondHandBook.Models; namespace SecondHandBook { [Route("api/[controller]")] [ApiController] public class BookADSAPIController : ControllerBase { private readonly BooksContext _context; public BookADSAPIController(BooksContext context) { _context = context; } // GET: api/BookADSAPI [HttpGet] public async Task<ActionResult<IEnumerable<BookADS>>> GetbookADs() { return await _context.bookADs.ToListAsync(); } // GET: api/BookADSAPI/5 [HttpGet("{id}")] public async Task<ActionResult<BookADS>> GetBookADS(int id) { var bookADS = await _context.bookADs.FindAsync(id); if (bookADS == null) { return NotFound(); } return bookADS; } // PUT: api/BookADSAPI/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPut("{id}")] public async Task<IActionResult> PutBookADS(int id, BookADS bookADS) { if (id != bookADS.ID) { return BadRequest(); } _context.Entry(bookADS).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BookADSExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/BookADSAPI // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPost] public async Task<ActionResult<BookADS>> PostBookADS(BookADS bookADS) { var image = bookADS.ImagePath; if (image != null) { string imageName = Guid.NewGuid() + ".jpg"; string SavePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/img", imageName); var imageString = Regex.Replace(image, @"^data:image\/[a-zA-Z]+;base64,", string.Empty); byte[] imageBytes = Convert.FromBase64String(imageString); System.IO.File.WriteAllBytes(SavePath, imageBytes); bookADS.ImagePath = imageName; } _context.bookADs.Add(bookADS); await _context.SaveChangesAsync(); return CreatedAtAction("GetBookADS", new { id = bookADS.ID }, bookADS); } // DELETE: api/BookADSAPI/5 [HttpDelete("{id}")] public async Task<ActionResult<BookADS>> DeleteBookADS(int id) { var bookADS = await _context.bookADs.FindAsync(id); if (bookADS == null) { return NotFound(); } _context.bookADs.Remove(bookADS); await _context.SaveChangesAsync(); return bookADS; } private bool BookADSExists(int id) { return _context.bookADs.Any(e => e.ID == id); } } }
JavaScript
UTF-8
1,350
2.84375
3
[]
no_license
define(function(require) { var Vector2D = require('lib/vector2d'); function createPlayerView(c) { return new Kinetic.Rect({ x: c.x, y: c.y, width: c.width, height: c.height, offset: { x: 1 * (c.width / 2), y: 1 * (c.height / 2), }, fill: "green", stroke: "black", strokeWidth: 4 }); } function Player(data) { this._data = data; this._view = createPlayerView(data); this._state = { moveSpeed: 60 / 1000, coords: new Vector2D(this._data.x, this._data.y), deltaVelocity: new Vector2D(0, 0), rotation: this._data.rotation }; } Player.prototype.getView = function() { return this._view; } Player.prototype.setData = function(data) { this._data = data; } Player.prototype.update = function(frame) { var neededCoords = new Vector2D(this._data.x, this._data.y); var currentCoords = new Vector2D(this._view.position()); var distance = Vector2D.minus(neededCoords, currentCoords); var direction = Vector2D.normalize(distance); this._state.deltaVelocity = Vector2D.mul(direction, this._state.moveSpeed * frame.timeDiff); } Player.prototype.draw = function(frame) { this._view.move(this._state.deltaVelocity); this._view.rotation(this._data.rotation); } return Player; })
Java
UTF-8
1,127
2.203125
2
[]
no_license
package com.pommert.jedidiah.bouncecraft2.items; import java.util.TreeMap; import net.minecraftforge.oredict.ShapedOreRecipe; import com.pommert.jedidiah.bouncecraft2.creativetabs.BCCreativeTabs; import com.pommert.jedidiah.bouncecraft2.ref.ModRef; import cpw.mods.fml.common.registry.GameRegistry; public class BCItems { public static final TreeMap<String, BCItem> items = new TreeMap<String, BCItem>(); public static void init() { addItem(new ItemBCMultipart(), "itemBCMultiPart"); addItem(new ItemBCMultiblock(), "itemBCMultiBlock"); addItem(new ItemScrewDriver(), "itemScrewDriver").setMaxStackSize(1); } public static BCItem addItem(BCItem item, String name) { item.setUnlocalizedName(name); item.setTextureName(ModRef.MOD_ID + ":" + name); GameRegistry.registerItem(item, name, ModRef.MOD_ID); items.put(name, item); item.setCreativeTab(BCCreativeTabs.tabBounceCraft()); return item; } public static void initCrafting() { GameRegistry.addRecipe(new ShapedOreRecipe( items.get("itemScrewDriver"), " i ", " i ", "gGg", 'i', "ingotIron", 'g', "blockGlass", 'G', "ingotGold")); } }
Java
UTF-8
962
2.15625
2
[]
no_license
package com.spring.demo; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.spring.dao.MemberDAO; import com.spring.vo.MemberVO; @RunWith(SpringJUnit4ClassRunner.class) // main 이 없어도 메인처럼 동작시키게 하는데 동작시키게 하는 것 @ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"}) public class MemberDAOTest { @Inject private MemberDAO memberDAO; @Test public void testTime() { System.out.println(memberDAO.getTime()); } // @Test // public void testInsertMember() { // MemberVO vo = new MemberVO(); // vo.setUid("스레기"); // vo.setPwd("1234"); // vo.setUsername("조반석"); // vo.setEmail("오철민@trash.com"); // // memberDAO.insertMember(vo); // } }
C#
UTF-8
3,053
3.28125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinAppParabolicShoot { class CParabolicShoot { private float mVelocity, mTheta, mDistance, mHigh, mTime; private const float G = 9.81f; // con const se declara una constante //funciones miembro - metodos de una clase //constructor de la clase sin parametros public CParabolicShoot() { InitializeData(); } //funcion para inicializar los datos miembro public void InitializeData() { mVelocity = 0.0f; mTheta = 0.0f; mDistance = 0.0f; mHigh = 0.0f; mTime = 0.0f; } public void InitializeData(TextBox txtVelocity, TextBox txtTheta, TextBox txtDistance, TextBox txtHigh, TextBox txtTime) { //Inicializar las variables radiuos, perimeter, area con cero mVelocity = 0; mTheta = 0; mDistance = 0; mHigh = 0; mTime = 0; //Inicializar las cajas de texto con comillas dobles ("") txtSideA.Text = "";// las comillas dobles es equivalente a (BLANK) txtSideB.Text = ""; txtSideC.Text = ""; txtSemiperimeter.Text = ""; txtPerimetro.Text = ""; txtArea.Text = ""; //la funcion focus activa el cursor en la caja de texto txtRadiuos txtVelocity.Focus(); } //leer loa valores de la velocidad y el angulo de lanzamiento public void ReadData() { Scanner scan = new Scanner(System.in); System.out.printf("Ingrese el valor de la velocidad (m/seg): "); mVelocity = scan.nextFloat(); System.out.printf("Ingrese el valor del angulo theta (grados)"); mTheta = scan.nextFloat(); } //convertir de grados a radianes al angulo public void ConvertGradesToRadians() { mTheta = mTheta * (float)Math.PI / 180.0f; } //calcular la distancia public void CalculateDistance() { mDistance = ((float)Math.pow(mVelocity, 2) * (float)Math.sin(2 * mTheta)); } //calcular tiempo public void CalculateTime() { mTime = (2 * mVelocity * (float)Math.sin(mTheta)) / G; } //calcular altura public void CalculateHigh() { MHigh = ((float)Math.pow(mVelocity, 2) * (float)Math.sin(mTheta)) / G; } public void PrintData() { System.out.printf("Distancia (m): %f\n", mDistance); System.out.printf("Altura (m): %f\n", MHigh); System.out.printf("Tiempo de vuelo (seg): %f", mTime); } } }
C++
UTF-8
1,273
3.234375
3
[]
no_license
#ifndef _GAMEROLE_ #define _GAMEROLE_ #include <string> #include <iostream> class GameRole{ int hp; std::string name; int mana; int attack; public: void useMana(){ std::cout << "Dark squeeze! mana-10" << std::endl; mana = mana-10; } void changeHP(int amount){ this->hp += amount; } GameRole(int hp, std::string name, int mana, int attack): hp{hp}, name{name}, mana{mana}, attack{attack}{} class Memento{ public: int hp; std::string name; int mana; int attack; Memento(int hp, std::string name, int mana, int attack): hp{hp}, name{name}, mana{mana}, attack{attack}{} }; Memento* save(){ return new Memento(hp, name, mana, attack); } void load(Memento* ss){ hp = ss->hp; name = ss->name; mana = ss->mana; attack = ss->attack; } void display(){ std::cout << "Name: " << name << std::endl; std::cout << "HP: " << hp << std::endl; std::cout << "Mana: " << mana << std::endl; std::cout << "attack: " << attack << std::endl; } }; #endif
Markdown
UTF-8
3,267
2.875
3
[]
no_license
To improve php performance, it's good to start profiling the application you are working on, as there might be some bad code that heavily decreases performance. One tool to do this with, is Xhprof. Xhprof is a tool that helps you detect possible code issues, it accomplishes this by showing you what function get called most, how long it takes, memory and cpu usage per call etc etc. I'm going to show you how you can upgrade your environment to enable Xhprof in an easy way, (One time setup). As I am working with OS X, I'll be using homebrew to install xhprof, for additional information on how to install xhprof you can look <a href="https://pecl.php.net/package/xhprof">here</a>. ### Install xhprof Assuming that you already have php (5.6) configured, we are now installing xhprof with the following command. ``` brew install php56-xhprof ``` Now that we have xhprof installed, we can go on and install a tool to look at the data. ### Install Xhgui [Xhgui](https://github.com/preinheimer/xhprof "xhgui") is a tool that captures the profiling data to a database. It's easy to install, just follow the instructions you can find on the github page. [Installation instructions](https://github.com/preinheimer/xhprof#installation "Installation instructions") But skip the "auto_prepend_file" step. A tip in this section: * set **$_xhprof['servername']** to something short. ### Chrome extension To enable per site profiling, we need a Cookie. In chrome this can be easily done by using the [Xhprof helper](https://chrome.google.com/webstore/detail/xhprof-helper/adnlhmmjijeflmbmlpmhilkicpnodphi "Xhprof helper"). Please see your browser of preference for a similar tool. ### Glue! All tools in place, we will glue them together. In your apache virtualhost config, we'll add a new section. Make sure it looks a bit like the example below: ``` <Virtualhost *:80> VirtualDocumentRoot "/Users/<USER>/Sites/localhost/%1/public" ServerName sites.loc ServerAlias *.loc UseCanonicalName Off <IfModule mod_php5.c> php_value auto_prepend_file "/Users/<USER>/Sites/localhost/xhprof/external/header.php" </IfModule> </Virtualhost> ``` As you can see, I have Xhgui installed in **/Users/<USER>/Sites/localhost/xhprof/external/header.php** What does it do? ``` php_value auto_prepend_file "/Users/<USER>/Sites/localhost/xhprof/external/header.php" ``` This line automatically prepends the xhprof header file to all pages. In it's current state, this will start profiling every page (which is not what we want), so lets go ahead and change this file a bit. So, open up /Users/**USER**/Sites/localhost/xhprof/external/header.php with your favorite editor. And wrap the full file in an IF statement. ``` <?php if (isset($_COOKIE["_profile"])) { // Original code. } ``` The same in /Users/**USER**/Sites/localhost/xhprof/external/footer.php. ``` <?php if (isset($_COOKIE["_profile"])) { // Original code. } ``` The changes we made above, will make the toggle button, that we installed into chrome, will trigger the profiler to start. ![Xhprof button](http://harings.be/sites/default/files/2016-02/Schermafbeelding%202016-02-22%20om%2012.55.46_7.png) If it is not active, we just use the pages as normal without any performance issues.
C++
UTF-8
2,786
3.4375
3
[]
no_license
#ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include "TreeNode.h" //"Jack" Daniel Kinne /* Incomplete BST. We will fill this out more in future lectures. */ template <typename T> class BinarySearchTree { private: TreeNode<T> *_root = nullptr; protected: virtual TreeNode<T> *findLargestRec(TreeNode<T> *root) { //base case: root has no right child or root is null if (root == nullptr || root->getRightChild() == nullptr) { return root; } return findLargestRec(root->getRightChild()); } virtual TreeNode<T> *findLargestIter(TreeNode<T> *root) { while (root != nullptr || root->getRightChild() != nullptr) { root = root->getRightChild(); } return root; } virtual TreeNode<T> * addItemHelper(TreeNode<T> *root, T item) { //BASE CASE: null root if (root == nullptr) { //allocate new space, store value, then return. root = new TreeNode<T>{}; root->setValue(item); return root; } //RECURSIVE CASE: root is not null if (item >= root->getValue()) { //CASE 1: belongs on the right side of root TreeNode<T> *right = addItemHelper( root->getRightChild(), item ); //update right side with reconfigured state root->setRightChild(right); } else { //CASE 2: belongs on the left side of root TreeNode<T> *left = addItemHelper( root->getLeftChild(), item ); root->setLeftChild(left); } return root; } virtual TreeNode<T> * getHeightHelper(TreeNode<T> *root) { if (_root == nullptr) { return 0; } else { return 1 + max(getHeightHelper(root->getRightChild() ), getHeightHelper(root->getLeftChild() ) ) ; } } virtual TreeNode<T> * getSizeHelper(TreeNode<T> *root) { if (_root == nullptr) { return 0; } else { return (1 + getSizeHelper(root->getRightChild() ) + getSizeHelper(root->getLeftChild() ) ) ; } } public: virtual void addItem(T value) { _root = addItemHelper(_root, value); } //MA #7 TODO: implement! //Gets the height of the tree. int getHeight() { return getHeightHelper(_root); } //MA #7 TODO: implement! //Note: You cannot use a "counter variable" to track height. Your function must //calculate the height manually (probably w/ recursion). int getSize() { return getSizeHelper(_root); } }; #endif // BINARY_SEARCH_TREE_H
Markdown
UTF-8
968
3.84375
4
[]
no_license
## Position Improved Positioning your cat with calculations is handy. However there is another way to do this, where you don't need to do all those calculations by yourself. (Why didn't I tell you this earlier, right?) The solution is a function called `translate` that is part of the drawing context. By calling it you can set the anchor of your coordination system to another position. So if you set your anchor to `(10,10)` by calling `ctx.translate(10,10)` everthing you draw after that point will be shifted by `(10,10)`. So drawing a rectangle like this `ctx.fillRect(0, 0, 2, 2)` will actually draw the rectangle at the position `(10,10)`. This means ```js ctx.translate(10, 10) ctx.fillRect(0, 0, 2, 2) ``` would draw the rectangle at the same position as ```js ctx.translate(0, 0) ctx.fillRect(10, 10, 2, 2) ``` ## Instructions Set the anchor of this canvas to the `x` and `y` position specified in the code to make sure it will be in the right position.
Shell
UTF-8
1,504
3.6875
4
[]
no_license
#! /bin/bash set -eu # Execute terraform graph and output results as svg file. # Terraform gaph output a 'dot' file. # Docker image is use as 'dot' file requires Graphviz tool to convert to another format, eg svg # # Execute terraform graph beautifier and output results as html file. # # Arguments: # - DefaultWorkingDirectory: typically equal to '$(System.DefaultWorkingDirectory)/terraform' # - CodeQualityDirectory: typically equal to '$(System.DefaultWorkingDirectory)/terraform/codequality' DefaultWorkingDirectory=$1 CodeQualityDirectory=$2 cd "$DefaultWorkingDirectory" # Terraform Graph echo "" echo -e "\n\n>>> Execute terraform graph" (terraform graph -draw-cycles | docker run --rm -i nshine/dot > "$DefaultWorkingDirectory"/"$CodeQualityDirectory"/tf-graph.png) # Terraform Graph Beautifier echo -e "\n\n>>> Install tar to unzip" sudo apt-get install -y tar echo -e "\n\n>>> Install Terraform Graph Beautifier" cd "$DefaultWorkingDirectory" curl -L "$(curl -s https://api.github.com/repos/pcasteran/terraform-graph-beautifier/releases/latest | grep -o -E "https://.+?_Linux_x86_64.tar.gz")" > terraform-graph-beautifier.tar.gz && tar xvzf terraform-graph-beautifier.tar.gz && rm terraform-graph-beautifier.tar.gz echo -e "\n\n>>> Execute Terraform Graph Beautifier" (terraform graph | "$DefaultWorkingDirectory"/terraform-graph-beautifier > "$DefaultWorkingDirectory"/"$CodeQualityDirectory"/tf-graph-beautifier.html )
PHP
UTF-8
1,267
2.609375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php final class PhabricatorRepositoryGitLFSRefQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $repositoryPHIDs; private $objectHashes; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withRepositoryPHIDs(array $phids) { $this->repositoryPHIDs = $phids; return $this; } public function withObjectHashes(array $hashes) { $this->objectHashes = $hashes; return $this; } public function newResultObject() { return new PhabricatorRepositoryGitLFSRef(); } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'id IN (%Ld)', $this->ids); } if ($this->repositoryPHIDs !== null) { $where[] = qsprintf( $conn, 'repositoryPHID IN (%Ls)', $this->repositoryPHIDs); } if ($this->objectHashes !== null) { $where[] = qsprintf( $conn, 'objectHash IN (%Ls)', $this->objectHashes); } return $where; } public function getQueryApplicationClass() { return 'PhabricatorDiffusionApplication'; } }
Python
UTF-8
940
3.296875
3
[]
no_license
from collections import Counter input_ = "...^^^^^..^...^...^^^^^^...^.^^^.^.^.^^.^^^.....^.^^^...^^^^^^.....^.^^...^^^^^...^.^^^.^^......^^^^" def expand(start, rows, log=False): traps = [start] while True: old_traps = "." + traps[-1] + "." new_traps = "" for idx, trap in enumerate(old_traps[1:-1]): above = old_traps[idx:idx+3] if above in ["^^.", ".^^", "^..", "..^"]: new_traps += "^" else: new_traps += "." traps.append(new_traps) if len(traps) == rows: break if log: for trap in traps: print(trap) print("") return traps def count_safe_tiles(rows): return sum([len(row.replace('^', '')) for row in rows]) expand("..^^.", 3, True) expand('.^^.^.^^^^', 10, True) print(count_safe_tiles(expand(input_, 40))) print(count_safe_tiles(expand(input_, 400000)))
C++
UTF-8
986
2.8125
3
[]
no_license
#ifndef MICROPHONE_H_ #define MICROPHONE_H_ #include "GlobalConfig.h" #include "Utils.h" namespace Beam{ class Microphone { public: Microphone(int _id, float _x, float _y, float _z, int _type, float _direction, float _elevation); ~Microphone(); /// microphone id. int id; /// coordinates of the microphone. float x; float y; float z; /// microphone type. int type; /// direction of the microphone. float direction; /// elevation of the microphone. float elevation; /// returns the complex gain for cardioid microphones. static std::complex<float> micRatio(float cos_theta, float freq); /// returns the complex gain for ideal microphone given alpha and beta static std::complex<float> microphoneDirectivity(float freq, float cos_theta, float alpha, float beta); /// returns the complex gain for ideal gradient microphone. static std::complex<float> gradientMicrophoneDirectivity(float freq, float cos_theta); }; } #endif /* MICROPHONE_H_ */
Java
UTF-8
1,293
3.546875
4
[]
no_license
package gameoflife.model; import java.util.LinkedList; import java.util.ListIterator; public class Cell { private boolean alive; private boolean nextAlive; private int amountOfAliveNeighbours; private LinkedList<Cell> neighboursCells; public Cell() { alive = false; nextAlive = false; amountOfAliveNeighbours = 0; neighboursCells = new LinkedList<>(); } public boolean isAlive() { return alive; } public void changeState() { alive = !alive; } public void updateAliveNeighbours() { int counter = 0; ListIterator<Cell> iterator = neighboursCells.listIterator(); while (iterator.hasNext()) { if (iterator.next().isAlive()) counter++; } amountOfAliveNeighbours = counter; } public void updateNextState() { updateAliveNeighbours(); if (alive) { nextAlive = (amountOfAliveNeighbours == 2 || amountOfAliveNeighbours == 3) ? true : false; } else { nextAlive = (amountOfAliveNeighbours == 3) ? true : false; } } public void updateCurrentState() { alive = nextAlive; } public void addObserver(Cell observer) { this.neighboursCells.add(observer); } }
JavaScript
UTF-8
6,376
3.703125
4
[]
no_license
var square = []; // Objects made for all the square divs var k = 6; // It is the number of squares presently on the board, 6 for hard mode 3 for easy var pickedColor; // It will contain the color of the div that needs to be clicked for winning for(var i = 1; i <= k; i++) { square[i - 1] = document.querySelector("#a" + i); } // All square divs are given an object in javascript for(var i = 0; i < k; i++) { square[i].addEventListener("click", function() { if(this.style.backgroundColor != pickedColor) { document.querySelector("#message").textContent = "Try Again"; this.style.backgroundColor = "#232323"; } else { document.querySelector("#message").textContent = "Correct!"; document.querySelector(".blue-background").style.backgroundColor = this.style.backgroundColor; for(var j = 0; j < k; j++) { square[j].style.backgroundColor = this.style.backgroundColor; } document.querySelector("#reset").textContent = "Play Again?"; } }); /* An event listener is the added to all the squares First it checks whether the clicked div color is same as that of the rgb color asked for If the color is different then it makes the color of the div to the background color If it mathes then all the other squares are given that color and also the title bar changes its color to the color of the selected div Also the text of the New colors button changes to Play again*/ } function rand() { return (Math.floor(Math.random() * 256)); } // It generates some random number between 0 & 255 document.querySelector("#reset").addEventListener("click", function() { window.location.href=window.location.href; }); //It adds an event listener to the new colors button, On being clicked it refreshes the window var colors = []; function start() { for(var i = 0; i < k; i++) { colors[i] = { r: rand(), g: rand(), b: rand() }; } // It generates random numbers for making different colors for all the squares for(var i = 0; i < k; i++) { square[i].style.backgroundColor = 'rgb(' + [colors[i].r, colors[i].g, colors[i].b].join(',') + ')'; } // It sets the color to all the squares var ans = Math.floor(Math.random() * k); // It randomly selects the number of the color to be selected from the values 0 to k - 1 pickedColor = 'rgb(' + colors[ans].r + ', ' + colors[ans].g + ', ' + colors[ans].b + ')'; // It sets the value of the picked color to the value of the color of the present at ans position var r = document.querySelector("#r"); var g = document.querySelector("#g"); var b = document.querySelector("#b"); r.textContent = colors[ans].r; g.textContent = colors[ans].g; b.textContent = colors[ans].b; } // It sets the numbers present at the title bar using the color code of the answer color var easy = document.querySelector("#easy"); // It is the object for the easy button var hard = document.querySelector("#hard"); // It is the object for the hard button easy.addEventListener("click", function() { hard.classList.remove("selected"); easy.classList.add("selected"); var s4 = document.querySelector("#a4"); var s5 = document.querySelector("#a5"); var s6 = document.querySelector("#a6"); if(s4 !== null) { s4.parentNode.removeChild(s4); s5.parentNode.removeChild(s5); s6.parentNode.removeChild(s6); } k = 3; start(); }); /* It is an event listener to the easy button It first removes the class "selected" from the hard object Then it adds the class "selected" to easy object The class selected makes the background of the easy button bluish which gives the button a look that it is selected Then the last three divs are provided with an object variable they are checked if they are present in the html by comparing for their object with null If the object is null that means that the div is not present in the html If it is not null that means the div is present in the html if it is present then they are deleted Then it sets the value of k to be 3 and the start function is called so that the colors to all the divs can be given again */ var parent = document.querySelector("#parent"); // It is the object of the parent div to all the squares with colors function createNewNode() { var div = document.createElement("div"); div.classList.add("square"); parent.appendChild(div); return div; } // It creates a new div node, add required looks to it by adding the class square to it, adds it to the parent object and returns the div object hard.addEventListener("click", function() { hard.classList.add("selected"); easy.classList.remove("selected"); var s4 = document.querySelector("#a4"); var s5 = document.querySelector("#a5"); var s6 = document.querySelector("#a6"); if(s4 === null) { s4 = createNewNode(); s4.setAttribute("id", "a4"); } if(s5 === null) { s5 = createNewNode(); s5.setAttribute("id", "a5"); } if(s6 === null) { s6 = createNewNode(); s6.setAttribute("id", "a6"); } k = 6; for(var i = 4; i <= k; i++) { square[i - 1] = document.querySelector("#a" + i); } for(var i = 3; i < k; i++) { square[i].addEventListener("click", function() { if(this.style.backgroundColor != pickedColor) { document.querySelector("#message").textContent = "Try Again"; this.style.backgroundColor = "#232323"; } else { document.querySelector("#message").textContent = "Correct!"; document.querySelector(".blue-background").style.backgroundColor = this.style.backgroundColor; for(var j = 0; j < k; j++) { square[j].style.backgroundColor = this.style.backgroundColor; } document.querySelector("#reset").textContent = "Play Again?"; } }); } start(); }) /* It adds selected class to the hard object and deletes it from the easy object It makes object for the three squares that are to be added; Then it checks if each of the object is null or not If the object is null that means the square is not present in the html and needs to be added if the object is not null that means that the square are already present there and there is no need for anyhting to add if the squares are null then each of div is created and is given the required id then the value of k is set to 6 all the new squares created are added to the square array all the newly created square array elements are given an eventlistener the same that was given to them earlier the start function called so that the program can start again */ start();
Markdown
UTF-8
12,854
3.1875
3
[]
no_license
Confoo Two-Factor Demo ====================== This Express route is where I've put in all the code for my little demonstration of authentication using Google Authenticator and a Yubikey. This is a literate coffee-script file, which is a new feature of coffee-script 1.5.0. This means that this document is written in Markdown, using the same convention of indentation for code. However, note that the indented code Is also executable, Exciting! This will allow me to document thought processes and pitfalls of this toy project. Dependencies --------- In order to communicate with Yubico's authentication server, you'll need to use the **http or https** module. Other than that, we'll be abstracting the HMAC SHA-1 hashing and use some conversion methods of **CryptoJS** to make things clearer. Lastly, we'll use **underscore** to make it easier to search in our in-memory user store, you normally wouldn't really need that. ```coffeescript https = require('https') Crypto = (require 'cryptojs').Crypto _ = require 'underscore' module.exports = (app)-> ``` Users ----- Since we wanted to remove the complexity of managing a database of users, we just decided to use an array of user objects. This array is editable, as we'll see in the registration route, but will be wiped with each Express reboot. Note the **yubico_identity** and **googleCode** fields. The **yubico_identity** field is the static portion of the code generated by the yubikey device, and is used to map a user to a key. As of **googleCode**, it is a base32 encoded shared secret between the authenticator app (or service) and the user in this webapp. ```coffeescript @users = [ { user: "admin" password: "password" yubico_identity: "ccccccbggtft" googleCode: "JBSWY3DPEHPK3PXP" }, { user: "schmuck" password: "password" yubico_identity: "fifjgjgkhcha" googleCode: "JBSWY3DPEHPK3PXX" } ] ``` Routes ------ Here we have two simple routes to the index and register pages, they are simple jade pages, nothing awesome. ```coffeescript app.get '/', (req, res )-> res.render 'index', { title: 'Confoo Demo' } app.get '/register', (req, res )-> res.render 'register', { title: 'Confoo Demo' } ``` The **do_register** lets a user register to our webapp. Basically, we take the form data from the body and add a **user** object to our **users** collection. The two things to note are that we generate a new base32 secret to use for google authenticator in **generateBase32Code()** (more below) and we extract the identity from the code generated by the yubikey. Note that we also pass the code to our jade view. That'll allow us to render a scannable QR code for our user. ```coffeescript app.post '/do_register', (req, res )-> #Save user, generate key code = generateBase32Code() user = user: req.body.user password: req.body.password yubico_identity: extractYubicoIdentity req.body.yubicode googleCode: code @users.push user res.render 'do_register', { title: 'Confoo Demo', user:user.user, code:user.googleCode } ``` Our **verify** route is where we really test out our two-factor strategies. First off, we do the usual: ```coffeescript app.post '/verify', (req, res )-> #Check if user exists user =_.find @users, (user) -> user.user is req.body.user #Check if old style password works if user && user.password is req.body.password ``` At that point, we have roughly validated that the user exists, and that he's used the right password. We must now verify that the key entered is either a Yubico key or a Google code, and we call the appropriate verification code. Note that we check for a Yubico code by using a length range. The Yubiko secret part of the OTP is 32 characters long, and the identity can be up to 16 characters long. Keep in mind also that we do not validate the keyspace with regex, as Yubico uses a format called **modhex** to generate keys. This is due to their device actually behaving like keyboards, which can behave differently according to machine settings and locale. If we do detect a Yubico code, we check that the identity part matches what we saved in our user settings. ```coffeescript #Check if key format Yubikey or Google key = req.body.key if 32 <= key.length <= 48 identity = extractYubicoIdentity key #Check to make sure identity matches if user.yubico_identity is identity #Call yubico HQ verifyYubicode key , user, res else res.render 'fail', {title: 'Confoo Demo' , reason: 'Unknown Yubico identity.' } else #Try to derive the same key with code and time otp = computeOTP(user.googleCode) if otp is key res.render 'authenticated', {title: 'Confoo Demo' , user: user.user } else res.render 'fail', {title: 'Confoo Demo' , reason: 'Bad Key.' } else res.render 'fail', {title: 'Confoo Demo' , reason: 'Wrong Username/Password' } ``` Yubico verification and utilities ------------- First off, a little simple function to extract the Yubico public identity from a generated key. Granted, it's basically a one liner, but it helps understand the registration and verification flow to name it. ```coffeescript extractYubicoIdentity = (code) -> #the key is always 32 chars, the rest is identity code.slice 0,-32 ``` Alright, here's where the Yubico magic happens. First off, if you have an API Key, configure your environment variables **YUBIKEY\_CLIENT** and **YUBIKEY\_ SECRET**. If you have a yubikey, you can get your client id and client secret from [the Yubico site](https://upgrade.yubico.com/getapikey/). Every response from the Yubico server is sent back with a signature hash made with their copy of the shared secret key for the corresponding id. This allows you to verify this signature by re-hashing the response and comparing the hashes (we'll see that below). We also generate a **nonce** to add to our request, which will be sent back to us by the Yubico server. We then make an https request to the yubico server. ```coffeescript verifyYubicode = (otp, user, response)-> clientId = process.env['YUBIKEY_CLIENT'] || 1 secretKey = process.env['YUBIKEY_SECRET'] #You would probably use a better random here. nonce = Crypto.util.bytesToHex Crypto.util.randomBytes 20 req = https.get "https://api2.yubico.com/wsapi/2.0/verify?id=#{clientId}&otp=#{otp}&nonce=#{nonce}", (res)-> data = "" res.setEncoding('utf8') res.on 'data', (chunk) -> data = data + chunk ``` The Yubico server replies to our request with a few lines, containing a **hash**, a **status** for our OTP, the **otp** itself and the **nonce** we gave it at the time of the request. We then construct an easier to manipulate object and we check the following: + We make sure the **status** is **OK** + The **nonce** sent back by Yubico is the same we sent it + The **otp** sent back by Yubico is the same we sent it If that's all right and we didn't set our **YUBIKEY\_SECRET**, then we're done! ```coffeescript res.on 'end', () -> lines = data.split "\n" result = {} #Create a friendlier object for line in lines line = line.split "=" #We trim the end result[line[0]] = line[1]?.replace(/^\s+|\s+$/g, '') #restore stripped = result.h = result.h + "=" #Check status if result.status is "OK" #Check nonce if result.nonce is nonce #Check same OTP if result.otp is otp #If we haven't changed our clientId we'll skip hashing if clientId is 1 || !secretKey console.log "Warning: No hash configuration" response.render 'authenticated', {title: 'Confoo Demo' , user: user.user } else ``` If we have specified a specific secret key, we'll use HMAC-SHA1 using that key to generate a hash of the server reply. Note that the message to be hashed is the list of **alphabetically sorted** parameters (aside from **h**) and values sent back from the server, separated by **&** instead of new lines. We'll be using CryptoJS to assist us. The computed hash should be the same as the **h** parameter (in a Base64). ```coffeescript #Combine all parameters except hash, in a single string no new line #Separate params with &, then HMAC-SHA1 it using private key message = "nonce=#{result.nonce}&otp=#{result.otp}&sl=#{result.sl}&status=#{result.status}&t=#{result.t}" key = Crypto.util.base64ToBytes secretKey hmac = Crypto.HMAC(Crypto.SHA1, message, key, null) computedHash = Crypto.util.hexToBytes hmac computedHash = Crypto.util.bytesToBase64 computedHash #Compare the hash if result.h is computedHash response.render 'authenticated', {title: 'Confoo Demo' , user: user.user } else response.render 'fail', {title: 'Confoo Demo' , reason: "Yubico responded with a bad signature hash, impersonator?" } else response.render 'fail', {title: 'Confoo Demo' , reason: "Yubico responded with a different otp, copy-paste attack?" } else response.render 'fail', {title: 'Confoo Demo' , reason: "Yubico responded with a different nonce, copy-paste attack?" } else response.render 'fail', {title: 'Confoo Demo' , reason: "Yubico responded with status: #{result.status}." } req.on 'error', (e)-> console.log('problem with request: ' + e.message) response.render 'fail', {title: 'Confoo Demo' , reason: 'Unknown Yubico identity.' } ``` Below conversion and OTP code inspired by TOPT Draft http://tools.ietf.org/id/draft-mraihi-totp-timebased-06.html And JS implementation at http://blog.tinisles.com/2011/10/google-authenticator-one-time-password-algorithm-in-javascript/ Provides a working example, will refactor for readability and eventually migrate components to external lib. ```coffeescript generateBase32Code = ()-> #Granted, you'll want something a little more advanced than this base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" key = "" for i in [1..16] key += base32chars.charAt Math.floor( Math.random() * (base32chars.length-1) ) key dec2hex = (s) -> return (if s < 15.5 then '0' else '') + Math.round(s).toString(16) hex2dec = (s) -> return parseInt s, 16 ``` A quick note about Base32, be aware that there's multiple implementations of it. The base32 encoding allows a human-readable representation of data. As such, characters that look alike such as **O** and **0** as well as **I** and **1** are avoided. In the case of Google Authenticator's shared secret, it uses the implementation found in *base32chars* (full alphabet and 234567). You can find more details in [RFC3548](http://tools.ietf.org/html/rfc3548#page-6) ```coffeescript base32tohex = (base32) -> base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" bits = "" hex = "" for char, index in base32.split '' val = base32chars.indexOf(char.toUpperCase()) bits += leftpad(val.toString(2), 5, '0') for char, index in bits.split '' if index%4 is 0 && index < bits.length - 1 chunk = bits.substr(index, 4) hex = hex + parseInt(chunk, 2).toString(16) hex leftpad = (str, len, pad) -> if (len + 1 >= str.length) str = Array(len + 1 - str.length).join(pad) + str str ``` And here's the TOTP calculation used for Google Authenticator according to [RFC6238](http://tools.ietf.org/html/rfc6238) which is an extension to HOTP defined in [RFC4226](http://tools.ietf.org/html/rfc4226). ```coffeescript computeOTP = (key)-> delay = 30 key = base32tohex key seconds = Math.round(new Date().getTime() / 1000.0) time = leftpad(dec2hex(Math.floor(seconds / delay)), 16, '0') bytesTime = Crypto.util.hexToBytes time bytesKey = Crypto.util.hexToBytes key hmac = Crypto.HMAC(Crypto.SHA1, bytesTime, bytesKey, null) offset = hex2dec(hmac.slice -1) otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) + '' otp = otp.slice -6 otp ```
Python
UTF-8
328
2.875
3
[ "MIT" ]
permissive
import os dir_path = os.path.dirname(os.path.realpath(__file__)) for file in os.listdir(dir_path): if file.endswith(".pdf"): # print(os.path.join(dir_path, file)) # print("Converting file:", str(file)) cmd = "pdftotext '" + os.path.join(dir_path, file) + "'" print(cmd) os.system(cmd)
Python
UTF-8
266
3.84375
4
[]
no_license
numbers = [[], []] for i in range(0, 7): number = int(input('number: ')) if number % 2 == 0: numbers[0].append(number) else: numbers[1].append(number) numbers[0].sort() numbers[1].sort() print(f'Pares: {numbers[0]}') print(f'Impares: {numbers[1]}')
Markdown
UTF-8
2,012
3.609375
4
[]
no_license
MySQL OOP Class PHP (v.1.0) ------------ This is a simple to use MySQL class that easily bolts on to any existing PHP application, streamlining your MySQL interactions. Setup ----- Simply include this class into your project like so: ```php <?php //Simply include this file on your page require_once("MySQL.class.php"); //Set up all yor paramaters for connection $db = new connectDB("localhost","username","password","database",$persistent=false); ?> ``` Usage ----- To use this class, you'd first init the object like so (using example credentials): `$db = new connectDB("localhost","username","password","database",$persistent=false);` Provided you see no errors, you are now connected and can execute full MySQL queries using: `$db->execute($query);` `execute()` will return an array of results, or a true (if an UPDATE or DELETE). There are other functions such as `insert()`, `delete()` and `select()` which may or may not help with your queries to the database. Example ------- To show you how easy this class is to use, consider you have a table called *admin*, which contains the following: ``` +----+--------------+ | id | username | +----+--------------+ | 1 | superuser | | 2 | admin | +----+--------------+ ``` To add a user, you'd simply use: ``` $newUser = array('username' => 'user'); $db->insert($newUser, 'admin'); ``` And voila: ``` +----+---------------+ | id | username | +----+---------------+ | 1 | superuser | | 2 | admin | | 3 | user | +----+---------------+ ``` To get the results into a usable array, just use `$db->select('admin')` ...for example, doing the following: `print_r($db->select('admin'));` will yield: ``` Array ( [0] => Array ( [id] => 1 [username] => superuser ) [1] => Array ( [id] => 2 [username] => admin ) [2] => Array ( [id] => 3 [username] => user ) ) ```
Markdown
UTF-8
4,991
2.84375
3
[ "Apache-2.0" ]
permissive
+++ title = "Design" description = "Dive into key design elements" +++ Read more [about the goals](../goals/) first if necessary. # Registries ## Driver registry The core of extensibility is implemented as an in-process driver registry. The things that make it work are: - Clear priority classes via explicit dependencies. Each drive ris loaded after its dependencies are loaded so a driver can assume that all relevant drivers of lower level types were fully loaded. - Native way to skip a driver on unrelated platform. - At compile time via conditional compilation. - At runtime via early `Init()` exit. - Native way to return the state of all registered drivers. The ones loaded, the ones skipped and the ones that failed. - Native way to declare inter-driver dependency. A specialized processor driver may dependent on a generic one and the drivers will be loaded sequentially. - In another other case, the drivers are loaded in parallel for minimum total latency. ## Interface-specific registries Many packages under [conn](/x/conn/v3) contain interface-specific `XXXreg` registry as a subpackage. The goal is to not have a one-size-fits-all approach that would require broad generalization; when a user needs an I²C bus handle, the user knows they can find it in [conn/i2c/i2creg](/x/conn/v3/i2c/i2creg). It's is assumed the user knows what bus to use in the first place. Strict type typing guides the user towards providing the right object. A non exhaustive list of registries: [gpioreg](/x/conn/v3/gpio/gpioreg), [i2creg] (/x/periph/conn/i2c/i2creg), [onewirereg](/x/conn/v3/onewire/onewirereg), [pinreg](/x/conn/v3/pin/pinreg), [spireg](/x/conn/v3/spi/spireg). The packages follow the `Register()` and `All()` pattern. At [host.Init()](/x/host/v3#Init) time, each driver registers itself in the relevant registry. Then the application can query for the available components, based on the type of hardware interface desired. For each of these registries, registering the same pseudo name twice is an error. This helps reducing ambiguity for the users. # pins There's a strict separation between [analog](/x/conn/v3/analog#PinIO), [digital (gpio)](/x/conn/v3/gpio#PinIO) and [generic pins](/x/conn/v3/pins#Pin). The common base is [pins.Pin](/x/conn/v3/pins#Pin), which is a purely generic pin. This describes GROUND, VCC, etc. Each pin is registered by the relevant device driver at initialization time and has a unique name. The same pin may be present multiple times on a header. The only pins not registered are the INVALID ones. There's one generic at [pins.INVALID](/x/conn/v3/pins#INVALID) and two specialized, [analog.INVALID](/x/conn/v3/analog#INVALID) and [gpio.INVALID](/x/conn/v3/gpio#INVALID). *Warning:* analog is not yet implemented. # Edge based triggering and input pull resistor CPU drivers can have immediate access to the GPIO pins by leveraging memory mapped GPIO registers. The main problem with this approach is that one looses access to interrupted based edge detection, as this requires kernel coordination to route the interrupt back to the user. This is resolved by to use the GPIO memory for everything _except_ for edge detection. The CPU drivers has the job of hiding this fact to the users and make the dual-use transparent. Using CPU specific drivers enable changing input pull resistor, which sysfs notoriously doesn't expose. The setup described above enables the best of both world, low latency read and write, and CPU-less edge detection, all without the user knowing about the intricate details! # Ambient vs opened devices A device can either be ambient or opened. An ambient device _just exists_ and doesn't need to be opened. Any other device require an `open()`-like call to get an handle to be used. Most operating system virtualizes the system's GPU even if the host system only has one video card. The application "opens" the video card, effectively its driver, and ask the GPU device drive rto load texture, run shaders and display in a window context. When working with hardware, coordination of multiple users is needed but virtualization eventually fall short in certain use cases. Ambient devices are point-to-point single bit devices; GPIO, LED, pins headers. They are simplistic in nature and normally soldered on the board. They are often spec'ed by a datasheet. Sharing the device across applications doesn't make sense yet it is hard to do via the OS provided means. Opened devices are dynamic in nature. They may or may not be present. They may be used by multiple users (applications) concurrently. This includes buses and devices connected to buses. Using an ambient design is useful for the user because it can be presented by statically typed global variables. This reduces ambiguity, error checking, it's just there. Openable devices permits state, configurability. You can connect a device on a bus. Multiple applications can communicate to multiple devices on a share bus.
Java
UTF-8
1,449
2.65625
3
[]
no_license
package ru.toolkas.jshell.lang; import ru.toolkas.jshell.runtime.JShellContext; import ru.toolkas.jshell.runtime.JShellRuntimeException; import ru.toolkas.jshell.runtime.TypeCastException; import java.io.File; public class NullValue implements Value { @Override public Type type() { return Type.UNDEFINED; } @Override public boolean asBoolean(JShellContext context) throws JShellRuntimeException { throw new TypeCastException(Type.UNDEFINED, Type.BOOLEAN, null); } @Override public String asString(JShellContext context) throws JShellRuntimeException { throw new TypeCastException(Type.UNDEFINED, Type.STRING, null); } @Override public double asNumber(JShellContext context) throws JShellRuntimeException { throw new TypeCastException(Type.UNDEFINED, Type.NUMBER, null); } @Override public File asFile(JShellContext context) throws JShellRuntimeException { throw new TypeCastException(Type.UNDEFINED, Type.FILE, null); } @Override public Object asObject(JShellContext context) throws JShellRuntimeException { throw new TypeCastException(Type.UNDEFINED, Type.NUMBER, null); } @Override public String toString() { return "null"; } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { return obj instanceof NullValue; } }
TypeScript
UTF-8
1,312
2.59375
3
[ "MIT" ]
permissive
import { Card } from '../../../interfaces' import Set from '../Primal Clash' const card: Card = { name: { en: "Weedle", fr: "Aspicot", es: "Weedle", it: "Weedle", pt: "Weedle", de: "Hornliu" }, illustrator: "Midori Harada", rarity: "Common", category: "Pokemon", set: Set, dexId: [ 13, ], hp: 50, types: [ "Grass", ], stage: "Basic", attacks: [ { cost: [ "Grass", ], name: { en: "Multiply", fr: "Multiplication", es: "Multiplicar", it: "Moltiplicazione", pt: "Multiplicar", de: "Vervielfachung" }, effect: { en: "Search your deck for Weedle and put it onto your Bench. Shuffle your deck afterward.", fr: "Cherchez Aspicot dans votre deck et placez-le sur votre Banc. Mélangez ensuite votre deck.", es: "Busca en tu baraja 1 Weedle y ponlo en tu Banca. Baraja las cartas de tu baraja después.", it: "Cerca Weedle nel tuo mazzo e mettilo nella tua panchina. Poi rimischia le carte del tuo mazzo.", pt: "Procure em seu baralho por Weedle e coloque-o no seu Banco. Em seguida, embaralhe seus cards.", de: "Durchsuche dein Deck nach Hornliu und lege es auf deine Bank. Mische anschließend dein Deck." }, }, ], weaknesses: [ { type: "Fire", value: "×2" }, ], retreat: 1, } export default card
Markdown
UTF-8
669
3.1875
3
[ "MIT" ]
permissive
Multiplies a scalar times a `Tensor` or `IndexedSlices` object. ``` tf.compat.v1.scalar_mul( scalar, x, name=None) ``` Intended for use in gradient code which might deal with `IndexedSlices` objects, which are easy to multiply by a scalar but more expensive tomultiply with arbitrary tensors. #### 参数: - **`scalar`** : A 0-D scalar `Tensor` . Must have known shape. - **`x`** : A `Tensor` or `IndexedSlices` to be scaled. - **`name`** : A name for the operation (optional). #### 返回: `scalar * x` of the same type ( `Tensor` or `IndexedSlices` ) as `x` . #### 加薪: - **`ValueError`** : if scalar is not a 0-D `scalar` .
Python
UTF-8
1,741
2.59375
3
[]
no_license
import numpy as np import math import matplotlib.pyplot as plt import vtk from matplotlib import pyplot from matplotlib import collections as mc from matplotlib.patches import Circle, Wedge, Polygon from matplotlib.collections import PatchCollection from vtk.util.numpy_support import vtk_to_numpy def create_horizontal_points(vertical_index): points = [(i*segment, vertical_index*L0) for i in range(0, resolution*n_cells + 1)] return np.asarray(points) def create_vertical_points(horizontal_index): points = [(horizontal_index*L0, i*segment) for i in range(0, resolution*n_cells + 1)] return np.asarray(points) if __name__ == '__main__': # plot from vtk reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName("data/mesh_assemble.vtu") reader.Update() data = reader.GetOutput() points = data.GetPoints() npts = points.GetNumberOfPoints() x = vtk_to_numpy(points.GetData()) triangles = vtk_to_numpy(data.GetCells().GetData()) ntri = triangles.size//4 # number of cells tri = np.take(triangles, [n for n in range(triangles.size) if n%4 != 0]).reshape(ntri,3) plt.figure(figsize=(8, 8)) plt.triplot(x[:,0], x[:,1], tri, marker='o', markersize=1, linewidth=0.5, color='b') plt.gca().set_aspect('equal') plt.axis('off') # homemade plot plt.figure(figsize=(8, 8)) L0 = 0.5 n_cells = 5 resolution = 10 segment = L0/resolution for i in range(0, n_cells + 1): points = create_horizontal_points(i) plt.plot(points[:,0], points[:, 1], marker ='o', markersize=1, linewidth=0.5, color='b') for i in range(0, n_cells + 1): points = create_vertical_points(i) plt.plot(points[:,0], points[:, 1], marker ='o', markersize=1, linewidth=0.5, color='b') plt.axis('off') plt.axis('equal') plt.show()
Java
UTF-8
747
2.234375
2
[]
no_license
package com.stech.csw.crawler.news.api.repository; import com.stech.csw.crawler.news.api.model.News; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface NewsRepository extends JpaRepository<News, Long> { @Query("SELECT n FROM News n WHERE n.title LIKE %?1%" + " OR n.content LIKE %?1%" + " OR n.link LIKE %?1% ORDER BY createdAt DESC") List<News> search(String keyword); @Query("SELECT n FROM News n WHERE n.rank = ?1 ORDER BY rank DESC") List<News> findByRank(Integer rank); News findByTitleAndLink(String title, String link); }
PHP
UTF-8
3,866
2.65625
3
[]
no_license
<?php declare(strict_types=1); /** * Saito - The Threaded Web Forum * * @copyright Copyright (c) the Saito Project Developers * @link https://github.com/Schlaefer/Saito * @license http://opensource.org/licenses/MIT */ namespace App\Controller\Component; use App\Model\Entity\Entry; use App\Model\Table\EntriesTable; use Cake\Controller\Component; use Cake\ORM\TableRegistry; use Saito\Exception\SaitoForbiddenException; use Saito\Posting\Basic\BasicPostingInterface; use Saito\Posting\Posting; use Saito\User\CurrentUser\CurrentUserInterface; class PostingComponent extends Component { /** * Creates a new posting from user * * @param array $data raw posting data * @param CurrentUserInterface $CurrentUser the current user * @return Entry|null on success, null otherwise */ public function create(array $data, CurrentUserInterface $CurrentUser): ?Entry { if (!empty($data['pid'])) { /// new posting is answer to existing posting $parent = $this->getTable()->get($data['pid']); $data = $this->prepareChildPosting($parent, $data); } else { /// if no pid is provided the new posting is root-posting $data['pid'] = 0; // We can't wait for entity-validation cause we check the category // in permissions. if (!isset($data['category_id'])) { throw new \InvalidArgumentException( 'No category for new posting provided.', 1573123345 ); } } $posting = new Posting($data + ['id' => 0]); $action = $posting->isRoot() ? 'thread' : 'answer'; // @td better return !$posting->isAnsweringForbidden(); $allowed = $CurrentUser->getCategories()->permission($action, $posting->get('category_id')); if ($allowed !== true) { throw new SaitoForbiddenException('Creating new posting not allowed.'); } return $this->getTable()->createEntry($data); } /** * Updates an existing posting * * @param Entry $entry the posting to update * @param array $data data the posting should be updated with * @param CurrentUserInterface $CurrentUser the current-user * @return Entry|null the posting which was asked to update */ public function update(Entry $entry, array $data, CurrentUserInterface $CurrentUser): ?Entry { $isRoot = $entry->isRoot(); if (!$isRoot) { $parent = $this->getTable()->get($entry->get('pid')); $data = $this->prepareChildPosting($parent, $data); } $allowed = $entry->toPosting()->withCurrentUser($CurrentUser)->isEditingAllowed(); if ($allowed !== true) { throw new SaitoForbiddenException('Updating posting not allowed.'); } return $this->getTable()->updateEntry($entry, $data); } /** * Populates data of an child derived from its parent-posting * * @param BasicPostingInterface $parent parent data * @param array $data current posting data * @return array populated $data */ public function prepareChildPosting(BasicPostingInterface $parent, array $data): array { if (empty($data['subject'])) { // if new subject is empty use the parent's subject $data['subject'] = $parent->get('subject'); } $data['category_id'] = $data['category_id'] ?? $parent->get('category_id'); $data['tid'] = $parent->get('tid'); return $data; } /** * Get Entries table * * @return EntriesTable */ protected function getTable(): EntriesTable { /** @var EntriesTable */ $table = TableRegistry::getTableLocator()->get('Entries'); return $table; } }
Markdown
UTF-8
2,163
3
3
[]
no_license
--- title: Desktop Notifier by Python date: 2017-07-28 16:37:40 tags: - Python --- This article show how to send desktop notice using Python ![simpleNotification](https://raw.githubusercontent.com/xibuka/git_pics/master/simpleNotification.png) # Install requirments we need to install `notify2` by pip ``` # pip install notify2 Collecting notify2 Downloading notify2-0.3.1-py2.py3-none-any.whl Installing collected packages: notify2 Successfully installed notify2-0.3.1 ``` <!-- more --> # Coding First we need to import notify2 ```python import notify2 ``` Then need to initialise the d-bus connection. D-Bus is a message bus system, a simple way for applications to talk to one another. ``` # initialise the d-bus connection notify2.init("hello") ``` Next we need to create a Notification object. The simplest way is ```python n = notify2.Notification(None) ``` else, you can add a icon to the notification. ```python n = notify2.Notification(None, icon = "/home/wenshi/Pictures/me.jpg") ``` next, set the urgency level for the notification. ```python n.set_urgency(notify2.URGENCY_NORMAL) ``` the other available options are ```python notify2.URGENCY_LOW notify2.URGENCY_NORMAL notify2.URGENCY_CRITICAL ``` next, you can decide how long will the notification will display. use `set_timeout` to set the time in milliseconds. ```python n.set_timeout(5000) ``` next, file the title and message body of the notification ```python n.update("hello title", "hello messages") ``` notification will be shown on screen by `show` method. ```python n.show() ``` # Try it. ```python import notify2 # initialise the d-bus connection notify2.init("hello") # create Notification object n = notify2.Notification(None, icon = "/path/to/your/image") # set urgency level n.set_urgency(notify2.URGENCY_NORMAL) # set timeout for a notification n.set_timeout(5000) # update notification data for Notification object n.update("hello title", "hello messages") # show notification on screen n.show() ``` and it will show up in your screen ![simpleNotification](https://raw.githubusercontent.com/xibuka/git_pics/master/simpleNotification.png)
Java
UTF-8
660
3.59375
4
[]
no_license
package com.company; import com.sun.source.util.SourcePositions; public class DefineBasicInfo { public static void main(String[] args) { // Define several things as a variable then print their values // Your name as a string // Your age as an integer // Your height in meters as a double // Whether you are married or not as a boolean String myName = "Martin Peleška"; int myAge = 48; double myHeight = 1.99; boolean married = false; System.out.println(myName); System.out.println(myAge); System.out.println(myHeight); System.out.println(married); } }
Java
UTF-8
1,973
3.6875
4
[]
no_license
//Scanner import java.util.Scanner; public class Lab { public static void main(String[] args) { // Scanner scan = new Scanner(System.in); // System.out.println("Are you in NY "); // String userName = scan; // boolean whereAreYou = scan.nextBoolean(); // // System.out.println("Are you in NY: " + whereAreYou); // int number = 100; // if (number % 15 == 0) // System.out.println("Divisible fby 15"); // else // System.out.println(number%15); // boolean GuestOneVegan = true; // boolean GuestTwoVegan = true; // // if (GuestOneVegan && GuestTwoVegan) // System.out.println("Only Veg. "); // else if (GuestOneVegan || GuestTwoVegan) // System.out.println("Some Veg. menu "); // else // System.out.println("Anything from the menu "); // print the names using for loop // String [] words = {"Dhaka", "Vienna", "New York", "Mumbai"}; // words [0] = "Dhaka"; // words [1]= "Vienna"; // words [2]= "New York"; // words [3]= "Mumbai"; // // for ( int i = 0; i <= words.length -1; i++) // { // System.out.println(words[i]); // } //String [] words = {"grow", "help", "learn", "happy"} //print words with length greater than 4 String [] words = {"grow", "help", "learn", "happy"}; words [0] = "grow"; words [1] = "help"; words [2] = "learn"; words [3] = "happy"; System.out.println(words.length); // // for (int i = 0; i >=words.length - 1; i++); // // if (words 4) { // // System.out.println(words[i]); // } // else { // // System.out.println("Ignore"); // } for (int i = 0; i <= words.length - 1; i++) if (words[i].length() >4){ System.out.println(words[i]); } } }
Python
UTF-8
151
3.203125
3
[]
no_license
s = input() now = "" ans = 0 for i in range(len(s)): if i == 0: now = s[0] continue if s[i] != now: ans += 1 now = s[i] print(ans)