language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
2,917
3
3
[]
no_license
# RR2015-FRC1410 The code is written in C++, using the Command Based Robot template. We have 4 subsystems, the DriveBase, IntakeArms, ToteLifter, and CanManipulator. The DriveBase Subsystem has 4 CANTalons, two per side to drive the robot. It also has a Gyro, for turning. We drive the DriveBase using a two stick tank drive, meaning that the left stick drives the left side of the robot, and the right stick drives the right side. Inside of this subsystem are also methods to return the Encoder (we have 2, one per side) values and Gyro values during Auto. The IntakeArms Subsystem has 4 CANTalons, two per side, with one motor to move the arm and one to turn a roller on each side. There are two methods, one to move the elbows, and one to toggle the rollers. Also, we have methods to use potentiometers, but we figured that we couldn't have them on the robot for mechanical reasons, so these methods are never used. The ToteLifter Subsystem has 1 CANTalon, used to drive the elevator up and down. We have one method to drive the elevator, one to return the state of the top (reverse) limit switch, and one to return the bottom (forward) limit switch. The CanManipulator Subsystem has 3 CANTalons, one to drive the elevator, and one on each side to move the arm. There is also one potentiometer plugged into the left and right CANTalon, and two limit switches in the elevator motor. There are two main methods, one to drive the elevator, and one to drive them arms. We also have methods to return potentiometer and limit switch values, and to reset the potentiometers. Moving on to control of the robot we have 2 Joysticks, which are Xbox 360 controllers for us. One is driver_stick, and is only used to drive the robot around, axis 1 for left, and axis 5 for right. The second is operator_stick, on which we use 4 JoystickButtons and 2 axis. JoystickButton 1 (A button) toggles the rollers. JoystickButton 2 (B button) toggles the back (ToteLifter) elevator. JoystickButton 3 (X button) moves the front (CanManipulator) elevator down, and JoystickButton 4 (Y button) moves it up. Axis 0 moves the upper (CanManipulator) arms, and axis 4 moves the lower (IntakeArms) arms. All of the Commands are organized into folders labeled with their respective Subsystems, so there are 4 (DriveBase, IntakeArms, CanManipulator, ToteLifter) folders. There is also an Auto folder, but this is unfinished at this time. You may notice two weird things. The first is the array and method at the top of the OI. These are used to add a dead-zone into the controller, making them less sensitive. The second would be the SimultaneousOp CommandGroups in the IntakeArms and CanManipulator Commands folders. These are used so that we can both drive the rollers/arms, and the elevator/arms simultaneously. We could have had a command for this, but by using a command group we can also use the separate commands outside of it.
Rust
UTF-8
776
2.609375
3
[]
no_license
use crate::Solution; impl Solution { fn find(x: usize, p: &mut [usize]) -> usize { if p[x] != x { p[x] = Solution::find(p[x], p); } p[x] } pub fn find_circle_num(is_connected: Vec<Vec<i32>>) -> i32 { let n = is_connected.len(); let mut p = (0..n).into_iter().collect::<Vec<usize>>(); let mut cnt = n; for i in 0..n { for j in 0..n { let parent_i = Solution::find(i, p.as_mut_slice()); let parent_j = Solution::find(j, p.as_mut_slice()); if is_connected[i][j] == 1 && parent_i != parent_j { p[parent_i] = parent_j; cnt -= 1; } } } cnt as i32 } }
C#
UTF-8
672
2.6875
3
[ "MS-PL" ]
permissive
using System; using System.IO; using System.Collections.Generic; namespace Acr.MvvmCross.Plugins.SignaturePad { public class SignatureResult { private readonly Func<Stream> getStreamFunc; public bool Cancelled { get; private set; } public IEnumerable<DrawPoint> Points { get; private set; } public SignatureResult(bool cancelled, Func<Stream> getStream, IEnumerable<DrawPoint> points) { this.Cancelled = cancelled; this.Points = points; this.getStreamFunc = getStream; } public virtual Stream GetStream() { var s = this.getStreamFunc(); s.Position = 0; return s; } } }
JavaScript
UTF-8
1,253
3.078125
3
[]
no_license
var fs = require('fs'); var globalConfig = require('./config'); // 记录日志 var fileName = globalConfig.log_path + '/' + globalConfig.log_name; function log(data) { // fs.writeFile(fileName, data + '\n', { flag: 'a' }, () => { }); // flag:a表示在原来基础上写入,不直接替换之前内容 fs.appendFile(fileName, data + '\n', () => { }); // append默认就是flag:a 追加写入,代替如上写法 // 同步的方式(尽量不用) // fs.writeFileSync(fileName, 'asd2'); } module.exports = log; /** * 第三个默认参数options中的mode * * { flag: 'a' ,mode:0o666} // 0o代表8进制 * 第一个数6:代表文件所有者的权限 * 第二个数6:代表同组用户的权限 * 第三个数6:非同组用户的权限 * * 其中每个数字有三个位分别对应可读、写、执行(如下) * r w x * 4 2 1 * ------- * 4 0 0 === 4 可读 * 4 2 0 === 6 可读可写 * 4 2 1 === 7 可读可写可执行 * 4 0 1 === 5 可读可执行 * ... */ /** * flag常用参数 * r read * rs readSync * w write * wx 排他写(写入的时候不允许其他人写) * a 追加 === fs.appendFile() * ax 排他追加 */
Shell
UTF-8
1,470
2.796875
3
[ "Apache-2.0" ]
permissive
#! /bin/sh # Copyright 2014 TIS Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. source /opt/cloudconductor/lib/common.sh source /opt/cloudconductor/lib/run-base.sh CONFIG_DIR="${ROOT_DIR}/etc" LOG_FILE="${LOG_DIR}/bootstrap.log" cd ${ROOT_DIR} log_info "execute first-setup." run ./bin/setup.sh if [ ${status} -ne 0 ]; then log_error "first-setup has finished abnormally." log_error ${output} echo "${output}" >&2 exit ${status} fi log_info "first-setup has finished successfully." log_info "execute metronome with setup event." /opt/cloudconductor/bin/metronome dispatch setup if [ $? -eq 0 ]; then log_info "setup has finished successfully." else log_error "setup has finished abnormally." exit -1 fi if [ -f /etc/sysconfig/network ]; then sed -i -e 's/HOSTNAME=.*/HOSTNAME=localhost.localdomain/' /etc/sysconfig/network fi if [ -f /etc/cloud/cloud.cfg ]; then sed -i -e '/^syslog_fix_perms/apreserve_hostname: true' /etc/cloud/cloud.cfg fi
SQL
UTF-8
6,035
2.984375
3
[]
no_license
--INSERCIÓN DE DATOS EN LA TABLA FESTIVAL INSERT INTO festival (id, nombre, fechaInicio, fechaFin) VALUES (1, 'ArenalSound', '2020-07-20', '2020-07-23'), (2, 'QuevedoFest', '2020-08-15', '2020-08-18'), (3, 'QuevedoFest', '2021-07-10', '2021-08-13'); --INSERCIÓN DE DATOS EN LA TABLA CARTEL INSERT INTO cartel (id, id_festival, nombre, fecha, hora, generoMusical) VALUES (1, 1, 'Savage', '2020-07-20', '15:30', 'Trap'), (2, 1, 'Colors', '2020-07-21', '16:30', 'Reggaetón'), (3, 1, 'Random', '2020-07-22', '15:30', 'Rock'), (4, 1, 'Reel', '2020-07-23', '15:00', 'Rap'), (5, 2, 'Sun', '2020-08-15', '15:30', 'Hardcore'), (6, 2, 'Fandom', '2020-08-16', '17:30', 'Reggae'), (7, 2, 'Moon', '2020-08-17', '16:30', 'Pop'), (8, 2, 'World', '2020-08-18', '15:00', 'Punky'), (9, 3, 'Luxury', '2021-07-10', '15:00', 'Hardcore'), (10, 3, 'Swing', '2021-07-11', '16:00', 'Pop'), (11, 3, 'Gang', '2021-07-12', '17:00', 'Flamenco'), (12, 3, 'Rumba', '2021-07-13', '15:30', 'Bachata'); --INSERCIÓN DE DATOS EN LA TABLA ESCENARIO INSERT INTO escenario (id, id_cartel, nombre, fecha, hora, capacidad) VALUES (1, 9, 'Jungly', '2020-07-22', '15:30', 1000), (2, 7, 'BigSound', '2020-08-16', '17:30', 1200), (3, 10, 'Kontrol', '2021-07-10', '15:00', 950), (4, 11, 'Fire', '2020-08-15', '15:30', 900), (5, 12, 'Summer', '2021-07-12', '17:00', 950); --INSERCIÓN DE DATOS EN LA TABLA ENTRADA INSERT INTO entrada (id, id_festival, fecha, precio) VALUES (1, 1, '2020-07-20', 80), (2, 2, '2020-08-15', 70), (3, 3, '2021-07-10', 90), (4, 3, '2021-07-10', 90), (5, 3, '2021-07-10', 90); --INSERCIÓN DE DATOS EN LA TABLA CLIENTE INSERT INTO cliente (dni, id_entrada, nombre, apellido1, apellido2, fechaNac, localidad, telefono) VALUES ('12365478R', 1, 'Raúl', 'Gonzalez', 'Fernandez', '1998-12-20', 'Móstoles', '654987321'), ('78954623L', 2, 'Cristiano', 'Ronaldo', 'Pérez', '1997-10-05', 'Mérida', '645123789'), ('45612378D', 3, 'Luisa', 'Ruiz', 'Verde', '2005-07-11', 'Alcorcón', '698675645'), ('65784147M', 4, 'Carla', 'Alonso', 'De Mateo', '2006-08-15', 'Getafe', '636521425'), ('65897423N', 5, 'Sergio', 'Ramos', 'Palao', '1990-04-24', 'Rivas-Vaciamadrid', '678951423'); --INSERCIÓN DE DATOS EN LA TABLA MAYOR DE EDAD INSERT INTO mayorEdad (dni) VALUES ('12365478R'), ('78954623L'), ('65897423N'); --INSERCIÓN DE DATOS EN LA TABLA PERTENECER INSERT INTO pertenecer (dni_mayorEdad, id_clubFans) VALUES ('78954623L', 1), ('65897423N', 3); --INSERCIÓN DE DATOS EN LA TABLA CLUB DE FANS INSERT INTO clubFans (id, dni_artista, fecha_creacion, nombre, recaudacion) VALUES (1, '45698235S', '2017-09-18', 'Los Tanguitos', 3000), (2, '78998754T', '2015-10-25', 'Believers', 2700), (3, '25896346K', '2018-02-20', 'Ros-alitas', 1800); --INSERCIÓN DE DATOS EN LA TABLA ARTISTA INSERT INTO artista (dni, id_cartel, dni_manager, fechaYHora_camerino, nombre, nacionalidad, salario, generoMusical, hora_entrada, hora_salida) VALUES ('14725835J', 1, '56351711M', '2020-07-20 14:30:00', 'Kidd Keo', 'España', 1500, 'Trap', '15:30', '17:30'), ('36985214H', 1, '45447824A', '2020-07-20 16:30:00', 'Camin', 'España', 1000, 'Trap', '17:30', '18:30'), ('25896346K', 1, '65686764S', '2020-07-20 17:30:00', 'Rosalia', 'España', 1600, 'Trap', '18:30', '22:30'), ('45698235S', 1, '32365362P', '2020-07-20 21:30:00', 'C. Tangana', 'España', 1900, 'Trap', '22:30', '24:00'), ('86249517B', 9, '21546866W', '2021-07-10 14:00:00', 'AngerFirst', 'Alemania', 2000, 'Hardcore', '15:00', '19:30'), ('54982175B', 9, '45447824A', '2021-07-10 18:30:00', 'HeadHunter', 'Holanda', 2200, 'Hardcore', '19:30', '20:30'), ('75324861M', 9, '95987994I', '2021-07-10 19:30:00', 'Coone', 'Francia', 2100, 'Hardcore', '20:30', '22:00'), ('78998754T', 10, '56351711M', '2021-07-11 15:30:00', 'Justin Biever', 'EEUU', 2500, 'Pop', '16:30', '19:00'), ('48269125W', 10, '12321141T', '2021-07-11 18:00:00', 'Jennifer López', 'EEUU', 2600, 'Pop', '19:00', '20:00'), ('45987623G', 11, '65686764S', '2021-07-12 16:00:00', 'Daviles de Novelda', 'España', 1200, 'Flamenco', '17:00', '18:30'), ('64859127F', 11, '74455778H', '2021-07-12 17:30:00', 'Chambao', 'España', 1250, 'Flamenco', '18:30', '19:30'), ('72486593H', 12, '46685513F', '2021-07-12 14:00:00', 'Romeo Santos', 'Colombia', 1700, 'Bachata', '15:30', '18:00'), ('81592634T', 12, '55566989Q', '2021-07-12 18:15:00', 'Wellinton Quiw', 'Colombia', 800, 'Bachata', '18:30', '19:00'), ('94587126A', 12, '56351711M', '2021-07-12 18:00:00', 'Farruko', 'Puerto Rico', 2400, 'Bachata', '19:00', '21:00'); --INSERCIÓN DE DATOS EN LA TABLA CAMERINO INSERT INTO camerino (fechaYHora, id, gama, nombre) VALUES ('2020-07-20 14:30:00', 1,'Alta', 'Rumba'), ('2020-07-20 16:30:00', 2, 'Media', 'World'), ('2020-07-20 17:30:00', 1, 'Alta', 'Rumba'), ('2020-07-20 21:30:00', 1 , 'Alta', 'Rumba'), ('2021-07-10 14:00:00', 2 , 'Media', 'World'), ('2021-07-10 18:30:00', 1, 'Alta', 'Rumba'), ('2021-07-10 19:30:00', 2, 'Media', 'World'), ('2021-07-11 15:30:00', 1, 'Alta', 'Rumba'), ('2021-07-11 18:00:00', 1, 'Alta', 'Rumba'), ('2021-07-12 16:00:00', 2, 'Media', 'World'), ('2021-07-12 17:30:00', 2, 'Media', 'World'), ('2021-07-12 14:00:00', 2, 'Media', 'World'), ('2021-07-12 18:15:00', 1, 'Alta', 'Rumba'), ('2021-07-12 18:00:00', 2, 'Alta', 'World'); --INSERCIÓN DE DATOS EN LA TABLA MÁNAGER (TABLA CREADA POSTERIORMENTE) INSERT INTO manager (dni, nombre_completo, telefono) VALUES ('55566989Q', 'Luis Fernández Gomez', '699885544'), ('45447824A', 'Manolo Lama', '644777456'), ('65686764S', 'María Gomez Palos', '633662211'), ('32365362P', 'Ramón Moreno', '644665544'), ('21546866W', 'Nuria Ros Plaz', '685867417'), ('95987994I', 'Mariano Rajoy Rojo', '677284663'), ('56351711M', 'Irene Montero', '623245112'), ('12321141T', 'Sebastián Filimón', '673525366'), ('74455778H', 'Jaime Montaner Pla', '685958685'), ('46685513F', 'Pablo Moreno Pérez', '666666645');
Python
UTF-8
483
3.109375
3
[]
no_license
print("你".encode("BIG5")) print("你".encode("utf-8")) #f = open("a.txt", "r", encoding="utf-8") with open("a.txt", "r", encoding="utf-8") as f: article = f.read() #f.close() result = {} total = 0 for c in article: total = total + 1 c = c.lower() if not c in result: #第一次遇到, 才被設進result{} result[c] = 1 else: result[c] = result[c] + 1 print(result) prob = {} for key in result: prob[key] = result[key] / total print(prob)
Python
UTF-8
1,146
3.125
3
[]
no_license
LarghezzaImg=500 AltezzaImg=500 dimTessera=50 #Creo immagine vuote img=createImage(LarghezzaImg,AltezzaImg,RGB) #Carico pixel nell'array pixels img.loadPixels() def setup(): size(LarghezzaImg,AltezzaImg) creaImg() def creaImg(): #Apro file di input input = createInput("Input"); content = "" #Leggo il primo carattere (da saltare) data1 = input.read() pixel=0 while (data1 != -1 and pixel<LarghezzaImg*AltezzaImg): #Leggo il primo carattere data1 = input.read() if data1 != -1: #Se l'input non è finito, Leggo il secondo carattere data2 = input.read() if data2 != -1: #Se l'input non è finito, Leggo il terzo carattere data3=input.read() #Creo il pixel #passo al lixel successivo img.pixels[pixel]=color(data1,data2,data3) pixel+=1 #Aggiorno l'immagine con i pixel nuovi img.updatePixels() #Visualizzo l'immagine image(img,0,0) #Salvo l'immagine save("Out.tiff") print(pixel)
C++
UTF-8
2,429
4.25
4
[]
no_license
// Creating binary tree (using queue) // Preorder , Inorder , Postorder Traversals (Iterative Procedure) #include<iostream> #include<stdlib.h> #include<queue> #include<stack> using namespace std; struct node { struct node *lchild; int data; struct node *rchild; }; struct node *root = NULL; void CreateBinaryTree() { struct node *p , *t; int x; queue<struct node *>q; cout << "Enter root node : "; cin >> x; root = (struct node *)malloc(sizeof(struct node)); root->data = x; root->lchild = root->rchild = NULL; q.push(root); while(!q.empty()) { p = q.front(); q.pop(); cout << "Enter left child of " << p->data << " : "; cin >> x; if(x != -1) { t = (struct node *)malloc(sizeof(struct node)); t->data = x; t->lchild = t->rchild = NULL; p->lchild = t; q.push(t); } cout << "Enter right child of " << p->data << " : "; cin >> x; if(x != -1) { t = (struct node *)malloc(sizeof(struct node)); t->data = x; t->lchild = t->rchild = NULL; p->rchild = t; q.push(t); } } } void IPreOrder(struct node *p) { stack<struct node *>s; while(p!=NULL || !s.empty()) { if(p!=NULL) { cout << p->data << " "; s.push(p); p = p->lchild; } else { p = s.top(); s.pop(); p = p->rchild; } } } void IInOrder(struct node *p) { stack<struct node *>s; while(p!=NULL || !s.empty()) { if(p!=NULL) { s.push(p); p = p->lchild; } else { p = s.top(); s.pop(); cout << p->data << " "; p = p->rchild; } } } void IPostOrder(struct node *p) { } int main() { CreateBinaryTree(); cout << endl; cout << "PreOrder Traversal : "; IPreOrder(root); cout << endl; cout << endl; cout << "InOrder Traversal : "; IInOrder(root); cout << endl; cout << endl; cout << "PostOrder Traversal : "; IPostOrder(root); cout << endl; return 0; }
SQL
UTF-8
2,358
3.484375
3
[]
no_license
select 1 AS version ,'1900-01-01 00:00:00'::timestamp without time zone AS date_from ,'2199-12-31 23:59:59'::timestamp without time zone AS date_to , date_trunc('day', data)::timestamp without time zone as data ,to_char(data,'YYYY')::BigInt as ano ,(to_char(data, 'mm')::integer) as mes ,(((to_char(data, 'mm')::integer)/7))+1 as semestre ,(((to_char(data, 'mm')::integer)/7))+1 || '° Semestre' as semestre_desc ,(((to_char(data, 'mm')::integer)/7))+1 || '° Sem' as semestre_abrev , to_char(data,'Q')::BigInt as trimestre_ano , to_char(data,'Q')::BigInt || '° Trimestre' as trimestre_desc , to_char(data,'Q')::BigInt || '° Trim' as trimestre_abrev ,CASE when ((to_char(data, 'mm')::integer) <= 2) then 1 when ((to_char(data, 'mm')::integer) <= 4) then 2 when ((to_char(data, 'mm')::integer) <= 6) then 3 when ((to_char(data, 'mm')::integer) <= 8) then 4 when ((to_char(data, 'mm')::integer) <= 10) then 5 when ((to_char(data, 'mm')::integer) <= 12) then 6 end as bimestre ,CASE when ((to_char(data, 'mm')::integer) <= 2) then '1° Bimestre' when ((to_char(data, 'mm')::integer) <= 4) then '2° Bimestre' when ((to_char(data, 'mm')::integer) <= 6) then '3° Bimestre' when ((to_char(data, 'mm')::integer) <= 8) then '4° Bimestre' when ((to_char(data, 'mm')::integer) <= 10) then '5° Bimestre' when ((to_char(data, 'mm')::integer) <= 12) then '6° Bimestre' end as bimestre_desc ,CASE when ((to_char(data, 'mm')::integer) <= 2) then '1° Bim' when ((to_char(data, 'mm')::integer) <= 4) then '2° Bim' when ((to_char(data, 'mm')::integer) <= 6) then '3° Bim' when ((to_char(data, 'mm')::integer) <= 8) then '4° Bim' when ((to_char(data, 'mm')::integer) <= 10) then '5° Bim' when ((to_char(data, 'mm')::integer) <= 12) then '6° Bim' end as bimestre_abrev , to_char(data,'TMMONTH')::Character varying(9)as mes_desc , to_char(data,'TMMon')::Character varying(3) as mes_abrev , to_char(data,'WW')::BigInt as semana_ano , to_char(data,'DDD')::BigInt as dia_ano , to_char(data,'DD')::BigInt as dia_mes , to_char(data,'D')::BigInt as dia_semana , to_char(data,'TMDay')::Character varying(13) as dia_semana_desc , to_char(data,'TMDY')::Character varying(3) as dia_semana_abrev FROM generate_series( to_date('2013-01-01','YYYY-MM-DD') ,to_date('2019-01-01','YYYY-MM-DD') -- - interval '365 day' ,'1 day' ) data;
Swift
UTF-8
838
4.15625
4
[]
no_license
// // SeqSearch.swift // 查找算法相关 // // Created by Tate on 2021/10/8. // import Foundation //有一个数列: {1,8, 10, 89, 1000, 1234} ,判断数列中是否包含此名称【顺序查找】 要求: 如果找到了,就提 示找到,并给出下标值。 /*** 这里我们实现的线性查找是找到一个满足条件的值,就返回 * @param arr * @param value * @return 就返回索引i,没有找到就返回 - 1 */ //时间复杂度 O(n) 线性级 还不错。如果你有 100 个元素,这种算法就要做 100 次工作。数据量翻倍那么运行时间也翻倍。例子:线性查找。 func seqSearch(_ numbers:[Int] ,_ value:Int) -> Int { let n = numbers.count for i in 0..<n { if numbers[i] == value { return i } } return -1 }
JavaScript
UTF-8
1,580
2.6875
3
[ "MIT" ]
permissive
'use strict'; var objectAssign = require('object-assign'); // based on angular style commits // https://github.com/angular/angular.js/blob/v1.4.8/CONTRIBUTING.md#commit module.exports = function parseCommit(commit) { // add defaults objectAssign(commit, { type: '', isRevert: false, typeIsStandard: false, scope: '', body: '', footer: '' }); objectAssign(commit, parseMessage(commit.title)); return commit; }; function parseMessage(message) { var revert = 'revert:'; if (message.indexOf(revert) === 0) { var a = { isRevert: true }; objectAssign(a, parseMessage(message.substr(7))); return a; } var types = ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'chore', 'revert']; var firstColonIndex = message.indexOf(':'); if (firstColonIndex <= 0) { return {}; } var preTitle = message.substr(0, firstColonIndex); var postTitle = message.substr(firstColonIndex + 1); var preTitleExp = /^([^\(]+)(\(([^\)]+)\))?/; var postTitleExp = /^([^\n]*)(\n[^\n]*)?(\n[^\n]*)?/; var preTitleParts = preTitle.match(preTitleExp); var postTitleParts = postTitle.match(postTitleExp); if (!preTitleParts || !postTitleParts) { return {}; } var type = preTitleParts[1].toLowerCase(); return { type: type, typeIsStandard: types.indexOf(type) !== -1, scope: preTitleParts[3], title: postTitleParts[1] ? postTitleParts[1].trim() : '', body: postTitleParts[2] ? postTitleParts[2].trim() : '', footer: postTitleParts[3] ? postTitleParts[3].trim() : '' }; }
Java
UTF-8
511
2.0625
2
[]
no_license
package org.jrest4guice.commons.fileupload; import javax.servlet.http.HttpServletRequest; import com.google.inject.Inject; /** * * @author <a href="mailto:zhangyouqun@gmail.com">cnoss (QQ:86895156)</a> * */ public class UploadMonitor { @Inject private HttpServletRequest request; public UploadInfo getUploadInfo() { if (request.getSession().getAttribute("uploadInfo") != null) return (UploadInfo) request.getSession().getAttribute("uploadInfo"); else return new UploadInfo(); } }
Java
UTF-8
2,794
2.171875
2
[]
no_license
package com.example.oleksandr.browser; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private WebView mWevView; //private MyWebViewClient mMyWebViewClient; private Toast mToast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWevView = (WebView) findViewById(R.id.webView); mWevView.getSettings().setJavaScriptEnabled(true); mWevView.loadUrl("https://www.google.com.ua"); mWevView.setWebViewClient(new MyWebViewClient()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id){ case R.id.action_settings: final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this); alertBuilder.setTitle("Settings"); alertBuilder.setMessage("123"); alertBuilder.setIcon(R.mipmap.ic_launcher); alertBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //TODO } }); alertBuilder.setNegativeButton("Cancle", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //TODO } }); alertBuilder.show(); break; case R.id.back: onBackPressed(); break; case R.id.next: //TODO break; case R.id.reload: mWevView.reload(); break; default: return super.onOptionsItemSelected(item); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (mWevView.canGoBack()){ mWevView.goBack(); }else { super.onBackPressed(); mToast= Toast.makeText(getApplicationContext(), "The last page", Toast.LENGTH_LONG); mToast.show(); } } }
Python
UTF-8
288
2.6875
3
[]
no_license
import util from my_util import util2 #my_utin is package or folder #util, util2 is module or a file from my_util.util2 import squre as squre_x print(util.sum(1,2)) #3 print(util2.squre(2)) #4 print(squre_x(3)) #9 #pip install .... #pip uninstall ... #to install package of modules
C
UTF-8
1,518
3.71875
4
[ "MIT" ]
permissive
/* Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them. Example 1: Input: nums = ["01","10"] Output: "11" Explanation: "11" does not appear in nums. "00" would also be correct. Example 2: Input: nums = ["00","01"] Output: "11" Explanation: "11" does not appear in nums. "10" would also be correct. Example 3: Input: nums = ["111","011","001"] Output: "101" Explanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct. Constraints: n == nums.length 1 <= n <= 16 nums[i].length == n nums[i] is either '0' or '1'. All the strings of nums are unique. */ #include <assert.h> #include <stdio.h> #include <string.h> #define nelem(x) (sizeof(x) / sizeof(x[0])) char * dbs(const char **s, size_t n, char *b) { size_t i; for (i = 0; i < n; i++) b[i] = (s[i][i] == '0') ? '1' : '0'; b[i] = '\0'; return b; } void test(const char **s, size_t n) { char b[128]; size_t i; dbs(s, n, b); printf("%s\n", b); for (i = 0; i < n; i++) assert(strcmp(b, s[i]) != 0); } int main(void) { const char *s1[] = {"01", "10"}; const char *s2[] = {"00", "01"}; const char *s3[] = {"111", "011", "001"}; const char *s4[] = {"010", "011", "100"}; const char *s5[] = {"0101", "0000", "1000", "1111"}; test(s1, nelem(s1)); test(s2, nelem(s2)); test(s3, nelem(s3)); test(s4, nelem(s4)); test(s5, nelem(s5)); return 0; }
C++
WINDOWS-1252
574
2.953125
3
[]
no_license
#include<iostream> using namespace std; const int maxn=10010; int data[maxn][maxn]={0}; bool visited[maxn]={false}; void dfs(int nowVisit,int N,int cursum, int& max){ //cursum++; visited[nowVisit]=true; if(cursum>max) max=cursum; for(int v=0;v<N;v++){ if(visited[v]==false&&data[nowVisit][v]!=0){ dfs(v,N,cursum+1,max); } } } int main(){ int N,M; //MǸ cin>>N>>M; int u,v; for(int i=0;i<N-1;i++){ cin>>u>>v; data[u][v]=data[v][u]=true; } int cursum=0,max=0; visited[M]=true; dfs(M,N,cursum,max); cout<<max<<endl; return 0; }
PHP
UTF-8
1,337
2.75
3
[]
no_license
<?php function printMsg($msg, $redirect) { echo "<div class='msg'>" . $msg . "</div>"; echo "<script>"; echo "window.location ='" . $redirect . "'"; echo "</script>"; } function setToken($conn, $username) { $token = uniqid(); $sql = "DELETE FROM wanwan418_certificates WHERE username='$username'"; $conn->query($sql); $sql = "INSERT INTO wanwan418_certificates(username, token) VALUES ('$username','$token')"; $conn->query($sql); setcookie("token", $token, time()+3600*24); } function getUserByToken($conn, $token) { if (isset($token) && !empty($token)) { $sql = "SELECT * FROM wanwan418_certificates WHERE token='$token'"; $result = $conn->query($sql); if(!$result || $result->num_rows <= 0) { return null; } $row = $result->fetch_assoc(); return $row['username']; } else { return null; } } function deleteBtn($id) { return " <div class='deleteComment'> <form method='POST' action='delete_comment.php'> <input type='hidden' name='id' value='$id'> <input type='submit' value='刪除'> </form> </div> "; } function editBtn($id) { return " <div class='editComment'> <form method='GET' action='edit_comment.php'> <input type='hidden' name='id' value='$id'> <input type='submit' value='編輯'> </form> </div> "; } ?>
TypeScript
UTF-8
529
2.8125
3
[ "MIT" ]
permissive
import * as Yup from 'yup'; const NewPatientSchema = Yup.object().shape({ name: Yup.string().trim().required('Digite o nome !'), gender: Yup.string().required('Informe o sexo !').oneOf(['male', 'female']), birthdate: Yup.date().required('Informe a data de nascimento !'), medication: Yup.string().required('Informe as medicações !'), height: Yup.number().required('Informe a altura !'), weight: Yup.number().required('Informe o peso !') }); export default NewPatientSchema;
Markdown
UTF-8
18,482
3.03125
3
[ "BSD-3-Clause", "MIT", "CC-BY-2.0", "CC-BY-3.0", "CC-BY-4.0" ]
permissive
# README 之道 <!-- Notes on Chinese formatting: * GitHub does not support inline styles, leading to appearance of oblique text which is wrong in Chinese. I have replaced some of these <em>'s with bold text. * Do not try to use line breaks for Chinese, or you get a bunch of extra spaces. If you find the source ugly without linebreak, blame markdown and let it be. --> ## 名词解释 “README”(读我)这个词从何而来? 正式命名的日期可以追溯到**至少** 1970 年和 [PDP-10](http://pdp-10.trailing-edge.com/decuslib10-04/01/43,50322/read.me.html);不过也有可能是来自更早之前放在打孔卡片上的便签纸,上面潦草地写着的“READ ME!”。 有位读者<sup>[1](#footnote-1)</sup>则提议说,“README”可能是来自于《爱丽丝漫游仙境》,其中一瓶药水和一个月饼上分别贴着“DRINK ME”(喝我)和“EAT ME”(吃我)的标签。 README 这个词从出现开始就一直是大写的。除了大写单词更醒目之外,UNIX 系统中大写字母会排在小写字母的前面,这样 README 就会显示在其它内容的前面 <sup>[2](#footnote-2)</sup>。 这样做的目的显而易见:“这是进行下一步之前的**重要信息**”。让我们来看一下现代的“**重要信息**”是怎么构成的。 ## 针对创建者和使用者 这是一篇关于 README 的文章,介绍了做什么、为什么要做、怎么才能做好。 README 是写给模块创建者的。模块创建者的工作是创建一些能持续的东西,这是一种内在的动机,尽管作者可能并没想分享他的工作。一个没有文档的模块,往往时隔 6 个月后,就连作者自己都会觉得陌生。 README 也是写给模块使用者的。每个模块的作者同时也是该模块的使用者。Node 有一个非常健康的依赖关联度:没人会处在依赖树的底部。 尽管内容主要是跟 Node 相关,也同样适用于其它语言的生态系统。 ## 很多模块,有好有坏 Node 的生态系统源于它的模块,[npm](https://npmjs.org)起着**关键**作用。Node 开发人员每周都会评估包含在他们的项目中的几十个模块。只要会写`npm install`,就能在日常工作中使用各种成熟的模块。 npm 可以非常方便的对模块进行打包和分发,但是质量却是良莠不齐:有新的、有旧的,甚至有些连用途都不知道。 什么是坏的模块?名字不清晰(猜猜 `fudge` 干什么的?)、没有文档、没有测试、没有注释,还有函数名字不易于理解。 很多模块没有活跃的维护者。如果一个模块没人回答问题或者说明模块的用途,再加上没有文档,就会变成一个火星上的东西,不可用并难以理解。 那些有文档的模块质量不好的原因又是什么?有的是因为文档里只有一行描述: `"sorts numbers by their hex value"`。有的是因为文档里只是一些代码片段。这使得模块使用者只能通过阅读源码来理解模块是怎么工作的。编写优秀的文档可以使用户不用阅读源码就能理解你模块的精妙之处。 Node的生态环境非常广泛:由大量的“只做一件事”的模块构成。[例外](https://github.com/lodash/lodash)当然也有,但总之都是那些“只做一件事”的大众统治着 Node 世界。 这就有一个易于发现的问题:找到你想要的**高质量**模块很困难。 **没事儿**。低门槛的生态、是否易于发现的问题总比出现封闭的社区文化问题好。 并且,事实证明可发现性问题总是容易解决的。 ## 条条大路通向 README.md Node 社区已经用不同的方法来着手解决可发现性的问题。 一些有经验的 Node 开发者合力创建了高质量模块的[列表](https://github.com/sindresorhus/awesome-nodejs),筛选出了每个类别里的最好的模块。 受到社交图谱的启发,一个替代 `npm search` 的查找工具 [node-modules.com](http://node-modules.com/) 利用 GitHub 的社交图谱来查找你的朋友喜欢或创建的模块。 当然新的开发者还是可以用 npm 自带的 [search](https://npmjs.org) 功能。 用户无论是在 [npmjs.org](https://npmjs.org) 或者 [github.com](https://github.com) 或在其它途径发现了你的模块,首先映入他们眼帘的是 README。如何在这惊鸿一瞥中给他们留下深刻的印象? ## 职业的模块勘探 ### README:一站式服务 README 是使用者首先(或唯一)审视你作品的入口。用户希望模块能满足他们的需要,所以你要清楚的说明你的模块的主要作用和优势。 你要做的是 1. 告诉他们这是什么 (使用场景) 2. 告诉他们在实际使用中是什么样子 3. 告诉他们使用的方法 4. 告诉他们其它相关的细节 这是 *你* 的工作。模块作者要证明他的作品在众多模块中是廖落星辰里的璀璨明珠。既然很多开发者第一眼看到的是你的 README,README 的编写质量决定了是否能给人留下好的第一印象。 ### 简洁 README 必须要有,但是 README 内容的长度和质量没什么关系。理想的 README 应该尽可能的短。详细的文档可以在单独的页面里描述。保持 README 简洁。 ### 以史为鉴 古人云:以史为鉴,可以知兴替。开发者编写文档已经有多年的历史了。值得我们花时间去看看在 Node 之前人们是怎么正确写文档的。 在某些方面,Node 跟 Perl 非常类似。都是高级脚本语言、采用了很多 UNIX 的理念、推动了互联网的发展、都有广泛的模块生态系统。 事实证明 Perl 社区的[圣僧们](http://perlmonks.org)在编写[高质量 README](http://search.cpan.org/~kane/Archive-Tar/lib/Archive/Tar.pm)方面很有经验。CPAN 是值得仔细阅读的优秀资源, 可以学到一个社区如何能够始终如一的编写出高质量的文档。 ### 没有 README 就没有抽象 没有 README 意味着开发者需要阅读源码才能理解你的模块。 Perl 圣僧们所分享的智慧: > 只要你的文档是完备的,用户就可以直接使用你的模块而无需去阅读源码。这是非常重要的。通过文档可以在很大程度上将你的模块的外部接口和内部实现进行分离。这样就可以在保持接口不变的情况下,灵活的修改内部实现。 > > 记住: 对模块进行定义的是文档而不是代码。 ——[Ken Williams](http://mathforum.org/ken/perl_modules.html#document) ### 关键要素 有了 README 之后,勇敢的模块探险家会阅读它来判断模块是否满足开发者的需要。这是他们的思维模式,一步一步的去了解模块的细节。 比如说,当我想要一个 2D 碰撞检测模块时我找到了[`collide-2d-aabb-aabb`](https://github.com/noffle/collide-2d-aabb-aabb)。 我开始从头开始检查这个模块: 1. **取名**:名字要能做到“其义自见”。`collide-2d-aabb-aabb` 听起来是个不错的匹配,尽管它假设我知道"aabb"是什么意思。如果名字含义非常模糊或与我要找的没什么关系,我就会继续查找其它的模块了。 2. **一行流**:通过一句话简明扼要的说明了这个模块是做什么的。 `collide-2d-aabb-aabb` 的描述是: > Determines whether a moving axis-aligned bounding box (AABB) collides with > other AABBs. 太棒了——描述了 AABB 的定义是什么,并且说明了这个模块是做什么的。现在开始评测它是否适合我的代码: 3. **用法**:在开始探究 API 文档之前,最好看看这个模块在实际应用中是什么样子。我可以快速决定用JS写的示例程序是否符合我的代码样式和我要解决的问题。人们会在很多问题上意见相左,比如 promises/callbacks 和 ES6。如果符合我的要求,我会进一步去研究细节。 4. **API**:模块的名字,描述和使用方法都符合我的胃口。在这一点上我很乐意使用这个模块。我需要浏览API来确定这就是我需要的,并且很容易整合到我的代码中。API 部分应该详述模块的对象和函数,以及它们的签名,返回值,回调和事件。当类型不是特别明显的时候,也无需进行描述。注意事项要描述清楚。 5. **安装**:当我读到这儿的时候我就要开始试用这个模块了。 如果不是通用的安装说明,就需要在这儿进行描述。即使是一句简单的`npm install`也好。 对于使用Node的新用户来说,放一个指向npmjs.org的链接和安装命令,可以让用户快速上手使用模块。 6. **授权**:大多数模块把这个放在最末尾,但是最好还是往前放一些;非常有可能在把这个模块整合完后才发现授权协议不合适。我通常使用 MIT/BSD/X11/ISC。如果你的协议不是很宽容,最好是放到最前面。 ## 认知漏斗 上面的顺序不是随意选择的。 模块使用者需要用到很多模块,需要查看很多模块。 当你查看了上百个模块之后,就可以体会到使用可以预测的模式的好处。 你也开始建立你自己的策略来快速的决定哪些是你需要的,哪些是不需要的。 因此,README应该包涵一下信息: 1. 一个可以预测的格式 2. 某些关键元素 你不必非要用 *这个* 格式,但要保持统一以符合你的用户的认知习惯。 这儿介绍的顺序被简称为“认知漏斗”, 可以想象成是一个直立的漏斗,最宽的部分相关细节最宽泛,越往下移动细节越具体,只有对你的作品足够感兴趣的人才会关注这部分内容。最后,底部可以放一些作品背景的细节 (background,credits,biblio,...) 再一次,Perl圣僧们在这个主题上分享了他们的智慧: > Perl模块的文档对于细节的描述是从少到多的。 > 你的简介部分应该包涵一个小的例子程序 > (或许只有一行代码,省略掉不常用的用例或大多数用户用不到的功能) > 描述部分应该从总体上描述你的模块, > 通常只需要几个段落;在随后的章节中再详细描述模块的例程或方法,长的代码示例,或其它的资料。 > 理想情况下,在点“下一页”之前就能让人大体上了解你的模块。 > 随着用户继续阅读文档,他们能够渐进的获得更多的知识。 > -- from `perlmodstyle` ## 珍惜时间 很棒;这些关键要素的排序应该让人尽快“短路”并放弃你的模块。 这听起来有点凄凉,不是吗?但是要这样想:你的工作,当你用利他主义思想来做的时候,不是为了销售给别人,而是为了让人们尽可能客观公正的评估你的作品,并判断是否满足他们的需要。而不是让你的下载量和用户数最大化。(老外的思想境界真是高) 并不是每个人都有这样的心态;这需要有自我约束和实事求是的态度。你唯一要做的是简洁的描述它的承诺,这样模块探险者们就可以或者使用你的作品或者别求他寻。 ## 奖励: 其它好的实践 在文章的重点之外,有其它的实践你可以遵循(或不遵循)来提高你的README的质量,最大限度地发挥其作用。 1. 考虑包涵一个 **Background** 部分,如果你的模块依赖于重要但是不为人所熟知的抽象或生态系统。[`bisecting-between`](https://github.com/noffle/bisecting-between)的函数从它的名字上看不是特别明显,所以在 *Background* 部分会描述定义,并且给出具体概念和抽象的链接,以便需要的人去使用和获取。如果已经有相似的模块在npm上存在了,这儿也是一个非常适合描述建立模块的动机的地方。 2. 积极建立连接!如果你谈及其它的模块,想法,或者其他人的时候,在相关的引用内容上加上链接,这样访客就可以很容易的得到你的模块背后的想法。极少有模块是凭空诞生的:所有的作品来源于其它作品,因此很有必要让用户追溯你的模块的历史和灵感。 3. 包涵参数和返回值的类型的信息,当这些信息不明确的时候。 尽可能的符合约定(`cb` 代表回调函数,`num` 代表 `Number`)。 4. 在 **Usage** 部分包含的示例代码,要在repo中以文件的形式体现 -- 例如`example.js`。这样当用户clone项目后,就可以直接运行README中提及的代码。 5. 使用徽章要慎重。经常会被 [滥用](https://github.com/angular/angular)。它们会容易引起争论。它们在你的README中加入了视觉噪声,并且只有当用户在联网的浏览器里阅读你的markdown时才能看到徽章,因为图片是存放在互联网上的其它地方。对于每一个徽章,需要考虑:README中的徽章提供给典型读者的真实含义是什么?用一个CI徽章来显示build/test状态?这个信号更应该发邮件给维护者,或者自动创建一个issue -- 永远要考虑你的README中的数据的受众并且自问一下是否有一个流程能够让数据更好的送达到目标受众。 6. API 文档格式没有局限。使用任何你认为是清晰的格式,但是要包含重要的细节: a. 参数是否可选,以及默认值 b. 包含类型信息,如果类型不能清楚的根据约定进行体现 c. 对于 `opts` 对象参数,描述它所接受的所有的 keys 和 values d. 为每个API提供一个小的调用示例,如果它们的用法不明显或是在 **Usage** 部分没有体现。 不过,也有可能是函数太复杂了,需要进行重构,划分成更细粒度的函数,或者整体删除。 e. 为特殊术语建立链接! 在markdown中你可以把 [footnotes](https://daringfireball.net/projects/markdown/syntax#link) 放在文档的末尾,可以很方便的多次引用它们。[这儿](https://github.com/noffle/common-readme/blob/master/api_formatting.md)有一些我的API文档格式的个人偏好。 7. 如果你的模块是无状态函数的一个小的集合,在 **Usage** 部分以 [Node REPL session](https://github.com/noffle/bisecting-between#example) 格式放一些调用和返回值的示例比运行一个示例文件更清晰。 8. 如果你的模块提供了 CLI (command line interface)而不是 API,用命令调用的方式展示调用示例和输出。如果你创建了或更改了一个文件, `cat` 它来展示更改前后的变化。 9. 不要忘记使用 `package.json` [keywords](https://docs.npmjs.com/files/package.json#keywords) 来盛情邀请模块探险者们。 10. API改的越多,越要努力的去更新文档 -- 言外之意是让你的API 精简并及早给出具体定义。需求一直在变化,但是我们要做的是建立一个抽象层: 模块集合本身,而不是在API中做提前的假设。当需求 *变更* 时,并且'只做一件事'不能满足要求的时候,只需写一个新的模块。 '只做一件事'对npm生态系统来说能够使一个模块是有效的和有价值的,并且你的改进过程只是简单的用一个模块来替换另一个模块。 11. 最后,请记住你的版本控制仓库和其中的README存在的时间要比你的 [repository host](https://github.com) 和你链接到的其它任何东西--特别是图片--的时间都要长久。所以 *inline* 任何对将来要获取你的作品的用户来说是重要的东西。 ## 奖励:*common-readme* 不是巧合, 这也是 [**common-readme**](https://github.com/noffle/common-readme)用的文档格式,一个README写作指南和方便的command-line生成器。如果你喜欢这儿的内容, 通过`common-readme`你可以节省编写README的时间。你也可以找到使用这个格式的真实的模块的例子。 ## 战斗的召唤! 前进,勇敢的模块探险家,通过出色的文档,让你的作品能够被发现和使用! ## 作者 我是 [noffle](http://blog.eight45.net/about/)。联系方式: [blog](http://blog.eight45.net),[tweet](https://twitter.com/noffle),和 [hack](https://github.com/noffle). 这个小项目于5月份诞生在柏林的squatconf,在那儿我钻研Perl的圣僧们怎么编写他们的文档,同时叹息在Node生态系统中的我写的README。它促使我创建了 [common-readme](https://github.com/noffle/common-readme)。尽管"README Tips"部分满是tips,我仍然决定集中写一篇关于如何编写README的文章。于是,Art of README诞生了! ## Footnotes 1. <a name="footnote-1"></a>Thanks, [Sixes666](https://www.reddit.com/r/node/comments/55eto9/nodejs_the_art_of_readme/d8akpz6)! 1. <a name="footnote-2"></a>See [The Jargon File](http://catb.org/~esr/jargon/html/R/README-file.html). 然而,现在的多数系统不会将大写字母排在小写字母前面,弱化了这个约定的作用,全部大写只能是在视觉上更显著。 ## Credits A heartfelt thank you to [@mafintosh](https://github.com/mafintosh) and [@feross](https://github.com/feross) for the encouragement I needed to get this idea off the ground and start writing! Thank you to the following awesome readers for noticing errors and sending me PRs :heart: : - [@ungoldman](https://github.com/ungoldman) - [@boidolr](https://github.com/boidolr) - [@imjoehaines](https://github.com/imjoehaines) - [@radarhere](https://github.com/radarhere) - [@joshmanders](https://github.com/joshmanders) - [@ddbeck](https://github.com/ddbeck) - [@RichardLitt](https://github.com/RichardLitt) - [@StevenMaude](https://github.com/StevenMaude) - [@KrishMunot](https://github.com/KrishMunot) - [@chesterhow](https://github.com/chesterhow) Thank you to [@qihaiyan](https://github.com/qihaiyan) for translating Art of README to Chinese! The following users also made contributions: - [@BrettDong](https://github.com/brettdong) for revising punctuation in Chinese version. - [@Alex-fun](https://github.com/Alex-fun) - [@HmyBmny](https://github.com/HmyBmny) - [@vra](https://github.com/vra) Finally, thanks for all of the feedback! Please share your comments [as an issue](https://github.com/noffle/art-of-readme/issues)! ## Pull requests welcome! Spotted an error? Something doesn't make sense? Send me a [pull request](https://github.com/noffle/art-of-readme/pulls)!
PHP
UTF-8
1,969
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\SessionRepository") */ class Session { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $title; /** * @ORM\Column(type="date") */ private $date_from; /** * @ORM\Column(type="date") */ private $date_to; /** * @ORM\ManyToOne(targetEntity="App\Entity\Studies", inversedBy="sessions") */ private $studies; // /** // * @ORM\ManyToOne(targetEntity="App\Entity\Studies", inversedBy="sessions") // */ // private $studies; public function getId(): ?int { return $this->id; } public function getTitle(): ?string { return $this->title; } public function setTitle(?string $title): self { $this->title = $title; return $this; } public function getDateFrom(): ?\DateTimeInterface { return $this->date_from; } public function setDateFrom(\DateTimeInterface $date_from): self { $this->date_from = $date_from; return $this; } public function getDateTo(): ?\DateTimeInterface { return $this->date_to; } public function setDateTo(\DateTimeInterface $date_to): self { $this->date_to = $date_to; return $this; } public function getStudies(): ?Studies { return $this->studies; } public function setStudies(?Studies $studies): self { $this->studies = $studies; return $this; } // public function getStudies(): ?Studies // { // return $this->studies; // } // public function setStudies(?Studies $studies): self // { // $this->studies = $studies; // return $this; // } }
PHP
UTF-8
3,201
2.671875
3
[]
no_license
<?php /* class nmiSessCache { public static $_instance; public $sessInitialized = FALSE; public static $MemchacheExtIsLoaded = FALSE; public function __construct() { if($this->sessInitialized === FALSE) { $this->sessInitialized = $_SESSION[self::$_instance]; } } public static function Cache() { if(empty(self::$_instance)) { self::$_instance = new nmiSessCache(); } return self::$_instance; } public function __cacheSet($key, $val) { $_SESSION[$key] = $val; } public function __cacheGet($key) { return $_SESSION[$key]; } public function cacheDelete($key) { if(!array_key_exists($key, $_SESSION)) { return $_SESSION[$key]; } else { return FALSE; } } } */ /* private function __construct() { $this->MemchacheExtIsLoaded = extension_loaded("apc"); apc_store("Initialized", TRUE); } public function __cacheSet($key, $val) { return apc_store($key, $val); } public function __cacheGet($key) { $is_val = FALSE; return apc_fetch($key, $is_val); //RETURNS FALSE IF KEY IS NOT FOUND } public function __cacheDelete($key) { return $this->__cacheGet($key) === FALSE ? FALSE : apc_delete($key); } public static function Cache() { if(apc_store("Initialized") === FALSE) { self::$_instance = new nmiCache(); } return self::$_instance; } public static function isStarted() { return (apc_store("Initialized") === FALSE) ? FALSE : TRUE; } */ /* abstract class Cache { public static __returnPersistingMedium() { } } */ class nmiCache { public $sessInitialized = FALSE; public static $_instance; public $MemcacheExtIsLoaded = FALSE; private function __construct() { $this->MemchacheExtIsLoaded = extension_loaded("apc"); apc_store("Initialized", TRUE); } public function __cacheSet($key, $val) { return apc_store($key, $val); } public function __cacheClear() { return apc_clear_cache(); } public function __cacheGet($key) { $is_val = FALSE; return apc_fetch($key, $is_val); //RETURNS FALSE IF KEY IS NOT FOUND } public function __cacheDelete($key) { return $this->__cacheGet($key) === FALSE ? FALSE : apc_delete($key); } public static function Cache() { if(apc_store("Initialized") === FALSE) { self::$_instance = new nmiCache(); } return self::$_instance; } public static function isStarted() { return (apc_store("Initialized") === FALSE) ? FALSE : TRUE; } /* public function __construct() { if(empty($_SESSION)) session_start(); if($this->sessInitialized === FALSE) { $this->sessInitialized = $_SESSION["Initilized"] = self::$_instance; } } public static function Cache() { if(empty(self::$_instance)) { self::$_instance = new nmiCache(); } return self::$_instance; } public function __cacheSet($key, $val) { $_SESSION[$key] = $val; } public function __cacheGet($key) { return isset($_SESSION[$key]) ? $_SESSION[$key] : FALSE; } public function cacheDelete($key) { if(!array_key_exists($key, $_SESSION)) { return $_SESSION[$key]; } else { return FALSE; } } public static function isStarted() { return !empty($_SESSION["Initialized"]) ? TRUE : FALSE; } */ } ?>
Python
UTF-8
1,528
4.5
4
[]
no_license
''' In the english dictionary the word stack means arranging objects on over another. It is the same way memory is allocated in this data structure. It stores the data elements in a similar fashion as a bunch of plates are stored one above another in the kitchen. So stack data structure allows operations at one end wich can be called top of the stack. We can add elements or remove elements only form this en dof the stack. In a stack the element insreted last in sequence will come out first as we can remove only from the top of the stack. Such feature is known as Last in First Out(LIFO) feature. The operations of adding and removing the elements is known as PUSH and POP. In the following program we implement it as add and and remove functions. We dclare an empty list and use the append() and pop() methods to add and remove the data elements. ''' class Stack: def __init__(self): self.stack = [] def add(self, dataval): if dataval not in self.stack: self.stack.append(dataval) return True else: return False def remove(self): if (len(self.stack) <= 0): return ("No element in the Stack") else: self.stack.pop() def peek(self): return self.stack[-1] if __name__ == "__main__": s= Stack() s.add("Monday") s.add("Tuesday") s.add("Wednesday") print(s.peek()) temp = s.peek() print(f"\nAfter deleting: {temp}", s.remove()) print(s.peek())
C++
UTF-8
4,327
2.84375
3
[ "MIT" ]
permissive
/*************************************************************************** Laser Transmitter Code This is a program using an AM2320 humidity and temperature sensor using I2C to communicate to an Arduino. The sensor is connected to SCL -> SCL, SCA -> SCA, VCC -> 3-5V, GND -> GND. DON'T FORGET TO PULLUP YOUR SCL AND SDA LINES TO THE 5V RAIL WITH 2K-10K RESISTORS. A laser is also connected to the Arduino to send data to a receiver. Hamming encoder/decoder and Optical modulator/demodulator are based on the LumenWire library written by Andrew Ramanjooloo and modified by Tom Gitlin. https://github.com/HobbyTransform/Encoded-Laser-and-LED-Serial-Communication Arduino sketch by Tom Gitlin with some extra versatility hacked on by Jimmy Acevedo. ***************************************************************************/ #include <Wire.h> // library to communicate with the sensor using I2C #include <Adafruit_Sensor.h> // generic sensor library #include <Adafruit_AM2320.h> // specific sensor library /*#define BME280_ADDRESS (0x76) // Need to set the I2C address to Low = 0x76 (vs High = 0x77) */ Adafruit_AM2320 am2320 = Adafruit_AM2320(); // create an I2C instance to talk to the sensor #include <HammingEncDec.h> // include the Hamming encoder/decoder functionality #include <OpticalModDemod.h> // include the modulator/demodulator functionality OpticalTransmitter laser; // create an instance of the transmitter unsigned long delaytime = 500; // delay between transmitting measurands in milliseconds (nominally 500ms) // need a 'long' value due to it being compared to the Arduino millis value const int CHAR_DELAY = 30; // delay between individual characters of a message (nominally 30ms) float temperature, humidity = 0; boolean english=false; // flag to use english units, otherwise use SI String strTemperature, strHumidity; // String values for the measurands char incomingByte; // variable to hold the byte to be encoded uint16_t msg; // varible to hold the message (character) int LED_SensorError = 5; // Pin for an LED to indicate something is wrong with the sensor int i; void setup() { pinMode(LED_SensorError, OUTPUT); Serial.begin(9600); am2320.begin(); // Check for the sensor. If there is an error, blink the SensorError LED while (!am2320.begin()) { //Serial.println(F("Could not find the temp/humidity/pressure sensor. Check the I2C address and/or wiring")); digitalWrite(LED_SensorError, HIGH); delay (500); digitalWrite(LED_SensorError, LOW); delay (500); } laser.set_speed(2000); // laser modulation speed - should be 500+ bits/second, nominal 2000 (=2KHz) laser.set_txpin(13); // pin the laser is connected to laser.begin(); // initialize the laser } // END of setup(); /* Set up an Interrupt Service Routine to transmit characters. * Arduino Timer2 interrupt toggles the LIGHT_SEND_PIN at the * laser send speed to transmit each half bit. */ ISR(TIMER2_COMPA_vect) { laser.transmit(); // transmit a character if one is ready } void loop() { temperature = am2320.readTemperature(); // read the temperature from the sensor. [degrees C] humidity = am2320.readHumidity(); // read the humidity. Humidity is returned in percent relative humidity // if english units are desired, perform the conversion if (english) { temperature = temperature * 1.8 + 32.0; // convert C to F } strTemperature=String(temperature)+="T"; laserTransmit(strTemperature); delay(delaytime); strHumidity=String(humidity)+="H"; laserTransmit(strHumidity); delay(delaytime); } //END of loop() void laserTransmit(String xmitmsg) { for (i=0; i<(xmitmsg.length()+1); i++) // transmit the string byte by byte { incomingByte=xmitmsg.charAt(i); // get the character at position i //Serial.print(incomingByte); msg = hamming_byte_encoder(incomingByte); // encode the character laser.manchester_modulate(msg); // modulate the character using the laser delay(CHAR_DELAY); // wait delay between transmitting individual characters of the message } } // END of laserTransmit()
Rust
UTF-8
5,244
3.359375
3
[]
no_license
use super::tokenizer::{Token, Tokenizer}; use super::types::{MalList, MalType, MalMap}; use std::iter::Peekable; use std::collections::HashMap; fn read_list(tokenizer: &mut Peekable<Tokenizer<'_>>) -> MalList { let token = tokenizer.next(); if !matches!(token, Some(Token::LParen)) { panic!( "Error read_list: Called without beginning left parenthesis, found {:?} instead", token ) } let mut elements = Vec::<MalType>::new(); loop { let maybe_form = read_form(tokenizer); if let Some(form) = maybe_form { elements.push(form); } else if let Some(Token::RParen) = tokenizer.peek() { tokenizer.next(); return MalList::new(elements); } else if matches!(tokenizer.peek(), None) { // read_form returning 'None' is an overloaded value. It means both no more forms // and we hit some token that it cannot handle (e.g. closing paren) but doesn't // want to panic!() on. For example consider the list ( {"a" 1} 2 3 4) // We only want to panic in the case where we're out of forms and out of tokens. panic!( "Error read_list: missing end parenthesis for list {:?}", elements ); } if let Some(Token::RParen) = tokenizer.peek() { tokenizer.next(); return MalList::new(elements); } } } fn read_map(tokenizer: &mut Peekable<Tokenizer<'_>>) -> MalMap { let next = tokenizer.next(); if !matches!(next, Some(Token::LCurly)) { panic!( "Error read_map: Called without beginning left curly brace, found {:?} instead.", next ); } let mut map = HashMap::<String, MalType>::new(); loop { let maybe_key = read_form(tokenizer); let mut key = None; if let Some(MalType::Symbol(value)) = maybe_key { key = Some(value); } else if let Some(MalType::Str(value)) = maybe_key { key = Some(value); } else if let None = maybe_key { // Possibly empty map. } else if matches!(tokenizer.peek(), None){ panic!("Error read_map: Missing or invalid key value. {:?}", maybe_key); } let maybe_value = read_form(tokenizer); if key.is_some() && maybe_value.is_some() { map.insert(key.unwrap(), maybe_value.unwrap()); } else if key.is_none() && maybe_value.is_none() { let next = tokenizer.next(); if !matches!(next, Some(Token::RCurly)) { panic!("Error read_map: missing ending right curly brace, found {:?} instead.", next); } return MalMap::new(HashMap::new()); } else { panic!("Error read_map: no valid key, value pair found."); } if let Some(Token::RCurly) = tokenizer.peek() { // End of the line return MalMap::new(map); } } } pub fn read_str(input: &str) -> Option<MalType> { let tokenizer = Tokenizer::new(&input); read_form(&mut tokenizer.peekable()) } pub fn read_form(tokenizer: &mut Peekable<Tokenizer<'_>>) -> Option<MalType> { let maybe_next = tokenizer.peek(); match maybe_next { Some(Token::LParen) => Some(MalType::List(read_list(tokenizer))), Some(Token::RParen) => consume_and_forget(tokenizer), Some(Token::LCurly) => Some(MalType::Map(read_map(tokenizer))), Some(Token::RCurly) => consume_and_forget(tokenizer), Some(Token::NonSpecial(_)) => read_non_special(tokenizer), Some(Token::Str(_)) => read_string(tokenizer), Some(tkn) => panic!("Error read_form: unsupported token {:?}", tkn), None => None, } } fn consume_and_forget(tokenizer: &mut Peekable<Tokenizer<'_>>) -> Option<MalType> { tokenizer.next(); None } fn read_non_special(tokenizer: &mut Peekable<Tokenizer<'_>>) -> Option<MalType> { if let Some(Token::NonSpecial(value)) = tokenizer.next() { if let Ok(number) = value.parse::<isize>() { return Some(MalType::Int(number)); } else if value == "nil" { return Some(MalType::Nil); } else if value == "true" { return Some(MalType::True); } else if value == "false" { return Some(MalType::False); } else { return Some(MalType::Symbol(value.to_string())); } } None } fn read_string(tokenizer: &mut Peekable<Tokenizer<'_>>) -> Option<MalType> { if let Some(Token::Str(value)) = tokenizer.next() { return Some(MalType::Str(value)); } None } #[cfg(test)] mod tests { use super::*; #[test] #[should_panic(expected = "Error read_list: missing end parenthesis for list")] fn read_list_no_end_paren() { let input = String::from("(1, 2, 3, 4"); read_str(&input); } #[test] #[should_panic(expected = "Error read_list: Called without beginning left parenthesis, found")] fn read_list_no_begin_paren() { let input = String::from("1, 2, 3, 4)"); let tokenizer = Tokenizer::new(&input); read_list(&mut tokenizer.peekable()); } }
Java
UTF-8
608
2.40625
2
[]
no_license
package com.alexyu.connection; import java.sql.Connection; /** * 管理线程池 * * @author Alex Yu * @date 2019/8/3 23:32 */ public class ConnectionPoolManager { private static DbBean dbBean = new DbBean(); private static ConnectionPool connectionPool = new ConnectionPool(dbBean); // 获取链接(重复利用机制) public static Connection getConnection() { return connectionPool.getConnection(); } // 释放链接(可回收机制) public static void releaseConnection(Connection connection) { connectionPool.releaseConnection(connection); } }
C
UTF-8
238
3.078125
3
[]
no_license
#include "main.h" /** * main - argc & argv * @argc: int * @argv: pointer * Return: 0 */ int main(int argc, char *argv[]) { int i; int count; for (i = 0; i < argc && argv[i]; i++) { count = i; } printf("%d\n", count); return (0); }
Markdown
UTF-8
5,455
3.046875
3
[ "LicenseRef-scancode-unknown-license-reference", "CC-BY-4.0" ]
permissive
--- layout: post title: "读书笔记-以终为始:诱发行为改变的产品设计" categories: 读书笔记 tags: 读书笔记 author: xueyp description: --- ## 行为改变的基本要素 干预设计过程是为了找到现实中已有的事物的替代品,分析这种替代品的可能性,并将可能性转化为现实,确定其是否可以创造价值。 1. 可能性分析 2. 验证并找出促进因素和阻碍因素 3. 干预设计和选择 4. 预试验并使之运行 5. 对之前的定量数据和定性数据进行验证 ### 可能性分析和验证 可能性分析的四个方法: - 定量分析 - 定性分析 - 基于个人感觉分析 - 基于外部资料分析 验证的目的是通过先进的科学过程来确保我们达成目标,让我们**避免基于错误假设得出错误的结论**。 ### 行为陈述 干预设计过程的核心是行为陈述: > 当某些人(人群)想要做某事(动机)时,他们如果具备什么条件(限制条件),就会做什么(行为)[ 由(数据)衡量 ] - 人群=你正试图改变其行为的一群人 - 动机=这群人实施某行为的核心动机 - 限制条件=行为产生的前提条件,这一条件不受你控制 - 行为=当这群人有以上动机,且满足以上条件时,你想让他们做的可衡量的活动 - 数据=你在这群人的行为发生时所做的统计 行为陈述中的常见错误: - 选择错误的行为 - 缺乏行为陈述:只关注愿景陈述而不是行为陈述 - 不够大胆的行为陈述 - 坚定最初的行为陈述,即拒绝改进行为陈述 ### 压力分析和压力验证 促进压力和抑制压力均可被用来改变行为,如果促进压力超过抑制压力,我们就会做出行为;如果抑制压力更强,我们就不会去做。只有成功地把验证过的压力和与其对应的干预设计结合起来时,我们才能真正地实现我们的目标。我们需要把干预设计变成真正的实施过程,才能使那些压力起作用。检验你所识别的压力正确与否的唯一方法是看**在此基础上建立的干预能否真正地改变行为**。 - 促进压力往往不适用于所有人 - 抑制压力更具辨识度,更容易在众多干预手段中脱颖而出 - 抑制压力更具普遍性,能产生持续而有效的影响 - 抑制压力相对稳定,并不会随时间的流逝而快速改变 - 抑制压力具有可预测性,通常有相应的衡量标准 ### 干预设计和干预选择 干预设计的关键是确定研究规模,需要针对抑制压力设计尽可能多、尽可能详尽的干预措施。 干预选择就是要找出成本最低、效果最好、覆盖范围最广的改变行为的干预措施。 尽管你不可能对所有的干预措施都进行预试验,你也不应该只预试验一种方法。选择干预措施不是为了寻求一种解决方案,而是为一系列预试验方案做好准备,从而最大限度地增加改变行为的可能性。因为,像其他所有严谨的科学一样,好的行为科学也需要假定你的干预方案可能无效。 - 组合干预措施 - 适当减少干预措施的种类 - 关注干预措施奏效的范围 ### 透明度和责任感 在对已经选好的干预措施进行预试验之前,我们需要停下来,进行两方面的道德因素检查:我们要改变什么行为?我们该如何改变这个行为?这两个伦理问题体现在两个基本的行为差距上: - 意图-行动差距:行为结果与最初的行为动机清楚地显示它们具有一致性,这就可以确保消除道德上的顾虑 - 意图-目标差距:**如果改变行为不尊重他人的动机,即使动机是显而易见的,这个行为改变也是不道德的** ### 从预试验到持续监测 干预设计过程的三个过程:“预试验”、“测试”、“大规模试验”。预试验是我们第一次真正地衡量目标行为,逐级加大实验规模。它们有严格的先后顺序,前一阶段未达预期时,不进入下一步。 ## 高级行为改变 - 角色启动、角色调整和角色介入 - 身份是最强的压力影响因素,也是最需要小心处理的因素 - 身份可以灵活转换,所以可以根据需要创造压力影响因素来转换身份 - 优化认知 - 明确你的目标人群想或者不想在何处消耗他们的认知注意力,考虑他们的认知习惯和你的干预认知环境 - 大脑很忙,所以它通常会接受默认选择,即使是对我们通常认为很重要的决定来说也是如此 - 认知负荷越大,人们就越有可能做出默认的选择 - 减轻认知负担是对现有干预的有力补充,因为经过深思熟虑的选择会带来被期望的行为 - 独特性和归属感这两种压力能被应用于每一次干预 - 要想与众不同,那就进行私人定制;要想增强归属感,那就共享私人定制 - 文化差异 - 社会经济地位 - 消除行为和替代行为 - 设计消除行为要增强抑制压力,减弱促进压力 - 当我们专注于消除一种行为时,我们也需要寻找一个替代行为 群体的四个身份:2X2矩阵: | | | | ----- | ----- | | 稳定的 | 爱好者 | | 不稳定的 | 厌恶者 | 参考 ============ 版权声明:本文为博主原创文章,转载请注明出处。 [旭日酒馆](https://xueyp.github.io/)
Python
UTF-8
1,389
2.640625
3
[]
no_license
from functools import * from itertools import * from collections import defaultdict import sys sys.setrecursionlimit(100000) def mint(ns): return list(map(int,ns)) ds = [(0,1),(1,0),(0,-1),(-1,0)] f = open("input") l=[x for x in f] d=defaultdict(int) #r=list(map(int,l[0].split())) ps=[] p={} n=0 v=0 for x in l: if x=="\n": ps.append(p) p={} for f in x.split(): a,b=f.split(":") p[a]=b.strip() ps.append(p) s = """byr (Birth Year) iyr (Issue Year) eyr (Expiration Year) hgt (Height) hcl (Hair Color) ecl (Eye Color) pid (Passport ID)""" #def test(p): def th(h): if h[-2:]=="cm": return 150<=int(h[:-2])<=193 if h[-2:]=="in": return 59<=int(h[:-2])<=76 return False for p in ps: for l in s.split("\n"): k=l.split()[0] if k not in p: #print(k) break else: if (1920<=int(p["byr"])<=2002 and 2010<=int(p["iyr"])<=2020 and 2020<=int(p["eyr"])<=2030 and th(p["hgt"])): c=p["hcl"] if c[0]=="#" and all([x in "1234567890abcdef" for x in c[1:]]): print(p) if (len(c)==7 and p["ecl"] in "amb blu brn gry grn hzl oth".split() and all([x in "1234567890" for x in p["pid"]]) and len(p["pid"])==9): v+=1 print(v)
Markdown
UTF-8
17,788
3.4375
3
[ "MIT" ]
permissive
--- layout: post title: Final Thoughts --- I'll be honest. From the first few lectures I didn't really expect much out of this course, but as the semester has progressed, Dr. Downing has surprised me. Even though the lectures did not focus as much on object oriented programming as much as I thought the title of the course implied, I found that drilling in details about C++ was incredibly valuable. After this course, I think I can confidently say that I know about as much about C++ as I do about Java. I wouldn't say I'm an expert in either language (JavaScript would be the one I'm closest to being an expert in [I don't care if you hate me for it, it just means more job security for me]), but I'll say I can reason my way through most of the things I'd encounter in a codebase in either language now, plus a few other things I hope to never see in a real codebase, such as: ```java int foo() { try { return 1; } catch (Exception e) { // nothing } finally { return 2; } } ``` *Fun exercise: without compiling or running the above code, what does `foo()` return?* * `1` * `2` * please stop ```java static { System.exit(0); } ``` *Bonus: if you want to mess with somebody doing a programming assignment for CS312, add this to a random file and watch them struggle to figure out why none of their code runs. (Don't actually do this though, it's kinda mean.)* From what I understand, there are three main topics in CS371p: C++, tooling, and object-oriented programming. The lectures and exams focused on C++, while the projects covered C++ and tooling. Most of the stuff related to object-oriented programming in the course was contained in the readings that we were supposed to do outside of class, but personally, I didn't have the motivation to do them because to pass the quizzes I only really needed to do a surface-level skim through each reading. For my personal learning style, it would have helped to cover the concepts in class, perhaps by going through some examples of how to create good object-oriented designs during lectures. ## Lectures Lectures focused primarily on teaching C++, especially drilling in details that people may find easy to confuse. The lectures were the most well-thought out and well-executed aspect of the class, and I enjoyed learning about all of the small details. I especially appreciate the pedantry; programming languages are inherently precise and pedantic, so to understand them well, one's understanding of the language must also be precise and pedantic. From reading what others have had to say on their blogs, Dr. Downing's way of encouraging people to participate in the class helped a lot of people pay attention in class and better learn the material. Dr. Downing did an excellent job of making lectures engaging. As I mentioned above, I would have liked to see more discussion of object oriented programming, particularly the SOLID principles, during lectures. I think that having lectures that go through examples like the readings over the SOLID principles would help drill in an understanding of what they mean and why they are significant. And overall, this would help students think more carefully about their designs, especially since many of us are preparing to work in companies whose codebases are most definitely big enough for good design to matter. ## Quizzes The quiz questions over readings were generally questions that you could answer correctly with a 5 minute skim of the actual article. Quiz questions over lecture material tended to be application of small details covered in the previous lecture or two. I found the topics that the quizzes covered to generally be fair, even though the average scores on the quizzes were often disappointingly low. Occasionally, there were a few quiz questions that had poorly written or incomplete instructions. For example, the following (not a real quiz question, but similar to one that we actually encountered) would not be complete: ```cpp int main() { A x; A y = x; x = y; } a. A() A(A) A(A) b. A() A(A) =(A) c. A() A() A(A) A(A) d. A() A() =(A) =(A) ``` The issue here is that it is hard to figure out, without having seen similar questions before, what the answer choices represent or even what the question is asking. A more complete way of stating this problem would be this: ```cpp What is the output of the following program? #include <iostream> using namespace std; class A { A() { cout << "A() "; } A(const A&) { cout << "A(A) "; } A& operator=(const A&) { cout << "=(A) "; } }; int main() { A x; A y = x; x = y; } a. A() A(A) A(A) b. A() A(A) =(A) c. A() A() A(A) A(A) d. A() A() =(A) =(A) ``` After this issue was pointed out, later quiz questions of this format were more explicit in stating what they were asking. However, I would still like to see an explicitly stated "What is the output of the following program?" in every quiz question like this; in my mind, the question is still not complete and well-defined without it. ## Tests Contrary to what Dr. Downing claimed about cheat sheets not being useful, I found that having a good cheat sheet made the exams more or less trivial. For the most part, this means writing down the prototypes for all of the mentioned standard library functions, the provided operators for each type of iterator, the prototypes for all of the operator overloads, and the prototypes for `std::vector` and `std::deque`. If you have those things on your cheat sheet, you've paid attention in lecture, and you've made an earnest effort in the projects, both exams are more or less a typing speed test. As such, the best way to study for an OOP exam is [typing.io](https://typing.io). I think the tests would benefit from having other types of questions in addition to code writing. I like the idea of having the test be primarily code writing, but I think having a few other types of questions mixed in would be nice. For example, one can imagine conceptual multiple choice questions such as: > When is a local static variable initialized? > > * on scope entry > * on program entry > * at compile time > * the first time the function is called > > Which of the following exhibit replacement overriding in C++? Check all that apply. > > * constructors > * destructors > * virtual methods > * non-virtual methods > * finalizers Additionally, the tests could have short free response sections with questions such as: > List three ways that a programmer could introduce bugs by allocating memory on the heap as opposed to on the stack. > > Explain why a programmer may want to allocate memory on the heap instead of on the stack. > > Explain the steps needed to determine the value of `baz` at runtime in the following line of C++ code: > > ```cpp int baz = *p.foo()->bar; ``` > > Assume that `p` is an instance of a class with a method `foo()` that returns a pointer to a struct with a `bar` field of type `int *`. > > What is the difference between the pre-increment and post-increment operators in C++ and when would you use one but not the other? By having more varied types of questions, the tests would be a more enjoyable experience for people who have different study styles that may not be attuned to designing and writing code under time constraints and without access to external resources. It would also make the tests more comprehensive instead of testing understanding of only the C++ aspect of the class material. ## Speakers I enjoyed the speakers, particularly JPL but mostly because they demoed HoloLens. There are plenty of opportunities to find cool companies through the events they host within UTCS such as Food for Thought, Rise and Dine, and various info sessions and tech talks, but the personal connection that the speakers that come in OOP have with Dr. Downing makes it that much more cool. ## Projects The projects were a mixed bag. They are good experience for becoming familiar with idiomatic C++ and learning how to use the various tools introduced in the class, including GNU Make, Travis CI, Doxygen, Google Test, Valgrind, and Gcov. However, I think there is a lot of room for improvement in motivating the use of the tools. Aside from Travis CI and Google Test, which I found useful to convince myself of the correctness of my code, the other tools were more of a burden and chuck-to-the-side-we'll-do-it-half-an-hour-before-the-project's-due sort of deal. ### Doxygen Code documentation with Doxygen can be useful but not in codebases of this size. Though there were provided examples of what the documentation should look like in Collatz, I think that setting aside part of a lecture to give examples of what makes good documentation and how to write it well would be useful. In particular, it would be helpful to explain: * Why is documentation important when you can just read the source code? * What kinds of information should you put in your documentation? * What kinds of information should you not put in your documentation? * How can you avoid unnecessary redundancy in your function/method documentation? To illustrate the importance of the last question, consider the following three docstrings for the same function: ```cpp /** Checks if a number is zero. */ bool is_zero(int num) { return num == 0; } /** * Checks if <code>num</code> is zero. * @param num a number * @return <code>true</code> if <code>num</code> is <code>0</code>. */ bool is_zero(int num) { return num == 0; } /** * Returns <code>true</code> if <code>num</code> is <code>0</code>, or * <code>false</code> otherwise. * @param num the number to check * @return <code>true</code> if <code>num</code> is <code>0</code>, or * <code>false</code> otherwise */ bool is_zero(int num) { return num == 0; } ``` Which one seems the most useful? The third is clearly the most complete, but it is also redundant and can be expressed more succinctly. The first one is most succinct and would suffice for such a simple function, but you might want something a bit more detailed if you are writing a library that many people will want to use or if you are describing a more complex function or method. Explaining the importance of finding the balance between being concise and being comprehensive (or even conforming to verbose documentation requirements) would be of practical help to future engineers. Good documentation makes people's lives easier and will cause people to see you as a better person. ### Google Test The first project did not motivate the importance of unit testing well. Having a requirement of three unit tests per function/method forces you to write contrived or redundant (i.e. testing the same code path) unit tests since you could achieve the same coverage with half the number of unit tests, particularly in Collatz because most of the functions barely had any branching that needed multiple unit tests to cover. Adding sufficient optimizations may have increased the complexity of some parts of the code to warrant more unit tests, but due to the mathematical properties of the Collatz conjecture, there's not really much you can do in terms of intensive optimization. (You can add a cache, sure, but adding things to a cache and reading them from a cache don't add very many new code paths to have to verify. I was thinking of stuff more like using SIMD and pthreads, but the overhead of starting multiple threads actually made things run slower for our data size and it's not clear how you can optimize Collatz to use SIMD instructions.) For the Netflix project, precomputing almost everything beforehand meant that there was very little to actually write unit tests for since the client code that we submitted was very thin and more or less just read in a cache and performed a few simple arithmetic operations on some numbers for each input. Unit tests were not very helpful for that project either. Even the Allocator project was simple enough that you didn't need that many unit tests to comprehensively cover most or all of the possible code paths, since the allocator spec was just about the simplest free list-based solution you could come up with. No thread safety, no performance bounds or guarantees, and no optimizations for real-world usage. My partner and I ended up manually inlining all of our helper functions because we didn't want to write dozens upon dozens of unit tests that all tested the same code paths and didn't add anything meaningful to the solution. Extensive unit testing was more helpful for the final two projects since there were lots of tricky edge cases and lots of branching overall. I found that writing unit tests convinced me that my code was working properly and I actually uncovered several bugs in our implementation by writing comprehensive tests for every method. I think Darwin and Life are excellent and challenging projects that not only force students to think about object oriented design but also motivate the need for and usefulness of unit testing. Overall, I think that it would be good to relax the 3 unit tests per function/method requirement for the first three projects to perhaps 2 unit tests per function/method or even some fixed total number of unit tests for the entire project, since the code overall isn't terribly complex for those projects. As is the case in the real world, the same thing (3 unit tests per function/method) may work great for one project but may not be useful at all for another, so showing that requirements are not mindlessly legalistic but rather adapt to the nature of each individual project would be valuable for future semesters. ### GNU Make Aside from the handful of students who actually went and looked at the contents of the makefiles for the projects, I don't think most people understood what the makefiles were for or why they were having problems with them at various points throughout the semester. There were some issues with the provided makefiles for the proojects, although those mostly got fixed and later projects ran more smoothly afterwards. I think providing comments in the makefile would encourage students to try to fix Make problems on their own instead of just panicking on Piazza, but that's only part of the solution. Encouraging students to not only read but also understand error messages from Make would be very helpful towards the independent inquiry objective of tthe class. This could even take the form of spending 10 minutes during a lecture going through what a Make error looks like and what information Make gives you when something goes wrong, e.g. filename, line number, exit status, command that returned an error. By showing students that Make is not just a box of black magic that spews out nonsense that only the TAs can understand, they can debug more effectively and more independently, which will be good for them in the long run. ### Valgrind We weren't even allowed to use the heap directly in most of the projects, so what's the point of checking for memory leaks? Running everything in Valgrind just added some additional runtime overhead and confused people when they weren't sure if "still reachable" was an acceptable output: ``` ==50== LEAK SUMMARY: ==50== definitely lost: 0 bytes in 0 blocks ==50== indirectly lost: 0 bytes in 0 blocks ==50== possibly lost: 0 bytes in 0 blocks ==50== still reachable: 72,704 bytes in 1 blocks ==50== suppressed: 0 bytes in 0 blocks ==50== Rerun with --leak-check=full to see details of leaked memory ``` ### Travis CI Travis was helpful and overall I appreciated that we learned how to set it up and use it for regression testing. Though there were some outages, those could not really have been predicted so I can't really fault anybody for that. However, I would like to see a faster official response to third-party service incidents from the instructors in the future. Leaving students in the dark about services that are tied to project requirements is not very fun to be on the other side of. ## Concluding Remarks: How to Pass OOP Since this blog post is ostensibly aimed towards a future student, here's a simple list of things you can do to pass OOP in a cinch: * Go to every lecture and pay attention. * Write the things I mentioned above in the "Tests" section on your cheat sheet. * Work with a partner on every project you have the option to. * Do all the extra credit you can. They're free points and not a lot of effort. ## Concluding Remarks: Rust Throughout the course, during the lectures I was very interested in comparing C++ idioms to those in Rust. A big theme that Dr. Downing emphasizes throughout the course is that object oriented languages tend to push errors that are runtime errors in other languages into compile time errors. This is true, and C++ does a fairly good job at it compared to some of the other languages I've worked with (cough JavaScript), but if you're really serious about pushing errors to compile time, you should really be looking at one of the hottest new kids on the block, Rust. Rust enforces memory safety at compile time and without a garbage collector. If you don't use any `unsafe` blocks, you can know that any code you write will not contain memory leaks because the compiler knows when to allocate and free everything and will make sure that everything gets freed exactly once when it falls out of scope. Rust also does a lot of other cool things, but I'll leave what exactly those things are as an exercise for the reader. ## Concluding Remarks: Tip of the Week Dr. Downing, Thanks for a great semester and an interesting, unique course. All the best with future classes and I'll see you in SWE before I graduate. ![tips fedora](http://i1.kym-cdn.com/photos/images/newsfeed/000/682/880/0d0.gif)
Java
UTF-8
1,683
2.5
2
[ "MIT" ]
permissive
package aes.gui.widgets; import net.minecraft.client.Minecraft; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import aes.gui.widgets.base.Slider; /** * * Vanilla GuiSlider in Widget form. * */ public class SliderVanilla extends Slider { private static final ResourceLocation TEXTURE = new ResourceLocation("textures/gui/widgets.png"); public SliderVanilla(int width, int height, float value, SliderFormat format, ValueChangedHandler valueChangedHandler) { super(width, height, value, format, valueChangedHandler); } @Override public void draw(int mx, int my) { if (this.dragging) { this.value = (mx - (this.x + 4)) / (this.width - 8); this.value = MathHelper.clamp_float(this.value, 0, 1); } Minecraft.getMinecraft().renderEngine.bindTexture(TEXTURE); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); drawTexturedModalRect(this.x, this.y, 0, 46, this.width / 2, this.height); drawTexturedModalRect(this.x + this.width / 2, this.y, 200 - (int) (this.width / 2), 46, (int) (this.width / 2), this.height); drawTexturedModalRect(this.x + (int) (this.value * (this.width - 8)), this.y, 0, 66, 4, 20); drawTexturedModalRect(this.x + (int) (this.value * (this.width - 8)) + 4, this.y, 196, 66, 4, 20); drawCenteredString(fontRenderer, this.format.format(this), (int) (this.x + this.width / 2), (int) (this.y + (this.height - 8) / 2), this.dragging || inBounds(mx, my) ? 16777120 : 14737632); } @Override public void handleClick(int mx, int my, int button) { super.handleClick(mx, my, button); Minecraft.getMinecraft().sndManager.playSoundFX("random.click", 1.0F, 1.0F); } }
Python
UTF-8
4,343
2.890625
3
[ "MIT" ]
permissive
from psi.core.enaml.api import load_manifest class ParadigmManager: ''' Core class for managing experiment paradigms available to psiexperiment ''' def __init__(self): self.paradigms = {} self.broken_paradigms = {} def register(self, paradigm, exception=None): self.paradigms[paradigm.name] = paradigm if exception is not None: raise def list_paradigms(self, experiment_type=None): ''' Iterate through available experiment paradigms Parameters ---------- experiment_type : {None, str} If None, yield all paradigms. If experiment_type is specified, yield only paradigms matching that experiment type. Returns ------- iterator Iterator over set of matching paradigm descriptions ''' matches = [] for paradigm in self.paradigms.values(): if experiment_type is None: matches.append(paradigm) elif paradigm.experiment_type == experiment_type: matches.append(paradigm) return matches def list_paradigm_names(self, experiment_type=None): matches = self.list_paradigms() return sorted(m.name for m in matches) def get_paradigm(self, name): ''' Return definition for experiment paradigm Parameters ---------- name : str Name of experiment paradigm to return Returns ------- description Instance of ParadigmDescription for the experiment paradigm ''' return self.paradigms[name] class PluginDescription: def __init__(self, manifest, selected=False, required=None, name=None, title=None, attrs=None): if attrs is None: attrs = {} self.manifest = load_manifest(manifest)(**attrs) self.selected = selected # Default values are loaded directly from the PluginManifest if the # provided value is None. self.setdefault('required', required) self.setdefault('name', name) self.setdefault('title', title) def setdefault(self, attr, value): if value is not None: setattr(self, attr, value) else: setattr(self, attr, getattr(self.manifest, attr)) class ParadigmDescription: def __init__(self, name, title, experiment_type, plugin_info): ''' Parameters ---------- name : str Simple name that will be used to identify experiment. Must be globally unique. Will often be used at the command line to start the experment (e.g., `psi name`). title : str Title to show in main window of the experiment as well as in any user experience where the user is asked to select from a list of experiments. experiment_type : {'ear', 'animal', 'cohort', 'calibration', str} Type of experiment. This is mainly used to organize the list of available experments in different user interfaces. plugin_info : list List of tuples containing information about the plugins that are available for this particular paradigm. ''' self.name = name self.title = title self.experiment_type = experiment_type global paradigm_manager try: self.plugins = [PluginDescription(**d) for d in plugin_info] paradigm_manager.register(self) except Exception as exc: print(plugin_info) paradigm_manager.register(self, exc) def enable_plugin(self, plugin_name): for p in self.plugins: if p.name == plugin_name: p.selected = True break else: choices = ', '.join(p.name for p in self.plugins) raise ValueError(f'Plugin {plugin_name} not found. ' \ f'Valid plugins are {choices}.') def disable_plugin(self, plugin_name): for p in self.plugins: if p.name == plugin_name: p.selected = False def disable_all_plugins(self): for p in self.plugins: p.selected = False paradigm_manager = ParadigmManager()
PHP
UTF-8
624
2.609375
3
[]
no_license
<?php namespace App\Domain\Payment\Core; use App\Domain\Order\Core\OrderInterface; use App\Domain\Payment\Component\PaymentInterface as ComponentPaymentInterface; interface PaymentInterface extends ComponentPaymentInterface { public function getOrder(): OrderInterface; public function setOrder(OrderInterface $order): void; public function getPaymentMethod(): ?PaymentMethodInterface; public function setPaymentMethod(PaymentMethodInterface $paymentMethod): void; public function getCreditCard(): ?CreditCardInterface; public function setCreditCard(?CreditCardInterface $creditCard): void; }
Ruby
UTF-8
816
3.125
3
[]
no_license
require 'spec_helper' require_relative '../robot' RSpec.describe Robot do before do @utils = Class.new do include Utils end.new end it 'checks if string contains an integer positive coordinate' do expect(@utils.integer? '-1').to eq false expect(@utils.integer? '1').to eq true expect(@utils.integer? '2').to eq true expect(@utils.integer? ' ').to eq false expect(@utils.integer? nil).to eq false expect(@utils.integer? 'a').to eq false end it 'abreviates a symbol to two characters' do expect(@utils.abbreviate :north).to eq 'N' expect(@utils.abbreviate :north_west).to eq 'NW' end it 'converts a string to symbol' do expect(@utils.string_to_symbol 'north west').to eq :north_west expect(@utils.string_to_symbol 'north').to eq :north end end
Java
GB18030
2,202
2.734375
3
[]
no_license
/** * */ package com.fr.design.report.share; import java.util.HashMap; import com.fr.data.impl.EmbeddedTableData; import com.fr.general.GeneralUtils; import com.fr.stable.ArrayUtils; import com.fr.stable.StringUtils; /** * tabledata * * @author neil * * @date: 2015-3-10-10:45:41 */ public class ConfuseTabledataAction { /** * ָݼ * * @param info صϢ * @param tabledata Ҫݼ * */ public void confuse(ConfusionInfo info, EmbeddedTableData tabledata){ int rowCount = tabledata.getRowCount(); String[] keys = info.getConfusionKeys(); for (int j = 0, len = ArrayUtils.getLength(keys); j < len; j++) { if(StringUtils.isEmpty(keys[j])){ continue; } //Ѿ, ͬԭʼ, Ľһµ. HashMap<Object, Object> cachedValue = new HashMap<Object, Object>(); for (int k = 0; k < rowCount; k++) { Object oriValue = tabledata.getValueAt(k, j); Object newValue; if(cachedValue.containsKey(oriValue)){ newValue = cachedValue.get(oriValue); }else{ newValue = confusionValue(info, j, keys[j], cachedValue, oriValue); cachedValue.put(oriValue, newValue); } tabledata.setValueAt(newValue, k, j); } } } //ÿһӵ private Object confusionValue(ConfusionInfo info, int colIndex, String key, HashMap<Object, Object> cachedValue, Object oriValue){ if (info.isNumberColumn(colIndex)){ //ָʽ, ô˷, eg: 3 * 3, 8 *3..... Number keyValue = GeneralUtils.objectToNumber(key, false); Number oriNumber = GeneralUtils.objectToNumber(oriValue, false); return oriNumber.doubleValue() * keyValue.doubleValue(); } String oriStrValue = GeneralUtils.objectToString(oriValue); if(StringUtils.isEmpty(oriStrValue)){ //ǿֶ, Ĭϲ. ΪеĿͻ˿ֶһЩ, ֮. return oriStrValue; } //Ĭʽľӷ, eg: 1, 2...... return key + cachedValue.size(); } }
Python
UTF-8
56
3.359375
3
[]
no_license
x = 10 y = 5 s = 'greater' if x>y else 'less' print(s)
Java
UTF-8
6,951
2.328125
2
[]
no_license
package model; import controller.AppointmentForm; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.util.StringJoiner; import static controller.inputControls.SYSTEM_ZONE_OFFSET; import static model.Inventory.appointmentList; import static model.MeridiemIndicator.AM; import static model.MeridiemIndicator.PM; public class Appointment extends TableItem { private Integer Appointment_ID; private String Title; private String Description; private String Location; private String Type; private DateTime Start; private DateTime End; private Integer Customer_ID; private Integer User_ID; private Integer Contact_ID; public Appointment(){ super(); } public Appointment(Integer appointment_ID, String title, String description, String location, String type, DateTime start, DateTime end, Integer customer_ID, Integer user_ID, Integer contact_ID) { super(); Appointment_ID = appointment_ID; Title = title; Description = description; Location = location; Type = type; Start = start; End = end; Customer_ID = customer_ID; User_ID = user_ID; Contact_ID = contact_ID; } public Appointment(Integer appointment_ID, String title, String description, String location, String type, DateTime start, DateTime end, DateTime create_Date, String created_By, DateTime last_Update, String last_Updated_By, Integer customer_ID, Integer user_ID, Integer contact_ID) { this(appointment_ID,title,description,location,type,start,end,customer_ID,user_ID,contact_ID); Create_Date = create_Date; Created_By = created_By; Last_Update = last_Update; Last_Updated_By = last_Updated_By; } public Appointment(AppointmentForm appointmentForm) { super(); Appointment_ID = appointmentForm.getAppointment_ID(); Title = appointmentForm.getTitleTextField().getText().trim(); Description = appointmentForm.getDescriptionTextField().getText().trim(); Location = appointmentForm.getLocationTextField().getText().trim(); Type = appointmentForm.getTypeTextField().getText().trim(); Customer_ID = appointmentForm.getCustomerComboBox().getSelectionModel().getSelectedItem().getCustomer_ID(); User_ID = appointmentForm.getUserComboBox().getSelectionModel().getSelectedItem().getUser_ID(); Contact_ID = appointmentForm.getContactComboBox().getSelectionModel().getSelectedItem().getContact_ID(); LocalDate startLocalDate = appointmentForm.getStartDatePicker().getValue(); Integer startTimeHour = appointmentForm.getStartTimeHourComboBox().getValue(); Integer startTimeMinute = appointmentForm.getStartTimeMinuteComboBox().getValue(); LocalTime startLocalTime = LocalTime.of(startTimeHour, startTimeMinute); Start = new DateTime(OffsetDateTime.of(startLocalDate, startLocalTime, SYSTEM_ZONE_OFFSET)); LocalDate endLocalDate = appointmentForm.getEndDatePicker().getValue(); Integer endTimeHour = appointmentForm.getEndTimeHourComboBox().getValue(); Integer endTimeMinute = appointmentForm.getEndTimeMinuteComboBox().getValue(); LocalTime endLocalTime = LocalTime.of(endTimeHour, endTimeMinute); End = new DateTime(OffsetDateTime.of(endLocalDate, endLocalTime, SYSTEM_ZONE_OFFSET)); } public Integer getAppointment_ID() { return Appointment_ID; } public void setAppointment_ID(Integer appointment_ID) { Appointment_ID = appointment_ID; } public String getTitle() { return Title; } public void setTitle(String title) { Title = title; } public String getDescription() { return Description; } public void setDescription(String description) { Description = description; } public String getLocation() { return Location; } public void setLocation(String location) { Location = location; } public String getType() { return Type; } public void setType(String type) { Type = type; } public DateTime getStart() { return Start; } public void setStart(DateTime start) { Start = start; } public DateTime getEnd() { return End; } public void setEnd(DateTime end) { End = end; } public Integer getCustomer_ID() { return Customer_ID; } public void setCustomer_ID(Integer customer_ID) { Customer_ID = customer_ID; } public Integer getUser_ID() { return User_ID; } public void setUser_ID(Integer user_ID) { User_ID = user_ID; } public Integer getContact_ID() { return Contact_ID; } public void setContact_ID(Integer contact_ID) { Contact_ID = contact_ID; } @Override public int getId() { return Appointment_ID; } @Override public String getIdString() { return Integer.toString(Appointment_ID); } @Override public String getName() { return Title; } @Override public String toString() { return new StringJoiner("\n", Appointment.class.getSimpleName() + ": \n", "") .add("Appointment_ID: " + Appointment_ID) .add("Title: '" + Title + "'") .add("Description: '" + Description + "'") .add("Location: '" + Location + "'") .add("Type: '" + Type + "'") .add("Start: " + Start) .add("End: " + End) .add("Customer_ID: " + Customer_ID) .add("User_ID: " + User_ID) .add("Contact_ID: " + Contact_ID) .add("Id: " + Id) .add("Create_Date: " + Create_Date) .add("Created_By: '" + Created_By + "'") .add("Last_Update: " + Last_Update) .add("Last_Updated_By: '" + Last_Updated_By + "'") .toString(); } public LocalDate getStartDate() { return Start.getLocalDate(); } public LocalTime getStartTime() { return Start.getLocalTime(); } public Integer getStartHour() { return Start.getHour(); } public Integer getStartMinute() { return Start.getMinute(); } public MeridiemIndicator getStartMeridiem() { return Start.getMeridiem(); } public LocalDate getEndDate() { return End.getLocalDate(); } public LocalTime getEndTime() { return End.getLocalTime(); } public MeridiemIndicator getEndMeridiem() { return End.getMeridiem(); } public Integer getEndHour() { return End.getHour(); } public Integer getEndMinute() { return End.getMinute(); } }
Java
UTF-8
2,227
1.976563
2
[]
no_license
package com.skypremiuminternational.app.data.network.service; import com.skypremiuminternational.app.data.network.URL; import com.skypremiuminternational.app.domain.models.myOrder.ExtraOrderDetail; import com.skypremiuminternational.app.domain.models.myOrder.MyOrderResponse; import com.skypremiuminternational.app.domain.models.myOrder.detail.OrderDetailResponse; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.Path; import retrofit2.http.Query; import rx.Observable; /** * Created by aeindraaung on 2/9/18. */ public interface OrderHistoryService { @Headers("Content-Type: application/json") @GET(URL.ORDER_HISTORY) Observable<MyOrderResponse> getOrderHistory(@Header("Authorization") String auth, @Query("searchCriteria[filterGroups][0][filters][0][value]") String email, @Query("searchCriteria[sortOrders][0][direction]") String selectedSorting); @Headers("Content-Type: application/json") @GET(URL.ORDERHISTORY_WITH_CATEGORY) Observable<MyOrderResponse> getOrderHistoryWithFilter(@Header("Authorization") String auth, @Query("searchCriteria[filterGroups][0][filters][0][value]") String email, @Query("searchCriteria[filterGroups][1][filters][0][value]") String selectedCategory, @Query("searchCriteria[sortOrders][0][direction]") String selectedSorting, @Query("searchCriteria[sortOrders][0][field]") String field); @Headers("Content-Type: application/json") @GET(URL.ORDER_DETAIL) Observable<OrderDetailResponse> getOrderDetail(@Header("Authorization") String clientToken, @Path("order_id") Integer orderId); @Headers("Cache-Control: no-cache") @GET(URL.ORDER_HISTORY_EXTRA) Observable<ExtraOrderDetail> getOrderHistoryExtra(@Header("Authorization") String clientToken, @Path("order_id") Integer orderId); }
Java
UTF-8
238
1.570313
2
[]
no_license
package com.lunar.mgr.dao; import com.lunar.mgr.pojo.ChargeInfoPO; import tk.mybatis.mapper.common.Mapper; import java.util.List; public interface ChargeInfoMapper extends Mapper<ChargeInfoPO> { List<ChargeInfoPO> selectInfo(); }
JavaScript
UTF-8
444
3.546875
4
[]
no_license
function checkGoldbach(n) { if (n % 2 == 1 || n < 4) { console.log(null); } else { for (var a = 2; a <= n / 2; a++) { var b = n - a; if (isPrime(a) && isPrime(b)) { console.log(String(a) + " " + String(b)); } } } } function isPrime(n) { if (n <= 1) { return false; } else { for (var i = 2; i < n; i++) { if (n % i === 0) { return false; } } } return true; }
Python
UTF-8
262
3.484375
3
[]
no_license
print("R$ {:7.1f}".format(1000.12)) print("R$ {:07.2f}".format(4.11)) print("R$ {:7.1f}".format(1000.16)) dia_ini = 24 dia_fim = 28 mes = "fevereiro" ano = 2017 print("Em {} o Carnaval acontece em {} do dia {} até o dia {}".format(ano, mes, dia_ini, dia_fim))
C++
UTF-8
2,192
2.921875
3
[]
no_license
// Quick, naive, thrown-together scanner for CS254 parser generator assignment. // Recognizes a variety of useful tokens, for no particular language. // Michael L. Scott, Sept. 2008. #include <string> using std::string; namespace scanner { enum tok_num { undef = 0, // placeholder; value 0 not used tok_eof = 1, // end of file ident = 2, // letter ( letter | '_' | digit )* rw_array = 3, // "array" rw_begin = 4, // "begin" rw_do = 5, // "do" rw_else = 6, // "else" rw_end = 7, // "end" rw_float = 8, // "float" rw_for = 9, // "for" rw_if = 10, // "if" rw_int = 11, // "int" rw_proc = 12, // "proc" rw_read = 13, // "read" rw_real = 14, // "real" rw_then = 15, // "then" rw_trunc = 16, // "trunc" rw_while = 17, // "while" rw_write = 18, // "write" lit_int = 19, // digit+ lit_real = 20, // digit+ '.' digit+ becomes = 21, // ":=" op_add = 22, // "+" op_sub = 23, // "-" op_mul = 24, // "*" op_div = 25, // "/" lparen = 26, // "(" rparen = 27, // ")" lbrac = 28, // "[" rbrac = 29, // "]" comma = 30, // "," semic = 31, // ";" colon = 32, // ":" op_lt = 33, // "<" op_gt = 34, // ">" op_le = 35, // "<=" op_ge = 36, // ">=" op_eq = 37, // "==" op_ne = 38, // "!=" tok_error = 39 // not a valid token }; static const tok_num first_rw = rw_array; static const tok_num last_rw = rw_write; struct token { tok_num num; const char* name; // generic name of this sort of token string image; // printable image of this particular token int line; // location of token; int column; // for error messages }; extern token scan(); } // end namespace scanner
C++
UTF-8
1,193
2.75
3
[]
no_license
#ifndef BSTREENODE_HPP #define BSTREENODE_HPP #include <string> template <typename T> class BSTreeNode { private: T data; BSTreeNode<T> *rightChild; BSTreeNode<T> *leftChild; //using parent node to determine when the root has to be adjusted BSTreeNode<T> *parent; int balanceFactor; // if change root is true then the root gets adjusted bool changeRoot; void rightRotation(); void leftRotation(); void leftRightRotation(); void rightLeftRotation(); void ComputeEffort(int level, int & totalEffort, int & size); public: BSTreeNode(const T& value); //custom constructor ~BSTreeNode(); BSTreeNode<T> & operator=(const BSTreeNode<T> rhs); //delegate target for BSTree's version in Insert void Insert(const T& value); //the AVL version of Insert BSTreeNode<T> * InsertAVL(const T& value); // more here from BSTree.hpp bool Search(const T& value); void InOrderPrint(); void PostOrderPrint(); void PreOrderPrint(); void DotFormat(); float ComputeACE(); }; #endif
Java
UTF-8
818
2.234375
2
[]
no_license
package com.PIK.domain; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.Date; @Data @ToString(exclude = {"vehicle","service"}) @NoArgsConstructor @Entity @Table(name = "Reservations") public class Reservation { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @NotNull(message = "Please fill in 'date' field.") @Column(name = "date") private Date reservationDate; @NotNull(message = "Please fill in 'status' field.") @Column(name = "status") private boolean status; @OneToOne @JoinColumn(name = "fk_vehicle_id") private Vehicle vehicle; @ManyToOne @JoinColumn(name = "fk_service_id") private Service service; }
Python
UTF-8
238
3.40625
3
[]
no_license
def min(a,b): if(a>b): return b else: return a c = min(10,20) print("{0}".format(c)) def printS(c): print(c) printS("Hello") def divide(a,b): return(a/b,a%b) d,v=divide(12,3) print(d,v) print(type(d))
Python
UTF-8
4,115
2.625
3
[]
no_license
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import re precisionRegex= re.compile(r'(?<=precision:\s\s)(\d+\.\d+)') recallRegex= re.compile(r'(?<=recall:\s\s)(\d+\.\d+)') f1ScoreRegex= re.compile(r'(?<=f1\sscore:\s\s)(\d+\.\d+)') totalLossRegex= re.compile(r'(?<=total\sloss:\s)(\d+\.\d+)') def plotting_storing(loss_train_record, loss_val_record, loss_test_record, f1_train_record, f1_val_record, f1_test_record): num_points = len(loss_train_record) x_list = range(1, len(loss_train_record) + 1) colors_train = [] colors_val = [] colors_test = [] interval_idx = 0 for idx in x_list: interval_idx += 1 if interval_idx - 1 == 10: colors_train.append('b') colors_val.append('m') colors_test.append('g') interval_idx = 0 else: colors_train.append('b') colors_val.append('m') colors_test.append('g') plt.figure(figsize=(12, 5)) #figure_name = Model_Parameters['fig_path'] + 'loss_' + Model_Parameters['fig_name'] + '.png' plt.scatter(x=x_list, y=loss_train_record, c=colors_train, marker='o', label='Training loss') plt.scatter(x=x_list, y=loss_val_record, c=colors_val, marker='s', label='Validaton loss') plt.scatter(x=x_list, y=loss_test_record, c=colors_test, marker='v', label='Testing loss') plt.legend(loc=1) plt.title('Loss covergence curve') plt.xlabel('Iteration') plt.ylabel('Loss') plt.savefig("loss_test.png") plt.show() plt.figure(figsize=(12, 5)) #figure_name = Model_Parameters['fig_path'] + 'f1_' + Model_Parameters['fig_name'] + '.png' plt.scatter(x=x_list, y=f1_train_record, c=colors_train, marker='o', label='Training F1') plt.scatter(x=x_list, y=f1_val_record, c=colors_val, marker='s', label='Validation F1') plt.scatter(x=x_list, y=f1_test_record, c=colors_test, marker='v', label='Testing F1') x_best = f1_val_record.index(max(f1_val_record)) + 1 val_best = max(f1_val_record) train_best = f1_train_record[x_best - 1] test_best = f1_test_record[x_best - 1] plt.annotate(str(max(f1_val_record)), xy=(x_best, val_best), xytext=(x_best-(len(x_list) / 5)-1, val_best-5), arrowprops=dict(arrowstyle='->', color='m')) plt.legend(loc=2) plt.title('F1 score convergence curve') plt.xlabel('Iteration') plt.ylabel('F1') plt.savefig("f1_test.png") plt.show() print("Done plotting") return def getF1andLoss(filepath="./char-w-lstm-word-crf-conll2003.o3128445"): train_losses, train_precision, train_recall, train_f1, test_precision, test_recall, test_f1, val_precision, val_recall, val_f1,test_losses,val_losses = [],[],[],[],[],[],[],[],[],[],[],[] with open(filepath, 'r') as myfile: data = myfile.read() text_splits=data.split("Iteration") for Iteration in text_splits[1:]: precisions=precisionRegex.findall(Iteration) recalls = recallRegex.findall(Iteration) f1Scores = f1ScoreRegex.findall(Iteration) losses = totalLossRegex.findall(Iteration) train_precision.append(float(precisions[0])) train_recall.append(float(recalls[0])) train_f1.append(float(f1Scores[0])) train_losses.append(float(losses[0])) val_precision.append(float(precisions[1])) val_recall.append(float(recalls[1])) val_f1.append(float(f1Scores[1])) val_losses.append(float(losses[1])) test_precision.append(float(precisions[2])) test_recall.append(float(recalls[2])) test_f1.append(float(f1Scores[2])) test_losses.append(float(losses[2])) return train_losses, train_precision, train_recall, train_f1, test_precision, test_recall, test_f1,test_losses, val_precision, val_recall, val_f1,val_losses train_losses, train_precision, train_recall, train_f1, test_precision, test_recall, test_f1, test_losses, val_precision, val_recall, val_f1, val_losses=getF1andLoss() plotting_storing(train_losses,val_losses,test_losses,train_f1,val_f1,test_f1)
Java
UTF-8
1,352
2.234375
2
[ "Apache-2.0" ]
permissive
package com.mic.keisystem.network.protocol; import com.mic.BitConverter; import com.mic.keisystem.InvalidKSMessageException; import com.mic.keisystem.KSMessage; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import java.io.IOException; /** * Created by MIC/Headcrabbed on 2015/3/17. */ public final class KSMessageRequestDecoder extends CumulativeProtocolDecoder { // See: http://mina.apache.org/mina-project/userguide/ch9-codec-filter/ch9-codec-filter.html @Override protected boolean doDecode(IoSession ioSession, IoBuffer ioBuffer, ProtocolDecoderOutput protocolDecoderOutput) throws Exception { // 前4个字节是长度说明符(int),参数 i 为说明符长度 if (ioBuffer.prefixedDataAvailable(4)) { KSMessage message = readMessage(ioBuffer); KSMessageRequest request = new KSMessageRequest(message); protocolDecoderOutput.write(request); return true; } else { return false; } } private KSMessage readMessage(IoBuffer ioBuffer) throws IOException, InvalidKSMessageException { return KSMessage.fromByteArray(ioBuffer.asInputStream()); } }
Java
UTF-8
98,919
2.65625
3
[]
no_license
package com.earthview.world.graphic; import global.*; import com.earthview.world.base.*; import com.earthview.world.util.*; import com.earthview.world.core.*; /** * 粒子系统管理器 */ public class ParticleSystemManager extends com.earthview.world.graphic.ScriptLoader { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager", new ParticleSystemManagerClassFactory()); GlobalClassFactoryMap.put("EarthView::World::Graphic::JCParticleSystemManagerProxy", new ParticleSystemManagerClassFactory()); } public static class ParticleTemplateMap extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::ParticleTemplateMap", new ParticleTemplateMapClassFactory()); } /** * 默认构造函数 * @param */ public ParticleTemplateMap() { super(CreatedWhenConstruct.CWC_NotToCreate); Create("ParticleTemplateMap", null); } native private boolean push_EVString_CParticleSystem(long pNativeObject, String key, long ref_val); /** * 在map容器中添加元素 * @param key 键 * @param val 值 * @return 成功增加true,否则false */ public boolean push(String key, NativeObjectPointer<com.earthview.world.graphic.ParticleSystem> ref_val) { String keyParamValue = key; long ref_valParamValue = ref_val.nativeObject.pointer; boolean returnValue = push_EVString_CParticleSystem(this.nativeObject.pointer, keyParamValue, ref_valParamValue); return returnValue; } native private boolean exist_EVString(long pNativeObject, String key); /** * 判断元素是否存在 * @param key 键 * @return 存在true,否则false */ public boolean exist(String key) { String keyParamValue = key; boolean returnValue = exist_EVString(this.nativeObject.pointer, keyParamValue); return returnValue; } native private long OperatorIndex_EVString(long pNativeObject, String key); /** * 重载[]操作符 * @param key 键 * @return 返回键对应的值 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleSystem> OperatorIndex(String key) { String keyParamValue = key; long returnValue = OperatorIndex_EVString(this.nativeObject.pointer, keyParamValue); NativeObjectPointer<com.earthview.world.graphic.ParticleSystem> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleSystem>(new InstancePointer(returnValue)); return __returnValue; } native private long get_EVString(long pNativeObject, String key); /** * 获得键对应的值 * @param key 键 * @return 返回键对应的值 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleSystem> get(String key) { String keyParamValue = key; long returnValue = get_EVString(this.nativeObject.pointer, keyParamValue); NativeObjectPointer<com.earthview.world.graphic.ParticleSystem> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleSystem>(new InstancePointer(returnValue)); return __returnValue; } native private void erase_EVString(long pNativeObject, String key); /** * 删除键对应的值 * @param key 键 */ public void erase(String key) { String keyParamValue = key; erase_EVString(this.nativeObject.pointer, keyParamValue); } native private long size_void(long pNativeObject); /** * 返回容器的大小 * @param * @return 容器的大小 */ public long size() { long returnValue = size_void(this.nativeObject.pointer); return returnValue; } native private void clear_void(long pNativeObject); /** * 清空容器 * @param */ public void clear() { clear_void(this.nativeObject.pointer); } native private boolean empty_void(long pNativeObject); /** * 判断容器是否为空 * @param * @return 容器为空返回true,否则false */ public boolean empty() { boolean returnValue = empty_void(this.nativeObject.pointer); return returnValue; } public ParticleTemplateMap(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public ParticleTemplateMap(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static ParticleTemplateMap fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } ParticleTemplateMap obj = null; if(baseObj instanceof ParticleTemplateMap) { obj = (ParticleTemplateMap)baseObj; } else { obj = new ParticleTemplateMap(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "ParticleTemplateMap"); obj.increaseCast(); } return obj; } } public static class ParticleTemplateMapClassFactory implements IClassFactory { public BaseObject create() { ParticleTemplateMap emptyInstance = new ParticleTemplateMap(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } public static class ParticleAffectorFactoryMap extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::ParticleAffectorFactoryMap", new ParticleAffectorFactoryMapClassFactory()); } /** * 默认构造函数 * @param */ public ParticleAffectorFactoryMap() { super(CreatedWhenConstruct.CWC_NotToCreate); Create("ParticleAffectorFactoryMap", null); } native private boolean push_EVString_CParticleAffectorFactory(long pNativeObject, String key, long ref_val); /** * 在map容器中添加元素 * @param key 键 * @param val 值 * @return 成功增加true,否则false */ public boolean push(String key, NativeObjectPointer<com.earthview.world.graphic.ParticleAffectorFactory> ref_val) { String keyParamValue = key; long ref_valParamValue = ref_val.nativeObject.pointer; boolean returnValue = push_EVString_CParticleAffectorFactory(this.nativeObject.pointer, keyParamValue, ref_valParamValue); return returnValue; } native private boolean exist_EVString(long pNativeObject, String key); /** * 判断元素是否存在 * @param key 键 * @return 存在true,否则false */ public boolean exist(String key) { String keyParamValue = key; boolean returnValue = exist_EVString(this.nativeObject.pointer, keyParamValue); return returnValue; } native private long OperatorIndex_EVString(long pNativeObject, String key); /** * 重载[]操作符 * @param key 键 * @return 返回键对应的值 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleAffectorFactory> OperatorIndex(String key) { String keyParamValue = key; long returnValue = OperatorIndex_EVString(this.nativeObject.pointer, keyParamValue); NativeObjectPointer<com.earthview.world.graphic.ParticleAffectorFactory> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleAffectorFactory>(new InstancePointer(returnValue)); return __returnValue; } native private long get_EVString(long pNativeObject, String key); /** * 获得键对应的值 * @param key 键 * @return 返回键对应的值 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleAffectorFactory> get(String key) { String keyParamValue = key; long returnValue = get_EVString(this.nativeObject.pointer, keyParamValue); NativeObjectPointer<com.earthview.world.graphic.ParticleAffectorFactory> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleAffectorFactory>(new InstancePointer(returnValue)); return __returnValue; } native private void erase_EVString(long pNativeObject, String key); /** * 删除键对应的值 * @param key 键 */ public void erase(String key) { String keyParamValue = key; erase_EVString(this.nativeObject.pointer, keyParamValue); } native private long size_void(long pNativeObject); /** * 返回容器的大小 * @param * @return 容器的大小 */ public long size() { long returnValue = size_void(this.nativeObject.pointer); return returnValue; } native private void clear_void(long pNativeObject); /** * 清空容器 * @param */ public void clear() { clear_void(this.nativeObject.pointer); } native private boolean empty_void(long pNativeObject); /** * 判断容器是否为空 * @param * @return 容器为空返回true,否则false */ public boolean empty() { boolean returnValue = empty_void(this.nativeObject.pointer); return returnValue; } public ParticleAffectorFactoryMap(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public ParticleAffectorFactoryMap(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static ParticleAffectorFactoryMap fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } ParticleAffectorFactoryMap obj = null; if(baseObj instanceof ParticleAffectorFactoryMap) { obj = (ParticleAffectorFactoryMap)baseObj; } else { obj = new ParticleAffectorFactoryMap(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "ParticleAffectorFactoryMap"); obj.increaseCast(); } return obj; } } public static class ParticleAffectorFactoryMapClassFactory implements IClassFactory { public BaseObject create() { ParticleAffectorFactoryMap emptyInstance = new ParticleAffectorFactoryMap(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } public static class ParticleEmitterFactoryMap extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::ParticleEmitterFactoryMap", new ParticleEmitterFactoryMapClassFactory()); } /** * 默认构造函数 * @param */ public ParticleEmitterFactoryMap() { super(CreatedWhenConstruct.CWC_NotToCreate); Create("ParticleEmitterFactoryMap", null); } native private boolean push_EVString_CParticleEmitterFactory(long pNativeObject, String key, long ref_val); /** * 在map容器中添加元素 * @param key 键 * @param val 值 * @return 成功增加true,否则false */ public boolean push(String key, NativeObjectPointer<com.earthview.world.graphic.ParticleEmitterFactory> ref_val) { String keyParamValue = key; long ref_valParamValue = ref_val.nativeObject.pointer; boolean returnValue = push_EVString_CParticleEmitterFactory(this.nativeObject.pointer, keyParamValue, ref_valParamValue); return returnValue; } native private boolean exist_EVString(long pNativeObject, String key); /** * 判断元素是否存在 * @param key 键 * @return 存在true,否则false */ public boolean exist(String key) { String keyParamValue = key; boolean returnValue = exist_EVString(this.nativeObject.pointer, keyParamValue); return returnValue; } native private long OperatorIndex_EVString(long pNativeObject, String key); /** * 重载[]操作符 * @param key 键 * @return 返回键对应的值 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleEmitterFactory> OperatorIndex(String key) { String keyParamValue = key; long returnValue = OperatorIndex_EVString(this.nativeObject.pointer, keyParamValue); NativeObjectPointer<com.earthview.world.graphic.ParticleEmitterFactory> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleEmitterFactory>(new InstancePointer(returnValue)); return __returnValue; } native private long get_EVString(long pNativeObject, String key); /** * 获得键对应的值 * @param key 键 * @return 返回键对应的值 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleEmitterFactory> get(String key) { String keyParamValue = key; long returnValue = get_EVString(this.nativeObject.pointer, keyParamValue); NativeObjectPointer<com.earthview.world.graphic.ParticleEmitterFactory> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleEmitterFactory>(new InstancePointer(returnValue)); return __returnValue; } native private void erase_EVString(long pNativeObject, String key); /** * 删除键对应的值 * @param key 键 */ public void erase(String key) { String keyParamValue = key; erase_EVString(this.nativeObject.pointer, keyParamValue); } native private long size_void(long pNativeObject); /** * 返回容器的大小 * @param * @return 容器的大小 */ public long size() { long returnValue = size_void(this.nativeObject.pointer); return returnValue; } native private void clear_void(long pNativeObject); /** * 清空容器 * @param */ public void clear() { clear_void(this.nativeObject.pointer); } native private boolean empty_void(long pNativeObject); /** * 判断容器是否为空 * @param * @return 容器为空返回true,否则false */ public boolean empty() { boolean returnValue = empty_void(this.nativeObject.pointer); return returnValue; } public ParticleEmitterFactoryMap(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public ParticleEmitterFactoryMap(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static ParticleEmitterFactoryMap fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } ParticleEmitterFactoryMap obj = null; if(baseObj instanceof ParticleEmitterFactoryMap) { obj = (ParticleEmitterFactoryMap)baseObj; } else { obj = new ParticleEmitterFactoryMap(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "ParticleEmitterFactoryMap"); obj.increaseCast(); } return obj; } } public static class ParticleEmitterFactoryMapClassFactory implements IClassFactory { public BaseObject create() { ParticleEmitterFactoryMap emptyInstance = new ParticleEmitterFactoryMap(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } public static class ParticleSystemRendererFactoryMap extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::ParticleSystemRendererFactoryMap", new ParticleSystemRendererFactoryMapClassFactory()); } /** * 默认构造函数 * @param */ public ParticleSystemRendererFactoryMap() { super(CreatedWhenConstruct.CWC_NotToCreate); Create("ParticleSystemRendererFactoryMap", null); } native private boolean push_EVString_CParticleSystemRendererFactory(long pNativeObject, String key, long ref_val); /** * 在map容器中添加元素 * @param key 键 * @param val 值 * @return 成功增加true,否则false */ public boolean push(String key, NativeObjectPointer<com.earthview.world.graphic.ParticleSystemRendererFactory> ref_val) { String keyParamValue = key; long ref_valParamValue = ref_val.nativeObject.pointer; boolean returnValue = push_EVString_CParticleSystemRendererFactory(this.nativeObject.pointer, keyParamValue, ref_valParamValue); return returnValue; } native private boolean exist_EVString(long pNativeObject, String key); /** * 判断元素是否存在 * @param key 键 * @return 存在true,否则false */ public boolean exist(String key) { String keyParamValue = key; boolean returnValue = exist_EVString(this.nativeObject.pointer, keyParamValue); return returnValue; } native private long OperatorIndex_EVString(long pNativeObject, String key); /** * 重载[]操作符 * @param key 键 * @return 返回键对应的值 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleSystemRendererFactory> OperatorIndex(String key) { String keyParamValue = key; long returnValue = OperatorIndex_EVString(this.nativeObject.pointer, keyParamValue); NativeObjectPointer<com.earthview.world.graphic.ParticleSystemRendererFactory> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleSystemRendererFactory>(new InstancePointer(returnValue)); return __returnValue; } native private long get_EVString(long pNativeObject, String key); /** * 获得键对应的值 * @param key 键 * @return 返回键对应的值 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleSystemRendererFactory> get(String key) { String keyParamValue = key; long returnValue = get_EVString(this.nativeObject.pointer, keyParamValue); NativeObjectPointer<com.earthview.world.graphic.ParticleSystemRendererFactory> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleSystemRendererFactory>(new InstancePointer(returnValue)); return __returnValue; } native private void erase_EVString(long pNativeObject, String key); /** * 删除键对应的值 * @param key 键 */ public void erase(String key) { String keyParamValue = key; erase_EVString(this.nativeObject.pointer, keyParamValue); } native private long size_void(long pNativeObject); /** * 返回容器的大小 * @param * @return 容器的大小 */ public long size() { long returnValue = size_void(this.nativeObject.pointer); return returnValue; } native private void clear_void(long pNativeObject); /** * 清空容器 * @param */ public void clear() { clear_void(this.nativeObject.pointer); } native private boolean empty_void(long pNativeObject); /** * 判断容器是否为空 * @param * @return 容器为空返回true,否则false */ public boolean empty() { boolean returnValue = empty_void(this.nativeObject.pointer); return returnValue; } public ParticleSystemRendererFactoryMap(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public ParticleSystemRendererFactoryMap(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static ParticleSystemRendererFactoryMap fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } ParticleSystemRendererFactoryMap obj = null; if(baseObj instanceof ParticleSystemRendererFactoryMap) { obj = (ParticleSystemRendererFactoryMap)baseObj; } else { obj = new ParticleSystemRendererFactoryMap(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "ParticleSystemRendererFactoryMap"); obj.increaseCast(); } return obj; } } public static class ParticleSystemRendererFactoryMapClassFactory implements IClassFactory { public BaseObject create() { ParticleSystemRendererFactoryMap emptyInstance = new ParticleSystemRendererFactoryMap(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } /** * 默认构造函数 * @param */ public ParticleSystemManager() { super(CreatedWhenConstruct.CWC_NotToCreate); Create("JCParticleSystemManagerProxy", null, true); this.registerCallback(); if (!"com.earthview.world.graphic.ParticleSystemManager".equals(this.getClass().getName())) { this.setCustomExtend(true); } } native private void addEmitterFactory_CParticleEmitterFactory(long pNativeObject, long ref_factory); /** * 添加一个新的发射器对象工厂到可用的发射器类型列表中 * @param factory 指向EarthView::World::Graphic::CParticleEmitterFactory的指针 */ public void addEmitterFactory(com.earthview.world.graphic.ParticleEmitterFactory ref_factory) { long ref_factoryParamValue = (ref_factory == null ? 0L : ref_factory.nativeObject.pointer); addEmitterFactory_CParticleEmitterFactory(this.nativeObject.pointer, ref_factoryParamValue); } native private void addAffectorFactory_CParticleAffectorFactory(long pNativeObject, long ref_factory); /** * 添加一个新的效果器对象工厂到可用的发射器类型列表中 * @param factory 指向EarthView::World::Graphic::CParticleEmitterFactory的指针 */ public void addAffectorFactory(com.earthview.world.graphic.ParticleAffectorFactory ref_factory) { long ref_factoryParamValue = (ref_factory == null ? 0L : ref_factory.nativeObject.pointer); addAffectorFactory_CParticleAffectorFactory(this.nativeObject.pointer, ref_factoryParamValue); } native private void addRendererFactory_CParticleSystemRendererFactory(long pNativeObject, long ref_factory); /** * 注册一个工厂类来创建EarthView::World::Graphic::CParticleSystemRenderer实例 * @param factory 指向EarthView::World::Graphic::CParticleSystemRendererFactory的指针 */ public void addRendererFactory(com.earthview.world.graphic.ParticleSystemRendererFactory ref_factory) { long ref_factoryParamValue = (ref_factory == null ? 0L : ref_factory.nativeObject.pointer); addRendererFactory_CParticleSystemRendererFactory(this.nativeObject.pointer, ref_factoryParamValue); } native private void addTemplate_EVString_CParticleSystem(long pNativeObject, String name, long ref_sysTemplate); /** * 添加一个新的粒子系统模板到可用的模板列表中 * @param name 模板的名称 * @param sysTemplate 指向粒子系统的指针 */ public void addTemplate(String name, com.earthview.world.graphic.ParticleSystem ref_sysTemplate) { String nameParamValue = name; long ref_sysTemplateParamValue = (ref_sysTemplate == null ? 0L : ref_sysTemplate.nativeObject.pointer); addTemplate_EVString_CParticleSystem(this.nativeObject.pointer, nameParamValue, ref_sysTemplateParamValue); } native private void removeTemplate_EVString_ev_bool(long pNativeObject, String name, boolean deleteTemplate); /** * 从粒子系统管理中去除掉一个已给的模板 * @param name 去除模板的名称 * @param deleteTemplate 如果为ture删除模板,否则不删除 */ public void removeTemplate(String name, boolean deleteTemplate) { String nameParamValue = name; boolean deleteTemplateParamValue = deleteTemplate; removeTemplate_EVString_ev_bool(this.nativeObject.pointer, nameParamValue, deleteTemplateParamValue); } native private void removeTemplate_EVString(long pNativeObject, String name); /** * 从粒子系统管理中去除掉一个已给的模板 * @param name 去除模板的名称 */ public void removeTemplate(String name) { String nameParamValue = name; removeTemplate_EVString(this.nativeObject.pointer, nameParamValue); } native private void removeAllTemplates_ev_bool(long pNativeObject, boolean deleteTemplate); /** * 从粒子系统管理中去除所有的模板 * @param deleteTemplate 如果为ture删除模板,否则不删除 */ public void removeAllTemplates(boolean deleteTemplate) { boolean deleteTemplateParamValue = deleteTemplate; removeAllTemplates_ev_bool(this.nativeObject.pointer, deleteTemplateParamValue); } native private void removeAllTemplates_void(long pNativeObject); /** * 从粒子系统管理中去除所有的模板 * @param */ public void removeAllTemplates() { removeAllTemplates_void(this.nativeObject.pointer); } native private void removeTemplatesByResourceGroup_EVString(long pNativeObject, String resourceGroup); /** * 去除指定资源组的所有模板 * @param resourceGroup 删除模板的资源组 */ public void removeTemplatesByResourceGroup(String resourceGroup) { String resourceGroupParamValue = resourceGroup; removeTemplatesByResourceGroup_EVString(this.nativeObject.pointer, resourceGroupParamValue); } native private long createTemplate_EVString_EVString(long pNativeObject, String name, String resourceGroup); /** * 创建一个新的粒子系统模板 * @param name 模板的名称 * @param resourceGroup 资源组的名称 */ public com.earthview.world.graphic.ParticleSystem createTemplate(String name, String resourceGroup) { String nameParamValue = name; String resourceGroupParamValue = resourceGroup; long returnValue = createTemplate_EVString_EVString(this.nativeObject.pointer, nameParamValue, resourceGroupParamValue); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystem __returnValue = new com.earthview.world.graphic.ParticleSystem(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystem"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystem)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystem"); } return __returnValue; } native private long getTemplate_EVString(long pNativeObject, String name); /** * 获得粒子系统模板 * @param name 模板的名称 */ public com.earthview.world.graphic.ParticleSystem getTemplate(String name) { String nameParamValue = name; long returnValue = getTemplate_EVString(this.nativeObject.pointer, nameParamValue); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystem __returnValue = new com.earthview.world.graphic.ParticleSystem(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystem"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystem)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystem"); } return __returnValue; } native private long _createEmitter_EVString_CParticleSystem(long pNativeObject, String emitterType, long psys); /// <summary> /// 创建一个新的发射器 /// </summary> /// <param name="emitterType">创建的发射器类型的名称</param> /// <param name="psys"><指向粒子系统的指针/param> /// <returns></returns> public com.earthview.world.graphic.ParticleEmitter _createEmitter(String emitterType, com.earthview.world.graphic.ParticleSystem psys) { String emitterTypeParamValue = emitterType; long psysParamValue = (psys == null ? 0L : psys.nativeObject.pointer); long returnValue = _createEmitter_EVString_CParticleSystem(this.nativeObject.pointer, emitterTypeParamValue, psysParamValue); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleEmitter __returnValue = new com.earthview.world.graphic.ParticleEmitter(CreatedWhenConstruct.CWC_NotToCreate, "CParticleEmitter"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleEmitter)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleEmitter"); } return __returnValue; } native private void _destroyEmitter_CParticleEmitter(long pNativeObject, long emitter); /** * 销毁一个发射器 * @param emitter 指向被销毁发射器的指针 */ public void _destroyEmitter(com.earthview.world.graphic.ParticleEmitter emitter) { long emitterParamValue = (emitter == null ? 0L : emitter.nativeObject.pointer); _destroyEmitter_CParticleEmitter(this.nativeObject.pointer, emitterParamValue); } native private long _createAffector_EVString_CParticleSystem(long pNativeObject, String affectorType, long psys); /// <summary> /// 创建一个新的效果器 /// </summary> /// <param name="affectorType">创建的效果器类型的名称</param> /// <param name="psys"><指向粒子系统的指针/param> /// <returns></returns> public com.earthview.world.graphic.ParticleAffector _createAffector(String affectorType, com.earthview.world.graphic.ParticleSystem psys) { String affectorTypeParamValue = affectorType; long psysParamValue = (psys == null ? 0L : psys.nativeObject.pointer); long returnValue = _createAffector_EVString_CParticleSystem(this.nativeObject.pointer, affectorTypeParamValue, psysParamValue); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleAffector __returnValue = new com.earthview.world.graphic.ParticleAffector(CreatedWhenConstruct.CWC_NotToCreate, "CParticleAffector"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleAffector)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleAffector"); } return __returnValue; } native private void _destroyAffector_CParticleAffector(long pNativeObject, long affector); /** * 销毁一个效果器 * @param affector 指向被销毁效果器的指针 */ public void _destroyAffector(com.earthview.world.graphic.ParticleAffector affector) { long affectorParamValue = (affector == null ? 0L : affector.nativeObject.pointer); _destroyAffector_CParticleAffector(this.nativeObject.pointer, affectorParamValue); } native private long _createRenderer_EVString(long pNativeObject, String rendererType); /** * 创建一个新的渲染器 * @param rendererType 创建的渲染器类型的名称 */ public com.earthview.world.graphic.ParticleSystemRenderer _createRenderer(String rendererType) { String rendererTypeParamValue = rendererType; long returnValue = _createRenderer_EVString(this.nativeObject.pointer, rendererTypeParamValue); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystemRenderer __returnValue = new com.earthview.world.graphic.ParticleSystemRenderer(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystemRenderer"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemRenderer)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystemRenderer"); } return __returnValue; } native private void _destroyRenderer_CParticleSystemRenderer(long pNativeObject, long renderer); /** * 销毁一个渲染器 * @param renderer 指向被销毁渲染器的指针 */ public void _destroyRenderer(com.earthview.world.graphic.ParticleSystemRenderer renderer) { long rendererParamValue = (renderer == null ? 0L : renderer.nativeObject.pointer); _destroyRenderer_CParticleSystemRenderer(this.nativeObject.pointer, rendererParamValue); } native private void _initialise_void(long pNativeObject); /** * 初始化方法 * @param */ public void _initialise() { _initialise_void(this.nativeObject.pointer); } native private long getScriptPatterns_void(long pNativeObject); /** * 获得用来查找脚本文件的文件样式 * @param */ public com.earthview.world.core.StringVector getScriptPatterns() { long returnValue = getScriptPatterns_void(this.nativeObject.pointer); com.earthview.world.core.StringVector __returnValue = new com.earthview.world.core.StringVector(CreatedWhenConstruct.CWC_NotToCreate, "StringVector"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.core.StringVector)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringVector"); } return __returnValue; } native private long getScriptPatterns_void_NoVirtual(long pNativeObject); protected com.earthview.world.core.StringVector getScriptPatterns_NoVirtual() { long returnValue = getScriptPatterns_void_NoVirtual(this.nativeObject.pointer); com.earthview.world.core.StringVector __returnValue = new com.earthview.world.core.StringVector(CreatedWhenConstruct.CWC_NotToCreate, "StringVector"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.core.StringVector)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringVector"); } return __returnValue; } native private void parseScript_DataStreamPtr_EVString(long pNativeObject, long stream, String groupName); /** * 解析脚本文件 * @param */ public void parseScript(com.earthview.world.core.DataStreamPtr stream, String groupName) { long streamParamValue = stream.nativeObject.pointer; String groupNameParamValue = groupName; parseScript_DataStreamPtr_EVString(this.nativeObject.pointer, streamParamValue, groupNameParamValue); } native private void parseScript_DataStreamPtr_EVString_NoVirtual(long pNativeObject, long stream, String groupName); protected void parseScript_NoVirtual(com.earthview.world.core.DataStreamPtr stream, String groupName) { long streamParamValue = stream.nativeObject.pointer; String groupNameParamValue = groupName; parseScript_DataStreamPtr_EVString_NoVirtual(this.nativeObject.pointer, streamParamValue, groupNameParamValue); } native private double getLoadingOrder_void(long pNativeObject); /** * 获得文件的下载顺序 * @param */ public double getLoadingOrder() { double returnValue = getLoadingOrder_void(this.nativeObject.pointer); return returnValue; } native private double getLoadingOrder_void_NoVirtual(long pNativeObject); protected double getLoadingOrder_NoVirtual() { double returnValue = getLoadingOrder_void_NoVirtual(this.nativeObject.pointer); return returnValue; } ///typedef EarthView::World::Core::CMapIterator<EarthView::World::Graphic::CParticleSystemManager::ParticleAffectorFactoryMap> EarthView::World::Graphic::CParticleSystemManager::ParticleAffectorFactoryIterator; public static class StringParticleAffectorFactoryPair extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::StringParticleAffectorFactoryPair", new StringParticleAffectorFactoryPairClassFactory()); } /** * 默认构造函数 * @param */ public StringParticleAffectorFactoryPair() { super(CreatedWhenConstruct.CWC_NotToCreate); Create("StringParticleAffectorFactoryPair", null); } native private String get_first_void(long pNativeObject); public String get_first() { String jniValue = get_first_void(this.nativeObject.pointer); return jniValue; } native private void set_first_EVString (long pNativeObject, String value); public void set_first(String first) { String firstParamValue = first; set_first_EVString(this.nativeObject.pointer, firstParamValue); } native private long get_second_void(long pNativeObject); public com.earthview.world.graphic.ParticleAffectorFactory get_second() { long jniValue = get_second_void(this.nativeObject.pointer); if(jniValue == 0L) { return null; } com.earthview.world.graphic.ParticleAffectorFactory __returnValue = new com.earthview.world.graphic.ParticleAffectorFactory(CreatedWhenConstruct.CWC_NotToCreate, "CParticleAffectorFactory"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(jniValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleAffectorFactory)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleAffectorFactory"); } return __returnValue; } native private void set_second_CParticleAffectorFactory (long pNativeObject, long value); public void set_second(com.earthview.world.graphic.ParticleAffectorFactory second) { long secondParamValue = (second == null ? 0L : second.nativeObject.pointer); set_second_CParticleAffectorFactory(this.nativeObject.pointer, secondParamValue); } public StringParticleAffectorFactoryPair(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public StringParticleAffectorFactoryPair(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static StringParticleAffectorFactoryPair fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } StringParticleAffectorFactoryPair obj = null; if(baseObj instanceof StringParticleAffectorFactoryPair) { obj = (StringParticleAffectorFactoryPair)baseObj; } else { obj = new StringParticleAffectorFactoryPair(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "StringParticleAffectorFactoryPair"); obj.increaseCast(); } return obj; } } public static class StringParticleAffectorFactoryPairClassFactory implements IClassFactory { public BaseObject create() { StringParticleAffectorFactoryPair emptyInstance = new StringParticleAffectorFactoryPair(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } public static class ParticleAffectorFactoryIterator extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::ParticleAffectorFactoryIterator", new ParticleAffectorFactoryIteratorClassFactory()); } /** * 复制构造函数 * @param other 其它迭代器 */ public ParticleAffectorFactoryIterator(com.earthview.world.graphic.ParticleSystemManager.ParticleAffectorFactoryIterator other) { super(CreatedWhenConstruct.CWC_NotToCreate); NameValuePairList list = new NameValuePairList(); BasePointer otherPtr = new BasePointer(other); list.add("other", otherPtr.get()); Create("ParticleAffectorFactoryIterator", list); } /** * 构造函数 * @param rhs 迭代器对应集合 */ public ParticleAffectorFactoryIterator(com.earthview.world.graphic.ParticleSystemManager.ParticleAffectorFactoryMap lst) { super(CreatedWhenConstruct.CWC_NotToCreate); NameValuePairList list = new NameValuePairList(); BasePointer lstPtr = new BasePointer(lst); list.add("lst", lstPtr.get()); Create("ParticleAffectorFactoryIterator", list); } native private boolean hasMoreElements_void(long pNativeObject); /** * 判断迭代器是否到达容器末尾 * @param * @return 是返回true,否则false */ public boolean hasMoreElements() { boolean returnValue = hasMoreElements_void(this.nativeObject.pointer); return returnValue; } native private void moveNext_void(long pNativeObject); /** * 迭代器位置后移 * @param */ public void moveNext() { moveNext_void(this.nativeObject.pointer); } native private String nextKey_void(long pNativeObject); /** * 返回容器当前的键 * @param * @return 键 */ public String nextKey() { String returnValue = nextKey_void(this.nativeObject.pointer); return returnValue; } native private long nextValue_void(long pNativeObject); /** * 返回容器当前的值 * @param * @return 值 */ public com.earthview.world.graphic.ParticleAffectorFactory nextValue() { long returnValue = nextValue_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleAffectorFactory __returnValue = new com.earthview.world.graphic.ParticleAffectorFactory(CreatedWhenConstruct.CWC_NotToCreate, "CParticleAffectorFactory"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleAffectorFactory)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleAffectorFactory"); } return __returnValue; } native private long nextValuePtr_void(long pNativeObject); /** * 返回容器当前的值指针 * @param * @return 值地址 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleAffectorFactory> nextValuePtr() { long returnValue = nextValuePtr_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } NativeObjectPointer<com.earthview.world.graphic.ParticleAffectorFactory> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleAffectorFactory>(new InstancePointer(returnValue)); return __returnValue; } native private long next_void(long pNativeObject); /** * 返回容器当前的值 * @param * @return 值 */ public com.earthview.world.graphic.ParticleAffectorFactory next() { long returnValue = next_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleAffectorFactory __returnValue = new com.earthview.world.graphic.ParticleAffectorFactory(CreatedWhenConstruct.CWC_NotToCreate, "CParticleAffectorFactory"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleAffectorFactory)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleAffectorFactory"); } return __returnValue; } native private long getBegin_void(long pNativeObject); /** * 返回容器首键值对 * @param * @return 首键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair getBegin() { long returnValue = getBegin_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleAffectorFactoryPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleAffectorFactoryPair"); } return __returnValue; } native private long getEnd_void(long pNativeObject); /** * 返回容器尾键值对 * @param * @return 尾键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair getEnd() { long returnValue = getEnd_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleAffectorFactoryPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleAffectorFactoryPair"); } return __returnValue; } native private long getCurrent_void(long pNativeObject); /** * 返回容器当前键值对 * @param * @return 当前键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair getCurrent() { long returnValue = getCurrent_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleAffectorFactoryPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleAffectorFactoryPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleAffectorFactoryPair"); } return __returnValue; } public ParticleAffectorFactoryIterator(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public ParticleAffectorFactoryIterator(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static ParticleAffectorFactoryIterator fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } ParticleAffectorFactoryIterator obj = null; if(baseObj instanceof ParticleAffectorFactoryIterator) { obj = (ParticleAffectorFactoryIterator)baseObj; } else { obj = new ParticleAffectorFactoryIterator(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "ParticleAffectorFactoryIterator"); obj.increaseCast(); } return obj; } } public static class ParticleAffectorFactoryIteratorClassFactory implements IClassFactory { public BaseObject create() { ParticleAffectorFactoryIterator emptyInstance = new ParticleAffectorFactoryIterator(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } ///typedef EarthView::World::Core::CMapIterator<EarthView::World::Graphic::CParticleSystemManager::ParticleEmitterFactoryMap> EarthView::World::Graphic::CParticleSystemManager::ParticleEmitterFactoryIterator; public static class StringParticleEmitterFactoryPair extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::StringParticleEmitterFactoryPair", new StringParticleEmitterFactoryPairClassFactory()); } /** * 默认构造函数 * @param */ public StringParticleEmitterFactoryPair() { super(CreatedWhenConstruct.CWC_NotToCreate); Create("StringParticleEmitterFactoryPair", null); } native private String get_first_void(long pNativeObject); public String get_first() { String jniValue = get_first_void(this.nativeObject.pointer); return jniValue; } native private void set_first_EVString (long pNativeObject, String value); public void set_first(String first) { String firstParamValue = first; set_first_EVString(this.nativeObject.pointer, firstParamValue); } native private long get_second_void(long pNativeObject); public com.earthview.world.graphic.ParticleEmitterFactory get_second() { long jniValue = get_second_void(this.nativeObject.pointer); if(jniValue == 0L) { return null; } com.earthview.world.graphic.ParticleEmitterFactory __returnValue = new com.earthview.world.graphic.ParticleEmitterFactory(CreatedWhenConstruct.CWC_NotToCreate, "CParticleEmitterFactory"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(jniValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleEmitterFactory)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleEmitterFactory"); } return __returnValue; } native private void set_second_CParticleEmitterFactory (long pNativeObject, long value); public void set_second(com.earthview.world.graphic.ParticleEmitterFactory second) { long secondParamValue = (second == null ? 0L : second.nativeObject.pointer); set_second_CParticleEmitterFactory(this.nativeObject.pointer, secondParamValue); } public StringParticleEmitterFactoryPair(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public StringParticleEmitterFactoryPair(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static StringParticleEmitterFactoryPair fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } StringParticleEmitterFactoryPair obj = null; if(baseObj instanceof StringParticleEmitterFactoryPair) { obj = (StringParticleEmitterFactoryPair)baseObj; } else { obj = new StringParticleEmitterFactoryPair(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "StringParticleEmitterFactoryPair"); obj.increaseCast(); } return obj; } } public static class StringParticleEmitterFactoryPairClassFactory implements IClassFactory { public BaseObject create() { StringParticleEmitterFactoryPair emptyInstance = new StringParticleEmitterFactoryPair(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } public static class ParticleEmitterFactoryIterator extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::ParticleEmitterFactoryIterator", new ParticleEmitterFactoryIteratorClassFactory()); } /** * 复制构造函数 * @param other 其它迭代器 */ public ParticleEmitterFactoryIterator(com.earthview.world.graphic.ParticleSystemManager.ParticleEmitterFactoryIterator other) { super(CreatedWhenConstruct.CWC_NotToCreate); NameValuePairList list = new NameValuePairList(); BasePointer otherPtr = new BasePointer(other); list.add("other", otherPtr.get()); Create("ParticleEmitterFactoryIterator", list); } /** * 构造函数 * @param rhs 迭代器对应集合 */ public ParticleEmitterFactoryIterator(com.earthview.world.graphic.ParticleSystemManager.ParticleEmitterFactoryMap lst) { super(CreatedWhenConstruct.CWC_NotToCreate); NameValuePairList list = new NameValuePairList(); BasePointer lstPtr = new BasePointer(lst); list.add("lst", lstPtr.get()); Create("ParticleEmitterFactoryIterator", list); } native private boolean hasMoreElements_void(long pNativeObject); /** * 判断迭代器是否到达容器末尾 * @param * @return 是返回true,否则false */ public boolean hasMoreElements() { boolean returnValue = hasMoreElements_void(this.nativeObject.pointer); return returnValue; } native private void moveNext_void(long pNativeObject); /** * 迭代器位置后移 * @param */ public void moveNext() { moveNext_void(this.nativeObject.pointer); } native private String nextKey_void(long pNativeObject); /** * 返回容器当前的键 * @param * @return 键 */ public String nextKey() { String returnValue = nextKey_void(this.nativeObject.pointer); return returnValue; } native private long nextValue_void(long pNativeObject); /** * 返回容器当前的值 * @param * @return 值 */ public com.earthview.world.graphic.ParticleEmitterFactory nextValue() { long returnValue = nextValue_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleEmitterFactory __returnValue = new com.earthview.world.graphic.ParticleEmitterFactory(CreatedWhenConstruct.CWC_NotToCreate, "CParticleEmitterFactory"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleEmitterFactory)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleEmitterFactory"); } return __returnValue; } native private long nextValuePtr_void(long pNativeObject); /** * 返回容器当前的值指针 * @param * @return 值地址 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleEmitterFactory> nextValuePtr() { long returnValue = nextValuePtr_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } NativeObjectPointer<com.earthview.world.graphic.ParticleEmitterFactory> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleEmitterFactory>(new InstancePointer(returnValue)); return __returnValue; } native private long next_void(long pNativeObject); /** * 返回容器当前的值 * @param * @return 值 */ public com.earthview.world.graphic.ParticleEmitterFactory next() { long returnValue = next_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleEmitterFactory __returnValue = new com.earthview.world.graphic.ParticleEmitterFactory(CreatedWhenConstruct.CWC_NotToCreate, "CParticleEmitterFactory"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleEmitterFactory)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleEmitterFactory"); } return __returnValue; } native private long getBegin_void(long pNativeObject); /** * 返回容器首键值对 * @param * @return 首键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair getBegin() { long returnValue = getBegin_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleEmitterFactoryPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleEmitterFactoryPair"); } return __returnValue; } native private long getEnd_void(long pNativeObject); /** * 返回容器尾键值对 * @param * @return 尾键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair getEnd() { long returnValue = getEnd_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleEmitterFactoryPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleEmitterFactoryPair"); } return __returnValue; } native private long getCurrent_void(long pNativeObject); /** * 返回容器当前键值对 * @param * @return 当前键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair getCurrent() { long returnValue = getCurrent_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleEmitterFactoryPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleEmitterFactoryPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleEmitterFactoryPair"); } return __returnValue; } public ParticleEmitterFactoryIterator(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public ParticleEmitterFactoryIterator(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static ParticleEmitterFactoryIterator fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } ParticleEmitterFactoryIterator obj = null; if(baseObj instanceof ParticleEmitterFactoryIterator) { obj = (ParticleEmitterFactoryIterator)baseObj; } else { obj = new ParticleEmitterFactoryIterator(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "ParticleEmitterFactoryIterator"); obj.increaseCast(); } return obj; } } public static class ParticleEmitterFactoryIteratorClassFactory implements IClassFactory { public BaseObject create() { ParticleEmitterFactoryIterator emptyInstance = new ParticleEmitterFactoryIterator(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } ///typedef EarthView::World::Core::CMapIterator<EarthView::World::Graphic::CParticleSystemManager::ParticleSystemRendererFactoryMap> EarthView::World::Graphic::CParticleSystemManager::ParticleRendererFactoryIterator; public static class StringParticleSystemRendererFactoryPair extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::StringParticleSystemRendererFactoryPair", new StringParticleSystemRendererFactoryPairClassFactory()); } /** * 默认构造函数 * @param */ public StringParticleSystemRendererFactoryPair() { super(CreatedWhenConstruct.CWC_NotToCreate); Create("StringParticleSystemRendererFactoryPair", null); } native private String get_first_void(long pNativeObject); public String get_first() { String jniValue = get_first_void(this.nativeObject.pointer); return jniValue; } native private void set_first_EVString (long pNativeObject, String value); public void set_first(String first) { String firstParamValue = first; set_first_EVString(this.nativeObject.pointer, firstParamValue); } native private long get_second_void(long pNativeObject); public com.earthview.world.graphic.ParticleSystemRendererFactory get_second() { long jniValue = get_second_void(this.nativeObject.pointer); if(jniValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystemRendererFactory __returnValue = new com.earthview.world.graphic.ParticleSystemRendererFactory(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystemRendererFactory"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(jniValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemRendererFactory)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystemRendererFactory"); } return __returnValue; } native private void set_second_CParticleSystemRendererFactory (long pNativeObject, long value); public void set_second(com.earthview.world.graphic.ParticleSystemRendererFactory second) { long secondParamValue = (second == null ? 0L : second.nativeObject.pointer); set_second_CParticleSystemRendererFactory(this.nativeObject.pointer, secondParamValue); } public StringParticleSystemRendererFactoryPair(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public StringParticleSystemRendererFactoryPair(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static StringParticleSystemRendererFactoryPair fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } StringParticleSystemRendererFactoryPair obj = null; if(baseObj instanceof StringParticleSystemRendererFactoryPair) { obj = (StringParticleSystemRendererFactoryPair)baseObj; } else { obj = new StringParticleSystemRendererFactoryPair(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "StringParticleSystemRendererFactoryPair"); obj.increaseCast(); } return obj; } } public static class StringParticleSystemRendererFactoryPairClassFactory implements IClassFactory { public BaseObject create() { StringParticleSystemRendererFactoryPair emptyInstance = new StringParticleSystemRendererFactoryPair(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } public static class ParticleRendererFactoryIterator extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::ParticleRendererFactoryIterator", new ParticleRendererFactoryIteratorClassFactory()); } /** * 复制构造函数 * @param other 其它迭代器 */ public ParticleRendererFactoryIterator(com.earthview.world.graphic.ParticleSystemManager.ParticleRendererFactoryIterator other) { super(CreatedWhenConstruct.CWC_NotToCreate); NameValuePairList list = new NameValuePairList(); BasePointer otherPtr = new BasePointer(other); list.add("other", otherPtr.get()); Create("ParticleRendererFactoryIterator", list); } /** * 构造函数 * @param rhs 迭代器对应集合 */ public ParticleRendererFactoryIterator(com.earthview.world.graphic.ParticleSystemManager.ParticleSystemRendererFactoryMap lst) { super(CreatedWhenConstruct.CWC_NotToCreate); NameValuePairList list = new NameValuePairList(); BasePointer lstPtr = new BasePointer(lst); list.add("lst", lstPtr.get()); Create("ParticleRendererFactoryIterator", list); } native private boolean hasMoreElements_void(long pNativeObject); /** * 判断迭代器是否到达容器末尾 * @param * @return 是返回true,否则false */ public boolean hasMoreElements() { boolean returnValue = hasMoreElements_void(this.nativeObject.pointer); return returnValue; } native private void moveNext_void(long pNativeObject); /** * 迭代器位置后移 * @param */ public void moveNext() { moveNext_void(this.nativeObject.pointer); } native private String nextKey_void(long pNativeObject); /** * 返回容器当前的键 * @param * @return 键 */ public String nextKey() { String returnValue = nextKey_void(this.nativeObject.pointer); return returnValue; } native private long nextValue_void(long pNativeObject); /** * 返回容器当前的值 * @param * @return 值 */ public com.earthview.world.graphic.ParticleSystemRendererFactory nextValue() { long returnValue = nextValue_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystemRendererFactory __returnValue = new com.earthview.world.graphic.ParticleSystemRendererFactory(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystemRendererFactory"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemRendererFactory)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystemRendererFactory"); } return __returnValue; } native private long nextValuePtr_void(long pNativeObject); /** * 返回容器当前的值指针 * @param * @return 值地址 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleSystemRendererFactory> nextValuePtr() { long returnValue = nextValuePtr_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } NativeObjectPointer<com.earthview.world.graphic.ParticleSystemRendererFactory> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleSystemRendererFactory>(new InstancePointer(returnValue)); return __returnValue; } native private long next_void(long pNativeObject); /** * 返回容器当前的值 * @param * @return 值 */ public com.earthview.world.graphic.ParticleSystemRendererFactory next() { long returnValue = next_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystemRendererFactory __returnValue = new com.earthview.world.graphic.ParticleSystemRendererFactory(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystemRendererFactory"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemRendererFactory)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystemRendererFactory"); } return __returnValue; } native private long getBegin_void(long pNativeObject); /** * 返回容器首键值对 * @param * @return 首键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair getBegin() { long returnValue = getBegin_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleSystemRendererFactoryPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleSystemRendererFactoryPair"); } return __returnValue; } native private long getEnd_void(long pNativeObject); /** * 返回容器尾键值对 * @param * @return 尾键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair getEnd() { long returnValue = getEnd_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleSystemRendererFactoryPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleSystemRendererFactoryPair"); } return __returnValue; } native private long getCurrent_void(long pNativeObject); /** * 返回容器当前键值对 * @param * @return 当前键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair getCurrent() { long returnValue = getCurrent_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleSystemRendererFactoryPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleSystemRendererFactoryPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleSystemRendererFactoryPair"); } return __returnValue; } public ParticleRendererFactoryIterator(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public ParticleRendererFactoryIterator(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static ParticleRendererFactoryIterator fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } ParticleRendererFactoryIterator obj = null; if(baseObj instanceof ParticleRendererFactoryIterator) { obj = (ParticleRendererFactoryIterator)baseObj; } else { obj = new ParticleRendererFactoryIterator(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "ParticleRendererFactoryIterator"); obj.increaseCast(); } return obj; } } public static class ParticleRendererFactoryIteratorClassFactory implements IClassFactory { public BaseObject create() { ParticleRendererFactoryIterator emptyInstance = new ParticleRendererFactoryIterator(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } native private long getAffectorFactoryIterator_void(long pNativeObject); /** * 获得效果器工厂的一个迭代器 * @param * @return 迭代器 */ public com.earthview.world.graphic.ParticleSystemManager.ParticleAffectorFactoryIterator getAffectorFactoryIterator() { long returnValue = getAffectorFactoryIterator_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.ParticleAffectorFactoryIterator __returnValue = new com.earthview.world.graphic.ParticleSystemManager.ParticleAffectorFactoryIterator(CreatedWhenConstruct.CWC_NotToCreate); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.bindNativeObject(__instancePointer, "ParticleAffectorFactoryIterator"); __returnValue.createNativeObjectPointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.ParticleAffectorFactoryIterator)__returnValueClassFactory.create(); __returnValue.bindNativeObject(__instancePointer, "ParticleAffectorFactoryIterator"); } return __returnValue; } native private long getEmitterFactoryIterator_void(long pNativeObject); /** * 获得发射器工厂的一个迭代器 * @param * @return 迭代器 */ public com.earthview.world.graphic.ParticleSystemManager.ParticleEmitterFactoryIterator getEmitterFactoryIterator() { long returnValue = getEmitterFactoryIterator_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.ParticleEmitterFactoryIterator __returnValue = new com.earthview.world.graphic.ParticleSystemManager.ParticleEmitterFactoryIterator(CreatedWhenConstruct.CWC_NotToCreate); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.bindNativeObject(__instancePointer, "ParticleEmitterFactoryIterator"); __returnValue.createNativeObjectPointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.ParticleEmitterFactoryIterator)__returnValueClassFactory.create(); __returnValue.bindNativeObject(__instancePointer, "ParticleEmitterFactoryIterator"); } return __returnValue; } native private long getRendererFactoryIterator_void(long pNativeObject); /** * 获得渲染器工厂的一个迭代器 * @param * @return 迭代器 */ public com.earthview.world.graphic.ParticleSystemManager.ParticleRendererFactoryIterator getRendererFactoryIterator() { long returnValue = getRendererFactoryIterator_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.ParticleRendererFactoryIterator __returnValue = new com.earthview.world.graphic.ParticleSystemManager.ParticleRendererFactoryIterator(CreatedWhenConstruct.CWC_NotToCreate); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.bindNativeObject(__instancePointer, "ParticleRendererFactoryIterator"); __returnValue.createNativeObjectPointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.ParticleRendererFactoryIterator)__returnValueClassFactory.create(); __returnValue.bindNativeObject(__instancePointer, "ParticleRendererFactoryIterator"); } return __returnValue; } /// typedef EarthView::World::Core::CMapIterator<EarthView::World::Graphic::CParticleSystemManager::ParticleTemplateMap> EarthView::World::Graphic::CParticleSystemManager::ParticleSystemTemplateIterator; public static class StringParticleTemplateMapPair extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::StringParticleTemplateMapPair", new StringParticleTemplateMapPairClassFactory()); } /** * 默认构造函数 * @param */ public StringParticleTemplateMapPair() { super(CreatedWhenConstruct.CWC_NotToCreate); Create("StringParticleTemplateMapPair", null); } native private String get_first_void(long pNativeObject); public String get_first() { String jniValue = get_first_void(this.nativeObject.pointer); return jniValue; } native private void set_first_EVString (long pNativeObject, String value); public void set_first(String first) { String firstParamValue = first; set_first_EVString(this.nativeObject.pointer, firstParamValue); } native private long get_second_void(long pNativeObject); public com.earthview.world.graphic.ParticleSystem get_second() { long jniValue = get_second_void(this.nativeObject.pointer); if(jniValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystem __returnValue = new com.earthview.world.graphic.ParticleSystem(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystem"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(jniValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystem)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystem"); } return __returnValue; } native private void set_second_CParticleSystem (long pNativeObject, long value); public void set_second(com.earthview.world.graphic.ParticleSystem second) { long secondParamValue = (second == null ? 0L : second.nativeObject.pointer); set_second_CParticleSystem(this.nativeObject.pointer, secondParamValue); } public StringParticleTemplateMapPair(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public StringParticleTemplateMapPair(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static StringParticleTemplateMapPair fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } StringParticleTemplateMapPair obj = null; if(baseObj instanceof StringParticleTemplateMapPair) { obj = (StringParticleTemplateMapPair)baseObj; } else { obj = new StringParticleTemplateMapPair(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "StringParticleTemplateMapPair"); obj.increaseCast(); } return obj; } } public static class StringParticleTemplateMapPairClassFactory implements IClassFactory { public BaseObject create() { StringParticleTemplateMapPair emptyInstance = new StringParticleTemplateMapPair(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } public static class ParticleSystemTemplateIterator extends com.earthview.world.core.BaseObject { static { GlobalClassFactoryMap.put("EarthView::World::Graphic::CParticleSystemManager::ParticleSystemTemplateIterator", new ParticleSystemTemplateIteratorClassFactory()); } /** * 复制构造函数 * @param other 其它迭代器 */ public ParticleSystemTemplateIterator(com.earthview.world.graphic.ParticleSystemManager.ParticleSystemTemplateIterator other) { super(CreatedWhenConstruct.CWC_NotToCreate); NameValuePairList list = new NameValuePairList(); BasePointer otherPtr = new BasePointer(other); list.add("other", otherPtr.get()); Create("ParticleSystemTemplateIterator", list); } /** * 构造函数 * @param rhs 迭代器对应集合 */ public ParticleSystemTemplateIterator(com.earthview.world.graphic.ParticleSystemManager.ParticleTemplateMap lst) { super(CreatedWhenConstruct.CWC_NotToCreate); NameValuePairList list = new NameValuePairList(); BasePointer lstPtr = new BasePointer(lst); list.add("lst", lstPtr.get()); Create("ParticleSystemTemplateIterator", list); } native private boolean hasMoreElements_void(long pNativeObject); /** * 判断迭代器是否到达容器末尾 * @param * @return 是返回true,否则false */ public boolean hasMoreElements() { boolean returnValue = hasMoreElements_void(this.nativeObject.pointer); return returnValue; } native private void moveNext_void(long pNativeObject); /** * 迭代器位置后移 * @param */ public void moveNext() { moveNext_void(this.nativeObject.pointer); } native private String nextKey_void(long pNativeObject); /** * 返回容器当前的键 * @param * @return 键 */ public String nextKey() { String returnValue = nextKey_void(this.nativeObject.pointer); return returnValue; } native private long nextValue_void(long pNativeObject); /** * 返回容器当前的值 * @param * @return 值 */ public com.earthview.world.graphic.ParticleSystem nextValue() { long returnValue = nextValue_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystem __returnValue = new com.earthview.world.graphic.ParticleSystem(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystem"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystem)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystem"); } return __returnValue; } native private long nextValuePtr_void(long pNativeObject); /** * 返回容器当前的值指针 * @param * @return 值地址 */ public NativeObjectPointer<com.earthview.world.graphic.ParticleSystem> nextValuePtr() { long returnValue = nextValuePtr_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } NativeObjectPointer<com.earthview.world.graphic.ParticleSystem> __returnValue = new NativeObjectPointer<com.earthview.world.graphic.ParticleSystem>(new InstancePointer(returnValue)); return __returnValue; } native private long next_void(long pNativeObject); /** * 返回容器当前的值 * @param * @return 值 */ public com.earthview.world.graphic.ParticleSystem next() { long returnValue = next_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystem __returnValue = new com.earthview.world.graphic.ParticleSystem(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystem"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystem)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystem"); } return __returnValue; } native private long getBegin_void(long pNativeObject); /** * 返回容器首键值对 * @param * @return 首键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair getBegin() { long returnValue = getBegin_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleTemplateMapPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleTemplateMapPair"); } return __returnValue; } native private long getEnd_void(long pNativeObject); /** * 返回容器尾键值对 * @param * @return 尾键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair getEnd() { long returnValue = getEnd_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleTemplateMapPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleTemplateMapPair"); } return __returnValue; } native private long getCurrent_void(long pNativeObject); /** * 返回容器当前键值对 * @param * @return 当前键值对 */ public com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair getCurrent() { long returnValue = getCurrent_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair __returnValue = new com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair(CreatedWhenConstruct.CWC_NotToCreate, "StringParticleTemplateMapPair"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.StringParticleTemplateMapPair)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "StringParticleTemplateMapPair"); } return __returnValue; } public ParticleSystemTemplateIterator(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public ParticleSystemTemplateIterator(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } public static ParticleSystemTemplateIterator fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } ParticleSystemTemplateIterator obj = null; if(baseObj instanceof ParticleSystemTemplateIterator) { obj = (ParticleSystemTemplateIterator)baseObj; } else { obj = new ParticleSystemTemplateIterator(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "ParticleSystemTemplateIterator"); obj.increaseCast(); } return obj; } } public static class ParticleSystemTemplateIteratorClassFactory implements IClassFactory { public BaseObject create() { ParticleSystemTemplateIterator emptyInstance = new ParticleSystemTemplateIterator(CreatedWhenConstruct.CWC_NotToCreate); return emptyInstance; } } native private long getTemplateIterator_void(long pNativeObject); /** * 获得粒子系统模板迭代器 * @param */ public com.earthview.world.graphic.ParticleSystemManager.ParticleSystemTemplateIterator getTemplateIterator() { long returnValue = getTemplateIterator_void(this.nativeObject.pointer); com.earthview.world.graphic.ParticleSystemManager.ParticleSystemTemplateIterator __returnValue = new com.earthview.world.graphic.ParticleSystemManager.ParticleSystemTemplateIterator(CreatedWhenConstruct.CWC_NotToCreate); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.bindNativeObject(__instancePointer, "ParticleSystemTemplateIterator"); __returnValue.createNativeObjectPointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager.ParticleSystemTemplateIterator)__returnValueClassFactory.create(); __returnValue.bindNativeObject(__instancePointer, "ParticleSystemTemplateIterator"); } return __returnValue; } native private long _getFactory_void(long pNativeObject); /** * 获得EarthView::World::Graphic::CParticleSystemFactory类的实例 * @param */ public com.earthview.world.graphic.ParticleSystemFactory _getFactory() { long returnValue = _getFactory_void(this.nativeObject.pointer); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystemFactory __returnValue = new com.earthview.world.graphic.ParticleSystemFactory(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystemFactory"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemFactory)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystemFactory"); } return __returnValue; } native private static long getSingleton_void(); public static com.earthview.world.graphic.ParticleSystemManager getSingleton() { long returnValue = getSingleton_void(); com.earthview.world.graphic.ParticleSystemManager __returnValue = new com.earthview.world.graphic.ParticleSystemManager(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystemManager"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystemManager"); } return __returnValue; } native private static long getSingletonPtr_void(); public static com.earthview.world.graphic.ParticleSystemManager getSingletonPtr() { long returnValue = getSingletonPtr_void(); if(returnValue == 0L) { return null; } com.earthview.world.graphic.ParticleSystemManager __returnValue = new com.earthview.world.graphic.ParticleSystemManager(CreatedWhenConstruct.CWC_NotToCreate, "CParticleSystemManager"); __returnValue.setDelegate(true); InstancePointer __instancePointer = new InstancePointer(returnValue); __returnValue.setInstancePointer(__instancePointer); IClassFactory __returnValueClassFactory = GlobalClassFactoryMap.get(__returnValue.getCppInstanceTypeName()); if (__returnValueClassFactory != null) { __returnValue.setDelegate(true); __returnValue = (com.earthview.world.graphic.ParticleSystemManager)__returnValueClassFactory.create(); __returnValue.setDelegate(true); __returnValue.bindNativeObject(__instancePointer, "CParticleSystemManager"); } return __returnValue; } public ParticleSystemManager(CreatedWhenConstruct cwc) { super(CreatedWhenConstruct.CWC_NotToCreate); } public ParticleSystemManager(CreatedWhenConstruct cwc, String classNameStr) { super(CreatedWhenConstruct.CWC_NotToCreate, classNameStr); } native protected void register_getScriptPatterns_void(long pNativeObject, String method); native protected void register_parseScript_DataStreamPtr_EVString(long pNativeObject, String method); native protected void register_getLoadingOrder_void(long pNativeObject, String method); public void registerCallback(){ if (!this.nativeObject.equals(InstancePointer.ZERO)){ this.register_getScriptPatterns_void(this.nativeObject.pointer, "getScriptPatterns_void_callback"); this.register_parseScript_DataStreamPtr_EVString(this.nativeObject.pointer, "parseScript_DataStreamPtr_EVString_callback"); this.register_getLoadingOrder_void(this.nativeObject.pointer, "getLoadingOrder_void_callback"); } } public static ParticleSystemManager fromBaseObject(BaseObject baseObj) { if (baseObj == null || InstancePointer.ZERO.equals(baseObj.nativeObject)) { return null; } ParticleSystemManager obj = null; if(baseObj instanceof ParticleSystemManager) { obj = (ParticleSystemManager)baseObj; } else { obj = new ParticleSystemManager(CreatedWhenConstruct.CWC_NotToCreate); obj.bindNativeObject(baseObj.nativeObject, "CParticleSystemManager"); obj.increaseCast(); } return obj; } }
PHP
UTF-8
572
2.765625
3
[ "CC-BY-3.0" ]
permissive
<?php $username = $_GET["username"]; $greeting = $_GET["greeting"]; ?> <!DOCTYPE html> <head> </head> <body> <!-- TODO replace "false" below with a condition to check if either value is empty (same condition as last time) --> <?php if(empty($username) || empty($greeting)): ?> <p>Hey - you've got to fill the whole form out!</p> <p><a rel="stylesheet" href="https://ide50-eniebauer.cs50.io/hello-form-2.php" type="text/css" />Go back</a></p> <?php else: ?> <?php print("{$greeting}, {$username}!"); ?> <?php endif ?> </body>
Python
UTF-8
552
4.03125
4
[]
no_license
# Luan Scolfaro Amorim Carneiro # UNIFIP - Patos # 13 de março de 2020 # Questão 10 - Faça um Programa que pergunte em que turno você estuda. Peça para digitar M-matutino ou V-Vespertino ou N- Noturno. Imprima a mensagem "Bom Dia!", "Boa Tarde!" ou "Boa Noite!" ou "Valor Inválido!", conforme o caso. turno_estudo = input("Qual é o turno que você estuda?(M-Matutino, V-Vespertino e N-Noturno) ") if turno_estudo == "M": print("Bom dia!") elif turno_estudo == "V": print("Boa tarde!") elif turno_estudo == "N": print("Boa noite!") else: print("Valor inválido")
C
SHIFT_JIS
695
2.6875
3
[ "Apache-2.0", "MIT" ]
permissive
#pragma once #include "ev3api.h" extern void init_buff(int size, char *buff, char val); extern int limit_int(int value, int min, int max); /** * @macro * obt@[̏sB * obt@[̃CfbNXϐA1Ɏw肷B * valŁAl(l)w肷B */ #define INIT_BUF_VAL(size, buff, val) init_buff(size, buff, val) /** * @macro * obt@[̏sB * obt@[̃CfbNXϐA1Ɏw肷B * obt@[́ASāu0vŏB */ #define INIT_BUF(size, buff) INIT_BUF_VAL(size, buff, 0)
Python
UTF-8
4,600
2.65625
3
[]
no_license
# -*- coding: utf-8 -*- # Created on Tue Jun 19 11:29:28 2018 """ 这是阿里巴巴广告算法打算的一个model的baseline版本 """ # 加载需要用到的模块 import math import numpy as np import pandas as pd from scipy.optimize import minimize from sklearn.cross_validation import train_test_split #from sklearn.linear_model import LogisticRegressionCV from sklearn.metrics import accuracy_score, confusion_matrix # 加载训练集 df = pd.read_csv(r'C:\Users\Administrator\Desktop\ali_ad\OfflineTrain.csv') # 根据是否交易划分数据集 df_0 = df.loc[df['is_trade'] == 0] # 未交易 df_1 = df.loc[df['is_trade'] == 1] # 交易 # 将要选用的特征列 feature_cols = ['item_price_level', 'item_collected_level', 'user_gender_id', 'user_age_level', 'shop_star_level', 'shop_score_service', 'shop_score_delivery', 'shop_score_description', ] # 选取未交易的特征列和标签列 data_x_0 = df_0[feature_cols] data_y_0 = df_0['is_trade'] # 选取交易的特征列和标签列 data_x_1 = df_1[feature_cols] data_y_1 = df_1['is_trade'] # 分别从未交易数据集和交易数据集分割出训练集和验证集 x_train_0, x_test_0, y_train_0, y_test_0 = train_test_split(data_x_0, data_y_0, test_size = 0.2) # 未交易数据集 x_train_1, x_test_1, y_train_1, y_test_1 = train_test_split(data_x_1, data_y_1, test_size = 0.2) # 交易数据集 # 初始化训练集和验证集 x_train = pd.concat([x_train_0, x_train_1]) y_train = pd.concat([y_train_0, y_train_1]) x_test = pd.concat([x_test_0, x_test_1]) y_test = pd.concat([y_test_0, y_test_1]) # 对交易样本进行过采样 for _ in range(20): x_train = pd.concat([x_train, x_train_1]) y_train = pd.concat([y_train, y_train_1]) x_test = pd.concat([x_test, x_test_1]) y_test = pd.concat([y_test, y_test_1]) X = np.c_[x_train] y = np.c_[y_train] # 使用逻辑回归模型 # 定义sigmoid函数 def sigmoid(z): return(1 / (1 + np.exp(-z))) #定义损失函数 def costFunction(theta, reg, X, y): m = y.size h = sigmoid(X.dot(theta)) J = -1.0*(1.0/m)*(np.log(h).T.dot(y)+np.log(1-h).T.dot(1-y)) + + (reg/(2.0*m))*np.sum(np.square(theta[1:])) if np.isnan(J[0]): return(np.inf) return J[0] #求解梯度 def gradient(theta, reg, X, y): m = y.size h = sigmoid(X.dot(theta.reshape(-1,1))) grad =(1.0/m)*X.T.dot(h-y) + (reg/m)*np.r_[[[0]],theta[1:].reshape(-1,1)] return(grad.flatten()) # 定义预测函数 def predict(X, threshold =0.5): p = sigmoid(X.dot(res.x.T)) # 预测概率 clf =(p >= threshold) # 以0.5为基准判断是否交易 return(p, clf.astype('int')) reg = 10 # 正则项惩罚系数 initial_theta = np.zeros(X.shape[1]) cost = costFunction(initial_theta, reg, X, y) grad = gradient(initial_theta, reg, X, y) print('\n=============模型训练开始============\n') print('初始化的Cost: \n', cost) print('初始化的Grad: \n', grad) # 最小化损失函数 res = minimize(costFunction, initial_theta, args=(reg, X, y), jac=gradient, options={'maxiter':400}) print('\n=============模型训练完成============\n') print('最终收敛的Cost: \n', res.fun) print('最终稳定的Grad: \n', res.jac.tolist()) # 对划分的验证集的交易进行预测 y_pred = predict(x_test)[1] # 评价模型标准 score = accuracy_score(y_test, y_pred) # 准确率 score_matrix = confusion_matrix(y_test, y_pred) # 结果混淆矩阵 print('该模型在验证集的预测准确率是:{:.2f}'.format(score)) print('该模型在验证集预测结果混淆矩阵是:\n{}'.format(score_matrix)) print('\n\n=============用模型对测试集预测============\n\n') # 加载测试集 df_test = pd.read_csv(r'C:\Users\Administrator\Desktop\ali_ad\OfflineTest.csv') # 选取特征列并进行预测 data_x = df_test[feature_cols] test_pred_list = predict(data_x)[0].tolist() # 预测的概率列表 test_pred_count = predict(data_x)[1].tolist() # 预测的二分类列表 # 购买概率 p = np.count_nonzero(test_pred_list) / len(test_pred_list) # 对数损失函数log-loss的计算 ll = 0 for i, p in zip(test_pred_count, test_pred_list): ll += -(i * math.log(p) + (1 - i) * math.log(1 - p)) ll = ll / len(test_pred_list) # 对计算结果取均值 print('测试集总人数是:{}\n该模型的损失函数是:{:.2f}'.format(len(test_pred_list),ll)) print('预测会交易的人数将是:{}'.format(np.count_nonzero(test_pred_count)))
PHP
UTF-8
354
2.53125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace FightTheIce\Datatypes\Core\Contracts; interface PseudoStringInterface extends PseudoInterface { public function __toString(): string; public function is_standard_string(): BooleanInterface; public function is_unicode_string(): BooleanInterface; public function resolve(): StringInterface; }
TypeScript
UTF-8
992
2.671875
3
[]
no_license
class Loc { lat: String; lng: String; } export interface Resource { Data: Array<Tree>; } export interface Tree { nome_pop: string; nome_cie: string; familia: string; categoria: string; origem: string; clima: string; luminosidade: string; altura: string; info: string; localidade: string; loc: Array<Number>; } export class TreeModel implements Tree { constructor( public nome_pop: string, public nome_cie: string, public familia: string, public categoria: string, public origem: string, public clima: string, public luminosidade: string, public altura: string, public info: string, public localidade: string, public loc: Array<Number> ) {} clear() { this.nome_pop = ""; this.nome_cie = ""; this.familia = ""; this.categoria = ""; this.clima = ""; this.luminosidade = ""; this.origem = ""; this.altura = ""; this.info = ""; this.localidade = ""; this.loc = []; } }
C
UTF-8
429
3.78125
4
[]
no_license
#include <stdio.h> void conv(int n) { while (n != 0) { printf("%d", n % 2); n /= 2; } } // Условия задания: // Дано натуральное число N. // Выведите его представление в двоичном виде в обратном порядке. int main() { int N; scanf("%d", &N); conv(N); printf("\n"); return 0; }
Shell
UTF-8
1,214
2.546875
3
[]
no_license
# $Id$ # Maintainer: Jan de Groot <jgc@archlinux.org> # Contributor: Alexander Baldeck <alexander@archlinux.org> pkgname=libxcb pkgver=1.9.1 pkgrel=2 pkgdesc="X11 client-side library" arch=('i686' 'x86_64') url="http://xcb.freedesktop.org/" depends=('xcb-proto>=1.8-2' 'libxdmcp' 'libxau') makedepends=('pkgconfig' 'libxslt' 'python') license=('custom') source=($url/dist/$pkgname-$pkgver.tar.bz2 libxcb-1.1-no-pthread-stubs.patch reorder-configure.patch) sha256sums=('d44a5ff4eb0b9569e6f7183b51fdaf6f58da90e7d6bfc36b612d7263f83e362f' '1ec7a6e7dc8639baa6c3fbc61ca8556108fb824598bd6ab5ef1fa50d48d6d310' '3e1adc51246e1f48545c1ab9703219c987685d241f1eab5d912b0840ce8a122a') prepare() { cd "$pkgname-$pkgver" patch -Np1 -i ../libxcb-1.1-no-pthread-stubs.patch # https://bugs.freedesktop.org/show_bug.cgi?id=66413 patch -Np1 -i ../reorder-configure.patch NOCONFIGURE=1 ./autogen.sh } build() { cd "$pkgname-$pkgver" ./configure --prefix=/usr \ --enable-xinput \ --enable-xkb \ --disable-static make } package() { cd "$pkgname-$pkgver" make DESTDIR="$pkgdir" install install -m755 -d "$pkgdir/usr/share/licenses/$pkgname" install -m644 COPYING "$pkgdir/usr/share/licenses/$pkgname" }
Markdown
UTF-8
8,190
2.75
3
[]
no_license
--- description: "Simple Way to Prepare Homemade Rice and vegetable gravy" title: "Simple Way to Prepare Homemade Rice and vegetable gravy" slug: 1669-simple-way-to-prepare-homemade-rice-and-vegetable-gravy date: 2020-12-04T17:28:22.869Z image: https://img-global.cpcdn.com/recipes/db200fd3685d9494/751x532cq70/rice-and-vegetable-gravy-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/db200fd3685d9494/751x532cq70/rice-and-vegetable-gravy-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/db200fd3685d9494/751x532cq70/rice-and-vegetable-gravy-recipe-main-photo.jpg author: Curtis Young ratingvalue: 4 reviewcount: 9858 recipeingredient: - " Rice" - " Vegetables cabbagecarrotgreen beans nd pepperspring onions" - " Red onions and pepper tomatoes" - "cubes Salt seasoning" - " Vegetable oil" - " Plantain" - " Snail" - " Tumeric ginger and curry powders" recipeinstructions: - "Wash rice and parboil, afterwards wash and add a little Tumeric and salt then boil to dry, when water dries up put some sliced vegetables on it and set aside." - "Wash snails and boil with pepper and onions l, salt and seasoning cubes till soft and then fry in hot veg oil and set side" - "Wash and peel plantain, cut into sizes and fry in vegetable oil till golden brown." - "Wash and slice all veggies, Tomatoes and pepper, then put vegetable oil in a pan on medium heat, when hot add red onions and red pepper and stir, then add tomatoes and allow to fry properly then add snails, ginger n curry powders and stir, add salt and cubes allow for about 2mins and add the veggies and stir fry for about 3mins and turn off heat." - "Serve and enjoy meal." categories: - Recipe tags: - rice - and - vegetable katakunci: rice and vegetable nutrition: 198 calories recipecuisine: American preptime: "PT13M" cooktime: "PT60M" recipeyield: "4" recipecategory: Dinner --- ![Rice and vegetable gravy](https://img-global.cpcdn.com/recipes/db200fd3685d9494/751x532cq70/rice-and-vegetable-gravy-recipe-main-photo.jpg) Hey everyone, hope you are having an amazing day today. Today, we're going to make a special dish, rice and vegetable gravy. One of my favorites. This time, I'm gonna make it a little bit tasty. This will be really delicious. Rice and gravy is a staple of Louisiana Creole and Cajun cuisine, , made by deglazing a pan to make brown gravy, simmered with extra seasonings, and served over steamed or boiled rice. Sweet and sour vegetable is a popular Indo Chinese gravy recipe to serve with fried rice or noodles. I simply can not imagine any Indo Chinese restaurant meal without the sweet and. The trick to a perfect gravy is to always have equal amounts of fat (oil or butter) and flour so be sure to cut both equally. Rice and vegetable gravy is one of the most favored of current trending foods in the world. It's easy, it's fast, it tastes yummy. It's enjoyed by millions daily. They're nice and they look fantastic. Rice and vegetable gravy is something that I've loved my whole life. To get started with this recipe, we must first prepare a few components. You can have rice and vegetable gravy using 8 ingredients and 5 steps. Here is how you can achieve that. <!--inarticleads1--> ##### The ingredients needed to make Rice and vegetable gravy: 1. Make ready Rice 1. Make ready Vegetables cabbage,carrot,green beans nd pepper,spring onions 1. Get Red onions and pepper, tomatoes 1. Take cubes Salt, seasoning 1. Take Vegetable oil 1. Prepare Plantain 1. Make ready Snail 1. Prepare Tumeric, ginger and curry powders However vegetable fried rice has always stayed permanent in our choice of menu for Indo Chinese take aways or in restaurants. You can serve veg Chinese fried rice with any Indo Chinese gravy dish. The Best Rice Gravy Recipes on Yummly A healthy, satisfying plant-based side dish or entrée. <!--inarticleads2--> ##### Steps to make Rice and vegetable gravy: 1. Wash rice and parboil, afterwards wash and add a little Tumeric and salt then boil to dry, when water dries up put some sliced vegetables on it and set aside. 1. Wash snails and boil with pepper and onions l, salt and seasoning cubes till soft and then fry in hot veg oil and set side 1. Wash and peel plantain, cut into sizes and fry in vegetable oil till golden brown. 1. Wash and slice all veggies, Tomatoes and pepper, then put vegetable oil in a pan on medium heat, when hot add red onions and red pepper and stir, then add tomatoes and allow to fry properly then add snails, ginger n curry powders and stir, add salt and cubes allow for about 2mins and add the veggies and stir fry for about 3mins and turn off heat. 1. Serve and enjoy meal. The Best Rice Gravy Recipes on Yummly A healthy, satisfying plant-based side dish or entrée. I first tried rice &amp; gravy at the home of Ms Linda Armentor in New Orleans. It&#39;s a traditional Cajun dish, with it&#39;s roots in rural Southern Louisiana, using any kind of cheap meat that requires a slow braise but nowadays more often made with beef and served over that most ubiquitous Louisiana agricultural..like vegetable rice, peas pulao, jeera pulao, carrot rice, paneer pulao, mushroom rice, vegetable pulao How to make Vegetable Gravy (Indian Style). Our family loves Meatballs and Gravy over Rice, made with Better Than Bouillon! Learn How to Improve Your Mood with Food A lot of us think that comfort foods are bad for us and that we ought to stay away from them. If your comfort food is candy or junk food this can be true. Other times, though, comfort foods can be completely nourishing and it's good for you to consume them. A number of foods actually do improve your mood when you consume them. If you are feeling a little bit down and need a happiness pick me up, try some of these. Eggs, you might be surprised to learn, are terrific at battling depression. Just see to it that you do not throw away the egg yolk. The yolk is the most crucial part of the egg in terms of helping you cheer up. Eggs, the yolks in particular, are high in B vitamins. These B vitamins are great for helping to improve your mood. This is because they help improve the function of your neural transmitters, the parts of your brain that affect your mood. Eat an egg and feel happier! Make a trail mixout of various seeds and nuts. Almonds, cashews, peanuts, pumpkin seeds, sunflower seeds, etc are all good for raising your mood. This is because seeds and nuts have lots of magnesium which increases your brain's serotonin levels. Serotonin is a feel-good chemical that dictates to the brain how to feel at any given time. The more serotonin you have, the happier you are going to feel. Not only that but nuts, in particular, are a terrific source of protein. If you want to beat depression, try consuming some cold water fish. Tuna, trout, mackerel, herring and wild salmon are all rich in omega-3 fatty acids and DHA. These are two things that actually help the grey matter in your brain function a lot better. It's the truth: consuming tuna fish sandwiches can really help you battle your depression. Some grains are truly wonderful for repelling bad moods. Quinoa, millet, teff and barley are all actually excellent for helping boost your happiness levels. They help you feel full also which can actually help to make your mood better. Feeling hungry can actually bring you down! These grains can elevate your mood as it's not at all difficult for your body to digest them. They are easier to digest than other foods which helps bring up your blood sugar levels and that, in turn, elevates your mood. Your mood could actually be helped by green tea. You knew green tea had to be included in this article, right? Green tea has a lot of an amino acid referred to as L-theanine. Research has found that this amino acid induces the production of brain waves. This helps focus your mental energy while at the same time making the rest of your body more relaxed. You already knew green tea could help you be healthier. Now you know that green tea can improve your mood also! Now you realize that junk food isn't necessarily what you should eat when you want to help your moods get better. Try several of these instead!
JavaScript
UTF-8
7,434
2.765625
3
[]
no_license
const Room = require('../models/Room'); const Item = require('../models/Item'); module.exports = async() => { const horrorRoom = await Room.create({ name: 'horror' }); await Item.create({ name: 'entrance', room: horrorRoom._id, interactions: { look: 'You suddenly find yourself in darkened, dusty room. Your eyes catch sharp slivers of light cutting through what appears to be a <span class="object">window</span>. You notice it has been hastily boarded up at awkward angles, bent nail heads casting long, disfigured shadows against the sunlight as it makes its way through the cracks between the boards. As your eyes continue to adjust to the light, you begin to make out shapes around you. You notice an old wooden <span class="object">table</span> across from the <span class="object">window</span>. It\'s still very dark, but you observe stuff strewn about it. You can\'t discern what\'s there just yet. Next to the <span class="object">table</span> is a heavy wooden <span class="object">door</span>.', take: 'You can\'t take the room!', use: 'You can\'t use the room, you can only use items in the room.' } }); await Item.create({ name: 'table', room: horrorRoom._id, interactions: { look: 'You see the <span class="object">table</span> in greater detail. The items it holds aloft are in disarray. You see dusty glass <span class="object">jars</span> filled with strange fluids. There are weathered <span class="object">papers</span> strewn about the <span class="object">table</span> covered in scribbled sentences. The words are difficult to make out without looking more closely.', take: 'The <span class="object">table</span> is too heavy, you can\'t take it.', use: 'You can\'t use the <span class="object">table</span>, you can only use items on the <span class="object">table</span>.' } }); await Item.create({ name: 'papers', room: horrorRoom._id, takeable: false, interactions: { look: `<span>You pick a page up and examine it. You can make out dates and what appears to be logs of experiments. You can't make out everything. The author seemed to write aggressively, hurriedly, but there are a few passages that are legible enough to read:<br> <br> * Day 145: The blood samples coagulate and clot, the antidote doesn't appear to be working on infected samples. The vaccine we're working on doesn't show signs of protection against the virus. Infection rates rise daily, and the death count grows higher. The virus is seemingly unavoidable, like it's in the air. With nowhere to bury them, bodies are being piled up along roadsides. Transmission of the virus shows no signs of stopping, but mysteriously the bodies are disappearing. What's happening to them? Where do they go?<br> <br> * Day 411: City officials all over the world are reporting citizens who have seen their loved ones walking the streets AFTER they've succumbed to virus and died. It was just a few cases at first, and we brushed it off as incidents of extreme grief and cabin fever from isolation. But the reports are piling up exponentially, and can't be ignored. I've witnessed it myself. Am I going crazy? I hear things, I see things. I don't want what's outside to get in.<br> <br> You are shaking, too afraid to read on. You look over your shoulder at the boarded up <span class="object">window</span>, your eyes widening. You see the light outside the window shift and find yourself near panicking. Is something out there? You turn to put the <span class="object">paper</span> back and notice a glint of light on brass. It's a <span class="object">key</span>.</span>`, take: 'You have already read the <span class="object">paper</span>, there is nothing else you can do with it. You put it back.', use: 'You have already read the <span class="object">paper</span>, there is nothing else you can do with it. You put it back.' } }); await Item.create({ name: 'jars', room: horrorRoom._id, takeable: false, interactions: { look: 'You pick up the <span class="object">jars</span> one by one and blow the dust off. You examine the contents, holding it close to your face and turning it, watching what\'s inside move. The fluids are viscous and dark, thick like molasses. You put them back.', take: 'The <span class="object">jar</span> has nothing you can use. You put it back.', use: 'You open one of the <span class="object">jars</span> and smell it. You recoil in disgust. You immediately put it back.' } }); await Item.create({ name: 'door', room: horrorRoom._id, takeable: false, state: 'locked', interactions: { look: 'You notice in a dark corner a rectangular shape. It\'s a heavy wooden <span class="object">door</span>. There is a chair tucked under the handle. Your mind races-- what were they trying to keep out? Your only options to leave are the <span class="object">window</span> or the <span class="object">door</span>.', take: 'You can\'t take the <span class="object">door</span>, it is affixed to the wall.', use: 'You weigh your options, and hesitantly move the chair out of the way. You turn the handle and push all of your weight into the <span class="object">door</span>, but it won\'t budge. You try the handle again and can hear it clicking. The <span class="object">door</span> appears to be locked.', useunlocked: 'You open the <span class="object">door</span>... You find yourself back in the libraryinth. You take breath of relief to find you have escaped The Virus.' } }); await Item.create({ name: 'key', room: horrorRoom._id, takeable: true, interactions: { look: 'You look closer at the <span class="object">key</span>. It is small and looks antique, the brass discolored in a patina of oxidation. You wonder what it\'s for.', take: 'You pick up the <span class="object">key</span> and put it in your pocket. It may come in handy later.', inventorytake: 'You already have the <span class="object">key</span>.', inventorylook: 'You think you hear a sound. Your heart begins to pound and you frantically feel into your pocket for the <span class="object">key</span>. You take a deep breath of relief: It\'s still there.', inventoryuse: 'What are you trying to unlock?', usetable: 'The <span class="object">key</span> is not cumbersome. You decide not to put it back. It may come in handy later.', usedoor: 'You move towards the <span class="object">door</span> and find the <span class="object">key</span> in your pocket. You put it into the keyhole, and hesitate for a moment as you recall the chair. You decide to unlock the <span class="object">door</span>.' } }); await Item.create({ name: 'window', room: horrorRoom._id, takeable: false, interactions: { look: 'You see a boarded up <span class="object">window</span>.', take: 'The <span class="object">window</span> is heavily boarded. You can\'t take the <span class="object">window</span>.', use: 'You try to pry the boards from the <span class="object">window</span>, but they are fortified with too many nails. You can only look out from the cracks of space between the boards, but the light is too bright to see clearly.' } }); };
Markdown
UTF-8
3,139
3.203125
3
[]
no_license
## String+CodingConvention.swift A regex powered string extension for converting strings from one coding conventions to another, or converting from coding convention to a sentance/title. This extension is wseful for populating UIKit components with JSON keys. For example: A UILabel reads "Recognised as an Element By" as poplated from a dictionary key: "recognisedAsAnElementBy" ## Functions ### The fun stuff ```` extension String { func camelToSnake() -> String func snakeToCamel() -> String func camelToSentance() -> String func snakeToSentance() -> String func removeParenthesis() -> String func lowerCasePrepisitions() -> String } ```` ### Helper functions ```` extension String { // A block based find/replace function based on regex pattern input func regexReplace(pattern: String, replace: RegexReplacement) throws -> String { func regexReplace(pattern: String, replaceCaptureGroup: RegexCaptureGroup) throws -> String { func substring(nsRange: NSRange) -> String func range(nsRange: NSRange) -> Range<Index> subscript(range: CountableRange<Int>) -> String? } ```` ## Example Usage ```` // Camel to snake let foo = "myCamelVariable" let snake = foo.camelToSnake() // my_camel_variable ```` ```` // Camal to sentence let foo = "myCamelVariableAtDinner" let sentence = foo.camelToSentance() // My Camel Variable At Dinner let properSentence = sentence.lowerCasePrepisitions() // My Camel Variable at Dinner ```` ```` // Snake to camel let foo = "my_snake_variable" let camel = foo.snakeToCamel() // mySnakeVariable ```` ```` // Snake to sentence let foo = "my_camel_variable_at_dinner" let sentence = foo.snakeToSentance() // My Camel Variable At Dinner let properSentence = sentence.lowerCasePrepisitions() // My Camel Variable at Dinner ```` ## Other useful utilities ### Closure based regex find/replace based on pattern ```` let text = "another_long_work_day_and_one_more_until_weekend" let pattern = "a[a-z]" print("*** Testing regexReplace:pattern:regexReplacement with pattern: \(pattern)") do { let converted = try property.regexReplacePattern(pattern: pattern, replace: { (index, toReplace) -> String in let output = "(" + toReplace.uppercased() + ")" return output }) print("\t\(property)\n\t\(converted)") } catch { print("caught error: " + error.localizedDescription) } // (AN)other_long_work_d(AY)_(AN)d_one_more_until_weekend ```` ### Closure based regex find/replace based on capture groups (stuff inside parenthesis) ```` let text = "another_long_work_day_and_one_more_until_weekend" let pattern = "(a[a-z]+)_.*(d[a-z]+)_.*(u[a-z]+)_" do { let converted = try text.regexReplaceCaptureGroups(pattern: pattern, replace: { (index, toReplace) -> String in if index % 2 == 0 { return "(" + "<redacted>" + ")" } else { return "(" + toReplace.uppercased() + ")" } }) print("\t\(property)\n\t\(converted)") } catch { print("caught error: " + error.localizedDescription) } // (ANOTHER)_long_work_(<redacted>)_and_one_more_(UNTIL)_weekend ````
Markdown
UTF-8
1,499
2.734375
3
[ "MIT" ]
permissive
# Smoothsort [![Gem Version](https://badge.fury.io/rb/smoothsort.png)](http://badge.fury.io/rb/smoothsort) [![Dependency Status](https://gemnasium.com/toroidal-code/smoothsort-rb.png)](https://gemnasium.com/toroidal-code/smoothsort-rb) [![Build Status](https://travis-ci.org/toroidal-code/smoothsort-rb.png?branch=master)](https://travis-ci.org/toroidal-code/smoothsort-rb) This is an implementation of Djikstra's smoothsort algorithm, as both a C extension, and native ruby. ## Installation Add this line to your application's Gemfile: gem 'smoothsort' Or for the native ruby version: gem 'smoothsort', github: 'toroidal-code/smoothsort-rb', branch: 'pure-ruby' And then execute: $ bundle Or install it yourself as: $ gem install smoothsort ## Usage ```ruby >> require 'smoothsort' #=> true >> a = (1..20).to_a.shuffle => [13, 19, 2, 11, 9, 18, 14, 10, 3, 7, 1, 6, 8, 4, 16, 5, 12, 17, 15, 20] >> a.ssort => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] >> a => [13, 19, 2, 11, 9, 18, 14, 10, 3, 7, 1, 6, 8, 4, 16, 5, 12, 17, 15, 20] >> a.ssort! => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] >> a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] ``` ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request
C++
UTF-8
1,370
2.84375
3
[ "MIT" ]
permissive
namespace Manacher { vector<int> a; int manacher(const string &s, int len) { a.resize((unsigned int)len); a[0]=0; int ans = 0, j; for(int i=0;i<len;) { while(i-a[i]>0&&s[i+a[i]+1]==s[i-a[i]-1]) a[i]++; if(ans<a[i]) ans=a[i]; j = i+1; while(j<=i+a[i] && i-a[i]!=i+i-j-a[i+i-j]){ a[j]=min(a[i+i-j],i+a[i]-j); j++; } a[j]=max(i+a[i]-j,0); i=j; } return ans; } int getMax(const char * s) { auto len = strlen(s); string str; str.resize(len<<1|1); for(int i=0;i<len;++i) { str[i<<1]='$'; str[i<<1|1]=s[i]; } str[len<<1]='$'; return manacher(str,2*len+1); } int getMax(const string &s) { auto len = s.size(); string str; str.resize(len<<1|1); for(int i=0;i<len;++i){ str[i<<1]='$'; str[i<<1|1]=s[i]; } str[len<<1]='$'; return manacher(str,len<<1|1); } vector<int> getMatch(const char * s) { getMax(s); return a; } vector<int> getMatch(const string &s) { getMax(s); return a; } }
Markdown
UTF-8
1,321
2.671875
3
[ "MIT" ]
permissive
## Quiz 5 Study Guide You should be able to answer questions on these topics for Quiz #5. 1. What does POMA mean? What is it used for? 2. Be able to do Lorenz-Kidd OO estimation. 3. Why did we decide to go in-depth on Lorenz-Kidd instead of COCOMO, COCOMO II, or function point estimation? Benefits/drawbacks of Lorenz-Kidd. 4. Given a list of tasks, be able to create a task network for a project and estimate its schedule. 5. Know the classes of comments we went over in class: Repeat of code, Explanation of code, Marker in code, Summary of code, Description of intent, and External Reference. Given a comment, be able to explain what class of comment is and whether or not it is a useful comment. 6. What is defensive programming? Given a method, say whether or not it practices defensive programming and justify why or why not. 7. What is refactoring? 8. What is the difference between parallelism and concurrency? 9. What are the benefits/drawbacks of multi-threaded programming? 10. What does it mean to start and join threads? 11. What is a data race? What are some ways to avoid them? 12. What does synchronized do? 13. What is deadlock? What are some ways to avoid it? 14. What is livelock? What are some ways to avoid it? 15. What is an atomic variable? What are the benefits/drawbacks to using one?
Java
UTF-8
8,596
2.140625
2
[]
no_license
package com.backpackers.android.backend.api; import com.google.api.server.spi.ServiceException; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiClass; import com.google.api.server.spi.config.ApiMethod; import com.google.api.server.spi.config.ApiNamespace; import com.google.api.server.spi.response.CollectionResponse; import com.google.api.server.spi.response.NotFoundException; import com.google.appengine.api.users.User; import com.backpackers.android.backend.authenticator.GoogleAuthenticator; import com.backpackers.android.backend.controller.CommentController; import com.backpackers.android.backend.model.comment.Comment; import com.backpackers.android.backend.validator.Validator; import com.backpackers.android.backend.validator.rule.comment.CommentCreateRule; import com.backpackers.android.backend.validator.rule.common.IdValidationRule; import com.backpackers.android.backend.Constants; import com.backpackers.android.backend.authenticator.FacebookAuthenticator; import com.backpackers.android.backend.authenticator.YolooAuthenticator; import com.backpackers.android.backend.validator.rule.common.AllowedToOperate; import com.backpackers.android.backend.validator.rule.common.AuthenticationRule; import com.backpackers.android.backend.validator.rule.common.NotFoundRule; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.inject.Named; @Api( name = "yolooApi", version = "v1", namespace = @ApiNamespace( ownerDomain = Constants.API_OWNER, ownerName = Constants.API_OWNER, packagePath = Constants.API_PACKAGE_PATH ) ) @ApiClass( resource = "comments", clientIds = { Constants.ANDROID_CLIENT_ID, Constants.IOS_CLIENT_ID, Constants.WEB_CLIENT_ID}, audiences = {Constants.AUDIENCE_ID}, authenticators = { GoogleAuthenticator.class, FacebookAuthenticator.class, YolooAuthenticator.class } ) public class CommentEndpoint { private static final Logger logger = Logger.getLogger(CommentEndpoint.class.getName()); /** * Inserts a new {@code Comment}. */ @ApiMethod( name = "posts.comments.add", path = "posts/{postId}/comments", httpMethod = ApiMethod.HttpMethod.POST) public Comment addPostComment(@Named("postId") final String websafePostId, @Named("text") final String text, final User user) throws ServiceException { Validator.builder() .addRule(new IdValidationRule(websafePostId)) .addRule(new AuthenticationRule(user)) .addRule(new CommentCreateRule(text)) .addRule(new NotFoundRule(websafePostId)) .validate(); return CommentController.newInstance().add(websafePostId, text, user); } /** * Inserts a new {@code Comment}. */ @ApiMethod( name = "questions.comments.add", path = "questions/{questionId}/comments", httpMethod = ApiMethod.HttpMethod.POST) public Comment addQuestionComment(@Named("questionId") final String websafePostId, @Named("text") final String text, final User user) throws ServiceException { Validator.builder() .addRule(new IdValidationRule(websafePostId)) .addRule(new AuthenticationRule(user)) .addRule(new CommentCreateRule(text)) .addRule(new NotFoundRule(websafePostId)) .validate(); return CommentController.newInstance().add(websafePostId, text, user); } /** * Deletes the specified {@code Comment}. * * @throws NotFoundException if the {@code id} does not correspond to an existing * {@code Comment} */ @ApiMethod( name = "posts.comments.remove", path = "posts/{postId}/comments/{commentId}", httpMethod = ApiMethod.HttpMethod.DELETE) public void removePostComment(@Named("postId") final String websafePostId, @Named("commentId") final String websafeCommentId, final User user) throws ServiceException { Validator.builder() .addRule(new IdValidationRule(websafePostId)) .addRule(new IdValidationRule(websafeCommentId)) .addRule(new AuthenticationRule(user)) .addRule(new NotFoundRule(websafePostId, websafeCommentId)) .addRule(new AllowedToOperate(user, websafeCommentId, AllowedToOperate.Operation.DELETE)) .validate(); CommentController.newInstance().remove(websafePostId, websafeCommentId, user); } /** * Deletes the specified {@code Comment}. * * @throws NotFoundException if the {@code id} does not correspond to an existing * {@code Comment} */ @ApiMethod( name = "questions.comments.remove", path = "questions/{questionId}/comments/{commentId}", httpMethod = ApiMethod.HttpMethod.DELETE) public void removeQuestionComment(@Named("questionId") final String websafePostId, @Named("commentId") final String websafeCommentId, final User user) throws ServiceException { Validator.builder() .addRule(new IdValidationRule(websafePostId)) .addRule(new IdValidationRule(websafeCommentId)) .addRule(new AuthenticationRule(user)) .addRule(new NotFoundRule(websafePostId, websafeCommentId)) .addRule(new AllowedToOperate(user, websafeCommentId, AllowedToOperate.Operation.DELETE)) .validate(); CommentController.newInstance().remove(websafePostId, websafeCommentId, user); } /** * List all entities. * * @param cursor used for pagination to determine which page to return * @param limit the maximum number of entries to return * @return a response that encapsulates the result list and the next page token/cursor */ @ApiMethod( name = "questions.comments.list", path = "questions/{questionId}/comments", httpMethod = ApiMethod.HttpMethod.GET) public CollectionResponse<Comment> listQuestionComments(@Named("questionId") final String websafeCommentableId, @Nullable @Named("cursor") String cursor, @Nullable @Named("limit") Integer limit, final User user) throws ServiceException { Validator.builder() .addRule(new IdValidationRule(websafeCommentableId)) .addRule(new AuthenticationRule(user)) .addRule(new NotFoundRule(websafeCommentableId)) .validate(); return CommentController.newInstance() .list(websafeCommentableId, cursor, limit, user); } /** * List all entities. * * @param cursor used for pagination to determine which page to return * @param limit the maximum number of entries to return * @return a response that encapsulates the result list and the next page token/cursor */ @ApiMethod( name = "posts.comments.list", path = "posts/{postId}/comments", httpMethod = ApiMethod.HttpMethod.GET) public CollectionResponse<Comment> listPostComments(@Named("postId") final String websafeCommentableId, @Nullable @Named("cursor") String cursor, @Nullable @Named("limit") Integer limit, final User user) throws ServiceException { Validator.builder() .addRule(new IdValidationRule(websafeCommentableId)) .addRule(new AuthenticationRule(user)) .addRule(new NotFoundRule(websafeCommentableId)) .validate(); return CommentController.newInstance() .list(websafeCommentableId, cursor, limit, user); } }
Java
UTF-8
3,843
3.703125
4
[]
no_license
package AdvancedExercises.Battleships; import java.util.Scanner; public class CLInterface implements PlayerInterface { private Scanner reader; public CLInterface() { reader = new Scanner(System.in); setDelimiter("\n"); } public String playerInput(String prompt) { System.out.println(prompt); return reader.next(); } public String[] readShipPlacement(Ship ship) { String input = playerInput("Where do you want to place your next ship? (" + ship.getName() + ", Length: " + ship.getSize() + ")"); return input.split(","); } public Coordinates getPlayerGuess(int playerNo) { Coordinates guess = new Coordinates(-1, -1); String input = ""; while (!guess.isValid()) { input = playerInput("Player " + playerNo + "'s turn." + " Enter guess in form [letter][number] (eg A1) or enter 'QUIT' to exit:"); if (input.length() == 2 || input.length() ==3) { guess = convertCoordinates(input); } if (!guess.isValid()) { System.out.println("Invalid input. Try again."); } } return convertCoordinates(input); } public String setOrientation(String inputOrientation) { String orientation; switch (inputOrientation.toLowerCase().trim()) { case "h": case "horizontal": orientation = "h"; break; case "v": case "vertical": orientation = "v"; break; default: orientation = "invalid"; } return orientation; } public void setDelimiter(String delimiter) { reader.useDelimiter(delimiter); } public Coordinates convertCoordinates(String alphanumericCoords) { Coordinates coordinates = new Coordinates(-1, -1); char letterPart = alphanumericCoords.toUpperCase().charAt(0); int numberPart = parseInt(alphanumericCoords.substring(1)); if (letterPart >= 'A' && letterPart < 'M' && numberPart > 0 && numberPart <= 12) { coordinates.setX(letterPart - 'A'); coordinates.setY(numberPart - 1); } return coordinates; } public String coordinateString(Coordinates coordinates) { char letter = (char) (coordinates.getX() + 'A'); return Character.toString(letter) + (coordinates.getY() + 1); } public String actionText(GridSpace spaceAction) { String action; switch (spaceAction) { case EMPTY: action = "Missed!"; break; case SHIP: action = "Hit! Have another turn!"; break; case MISS: action = "You've already tried that space and it was empty. Guess again."; break; case HIT: action = "You've already tried that space and it was a hit. Guess again."; break; case SUNK: action = "You hit and sunk your opponent's ship! Have another turn!"; break; case WON: action = "Congratulations! You sunk all of your opponent's ships! You win!"; break; default: action = "Invalid coordinates."; } return action; } public int parseInt(String intString) { int value = -1; try { value = Integer.parseInt(intString); } catch (NumberFormatException e) { System.out.println(intString + " is not an integer"); } return value; } public void displayAction(String output) { System.out.println(output); } }
C++
UTF-8
215
2.578125
3
[]
no_license
#ifndef PONY_HPP # define PONY_HPP #include <string> class Pony { private: std::string _name; public: void setName(std::string name); void introduce(void) const; ~Pony(void); }; #endif
Markdown
UTF-8
6,211
2.84375
3
[]
no_license
一〇九 第三十九章 图穷匕现 于梵道:“陈姑娘,假如我说这是出自贵府西席李老夫子的手笔,大约你该不会否认吧!” 陈翠绫默然半晌,然后满面庄重之色:“于公子,这东西你是哪里弄来的!” 于梵又是一声冷笑道:“陈姑娘,难道你已忘记向枯木尊者换回太阳真解的那回事了?” “没有!” “你们是用什么向他交换的?” “李夫子珍藏的二王法帖!” “哼哼,好一幅珍藏的二王法帖,只可惜枯木尊者并不欣赏,你们只不过方一离开,他就将其撕得粉碎了!” “为什么?” “因为那根本就不是二王法帖!” “不是二王法帖是什么?” “是贵府西席李夫子的一封书信!” 陈翠续大愕道:“一封书信?枯木尊者怎肯以太阳真解交换?” 于梵道:“李拙夫在这封书信中讲得明明白白,那本太阳真解乃是他一手伪造之物,枯木尊者当然落得做个顺手人情!” 陈翠绫神色一变道:“难道你给我的这张纸片……” 于梵冷笑一声:“不错,那就是被枯木尊者撕碎的所谓二王法帖!” 陈翠绫凝视着手中的碎纸片,满面茫然道:“奇怪,李夫子为什么要做这种事?” 于梵面带怒色道:“为什么?嘿嘿,为的是藉此挑动天下武林相互残杀,好让你们坐收渔人之利,以遂独霸江湖之愿!” 陈翠绫凄然笑道:“于公子,你这种想法虽然有理,怎奈我从无逐鹿江湖之心,李夫子更是手无缚鸡之力的老弱书生……” 一字未落,于梵狂笑接口道:“哈哈,陈翠绫,事到如今你就不必再加隐瞒了,假如威慑江湖的红灯老祖也算弱者的话,天下哪里还有强人!” 陈翠绫与小黛闻言同声惊叫道:“什么?红灯老祖?于公子,你说谁是红灯老祖?” 那神态,那表情,显然是发自内心的,于梵不由一愣道:“怎么?你们真的不知道?” 陈翠绫目中惊诧之色更甚道:“你……你是说李夫子?” 于梵道:“一点不错,就是他,他就是九大凶人之首的红灯老祖李庸!” 陈翠绫像是仍然不敢相信道:“李夫子虽懂武功,你……你不会弄错吧?” 于梵一怔道:“懂而不会?这是谁说的?” 陈翠绫道:“君山水寨人尽皆知!” “你们相信?” “那是事实!” 于梵不由冷笑道:“嘿嘿,人在数丈开外,举手投足间便将在下的穴道制住,这又何尝不是事实!” “你说的难道也是李夫子?” 由于陈翠绫的一再表示意外,于梵心念一转,突然间醒悟了过来。 李拙夫的一切作为,陈翠绫分明全被蒙在鼓里! 不是么?假如陈翠绫也是同伙的话,则那日李拙夫尽可与枯木尊者明言,实在用不着再弄那些玄虚。 这样一想,他立即将自己所知有关李拙夫的一切,迅速地扼要述说一遍。 果然,这一席话,只把个陈翠绫听得目瞪口呆,好半晌才失声说道:“啊!居然有这种事?” 于梵道:“此事若非亲目所睹,的确难以令人置信,好在那些石牢地道一时间总是搬不了的,姑娘请到后山一看就明白了!” 这话有理,陈翠绫一顿之后,立道:“小黛,取我的剑来,我们随同于公子到后山看看!” 情况霍然转变,于梵心中不由大为振奋。 庵堂的门打开了,他一马当先,后面紧跟着小黛与陈翠绫,三个人的心中全部急如星火,怕不能一步跨到后山! 可是,他们不过行出一箭之地,突然,人影一闪,一名黑衣大汉横身拦住了去路道:“姑娘到哪里去?” 陈翠绫双眉一扬,喝道:“洪滨你想干什么?给我闪开!” 这叫洪滨的大汉,乃是君山水寨中的一名巡察,平昔只要见到陈翠绫脸色一沉,早就夹着尾巴滚得远远地了。 可是今天,这小子竟像吃了老虎心,豹子胆,闻言非但没有闪开,反而毫不在乎露出一脸诡笑道:“嘿嘿,你还没回答我要到哪里去呢?” 君山水寨中自从老寨主追风挟陈屏死后,陈翠绫已经是君山主人,这小子如此放肆,实在无礼至极,陈翠绫听得脸色一变道:“洪滨,我到哪里去,难道还要得你允许么?” 洪滨浓眉一扬,又是一声出人意外地阴笑道:“嘿嘿,姑娘不愧聪明人,你这话完全说对了!” 陈翠绫听得怒叱一声:“大胆的奴才,你是受谁的指使?” 洪滨昂然答道:“属下奉的是天尊法谕!” 陈翠绫虽然已听于梵说过,但仍情不自禁的一愕道:“天尊?什么天尊?” 于梵道:“姑娘怎么忘了,他说的天尊就是元始天尊,也就是李拙夫!” 陈翠绫面色一寒道:“洪滨,于公子说的是么?” 洪滨道:“不错,天尊就是元始天尊,至于他姓什名谁,那就不是属下能够知道的了!” “洪滨,我问你,君山水寨的主人是他还是我?” 洪滨嘿嘿笑道:“姑娘,虽然你是君山水寨的主人,可是天尊却是天下武林共同的主人,所以为了遵从天尊的法谕,说不得有些地方将要得罪姑娘了!” 陈翠绫气得脸色苍白,怒喝一声:“好一个狂妄的奴才,既然你陷溺已深,我可不能再姑息你了!” 寒光一闪,宝剑出鞘。 那洪滨想是知道厉害,双肩一晃,身形闪电退后…… 陈翠绫陡发一声娇笑:“好奴才,如果容你逃出手去,我还凭什么领袖君山群豪,看剑!” 声落剑起,寒光骤然一闪,直向洪滨背心点到…… 那洪滨身形凌空,已经到达八步开外,可是被陈翠绫剑上的芒尾一扫,顿如惨号一声,平空摔落在地。 于梵真没想到,陈翠绫剑上竟有这样高深的火候,不由心头骇然。
Java
UTF-8
1,715
2.8125
3
[]
no_license
package view.notePane; import controllers.NoteWindowController; import javafx.geometry.Insets; import javafx.scene.control.*; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import model.Note; import model.Notes; public class NotePane extends VBox { private Note note; private TextField topic; private TextArea content; private Button delete = new Button(); private Button edit = new Button(); public NotePane(Note note, Notes notes) { setSpacing(10); topic = new TextField(note.getTopic()); topic.setEditable(false); topic.setId("topic"); topic.setFocusTraversable(false); content = new TextArea(note.getContent()); content.setEditable(false); content.setWrapText(true); content.setMinHeight(200); content.setId("content"); content.setFocusTraversable(false); setId("pane"); getStylesheets().add("/style/notePane.css"); setFillWidth(true); delete.setPrefSize(40, 40); delete.setMinSize(40, 40); delete.setOnAction(del -> { if (new Alert( Alert.AlertType.CONFIRMATION, "Are you sure", ButtonType.YES, ButtonType.NO) .showAndWait() .get() == ButtonType.YES ) { notes.delete(note); ((VBox) getParent()).getChildren().remove(this); } }); delete.setId("deleteButton"); edit.setPrefSize(40, 40); edit.setMinSize(40, 40); edit.setOnAction(e -> { Note n = NoteWindowController.editNote(note); if(n == null) return; notes.update(n); topic.setText(n.getTopic()); content.setText(n.getContent()); }); edit.setId("editButton"); HBox b = new HBox(30, delete, edit); b.setPadding(new Insets(10, 10, 10, 10)); b.setPrefHeight(100); getChildren().addAll(topic, content, b); } }
JavaScript
UTF-8
7,666
2.59375
3
[]
no_license
import React, { Fragment, useState } from "react"; import moment from "moment"; import { Table, Button } from "reactstrap"; import { formatDisplay, formatDatabase, formatPrint } from "../../shared/constants"; import Animal from "./models/Animal"; import { formatRegistro } from "../../shared/utils"; const Animais = (props) => { const deleteAnimal = (key) => { props.delete(key); } const animais = props.animais.map((animal) => Animal.FromFirestore(animal)); let animaisComGdp = 0; const convertToNumber = (value) => { const number = Number(value); if (Number.isNaN(number)) { return 0; } return number; }; const totals = animais.reduce((acc, cur) => { if (cur.gdp ?? 0 != 0) { animaisComGdp++; } return { pesoInicial: acc.pesoInicial + convertToNumber(cur.pesoInicial), pesoFinal: acc.pesoFinal + convertToNumber(cur.pesoFinal), gdp: acc.gdp + convertToNumber(cur.gdp) } }, { pesoInicial: Number(0), pesoFinal: Number(0), gdp: Number(0) }); const average = { pesoInicial: totals.pesoInicial / animaisComGdp, pesoFinal: totals.pesoFinal / animais.length, gdp: totals.gdp / animaisComGdp }; return ( <Table responsive bordered className="align-middle text-center"> <thead> <tr> <th rowSpan="2" className="align-middle text-center d-none d-print-table-cell" > Ordem </th> <th rowSpan="2" className="align-middle text-center"> Animal </th> <th colSpan="2" className="text-center"> Data Pesagem </th> <th rowSpan="2" className="align-middle text-center"> Dias </th> <th colSpan="2" className="text-center"> Pesagem (Kg) </th> <th rowSpan="2" className="d-none d-print-table-cell align-middle text-center" > Pesagem Curral </th> <th rowSpan="2" className="align-middle text-center"> GPD </th> <th rowSpan="2" className="d-print-none" /> </tr> <tr> <th className="text-center">Anterior</th> <th className="text-center">Atual</th> <th className="text-center">Inicial</th> <th className="text-center">Final</th> </tr> </thead> <tbody> {animais.map((animal, index) => { const gdpClass = animal.gdp > average.gdp ? "table-success" : animal.gdp < average.gdp ? "table-danger" : ""; return ( <tr key={animal.key}> <td className="align-middle text-center d-none d-print-table-cell" > {index + 1} </td> <td><Button color="link" block onClick={() => props.showHistory(animal.key)}>{formatRegistro(animal.registro)}</Button></td> <td className="d-none d-print-table-cell"> {animal.dataAnterior && moment( animal.dataAnterior, formatDatabase ).format(formatPrint)} </td> <td className="d-none d-print-table-cell"> {moment( animal.dataAtual, formatDatabase ).format(formatPrint)} </td> <td className="d-print-none"> {animal.dataAnterior && moment( animal.dataAnterior, formatDatabase ).format(formatDisplay)} </td> <td className="d-print-none"> {moment( animal.dataAtual, formatDatabase ).format(formatDisplay)} </td> <td>{animal.dias}</td> <td>{animal.pesoInicial.toLocaleString('pt-BR', { maximumFractionDigits: 2 })}</td> <td>{animal.pesoFinal.toLocaleString('pt-BR', { maximumFractionDigits: 2 })}</td> <td className="d-none d-print-table-cell" /> <td className={gdpClass}>{animal.gdp.toLocaleString('pt-BR', { maximumFractionDigits: 2 })}</td> <td className="d-print-none"> <Button size="sm" color="danger" block onClick={() => deleteAnimal(animal.key) } > Apagar </Button> </td> </tr> ); })} </tbody> <tfoot className="fw-semibold"> <tr> <td>Média</td> <td colSpan={4} className="d-none d-print-table-cell"></td> <td colSpan={3} className="d-print-none"></td> <td>{average.pesoInicial.toLocaleString('pt-BR', { maximumFractionDigits: 2 })}</td> <td>{average.pesoFinal.toLocaleString('pt-BR', { maximumFractionDigits: 2 })}</td> <td className="d-none d-print-table-cell" /> <td>{average.gdp.toLocaleString('pt-BR', { maximumFractionDigits: 2 })}</td> <td className="d-print-none"></td> </tr> <tr> <td>Total</td> <td colSpan={4} className="d-none d-print-table-cell"></td> <td colSpan={3} className="d-print-none"></td> <td>{totals.pesoInicial.toLocaleString('pt-BR', { maximumFractionDigits: 2 })}</td> <td>{totals.pesoFinal.toLocaleString('pt-BR', { maximumFractionDigits: 2 })}</td> <td colSpan={2}></td> </tr> </tfoot> </Table> ); } export default Animais;
Python
UTF-8
1,076
2.671875
3
[]
no_license
# -*- coding: utf-8 -*- from config import * import showing as sh from random import randrange as rndt class Barrier: """ этот класс связан со всем, что связано с преградами """ def __init__(self, name, race, health, force, x, y): self.x = x self.y = y self.health = health self.race = race self.force = force self.color = "orange" self.rect_id = sh.Entity(x, y, self.color) def coords(self): self.coordinates = self.rect_id.coords() list_of_barriers = [] a = 0 b = 0 for i in map: for j in i: if a == WIDTH: a = 0 b += step if j == "*": temp = Barrier("b" + str(3), "barrier", 1, 0, a, b) temp.coords() list_of_barriers.append(temp) a += step #for barrier in range(count_of_barriers): # temp = Barrier("b" + str(barrier), "barrier", 1, 0, rndt(0, WIDTH, step), rndt(0, HEIGHT, step)) # temp.coords() # list_of_barriers.append(temp)
Markdown
UTF-8
3,730
2.703125
3
[]
no_license
# Data analysis script This script details the commands used in order to get information about the data used for this project. The goal was to assess allele frequencies, polymorphisms... ## Download and install tools wget http://s3.amazonaws.com/plink1-assets/plink_mac_20200121.zip ## Pipeline ### 1. Prepare files for PLINK (--make-bed) To execute plink yu must, either add plink to the PATH, or work from the directory where PLINK is located. The input is the name of the .bim, .bed and .fam file (same for the three files) without the extension. The same applies for the output. ./plink --bfile <ctrl_filename> --make-bed --allow-no-sex --out <ctrl_plink> ./plink --bfile <case_filename> --make-bed --allow-no-sex --out <case_plink> * In our samples "--allow-no-sex" is required for the case files because there are ambiguous-sex samples, and with this command those are ignored. ### 2. Get basic statistics With PLINK we can obtain statistics of the input files, which creates a set of output files with counts and frequencies that we will later on analyse. ./plink --bfile <ctrl_plink> --freqx --maf 0.05 --missing --het --make-bed --allow-no-sex --out <ctrl_analysis> ./plink --bfile <case_plink> --freqx --maf 0.05 --missing --het --make-bed --allow-no-sex --out <case_analysis> #### a) freqx This option produces a detailed genotype count report in a .frqx file that consists in a tab separated file. By filtering the SNPs that have a value of 1 in the heterozygote count (6th column) and 0 for the homozygote count of both alleles (columns 5th and 7th), we can obtain the count of singletons since they are the variants that appear once in the cohort and in a heterozygous genotype. We can filter those SNPs with the following command: # Singleton count awk '($6==1)' ctrl.frqx | awk -F "\t" '{ if(($5 == 0) || ($7 == 0)) {print} }' | wc -l awk '($6==1)' case.frqx | awk -F "\t" '{ if(($5 == 0) || ($7 == 0)) {print} }' | wc -l #### b) maf 0.05 This option filters the SNPs with a minor allele frequency lower than 5% and gives you the filtering information in the -log file. #### c) missing This setting creates two files, one with sample missing data (.lmiss) and another with variant missing data (.imiss). We will count the SNPs or genotypes that have a missing call rate over 2% using the following commands: # CONTROL awk '($6>0.02)' ctrl.imiss | wc -l # genotypes awk '($5>0.02)' ctrl.lmiss | wc -l # SNPs # CASES awk '($6>0.02)' case.imiss | wc -l # genotypes awk '($5>0.02)' case.lmiss | wc -l # SNPs #### d) het It creates a list of the heterozygous haploid genotypes found in our samples. The output is a tab separated file in which the 6th column contains the Method-of-moments F coefficient estimate. This estimate predicts the likehood of the observed homozygosity given the expected homozygosity for a random dataset. We can compurte the average heterozygosity of the population in the control samples and compare it to the case samples to detect inbreeding in the sample population. awk '{ total += $6 } END { print total/NR }' ctrl.het awk '{ total += $6 } END { print total/NR }' case.het ### 3. Missing data The experimental genotyping of samples has an error rate of 0.1% to 0.6% [[reference](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4216915/)], so in order to get an idea of the percentage of our data inputs that are not correctly genotyped, we count the missing data in the files as: grep -v "^#" <filteredCases.vcf> | cut -f 10- | tr "\t" "\n" | cut -d ':' -f 1 | awk '/^\.\/\./ {NC++;} END{printf("%f\n",NC/(1.0*NR))}'
Java
UTF-8
3,346
2.015625
2
[]
no_license
package org.wikipathways.indexer; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.apache.lucene.document.Document; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Searcher; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.BooleanClause.Occur; import org.bridgedb.Xref; import org.pathvisio.indexer.DataNodeIndexer; public class WikiPathwaysSearcher { Searcher searcher; public WikiPathwaysSearcher(IndexSearcher searcher) { this.searcher = searcher; } public List<SearchResult> query(Query query, int limit) throws IOException { TopDocs hits = searcher.search(query, null, limit); List<SearchResult> results = new ArrayList<SearchResult>(); for(ScoreDoc sd : hits.scoreDocs) { results.add(new SearchResult(searcher.doc(sd.doc), sd.score)); } return results; } public List<SearchResult> queryByXrefs(Collection<Xref> xrefs, int limit) throws IOException { BooleanQuery query = new BooleanQuery(); for(Xref x : xrefs) { Query tq = null; if(x.getDataSource() == null) { tq = new TermQuery(new Term(DataNodeIndexer.FIELD_XID, x.getId())); } else { tq = new TermQuery(new Term(DataNodeIndexer.FIELD_XID_CODE, x.getId() + ":" + x.getDataSource().getSystemCode())); } query.add(tq, Occur.SHOULD); } final Set<String> ids = new HashSet<String>(); final Set<String> idcodes = new HashSet<String>(); for(Xref x : xrefs) { ids.add(x.getId()); if(x.getDataSource() != null) { idcodes.add(x.getId() + ":" + x.getDataSource().getSystemCode()); } } FieldFilter filter = new FieldFilter() { public boolean include(String name, String value) { //Only include x.id, x.id.database when they are part of the query if(DataNodeIndexer.FIELD_XID.equals(name)) { return ids.contains(value); } if(DataNodeIndexer.FIELD_XID_CODE.equals(name)) { return idcodes.contains(value); } return true; } }; List<SearchResult> results = new ArrayList<SearchResult>(); TopDocs hits = searcher.search(query, null, limit); for(ScoreDoc sd : hits.scoreDocs) { results.add(new SearchResult(searcher.doc(sd.doc), sd.score, filter)); } return results; } public Set<String> listXrefs(String pathwaySource, String sysCode) throws IOException { Set<String> xrefs = new TreeSet<String>(); TermQuery query = new TermQuery(new Term( DataNodeIndexer.FIELD_INDEXERID, DataNodeIndexer.class.getName() + pathwaySource) ); TopDocs hits = searcher.search(query, null, 10000); for(ScoreDoc sd : hits.scoreDocs) { Document xrefDoc = searcher.doc(sd.doc); String[] idcodes = xrefDoc.getValues(DataNodeIndexer.FIELD_XID_CODE); if(idcodes == null) continue; for(String idcode : idcodes) { if(idcode.endsWith(":" + sysCode)) { xrefs.add(idcode.substring(0, idcode.lastIndexOf(':'))); } } } return xrefs; } }
Markdown
UTF-8
982
2.859375
3
[]
no_license
# CalculadoraJS ## Objetivo O desenvolvimento de uma calculadora utilizando as tecnologias: - <img src="https://img.shields.io/badge/html5%20-%23E34F26.svg?&style=for-the-badge&logo=html5&logoColor=white"/> - <img src="https://img.shields.io/badge/css3%20-%231572B6.svg?&style=for-the-badge&logo=css3&logoColor=white"/> - <img src="https://img.shields.io/badge/javascript%20-%23323330.svg?&style=for-the-badge&logo=javascript&logoColor=%23F7DF1E"/> <br> ### Funções adicionais - A interface da calculadora possui uma opção para mudança do tema light para o dark, que é um diferencial da aplicação <br> ### Screenshots da aplicação <br> Light Mode | Dark Mode ---|--- | <img src="https://github.com/MatheusAlves00/calculadoraJS/blob/master/assets/images/screenshots/lightmode.png?raw=true" resize="contain" width="800" /> | <img src="https://github.com/MatheusAlves00/calculadoraJS/blob/master/assets/images/screenshots/darkmode.png?raw=true" width="800" > |
Java
UTF-8
833
2.125
2
[]
no_license
package tr.com.bilkent.patientmonitoring.mapper; import org.mapstruct.InheritInverseConfiguration; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.factory.Mappers; import tr.com.bilkent.patientmonitoring.config.MapperConfig; import tr.com.bilkent.patientmonitoring.dto.symptom.SymptomDataDTO; import tr.com.bilkent.patientmonitoring.entity.SymptomData; import java.util.List; @Mapper(config = MapperConfig.class) public interface SymptomDataMapper { SymptomDataMapper INSTANCE = Mappers.getMapper(SymptomDataMapper.class); @Mapping(target = "key", source = ".") SymptomData symptomFromDto(SymptomDataDTO symptomData); @InheritInverseConfiguration SymptomDataDTO dtoFromSymptom(SymptomData symptomData); List<SymptomDataDTO> symptomsToDtos(List<SymptomData> districts); }
C
UTF-8
256
3.5
4
[]
no_license
#include "holberton.h" /** * factorial - Short description, single line * @n: Description of parameter * Return: Description of the returned value */ int factorial(int n) { if (n < 0) return (-1); if (n == 0) return (1); return (n * factorial(n - 1)); }
C++
UTF-8
450
2.84375
3
[]
no_license
// EulerProblems.cpp : Defines the entry point for the console application. // #include "EulerProblems.h" int main() { problem_55 problem; auto t0 = std::chrono::high_resolution_clock::now(); std::cout << problem.solution() << std::endl; auto t1 = std::chrono::high_resolution_clock::now(); std::cout << "Solution calculated in " << static_cast<std::chrono::duration<float>>(t1 - t0).count() << " seconds" << std::endl; return 0; }
C++
UTF-8
990
3.140625
3
[]
no_license
/* Title: Monster.cpp Author: Matthew Yoon Date: 11/6/2019 Description: .cpp file for Monster.h */ #include "Monster.h" using namespace std; // Name: Monster() - Default Constructor // Description: Would be used to create a monster but abstracted // Preconditions: None // Postconditions: Used to populate child class data Monster::Monster(){ } // Name: Monster(string name, int hp) - Overloaded Constructor // Description: Would be used to create a monster but abstracted // Preconditions: None // Postconditions: Used to populate child class data Monster::Monster(string name, int hp):Entity(name,hp){ } // Name: Attack() // Description: Describes attack statements for monster // Preconditions: None // Postconditions: Returns damage int Monster::Attack(){ int atk = 1; return atk; } // Name: SpecialAttack() // Description: Purely virtual SpecialAttack // Preconditions: None // Postconditions: May be used to call child class SpecialAttack //virtual int SpecialAttack()=0;
JavaScript
UTF-8
140
2.703125
3
[]
no_license
class Person { constructor(name) { this.name = name; var stone = false; this.stoned = stone ; } } module.exports = Person;
SQL
UTF-8
276
2.796875
3
[]
no_license
CREATE TABLE "group" ( "id" bigserial PRIMARY KEY, "password" text NOT NULL ); INSERT INTO "group" ("id", "password") VALUES (0, ''); ALTER TABLE "game" ADD "groupId" bigint NOT NULL DEFAULT 0 REFERENCES "group" ("id"); ALTER TABLE "game" ALTER "groupId" DROP DEFAULT;
Markdown
UTF-8
2,940
3
3
[]
no_license
<!-- Godzilla VS Biollante (1989) --> In the aftermath of Godzilla attack in 1984, a black market struggle ensues for control of the monster's radioactive tissues left behind in the destruction: the so-called "G-Cells." Saradia, a Middle Eastern province, acquires G-Cells for use in agriculture, under the guidance of disaffected Japanese scientist Shiragami. Shiragami's lab is destroyed in a terrorist attack by a rogue agency called BioMajor, however, and his daughter Erika is killed. Five years later, Shiragami has repatriated to Japan and lives in solitude, tending a rose plant he's grafted with Erika's DNA. Shiragami's upstart understudy, Kirishima, disagrees with Shiragami's cautious attitudes towards bio science and seeks to push the boundaries further. Incidentally, Kirishima is heading the development of a biological weapon to use in the event of Godzilla's return, and makes use of the government's stock of G-Cells. Shirigami initially refuses to join the project. When an earthquake damages Shirigami's house and kills his rose plant, he changes his mind in order to gain access to the G-Cells. Shirigami secretly uses the G-Cells to revive the rose plant, which begins to mutate. BioMajor infiltrates Shirigami's lab to steal the G-Cells, but they are attacked by the mutated rose plant. BioMajor instead plants bombs around Mt. Mihara and threatens to use them to free Godzilla from the volcano if the G-Cells are not turned over to them. Kirishima arrives at the exchange point but both parties are foiled by SSS9, an elite Saradian agent, sent to recover G-Cells for his home country. The bombs go off and Godzilla is released. The military tries to repel the monster but fails. Godzilla encounters the giant mutated rose bush, now called Biollante and towering hundreds of feet tall in Lake Ashino. Godzilla duels the plant and seemingly kills it. Godzilla arrives in Osaka, where a crack squad of marksmen inject the monster with Kirishima's new bio weapon, an anti nuclear energy bacteria. Kirishima, meanwhile, locates a Saradian front office in Osaka where the G-Cells are being held and recovers them. SSS9 receives orders to terminate Shirigami. After several hours, the bio weapon shows no effects on Godzilla. Kirishima theorizes that this is because of the monster's low body temperature. The military unveils an experimental weather control system, which they plan to use to raise Godzilla's temperature. A mine field of thunder mines is laid out in the monster's path, which when activated cause lightning bolts to strike him. Godzilla begins to slow under the effects of the bacteria. Biollante returns in a much more feral form and fights with Godzilla. Godzilla is beaten back into the ocean to recover from his wounds and wait out the effects of the bacteria. Biollante dissolves into glowing pollen. SSS9 assassinates Shiragami, but is in turn killed while fighting Kirishima in the mine field.
Markdown
UTF-8
746
2.671875
3
[ "MIT" ]
permissive
--- layout: post title: "Peggy Update: UI Tidyup" date: 2016-01-11 10:42:00 categories: peggy --- Hello from New Zealand! I made use of some airport downtime to tidy up the UI a little bit. It's still a long way from its final incarnation, but at least represents the idea of entering a command, then having the command and response displayed and scroll upwards from above the input window. <img src="/assets/images/2016-01-11/peggy-updated-ui.png" width="400"> The next two tasks, in no particular order: - hook up the web UI to the C++ game server - set up a public web server (probably a quick 'n dirty job) so anyone can try out the game As always, [source is available on github][gh]. [gh]: https://github.com/peterussell/peggy2
Python
UTF-8
4,551
3.21875
3
[]
no_license
import romanconvert, sys from PyQt5 import QtWidgets #Корректно конвертирует числа до 3999 включительно, так как для чисел выше 3999 используется несколько другая нотация. class romanConverter(QtWidgets.QDialog): def __init__(self): super(romanConverter, self).__init__() self.ui = romanconvert.Ui_Dialog() #создаёт экземпляр класса интерфейса self.form = QtWidgets.QWidget() #создаёт экземпляр класса QWidget self.ui_init() def ui_init(self): self.ui.setupUi(self.form) #инициализирует форму self.form.show() #выводит на экран форму self.run() def run(self): self.ui.convert.clicked.connect(self.solution) #при нажатии на кнопку выполняется функция def solution(self): roman = self.ui.typein.text() #записывает строку из QLineEdit в переменную roman pat = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} #-----------------НАЧАЛО ПРОВЕРКИ----------------- if len(roman) == 0: self.ui.result.setText("Arabic result: " + "0") self.ui.typein.clear() #после нажатия кнопки "Convert" очищает строку ввода return 0 elif len(list(filter((lambda x: x not in list(pat.keys())), roman))) != 0: #если ввели не римское число, то также self.ui.result.setText("Arabic result: " + "0") #возвращает 0 self.ui.typein.clear() return 0 elif len(roman) > 3: #если длина римского числа больше 3, то... for i in range(len(roman)): #переменная i инкрементируется в цикле от 0 до длины введённого римского числа if roman[i:i+4].count(roman[i]) == 4: #проверяет введённое римское число на стоящие подряд 4 одинаковых числа self.ui.result.setText("Arabic result: " + "0") #записывает результат в QLabel self.ui.typein.clear() return 0 #если 4 одинаковых числа стоят подряд, то возвращает 0 #-----------------КОНЕЦ ПРОВЕРКИ----------------- o = [pat[x] for x in roman.strip()] #для каждого числа из введённой римской строки берёт соответствующее значение #из словаря pat res, i = 0, 0 #переменная res для хранения результата конвертации while i <= len(o) - 1: if i == len(o) - 1: #если цикл дошёл до конца, то последнее число из списка о прибавляется к res += o[i] #переменной res, которая собирает в себя результат elif o[i] >= o[i + 1]: #если данное римское число больше или равно следующему римскому числу в строке res += o[i] #то данное число прибавляется к результату else: res += o[i + 1] - o[i] #а если наоборот, данное число меньше, чем следующее, то следующее число вычитает данное #и прибавляется к переменной res, а то есть, к результату i += 1 #и увеличивает цикл еще на один шаг, чтобы пропустить одно число, которое было вычтено i += 1 self.ui.result.setText("Arabic result: " + str(res)) self.ui.typein.clear() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) cnvrt = romanConverter() sys.exit(app.exec_())
PHP
UTF-8
5,223
3.25
3
[]
no_license
<?php /** * Routing class to extract and parse request parameters from the URL. * @package Core */ class Route { /** * Name of the route. * @var string * @access public */ public $name; /** * Rule for this route. * @var mixed * @access public */ public $rule; /** * Default parameters for this route. * @var mixed * @access public */ public $defaults; /** * Extracted parameters * @var array * @access public */ public $params = array(); /** * Associative array of route rules. * @var array * @access private * @static */ private static $rules = array(); /** * Associative array of route instances. * @var array * @access private * @static */ private static $routes = array(); /** * Constructs a route. * * @param string $name Name of the route * @param mixed $rule Rule for this route * @param array $defaults Default parameters for the route * @return Route Initialized Route * @access protected */ protected function __construct($name, $rule, $defaults) { $this->name = $name; $this->rule = $rule; $this->defaults = $defaults; } /** * Generates a url for a route * * @param array $params Parameters to substitute in the route * @param bool $absolute Whether to return an absolute url * @param string $protocol Protocol to use for absolute url * @return string Generated url * @access public */ public function url($params = array(), $absolute = false, $protocol = 'http') { if (is_callable($this->rule)) throw new Exception("The rule for '{$this->name}' route is a function and cannot be reversed"); $url = is_array($this->rule) ? $this->rule[0] : $this->rule; $replace = array(); $params = array_merge($this->defaults, $params); foreach ($params as $key => $value) $replace["<{$key}>"] = $value; $url = str_replace(array_keys($replace), array_values($replace), $url); $count = 1; $chars = '[^\(\)]*?'; while ($count > 0) $url = preg_replace("#\({$chars}<{$chars}>{$chars}\)#", '', $url, -1, $count); $url = str_replace(array('(', ')'), '', $url); if ($absolute) $url = $protocol.'://'.$_SERVER['HTTP_HOST'].$url; return $url; } /** * Ads a route * * @param string $name Name of the route. Routes with the same name will override one another. * @param mixed $rule Either an expression to match URI against or a function that will * be passed the URI and must return either an associative array of * extracted parameters (if it matches) or False. * @param array $defaults An associated array of default values. * @return void * @access public * @static */ public static function add($name, $rule, $defaults = array()) { Route::$rules[$name] = array( 'rule' => $rule, 'defaults' => $defaults ); } /** * Gets route by name * * @param string $name Route name * @return Route * @access public * @throws Exception If specified route doesn't exist * @static */ public static function get($name) { if (!isset(Route::$rules[$name])) throw new Exception("Route {$name} not found."); if (!isset(Route::$routes[$name])) { $rules = Route::$rules[$name]; Route::$routes[$name] = new static($name, $rules['rule'], $rules['defaults']); } return Route::$routes[$name]; } /** * Matches the URI against available routes to find the correct one. * * @param string $uri Request URI * @return Route * @access public * @throws Exception If no route matches the URI * @throws Exception If route matched but no Controller was defined for it * @throws Exception If route matched but no action was defined for it * @static */ public static function match($uri) { $matched = false; foreach (Route::$rules as $name => $rule) { $rule = $rule['rule']; if (is_callable($rule)) { if (($data = $rule($uri)) !== FALSE) { $matched = $name; break; } } else { $pattern = is_array($rule) ? $rule[0] : $rule; $pattern = str_replace(')', ')?', $pattern); $pattern = preg_replace_callback('/<.*?>/', function($str) use ($rule) { $str = $str[0]; $regexp = '[a-zA-Z0-9\-\._]+'; if (is_array($rule)) $regexp = Misc::arr($rule[1], str_replace(array('<', '>'), '', $str), $regexp); return '(?P'.$str.$regexp.')'; }, $pattern); preg_match('#^'.$pattern.'/?$#', $uri, $match); if (!empty($match[0])) { $matched = $name; $data = array(); foreach ($match as $k => $v) if (!is_numeric($k)) $data[$k] = $v; break; } } } if ($matched == false) throw new Exception('No route matched your request', 404); $rule = Route::$rules[$matched]; $params = array_merge($rule['defaults'], $data); if (!isset($params['controller'])) throw new Exception("Route {$matched} matched, but no controller was defined for this route", 404); if (!isset($params['action'])) throw new Exception("Route {$matched} matched with controller {$params['controller']}, but no action was defined for this route", 404); $route = Route::get($matched); $route->params = $params; return $route; } }
Ruby
UTF-8
892
4.25
4
[]
no_license
people = 10 cars = 25 trucks = 25 # if there is more cars than people then output "take cars" if cars > people puts "We should take the cars." # if not, check if cars is least than people then output "don't take cars" elsif cars < people puts "We should not take the cars." # else then cars = people then output "cant decide" else puts "We can't decide." end # if theres more trucks than cars, then output "too many trucks" if trucks > cars puts "That's too many trucks." # if trucks less than cars, then output "maybe take trucks" elsif trucks < cars && trucks == cars puts "Maybe we could take the trucks." # if trucks = cars, output "cant decide" else puts "We still can't decide." end # if more people than trucks, ouput "take trucks" if people > trucks puts "Alright, let's just take the trucks." # if not, output stay home else puts "Fine, let's stay home then." end
Markdown
UTF-8
2,173
2.59375
3
[]
no_license
--- wordpress_id: 881 layout: post title: supersize excerpt: last night hiromi and I went to go see the movie called supersize me. It was made by some guy named Morgan Spurlock. he ate mcdonalds everyday for one month. it totally destroyed him. heh. he was broken. it scared me. are country is so broke... date: 2004-06-10 18:52:54 -05:00 tags: job, phone, hiromi, nokia wordpress_url: http://new.nata2.org/?p=881 --- last night hiromi and I went to go see the movie called <a href="http://www.supersizeme.com/">supersize me</a>. It was made by some guy named <a href="http://www.supersizeme.com/home.aspx?page=aboutdirector">Morgan</a> <a href="http://imdb.com/name/nm1041597/">Spurlock</a>. he ate mcdonalds everyday for one month. it totally destroyed him. heh. he was broken. it scared me. are country is so broken. we are going down the drain. sad day. <br/><br/>rachel gave me <a href="http://www.nata2.info/?path=pictures%2Fmisc%2Fphone_camera%2Fphotolog&amp;img=1086842973-Nokia6600(889).jpg">a bike</a>. it rules. I am pretty happy with it. it seems to be a nice bike - other than the weird candy cane paint job. I think I am gunna paint it black and make the sides say dumb things. that will be cool. of course. haha. I need to tune it up. I can't decide what to do first. I shoudl probably paint it first and tune it up second. haha. umm. yea. I keep dreamign about popping wheelies and doing tricks. haha. I am lame. and by lame I mean incredible. <br/><br/>i broke down yesterday and purchased another copy of Anna Karenina. I gave up on attempting to find my old copy. mostly cuz I really want to just finish it. what this really means - is that matt and katie will bring me my copy tonight. haha. apparently oprah has <a href="'Anna Karenina' ">decided to promote</a> the translation I am reading. I really don't know how I feel about that. I guess it is good. but I feel like a dork carrying an oprah book around on the train, whereas before I felt like a badass. so yea. I guess I gotta finish it and move on to some light reading: gravity's rainbow. hehe. <br/><br/>RULE<br/><br/><a href="http://www.attackmorgan.com/gallery">here</a> are some pictures that morgan is posting
C#
UTF-8
673
3.109375
3
[]
no_license
public async Task<IActionResult> DownloadFile(string filename) { try { string file = @"c:\temp\test.csv"; var memory = new MemoryStream(); using (var stream = new FileStream(file, FileMode.Open)) { await stream.CopyToAsync(memory); } memory.Position = 0; return File(memory, GetMimeType(file), filename); } catch (Exception e) { return BadRequest(e); } }
Go
UTF-8
11,968
2.828125
3
[]
no_license
package repository import ( "database/sql" "github.com/go-openapi/strfmt" "github.com/jackc/pgx" "strings" "time" "github.com/IvanGorshkov/DB-TP-HW/internal/app/models" "github.com/IvanGorshkov/DB-TP-HW/internal/app/post" ) type PostRepository struct { dbConn *pgx.ConnPool } func NewPostRepository(conn *pgx.ConnPool) post.PostRepository { return &PostRepository{ dbConn: conn, } } func (pr *PostRepository) Update(id int, post models.Post) (*models.Post, error) { var newPost models.Post var created time.Time var parent sql.NullInt64 err := pr.dbConn.QueryRow( `UPDATE posts SET message=COALESCE(NULLIF($1, ''), message), is_edited = CASE WHEN $1 = '' OR message = $1 THEN is_edited ELSE true END WHERE id=$2 RETURNING parent, author, message, is_edited, forum, thread, created`, post.Message, id, ).Scan( &parent, &newPost.Author, &newPost.Message, &newPost.IsEdited, &newPost.Forum, &newPost.Thread, &created, ) newPost.Created = strfmt.DateTime(created.UTC()).String() newPost.ID = id if parent.Valid { post.Parent = int(parent.Int64) } if err != nil { return nil, err } return &newPost, nil } func (pr *PostRepository) GetPostById(id int) (*models.Post, error) { var post models.Post var created time.Time var parent sql.NullInt64 err := pr.dbConn.QueryRow(`SELECT parent, author, message, is_edited, forum, thread, created from posts WHERE id = $1`, id).Scan(&parent ,&post.Author, &post.Message, &post.IsEdited, &post.Forum, &post.Thread, &created) post.ID = id if parent.Valid { post.Parent = int(parent.Int64) } post.Created = strfmt.DateTime(created.UTC()).String() if err != nil { return nil, err } return &post, nil } func (pr *PostRepository) GetPostFullbyId(id int, related string) (*models.PostFull, error) { var parent sql.NullInt64 var created time.Time fullPost := &models.PostFull{ Post: models.Post{}, } if strings.Contains(related, "forum") && strings.Contains(related, "thread") && strings.Contains(related, "user") { var created2 time.Time fullPost.Author = &models.User{} fullPost.Thread = &models.Thread{} fullPost.Forum = &models.Forum{} err := pr.dbConn.QueryRow(` SELECT p.forum, p.thread, p.author, p.message, p.is_edited, p.created, p.parent, th.slug, th.id, th.forum, th.title, th.author, th.message, th.votes, th.created, f.title, f.nickname, f.slug, f.post, f.threads, u.nickname, u.fullname, u.about, u.email FROM posts as p INNER JOIN thread th on th.id = p.thread INNER JOIN forum f on f.slug = p.forum INNER JOIN users u on u.nickname = p.author WHERE p.id = $1 LIMIT 1 `, id).Scan( &fullPost.Post.Forum, &fullPost.Post.Thread, &fullPost.Post.Author, &fullPost.Post.Message, &fullPost.Post.IsEdited, &created, &parent, &fullPost.Thread.Slug, &fullPost.Thread.Id, &fullPost.Thread.Forum, &fullPost.Thread.Title, &fullPost.Thread.Author, &fullPost.Thread.Message, &fullPost.Thread.Votes, &created2, &fullPost.Forum.Title, &fullPost.Forum.User, &fullPost.Forum.Slug, &fullPost.Forum.Posts, &fullPost.Forum.Threads, &fullPost.Author.Nickname, &fullPost.Author.Fullname, &fullPost.Author.About, &fullPost.Author.Email, ) fullPost.Post.ID = id if err != nil { return nil, err } if parent.Valid { fullPost.Post.Parent = int(parent.Int64) } fullPost.Post.Created = strfmt.DateTime(created.UTC()).String() fullPost.Thread.Created = strfmt.DateTime(created2.UTC()).String() return fullPost, err } if strings.Contains(related, "forum") && strings.Contains(related, "thread") { var created2 time.Time fullPost.Thread = &models.Thread{} fullPost.Forum = &models.Forum{} err := pr.dbConn.QueryRow(` SELECT p.forum, p.thread, p.author, p.message, p.is_edited, p.created, p.parent, th.slug, th.id, th.forum, th.title, th.author, th.message, th.votes, th.created, f.title, f.nickname, f.slug, f.post, f.threads FROM posts as p INNER JOIN thread th on th.id = p.thread INNER JOIN forum f on f.slug = p.forum WHERE p.id = $1 LIMIT 1 `, id).Scan( &fullPost.Post.Forum, &fullPost.Post.Thread, &fullPost.Post.Author, &fullPost.Post.Message, &fullPost.Post.IsEdited, &created, &parent, &fullPost.Thread.Slug, &fullPost.Thread.Id, &fullPost.Thread.Forum, &fullPost.Thread.Title, &fullPost.Thread.Author, &fullPost.Thread.Message, &fullPost.Thread.Votes, &created2, &fullPost.Forum.Title, &fullPost.Forum.User, &fullPost.Forum.Slug, &fullPost.Forum.Posts, &fullPost.Forum.Threads, ) fullPost.Post.ID = id if err != nil { return nil, err } if parent.Valid { fullPost.Post.Parent = int(parent.Int64) } fullPost.Post.Created = strfmt.DateTime(created.UTC()).String() fullPost.Thread.Created = strfmt.DateTime(created2.UTC()).String() return fullPost, err } if strings.Contains(related, "forum") && strings.Contains(related, "user") { fullPost.Forum = &models.Forum{} fullPost.Author = &models.User{} err := pr.dbConn.QueryRow(` SELECT p.forum, p.thread, p.author, p.message, p.is_edited, p.created, p.parent, f.title, f.nickname, f.slug, f.post, f.threads, u.nickname, u.fullname, u.about, u.email FROM posts as p INNER JOIN forum f on f.slug = p.forum INNER JOIN users u on u.nickname = p.author WHERE p.id = $1 LIMIT 1 `, id).Scan( &fullPost.Post.Forum, &fullPost.Post.Thread, &fullPost.Post.Author, &fullPost.Post.Message, &fullPost.Post.IsEdited, &created, &parent, &fullPost.Forum.Title, &fullPost.Forum.User, &fullPost.Forum.Slug, &fullPost.Forum.Posts, &fullPost.Forum.Threads, &fullPost.Author.Nickname, &fullPost.Author.Fullname, &fullPost.Author.About, &fullPost.Author.Email, ) fullPost.Post.ID = id if err != nil { return nil, err } if parent.Valid { fullPost.Post.Parent = int(parent.Int64) } fullPost.Post.Created = strfmt.DateTime(created.UTC()).String() return fullPost, err } if strings.Contains(related, "thread") && strings.Contains(related, "user") { var created2 time.Time fullPost.Thread = &models.Thread{} fullPost.Author = &models.User{} err := pr.dbConn.QueryRow(` SELECT p.forum, p.thread, p.author, p.message, p.is_edited, p.created, p.parent, th.slug, th.id, th.forum, th.title, th.author, th.message, th.votes, th.created, u.nickname, u.fullname, u.about, u.email FROM posts as p INNER JOIN thread th on th.id = p.thread INNER JOIN users u on u.nickname = p.author WHERE p.id = $1 LIMIT 1 `, id).Scan( &fullPost.Post.Forum, &fullPost.Post.Thread, &fullPost.Post.Author, &fullPost.Post.Message, &fullPost.Post.IsEdited, &created, &parent, &fullPost.Thread.Slug, &fullPost.Thread.Id, &fullPost.Thread.Forum, &fullPost.Thread.Title, &fullPost.Thread.Author, &fullPost.Thread.Message, &fullPost.Thread.Votes, &created2, &fullPost.Author.Nickname, &fullPost.Author.Fullname, &fullPost.Author.About, &fullPost.Author.Email, ) fullPost.Post.ID = id if err != nil { return nil, err } if parent.Valid { fullPost.Post.Parent = int(parent.Int64) } fullPost.Post.Created = strfmt.DateTime(created.UTC()).String() fullPost.Thread.Created = strfmt.DateTime(created2.UTC()).String() return fullPost, err } if strings.Contains(related, "user") { fullPost.Author = &models.User{} err := pr.dbConn.QueryRow(` SELECT p.forum, p.thread, p.author, p.message, p.is_edited, p.created, p.parent, u.nickname, u.fullname, u.about, u.email FROM posts as p INNER JOIN users u on u.nickname = p.author WHERE p.id = $1 LIMIT 1 `, id).Scan( &fullPost.Post.Forum, &fullPost.Post.Thread, &fullPost.Post.Author, &fullPost.Post.Message, &fullPost.Post.IsEdited, &created, &parent, &fullPost.Author.Nickname, &fullPost.Author.Fullname, &fullPost.Author.About, &fullPost.Author.Email, ) fullPost.Post.ID = id if err != nil { return nil, err } if parent.Valid { fullPost.Post.Parent = int(parent.Int64) } fullPost.Post.Created = strfmt.DateTime(created.UTC()).String() return fullPost, err } if strings.Contains(related, "thread") { var created2 time.Time fullPost.Thread = &models.Thread{} err := pr.dbConn.QueryRow(` SELECT p.forum, p.thread, p.author, p.message, p.is_edited, p.created, p.parent, th.slug, th.id, th.forum, th.title, th.author, th.message, th.votes, th.created FROM posts as p INNER JOIN thread th on th.id = p.thread WHERE p.id = $1 LIMIT 1 `, id).Scan( &fullPost.Post.Forum, &fullPost.Post.Thread, &fullPost.Post.Author, &fullPost.Post.Message, &fullPost.Post.IsEdited, &created, &parent, &fullPost.Thread.Slug, &fullPost.Thread.Id, &fullPost.Thread.Forum, &fullPost.Thread.Title, &fullPost.Thread.Author, &fullPost.Thread.Message, &fullPost.Thread.Votes, &created2, ) fullPost.Post.ID = id if err != nil { return nil, err } if parent.Valid { fullPost.Post.Parent = int(parent.Int64) } fullPost.Post.Created = strfmt.DateTime(created.UTC()).String() fullPost.Thread.Created = strfmt.DateTime(created2.UTC()).String() return fullPost, err } if strings.Contains(related, "forum") { fullPost.Forum = &models.Forum{} err := pr.dbConn.QueryRow(` SELECT p.forum, p.thread, p.author, p.message, p.is_edited, p.created, p.parent, f.title, f.nickname, f.slug, f.post, f.threads FROM posts as p INNER JOIN forum f on f.slug = p.forum WHERE p.id = $1 LIMIT 1 `, id).Scan( &fullPost.Post.Forum, &fullPost.Post.Thread, &fullPost.Post.Author, &fullPost.Post.Message, &fullPost.Post.IsEdited, &created, &parent, &fullPost.Forum.Title, &fullPost.Forum.User, &fullPost.Forum.Slug, &fullPost.Forum.Posts, &fullPost.Forum.Threads, ) fullPost.Post.ID = id if err != nil { return nil, err } if parent.Valid { fullPost.Post.Parent = int(parent.Int64) } fullPost.Post.Created = strfmt.DateTime(created.UTC()).String() return fullPost, err } err := pr.dbConn.QueryRow(`SELECT parent, author, message, is_edited, forum, thread, created from posts WHERE id = $1`, id).Scan( &parent ,&fullPost.Post.Author, &fullPost.Post.Message, &fullPost.Post.IsEdited, &fullPost.Post.Forum, &fullPost.Post.Thread, &created) fullPost.Post.ID = id if parent.Valid { fullPost.Post.Parent = int(parent.Int64) } fullPost.Post.Created = strfmt.DateTime(created.UTC()).String() if err != nil { return nil, err } return fullPost, nil }
C#
UTF-8
5,676
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.IO; using System.Security.Claims; using System.Threading.Tasks; using BGTBackend.Models; using BGTBackend.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace BGTBackend.Middleware { internal class TokenProviderMiddleware { private readonly RequestDelegate _next; private readonly TokenProviderOptions _options; private readonly UserRepository _repository = new UserRepository(); public TokenProviderMiddleware(RequestDelegate next, IOptions<TokenProviderOptions> options) { this._next = next; this._options = options.Value; } /// <summary> /// Intercept request to check if the path matches the authenticate route /// </summary> /// <param name="context">Context to send token to if path matches</param> /// <returns>Task that resolves when the request has been handled</returns> public Task Invoke(HttpContext context) { // If path does not match /authentication, continue if (!context.Request.Path.Equals(this._options.Path, StringComparison.OrdinalIgnoreCase)) { return this._next(context); } if (context.Request.Method != "POST") { return Error(context, 405, "Gebruik een POST request om log in data mee te sturen"); } return this.GenerateToken(context); } /// <summary> /// Create a JSON web token if credentials are correct /// </summary> /// <param name="context">Context to get data from and write response to</param> /// <returns>Task that resolves when JSON web token has been sent</returns> /// <exception cref="Exception">Exception thrown when data is incorrect</exception> [ValidateAntiForgeryToken] private async Task GenerateToken(HttpContext context) { string username; string password; try { using (StreamReader sr = new StreamReader(context.Request.Body)) using (JsonTextReader jsonTextReader = new JsonTextReader(sr)) { dynamic response = new JsonSerializer().Deserialize(jsonTextReader); username = response.username; password = response.password; } } catch { await Error(context, 405, "Kan data niet lezen"); return; } User user; try { user = this._repository.GetByUsername(username); if (user == null) throw new Exception("No user exists with username: " + username); } catch (Exception error) { await Error(context, 401, "Gebruiker bestaat niet: " + error.Message); return; } // TODO: Compare passwords here if (!BCrypt.Net.BCrypt.Verify(password, user.Password)) { await Error(context, 401, "Gebruikersnaam of wachtwoord is incorrect"); return; } DateTime now = DateTime.UtcNow; List<Claim> claims = new List<Claim> { new Claim(JwtRegisteredClaimNames.Sub, username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64) }; JwtSecurityToken jwt = new JwtSecurityToken( this._options.Issuer, this._options.Audience, claims, now, now.Add(this._options.Expiration), this._options.SigningCredentials ); string encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); await Send(context, new { access_token = encodedJwt, expires = (int) this._options.Expiration.TotalSeconds }); } /// <summary> /// Write object in JSON to response /// </summary> /// <param name="context">Context to write to</param> /// <param name="message">Message to send</param> /// <returns>Task that completes when response message has been written</returns> private static Task Send(HttpContext context, object message) { context.Response.ContentType = "application/json"; return context.Response.WriteAsync(JsonConvert.SerializeObject(new Response(context.Response, message))); } /// <summary> /// Write error to response /// </summary> /// <param name="context">Context to write to</param> /// <param name="code">HTTP status error code</param> /// <param name="message">Message to send with error</param> /// <returns>Task thta completes when response error has been written</returns> private static Task Error(HttpContext context, int code, string message) { context.Response.ContentType = "application/json"; return context.Response.WriteAsync( JsonConvert.SerializeObject(new Response(context.Response, new Error(code, message)))); } } }
Java
UTF-8
736
1.960938
2
[]
no_license
package com.bioaba.taskmanager.web.controller; import javax.inject.Inject; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.RequestMapping; import com.bioaba.taskmanager.core.facade.BioDatabaseFacade; import com.bioaba.taskmanager.persistence.entity.BioDatabase; import com.bioaba.taskmanager.web.controller.base.AbstractCrudController; import com.bioaba.taskmanager.web.validation.BioDatabaseValidator; @ControllerAdvice @RequestMapping("/biodatabase") public class BioDatabaseController extends AbstractCrudController<BioDatabase> { @Inject public BioDatabaseController(BioDatabaseFacade facade, BioDatabaseValidator validator){ super(facade, validator); } }
Java
UTF-8
2,628
1.796875
2
[ "Apache-2.0" ]
permissive
/** * Licensed to niosmtp developers ('niosmtp') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * niosmtp licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.normanmaurer.niosmtp.delivery.chain; import java.util.Collection; import java.util.Locale; import me.normanmaurer.niosmtp.SMTPClientFutureListener; import me.normanmaurer.niosmtp.SMTPMessage; import me.normanmaurer.niosmtp.SMTPException; import me.normanmaurer.niosmtp.SMTPRequest; import me.normanmaurer.niosmtp.SMTPResponse; import me.normanmaurer.niosmtp.core.LMTPRequest; import me.normanmaurer.niosmtp.transport.FutureResult; import me.normanmaurer.niosmtp.transport.SMTPClientSession; /** * {@link SMTPClientFutureListenerFactoryImpl} implementation which returns the {@link SMTPClientFutureListener}'s while processing * the LMTP Transaction * * @author Norman Maurer * */ public class LMTPClientFutureListenerFactoryImpl extends SMTPClientFutureListenerFactoryImpl { @Override public SMTPClientFutureListener<FutureResult<SMTPResponse>> getListener(SMTPClientSession session, SMTPRequest request) throws SMTPException { if (request == null) { return LMTPWelcomeResponseListener.INSTANCE; } else { String cmd = request.getCommand().toUpperCase(Locale.UK); if (LMTPRequest.LHLO_COMMAND.equals(cmd)) { return EhloResponseListener.INSTANCE; } else { return super.getListener(session, request); } } } @Override public SMTPClientFutureListener<FutureResult<SMTPResponse>> getListener(SMTPClientSession session) throws SMTPException { return LMTPWelcomeResponseListener.INSTANCE; } @Override public SMTPClientFutureListener<FutureResult<Collection<SMTPResponse>>> getListener(SMTPClientSession session, SMTPMessage input) throws SMTPException { return LMTPPostDataResponseCallback.INSTANCE; } }
JavaScript
UTF-8
1,408
3.546875
4
[ "LicenseRef-scancode-public-domain" ]
permissive
// peso / altura * altura // var tdAltura = document.getElementById('altura-2'); // var tdPeso = document.getElementById('peso-2'); // var peso2 = tdPeso.textContent; // var Altura2 = tdAltura.textContent; // var paciente2 = {peso : peso2, altura : Altura2 }; // var tdAltura = document.getElementById('altura-1'); // var tdPeso = document.getElementById('peso-1'); // var peso1 = tdPeso.textContent; // var Altura1 = tdAltura.textContent; // var paciente1 = {peso : peso1, altura: Altura1 }; // var pacientes = [paciente1 , paciente2]; var trsPacientes = document.getElementsByClassName('paciente'); //Array de trs var ; for(var posicaoAtual = 0; posicaoAtual <= trsPacientes.length - 1; posicaoAtual++){ var pacienteTr = trsPacientes[posicaoAtual]; var tdNome = pacienteTr.getElementsByClassName('info-nome')[0]; var tdPeso = pacienteTr.getElementsByClassName('info-peso')[0]; var tdaltura = pacienteTr.getElementsByClassName('info-altura')[0]; var paciente = {nome: tdNome.textContent, peso: tdPeso.textContent, altura: tdaltura.textContent}; if(paciente.altura != 0){ var imc = paciente.peso / (paciente.altura * paciente.altura); var tdImc = pacienteTr.getElementsByClassName('info-imc')[0]; tdImc.textContent = imc; console.log(imc); }else{ console.log("não executei porque altura é igual a 0 e não posso dividir por zero"); } posicaoAtual++ }
Java
UTF-8
9,226
1.84375
2
[ "Apache-2.0" ]
permissive
package org.summerb.approaches.jdbccrud.impl.relations; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Required; import org.springframework.util.CollectionUtils; import org.summerb.approaches.jdbccrud.api.EasyCrudService; import org.summerb.approaches.jdbccrud.api.dto.HasId; import org.summerb.approaches.jdbccrud.api.dto.PagerParams; import org.summerb.approaches.jdbccrud.api.dto.relations.ManyToManyDto; import org.summerb.approaches.jdbccrud.api.dto.relations.Ref; import org.summerb.approaches.jdbccrud.api.dto.tools.EasyCrudDtoUtils; import org.summerb.approaches.jdbccrud.api.exceptions.EntityNotFoundException; import org.summerb.approaches.jdbccrud.api.query.Query; import org.summerb.approaches.jdbccrud.api.relations.EasyCrudM2mService; import org.summerb.approaches.jdbccrud.impl.EasyCrudServicePluggableImpl; import org.summerb.approaches.security.api.exceptions.NotAuthorizedException; import org.summerb.approaches.validation.FieldValidationException; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; /** * This is default impl for {@link EasyCrudM2mService}. * * IMPORTANT: By default this impl will auto generate entity type message code * based on referencer and referencee, like referencer.to.referencee. * * IMPORTANT: Queries will result in 2 round trips to the server (find ids, * retrieve dtos) which is not perfect in terms of the performance. In case it's * critical consider using your own DAO implementation that can make use of * joins -OR- consider caching options. * * NOTE: Proposed authorization approach is to re-use (with wrapper * {@link M2mAuthorizationWireTapImpl}) referencer's authorization. All reads of * m2m is considered as referencer read, add changes to m2m collection is * considered as update operation to referencer object. * * TODO: Consider providing default impl for cached wrapper for these m2m * relationships * * @author sergeyk * * @param <T1Id> * @param <T1Dto> * @param <T2Id> * @param <T2Dto> */ public class EasyCrudM2mServiceImpl<T1Id, T1Dto extends HasId<T1Id>, T2Id, T2Dto extends HasId<T2Id>> extends EasyCrudServicePluggableImpl<Long, ManyToManyDto<T1Id, T2Id>, EasyCrudM2mDaoImpl<T1Id, T1Dto, T2Id, T2Dto>> implements EasyCrudM2mService<T1Id, T1Dto, T2Id, T2Dto> { private EasyCrudService<T1Id, T1Dto> serviceFrom; private EasyCrudService<T2Id, T2Dto> serviceTo; @Override public void afterPropertiesSet() throws Exception { if (getEntityTypeMessageCode() == null) { setEntityTypeMessageCode(Ref.buildDefaultM2mEntityName(serviceFrom.getEntityTypeMessageCode(), serviceTo.getEntityTypeMessageCode())); } ManyToManyDto<T1Id, T2Id> example = new ManyToManyDto<>(); setDtoClass((Class<ManyToManyDto<T1Id, T2Id>>) example.getClass()); super.afterPropertiesSet(); } @Override public List<T2Dto> findReferenceeByReferencer(T1Id referencerId) { try { Preconditions.checkArgument(referencerId != null, "referencerId is required"); Query q = buildQueryToFindReferenceeByReferencerId(referencerId); List<ManyToManyDto<T1Id, T2Id>> m2mPairs = query(PagerParams.ALL, q).getItems(); if (m2mPairs.size() == 0) { return Collections.emptyList(); } Set<T2Id> referenceeIds = collectReferenceeIds(m2mPairs); return serviceTo.query(PagerParams.ALL, buildQueryToFindObjectsByIds(referenceeIds)).getItems(); } catch (Throwable t) { throw new RuntimeException("Failed to find " + serviceTo.getEntityTypeMessageCode() + " refernced by " + serviceFrom.getEntityTypeMessageCode() + " identified by " + referencerId, t); } } private Query buildQueryToFindObjectsByIds(Set<T2Id> referenceeIds) { T2Id referenceeId = referenceeIds.iterator().next(); Query q; if (referenceeId instanceof String) { q = Query.n().in(ManyToManyDto.FN_ID, referenceeIds.toArray(new String[0])); } else if (referenceeId instanceof Long) { q = Query.n().in(ManyToManyDto.FN_ID, referenceeIds.toArray(new Long[0])); } else { throw new RuntimeException("Unsupported type if Id = " + referenceeId.getClass()); } return q; } private Set<T2Id> collectReferenceeIds(List<ManyToManyDto<T1Id, T2Id>> m2mPairs) { Set<T2Id> ret = new HashSet<>(); for (ManyToManyDto<T1Id, T2Id> pair : m2mPairs) { ret.add(pair.getDst()); } return ret; } private Query buildQueryToFindReferenceeByReferencerId(T1Id referencerId) { Query q; if (referencerId instanceof String) { q = Query.n().eq(ManyToManyDto.FN_SRC, (String) referencerId); } else if (referencerId instanceof Long) { q = Query.n().eq(ManyToManyDto.FN_SRC, (Long) referencerId); } else { throw new RuntimeException("Unsupported type if Id = " + referencerId.getClass()); } return q; } private Query buildQueryToFindReferenceeByReferencerId(Set<T1Id> referencerIds) { T1Id referenceeId = referencerIds.iterator().next(); Query q; if (referenceeId instanceof String) { q = Query.n().in(ManyToManyDto.FN_SRC, referencerIds.toArray(new String[0])); } else if (referenceeId instanceof Long) { q = Query.n().in(ManyToManyDto.FN_SRC, referencerIds.toArray(new Long[0])); } else { throw new RuntimeException("Unsupported type if Id = " + referenceeId.getClass()); } return q; } @Override public Map<T1Id, List<T2Dto>> findReferenceeByReferencers(Set<T1Id> referencerIds) { try { Preconditions.checkArgument(!CollectionUtils.isEmpty(referencerIds), "referencerId is required"); Query q = buildQueryToFindReferenceeByReferencerId(referencerIds); List<ManyToManyDto<T1Id, T2Id>> m2mPairs = query(PagerParams.ALL, q).getItems(); if (m2mPairs.size() == 0) { // Q: Should we fill key set with null (or empty lists)??... return Collections.emptyMap(); } Set<T2Id> referenceeIds = collectReferenceeIds(m2mPairs); List<T2Dto> referencee = serviceTo.query(PagerParams.ALL, buildQueryToFindObjectsByIds(referenceeIds)) .getItems(); Map<T1Id, List<T2Dto>> ret = buildResultForFindReferenceeByReferencer(m2mPairs, referencee); return ret; } catch (Throwable t) { throw new RuntimeException("Failed to find " + serviceTo.getEntityTypeMessageCode() + " refernced by " + serviceFrom.getEntityTypeMessageCode() + " identified by " + Arrays.toString(referencerIds.toArray()), t); } } private Map<T1Id, List<T2Dto>> buildResultForFindReferenceeByReferencer(List<ManyToManyDto<T1Id, T2Id>> m2mPairs, List<T2Dto> referencee) { Map<T2Id, T2Dto> referenceeMap = EasyCrudDtoUtils.toMapById(referencee); Map<T1Id, List<T2Dto>> ret = new HashMap<>(); for (ManyToManyDto<T1Id, T2Id> pair : m2mPairs) { List<T2Dto> curReferencee = ret.get(pair.getSrc()); if (curReferencee == null) { ret.put(pair.getSrc(), curReferencee = new ArrayList<T2Dto>()); } curReferencee.add(referenceeMap.get(pair.getDst())); } return ret; } @Override public ManyToManyDto<T1Id, T2Id> addReferencee(T1Id referencerId, T2Id referenceeId) throws FieldValidationException, NotAuthorizedException { try { ManyToManyDto<T1Id, T2Id> pair = new ManyToManyDto<>(); pair.setSrc(referencerId); pair.setDst(referenceeId); return create(pair); } catch (Throwable t) { Throwables.throwIfInstanceOf(t, NotAuthorizedException.class); throw new RuntimeException("Failed to add reference from " + serviceFrom.getEntityTypeMessageCode() + " identified by " + referencerId + " to " + serviceTo.getEntityTypeMessageCode() + " identified by " + referenceeId, t); } } @Override public void removeReferencee(T1Id referencerId, T2Id referenceeId) throws NotAuthorizedException { try { Query q = Query.n(); addEqQuery(ManyToManyDto.FN_SRC, referencerId, q); addEqQuery(ManyToManyDto.FN_DST, referenceeId, q); ManyToManyDto<T1Id, T2Id> pair = findOneByQuery(q); try { deleteById(pair.getId()); } catch (EntityNotFoundException e) { // that's ok, we wanted it to not exist, it's not there. This // state // is acceptable } } catch (Throwable t) { Throwables.throwIfInstanceOf(t, NotAuthorizedException.class); throw new RuntimeException("Failed to remove reference from " + serviceFrom.getEntityTypeMessageCode() + " identified by " + referencerId + " to " + serviceTo.getEntityTypeMessageCode() + " identified by " + referenceeId, t); } } private void addEqQuery(String fnFrom, Object id, Query q) { if (id instanceof String) { q.eq(fnFrom, (String) id); } else if (id instanceof Long) { q.eq(fnFrom, (Long) id); } else { throw new RuntimeException("Unsupported type if Id = " + id.getClass()); } } public EasyCrudService<T1Id, T1Dto> getServiceFrom() { return serviceFrom; } @Required public void setServiceFrom(EasyCrudService<T1Id, T1Dto> serviceFrom) { this.serviceFrom = serviceFrom; } public EasyCrudService<T2Id, T2Dto> getServiceTo() { return serviceTo; } @Required public void setServiceTo(EasyCrudService<T2Id, T2Dto> serviceTo) { this.serviceTo = serviceTo; } }
Java
UTF-8
4,405
2.328125
2
[]
no_license
package com.xmheart.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xmheart.mapper.XPWDeptMapper; import com.xmheart.mapper.XPWDoctorMapper; import com.xmheart.model.XPWArticle; import com.xmheart.model.XPWArticleExample; import com.xmheart.model.XPWDept; import com.xmheart.model.XPWDeptExample; import com.xmheart.model.XPWDoctor; import com.xmheart.model.XPWDoctorExample; import com.xmheart.service.DoctorAndDeptService; @Service public class DoctorAndDeptServiceImpl implements DoctorAndDeptService { @Autowired private XPWDoctorMapper xpwDoctorMapper; @Autowired private XPWDeptMapper xpwDeptMapper; @Override public List<XPWDoctor> getDisplayDoctors() { XPWDoctorExample example = new XPWDoctorExample(); example.createCriteria().andIsDisplayedEqualTo(true); example.setOrderByClause("doc_order asc"); List<XPWDoctor> list = xpwDoctorMapper.selectByExample(example); return list; } @Override public List<XPWDept> getOutServiceDepts() { XPWDeptExample example = new XPWDeptExample(); example.createCriteria().andOutServiceEqualTo(true); List<XPWDept> list = xpwDeptMapper.selectByExampleWithBLOBs(example); return list; } @Override public XPWDoctor getDoctorAndDeptById(Long id) { XPWDoctor doctor = xpwDoctorMapper.selectDoctorWithDeptByPrimaryKey(id); return doctor; } @Override public XPWDept getDeptAndDoctorsById(Long id) { XPWDept dept = xpwDeptMapper.selectDeptWithDoctorsByPrimaryKey(id); return dept; } @Override public List<XPWDoctor> getDoctorsByDeptId(Long deptId) { XPWDoctorExample example = new XPWDoctorExample(); example.createCriteria().andDeptIdEqualTo(deptId); example.setOrderByClause("doc_order asc"); List<XPWDoctor> list = xpwDoctorMapper.selectByExample(example); return list; } @Override public XPWDoctor getDoctorById(Long id) { XPWDoctor doctor = xpwDoctorMapper.selectByPrimaryKey(id); return doctor; } @Override public int updateDoctor(XPWDoctor doctor) { int ret = xpwDoctorMapper.updateByPrimaryKeySelective(doctor); return ret; } @Override public int createDoctor(XPWDoctor doctor) { int ret = xpwDoctorMapper.insertSelective(doctor); return ret; } @Override public List<XPWDept> getDepts() { List<XPWDept> list = xpwDeptMapper.selectByExampleWithBLOBs(null); return list; } @Override public XPWDept getDeptById(Long id) { XPWDept dept = xpwDeptMapper.selectByPrimaryKey(id); return dept; } @Override public int updateDept(XPWDept dept) { int ret = xpwDeptMapper.updateByPrimaryKeySelective(dept); return ret; } @Override public int createDept(XPWDept dept) { int ret = xpwDeptMapper.insertSelective(dept); return ret; } @Override public List<XPWDoctor> searchDoctorByName(String name) { List<XPWDoctor> list = xpwDoctorMapper.selectDoctorByName(name); return list; } @Override public int swapDocOrder(Long doctorId1, Long doctorId2) { XPWDoctor doctor1 = xpwDoctorMapper.selectByPrimaryKey(doctorId1); XPWDoctor doctor2 = xpwDoctorMapper.selectByPrimaryKey(doctorId2); //只有置顶的文章才可以交换order if (!doctor1.getIsDisplayed() || !doctor2.getIsDisplayed()) { return -1; } // if (doctor1.getColumnId() != doctor2.getColumnId()) { // return -1; // } int order1 = doctor1.getDocOrder(); doctor1.setDocOrder(doctor2.getDocOrder()); xpwDoctorMapper.updateByPrimaryKey(doctor1); doctor2.setDocOrder(order1); xpwDoctorMapper.updateByPrimaryKey(doctor2); return 0; } @Override public int getMaxOrder() { XPWDoctorExample example = new XPWDoctorExample(); example.createCriteria().andIsDisplayedEqualTo(true); example.setOrderByClause("doc_order desc limit 1"); List<XPWDoctor> list = xpwDoctorMapper.selectByExample(example); if (list.size() != 0) { return list.get(0).getDocOrder(); } else { return 0; } } }
JavaScript
UTF-8
510
2.9375
3
[]
no_license
function rotateImage(a) { let len = a.length; for (let layer = 0; layer < len/2; layer++) { let first = layer; let last = len - 1 - layer; for (let i = first; i < last; i++) { let offset = i - first; let temp = a[first][i]; a[first][i] = a[last-offset][first]; a[last-offset][first] = a[last][last-offset]; a[last][last-offset] = a[i][last]; a[i][last] = temp; } } return a; }
SQL
UTF-8
1,353
3.6875
4
[]
no_license
select row_number() over() as id, '305' as sistema, 'processo-participante-proposta' as tipo_registro, '@' as separador, * from ( select distinct a.clicodigo, a.minano as ano_processo, a.minnro as nro_processo, a.aprsequencia as sequencial, concat(a.minnro, a.aprsequencia)::integer as nro_ata, left(a.aprdata::varchar, 4)::integer as ano_ata, coalesce (a.aprobservacao, 'MIGRACAO CLOUD - ATA SEM TEXTO') as texto_ata, (select id_gerado from public.controle_migracao_registro_compras where hash_chave_dsk = md5(concat(305, 'processo', a.clicodigo, a.minano, a.minnro))) as id_processo, (select id_gerado from public.controle_migracao_registro_compras where hash_chave_dsk = md5(concat(305, 'processo-sessao', a.clicodigo, a.minano, a.minnro))) as id_sessao, 386 as tipo_ata, (select id_gerado from public.controle_migracao_registro_compras where hash_chave_dsk = md5(concat(305, 'processo-sessao-ata', a.clicodigo, a.minano, a.minnro, '@', a.aprsequencia))) as id_gerado from wco.tbatalicitacao a where a.clicodigo = {{clicodigo}} and a.minano = {{ano}} and a.minnro in (81) order by 1, 2 desc, 3 desc ) tab where id_gerado is null and id_processo is not null and id_sessao is not null --and id_processo in (213969, 214060, 213812, 213811, 214200, 214180, 213809, 213807, 214166, 213803, 213802, 214107)
C++
UTF-8
1,247
2.890625
3
[]
no_license
#pragma once #include "Drawable.h" #include "Basket.h" #include "ActualBasket.h" #include <string> ///adapter class for the basket class CBasketAdapter : public CDrawable { public: ///constructor ///\param name ///\param x ///\param y CBasketAdapter(const std::wstring name, int x, int y); /** Default constructor disabled */ CBasketAdapter() = delete; /** Copy constructor disabled */ CBasketAdapter(const CBasketAdapter&) = delete; /** Assignment operator disabled */ void operator=(const CBasketAdapter&) = delete; ///draw function ///\param graphics void Draw(Gdiplus::Graphics* graphics) { mBasket->DrawBasket(graphics); } /** Test to see if we have been clicked on by the mouse * \param pos Position to test * \return true if clicked on */ bool HitTest(Gdiplus::Point pos) { return false; } /** * Add fruit to the basket * \param fruit Vector of fruit objects */ void AddToBasket(std::vector <std::shared_ptr<CFruit>> fruit) { mBasket->AddToBasket(fruit); } /** * Empty all fruit from the basket */ void EmptyBasket() { mBasket->EmptyBasket(); } private: ///member variable to hold the basket we are wrapping std::shared_ptr<CBasket> mBasket; };
Python
UTF-8
578
3.03125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Jul 11 16:52:05 2019 @author: home """ import numpy as np file = open("in1.txt","r") n = int(file.readline()) print(type(n)) A = np.zeros(shape=(n,n)) B = np.zeros(shape=(n,1)) for i in range(0,n): line = str(file.readline()) a = np.array(line.split(" ")) for j in range(0,n): A.itemset((i,j),float(a[j])) for i in range(0,n): tmp = float(file.readline()) B.itemset(i,tmp) file.close()
Python
UTF-8
444
4.1875
4
[]
no_license
#题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? x=0 y=1 z=1#x,y,z分别代表上个月,本月,下个月兔子对数 n=int(input("请输入月份n:")) for i in range(n): if n<2: z=1 else: z=x+y x=y y=z print("兔子总数为",2*y)
Shell
UTF-8
14,849
4.03125
4
[ "MIT" ]
permissive
#!/usr/bin/env bash #:title: Divine Bash utils: git #:author: Grove Pyree #:email: grayarea@protonmail.ch #:revdate: 2022.07.13 #:revremark: When checking Github repo existence via git, use https #:created_at: 2019.09.13 ## Part of Divine.dotfiles <https://github.com/divine-dotfiles/divine-dotfiles> # ## A set of utilities designed to clone Git repositories. # # Marker and dependencies readonly D__UTL_GIT=loaded d__load procedure prep-sys d__load util workflow d__load procedure check-gh #> d___clone_git_repo [-fgGs]... [-b BRANCH] [-t TITLE] [--] \ #> REPO_HANDLE REPO_PATH # ## INTERNAL USE ONLY # ## Makes a clone of Git repository REPO_HANDLE into REPO_PATH directory, which #. must be empty/non-existent. # ## Options: #. -b BRANCH, --branch BRANCH #. - Checkout branch BRANCH, instead of master. #. -t TITLE, --title TITLE #. - Use TITLE in debug output to refer to cloned repository. # ## Repo type options: #. -g, --generic - Treat REPO_HANDLE as generic git repo path, e.g., a local #. directory path. #. -G, --github - (default) Treat REPO_HANDLE as short handle of Github #. repo, e.g., 'username/repository'. # ## Deepness options: #. -f, --full - Make a full clone. #. -s, --shallow - (default) Make a shallow clone, of only the one branch. # ## Returns: #. 0 - Successfully cloned. #. 1 - Otherwise. # d___clone_git_repo() { # Pluck out options, round up arguments local args=() arg ii local cbrn cttl ctgh=true ctsh=true; unset cbrn cttl while (($#)); do arg="$1"; shift; case $arg in -*) case ${arg:1} in -) args+=("$@"); break;; b|-branch) if (($#)); then cbrn="$1"; shift; fi;; t|-title) if (($#)); then cttl="$1"; shift; fi;; f|-full) ctsh=false;; s|-shallow) ctsh=true;; g|-generic) ctgh=false;; G|-github) ctgh=true;; '') :;; -*) :;; *) for ((ii=1;ii<${#arg};++ii)); do case ${arg:ii:1} in b) if (($#)); then cbrn="$1"; shift; fi;; t) if (($#)); then cttl="$1"; shift; fi;; f) ctsh=false;; s) ctsh=true;; g) ctgh=false;; G) ctgh=true;; *) :;; esac; done;; esac;; *) args+=("$arg");; esac; done # Dice parsed options and arguments local crph="${args[0]}" crpp="${args[1]}" copt=() if [ -z ${cttl+isset} ]; then if $ctgh; then cttl="Github repository '$crph'" else cttl="Git repository at '$crph'" fi fi $ctgh && crph="https://github.com/$crph.git" if ! [ -z ${cbrn+isset} ]; then cttl+=" (branch '$cbrn')" copt+=( -b "$cbrn" ) fi cttl="clone of $cttl" if $ctsh; then cttl="shallow $cttl" copt+=( --depth=1 ) fi # Proceed to cloning d__context -- notch d__context -- push "Making a $cttl" d__context -- push "Cloning into: '$crpp'" d__cmd --q-- git clone "${copt[@]}" \ --REPO_SRC-- "$crph" --REPO_DST-- "$crpp" \ --else-- 'Failed to clone' || return 1 d__context -- pop d__context -t 'Done' -- pop "Successfully made a $cttl" d__context -- lop return 0 } #> d___dl_gh_repo [-cw]... [-b BRANCH] [-t TITLE] [--] REPO_HANDLE REPO_PATH # ## INTERNAL USE ONLY # ## Downloads using curl (or wget) the latest copy of Github repository #. REPO_HANDLE (in the form 'username/repository'), and untar it into REPO_PATH #. directory. # ## Options: #. -b BRANCH, --branch BRANCH #. - Download branch BRANCH, instead of master. #. -t TITLE, --title TITLE #. - Use TITLE in debug output to refer to downloaded #. repository. # ## Retrieval util options: #. -c, --curl - (default) Download using 'curl'. #. -w, --wget - Download using 'wget'. # ## Returns: #. 0 - Successfully downloaded and untarred. #. 1 - Otherwise. # d___dl_gh_repo() { # Pluck out options, round up arguments local args=() arg ii local dbrn dttl dutl=curl; unset dbrn dttl while (($#)); do arg="$1"; shift; case $arg in -*) case ${arg:1} in -) args+=("$@"); break;; b|-branch) if (($#)); then dbrn="$1"; shift; fi;; t|-title) if (($#)); then dttl="$1"; shift; fi;; c|-curl) dutl=curl;; w|-wget) dutl=wget;; '') :;; -*) :;; *) for ((ii=1;ii<${#arg};++ii)); do case ${arg:ii:1} in b) if (($#)); then dbrn="$1"; shift; fi;; t) if (($#)); then dttl="$1"; shift; fi;; c) dutl=curl;; w) dutl=wget;; *) :;; esac; done;; esac;; *) args+=("$arg");; esac; done # Dice parsed options and arguments local drph="${args[0]}" drpp="${args[1]}" dopt=() [ -z ${dttl+isset} ] && dttl="Github repository '$drph'" drph="https://api.github.com/repos/${args[0]}/tarball" if ! [ -z ${dbrn+isset} ]; then dttl+=" (branch '$dbrn')" drph+="/$dbrn" fi dttl="copy of $dttl" case $dutl in curl) dutl=( curl -sL ) dttl+=' via curl';; wget) dutl=( wget -qO - ) dttl+=' via wget';; esac # Proceed to downloading/untarring d__context -- notch d__context -- push "Downloading a $dttl" d__context -- push "Untarring into: '$drpp'" d__pipe --q-- ${dutl[@]} --REPO_SRC-- "$drph" \ --pipe-- tar --strip-components=1 -C --REPO_DST-- "$drpp" -xzf - \ --else-- 'Failed to download/untar' || return 1 d__context -- pop d__context -t 'Done' -- pop "Successfully downloaded a $dttl" d__context -- lop return 0 } #> d___pull_git_remote [-aBd]... [-r REMOTE] [-b BRANCH] [-t TITLE] [--] \ #> REPO_PATH # ## INTERNAL USE ONLY # ## Within a directory REPO_PATH, which must be a cloned Git repository, pulls #. using Git the remote version of the current branch. # ## If cloned repository is shallow and a branch other than current is #. requested, changes repository options to fetch all other branches. Refuses #. to touch REPO_PATH, if its working tree is dirty. # ## Options: #. -r REMOTE, --remote REMOTE #. - Pulls from REMOTE, instead of origin. #. -b BRANCH, --branch BRANCH #. - Before pulling, ensure BRANCH is checked out. If BRANCH #. is not the current branch, then, if allowed, fetch latest #. revision and switch, don't pull afterward. #. -t TITLE, --title TITLE #. - Use TITLE in debug output to refer to updated repository. # ## Branch changing options: #. -B, --keep-branch - (default) Under no circumstances allow to change #. current branch. #. -d, --dev-only - Only allow changing current branch from master to dev #. or vice versa. Blocks only cases where current branch #. does need to be changed. #. -a, --any-branch - Allow any changes to current branch. # ## Returns: #. 0 - Successfully pulled from the remote. #. 1 - Error occurred somewhere along the way. #. 2 - Refused to even begin. # d___pull_git_remote() { # Pluck out options, round up arguments local args=() arg ii local prem pbrn pttl pchb=false pchd=false; unset prem pbrn pttl while (($#)); do arg="$1"; shift; case $arg in -*) case ${arg:1} in -) args+=("$@"); break;; r|-remote) if (($#)); then prem="$1"; shift; fi;; b|-branch) if (($#)); then pbrn="$1"; shift; fi;; t|-title) if (($#)); then pttl="$1"; shift; fi;; B|-keep-branch) pchb=false pchd=false;; d|-dev-only) pchb=true pchd=true;; a|-any-branch) pchb=true pchd=false;; '') :;; -*) :;; *) for ((ii=1;ii<${#arg};++ii)); do case ${arg:ii:1} in r) if (($#)); then prem="$1"; shift; fi;; b) if (($#)); then pbrn="$1"; shift; fi;; t) if (($#)); then pttl="$1"; shift; fi;; B) pchb=false pchd=false;; d) pchb=true pchd=true;; a) pchb=true pchd=false;; *) :;; esac; done;; esac;; *) args+=("$arg");; esac; done # Dice parsed options and arguments local pspc= prpp="${args[0]}" [ -z ${pttl+isset} ] && pttl="cloned Git repository" if [ -z ${prem+isset} ]; then prem=origin else pspc+="from remote '$prem'" fi if ! [ -z ${pbrn+isset} ]; then [ -n "$pspc" ] && pspc+=', ' pspc+="to branch '$pbrn'" fi [ -n "$pspc" ] && pttl+=" ($pspc)" # Extract path; change into it d__context -- notch d__context -- push "Updating a $pttl" d__context -- push "Pulling into: '$prpp'" d__cmd --sb-- pushd -- --REPO_PATH-- "$prpp" \ --else-- 'Unable to pull updates into inaccessible directory' \ || return 2 # Ensure working tree is clean, or bail out if [ -n "$( git status --porcelain --untracked-files=no 2>/dev/null )" ]; then d__fail -t 'Refusing to pull' -- \ 'There are manual uncommitted changes in the directory' popd &>/dev/null return 2 fi # Figure out current branch local cbrn="$( git rev-parse --abbrev-ref HEAD 2>/dev/null )" prtc=0 case $cbrn in '') d__fail -- 'Unable to detect name of current Git branch' prtc=2 ;; 'HEAD') d__fail -- "Unable to pull in 'detached HEAD' state" prtc=2 ;; esac (($prtc)) && { popd &>/dev/null; return $prtc; } # Check if branch change rules allow to proceed local chbr=false achb=false [ -z ${pbrn+isset} ] && pbrn="$cbrn" if [ "$cbrn" = "$pbrn" ]; then : elif $pchb; then if $pchd; then case $cbrn in master|dev) :;; *) d__fail -- "Refusing to change current branch from '$cbrn'" prtc=2 ;; esac case $pbrn in master|dev) :;; *) d__fail -- "Refusing to change current branch to '$pbrn'" prtc=2 ;; esac fi chbr=true else d__fail -- "Refusing to change current branch from '$cbrn'" prtc=2 fi (($prtc)) && { popd &>/dev/null; return $prtc; } # Fork based on whether cnanging current branch if $chbr; then d__context -- push "Switching from branch '$cbrn' to branch '$pbrn'" else d__context -- push "Pulling latest revision of branch '$pbrn'" fi # Validate name of the remote; extract remote URL if ! git ls-remote --exit-code "$prem" "$pbrn" &>/dev/null; then d__fail -- "Unable to find branch '$pbrn' on remote '$prem'" popd &>/dev/null return 2 fi local psrc="$( git config --get remote.$prem.url 2>/dev/null )" if [ -z "$psrc" ]; then d__fail -- "Remote '$prem' doesn't appear to have an address" popd &>/dev/null return 2 fi if [[ $psrc = 'https://github.com/'* ]]; then psrc="${psrc%.git}" psrc="Github repository '${psrc#https://github.com/}'" else psrc="Git repository at '$psrc'" fi # Fork based on whether changing branch or not if $chbr; then # Announce plans d__context -- push "Pulling updates from '$psrc'," \ "switching to branch '$pbrn', and rebasing local commits on top" # Set proper Git options local curc reqc unic curc="$( git config --get remote.$prem.fetch 2>/dev/null )" reqc="+refs/heads/$pbrn:refs/remotes/$prem/$pbrn" unic="+refs/heads/*:refs/remotes/$prem/*" case $curc in # "$reqc") :;; "$unic") :;; *) d__cmd --sb-- git config "remote.$prem.fetch" --CFG_STR-- "$unic" \ --else-- 'Failed to set required Git configuration' \ || { popd &>/dev/null; return 1; };; esac # First, fetch updates for target branch local ufms="Failed to fetch updates for branch '$pbrn' from remote '$prem'" d__cmd --q-- git fetch "$prem" "$pbrn" \ --else-- "$ufms" || { popd &>/dev/null; return 1; } # Checkout required branch, which should definitely exist after fetch d__cmd --q-- git checkout "$pbrn" \ --else-- "Failed to change current branch to '$pbrn'" \ || { popd &>/dev/null; return 1; } # Finally, rebase any local commits on top of updates from remote ufms="Failed to rebase local commits in '$pbrn'" ufms+=" on top of its remote version '$prem/$pbrn'" d__cmd --q-- git rebase "$prem/$pbrn" "$pbrn" \ --else-- "$ufms" || { popd &>/dev/null; return 1; } # Finish up popd &>/dev/null d__context -t 'Done' -- pop \ "Successfully pulled updates and changed current branch to '$pbrn'" d__context -- lop return 0 else # With current branch, simple pull --rebase will do d__context -- push "Pulling updates from '$psrc'" \ "for current branch '$cbrn', and rebasing local commits on top" local ufms="Failed to pull updates for branch '$pbrn' from remote '$prem'" ufms+=' and rebase local commits on top of remote ones' d__cmd --q-- git pull --rebase --stat "$prem" "$cbrn" \ --else-- "$ufms" || { popd &>/dev/null; return 1; } popd &>/dev/null d__context -t 'Done' -- pop "Successfully pulled updates from $psrc" d__context -- lop return 0 fi } #> d___gh_repo_exists REPO_HANDLE # ## INTERNAL USE ONLY # ## Checks whether the handle REPO_HANDLE (in the form 'username/repository') #. describes an existing and accessible Github repository. # ## Uses in the global scope: #> $D__GH_METHOD - Global indicator of whether proper instruments for #. interaction with Github are available. # ## Returns: #. 0 - A Github repository by that handle exists and is accessible. #. non-zero - Otherwise. # d___gh_repo_exists() { case $D__GH_METHOD in g) git ls-remote "https://github.com/$1.git" &>/dev/null;; c) grep -q 200 < <( curl -I "https://api.github.com/repos/$1" \ 2>/dev/null | head -1 );; w) grep -q 200 < <( wget -q --spider --server-response \ "https://api.github.com/repos/$1" 2>&1 | head -1 );; *) return 1;; esac } #> d___path_is_gh_clone REPO_PATH REPO_HANDLE # ## INTERNAL USE ONLY # ## Checks whether the existing directory at REPO_PATH is a Git clone of the #. Github repository REPO_HANDLE (in the form 'username/repository'). # ## Returns: #. 0 - The directory is accessible, Git is available, and the directory is a #. Git clone of the given repository. #. 1 - Otherwise: the directory is accessible, but either Git is unavailable, #. or the directory is not a Git clone of the given repository. #. 2 - The directory is inaccessible. # d___path_is_gh_clone() { if pushd -- "$1" &>/dev/null; then if [ "$( git remote get-url origin 2>/dev/null )" \ = "https://github.com/$2.git" ] then popd &>/dev/null; return 0 else popd &>/dev/null; return 1; fi fi; return 2 }
Markdown
UTF-8
5,307
3.15625
3
[ "MIT", "Apache-2.0" ]
permissive
--- layout: post title: "The Flower Pot Key" date: 2020-11-01 23:50:03 +0000 permalink: the_flower_pot_key --- *The one huge vulnerability I almost left in my accounts system.* At the risk of contributing to the ever-growing “holiday creep,” this project truly reminded me of the value of making a list and checking it twice. My project is a Sinatra-based web application prototype for the service I am building, Paperless Playhouse(1). It allows registered users to create, save, view, and update (or delete) digital programs listing credits for theatrical productions. While not yet quite as attractive as I would want each program to look, I felt pretty happy about the basic functioning of the app as I was about to turn it in. However, going through the spec checklist revealed a near-fatal flaw. My imaginary user “Dandy Lion” had a neat little list of programs they’d created, but when I clicked one to view it, and I was taken to a completely different program, with another title, by another user. What was going on? A closer look at my programs.erb file revealed the issue. My code for showing each program listing was as follows: ``` <% @programs.each_with_index do |program, i|%> <h2><%= (i + 1) %>. <%= program.title %></h2> <h3><%= program.dates %></h3> <a href="/programs/<%= (i + 1) %>">See This Program Draft</a> <% end %> ``` For those who haven’t spotted it already, the problem was an inapplicable use of my i variable from the #each_with_index method. This code assumed that the program’s id number in the database would be the same as its index number in a ruby array (plus 1). This would be all well and good if the app was tracking only one persons show programs, but the array @programs is a curated list of only programs by the current user. I think the reason I didn’t catch this earlier was that in the beginning, I was only working with one imaginary user— I wanted to make sure all the basic CRUD functions were in working order before focusing too much on user verification(2). But all in all, it seemed a silly mistake, easily fixed by switching that one line of code to: ``` <a href="/programs/<%= program.id %>">See This Program Draft</a> ``` But wait! This way leaves it open for any user to view any program. Though their account will only show them programs they’ve created in their list of all programs, nothing stops them from viewing any program they wish if they know its url. It’s the equivalent of locking the front door but leaving a spare key blatantly sticking out of a flower pot. Of course, eventually, the full application would allow a program to be publicly available for the duration of a play’s run, but since this piece is focused on creating and tweaking drafts, this is highly undesirable— we don’t want anyone to be able to peek at material that the creator does not consider ready yet. Though I was taken aback that such a large flaw made it this far into my code, the good news was that it had a relatively simple fix— in fact, only one line of code needed to be changed. Originally, I had tried to protect the secrecy of a program draft by using: ``` <% if User.is_logged_in?(session) %> ``` —which is all well and good for just making sure a user is logged in, but after that, does nothing to shield the content from being seen by any user as long as they have an account to log in to— this code does not care whether the user is logged in to the same account that created the show program, just that they are logged in to ANY account at all. The new code: ``` <% if User.is_logged_in?(session) && User.current_user(session).id == @program.user_id %> ``` —takes the necessary extra step of making sure that the current_user’s id number is the same as the id number of the user that the program belongs_to. For anyone attempting a similar system— mind your metaphorical “flower pot keys”! ### Other Miscellaneous Observations: * I was definitely underutilizing my #current_user method in a lot of other areas as well at first. There were a lot of GET or POST routes where I found myself trying to force an @user= for use in the view, even when it was unwieldy to do so. Switching over to #current_user streamlined my program a lot. * When I did a lesson lab with bcrypt, it seemed like starring out the letters of the password happened automatically— but it seems not. One of my short term goals for improving this project is to black out the password input in some way. * On the note of things I want to tweak, I’m not sure it’s correct that all my routes go directly to an erb :(view)— it seems some of these should be changed to redirects. ### Footnotes 1. A non-automated version is already up at [www.paperlessplayhouse.com](http://) 2. This also led to a brief holdup when I tried to do without users entirely in the beginning— I only made a programs table to start and then was surprised and confused when I could not create any programs. A classmate (Thank you, Kayla!) clued me in that you can not create any objects of a class with a belongs_to relationship without an instance for it to belong to— which makes sense in retrospect, but caused a complete panic at the time about why .create wasn’t working!
Markdown
UTF-8
3,630
3.21875
3
[]
no_license
# 1. Algorithm ## 删除排序数组中的重复项 (Remove Duplicates from Sorted Array) ### 题目描述 https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/ ### 算法实现 ```java public static int removeDuplicates(int[] nums) { // 参数合法性检查 // 边界检查 if (nums == null || nums.length <= 0) { return 0; } if (nums.length == 1) { return 1; } // 正常结束:nums遍历完成 // 异常结束 // 提前退出 // 计数器要++ // 循环要结束 // 有效的最后一个元素索引号lastValidIndex // 当前有效长度len,默认为0,如果nums不为空则至少为1 // 下一个要比较的元素索引号nextCompareIndex // if (lastValidIndex==nextCompareIndex || nums[lastValidIndex]==nums[nextCompareIndex]) then continue // if (lastValidIndex!=nextCompareIndex) {if (lastValidIndex+1==nextCompareIndex)lastValidIndex=nextCompareIndex;nextCompareIndex++ else nums[++lastValidIndex]=nums[nextCompareIndex];nextCompareIndex++} int lastValidIndex = 0; int nextCompareIndex = 0; while (++nextCompareIndex < nums.length) { // 值相同则忽略 if (nums[lastValidIndex] == nums[nextCompareIndex]) { continue; } // lastValidIndex指针后移1位 lastValidIndex++; // 如果lastValidIndex与nextCompareIndex相同,则只须将指针分别后移一位 // 否则,将nextCompareIndex对应的元素移到lastValidIndex if (lastValidIndex != nextCompareIndex) { nums[lastValidIndex] = nums[nextCompareIndex]; } } return lastValidIndex + 1; } ``` 时间复杂度为O(n),空间复杂度为O(1) # 2. Review ## 技术文章 Hadoop: Setting up a Single Node Cluster. http://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-common/SingleCluster.html ## 总结 Hadoop单节点、单机虚拟集群、Yarn简单安装配置教程。 # 3. Technique org.apache.commons.lang3.math.NumberUtils.isParsable ```java org.apache.commons.lang3.math.NumberUtils String[] array = { null, "", " ", "\t", "a", "a1", "0", "1", "-1", "58.9", "398.75", "-30.0", "1.2a", "3b5", "3e2", "0x1F", "012" }; Arrays.asList(array).forEach(s -> { // Valid numbers include hexadecimal marked with the 0x or 0X qualifier, octal numbers, scientific notation and numbers marked with a type qualifier (e.g. 123L). // 数字、小数、十六进制、八进制、科学计数 System.out.println(String.format("NumberUtils.isCreatable(%s) = %s", s, NumberUtils.isCreatable(s))); System.out.println(String.format("NumberUtils.isNumber(%s) = %s", s, NumberUtils.isNumber(s))); // Parsable numbers include those Strings understood by Integer.parseInt(String), Long.parseLong(String), Float.parseFloat(String) or Double.parseDouble(String). // This method can be used instead of catching java.text.ParseException when calling one of those methods. // 数字、小数 System.out.println(String.format("NumberUtils.isParsable(%s) = %s", s, NumberUtils.isParsable(s))); // Checks whether the String contains only digit characters // 纯数字 System.out.println(String.format("NumberUtils.isDigits(%s) = %s", s, NumberUtils.isDigits(s))); System.out.println(); }); ``` # 4. Share **分享文章**:[JVM之压缩指针(CompressedOops)](https://mp.weixin.qq.com/s/TprwjqaSdKVrLO0msi_VUA) **个人公众号**:二进制之路 ![二进制之路](https://note.youdao.com/yws/public/resource/c590ee50585156111cc240ca1943cebf/xmlnote/021950D7D8FC4A8E91B08CDBD68547F2/80591)