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
Python
UTF-8
501
3.78125
4
[]
no_license
# 請參閱A-9頁 import asyncio import time orders = ['牛肉麵', '熱狗', '珍珠奶茶'] # 定義3筆訂單 def now(): return time.time() async def task(name): # 定義協程 (coroutine) print(f'"{name}" 訂單處理中…') await asyncio.sleep(3) print(f'"{name}" 完成') # 定義協程列表 tasks = [task(orders[i]) for i in range(len(orders))] start = now() asyncio.run(asyncio.wait(tasks)) # 用run()非同步執行任務 print(f'花費時間:{now() - start}秒')
Java
UTF-8
3,326
2.390625
2
[ "LicenseRef-scancode-public-domain" ]
permissive
package sq.client.render; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.Render; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import sq.entity.creature.EntityWebShot; import sq.enums.EnumWebType; /** * Sets the texture on the web shot model pre-render. */ public class RenderWeb extends Render { private static ResourceLocation textureWebShot = new ResourceLocation("sq:textures/entities/webshot.png"); private static ResourceLocation textureWebShotPoison = new ResourceLocation("sq:textures/entities/webshot-poison.png"); public RenderWeb() { } public void render(EntityWebShot entityWeb, double posX, double posY, double posZ, float rotationYaw, float rotationPitch) { bindEntityTexture(entityWeb); GL11.glPushMatrix(); { final Tessellator tessellator = Tessellator.instance; GL11.glTranslated(posX, posY, posZ); GL11.glRotatef(entityWeb.prevRotationYaw + (entityWeb.rotationYaw - entityWeb.prevRotationYaw) * rotationYaw - 90.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(entityWeb.prevRotationPitch + (entityWeb.rotationPitch - entityWeb.prevRotationPitch) * rotationYaw, 0.0F, 0.0F, 1.0F); final byte b0 = 0; final float f2 = 0.0F; final float f3 = 0.5F; final float f4 = (0 + b0 * 10) / 32.0F; final float f5 = (5 + b0 * 10) / 32.0F; final float f6 = 0.0F; final float f7 = 0.15625F; final float f8 = (5 + b0 * 10) / 32.0F; final float f9 = (10 + b0 * 10) / 32.0F; final float f10 = 0.05625F; GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glRotatef(45.0F, 1.0F, 0.0F, 0.0F); GL11.glScalef(f10, f10, f10); GL11.glTranslatef(-4.0F, 0.0F, 0.0F); GL11.glNormal3f(f10, 0.0F, 0.0F); tessellator.startDrawingQuads(); tessellator.addVertexWithUV(-7.0D, -2.0D, -2.0D, f6, f8); tessellator.addVertexWithUV(-7.0D, -2.0D, 2.0D, f7, f8); tessellator.addVertexWithUV(-7.0D, 2.0D, 2.0D, f7, f9); tessellator.addVertexWithUV(-7.0D, 2.0D, -2.0D, f6, f9); tessellator.draw(); GL11.glNormal3f(-f10, 0.0F, 0.0F); tessellator.startDrawingQuads(); tessellator.addVertexWithUV(-7.0D, 2.0D, -2.0D, f6, f8); tessellator.addVertexWithUV(-7.0D, 2.0D, 2.0D, f7, f8); tessellator.addVertexWithUV(-7.0D, -2.0D, 2.0D, f7, f9); tessellator.addVertexWithUV(-7.0D, -2.0D, -2.0D, f6, f9); tessellator.draw(); for (int i = 0; i < 4; ++i) { GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F); GL11.glNormal3f(0.0F, 0.0F, f10); tessellator.startDrawingQuads(); tessellator.addVertexWithUV(-8.0D, -2.0D, 0.0D, f2, f4); tessellator.addVertexWithUV(8.0D, -2.0D, 0.0D, f3, f4); tessellator.addVertexWithUV(8.0D, 2.0D, 0.0D, f3, f5); tessellator.addVertexWithUV(-8.0D, 2.0D, 0.0D, f2, f5); tessellator.draw(); } GL11.glDisable(GL12.GL_RESCALE_NORMAL); } GL11.glPopMatrix(); } @Override protected ResourceLocation getEntityTexture(Entity entity) { EntityWebShot web = (EntityWebShot)entity; return web.getType() == EnumWebType.NORMAL ? textureWebShot : textureWebShotPoison; } @Override public void doRender(Entity var1, double var2, double var4, double var6, float var8, float var9) { render((EntityWebShot) var1, var2, var4, var6, var8, var9); } }
Python
UTF-8
721
3.21875
3
[]
no_license
#!/usr/bin/python import numpy as np def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ cleaned_data = [] errors = np.array(predictions[:,0]) - np.array(net_worths[:,0]) sorted_errors_indices = np.argsort(errors) bottom_error_indices = sorted_errors_indices[:int(len(sorted_errors_indices)*0.9)] cleaned_data = [(ages[i], net_worths[i], errors[i]) for i in bottom_error_indices] return cleaned_data
Java
UTF-8
851
2.390625
2
[]
no_license
package com.homeki.core.actions; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import org.hibernate.Session; @Entity @Inheritance(strategy = InheritanceType.JOINED) public abstract class Action { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "action_id") private Action action; public int getId() { return id; } public void setParent(Action action) { this.action = action; } public abstract void execute(Session ses); public abstract String getType(); }
JavaScript
UTF-8
246
2.875
3
[]
no_license
"use strict"; // Get a reference to the element with the id "firstDiv". let firstDiv = document.getElementById("firstDiv"); // Get a reference to the element with the id "secondDiv". let secondDiv = document.getElementById("secondDiv");
TypeScript
UTF-8
256
2.984375
3
[]
no_license
export { }; declare global { interface Array<T> { selfConcat(): T } } Array.prototype.selfConcat = function () { if (!Array.isArray(this[0])) { return this } return this.reduce((acc, curr) => { return acc.concat(curr) }, []) }
JavaScript
UTF-8
2,829
2.734375
3
[]
no_license
import { GET_STUDENTS, DELETE_STUDENT, UPDATE_STUDENT, ADD_STUDENT, _deleteStudent, _updateStudent, _addStudent, _getStudents } from './../actions'; import axios from 'axios'; const updateStudent = (student, history) => { if(student.gpa===''){ student.gpa = null } if(student.schoolId===''){ student.schoolId = null } return (dispatch) => { return axios.put(`/api/students/${student.id}`, student) .then(res => res.data) .then(student => dispatch(_updateStudent(student))) .then(() => history.goBack()) } } const addStudent = (student, history) => { if(student.gpa===''){ student.gpa = null } if(student.schoolId===''){ student.schoolId = null } return (dispatch) => { return axios.post(`/api/students`, student) .then(res => res.data) .then(student => dispatch(_addStudent(student))) .then(() => history.goBack()) } } const deleteStudent = (student, history) => { return (dispatch) => { dispatch(_deleteStudent(student)); return axios.delete(`/api/students/${student.id}`) .then(()=> history.goBack()) } } const getStudents = () => { return (dispatch) => { return axios.get('/api/students') .then(res => res.data) .then(students => dispatch(_getStudents(students))) } } const studentsReducer = (state = [], action) => { switch(action.type){ case GET_STUDENTS: return action.students; case DELETE_STUDENT: return state.filter(student => student.id != action.student.id); case UPDATE_STUDENT: return state.map(student => { return student.id === action.student.id ? action.student : student; }) case ADD_STUDENT: return [ ...state, action.student]; default: return state } } const unenrollStudent = (student) => { const _student = { id: student.id, firstName: student.firstName, lastName: student.lastName, gpa: student.gpa, schoolId: null } return (dispatch) => { return axios.put(`/api/students/${student.id}`, _student) .then(res => res.data) .then(_student => dispatch(_updateStudent(_student)))} } const enrollStudent = (student, _schoolId) => { student.schoolId = _schoolId; return (dispatch) => { return axios.put(`/api/students/${student.id}`, student) .then(res => res.data) .then(_student => dispatch(_updateStudent(_student)))} } export default studentsReducer; export { getStudents, deleteStudent, updateStudent, addStudent, unenrollStudent, enrollStudent }
Markdown
UTF-8
6,806
3.03125
3
[]
no_license
# testweek01 // I keep Running into trouble with Github, it keeps asking for a security token. Sometimes resetting my password helps other times not. Constraint, Linear, Grid and Relative, Coordinator Constraint: Large and complex layout with a flat view hierarchy(means no nested view groups) Linear: aligns all children in a single direction, vertically or horizontally. Relative: Displays child views in relative positions. The position of each view can be specified as relative to sibling elements (such as to the left-of or below another view) or in positions relative to the parent GridLayout: A layout that places its children in a rectangular grid. View , View Group, View Hierachy View is anything can be view on android such as: * Text View * EditText * Button * ImageView * ImageButton * CheckBox * Radio button * RadioGroup * ListView * Spinner * AutoCompleteTextView A view group Holds and defines the properties of a view, View Group is the base class for layouts so their are interchangeable View Hierarchy is the combination of view groups and their views. Resembles the tree data structure Android Manifest: Refers to the Android Manifest File This is an xml file which must be named as AndroidManifest.xml and placed at application root. Every Android app must have AndroidManifest.xml file. AndroidManifest.xml allows us to define, The packages, API, libraries needed for the application. * Basic building blocks of application like activities, services and etc. * Details about permissions. * Set of classes needed before launch. Measurements for View Work: Screen size in Android is grouped into categories small, medium, large, extra large, double-extra and triple-extra. Screen density is the amount of pixels within an area (like inch) of the screen. Generally it is measured in dots-per-inch (dpi). Screen density is grouped as low, medium, high and extra high. Resolution is the total number of pixels in the screen. * dp: Density Independent Pixel, it varies based on screen density . In 160 dpi screen, 1 dp = 1 pixel. Except for font size, use dp always. * dip: dip == dp. In earlier Android versions dip was used and later changed to dp. * sp: Scale Independent Pixel, scaled based on user’s font size preference. Fonts should use sp. * px: our usual standard pixel which maps to the screen pixel. * in: inches, with respect to the physical screen size. * mm: millimeters, with respect to the physical screen size. * pt: 1/72 of an inch, with respect to the physical screen size. Always use dp and sp only. sp for font sizes and dp for everything else. It will make UI compatible for Android devices with different densities. Formula for Conversion between Units px = dp * (dpi / 160) Dalvik: Is a virtual machine that android runs on and also runs anything from applications to code written in the java language Java code is transcoded into Byte code which then converted into a .dex file which the Dalvik VM can read and use Duplicate data used in class files is included only once in the .dex output, which saves space and uses less overhead. The executable files can be modified again when you install an application to make things even more optimized for mobile. Things like byte order swapping and linking data structure and function libraries inline make the files smaller and run better on our devices. Android Runtime (ART): is the managed runtime used by applications and some system services on Android. Uses Ahead-of Time (AOT) compilation, I.e. translate high-level languages into machine code. So it can compile natively. These allow much longer battery life for androids, along with better memory management and less memory usage. The biggest downside is that the first time you compile, it will be significantly longer the first time around Principles of Software Design: Inheritance -Allows a child to inherit member function and variables(In Java you do this with the extends keyword, you can only extend one parent at a time. Encapsulation - (Allows access to the interworking of class and structs, these are know as access modifiers. Such as Public - anyone can see, private members are only visible to the class, protected- only those in the same directory can use member or variables, final - can no longer be access or modified Abstraction -Hides anything that isn’t nessacary for end users and other devs to see or interact with. Ex. Of this include Extended classes, defined methods Polymorphism -Overloading and overriding methods (In java overriding uses @ Overriding) SOLID 5 Software Design Principles intended to make software Designing easy. Those principles are : the Single Responsible principle: Ever object should have limited responsibility and should me Open/Closed principle: Entities like classes, modules and functions that can be extended, can be operated on without affecting their code Liskov substitution principle - Should be able to refractor without changing the underlying structure Interface segration princple- breaking stuff up into parts and having it clear is better than one gigantic program I Dependancy inversion principle -Code should be based on abstract so main implementation is not affected HashMap is non-synchronized it is not-thread safe and hashtable is thread-safe Principles of Software Design: Inheritance -Allows a child to inherit member function and variables(In Java you do this with the extends keyword, you can only extend one parent at a time. Encapsulation - (Allows access to the interworking of class and structs, these are know as access modifiers. Such as Public - anyone can see, private members are only visible to the class, protected- only those in the same directory can use member or variables, final - can no longer be access or modified Abstraction -Hides anything that isn’t nessacary for end users and other devs to see or interact with. Ex. Of this include Extended classes, defined methods Polymorphism -Overloading and overriding methods (In java overriding uses @ Overriding) SOLID 5 Software Design Principles intended to make software Designing easy. Those principles are : the Single Responsible principle: Ever object should have limited responsibility and should me Open/Closed principle: Entities like classes, modules and functions that can be extended, can be operated on without affecting their code Liskov substitution principle - Should be able to refractor without changing the underlying structure Interface segration princple- breaking stuff up into parts and having it clear is better than one gigantic program I Dependancy inversion principle -Code should be based on abstract so main implementation is not affected HashMap is non-synchronized it is not-thread safe and hashtable is thread-safe
C
GB18030
4,844
2.75
3
[]
no_license
#include "pid.h" #include "condition.h" //PIDʼ void PID_Init(PID * pid,float kp,float ki,float kd,float max_ek_sum,float max_out) { pid->kp = kp; pid->ki = ki; pid->kd = kd; pid->max_sum_error = max_ek_sum; pid->max_out = max_out; } //PID㺯 void PID_Calculat(PID * pid,float current,float target) { pid->set = target; pid->get = current; pid->error = pid->set - pid->get; pid->sum_error += pid->error; LIMIT(pid->sum_error,-pid->max_sum_error,pid->max_sum_error); pid->out = pid->kp * pid->error +pid->ki * pid->sum_error +pid->kd * (pid->error - pid->last_error); LIMIT(pid->out,-pid->max_out,pid->max_out); pid->last_error = pid->error; } //ģ static void LinearQuantization(FUZZY_PID * FU_PID,float set,float get) { FU_PID->set = set; FU_PID->get = get; FU_PID->this_error = FU_PID->set - FU_PID->get; FU_PID->this_ec = FU_PID->this_error - FU_PID->last_error; FU_PID->qu_error = (float)6.0*FU_PID->this_error/(FU_PID->max_num - FU_PID->min_num); FU_PID->qu_ec = (float)3.0*FU_PID->this_ec /(FU_PID->max_num - FU_PID->min_num); FU_PID->last_error = FU_PID->this_error; } //Ⱥ static void CalcMembership(float input,int * index,float * num) { if((input>=NB)&&(input<NM)) { index[0]=0; index[1]=1; num[0]=-0.5f*input-2.0f; //y=-0.5x-2.0 num[1]=(float)(0.5f*input+3.0f); //y=0.5x+3.0 } else if((input>=NM)&&(input<NS)) { index[0]=1; index[1]=2; num[0]=-0.5f*input-1.0f; //y=-0.5x-1.0 num[1]=(float)(0.5f*input+2.0f); //y=0.5x+2.0 } else if((input>=NS)&&(input<ZO)) { index[0]=2; index[1]=3; num[0]=-0.5f*input; //y=-0.5x num[1]=(float)(0.5f*input+1.0f); //y=0.5x+1.0 } else if((input>=ZO)&&(input<PS)) { index[0]=3; index[1]=4; num[0]=-0.5f*input+1.0f; //y=-0.5x+1.0 num[1]=(float)(0.5f*input); //y=0.5x } else if((input>=PS)&&(input<PM)) { index[0]=4; index[1]=5; num[0]=-0.5f*input+2.0f; //y=-0.5x+2.0 num[1]=(float)(0.5f*input-1.0f); //y=0.5x-1.0 } else if((input>=PM)&&(input<=PB)) { index[0]=5; index[1]=6; num[0]=-0.5f*input+3.0f; //y=-0.5x+3.0 num[1]=(float)(0.5f*input-2.0f); //y=0.5x-2.0 } } //ģPID void FuzzyComputation(FUZZY_PID *vPID,float set,float get) { int indexE[2]={0,0}; //ƫ float msE[2]={0,0}; //ƫ int indexEC[2]={0,0}; //ƫ float msEC[2]={0,0}; //ƫ float qValueK[3]; LinearQuantization(vPID,set,get); CalcMembership(vPID->qu_error,indexE,msE); CalcMembership(vPID->qu_ec,indexEC,msEC); // qValueK[0] = msE[0]*(msEC[0]*ruleKp[indexE[0]][indexEC[0]]+msEC[1]*ruleKp[indexE[0]][indexEC[1]]) // +msE[1]*(msEC[0]*ruleKp[indexE[1]][indexEC[0]]+msEC[1]*ruleKp[indexE[1]][indexEC[1]]); qValueK[1] = msE[0]*(msEC[0]*ruleKi[indexE[0]][indexEC[0]]+msEC[1]*ruleKi[indexE[0]][indexEC[1]]) +msE[1]*(msEC[0]*ruleKi[indexE[1]][indexEC[0]]+msEC[1]*ruleKi[indexE[1]][indexEC[1]]); // qValueK[2] = msE[0]*(msEC[0]*ruleKd[indexE[0]][indexEC[0]]+msEC[1]*ruleKd[indexE[0]][indexEC[1]]) // +msE[1]*(msEC[0]*ruleKd[indexE[1]][indexEC[0]]+msEC[1]*ruleKd[indexE[1]][indexEC[1]]); vPID->delt_kp = qValueK[0] * vPID->dkp; LIMIT(vPID->delt_kp,-vPID->max_delt_kp,vPID->max_delt_kp); vPID->delt_ki = qValueK[1] * vPID->dki; LIMIT(vPID->delt_ki,-vPID->max_delt_ki,vPID->max_delt_ki); vPID->delt_kd = qValueK[2] * vPID->dkd; LIMIT(vPID->delt_kd,-vPID->max_delt_kd,vPID->max_delt_kd); PID_Calculate_F(vPID); } void PID_Calculate_F(FUZZY_PID * pid_n) { pid_n->MOTO.sum_error += pid_n->this_error; // LIMIT(pid_n->MOTO.sum_error,-pid_n->MOTO.max_sum_error,pid_n->MOTO.max_sum_error); // pid_n->MOTO.out = ((pid_n->kp + pid_n->delt_kp)* pid_n->this_error) + ((pid_n->ki + pid_n->delt_ki)* pid_n->MOTO.sum_error) + ((pid_n->kd + pid_n->delt_kd)* pid_n->this_ec); LIMIT(pid_n->MOTO.out,-pid_n->MOTO.max_out,pid_n->MOTO.max_out); // } void FUZZY_PID_Init(FUZZY_PID * FU_PID,float * kp,float * ki,float * kd,float * pid,float mind,float maxd) { FU_PID->max_num = maxd; FU_PID->min_num = mind; FU_PID->kp = kp[0]; FU_PID->dkp = kp[1]; FU_PID->max_delt_kp = kp[2]; FU_PID->ki = ki[0]; FU_PID->dki = ki[1]; FU_PID->max_delt_ki = ki[2]; FU_PID->kd = kd[0]; FU_PID->dkd = kd[1]; FU_PID->max_delt_kd = kd[2]; FU_PID->MOTO.max_sum_error = pid[0]; FU_PID->MOTO.max_out = pid[1]; }
Python
UTF-8
7,036
2.640625
3
[]
no_license
import sys from PyQt5 import QtCore from copy import deepcopy from PyQt5.QtCore import QMimeData, QAbstractItemModel, Qt, QVariant, QModelIndex, QRect from PyQt5.QtWidgets import * class myNode(object): def __init__(self, name, state, description, parent=None): self.name = name self.state = state self.description = description self.parent = parent self.children = [] self.setParent(parent) def setParent(self, parent): if parent != None: self.parent = parent self.parent.appendChild(self) else: self.parent = None def appendChild(self, child): self.children.append(child) def childAtRow(self, row): return self.children[row] def rowOfChild(self, child): for i, item in enumerate(self.children): if item == child: return i return -1 def removeChild(self, row): value = self.children[row] self.children.remove(value) return True def __len__(self): return len(self.children) class myModel(QAbstractItemModel): def __init__(self, parent=None): super(myModel, self).__init__(parent) self.treeView = parent self.headers = ['Item', 'State', 'Description'] self.columns = 3 # Create items self.root = myNode('root', 'on', 'this is root', None) itemA = myNode('itemA', 'on', 'this is item A', self.root) itemA1 = myNode('itemA1', 'on', 'this is item A1', itemA) itemB = myNode('itemB', 'on', 'this is item B', self.root) itemB1 = myNode('itemB1', 'on', 'this is item B1', itemB) itemC = myNode('itemC', 'on', 'this is item C', self.root) itemC1 = myNode('itemC1', 'on', 'this is item C1', itemC) def supportedDropActions(self): return Qt.CopyAction | Qt.MoveAction def flags(self, index): defaultFlags = QAbstractItemModel.flags(self, index) if index.isValid(): return Qt.ItemIsEditable | Qt.ItemIsDragEnabled | \ Qt.ItemIsDropEnabled | defaultFlags else: return Qt.ItemIsDropEnabled | defaultFlags def headerData(self, section, orientation, role): if orientation == Qt.Horizontal and role == Qt.DisplayRole: return QVariant(self.headers[section]) return QVariant() def dropMimeData(self, mimedata, action, row, column, parentIndex): if action == Qt.IgnoreAction: return True dragNode = mimedata.instance() parentNode = self.nodeFromIndex(parentIndex) # make an copy of the node being moved newNode = deepcopy(dragNode) newNode.setParent(parentNode) self.insertRow(len(parentNode) - 1, parentIndex) self.emit(parentIndex, parentIndex, [QtCore.Qt.EditRole]) return True def insertRow(self, row, parent): return self.insertRows(row, 1, parent) def insertRows(self, row, count, parent): self.beginInsertRows(parent, row, (row + (count - 1))) self.endInsertRows() return True def removeRow(self, row, parentIndex): return self.removeRows(row, 1, parentIndex) def removeRows(self, row, count, parentIndex): self.beginRemoveRows(parentIndex, row, row) node = self.nodeFromIndex(parentIndex) node.removeChild(row) self.endRemoveRows() return True def index(self, row, column, parent): node = self.nodeFromIndex(parent) return self.createIndex(row, column, node.childAtRow(row)) def data(self, index, role): if role == Qt.DecorationRole: return QVariant() if role == Qt.TextAlignmentRole: return QVariant(int(Qt.AlignTop | Qt.AlignLeft)) if role != Qt.DisplayRole: return QVariant() node = self.nodeFromIndex(index) if index.column() == 0: return QVariant(node.name) elif index.column() == 1: return QVariant(node.state) elif index.column() == 2: return QVariant(node.description) else: return QVariant() def columnCount(self, parent): return self.columns def rowCount(self, parent): node = self.nodeFromIndex(parent) if node is None: return 0 return len(node) def parent(self, child): if not child.isValid(): return QModelIndex() node = self.nodeFromIndex(child) if node is None: return QModelIndex() parent = node.parent if parent is None: return QModelIndex() grandparent = parent.parent if grandparent is None: return QModelIndex() row = grandparent.rowOfChild(parent) assert row != - 1 return self.createIndex(row, 0, parent) def nodeFromIndex(self, index): return index.internalPointer() if index.isValid() else self.root class myTreeView(QTreeView): def __init__(self, parent=None): super(myTreeView, self).__init__(parent) self.myModel = myModel() self.setModel(self.myModel) self.dragEnabled() self.acceptDrops() self.showDropIndicator() self.setDragDropMode(QAbstractItemView.InternalMove) self.clicked.connect(self.change) self.expandAll() def change(self, topLeftIndex, bottomRightIndex): self.update(topLeftIndex) self.expandAll() self.expanded() def expanded(self): for column in range(self.model().columnCount(QModelIndex())): self.resizeColumnToContents(column) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(600, 400) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.treeView = myTreeView(self.centralwidget) self.treeView.setObjectName("treeView") self.horizontalLayout.addWidget(self.treeView) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(MainWindow) self.menubar.setGeometry(QRect(0, 0, 600, 22)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) #QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle("Main") if __name__ == "__main__": app = QApplication(sys.argv) MainWindow = QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
Python
UTF-8
3,436
2.609375
3
[]
no_license
import json import models.board as board class FakeURL: def __init__(self, queries={}): self.query = queries class FakeRequest: def __init__(self, _raise_exception=False, _json=None, app=None, url=None): self._json = _json self._raise_exception = _raise_exception self.app = app or {} self.rel_url = url async def json(self): if self._raise_exception: json.loads('None') return self._json async def test_get_board_404(pool): fake_url = FakeURL({"id": 2222}) fake_request = FakeRequest(app={'pool': pool}, url=fake_url) response = await board.get_board(fake_request) actual = json.loads(response.text) expected = {'Error': 'No board exists with that id'} assert expected == actual async def test_get_board_200(pool): fake_url = FakeURL({"id": 2}) fake_request = FakeRequest(app={'pool': pool}, url=fake_url) response = await board.get_board(fake_request) expected = { "boardInfo": { "id": 2, "description": "Test board", "playing": 2, "status": "playing", "players": [ { "id": 1, "username": "Billy-Bob", "colour": "#6ed173", "wins": 0, "draws": 0, "losses": 0, }, { "id": 2, "username": "Zanny-Zaz", "colour": "#fa6511", "wins": 0, "draws": 0, "losses": 0, } ] }, "tiles": [ { "id": 10, "owner": 1, "tokens": 5, "x": 0, "y": 0, "playable": 1, "neighbors": [ 11 ] }, { "id": 11, "owner": 2, "tokens": 9, "x": 0, "y": 1, "playable": 1, "neighbors": [ 10 ] } ] } actual = json.loads(response.text) del actual["boardInfo"]["created"] assert actual == expected async def test_get_board_info_200(pool): board_id = 2 actual = await board.get_board_information(pool, board_id) expected = { 'description': 'Test board', 'id': 2, 'playing': 2 } del actual["created"] assert expected == actual async def test_get_board_info_404(pool): board_id = 125125125 actual = await board.get_board_information(pool, board_id) expected = {'Error': 'No board exists with that id'} assert expected == actual async def test_get_current_turn(pool): url = FakeURL({"id": 2}) request = FakeRequest(app={'pool': pool}, url=url) response = await board.get_turn(request) actual = json.loads(response.text) expected = {"playing": 2} assert expected == actual async def test_update_current_turn(pool): data = {"id": 2, "next": 2} request = FakeRequest(app={'pool': pool}, _json=data) response = await board.update_turn(request) actual = json.loads(response.text) expected = {"next-player": 2} assert expected == actual
Java
UTF-8
41,691
2.75
3
[]
no_license
package com.santipe.tp_club; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * Trabajo practico - Clubes * * @author Santiago Perrin <1santiagoperrin@gmail.com> */ public class Socios extends javax.swing.JFrame { private Connection conexion; private int modificandoSocio; /** * Creates new form Socios */ public Socios() { initComponents(); actualizarListadoSocios(); } private Connection getDatabaseConnection() { if (this.conexion == null) { File temp = new File("tablaSocios.db"); String connstr = "jdbc:sqlite:" + temp.getAbsolutePath().replace("\\", "\\\\"); try { Class.forName("org.sqlite.JDBC"); this.conexion = DriverManager.getConnection(connstr); return this.conexion; } catch (ClassNotFoundException ex) { JOptionPane.showMessageDialog(null, "Ocurrio un error al conectarse con la base de datos, al parecer el Driver 'org.sqlite.JDBC' no esta disponible."); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Ocurrio un error al conectarse con la base de datos."); } return null; } return this.conexion; } private void actualizarListadoSocios() { // Creamos un "modelo" DefaultTableModel model = new DefaultTableModel(); // Le describimos sus columnas String[] columnNames = {"Id", "Nombre", "Apellido", "Calle", "Numero", "Telefono", "Documento"}; model.setColumnIdentifiers(columnNames); // Le avisamos al objeto jTable1 que tiene que usar este modelo jTable1.setModel(model); try { // Nos conectamos a la base de datos Connection conn = this.getDatabaseConnection(); // Generamos una nueva consulta Statement stmt = conn.createStatement(); // Executamos la consulta ResultSet rs = stmt.executeQuery("SELECT Id, Nombre, Apellido, Calle, Numero, Telefono, Documento FROM Socios"); // Obtenemos todas las filas while (rs.next()) { model.addRow(new Object[]{ rs.getInt("Id"), rs.getString("Nombre"), rs.getString("Apellido"), rs.getString("Calle"), rs.getInt("Numero"), rs.getString("Telefono"), rs.getInt("Documento") }); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Ocurrio un error al obtener los socios de la base de datos."); System.out.println(e.getMessage()); } } public boolean insertarSocio(String nombre, String apellido, String calle, int numero, String telefono, int documento) { try { // Obtenemos una conexion a la BD Connection conn = this.getDatabaseConnection(); // Creamos una nueva consulta PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Socios (Nombre, Apellido, Calle, Numero, Telefono, Documento) VALUES (?, ?, ?, ?, ?, ?)"); // Le damos los datos pstmt.setString(1, nombre); pstmt.setString(2, apellido); pstmt.setString(3, calle); pstmt.setInt(4, numero); pstmt.setString(5, telefono); pstmt.setInt(6, documento); // Ejecutamos la consulta return (pstmt.executeUpdate() == 1); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Ocurrio un error al insertar en la base de datos."); System.out.println(ex.getMessage()); return false; } } public boolean modificarSocio(int id, String nombre, String apellido, String calle, int numero, String telefono, int documento) { try { // Obtenemos una conexion a la BD Connection conn = this.getDatabaseConnection(); // Creamos una nueva consulta PreparedStatement pstmt = conn.prepareStatement("UPDATE Socios SET Nombre = ?, Apellido = ?, Calle = ?, Numero = ?, Telefono = ?, Documento = ? WHERE Id = ?"); // Le damos los datos pstmt.setString(1, nombre); pstmt.setString(2, apellido); pstmt.setString(3, calle); pstmt.setInt(4, numero); pstmt.setString(5, telefono); pstmt.setInt(6, documento); pstmt.setInt(7, id); // Ejecutamos la consulta return (pstmt.executeUpdate() == 1); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Ocurrio un error al insertar en la base de datos."); System.out.println(ex.getMessage()); return false; } } public boolean eliminarSocio(int id) { try { // Obtenemos una conexion a la BD Connection conn = this.getDatabaseConnection(); // Creamos una nueva consulta PreparedStatement pstmt = conn.prepareStatement("DELETE FROM Socios WHERE Id = ?"); // Le damos los datos pstmt.setInt(1, id); // Ejecutamos la consulta return (pstmt.executeUpdate() == 1); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Ocurrio un error al eliminar registro de la base de datos."); System.out.println(ex.getMessage()); return false; } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { AltaSocio = new javax.swing.JDialog(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jTextField5 = new javax.swing.JTextField(); jTextField6 = new javax.swing.JTextField(); darAlta = new javax.swing.JButton(); cancelarAlta = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); ModificarSocio = new javax.swing.JDialog(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jTextField8 = new javax.swing.JTextField(); jTextField9 = new javax.swing.JTextField(); jTextField10 = new javax.swing.JTextField(); jTextField11 = new javax.swing.JTextField(); jTextField12 = new javax.swing.JTextField(); jTextField13 = new javax.swing.JTextField(); darAlta1 = new javax.swing.JButton(); cancelarAlta1 = new javax.swing.JButton(); jLabel16 = new javax.swing.JLabel(); jFileChooser1 = new javax.swing.JFileChooser(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); botonAlta = new javax.swing.JButton(); botonModificar = new javax.swing.JButton(); botonBaja = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); jMenuItem3 = new javax.swing.JMenuItem(); AltaSocio.setMinimumSize(new java.awt.Dimension(400, 360)); jLabel1.setText("INGRESE NOMBRE"); jLabel2.setText("INGRESE APELLIDO"); jLabel3.setText("INGRESE CALLE"); jLabel4.setText("INGRESE NUMERO"); jLabel5.setText("INGRESE TELEFONO"); jLabel6.setText("INGRESE DOCUMENTO"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); darAlta.setText("Aceptar"); darAlta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { darAltaActionPerformed(evt); } }); cancelarAlta.setText("Cancelar"); cancelarAlta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelarAltaActionPerformed(evt); } }); jLabel7.setText("ALTA"); javax.swing.GroupLayout AltaSocioLayout = new javax.swing.GroupLayout(AltaSocio.getContentPane()); AltaSocio.getContentPane().setLayout(AltaSocioLayout); AltaSocioLayout.setHorizontalGroup( AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AltaSocioLayout.createSequentialGroup() .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AltaSocioLayout.createSequentialGroup() .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AltaSocioLayout.createSequentialGroup() .addGap(50, 50, 50) .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, AltaSocioLayout.createSequentialGroup() .addContainerGap() .addComponent(darAlta) .addGap(43, 43, 43))) .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cancelarAlta) .addComponent(jTextField1) .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(jTextField3) .addComponent(jTextField4) .addComponent(jTextField5) .addComponent(jTextField6))) .addGroup(AltaSocioLayout.createSequentialGroup() .addGap(165, 165, 165) .addComponent(jLabel7))) .addContainerGap(47, Short.MAX_VALUE)) ); AltaSocioLayout.setVerticalGroup( AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AltaSocioLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel7) .addGap(36, 36, 36) .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(AltaSocioLayout.createSequentialGroup() .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel4)) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(AltaSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(darAlta) .addComponent(cancelarAlta)) .addContainerGap(18, Short.MAX_VALUE)) ); ModificarSocio.setMinimumSize(new java.awt.Dimension(400, 360)); jLabel10.setText("INGRESE NOMBRE"); jLabel11.setText("INGRESE APELLIDO"); jLabel12.setText("INGRESE CALLE"); jLabel13.setText("INGRESE NUMERO"); jLabel14.setText("INGRESE TELEFONO"); jLabel15.setText("INGRESE DOCUMENTO"); jTextField8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField8ActionPerformed(evt); } }); jTextField9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField9ActionPerformed(evt); } }); darAlta1.setText("Aceptar"); darAlta1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { darAlta1ActionPerformed(evt); } }); cancelarAlta1.setText("Cancelar"); cancelarAlta1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelarAlta1ActionPerformed(evt); } }); jLabel16.setText("MODIFICACION"); javax.swing.GroupLayout ModificarSocioLayout = new javax.swing.GroupLayout(ModificarSocio.getContentPane()); ModificarSocio.getContentPane().setLayout(ModificarSocioLayout); ModificarSocioLayout.setHorizontalGroup( ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ModificarSocioLayout.createSequentialGroup() .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ModificarSocioLayout.createSequentialGroup() .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ModificarSocioLayout.createSequentialGroup() .addGap(50, 50, 50) .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11) .addComponent(jLabel12) .addComponent(jLabel13) .addComponent(jLabel14) .addComponent(jLabel15) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ModificarSocioLayout.createSequentialGroup() .addContainerGap() .addComponent(darAlta1) .addGap(43, 43, 43))) .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cancelarAlta1) .addComponent(jTextField8) .addComponent(jTextField9, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(jTextField10) .addComponent(jTextField11) .addComponent(jTextField12) .addComponent(jTextField13))) .addGroup(ModificarSocioLayout.createSequentialGroup() .addGap(165, 165, 165) .addComponent(jLabel16))) .addContainerGap(47, Short.MAX_VALUE)) ); ModificarSocioLayout.setVerticalGroup( ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ModificarSocioLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel16) .addGap(36, 36, 36) .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(ModificarSocioLayout.createSequentialGroup() .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel13)) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(jTextField13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(ModificarSocioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(darAlta1) .addComponent(cancelarAlta1)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(204, 204, 255)); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null} }, new String [] { "Socio N°", "Nombre", "Apellido", "Calle", "Número", "Telefono", "DNI" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane1.setViewportView(jTable1); botonAlta.setText("Alta Socio"); botonAlta.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonAltaMouseClicked(evt); } }); botonAlta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonAltaActionPerformed(evt); } }); botonModificar.setText("Modificar Socio"); botonModificar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonModificarMouseClicked(evt); } }); botonModificar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonModificarActionPerformed(evt); } }); botonBaja.setText("Baja Socio"); botonBaja.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { botonBajaMouseClicked(evt); } }); botonBaja.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonBajaActionPerformed(evt); } }); jMenu1.setText("Archivo"); jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuItem1.setText("Importar"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); jMenuItem2.setText("Exportar"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenu1.add(jSeparator1); jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem3.setText("Salir"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu1.add(jMenuItem3); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(botonAlta) .addGap(62, 62, 62) .addComponent(botonModificar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE) .addComponent(botonBaja) .addGap(27, 27, 27)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botonAlta) .addComponent(botonModificar) .addComponent(botonBaja)) .addGap(23, 23, 23)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void botonAltaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonAltaMouseClicked // TODO add your handling code here: }//GEN-LAST:event_botonAltaMouseClicked private void botonModificarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonModificarMouseClicked // TODO add your handling code here: }//GEN-LAST:event_botonModificarMouseClicked private void botonBajaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonBajaMouseClicked // TODO add your handling code here: }//GEN-LAST:event_botonBajaMouseClicked private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField2ActionPerformed private void cancelarAltaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarAltaActionPerformed int n = JOptionPane.showConfirmDialog( null, "Estas seguro que deseas cancelar?", "Cancelar Alta", JOptionPane.YES_NO_OPTION); if (n == 0) { AltaSocio.dispose(); } }//GEN-LAST:event_cancelarAltaActionPerformed private void botonAltaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAltaActionPerformed // TODO add your handling code here: this.conexion = getDatabaseConnection(); this.limpiarAltaSocio(); AltaSocio.setVisible(true); }//GEN-LAST:event_botonAltaActionPerformed private void darAltaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_darAltaActionPerformed String nombre = jTextField1.getText(); String apellido = jTextField2.getText(); String calle = jTextField3.getText(); String telefono = jTextField5.getText(); int numero; int documento; try { numero = Integer.parseInt(jTextField4.getText()); } catch (java.lang.NumberFormatException e) { JOptionPane.showMessageDialog(null, "El numero de domicilio debe ser numerico."); return; } try { documento = Integer.parseInt(jTextField6.getText()); } catch (java.lang.NumberFormatException e) { JOptionPane.showMessageDialog(null, "El numero de documento debe ser numerico."); return; } if (insertarSocio(nombre, apellido, calle, numero, telefono, documento)) { AltaSocio.dispose(); JOptionPane.showMessageDialog(null, "Nuevo socio insertado con exito."); actualizarListadoSocios(); } else { JOptionPane.showMessageDialog(null, "Ocurrio un error al agregar socio."); } }//GEN-LAST:event_darAltaActionPerformed private void botonBajaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBajaActionPerformed if (jTable1.getSelectedRow() < 0) { // Si no hay nada seleccionado, no hago nada :D return; } int n = JOptionPane.showConfirmDialog( null, "Estas seguro que deseas eliminar el socio?", "Dar de baja", JOptionPane.YES_NO_OPTION); if (n == 0) { int idSocio = (int) jTable1.getValueAt(jTable1.getSelectedRow(), 0); eliminarSocio(idSocio); actualizarListadoSocios(); } }//GEN-LAST:event_botonBajaActionPerformed private void jTextField8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField8ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField8ActionPerformed private void jTextField9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField9ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField9ActionPerformed private void darAlta1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_darAlta1ActionPerformed int n = JOptionPane.showConfirmDialog( null, "Estas seguro que deseas realizar la modificacion?", "Modificar", JOptionPane.YES_NO_OPTION); if (n == 0) { String nombre = jTextField8.getText(); String apellido = jTextField9.getText(); String calle = jTextField10.getText(); String telefono = jTextField12.getText(); int numero; int documento; try { numero = Integer.parseInt(jTextField11.getText()); } catch (java.lang.NumberFormatException e) { JOptionPane.showMessageDialog(null, "El numero de domicilio debe ser numerico."); return; } try { documento = Integer.parseInt(jTextField13.getText()); } catch (java.lang.NumberFormatException e) { JOptionPane.showMessageDialog(null, "El numero de documento debe ser numerico."); return; } if (modificarSocio(this.modificandoSocio, nombre, apellido, calle, numero, telefono, documento)) { this.modificandoSocio = 0; ModificarSocio.dispose(); JOptionPane.showMessageDialog(null, "Socio modificado con exito."); actualizarListadoSocios(); } else { JOptionPane.showMessageDialog(null, "Ocurrio un error al modificar socio."); } } }//GEN-LAST:event_darAlta1ActionPerformed private void cancelarAlta1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarAlta1ActionPerformed int n = JOptionPane.showConfirmDialog( null, "Estas seguro que deseas cancelar?", "Cancelar Modificacion", JOptionPane.YES_NO_OPTION); if (n == 0) { ModificarSocio.dispose(); } }//GEN-LAST:event_cancelarAlta1ActionPerformed private void botonModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonModificarActionPerformed if (jTable1.getSelectedRow() < 0) { // Si no hay nada seleccionado, no hago nada :D return; } int id = (int) jTable1.getValueAt(jTable1.getSelectedRow(), 0); String nombre = jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString(); String apellido = jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString(); String calle = jTable1.getValueAt(jTable1.getSelectedRow(), 3).toString(); String numero = jTable1.getValueAt(jTable1.getSelectedRow(), 4).toString(); String telefono = jTable1.getValueAt(jTable1.getSelectedRow(), 5).toString(); String documento = jTable1.getValueAt(jTable1.getSelectedRow(), 6).toString(); jTextField8.setText(nombre); jTextField9.setText(apellido); jTextField10.setText(calle); jTextField11.setText(numero); jTextField12.setText(telefono); jTextField13.setText(documento); this.modificandoSocio = id; ModificarSocio.setVisible(true); }//GEN-LAST:event_botonModificarActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed // Abrimos un menu del tipo "Abrir archivo" int returnValue = jFileChooser1.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File archivo = jFileChooser1.getSelectedFile(); if (CSV.Importar(this.getDatabaseConnection(), archivo.getAbsolutePath())) { JOptionPane.showMessageDialog(null, "Importado con exito."); } else { JOptionPane.showMessageDialog(null, "Ocurrio un error al importar."); } actualizarListadoSocios(); } }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed int returnValue = jFileChooser1.showSaveDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File archivo = jFileChooser1.getSelectedFile(); if (CSV.Exportar(this.getDatabaseConnection(), archivo.getAbsolutePath())) { JOptionPane.showMessageDialog(null, "Exportado con exito."); } else { JOptionPane.showMessageDialog(null, "Ocurrio un error al exportar."); } } }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed int n = JOptionPane.showConfirmDialog( null, "Estas seguro que deseas salir de la aplicacion?", "Salir", JOptionPane.YES_NO_OPTION); if (n == 0) { System.exit(0); } }//GEN-LAST:event_jMenuItem3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Socios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Socios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Socios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Socios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Socios().setVisible(true); } }); } public void limpiarAltaSocio() { this.jTextField1.setText(""); this.jTextField2.setText(""); this.jTextField3.setText(""); this.jTextField4.setText(""); this.jTextField5.setText(""); this.jTextField6.setText(""); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JDialog AltaSocio; private javax.swing.JDialog ModificarSocio; private javax.swing.JButton botonAlta; private javax.swing.JButton botonBaja; private javax.swing.JButton botonModificar; private javax.swing.JButton cancelarAlta; private javax.swing.JButton cancelarAlta1; private javax.swing.JButton darAlta; private javax.swing.JButton darAlta1; private javax.swing.JFileChooser jFileChooser1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField11; private javax.swing.JTextField jTextField12; private javax.swing.JTextField jTextField13; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField8; private javax.swing.JTextField jTextField9; // End of variables declaration//GEN-END:variables }
Java
UTF-8
46,956
2.125
2
[]
no_license
package com.github.technus.signalTester.fx.additions; import com.sun.javafx.charts.ChartLayoutAnimator; import com.sun.javafx.css.converters.SizeConverter; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.beans.InvalidationListener; import javafx.beans.binding.BooleanBinding; import javafx.beans.binding.DoubleBinding; import javafx.beans.binding.IntegerBinding; import javafx.beans.property.*; import javafx.beans.value.ChangeListener; import javafx.css.CssMetaData; import javafx.css.Styleable; import javafx.css.StyleableDoubleProperty; import javafx.css.StyleableProperty; import javafx.geometry.Dimension2D; import javafx.geometry.Side; import javafx.scene.chart.ValueAxis; import javafx.util.Duration; import javafx.util.StringConverter; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LogLinAxis extends ValueAxis<Number> { private static double EPSILON= Math.pow(10,-14); private Object currentAnimationID; private final ChartLayoutAnimator animator = new ChartLayoutAnimator(this); private final StringProperty currentFormatterProperty = new SimpleStringProperty(this, "currentFormatter", ""); private final DefaultFormatter defaultFormatter = new DefaultFormatter(this); //region -------------- PUBLIC PROPERTIES -------------------------------------------------------------------------------- /** Base of the logarithm, set to 1,<=0,-1, for linear */ private DoubleProperty logBase = new DoublePropertyBase(-10) { @Override protected void invalidated() { invalidateRange(); requestAxisLayout(); } @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "logBase"; } @Override public void set(double newValue) { if(newValue==0 || newValue==-1 || newValue==1){ super.set(-10); }else{ if(newValue>0){ log10logBase.set(Math.log10(newValue)); } super.set(newValue); } } }; public boolean isUsingLogBase(double base){ return base!=1 && base>0; } public boolean isUsingLinBase(double base){ return base==1 || base<=0; } public final boolean isUsingLogBase(){ return isUsingLogBase(logBase.getValue()); } public final boolean isUsingLinBase(){ return isUsingLinBase(logBase.getValue()); } public final double logBase() { return logBase.getValue(); } public final void setLogBase(double value) {logBase.set(value);} public final void setUsingLogBase(boolean usingLogBase){ if(usingLogBase!=isUsingLogBase()){ logBase.set(-logBase.getValue()); } } public final DoubleProperty logBaseProperty() { return logBase; } private ReadOnlyDoubleWrapper log10logBase =new ReadOnlyDoubleWrapper(this,"log10logBase",1); /** When true zero is always included in the visible range. This only has effect if auto-ranging is on. */ private BooleanProperty linForceZeroInRange = new BooleanPropertyBase(true) { @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "linForceZeroInRange"; } }; public final boolean isLinForceZeroInRange() { return linForceZeroInRange.getValue(); } public final void setLinForceZeroInRange(boolean value) { linForceZeroInRange.set(value); } public final BooleanProperty linForceZeroInRangeProperty() { return linForceZeroInRange; } /** When true zero is always included in the visible range. This only has effect if auto-ranging is on. */ private BooleanPropertyBase forceZeroInRange = new BooleanPropertyBase() { @Override protected void invalidated() { // This will effect layout if we are auto ranging if(isAutoRanging()) { requestAxisLayout(); invalidateRange(); } } @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "forceZeroInRange"; } }; public final boolean isForceZeroInRange() { return forceZeroInRange.getValue(); } public final void setForceZeroInRange(boolean value) { forceZeroInRange.set(value); } public final BooleanProperty forceZeroInRangeProperty() { return forceZeroInRange; } { forceZeroInRangeProperty().bind(new BooleanBinding() { { bind(logBaseProperty(),linForceZeroInRangeProperty()); } @Override protected boolean computeValue() { return isUsingLinBase() && linForceZeroInRangeProperty().get(); } }); } /** The value between each major tick mark in data units. This is automatically set if we are auto-ranging. */ private DoubleProperty logTickCount = new DoublePropertyBase(10) { @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "logTickCount"; } }; public final double getLogTickCount() { return logTickCount.get(); } public final void setLogTickCount(double value) { logTickCount.set(value); } public final DoubleProperty logTickCountProperty() { return logTickCount; } /** The value between each major tick mark in data units. This is automatically set if we are auto-ranging. */ private DoubleProperty linTickUnit = new DoublePropertyBase(10) { @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "linTickUnit"; } }; public final double getLinTickUnit() { return linTickUnit.get(); } public final void setLinTickUnit(double value) { linTickUnit.set(value); } public final DoubleProperty linTickUnitProperty() { return linTickUnit; } /** The value between each major tick mark in data units. This is automatically set if we are auto-ranging. */ private DoubleProperty tickUnit = new StyleableDoubleProperty() { @Override protected void invalidated() { if(!isAutoRanging()) { invalidateRange(); requestAxisLayout(); } } @Override public CssMetaData<LogLinAxis,Number> getCssMetaData() { return StyleableProperties.TICK_UNIT; } @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "tickUnit"; } }; public final double getTickUnit() { return tickUnit.get(); } public final void setTickUnit(double value) { tickUnit.set(value); } final DoubleProperty tickUnitProperty() { return tickUnit; } { tickUnitProperty().bind(new DoubleBinding() { { bind(logBaseProperty(),linTickUnitProperty(),logTickCountProperty()); } @Override protected double computeValue() { return isUsingLinBase()?linTickUnitProperty().get(): logTickCountProperty().get(); } }); } /** The value for the upper bound of this axis, ie max value. This is automatically set if auto ranging is on. */ private DoubleProperty linUpperBound = new DoublePropertyBase(100) { @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "linUpperBound"; } }; public final double getLinUpperBound() { return linUpperBound.get(); } public final void setLinUpperBound(double value) { linUpperBound.set(value); } public final DoubleProperty linUpperBoundProperty() { return linUpperBound; } /** The value for the upper bound of this axis, ie max value. This is automatically set if auto ranging is on. */ private DoubleProperty logUpperBound = new DoublePropertyBase(25000) { @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "logUpperBound"; } @Override public void set(double newValue) { if(newValue<=0 || Double.isInfinite(newValue) || Double.isNaN(newValue)){ newValue=Double.MAX_VALUE; } super.set(newValue); } }; public final double getLogUpperBound() { return logUpperBound.get(); } public final void setLogUpperBound(double value) { logUpperBound.set(value); } public final DoubleProperty logUpperBoundProperty() { return logUpperBound; } { upperBoundProperty().bind(new DoubleBinding() { { bind(logBaseProperty(),linUpperBoundProperty(),logUpperBoundProperty()); } @Override protected double computeValue() { return isUsingLinBase()?linUpperBoundProperty().get():logUpperBoundProperty().get(); } }); } /** The value for the lower bound of this axis, ie min value. This is automatically set if auto ranging is on. */ private DoubleProperty linLowerBound = new DoublePropertyBase(0) { @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "linLowerBound"; } }; public final double getLinLowerBound() { return linLowerBound.get(); } public final void setLinLowerBound(double value) { linLowerBound.set(value); } public final DoubleProperty linLowerBoundProperty() { return linLowerBound; } /** The value for the lower bound of this axis, ie min value. This is automatically set if auto ranging is on. */ private DoubleProperty logLowerBound = new DoublePropertyBase(25) { @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "logLowerBound"; } @Override public void set(double newValue) { if(newValue<=0 || Double.isInfinite(newValue) || Double.isNaN(newValue)){ newValue=Double.MIN_NORMAL; } super.set(newValue); } }; public final double getLogLowerBound() { return logLowerBound.get(); } public final void setLogLowerBound(double value) { logLowerBound.set(value); } public final DoubleProperty logLowerBoundProperty() { return logLowerBound; } { lowerBoundProperty().bind(new DoubleBinding() { { bind(logBaseProperty(),linLowerBoundProperty(),logLowerBoundProperty()); } @Override protected double computeValue() { return isUsingLinBase()?linLowerBoundProperty().get():logLowerBoundProperty().get(); } }); } /** * The number of minor tick divisions to be displayed between each major tick mark. * The number of actual minor tick marks will be one less than this. */ private IntegerProperty logMinorTickCount = new IntegerPropertyBase(10) { @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "logMinorTickCount"; } }; public final int getLogMinorTickCount() { return logMinorTickCount.get(); } public final void setLogMinorTickCount(int value) { logMinorTickCount.set(value); } public final IntegerProperty logMinorTickCountProperty() { return logMinorTickCount; } /** * The number of minor tick divisions to be displayed between each major tick mark. * The number of actual minor tick marks will be one less than this. */ private IntegerProperty linMinorTickCount = new IntegerPropertyBase(10) { @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "linMinorTickCount"; } }; public final int getLinMinorTickCount() { return linMinorTickCount.get(); } public final void setLinMinorTickCount(int value) { linMinorTickCount.set(value); } public final IntegerProperty linMinorTickCountProperty() { return linMinorTickCount; } { minorTickCountProperty().bind(new IntegerBinding() { { bind(logBaseProperty(),logMinorTickCountProperty(),linMinorTickCountProperty()); } @Override protected int computeValue() { return isUsingLinBase()?linMinorTickCountProperty().get():logMinorTickCountProperty().get(); } }); } //endregion private final DoubleProperty currentUpperBound = new SimpleDoubleProperty(this, "currentUpperBound"); private final DoubleProperty currentUpperLogBound = new SimpleDoubleProperty(this, "currentUpperLogBound"); { currentUpperLogBound.bind(new DoubleBinding() { { bind(currentUpperBound,logBaseProperty(),upperBoundProperty()); } @Override protected double computeValue() { return Math.log10(currentUpperBound.get())/log10logBase.get()+EPSILON; } }); } private final DoubleProperty currentLowerLogBound = new SimpleDoubleProperty(this, "currentLowerLogBound"); { currentLowerLogBound.bind(new DoubleBinding() { { bind(currentLowerBound,logBaseProperty(),lowerBoundProperty()); } @Override protected double computeValue() { return Math.log10(currentLowerBound.get())/log10logBase.get()-EPSILON; } }); } private double offset=0; private final ReadOnlyDoubleWrapper logScale=new ReadOnlyDoubleWrapper(LogLinAxis.this,"logScale"); { InvalidationListener listener= (observable) -> { if(isUsingLogBase()) { final Side side = getEffectiveSide(); final double upperBound = currentUpperLogBound.get(); final double lowerBound = currentLowerLogBound.get(); if (side.isVertical()) { final double length = getHeight(); offset = length; final double scale = ((upperBound - lowerBound) == 0) ? -length : -(length / (upperBound - lowerBound)); setScale(scale); logScale.set(scale); } else { // HORIZONTAL final double length = getWidth(); offset = 0; final double scale = ((upperBound - lowerBound) == 0) ? length : length / (upperBound - lowerBound); setScale(scale); logScale.set(scale); } } }; widthProperty().addListener(listener); heightProperty().addListener(listener); currentLowerLogBound.addListener(listener); currentUpperLogBound.addListener(listener); sideProperty().addListener(listener); } private final ComplexDoublePropertyBase scaleController =new ComplexDoublePropertyBase(getScale()){ @Override public Object getBean() { return LogLinAxis.this; } @Override public String getName() { return "scaleController"; } @Override public void set(double newValue) { setScale(newValue); } }; { scaleProperty().addListener((observable, oldValue, newValue) -> scaleController.setRawValue(newValue.doubleValue())); } //region -------------- CONSTRUCTORS ------------------------------------------------------------------------------------- /** * Create a auto-ranging LogarithmicAxis2 */ public LogLinAxis() {} /** * Create a non-auto-ranging LogarithmicAxis2 with the given upper bound, lower bound and tick unit * * @param lowerBound The lower bound for this axis, ie min plottable value * @param upperBound The upper bound for this axis, ie max plottable value * @param tickUnit The tick unit, ie space between tickmarks */ public LogLinAxis(double lowerBound, double upperBound, double tickUnit) { super(lowerBound, upperBound); setLogLowerBound(lowerBound); setLogUpperBound(upperBound); setTickUnit(tickUnit); setLogTickCount(tickUnit); } /** * Create a non-auto-ranging LogarithmicAxis2 with the given upper bound, lower bound and tick unit * * @param axisLabel The name to display for this axis * @param lowerBound The lower bound for this axis, ie min plottable value * @param upperBound The upper bound for this axis, ie max plottable value * @param tickUnit The tick unit, ie space between tickmarks */ public LogLinAxis(String axisLabel, double lowerBound, double upperBound, double tickUnit) { super(lowerBound, upperBound); setLogLowerBound(lowerBound); setLogUpperBound(upperBound); setTickUnit(tickUnit); setLogTickCount(tickUnit); setLabel(axisLabel); } private static double EPSILON_FORMAT=Math.pow(10,-6); { setTickLabelFormatter(new StringConverter<Number>() { DecimalFormat format = new DecimalFormat("0.0E0"); DecimalFormat shorter=new DecimalFormat(""); { DecimalFormatSymbols decimalFormatSymbols=new DecimalFormatSymbols(); decimalFormatSymbols.setGroupingSeparator(' '); format.setMaximumFractionDigits(3); format.setMinimumIntegerDigits(1); format.setRoundingMode(RoundingMode.HALF_UP); format.setDecimalFormatSymbols(decimalFormatSymbols); shorter.setMaximumFractionDigits(5); shorter.setMinimumIntegerDigits(1); shorter.setRoundingMode(RoundingMode.HALF_UP); shorter.setDecimalFormatSymbols(decimalFormatSymbols); } @Override public String toString(Number object) { if((object.intValue()<object.doubleValue()+EPSILON_FORMAT && object.intValue()>object.doubleValue()-EPSILON_FORMAT && object.doubleValue()<=100_000 && object.doubleValue()>=-100_000) || (object.doubleValue()<=1 && object.doubleValue()>=-1 && (object.doubleValue()-EPSILON_FORMAT<=-0.001 || object.doubleValue()+EPSILON_FORMAT>=0.001))){ return shorter.format(object); } return format.format(object); } @Override public Number fromString(String string) { try{ return (Number) format.parseObject(string); }catch (ParseException e){ return Double.parseDouble(string); } } }); setMinorTickLength(4); } //endregion // -------------- PROTECTED METHODS -------------------------------------------------------------------------------- /** * Get the string label name for a tick mark with the given value * * @param value The value to format into a tick label string * @return A formatted string for the given value */ @Override protected String getTickMarkLabel(Number value) { StringConverter<Number> formatter = getTickLabelFormatter(); if (formatter == null) formatter = defaultFormatter; return formatter.toString(value); } /** * Called to get the current axis range. * * @return A range object that can be passed to setRange() and calculateTickValues() */ @Override protected Object getRange() { return new Object[]{ getLowerBound(), getUpperBound(), getTickUnit(), getMinorTickCount(), getScale(), currentFormatterProperty.get() }; } @Override protected void layoutChildren() { if(!isAutoRanging()) { currentUpperBound.set(getUpperBound()); } double minorTickLength = Math.max(0, getMinorTickLength()); final Side side = getEffectiveSide(); final double length = side.isVertical() ? getHeight() :getWidth() ; if (minorTickLength > 0 && length > 2 * getTickMarks().size()) { doHack=true; } super.layoutChildren(); doHack=false; } /** * Called to set the current axis range to the given range. If isAnimating() is true then this method should * animate the range to the new range. * * @param range A range object returned from autoRange() * @param animate If true animate the change in range */ @Override protected void setRange(Object range, boolean animate) { final Object[] rangeProps = (Object[]) range; final double lowerBound = (Double)rangeProps[0]; final double upperBound = (Double)rangeProps[1]; final double tick = (Double)rangeProps[2]; final int minorTick = (Integer) rangeProps[3]; final double scale = (Double)rangeProps[4]; final String formatter = (String)rangeProps[5]; currentFormatterProperty.set(formatter); final double oldLowerBound = getLowerBound(); final double oldUpperBound = getUpperBound(); if(isUsingLinBase()){ setLinLowerBound(lowerBound); setLinUpperBound(upperBound); setLinTickUnit(tick); setLinMinorTickCount(minorTick); if(animate) { animator.stop(currentAnimationID); Timeline timeline = new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(currentLowerBound, oldLowerBound), new KeyValue(scaleController, getScale()) ), new KeyFrame(Duration.millis(700), new KeyValue(currentLowerBound, lowerBound), new KeyValue(scaleController, scale) ) ); currentAnimationID = animator.animate(timeline); } else { currentLowerBound.set(lowerBound); scaleController.set(scale); } }else { setLogLowerBound(lowerBound); setLogUpperBound(upperBound); setLogTickCount(tick); setLogMinorTickCount(minorTick); if(animate) { animator.stop(currentAnimationID); Timeline timeline = new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(currentLowerBound, oldLowerBound), new KeyValue(currentUpperBound, oldUpperBound) ), new KeyFrame(Duration.millis(700), new KeyValue(currentLowerBound, lowerBound), new KeyValue(currentUpperBound, upperBound) ) ); timeline.setOnFinished(event -> { getLowerBound(); getUpperBound(); }); currentAnimationID = animator.animate(timeline); } else { currentLowerBound.set(lowerBound); currentUpperBound.set(upperBound); } } } /** * Calculate a list of all the data values for each tick mark in range * * @param length The length of the axis in display units * @param range A range object returned from autoRange() * @return A list of tick marks that fit along the axis if it was the given length */ private final ArrayList<Number> tickValues=new ArrayList<>(); @Override protected List<Number> calculateTickValues(double length, Object range) { final Object[] rangeProps = (Object[]) range; final double lowerBound = (Double)rangeProps[0]; final double upperBound = (Double)rangeProps[1]; final double tickUnit = (Double)rangeProps[2]; tickValues.clear(); if (lowerBound == upperBound) { tickValues.add(lowerBound); } else if (tickUnit <= 0) { tickValues.add(lowerBound); tickValues.add(upperBound); } else if (tickUnit > 0) { tickValues.add(lowerBound); if(isUsingLinBase()) { if (((upperBound - lowerBound) / tickUnit) > 2000) { // This is a ridiculous amount of major tick marks, something has probably gone wrong System.err.println("Warning we tried to create more than 2000 major tick marks on a LogLinAxis. " + "Lower Bound=" + lowerBound + ", Upper Bound=" + upperBound + ", Tick Unit=" + tickUnit); } else { if (lowerBound + tickUnit < upperBound) { // If tickUnit is integer, start with the nearest integer double major = Math.rint(tickUnit) == tickUnit ? Math.ceil(lowerBound) : lowerBound + tickUnit; int count = (int) Math.ceil((upperBound - major) / tickUnit); for (int i = 0; major < upperBound && i < count; major += tickUnit, i++) { if (!tickValues.contains(major)) { tickValues.add(major); } } } } }else {//todo maybe for <1 log base //using amount of ticks per 1 whole log increase final double logUpperBound=Math.log10(upperBound)/log10logBase.get(); final double logLowerBound=Math.log10(lowerBound)/log10logBase.get(); final int tickUnitInt=(int) Math.ceil(tickUnit); if (((logUpperBound - logLowerBound) * tickUnitInt) > 2000) { // This is a ridiculous amount of major tick marks, something has probably gone wrong System.err.println("Warning we tried to create more than 2000 major tick marks on a LogLinAxis. " + "Lower Bound=" + lowerBound + ", Upper Bound=" + upperBound + ", Tick Unit=" + tickUnit); } else { final int logLower=(int)Math.floor(logLowerBound); final int logUpper=(int)Math.ceil(logUpperBound); calculateTicks(tickValues, lowerBound, upperBound, tickUnitInt, logLower, logUpper); } } tickValues.add(upperBound); } return tickValues; } /** * Calculate a list of the data values for every minor tick mark * * @return List of data values where to draw minor tick marks */ private volatile boolean doHack=false; private final ArrayList<Number> minorTickMarks=new ArrayList<Number>(){ @Override public int size() { if(doHack){ doHack=false; return 1; } return super.size(); } }; protected List<Number> calculateMinorTickMarks() { minorTickMarks.clear(); final double lowerBound = getLowerBound(); final double upperBound = getUpperBound(); final double tickUnit = getTickUnit(); final int minorTickCount = getMinorTickCount(); if (tickUnit > 0 && minorTickCount>1) { if(isUsingLinBase()) { final double minorUnit = tickUnit/Math.max(1, getMinorTickCount()); if (((upperBound - lowerBound) / minorUnit) > 10000) { // This is a ridiculous amount of major tick marks, something has probably gone wrong System.err.println("Warning we tried to create more than 10000 minor tick marks on a LogLinAxis. " + "Lower Bound=" + getLowerBound() + ", Upper Bound=" + getUpperBound() + ", Tick Unit=" + tickUnit+ ", Minor Tick Count=" + minorTickCount); return minorTickMarks; } final boolean tickUnitIsInteger = Math.rint(tickUnit) == tickUnit; if (tickUnitIsInteger) { double minor = Math.floor(lowerBound) + minorUnit; int count = (int) Math.ceil((Math.ceil(lowerBound) - minor) / minorUnit); for (int i = 0; minor < Math.ceil(lowerBound) && i < count; minor += minorUnit, i++) { if (minor > lowerBound) { minorTickMarks.add(minor); } } } double major = tickUnitIsInteger ? Math.ceil(lowerBound) : lowerBound; int count = (int) Math.ceil((upperBound - major) / tickUnit); for (int i = 0; major < upperBound && i < count; major += tickUnit, i++) { final double next = Math.min(major + tickUnit, upperBound); double minor = major + minorUnit; int minorCount = (int) Math.ceil((next - minor) / minorUnit); for (int j = 0; minor < next && j < minorCount; minor += minorUnit, j++) { minorTickMarks.add(minor); } } }else{ final double logUpperBound=Math.log10(upperBound)/log10logBase.get(); final double logLowerBound=Math.log10(lowerBound)/log10logBase.get(); final int tickUnitInt=(int) Math.ceil(tickUnit); final int minorTickUnitInt=tickUnitInt*minorTickCount; if (((logUpperBound - logLowerBound) * tickUnit * (minorTickCount-1)) > 10000) { // This is a ridiculous amount of major tick marks, something has probably gone wrong System.err.println("Warning we tried to create more than 10000 minor tick marks on a LogLinAxis. " + "Lower Bound=" + getLowerBound() + ", Upper Bound=" + getUpperBound() + ", Tick Unit=" + tickUnit+ ", Minor Tick Count=" + minorTickCount); } else { final int logBaseLower=(int)Math.floor(logLowerBound); final int logBaseUpper=(int)Math.ceil(logUpperBound); calculateTicks(minorTickMarks, lowerBound, upperBound, minorTickUnitInt, logBaseLower, logBaseUpper); } } } return minorTickMarks; } private void calculateTicks(List<Number> ticks, double lowerBound, double upperBound, int countPerBase, int logBaseLower, int logBaseUpper) { final double[] subDiv=new double[countPerBase-1]; for(int i=0;i<subDiv.length;i++){ subDiv[i]=(i+1)*logBase.get()/countPerBase; } for(int log=logBaseLower;log<=logBaseUpper;log++) { final double logTickBase=Math.pow(logBase.get(),log); for(int i=0;i<subDiv.length;i++){ final double tickValue=logTickBase*subDiv[i]; if(tickValue>lowerBound) { if(tickValue>upperBound){ return; }else{ ticks.add(tickValue); } } } } } /** * Measure the size of the label for given tick mark value. This uses the font that is set for the tick marks * * @param value tick mark value * @param range range to use during calculations * @return size of tick mark label for given value */ @Override protected Dimension2D measureTickMarkSize(Number value, Object range) { final Object[] rangeProps = (Object[]) range; final String formatter = (String)rangeProps[5]; return measureTickMarkSize(value, getTickLabelRotation(), formatter); } /** * Measure the size of the label for given tick mark value. This uses the font that is set for the tick marks * * @param value tick mark value * @param rotation The text rotation * @param numFormatter The number formatter * @return size of tick mark label for given value */ private Dimension2D measureTickMarkSize(Number value, double rotation, String numFormatter) { String labelText; StringConverter<Number> formatter = getTickLabelFormatter(); if (formatter == null) formatter = defaultFormatter; if(formatter instanceof DefaultFormatter) { labelText = ((DefaultFormatter)formatter).toString(value, numFormatter); } else { labelText = formatter.toString(value); } return measureTickMarkLabelSize(labelText, rotation); } private Side getEffectiveSide() { return getSide()==null?Side.BOTTOM:getSide(); } /** * Called to set the upper and lower bound and anything else that needs to be auto-ranged * * @param minValue The min data value that needs to be plotted on this axis * @param maxValue The max data value that needs to be plotted on this axis * @param length The length of the axis in display coordinates * @param labelSize The approximate average size a label takes along the axis * @return The calculated range */ @Override protected Object autoRange(double minValue, double maxValue, double length, double labelSize) { if(isUsingLogBase()){ final double minRounded=Math.pow(logBase.get(),Math.floor(Math.log10(minValue)/log10logBase.get())); final double maxRounded=Math.pow(logBase.get(),Math.ceil(Math.log10(maxValue)/log10logBase.get())); return new Object[]{minRounded, maxRounded, logBase.get(),10, getScale(),""}; } final Side side = getEffectiveSide(); // check if we need to force zero into range if (isForceZeroInRange()) { if (maxValue < 0) { maxValue = 0; } else if (minValue > 0) { minValue = 0; } } // calculate the number of tick-marks we can fit in the given length of the axis int numOfTickMarks = (int)Math.floor(length/labelSize); // can never have less than 2 tick marks one for each end numOfTickMarks = Math.max(numOfTickMarks, 2); int minorTickCount = Math.max(getMinorTickCount(), 1); double range = maxValue-minValue; if (range != 0 && range/(numOfTickMarks*minorTickCount) <= Math.ulp(minValue)) { range = 0; } // pad min and max by 2%, checking if the range is zero final double paddedRange = (range == 0) ? minValue == 0 ? 2 : Math.abs(minValue)*0.02 : Math.abs(range)*1.02; final double padding = (paddedRange - range) / 2; // if min and max are not zero then add padding to them double paddedMin = minValue - padding; double paddedMax = maxValue + padding; // check padding has not pushed min or max over zero line if ((paddedMin < 0 && minValue >= 0) || (paddedMin > 0 && minValue <= 0)) { // padding pushed min above or below zero so clamp to 0 paddedMin = 0; } if ((paddedMax < 0 && maxValue >= 0) || (paddedMax > 0 && maxValue <= 0)) { // padding pushed min above or below zero so clamp to 0 paddedMax = 0; } //todo // calculate tick unit for the number of ticks can have in the given data range double tickUnit = paddedRange/(double)numOfTickMarks; // search for the best tick unit that fits double tickUnitRounded = 0; double minRounded = 0; double maxRounded = 0; int count = 0; double reqLength = Double.MAX_VALUE; String formatter = "0.00000000"; // loop till we find a set of ticks that fit length and result in a total of less than 20 tick marks while (reqLength > length || count > 20) { int exp = (int)Math.floor(Math.log10(tickUnit)); final double mant = tickUnit / Math.pow(10, exp); double ratio = mant; if (mant > 5d) { exp++; ratio = 1; } else if (mant > 1d) { ratio = mant > 2.5 ? 5 : 2.5; } if (exp > 1) { formatter = "#,##0"; } else if (exp == 1) { formatter = "0"; } else { final boolean ratioHasFrac = Math.rint(ratio) != ratio; final StringBuilder formatterB = new StringBuilder("0"); int n = ratioHasFrac ? Math.abs(exp) + 1 : Math.abs(exp); if (n > 0) formatterB.append("."); for (int i = 0; i < n; ++i) { formatterB.append("0"); } formatter = formatterB.toString(); } tickUnitRounded = ratio * Math.pow(10, exp); // move min and max to nearest tick mark minRounded = Math.floor(paddedMin / tickUnitRounded) * tickUnitRounded; maxRounded = Math.ceil(paddedMax / tickUnitRounded) * tickUnitRounded; // calculate the required length to display the chosen tick marks for real, this will handle if there are // huge numbers involved etc or special formatting of the tick mark label text double maxReqTickGap = 0; double last = 0; count = (int)Math.ceil((maxRounded - minRounded)/tickUnitRounded); double major = minRounded; for (int i = 0; major <= maxRounded && i < count; major += tickUnitRounded, i++) { Dimension2D markSize = measureTickMarkSize(major, getTickLabelRotation(), formatter); double size = side.isVertical() ? markSize.getHeight() : markSize.getWidth(); if (i == 0) { // first last = size/2; } else { maxReqTickGap = Math.max(maxReqTickGap, last + 6 + (size/2) ); } } reqLength = (count-1) * maxReqTickGap; tickUnit = tickUnitRounded; // fix for RT-35600 where a massive tick unit was being selected // unnecessarily. There is probably a better solution, but this works // well enough for now. if (numOfTickMarks == 2 && reqLength > length) { break; } if (reqLength > length || count > 20) tickUnit *= 2; // This is just for the while loop, if there are still too many ticks } // calculate new scale final double newScale = calculateNewScale(length, minRounded, maxRounded); // return new range return new Object[]{minRounded, maxRounded, tickUnitRounded,minorTickCount, newScale, formatter}; } // -------------- STYLESHEET HANDLING ------------------------------------------------------------------------------ /** @treatAsPrivate implementation detail */ private static class StyleableProperties { private static final CssMetaData<LogLinAxis,Number> TICK_UNIT = new CssMetaData<LogLinAxis,Number>("-fx-tick-unit", SizeConverter.getInstance(), 5.0) { @Override public boolean isSettable(LogLinAxis n) { return n.logTickCount == null || !n.logTickCount.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(LogLinAxis n) { return (StyleableProperty<Number>) n.tickUnitProperty(); } }; private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES; static { final List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<CssMetaData<? extends Styleable, ?>>(ValueAxis.getClassCssMetaData()); styleables.add(TICK_UNIT); STYLEABLES = Collections.unmodifiableList(styleables); } } /** * @return The CssMetaData associated with this class, which may include the * CssMetaData of its super classes. * @since JavaFX 8.0 */ public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return StyleableProperties.STYLEABLES; } /** * {@inheritDoc} * @since JavaFX 8.0 */ @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return getClassCssMetaData(); } // -------------- INNER CLASSES ------------------------------------------------------------------------------------ /** * Default number formatter for LogarithmicAxis2, this stays in sync with auto-ranging and formats values appropriately. * You can wrap this formatter to add prefixes or suffixes; * @since JavaFX 2.0 */ public static class DefaultFormatter extends StringConverter<Number> { private DecimalFormat formatter; private String prefix = null; private String suffix = null; /** * Construct a DefaultFormatter for the given LogarithmicAxis2 * * @param axis The axis to format tick marks for */ public DefaultFormatter(final LogLinAxis axis) { DecimalFormatSymbols symbols=new DecimalFormatSymbols(); symbols.setGroupingSeparator(' '); setFormatter(axis, symbols); final ChangeListener<Object> axisListener = (observable, oldValue, newValue) -> setFormatter(axis, symbols); axis.currentFormatterProperty.addListener(axisListener); axis.autoRangingProperty().addListener(axisListener); } private void setFormatter(LogLinAxis axis, DecimalFormatSymbols symbols) { formatter = axis.isAutoRanging()? new DecimalFormat(axis.currentFormatterProperty.get(),symbols) : new DecimalFormat("",symbols); formatter.setRoundingMode(RoundingMode.HALF_UP); formatter.setMaximumFractionDigits(3); formatter.setMinimumIntegerDigits(1); } /** * Construct a DefaultFormatter for the given LogarithmicAxis2 with a prefix and/or suffix. * * @param axis The axis to format tick marks for * @param prefix The prefix to append to the start of formatted number, can be null if not needed * @param suffix The suffix to append to the end of formatted number, can be null if not needed */ public DefaultFormatter(LogLinAxis axis, String prefix, String suffix) { this(axis); this.prefix = prefix; this.suffix = suffix; } /** * Converts the object provided into its string form. * Format of the returned string is defined by this converter. * @return a string representation of the object passed in. * @see StringConverter#toString */ @Override public String toString(Number object) { return toString(object, formatter); } private String toString(Number object, String numFormatter) { if (numFormatter == null || numFormatter.isEmpty()) { return toString(object, formatter); } else { return toString(object, new DecimalFormat(numFormatter)); } } private static final StringBuilder builder=new StringBuilder(); private String toString(Number object, DecimalFormat formatter) { builder.setLength(0); if(prefix!=null){ builder.append(prefix); } String number=formatter.format(object); //if(object.doubleValue()<3 || number.length()>6){ // builder.append(); //}else { builder.append(number); //} if(suffix!=null){ builder.append(suffix); } return builder.toString(); } /** * Converts the string provided into a Number defined by the this converter. * Format of the string and type of the resulting object is defined by this converter. * @return a Number representation of the string passed in. * @see StringConverter#toString */ @Override public Number fromString(String string) { try { int prefixLength = (prefix == null)? 0: prefix.length(); int suffixLength = (suffix == null)? 0: suffix.length(); return formatter.parse(string.substring(prefixLength, string.length() - suffixLength)); } catch (ParseException e) { return null; } } } //pixel relative to value? @Override public Number getValueForDisplay(double displayPosition) { if(isUsingLinBase()){ return super.getValueForDisplay(displayPosition); }else { //return toRealValue(Math.pow(logBase.get(), (displayPosition - offset) / logScale.get() + currentLowerBound.get())); return toRealValue(Math.pow(logBase.get(), (displayPosition - offset) / logScale.get() + currentLowerLogBound.get())); } } //value to pixel relative? @Override public double getDisplayPosition(Number value) { System.out.println("currentLowerLogBound2 = " + currentLowerLogBound.get()); if(isUsingLinBase()){ return super.getDisplayPosition(value); }else { //return offset + (Math.log10(value.doubleValue())/log10logBase.get()-currentLowerLogBound.get())*logScale.get(); return offset + (Math.log10(value.doubleValue())/log10logBase.get()-currentLowerLogBound.get())*logScale.get(); } } }
Java
UTF-8
12,163
2.921875
3
[]
no_license
package org.ProxiBanque.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.ProxiBanque.domaine.Client; import org.ProxiBanque.domaine.Conseiller; import org.ProxiBanque.domaine.Courant; import org.ProxiBanque.domaine.Epargne; /** * @author Stagiaire * */ public class ClientDAO { // ClientDAO est la classe dans la couche DAO qui permet d'acceder aux // informations de la table 'Client'de la base de donnee specifiee dans la // classe Connexion. // Un client correspond a une ligne de la table. // Cette classe permet de creer, lire les informations, modifier, supprimer un // client, de recuperer ses comptes et de recuperer la liste de la // totalite des // clients ou seulement ceux propre a un conseiller. // Methode permettant d'inserer un client en base de donnee en prenant un // objet // de type client en entree et retournant un boolean de valeur true si // l'operation a ete un succes. /** * @param client * @return */ public boolean createClient(Client client) { int i = 0; boolean b = false; try { Statement stmt = Connexion.connexion().createStatement(); // Creation d'un objet de type Statement // Affectation a la chaine de caractere s de la requete SQL String s = "INSERT INTO `client`(`adresse`, `nom`, `prenom`, `codePostal`, `ville`, `email`, `situationFinanciere`, `situationProfessionnel`, `idConseiller`, `telephone`, `soldeTotal`) VALUES ('" + client.getAdresse() + "', '" + client.getNom() + "', '" + client.getPrenom() + "', '" + client.getCodePostal() + "', '" + client.getVille() + "', '" + client.getEmail() + "', '" + client.getSituationFinanciere() + "', '" + client.getSituationProfessionnel() + "', " + client.getidConseiller() + ", '" + client.getTelephone() + "', " + client.getSoldeTotal() + ")"; // execution de la requete i = stmt.executeUpdate(s); } catch (SQLException e) { e.printStackTrace(); } // Si l'operation est un succes, i est differend de 0 et la methode // retourne // true if (i != 0) b = true; return b; } // Methode permettant de recuperer les informations d'un client de la // table // 'client' en prenant comme parametre d'entree un objet client presentant // comme // attribut l'idClient du client a recuperer. La methode retourne un // objet // client presentants les informations recuperees. /** * @param client * @return */ public Client getClient(Client client) { try { Statement stmt = Connexion.connexion().createStatement(); // Creation d'un objet de type Statement // Affectation � la chaine de caract�re s de la requ�te SQL String s = "Select * from Client where idClient = " + client.getIdClient(); // Ex�cution de la requ�te ResultSet rs = stmt.executeQuery(s); // Lecture des r�sultats de la requ�te rs.next(); client.setIdClient(rs.getInt("idClient")); client.setAdresse(rs.getString("adresse")); client.setNom(rs.getString("nom")); client.setPrenom(rs.getString("prenom")); client.setCodePostal(rs.getString("codePostal")); client.setVille(rs.getString("ville")); client.setEmail(rs.getString("email")); client.setSituationFinanciere(rs.getString("situationFinanciere")); client.setSituationProfessionnel(rs.getString("situationProfessionnel")); client.setidConseiller(rs.getInt("idConseiller")); client.setTelephone(rs.getString("telephone")); client.setSoldeTotal(rs.getInt("soldeTotal")); } catch (SQLException e) { e.printStackTrace(); } return client; } // M�thode permettant de modifier les informations d'un client de la table // 'client' en prenant comme param�tre d'entr�e un objet client pr�sentant // les // nouvelles valeurs d'attributs . La m�thode retourne l'objet client // r�cup�r� // de la base de donn�e avec les nouvelles valeurs d'attribut. /** * @param client * @return */ public Client updateClient(Client client) { try { Statement stmt = Connexion.connexion().createStatement(); // Cr�ation d'un objet de type Statement // Affectation � la chaine de caract�re s de la requ�te SQL String s = "UPDATE client set adresse = '" + client.getAdresse() + "', nom = '" + client.getNom() + "', prenom = '" + client.getPrenom() + "', CodePostal = '" + client.getCodePostal() + "', ville = '" + client.getVille() + "', email = '" + client.getEmail() + "', situationProfessionnel = '" + client.getSituationProfessionnel() + "', idConseiller = " + client.getidConseiller() + ", telephone = '" + client.getTelephone() + "', soldeTotal = "+client.getSoldeTotal()+" where idClient = " + client.getIdClient() + ""; // ex�cution de la requ�te stmt.executeUpdate(s); // Affectation � la chaine de caract�re s de la requ�te SQL s = "Select * from client where idClient = " + client.getIdClient(); ResultSet rs = stmt.executeQuery(s); // Lecture des r�sultats de la requ�te rs.first(); client.setIdClient(rs.getInt("idClient")); client.setAdresse(rs.getString("adresse")); client.setNom(rs.getString("nom")); client.setPrenom(rs.getString("prenom")); client.setCodePostal(rs.getString("codePostal")); client.setVille(rs.getString("ville")); client.setEmail(rs.getString("email")); client.setSituationFinanciere(rs.getString("situationFinanciere")); client.setSituationProfessionnel(rs.getString("situationProfessionnel")); client.setidConseiller(rs.getInt("idConseiller")); client.setTelephone(rs.getString("telephone")); client.setSoldeTotal(rs.getInt("soldeTotal")); } catch (SQLException e) { e.printStackTrace(); } return client; } // M�thode permettant de suppimer l'entr�e de la table 'client' pr�sentant // le // m�me idClient que l'objet client en param�tre d'entr�e de m�thode et // retournant un boolean de valeur true si // l'op�ration a �t� un succ�s. /** * @param client * @return */ public boolean deleteClient(Client client) { int i; boolean b = false; try { Statement stmt = Connexion.connexion().createStatement(); // Cr�ation d'un objet de type Statement // Affectation � la chaine de caract�re s de la requ�te SQL, il est // n�cessaire // de supprimer les comptes du client avant de le supprimer car la table // 'compte' est d�pendante de la table 'client' String s = "DELETE from compte where idClient = " + client.getIdClient(); // ex�cution de la requ�te i = stmt.executeUpdate(s); // Affectation � la chaine de caract�re s de la requ�te SQL s = "DELETE from client where idClient = " + client.getIdClient(); // ex�cution de la requ�te i = stmt.executeUpdate(s); // Si l'op�ration est un succ�s, i est diff�rend de 0 et la m�thode // retourne // true if (i != 0) b = true; } catch (SQLException e) { e.printStackTrace(); } return b; } // M�thode retournant une liste de toute les entr�es de la table 'client' de // la // base de donn�e. /** * @return */ public List<Client> getAllClient() { List<Client> listClient = new ArrayList<Client>(); try { Statement stmt = Connexion.connexion().createStatement(); // Cr�ation d'un objet de type Statement // Affectation � la chaine de caract�re s de la requ�te SQL String s = "Select * from Client"; // ex�cution de la requ�te ResultSet rs = stmt.executeQuery(s); // Lecture des r�sultats de la requ�te et insertion dans la liste pour // chaque // boucle while (rs.next()) { Client client = new Client(); client.setIdClient(rs.getInt("idClient")); client.setAdresse(rs.getString("adresse")); client.setNom(rs.getString("nom")); client.setPrenom(rs.getString("prenom")); client.setCodePostal(rs.getString("codePostal")); client.setVille(rs.getString("ville")); client.setEmail(rs.getString("email")); client.setSituationFinanciere(rs.getString("situationFinanciere")); client.setSituationProfessionnel(rs.getString("situationProfessionnel")); client.setidConseiller(rs.getInt("idConseiller")); client.setTelephone(rs.getString("telephone")); client.setSoldeTotal(rs.getInt("soldeTotal")); listClient.add(client); } } catch (SQLException e) { return null; } return listClient; } // M�thode retournant une liste de toute les entr�es de la table 'client' // correspondant � l'objet conseiller en entr�e de m�thode /** * @param conseiller * @return */ public List<Client> getAllClientConseiller(Conseiller conseiller) { List<Client> listClient = new ArrayList<Client>(); try { Statement stmt = Connexion.connexion().createStatement(); // Cr�ation d'un objet de type Statement // Affectation � la chaine de caract�re s de la requ�te SQL String s = "Select * from Client where idConseiller = " + conseiller.getIdConseiller(); // ex�cution de la requ�te ResultSet rs = stmt.executeQuery(s); // Lecture des r�sultats de la requ�te et insertion dans la liste pour // chaque // boucle while (rs.next()) { Client client = new Client(); client.setIdClient(rs.getInt("idClient")); client.setAdresse(rs.getString("adresse")); client.setNom(rs.getString("nom")); client.setPrenom(rs.getString("prenom")); client.setCodePostal(rs.getString("codePostal")); client.setVille(rs.getString("ville")); client.setEmail(rs.getString("email")); client.setSituationFinanciere(rs.getString("situationFinanciere")); client.setSituationProfessionnel(rs.getString("situationProfessionnel")); client.setidConseiller(rs.getInt("idConseiller")); client.setTelephone(rs.getString("telephone")); client.setSoldeTotal(rs.getInt("soldeTotal")); listClient.add(client); } } catch (SQLException e) { return null; } return listClient; } // M�thode retournant le compte courant associ� au client en param�tre // d'entr�e // de m�thode. /** * @param client * @return */ public Courant getCompteCourant(Client client) { Courant compte = new Courant(); try { Statement stmt = Connexion.connexion().createStatement(); // Cr�ation d'un objet de type Statement // Affectation � la chaine de caract�re s de la requ�te SQL String s = "Select * from compte inner Join client on compte.idClient = client.idClient where typeDeCompte = 'courant' && client.idClient = " + client.getIdClient(); // ex�cution de la requ�te ResultSet rs = stmt.executeQuery(s); // Lecture des r�sultats de la requ�te rs.first(); compte.setIdClient(rs.getInt("IdClient")); compte.setIdCompte(rs.getInt("IdCompte")); compte.setNumeroCompte(rs.getInt("numeroCompte")); compte.setDecouvertAutorise(rs.getDouble("decouvertAutorise")); compte.setSolde(rs.getDouble("solde")); compte.setTypeCarte(rs.getString("typeCarte")); } catch (SQLException e) { return null; } return compte; } // M�thode retournant le compte �pargne associ� au client en param�tre // d'entr�e // de m�thode. /** * @param client * @return */ public Epargne getCompteEpargne(Client client) { Epargne compte = new Epargne(); try { Statement stmt = Connexion.connexion().createStatement(); // Cr�ation d'un objet de type Statement // Affectation � la chaine de caract�re s de la requ�te SQL String s = "Select * from compte inner Join client on compte.idClient = client.idClient where typeDeCompte = 'epargne' && client.idClient = " + client.getIdClient(); // ex�cution de la requ�te ResultSet rs = stmt.executeQuery(s); // Lecture des r�sultats de la requ�te rs.next(); compte.setIdClient(rs.getInt("IdClient")); compte.setIdCompte(rs.getInt("IdCompte")); compte.setNumeroCompte(rs.getInt("numeroCompte")); compte.setSolde(rs.getDouble("solde")); compte.setTauxInteret(rs.getDouble("tauxInteret")); } catch (SQLException e) { return null; } return compte; } }
C#
UTF-8
2,955
2.90625
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleLog.Repository { internal class LogTextFileContext : ILogContextAdd { #region attributes private string _FileName; #endregion #region properties public string FileName { get { return this._FileName; } set { this._FileName = value; addHeader(); } } #endregion #region constructors public LogTextFileContext(dynamic settings) { this.FileName = settings.FileName; this.CanAddError = settings.CanAddError; this.CanAddWarning = settings.CanAddWarning; this.CanAddInfo = settings.CanAddInfo; } #endregion public bool CanAddError { get; set; } public bool CanAddInfo { get; set; } public bool CanAddWarning { get; set; } public void Add(Message message) { #region check if can add message type switch (message.MessageType) { case Constants.MESSAGE_TYPE_ERROR: if (!this.CanAddError) { return; } break; case Constants.MESSAGE_TYPE_WARNING: if (!this.CanAddWarning) { return; } break; case Constants.MESSAGE_TYPE_INFO: if (!this.CanAddInfo) { return; } break; } #endregion validate(message); using (StreamWriter sw = File.AppendText(this._FileName)) { sw.WriteLine(string.Format("\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\", \"{5}\", \"{6}\", \"{7}\"", message.ID, message.Owner, message.IdentifierName, message.IdentifierValue, message.Group, message.Operation, message.Data, message.CreatedOn)); } } private void validate(Message message) { if(string.IsNullOrWhiteSpace(this.FileName)) { throw new InvalidOperationException("Filename not set in LogTextFileContext"); } } private void addHeader() { if (!File.Exists(this._FileName)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(this._FileName)) { sw.WriteLine("\"ID\", \"Owner\", \"IdentifierName\", \"IdentifierValue\", \"Group\", \"Operation\", \"Data\", \"CreatedOn\""); } } } } }
PHP
UTF-8
3,462
2.734375
3
[]
no_license
<?php session_start(); if (!isset($_SESSION['admin_access'])) { exit; } //this class formats the dropdown menu for clubs and facilities class loadInstructorsRooms { private $typeId = null; private $instructorName = null; private $instructorId = null; private $roomName = null; private $roomId = null; private $instructorDrops = null; private $roomDrops = null; private $rowCountOne = null; private $rowCountTwo = null; function setTypeId($typeId) { $this->typeId = $typeId; } //connect to database function dbconnect() { require"../dbConnect.php"; return $dbMain; } //----------------------------------------------------------------------------------------------------- function loadInstructorMenu() { $dbMain = $this->dbconnect(); $stmt = $dbMain ->prepare("SELECT instructor_id, instructor_name FROM instructor_info WHERE type_id = '$this->typeId' "); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($instructor_id, $instructor_name); $rowCount = $stmt->num_rows; $this->rowCountOne = $rowCount; if($rowCount > 0) { while ($stmt->fetch()) { $type_select .= "<option value=\"$instructor_id\">$instructor_name</option>\n"; } } $stmt->close(); $choose_type = "<option value>Select Instructor</option>\n"; $this->instructorDrops = "$choose_type$type_select"; } //----------------------------------------------------------------------------------------------------- function loadRoomMenu() { $dbMain = $this->dbconnect(); $stmt = $dbMain ->prepare("SELECT room_id, room_name FROM room_names WHERE type_id = '$this->typeId' "); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($room_id, $room_name); $rowCount = $stmt->num_rows; $this->rowCountTwo = $rowCount; if($rowCount > 0) { while ($stmt->fetch()) { $type_select .= "<option value=\"$room_id\">$room_name</option>\n"; } } $stmt->close(); $choose_type = "<option value>Select Room</option>\n"; $this->roomDrops = "$choose_type$type_select"; } //----------------------------------------------------------------------------------------------------------- function getRowCountOne() { return($this->rowCountOne); } function getRowCountTwo() { return($this->rowCountTwo); } function getInstructorDrops() { return($this->instructorDrops); } function getRoomDrops() { return($this->roomDrops); } } //====================================================== $ajax_switch = $_REQUEST['ajax_switch']; $schedule_type = $_REQUEST['schedule_type']; if($ajax_switch == "1") { $irDrops = new loadInstructorsRooms(); $irDrops-> setTypeId($schedule_type); $irDrops-> loadInstructorMenu(); $irDrops-> loadRoomMenu(); $row_count1 = $irDrops-> getRowCountOne(); $row_count2 = $irDrops-> getRowCountTwo(); if($row_count1 == 0 || $row_count2 == 0) { $type_drops = "1|bull|bull"; }else{ $instructor_drops = $irDrops-> getInstructorDrops(); $room_drops = $irDrops-> getRoomDrops(); $type_drops = "2|$instructor_drops|$room_drops"; } echo"$type_drops"; exit; } //------------------------------------------------------------------------------- ?>
Markdown
UTF-8
10,800
2.96875
3
[]
no_license
## eBenefits 21-686c Form Usability Session 1 #### Conducted: February 19, 2020 via Zoom #### Moderator: Aricka Lewis #### Participant: NB (F) #### Session Recorded: Yes #### Note-taker: S. Bildstein ## Participant 1 Thanks for joining us today! My name is Aricka and I also have some colleagues on the line observing and taking notes. Today we&#39;re going to talk about adding and removing dependents to/from your benefits on the VA website. Before we start, a few things I want to mention: - **This entire session should take about 30 minutes.** I want to be sure not to keep you much longer, so I may occasionally prompt you with the next question or topic. - **In this session, we want to hear your honest opinions.** We are not testing your ability. We just want to improve these tools to better meet Veteran&#39;s needs. I will not be offended by any opinions you express, and I welcome your feedback. - **You&#39;ll be interacting with a prototype.** This is a demo tool that may not function exactly the way you expect. Some areas of the prototype will be clickable, and some will not. Since it&#39;s a demo, none of your actions will affect your actual VA information or benefits. - **If for any reason and at any time you want to stop the session, please let me know.** - **Are you comfortable if I record my screen and audio as we talk today?** We use the recordings to confirm that we have captured your opinions accurately. The recordings are destroyed after we complete analysis, and none of your comments will be attributed to you directly. - If yes: **Once I start recording, I am going to confirm that you are ok with me recording this session once more.** _Start recording._ - \*\*I have started recording. I&#39;d like to confirm: Are you comfortable if I record my screen and audio as we talk today?&quot; ## **Warm-up Questions** Before we look at the prototype, let&#39;s start with a few warm-up questions. - Please tell me about your service history. I was a linguist for 20 years, joined in 94 and retired in 2014. I was deployed 1 and has a 1 year remote. That&#39;s just about it really. - What are your experiences adding or removing dependents from your disability claim? It was relatively easy but it was easier than it was with DSFA. When I got married and got married and now that I have sent all of the paperwork it still has not reflected after 3 years. I have not had any issue adding my husband to the VA. - Are you familiar with the VA 21-686 form? And what is your experience using the form (online or paper)? No, not by that name. ## **Screenshare** Will you share your screen with me? I&#39;m going to send you a link. I will be asking you to complete a few tasks using this prototype. Try to move a bit slower than you normally would on a website and talk me through your actions. ## **First Task: Find and select form(s)** You&#39;ve recently been married and want to add you new spouse and their child to your benefits. Show us how you would do this. First I would scroll down to see if it is in the boxes at all. It is not obvious here. I would go to the tab and click family member benefits to see what it says there. I am looking down the list to see if it is obvious so instead of looking forever I go to the search and place, add family members. I am looking for add or remove dependent. First impress: It has a nice title and it is obvious what it is for. I like that it has what you need to have before you add someone. It looks pretty good I don&#39;t see anything obvious that would be missing. Any questions: No not really. ## **Second Task: Step through form** Walk through the steps of this form. Be sure to think aloud and comment on the process of walking through the form. What would you do: click add or remove. Click claim benefits for spouse and child, oh it only lets me do one or another. Next: click continue. That is not my information. Click continue. Review the address and click continue. Fill in information then click continue. Impression on the fields shown: They all make sense, there&#39;s not much. It only applies for when you are finished, is there any information on how long it will take them to respond. I would really like to see that because I haven&#39;t talked to anyone so I don&#39;t know what is going on with it and it would be nice to see this reflected within the next 2 or 4 weeks. Next: Fill in information click continue. If I click others for marriage can I type it in. Maybe people that have had a proxy marriage would know what it is but an explanation may be good. It looks good. I don&#39;t see anything else than. Feed back on live with spouse: What are the implications if I have reason for separation, if you are separated because you have jobs in two different cities. Are there implications to the benefits at all if you are separated. Other than that it looks fine. Married prior- Are there implications if they have been married to someone that was in the military, a box that will explain what the implications to if they have va benefits already. I know that you want to keep this as clean and simple as possible but maybe a popup that someone can look at. Same thing with former spouse information because there are rules about the benefits that you can have. Next: Adding child, click continue. Feedback for adding a child: I see the if its not your biological child but a popup that explains the benefits for the child. What you can expect and what you cannot expect. Questions/feedback: Maybe also that same thing. Like if you are marrying someone with a child and the child may already have benefits through the VA. That happens often that someone gets divorced and the one parent has benefits through the VA and the new spouse has benefits through the VA. Do both the parent and step-parent get benefits. It should explain how that works and not be extremely confusing. If the child has been previously married, then what&#39;s frustrating is people go through this than find out that they are not eligible. It would be good to have the questions upfront instead of after you have filled everything out. Have all the criteria up front that will tell you if they are eligible or not eligible. Feedback for uploading evidence: It is straightforward it is just adding the information. You have a link to the additional evidence. It would be good to know what not additional evidence is. Like pictures or somethings that people think that it should that I am with this child. So it would be good to know what they do not consider evidence. ## **Third Task: Review application - X minutes** Take a moment to review the information presented on the screen. - Click the area of the prototype to complete this application process. What do you expect the sections to do: I would expect to jump back and change or edit. It should show me what I wrote and if I can see it and edit what I put in. That&#39;s pretty much it, just being able to jump back instead of having to go from the beginning and going all over it again. No one ever reads the privacy policy. That&#39;s just about it. Maybe being able to print it off to save it as a file, people like to have the evidence that they submitted it at this time and this is what I put in there. Next: Click submit. Impression: It does say it will take one week but people are not satisfied with that. Some people like to know how many applications there are awaiting because of holidays or the people are on strike. I like the line at the bottom. I had one more question but I don&#39;t remember what it is now. I think this looks really good and simple. ## **Fourth Task (if time): Remove** Let&#39;s say that your step-child has moved out on their own. How would you go about removing them from your benefits? It says to go through the add or remove. Report that a stepchild has left the household. Go through to verify who I am, none of the information has changed. The child has moved, yes that is the information about my stepchild. Supporting stepchild still, click no. Say the child has moved out on their own, this says who the child lives with, it should have a box that has self since they moved out on their own and not with another. I am wondering if it is required to add the child&#39;s address. If it is a va thing that it has to be submitted I understand but I don&#39;t think it should be because it is being taken off of the benefits. The VA doesn&#39;t need to know the address because its not their responsibility and maybe the child doesn&#39;t want them to know their address. That is the only thing, if they have aged out but if they are just being removed I understand. Review the application and submit. That&#39;s it and it has the same stuff as the other one. ## **Post-Task Interview** - Would you prefer to complete multiple tasks at the same time? Or individually? I prefer to do it altogether. - What are your thoughts on the length of the form? I think they were fine. I prefer but understand that you don&#39;t want to take up too much of the screen within information I prefer not to scroll as much so have as much information on one screen so you don&#39;t need to scroll. - What are your thoughts on completing a form that requires this type of personal information? The form must be done one way or the other if you want to get the benefits. If I don&#39;t feel like or like actually doing it on the computer you can fill it out and send it by mail. There is a choice. Some people don&#39;t like doing it on the computer so there should be a choice between online and paper. - What would you change about this prototype Not much really, it was well thought out for it being a child, step-child moving out. You should be able to click that they have left the nest and that should only be a one click thing and not put in their address. - Favorite part it was really easy. The fact that it had the information upfront that you need to fill out the form. - What kind of device (mobile/desktop/tablet) do you use most often? Would you use that kind of device to fill this form out? Usually my laptop. Yes. - Any questions for me? No I can&#39;t think of anything else. I think you guys are doing a good job. ## **Thank-You and Closing** Well we really appreciate you taking the time to share your thoughts with us today. Your feedback is so helpful to us as we continue to work on the site and make sure it really works for Veterans. Thanks! Lastly, do you know any other Veterans, caregivers, or service members who might be willing to participate in a future user research session? If Yes: Thank you! I&#39;ll have our team send you an email with a little blurb that you can pass along. Great, well thank you so much again, and enjoy the rest of your day!
TypeScript
UTF-8
1,504
2.59375
3
[]
no_license
import { inject, injectable } from 'tsyringe'; import { classToClass } from 'class-transformer'; import IUsersRepository from '@modules/users/repositories/IUsersRepository'; import ICacheProvider from '@shared/container/providers/CacheProvider/models/ICacheProvider'; import User from '@modules/users/infra/typeorm/entities/User'; interface IRequest { user_id: string; } @injectable() class ListProvidersService { constructor( @inject('UsersRepository') private usersRepository: IUsersRepository, @inject('CacheProvider') private cacheProvider: ICacheProvider, ) { // do nothing } public async execute({ user_id }: IRequest): Promise<User[]> { // Recuperando dados salvos em cache marcados por uma 'chave' do 'user_id': let users = await this.cacheProvider.recover<User[]>( `providers-list:${user_id}`, ); // Condiçao para caso nao encontrarmos os usuários em cache, iremos buscar no banco de dados e salvar em cache: if (!users) { // Listagem de todos os usuários, com exceçao o do próprio usuário que está fazendo a listagem: users = await this.usersRepository.findAllProviders({ except_user_id: user_id, }); // Salvando dados em cache marcados por uma 'chave' para não sobrescrevermos os caches de outros usuários: await this.cacheProvider.save( `providers-list:${user_id}`, classToClass(users), ); } return users; } } export default ListProvidersService;
Java
UTF-8
243
2.515625
3
[]
no_license
package com.company.model; import com.company.model.RealEstate; public class Street extends RealEstate { public Street(String name, int cost, int defRent){ setName(name); setCost(cost); setRent(defRent); } }
Java
UTF-8
4,687
2.6875
3
[]
no_license
package ab2.test; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.junit.Assert; import org.junit.Test; import ab2.AbstractHashMap; import ab2.AuD2; import ab2.impl.Gaggl_Gundacker_Kopali.AuD2Impl; public class Tests { private AuD2 impl = new AuD2Impl(); private static final int MOM_TEST_COUNT = 10; private static final int MOM_TEST_MINSIZE = 1; private static final int MOM_TEST_MAXSIZE = (int) Math.pow(2, 20); private static final int HASH_TEST_COUNT = 10; private static final int HASH_TEST_MINSIZE = 1; private static final int HASH_TEST_MAXSIZE = (int) Math.pow(2, 20); private static final double HASH_MAX_LOADFACTOR = 0.5; private static final Random rand = new Random(System.currentTimeMillis()); // 3 Pts @Test public void testHashLinear_3() { AbstractHashMap hm = impl.newHashMapLinear(14); Assert.assertEquals(14, hm.totalSize()); checkFullMap(hm); for (int size = HASH_TEST_MINSIZE; size <= HASH_TEST_MAXSIZE; size *= 2) { int maxElements = (int) Math.max(size * HASH_MAX_LOADFACTOR, 1); for (int i = 0; i < HASH_TEST_COUNT; i++) { AbstractHashMap hashMap = impl.newHashMapLinear(size); testAbstractHashMap(hashMap, maxElements); } } } // 3 Pts @Test public void testHashQuadratic_3() { AbstractHashMap hm = impl.newHashMapQuadratic(14); Assert.assertEquals(19, hm.totalSize()); checkFullMap(hm); for (int size = HASH_TEST_MINSIZE; size <= HASH_TEST_MAXSIZE; size *= 2) { int maxElements = (int) Math.max(size * HASH_MAX_LOADFACTOR, 1); for (int i = 0; i < HASH_TEST_COUNT; i++) { AbstractHashMap hashMap = impl.newHashMapQuadratic(size); testAbstractHashMap(hashMap, maxElements); } } } //3 Pts @Test public void testHashDouble_3() { AbstractHashMap hm = impl.newHashMapDouble(14); Assert.assertEquals(17, hm.totalSize()); checkFullMap(hm); for (int size = HASH_TEST_MINSIZE; size <= HASH_TEST_MAXSIZE; size *= 2) { int maxElements = (int) Math.max(size * HASH_MAX_LOADFACTOR, 1); for (int i = 0; i < HASH_TEST_COUNT; i++) { AbstractHashMap hashMap = impl.newHashMapDouble(size); testAbstractHashMap(hashMap, maxElements); } } } private void checkFullMap(AbstractHashMap hashMap) { for(int i = 0; i < hashMap.totalSize(); i++) { assertEquals(true, hashMap.put(i, i+"")); } assertEquals(false, hashMap.put(-1, "ein Wert zu viel")); } private void testAbstractHashMap(AbstractHashMap hashMap, int elementCount) { int totalSize = hashMap.totalSize(); // Als Referenz wird eine Map erzeugt, um die Implementierung zu testen Map<Integer, String> hashMapRef = new HashMap<>(totalSize); // Befülle die HashMaps for (int i = 0; i < elementCount; i++) { int key = rand.nextInt(totalSize); String value = "Wert " + key; hashMap.put(key, value); hashMapRef.put(key, value); } assertEquals(hashMapRef.size(), hashMap.elementCount()); // Teste, ob die Werte wiedergefunden werden for (int i = 0; i < 10*elementCount; i++) { int key = rand.nextInt(totalSize); String value = hashMap.get(key); String valueRef = hashMapRef.get(key); assertEquals(valueRef, value); } } // 3 Pts @Test public void testMediansOfMedians_3() { for (int size = MOM_TEST_MINSIZE; size <= MOM_TEST_MAXSIZE; size *= 2) { int[] data = new int[size]; for (int i = 0; i < MOM_TEST_COUNT; i++) { fillRandomInts(data, MOM_TEST_MAXSIZE); // kopiere das Array, sortiere es und bestimme den Median int[] data_sorted = Arrays.copyOf(data, data.length); Arrays.sort(data_sorted); int median_expected = data_sorted[data_sorted.length / 2]; // bestimme den berechneten Wert laut Implementierung int median = impl.getMedian(data); assertEquals(median_expected, median); } } } private void fillRandomInts(int[] data, int maxValue) { for (int i = 0; i < data.length; i++) { data[i] = rand.nextInt(maxValue + 1); } } }
PHP
UTF-8
1,081
2.703125
3
[]
no_license
<?php require_once '../../service/CuentaService.php'; require_once '../../model/Cuenta.php'; $data = json_decode(file_get_contents("php://input")); try { $nombres = $data->nombres; $apaterno = $data->aparteno; $ci = $data->ci; $celular = $data->celular; $tipocuenta = $data->tipocuenta; $ciudad = $data->ciudad; if($nombres != NULL && $celular != NULL && $ci != NULL && $tipocuenta != NULL && $ciudad != NULL){ $cuentaService = new CuentaService(); $cuenta = new Cuenta(); $cuenta->setCi($ci); $cuenta->setCelular($celular); $cuenta->setNombres($nombres); $cuenta->setAparteno($apaterno); $cuenta->setTipoCuenta($tipocuenta); $cuenta->setCiudad($ciudad); echo json_encode($cuentaService->saveCuenta($cuenta)); } else{ echo json_encode("Datos Incorrectos"); } } catch (Exception $ex) { echo json_encode('Entra por errores'); } ?>
Python
UTF-8
579
3.265625
3
[ "Apache-2.0" ]
permissive
import unittest from chapter_02.src.answer_04 import get_partition from chapter_02.src.LinkedList import LinkedList class TestPartition(unittest.TestCase): def test_empty_list(self): self.assertIs(get_partition(None, 4), None) def test_not_x(self): self.assertEqual(get_partition(LinkedList([1,2,3,4]), 5), LinkedList([1,2,3,4])) def test_delete_node(self): self.assertEqual(get_partition(LinkedList([3, 5, 8, 5, 10, 2, 1]), 5), LinkedList([3, 2, 1, 5, 8, 5, 10])) if __name__ == '__main__': unittest.main()
C#
UTF-8
2,346
3.484375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TabliceDwuwymiarowe { class Program { static void Main(string[] args) { Random random = new Random(); Console.WriteLine(random.Next(200)); int[,] tablica = new int[10, 10]; int liczba=0, maxLiczba=0; int pozycjaX = 0, pozycjaY = 0 ; for (int rowNumber = 0; rowNumber < tablica.GetLength(0); rowNumber++) { for (int columnNumber = 0; columnNumber < tablica.GetLength(0); columnNumber++) { tablica[rowNumber, columnNumber] = random.Next(200); } } for (int rowNumber = 0; rowNumber < tablica.GetLength(0); rowNumber++) { Console.ForegroundColor = ConsoleColor.DarkMagenta; Console.WriteLine("------------------------------------------------------------"); Console.Write("| "); for (int columnNumber = 0; columnNumber < tablica.GetLength(0); columnNumber++) { Console.ForegroundColor = ConsoleColor.White; Console.Write(Convert.ToString(tablica[rowNumber,columnNumber]).PadRight(3)); Console.ForegroundColor = ConsoleColor.DarkMagenta; Console.Write(" | "); } Console.WriteLine(""); } Console.WriteLine("-------------------------------------------------------------"); for (int rowNumber = 0; rowNumber < tablica.GetLength(0); rowNumber++) { for (int columnNumber = 0; columnNumber < tablica.GetLength(0); columnNumber++) { liczba = tablica[rowNumber, columnNumber]; if (liczba >maxLiczba) { maxLiczba = liczba; pozycjaX = rowNumber; pozycjaY = columnNumber; } } } Console.WriteLine($"MaxLiczba to: {maxLiczba} na pozycji {Environment.NewLine} {pozycjaX} {pozycjaY}"); Console.ReadKey(); } } }
Java
UTF-8
733
2.390625
2
[]
no_license
package ramchat.model.dao.impl; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import javax.imageio.ImageIO; public class FileClientConnectDaoImpl { public BufferedImage getImg(String id) throws IOException { Socket sk = null; InputStream is = null; BufferedImage img = null; PrintWriter pw = null; try { sk= new Socket("192.168.0.36", 7002); pw = new PrintWriter(sk.getOutputStream(), true); pw.println(id); is = sk.getInputStream(); img=ImageIO.read(is); } finally { if (is != null) is.close(); if (sk != null) sk.close(); } return img; } }
Python
UTF-8
1,417
2.890625
3
[]
no_license
from threading import Thread, Lock import cv2 class VideoGrabber(Thread): """ A threaded video grabber Attributes: encode_params (): cap (str): attr2 (:obj:`int`, optional): Description of `attr2`. """ def __init__(self, jpeg_quality, device_id): """Constructor. Args: jpeg_quality (:obj:`int`): Quality of JPEG encoding, in 0, 100. """ Thread.__init__(self) self.encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), jpeg_quality] self.cap = cv2.VideoCapture(device_id) self.running = True self.buffer = None self.lock = Lock() def stop(self): self.running = False def get_buffer(self): """Method to access the encoded buffer. Returns: np.ndarray: the compressed image if one has been acquired. None otherwise. """ if self.buffer is not None: self.lock.acquire() cpy = self.buffer.copy() self.lock.release() return cpy # ndarray def run(self): # 一直读取 while self.running: success, img = self.cap.read() if not success: continue self.lock.acquire() result, self.buffer = cv2.imencode('.jpg', img, self.encode_param) self.lock.release()
Python
UTF-8
4,060
2.640625
3
[]
no_license
import tensorflow as tf from tensorflow.keras.layers import Conv2D, BatchNormalization, LeakyReLU, ZeroPadding2D, Concatenate from tensorflow.keras.regularizers import l2 from tensorflow.keras import Model class DarknetConv2DBNLeaky(tf.keras.layers.Layer): """Convolutional layer with batch normaltion and leaky relu""" def __init__(self, filters, k_size, strides=None, padding=None): super(DarknetConv2DBNLeaky, self).__init__() self.conv_1 = Conv2D(filters=filters, kernel_size=k_size, kernel_regularizer=l2(5e-4), padding=padding if padding is not None else 'same', strides=strides if strides is not None else (1, 1)) self.batch_normalization_1 = BatchNormalization() self.leaky_relu_1 = LeakyReLU(alpha=0.1) def call(self, *args): x = self.conv_1(args) x = self.batch_normalization_1(x) return self.leaky_relu_1(x) class DownSampling(tf.keras.layers.Layer): """Downsample using zeropadding((1, 0), (1, 0)) and a conv with strides 2""" def __init__(self, filters): super(DownSampling, self).__init__() self.conv_2 = DarknetConv2DBNLeaky(filters=filters, k_size=(3, 3), strides=(2, 2), padding='valid') self.zeropadding_1 = ZeroPadding2D(((1, 0), (1, 0))) def call(self, *args): x = self.zeropadding_1(*args) return self.conv_2(x) class CSPRblock(tf.keras.layers.Layer): """Create an identity block for CSPRDarknet""" def __init__(self, filters, num_block): super(CSPRblock, self).__init__() self.conv_3 = DarknetConv2DBNLeaky(filters=filters, k_size=(3, 3)) self.downsample_1 = DownSampling(filters) self.concat_1 = Concatenate(axis=0) self.splitter = lambda x: tf.split(x, num_or_size_splits=2, axis=0) self.num_block = num_block def call(self, *args): x = self.downsample_1(*args) x1, x2 = self.splitter(x) for block in range(self.num_block): x = self.conv_3(x1) x1 += x return self.concat_1([x1, x2]) class Darknet53(tf.keras.layers.Layer): """All of the CSPRDarknet_53 but the last layer""" def __init__(self): super(Darknet53, self).__init__() self.conv_4 = DarknetConv2DBNLeaky(32, (3, 3)) self.block = dict() self.block[0] = CSPRblock(64, 1) self.block[1] = CSPRblock(128, 2) self.block[2] = CSPRblock(256, 8) self.block[3] = CSPRblock(512, 8) self.block[4] = CSPRblock(1024, 4) # def call(self, *args): # y = [] # x = self.conv_4(*args) # for i in range(len(self.block)): # x = self.block[i](x) # y.append(x) # y = y[-3:] # return y[::-1] def call(self, *args): x = self.conv_4(*args) x = self.block[0](x) x = self.block[1](x) y1 = self.block[2](x) y2 = self.block[3](y1) y3 = self.block[4](y2) return [y3, y2, y1] class PredictionLayer(tf.keras.layers.Layer): """Layer that make the predictions""" def __init__(self, filters, num_classes): super(PredictionLayer, self).__init__() self.conv_5 = Conv2D(filters=num_classes * (num_classes + 5), kernel_size=(3, 3), kernel_regularizer=l2(5e-4), padding='same') self.conv_6 = DarknetConv2DBNLeaky(filters * 2, (3, 3)) self.conv_7 = DarknetConv2DBNLeaky(filters, (1, 1)) def call(self, *args): x = self.conv_7(*args) # (1, 1) x = self.conv_6(x) # (3, 3) x = self.conv_7(x) # (1, 1) x = self.conv_6(x) # (3, 3) x = self.conv_7(x) # (1, 1) y = self.conv_6(x) # (3, 3) y = self.conv_5(y) return x, y
C
UTF-8
3,920
2.828125
3
[]
no_license
#ifndef max #define max(a,b) (((a) > (b)) ? (a) : (b)) #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif #include<stdio.h> #include<math.h> #include<mex.h> double H(double x); double IH(double x); double IIH(double x); int wrap(int j, int n); /*************************************************************************/ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* ********************************************************************** * MATLAB Interface: * ********************************************************************** * vf = loc_levset_to_volfluid(x,y,lev,Z) * ********************************************************************** * This routine returns a volume-of-fluid style representation for an * interface from an input of a level-set style representation. * ********************************************************************** * INPUT: * x = x-coords of pixels at which level-set representation is given. * One dimensional array. * y = y-coords of pixels at which level-set representation is given. * One dimensional array. * lev = Level set values at the x & y coordinates. 1D array. * Z = Workspace variable; should be all -1's. Size should be the same * as the 2D computational grid. * ********************************************************************** */ int *x, *y; int i, j, k, ind, xk, yk, E, W, N, S, Npix, m, n, test; double *lev, *Z, *vf; double mx, my, val; x = (int *) mxGetData(prhs[0]); /* Array of x coords. */ y = (int *) mxGetData(prhs[1]); /* Array of y coords. */ lev = (double *) mxGetData(prhs[2]); /* Level set values. */ Z = (double *) mxGetData(prhs[3]); /* Workspace. */ Npix = mxGetM(prhs[0]); /* Number of pixels currently in the subset. */ n = (int) mxGetN(prhs[3]); /* Dimension of grid. Assumed square. */ /* Allocate memory and get pointer for output variables. */ plhs[0] = mxCreateDoubleMatrix(Npix,1,mxREAL); // JK modificaiton. mxGetpr is not recommend ded in general //vf = mxGetPr(plhs[0]); vf = mxGetDoubles(plhs[0]); /* Populate Z with level set values: */ for (k=0;k<Npix;k++) { /* Loop over pixels. */ xk = x[k] - 1; yk = y[k] - 1; ind = n*xk + yk; Z[ind] = lev[k]; /* printf("%f\n",lev[k]); */ } /* Real action: */ for (k=0;k<Npix;k++){ /* Loop over pixels. */ xk = x[k] - 1; yk = y[k] - 1; val = lev[k]; ind = n*xk + yk; // This is just to define periodicity !! E = n*wrap(xk+1,n) + yk; W = n*wrap(xk-1,n) + yk; N = n*xk + wrap(yk+1,n); S = n*xk + wrap(yk-1,n); // mx and my are gradient mx = 0.5*(Z[E]-Z[W]); my = 0.5*(Z[N]-Z[S]); test = 0; if (fabs(mx)<1e-6) test = 1; if (fabs(my)<1e-6) { test = 2; if (fabs(mx)<1e-6) test = 3; } if (test==0) { vf[k] = (IIH(mx+my+val) - IIH(-mx+my+val) - IIH(mx-my+val) + IIH(-mx-my+val)) / (mx*my); } if (test==1) { vf[k] = 2*( IH(my+val) - IH(val-my) ) / my; } if (test==2) { vf[k] = 2*( IH(mx+val) - IH(val-mx) ) / mx; } if (test==3) { vf[k] = 4*H(val); } vf[k] = vf[k] / 4.0; // This is defining single phase if ( max(max(max(max(Z[E],Z[W]),Z[N]),Z[S]),val) < 0 ) vf[k] = 0; if ( min(min(min(min(Z[E],Z[W]),Z[N]),Z[S]),val) > 0 ) vf[k] = 1.0; } /* for k */ /* Clean up Z: */ for (k=0;k<Npix;k++){ xk = x[k]-1; yk = y[k]-1; ind = n*xk + yk; Z[ind] = -1.0; } } double H(double x) { if (x <= 0) return 0.0; else return 1.0; } double IH(double x) { if (x<=0) return 0.0; else return x; } double IIH(double x) { if (x<=0) return 0.0; else return 0.5*x*x; } int wrap(int j, int n) { if (j<0) return (n-1); else { if (j>n-1) return 0; } return j; }
Markdown
UTF-8
4,303
3.359375
3
[]
no_license
# API This document details the proper format for requests and what the caller should expect in terms of response. ## Requests Requests should be sent to this API as an 'application/json' post with the following properties: - "lang": A string specifying the language code of the source code. A full list can be found in the properties of compilers.js. - "src": A string containing all of the source code. - "tests": The inputs and outputs to test against the program. - "timeout": The number of seconds each test has to run (program runtime). ### Test Object Each test object in the `tests` array must have an `input` property and an `output` property. Optionally, a `hint` property may be included. Examples: ```json { "input": "0", "output": "2" } ``` ```json { "input" : "", "output" : "Hello, NU Code!", "hint" : "Double check for any spelling errors and note the casing. The string should read \"Hello, NU Code!\" exactly." } ``` ### Full Request Example JSON example: ```json { "lang": "java", "src": "import java.util.Scanner;\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int x = scanner.nextInt();\n int y = x * 2;\n System.out.println(y);\n }\n}\n", "tests": [ { "hint" : "0 * 2 = 0", "input" : "0", "output" : "0" }, { "input" : "2", "output" : "4" }, { "input" : "1024", "output" : "2048" }, { "input" : "-4", "output" : "-8" } ], "timeout": 3 } ``` JSON above sent via cURL: `curl -d '{ "lang": "java", "src": "import java.util.Scanner;\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int x = scanner.nextInt();\n int y = x * 2;\n System.out.println(y);\n }\n}\n", "tests": [ { "hint": "0 * 2 = 0", "input": "0", "output": "0" }, { "input": "2", "output": "4" }, { "input": "1024", "output": "2048" }, { "input": "-4", "output": "-8" } ], "timeout": 3 }' -H "Content-Type: application/json" http://code.neumont.edu/api` ## Responses Responses are sent as JSON. If the request was _incorrectly_ formatted, the JSON response will contain a single "error" property. ```json { "error": "Requests must be sent as JSON containing the following properties: \"lang\", \"src\", \"timeout\", and \"tests\"." } ``` If the request was _correctly_ formatted, then the JSON response will contain the results. ### "Pass" Response If all tests pass, the response will contain a `status` property equaling `"Pass"` and an `execTime` property with the total runtime in milliseconds. Example: ```json { "status": "Pass", "execTime": 0.192401 } ``` ### "Fail" Response If one or more tests fail, the response will contain a `status` property equaling `"Fail"`. If any of the failing tests contained a `hint` property, then that hint will be included in the `hints` property, an array of strings. Example: ```json { "status": "Fail" } ``` Example with hints: ```json { "status": "Fail", "hints": [ "Account for dividing by 0." ] } ``` ### "Timeout" Response If the program's runtime for a test exceeds the request's specified `timeout`, the response will contain a `status` property equaling `"Timeout"`. Example: ```json { "status": "Timeout" } ``` ### "Compilation Error" Response If the request's `lang` property corresponds to a compiled language, and the source code does not compile, then the response will contain a `status` property equaling `"CompilationError"` and a `message` property with the string message of the compiler's error output. - Example: ```json { "status": "CompilationError", "message": "solution.c: In function 'main':\nsolution.c:2:31: error: expected ';' before '}' token\n int main() { printf(\"233168\") }\n ^\n" } ``` ### "Runtime Error" Response If the program runs into a runtime error during any of the tests, then the response will contain a `status` property equaling `"RuntimeError"` and a `message` property with the stderr output of the program. - Example: ```json { "status": "RuntimeError", "message": "Exception in thread \"main\" java.lang.RuntimeException\n at Solution.main(Solution.java:3)" } ```
Java
UTF-8
3,691
1.804688
2
[]
no_license
package npg.webadmin.acceptance.test; import org.apache.log4j.Logger; public class Constants { public static final Logger LOGGER = Logger.getLogger("com.webadmin"); // types of elements public final static String BLANK = ""; public final static String EMPTY = "empty"; public final static String YES = "yes"; public final static String NO = "no"; public final static String TEXT = "text"; public final static String HEADER_2 = "header 2"; public final static String IMAGE = "image"; public final static String INPUT_FIELD = "input field"; public final static String INPUT_FIELD_NAME = "input field name"; public final static String INPUT_FIELD_VALUE = "input field value"; public final static String INPUT_CHECKBOX = "input checkbox"; public final static String INPUT_SUBMIT = "submit"; public final static String INPUT_SUBMIT_TEXT = "submit text"; public final static String INPUT_RESET = "reset"; public final static String INPUT_IMAGE = "input image"; public final static String FORM_ACTION = "form action"; public final static String SELECT_NAME = "select name"; public final static String SELECT_OPTION_TEXT = "select option text"; public final static String SELECTED_OPTION_TEXT = "select option text selected"; public final static String KEY_VALUE_SEPARATOR = "::"; public final static String OPTION_SELECT_SEPARATOR = "//"; public final static String LINK_TEXT = "link text"; public final static String LINK_URL = "link url"; public final static String BLANK_VALUE = ":BLANK:"; public final static String WITH_ATTRIBUTE_ID = ":WITH ID:"; public final static String WITH_ATTRIBUTE_TITLE = ":WITH TITLE:"; public final static String WITH_ATTRIBUTE_CLASS = ":WITH CLASS:"; public final static String WITH_ATTRIBUTE_TYPE = ":WITH TYPE:"; public final static String WITH_ATTRIBUTE_NAME = ":WITH NAME:"; public final static String WITH_ATTRIBUTE_VALUE = ":WITH VALUE:"; public final static String WITH_ATTRIBUTE_LINK = ":WITH LINK:"; public final static String WITH_ATTRIBUTE_ALT = ":WITH ALT:"; public final static String WITH_ATTRIBUTE_SOURCE = ":WITH SOURCE:"; public final static String WITH_ATTRIBUTE_LINK_PARENT = ":WITH LINK PARENT:"; public final static String WITH_ATTRIBUTE_VALUE_CHECKED = ":CHECKED WITH VALUE:"; public final static String WITH_ATTRIBUTE_NAME_AND_VALUE = ":NAME WITH VALUE:"; public final static String ATTRIBUTE_BLANK = ""; public final static String ATTRIBUTE_ID = "id"; public final static String ATTRIBUTE_TITLE = "title"; public final static String ATTRIBUTE_CLASS = "class"; public final static String ATTRIBUTE_TYPE = "type"; public final static String ATTRIBUTE_NAME = "name"; public final static String ATTRIBUTE_VALUE = "value"; public final static String ATTRIBUTE_HREF = "href"; public final static String ATTRIBUTE_ALT = "alt"; public final static String ATTRIBUTE_SRC = "src"; public final static String DEFINITION_TERM = "definition term"; public final static String DEFINITION_DESCRIPTION = "definition description"; public final static String PRECEDING_SIBLING_TEXT = ":PRECEDING SIBLING TEXT:"; public final static String FOLLOWING_SIBLING_TEXT = ":FOLLOWING SIBLING TEXT:"; public final static String WITH_SELECT_PARENT_NAME = ":WITH PARENT NAME:"; public final static String WITH_SELECT_PARENT_NAME_SELECTED = ":SELECTED WITH PARENT NAME:"; public final static String XPATH_PRECEDING_SIBLING = "preceding-sibling"; public final static String XPATH_FOLLOWING_SIBLING = "following-sibling"; }
TypeScript
UTF-8
212
2.671875
3
[]
no_license
export interface INode { node: string; weight: number; } export interface IAdjacentNodeList { [index: string]: INode[]; } export interface IWaypoint { node1: string; node2: string; weight: number; }
C
UTF-8
440
3.515625
4
[ "MIT" ]
permissive
#include<stdio.h> int totalAmount(void); int main(void) { int result; result = totalAmount(); printf("Total Amount is %d\n", result ); //printf("Total Amount is %d\n", totalAmount() ); return 0; } int totalAmount(void) { int x, y, total; printf("Total courses: "); scanf("%d", &x); printf("Fees for each course: "); scanf("%d", &y); total = x * y; return total; //return x * y; }
Markdown
UTF-8
2,932
3.375
3
[ "MIT" ]
permissive
--- layout: post # 使用的布局(不需要改) title: 数组中只出现一次的数字 subtitle: I'm too cabbage!!! date: 2020-03-21 # 时间 author: longzzzz # 作者 header-img: img/bg_12.jpg #这篇文章标题背景图片 catalog: true # 是否归档 tags: #标签 - 剑指offer --- >We work in the darkness to serve the light. 题目描述:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。 解题思路: * map * [题解思路:](https://www.nowcoder.com/questionTerminal/e02fdb54d7524710a7d664d082bb7811?answerType=1&f=discussion)位运算中异或的性质:**两个相同数字异或=0**,**一个数和0异或还是它本身** 我们来看两个数(我们假设是AB)出现一次的数组。我们首先还是先异或,剩下的数字肯定是A、B异或的结果,这个结果的二进制中的1,表现的是A和B的不同的位。我们就取第一个1所在的位数,假设是第3位,接着把原数组分成两组,分组标准是第3位是否为1。如此,相同的数肯定在一个组,因为相同数字所有位都相同,而不同的数,肯定不在一组。然后把这两个组按照最开始的思路,依次异或,剩余的两个结果就是这两个只出现一次的数字。 代码如下: ```java //num1,num2分别为长度为1的数组。传出参数 //将num1[0],num2[0]设置为返回结果 import java.util.HashMap; public class Solution { public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i : array){ if(map.containsKey(i)) map.put(i,2); else map.put(i,1); } int flag = 0; for(int i : array){ if(map.get(i) == 1){ if(flag == 0){ num1[0] = i; flag = 1; } else num2[0] = i; } } } } ``` ```java public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { int xor1 = 0; for(int i=0; i < array.length; i++) xor1 = xor1^array[i]; //在xor1中找到第一个不同的位对数据进行分类,分类为两个队列对数据进行异或求和找到我们想要的结果 int index = 1; while((index & xor1)==0) index = index <<1;//因为可能有多个位为1所以需要求一下位置 int result1 = 0; int result2 = 0; for(int i=0; i < array.length; i++){ if((index & array[i]) == 0) result1 = result1^array[i]; else result2 = result2^array[i]; } num1[0] = result1; num2[0] = result2; } ```
Markdown
UTF-8
3,551
2.875
3
[]
no_license
--- title: Spend Time With Family and Loved Ones date: 2016-06-09 21:15:40 tags: - 清晨朗读会 --- > BY LEO BABAUTA[^1] When was the last time you told your family and close personal friends that you loved them? Whatever your answer, do it today. Recently my grandfather was admitted to the hospital, just days after his 80th birthday, for heart problems. He’s had heart surgery in the past, and this time, just as in the past, he toughed it out. But any day could be his day, the day when it will be too late to tell him how much he’s meant to me over the years. <!-- more --> Don’t let that day come for your loved ones without telling them what they mean to you. I know that for many of us, expressing those kinds of feelings isn’t easy. That’s true for me, but I’ve been trying to overcome those barriers. But even if that’s too difficult for you, I recommend that you just hang out with your family or treasured friends. Talk to them. Listen to them. Understand them. Just spending a little time with someone shows that you care, shows that they are important enough that you’ve chosen — out of all the things to do on your busy schedule — to find the time for them. And if you go beyond that, and truly connect with them, through good conversation, that says even more. Many times its our actions, not just our words, that really speak what our hearts feel. Taking the time to connect with those you love will bring you true happiness. The more you do it, the happier you’ll be. Since I’m a notorious list-maker, and because many people are busy and might need help with this, here are some tips: Have five minutes? Send an email. It doesn’t take long to send an email to someone you care about, asking them how they are, wishing them a good day. And that little gesture could go a long way, especially if you follow it up over time with regular emails. Have 10 minutes? Call them up. A phone call is an easy way to connect with someone. It’s conversation, without the need for travel. What an invention! :) Have 30 minutes? You might not get the chance to do this every day, but at least once a week, take 30 minutes to drop in on someone you love (call first, so you don’t catch them in their underwear) and just visit. It’ll be some of the best 30 minutes you’ll spend this week. Have a couple hours? Have a good lunch or go somewhere with a loved one. Who among us doesn’t have a couple of free hours each month? Weekends, or evenings, there’s got to be a time that you spend in front of the TV or mindlessly surfing the internet. Take a chunk of that time, and devote it to a friend or family. (If you truly don’t have that time, see Edit Your Life, Part 1: Commitments.) Really focus on them. Don’t just spend time with someone but think about your work, or your blog, or the errands you have to run. Pay attention to that person. Listen. Really be there, in that moment, with that person. Because that’s a moment you’ll never get back, so spend it wisely. Have a blast. Tell jokes, crack each other up, do something fun and spontaneous. Really have a great time! [^1]:[清晨朗读会](https://mp.weixin.qq.com/s?__biz=MzI1NzIyNjU4Ng==&mid=2247483721&idx=1&sn=18f187bf1c47cca89bd42f3ecb669057&scene=1&srcid=0701ZFJgzzHttv3I5QIr4gyD&key=77421cf58af4a6531b3d4a0375ee6173f0575831da2d492d0b3fb3af8fae075c2d4395a1cb045edbcf63e13f9dbec327&ascene=0&uin=MTMzOTQ1ODU2MA%3D%3D&devicetype=iMac+MacBookPro11%2C2+OSX+OSX+10.11.5+build(15F34)&version=11020201&pass_ticket=JpMDsA87Kq8iq4HY%2FOuzK4P%2BqTAOjY2KZC29g2o579abtCXCDxqwF%2BCMOeJBwMsn)
C#
UTF-8
1,490
2.890625
3
[ "MIT" ]
permissive
namespace Samples.TestDataBuilder { public class TestUserBuilder { public const string DEFAULT_NAME = "John Smith"; public const string DEFAULT_ROLE = "ROLE_USER"; public const string DEFAULT_PASSWORD = "42"; private string name = DEFAULT_NAME; private string? password = DEFAULT_PASSWORD; private string role = DEFAULT_ROLE; private string? login; private TestUserBuilder() { } public static TestUserBuilder AUser() { return new TestUserBuilder(); } public TestUserBuilder WithName(string newName) { name = newName; return this; } public TestUserBuilder WithLogin(string? newLogin) { login = newLogin; return this; } public TestUserBuilder WithPassword(string? newPassword) { password = newPassword; return this; } public TestUserBuilder WithNoPassword() { password = null; return this; } public TestUserBuilder InUserRole() => InRole("ROLE_USER"); public TestUserBuilder InAdminRole() => InRole("ROLE_ADMIN"); public TestUserBuilder InRole(string newRole) { this.role = newRole; return this; } public TestUserBuilder But() => AUser() .InRole(role) .WithName(name) .WithPassword(password) .WithLogin(login); public User Build() => new User(name, login, password, role); public static User ARegularUser() => AUser().Build(); public static User AnAdmin() => AUser() .WithName("Neo") .WithLogin("neo") .InAdminRole() .Build(); } }
C
UTF-8
1,952
3.15625
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<string.h> void sortare_descrescatoare(float v[], int n) {//functie petru sortarea descrescatoare a vectorilor int i, j; for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { if(v[i] < v[j]) { float aux; aux=v[i]; v[i]=v[j]; v[j]=aux; } } } } int sum(int v[], int i) { //functie pentru calcularea sumei unui vector int sum, j; sum=0; for(j=0;j<i;j++) { sum=sum+v[j]; } return sum; } int main() {int **a, i, j=0, k, col[100], n, x, suma[100]; float med[100], copie[100]; scanf("%d", &n); // n=numarul materiilor a=malloc(n*sizeof(int*)); //matricea este complet alocata dinamic for(i=0;i<n;i++) { a[i]=(int*)malloc(3*sizeof(int)); //linia ese alocata initial cu o dimensiune maxima initiala 3 do { /////citesc matricea scanf("%d", &a[i][j]); x=a[i][j]; //retin fiecare element al matricei intr-o variabila pentru a o compara cu zero j++; //cresc cu o unitate numarul notelor if(j%3==2) a[i] = realloc(a[i], (j+4)*sizeof(int)); //dimensiunea este marita de fiecare data cu 3 atunci cand este depasita dimensiunea deja alocata col[i]=j; //retin intr-un vector numarul notelor(coloanelor) fiecarei materii(linii) } while(x != 0); j=0; } for(i=0;i<n;i++) { /// calculez suma notelor de pe fiecare linie suma[i]=sum(a[i], col[i]); } for(i=0;i<n;i++){ //calculez feicare medie de pe fiecare linie med[i]=(float)suma[i]/(col[i]-1); copie[i]=med[i]; //retin intr o matrice alaturata } sortare_descrescatoare(med, n); //sortez vectorul mediilor descrescator for(i=0;i<n;i++) { ///afsisez matricea ordonata descrescator in functie de media fiecarei materii printf("%-10.3f", med[i]); for(k=0;k<n;k++) { if(med[i]==copie[k]) { copie[k]=-100; for(j=1;j<col[k];j++) { printf("%d ", a[k][j-1]); } break; } } printf("\n"); } //eliberez memoria matricei for(i=0;i<n;i++) { free(a[i]); } free(a); return 0; }
JavaScript
UTF-8
409
3.671875
4
[ "MIT" ]
permissive
function calc(a, b, operator) { let result; switch (operator) { case '+': result = a + b; break; case '-': result = a - b; break; case '*': result = a * b; break; case '/': result = a / b; break; case '%': result = a % b; break; case '**': result = a ** b; break; } console.log(result); } calc(3, 5, '+'); calc(6, 9, '-'); calc(420, 69, '**');
C
UTF-8
722
2.71875
3
[]
no_license
unsigned grow_int (unsigned n, unsigned * keys) { htab_t ht = htab_create (0, hash_int_fn, eq_int_fn, NULL); unsigned i; unsigned count; for (i = 0; i < n; i ++) { void ** elem = htab_find_slot (ht, & keys [i], INSERT); if (elem) * elem = (void *) & keys [i]; } count = htab_elements (ht); htab_delete (ht); return count; } unsigned grow_str (unsigned n, char ** keys) { htab_t ht = htab_create (0, hash_str_fn, eq_str_fn, NULL); unsigned i; unsigned count; for (i = 0; i < n; i ++) { void ** elem = htab_find_slot (ht, keys [i], INSERT); if (elem) * elem = (void *) keys [i]; } count = htab_elements (ht); htab_delete (ht); return count; }
Java
UTF-8
12,433
2.34375
2
[ "Apache-2.0" ]
permissive
package com.sibosend.qrcode; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.imageio.ImageIO; import com.swetake.util.Qrcode; public class QRCodeCreate { // 生成点的大小 private static int WIDTH = 15; private static BufferedImage bufferedImage; private static Graphics2D gs; // private static int DEFAULT_WIDTH; /* * 生成二维码 */ public void qrCodeEncode(String content, String qrCodePath, String logoPath, int conType, int qrType, int red, int grenn, int blue, int redout, int greenout, int blueout, int redin, int greenin, int bluein) throws IOException { Qrcode qrcode = new Qrcode(); /* * 错误修正容量 L水平 7% 的字码可被修正 M水平 15% 的字码可被修正 Q水平 25% 的字码可被修正 H水平 30% 的字码可被修正 */ qrcode.setQrcodeErrorCorrect('M'); // L','M','Q','H' // 编码格式 qrcode.setQrcodeEncodeMode('B'); // "N","A" byte[] len = content.getBytes(); if (len.length < 29) { qrcode.setQrcodeVersion(3);// 设置版本,版本越高,容纳信息量越大,范围: 0-20 // 生成二维码绘制背景图 bufferedImage = new BufferedImage(455, 455, BufferedImage.TYPE_INT_RGB); gs = bufferedImage.createGraphics(); gs.setBackground(Color.WHITE); gs.clearRect(0, 0, 455, 455); } else if (len.length > 28) { qrcode.setQrcodeVersion(5); bufferedImage = new BufferedImage(463, 463, BufferedImage.TYPE_INT_RGB); gs = bufferedImage.createGraphics(); gs.setBackground(Color.WHITE); gs.clearRect(0, 0, 463, 463); } byte[] buffer = null; try { buffer = content.getBytes("utf-8"); boolean[][] bRect = qrcode.calQrcode(buffer); // 计算二维码,结果用布尔数组表示,用于绘制 // 设置抗锯齿 gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gs.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); QRType(qrType, redout, greenout, blueout, redin, greenin, bluein); Image eyeImage = ImageIO.read(new File("./res/image.png")); BufferedImage buffImage2 = ImageIO.read(new FileInputStream("./res/image.png")); ShapeCanvas.rotateImage(buffImage2, 90); Image eyeImage2 = ImageIO.read(new File("./res/image2.png")); BufferedImage buffImage3 = ImageIO.read(new FileInputStream("./res/image.png")); ShapeCanvas.rotateImage(buffImage3, 270); Image eyeImage3 = ImageIO.read(new File("./res/image3.png")); gs.setColor(new Color(red, grenn, blue)); // 绘制二维码 if (buffer.length > 0 && len.length < 29) { for (int i = 0; i < bRect.length; i++) { for (int j = 0; j < bRect.length; j++) { if (bRect[j][i]) { if (j < WIDTH / 2 && i < WIDTH / 2) { gs.drawImage(eyeImage, 4, 4, 125, 125, null); } else if (j > 20 && i < WIDTH / 2) { gs.drawImage(eyeImage2, 328, 4, 125, 125, null); } else if (j < WIDTH / 2 && i > 20) { gs.drawImage(eyeImage3, 4, 328, 125, 125, null); } else { if (conType > 0) { gs.fillRoundRect(j * WIDTH + 10, i * WIDTH + 10, WIDTH, WIDTH, 2 * conType, 2 * conType); } else { if (i == 0 && isLeft(bRect, j, i)) { gs.fillRoundRect((j - 1) * WIDTH + 10, i * WIDTH + 10, WIDTH, WIDTH, 13, 13); gs.fillRect((j - 1) * WIDTH + 15, i * WIDTH + 10, WIDTH, WIDTH); gs.fillRoundRect(j * WIDTH + 10, i * WIDTH + 10, WIDTH, WIDTH, 13, 13); } if ((i == 0 && isAroundI(bRect, j, i)) || (j > 7 && j < 28 && i == 28 && isAround(bRect, j, i))) { gs.fillOval(j * WIDTH + 10, i * WIDTH + 10, WIDTH + 2, WIDTH + 2); } if (i > 7 && i < 21 && isUpJ(bRect, j, i)) { gs.fillRoundRect(j * WIDTH + 10, (i - 1) * WIDTH + 10, WIDTH, WIDTH, 13, 13); gs.fillRect(j * WIDTH + 10, (i - 1) * WIDTH + 15, WIDTH, WIDTH); gs.fillRoundRect(j * WIDTH + 10, i * WIDTH + 10, WIDTH, WIDTH, 13, 13); } if (i > 7 && i < 21 && j == 0 && isAroundJ(bRect, j, i)) { gs.fillOval(j * WIDTH + 10, i * WIDTH + 10, WIDTH + 2, WIDTH + 2); } if (j == 28 && isRight(bRect, j, i)) { gs.fillOval(j * WIDTH + 10, i * WIDTH + 10, WIDTH + 2, WIDTH + 2); } if ((j > 0 && j < 28 && i > 0 && i < 28) && isAroundNo(bRect, j, i)) { gs.fillOval(j * WIDTH + 10, i * WIDTH + 10, WIDTH + 2, WIDTH + 2); } if ((j > 0 && j <= 28 && i > 0 && i <= 28) && isAroundLeft(bRect, j, i)) { gs.fillRoundRect((j - 1) * WIDTH + 10, i * WIDTH + 10, WIDTH, WIDTH, 13, 13); gs.fillRect((j - 1) * WIDTH + 15, i * WIDTH + 10, WIDTH, WIDTH); gs.fillRoundRect(j * WIDTH + 10, i * WIDTH + 10, WIDTH, WIDTH, 13, 13); } if ((j > 0 && j <= 28 && i > 0 && i <= 28) && isAroundUp(bRect, j, i)) { gs.fillRoundRect(j * WIDTH + 10, (i - 1) * WIDTH + 10, WIDTH, WIDTH, 13, 13); gs.fillRect(j * WIDTH + 10, (i - 1) * WIDTH + 15, WIDTH, WIDTH); gs.fillRoundRect(j * WIDTH + 10, i * WIDTH + 10, WIDTH, WIDTH, 13, 13); } if (i > 0 && j < 28 && isRightUp(bRect, j, i)) { gs.setStroke(new BasicStroke(7)); gs.drawLine(j * WIDTH + 20, i * WIDTH + 16, (j + 1) * WIDTH + 20, (i - 1) * WIDTH + 15); } if (i > 0 && j > 0 && isLeftUp(bRect, j, i)) { gs.setStroke(new BasicStroke(7)); gs.drawLine(j * WIDTH + 10, i * WIDTH + 10, j * WIDTH, i * WIDTH); } if (i < 27 && j > 0 && j < 27 && aroundCircle(bRect, j, i)) { gs.setStroke(new BasicStroke(7)); gs.drawOval(j * WIDTH + 7, (i + 1) * WIDTH + 7, 20, 20); } } } } } } } else if (buffer.length > 0 && len.length > 28) { for (int i = 0; i < bRect.length; i++) { for (int j = 0; j < bRect.length; j++) { if (bRect[j][i]) { if (j < WIDTH / 2 && i < WIDTH / 2) { gs.drawImage(eyeImage, 3, 3, 100, 100, null); } else if (j > 35 && i < WIDTH / 2) { gs.drawImage(eyeImage2, 362, 3, 100, 100, null); } else if (j < WIDTH / 2 && i > 35) { gs.drawImage(eyeImage3, 3, 362, 100, 100, null); } else { if (conType > 0) { gs.fillRoundRect(j * 12 + 10, i * 12 + 10, 13, 13, 2 * conType, 2 * conType); }else { if (i == 0 && isLeft(bRect, j, i)) { gs.fillRoundRect((j - 1) * 12 + 10, i * 12 + 10, 13, 13, 11, 11); gs.fillRect((j - 1) * 12 + 15, i * 12 + 10, 13, 13); gs.fillRoundRect(j * 12 + 10, i * 12 + 10, 13, 13, 11, 11); } if ((i == 0 && isAroundI(bRect, j, i)) || (j > 7 && j < 36 && i == 36 && isAround(bRect, j, i))) { gs.fillOval(j * 12 + 10, i * 12 + 10, 13 + 2, 13 + 2); } if (i > 7 && i < 36 && isUpJ(bRect, j, i)) { gs.fillRoundRect(j * 12 + 10, (i - 1) * 12 + 10, 13, 13, 11, 11); gs.fillRect(j * 12 + 10, (i - 1) * 12 + 15, 13, 13); gs.fillRoundRect(j * 12 + 10, i * 12 + 10, 13, 13, 11, 11); } if (i > 7 && i < 36 && j == 0 && isAroundJ(bRect, j, i)) { gs.fillOval(j * 12 + 10, i * 12 + 10, 13 + 2, 13 + 2); } if (i > 7 && i < 36 && j == 36 && isRight(bRect, j, i)) { gs.fillOval(j * 12 + 10, i * 12 + 10, 13 + 2, 13 + 2); } if (j > 0 && j < 36 && i > 0 && i < 36 && isAroundNo(bRect, j, i)) { gs.fillOval(j * 12 + 10, i * 12 + 10, 13 + 2, 13 + 2); } if ((j > 0 && j <= 36 && i > 0 && i <= 36) && isAroundLeft(bRect, j, i)) { gs.fillRoundRect((j - 1) * 12 + 10, i * 12 + 10, 13, 13, 11, 11); gs.fillRect((j - 1) * 12 + 15, i * 12 + 10, 13, 13); gs.fillRoundRect(j * 12 + 10, i * 12 + 10, 13, 13, 11, 11); } if ((j > 0 && j <= 36 && i > 0 && i <= 36) && isAroundUp(bRect, j, i)) { gs.fillRoundRect(j * 12 + 10, (i - 1) * 12 + 10, 13, 13, 11, 11); gs.fillRect(j * 12 + 10, (i - 1) * 12 + 15, 13, 13); gs.fillRoundRect(j * 12 + 10, i * 12 + 10, 13, 13, 11, 11); } if (i > 0 && j < 36 && isRightUp(bRect, j, i)) { gs.setStroke(new BasicStroke(6)); gs.drawLine(j * 12 + 20, i * 12 + 13, (j + 1) * 12 + 19, (i - 1) * 12 + 14); } if (i > 0 && j > 0 && isLeftUp(bRect, j, i)) { gs.setStroke(new BasicStroke(6)); gs.drawLine(j * 12 + 10, i * 12 + 10, (j-1) * 12 + 15, (i-1) * 12 + 15); } if (i < 35 && j > 0 && j < 35 && aroundCircle(bRect, j, i)) { gs.setStroke(new BasicStroke(5)); gs.drawOval(j * 12 + 10, (i + 1) * 12 + 9, 13, 13); } } } } } } } if (!logoPath.equals("N") && !logoPath.equals("n")) { Image image = ImageIO.read(new File(logoPath)); // 实例化一个Image对象。 gs.drawImage(image, 153, 153, 153, 153, null); } gs.dispose(); bufferedImage.flush(); // 生成二维码QRCode图片 File imgFile = new File(qrCodePath); ImageIO.write(bufferedImage, "png", imgFile); } catch (Exception e) { e.printStackTrace(); } System.out.println("保存成功!"); } private static boolean isLeft(boolean[][] bRect, int j, int i) { if (bRect[j - 1][i]) { return true; } return false; } private static boolean isUpJ(boolean[][] bRect, int j, int i) { if (bRect[j][i - 1]) { return true; } return false; } private static boolean isRight(boolean[][] bRect, int j, int i) { if (!bRect[j - 1][i] && !bRect[j][i + 1] && !bRect[j][i - 1]) { return true; } return false; } private static boolean isRightUp(boolean[][] bRect, int j, int i) { if (bRect[j][i] && bRect[j + 1][i - 1]) { return true; } return false; } private static boolean isLeftUp(boolean[][] bRect, int j, int i) { if (bRect[j][i] && bRect[j - 1][i - 1]) { return true; } return false; } private static boolean isAroundJ(boolean[][] bRect, int j, int i) { if (!bRect[j][i - 1] && !bRect[j][i + 1] && !bRect[j + 1][i]) { return true; } return false; } private static boolean isAroundI(boolean[][] bRect, int j, int i) { if (!bRect[j - 1][i] && !bRect[j + 1][i] && !bRect[j][i + 1]) { return true; } return false; } private static boolean isAround(boolean[][] bRect, int j, int i) { if (!bRect[j - 1][i] && !bRect[j + 1][i] && !bRect[j][i - 1]) { return true; } return false; } private static boolean aroundCircle(boolean[][] bRect, int j, int i) { if (bRect[j][i] && !bRect[j][i + 1] && bRect[j - 1][i + 1] && bRect[j + 1][i + 1] && bRect[j][i + 2]) { return true; } return false; } private static boolean isAroundNo(boolean[][] bRect, int j, int i) { if (!bRect[j - 1][i] && !bRect[j + 1][i] && !bRect[j][i - 1] && !bRect[j][i + 1]) { return true; } return false; } private static boolean isAroundLeft(boolean[][] bRect, int j, int i) { if (bRect[j - 1][i]) { return true; } return false; } private static boolean isAroundUp(boolean[][] bRect, int j, int i) { if (bRect[j][i - 1]) { return true; } return false; } private static void QRType(int qrType, int redout, int greenout, int blueout, int redin, int greenin, int bluein) { switch (qrType) { case 1: ShapeCanvas.canvas1(redout, greenout, blueout, redin, greenin, bluein); break; case 2: ShapeCanvas.canvas2(redout, greenout, blueout, redin, greenin, bluein); break; case 3: ShapeCanvas.canvas3(redout, greenout, blueout, redin, greenin, bluein); break; case 4: ShapeCanvas.canvas4(redout, greenout, blueout, redin, greenin, bluein); break; case 5: ShapeCanvas.canvas5(redout, greenout, blueout, redin, greenin, bluein); break; case 6: ShapeCanvas.canvas6(redout, greenout, blueout, redin, greenin, bluein); break; case 7: ShapeCanvas.canvas7(redout, greenout, blueout, redin, greenin, bluein); break; case 8: ShapeCanvas.canvas8(redout, greenout, blueout, redin, greenin, bluein); break; default: ShapeCanvas.canvas1(redout, greenout, blueout, redin, greenin, bluein); break; } } }
Markdown
UTF-8
647
2.953125
3
[]
no_license
# I Am Open Source (And So Can You!) ## Length 10 ## Audience Experience Level Novice ## Description Open Source Software (OSS) has changed the world in countless ways and has provided us with wonderful innovations such as the Python programming language. As Pythonistas, we use OSS every single day but only a fraction of us give back to the community. This talk will discuss the benefits of contributing to open source in the context of my experience as a newbie pandas contributor. I will also provide a Getting Started guide so you, too, can become an Open Source Contributor! ## Slides link (optional) http://bit.ly/i-am-open-source
Java
UTF-8
1,451
2.28125
2
[]
no_license
package com.pepperonas.enigma.app; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; /** * @author Martin Pfeffer (pepperonas) */ public class EncryptFragment extends Fragment { private static final String TAG = "EncryptFragment"; private MainActivity mMain; public static Fragment newInstance(int i) { EncryptFragment fragment = new EncryptFragment(); Bundle args = new Bundle(); args.putInt("the_id", i); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i(TAG, "onCreateView()"); View v = inflater.inflate(R.layout.fragment_encrypt, null, false); mMain = (MainActivity) getActivity(); mMain.setTitle(getString(R.string.encrypt)); return v; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Log.i(TAG, "onViewCreated()"); EditText encrypt_et_iv = (EditText) getActivity().findViewById(R.id.encrypt_et_iv); encrypt_et_iv.setText(String.valueOf(System.currentTimeMillis())); } }
Java
UTF-8
1,605
2.859375
3
[]
no_license
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * Created by andrew on 4/15/17. */ class GameModelTest { @Test void testCorrectState1Undo() throws GameModel.EmptyHistoryException, GameModel.MaxUndosReachedException, GameModel.GameFinishedException { GameModel model = new GameModel(); model.playerMove(4); model.undo(); BoardModel expectedStart = new BoardModel(6, 4); BoardData expectedBoardData = new BoardData(expectedStart); assertTrue(expectedBoardData.equals(model.getCurrentBoardData())); } @Test void testMaxUndosReachedException() throws Exception { GameModel model = new GameModel(); int maxUndos = model.MAX_UNDOS_PER_TURN; boolean caughtSuccessfully = false; model.playerMove(0); try { model.undo(); } catch (GameModel.EmptyHistoryException e) { e.printStackTrace(); } catch (GameModel.MaxUndosReachedException e) { throw e; } model.playerMove(0); try { model.undo(); } catch (GameModel.EmptyHistoryException e) { e.printStackTrace(); } catch (GameModel.MaxUndosReachedException e) { throw e; } model.playerMove(0); try { model.undo(); } catch (GameModel.EmptyHistoryException e) { e.printStackTrace(); } catch (GameModel.MaxUndosReachedException e) { throw e; } model.playerMove(0); try { model.undo(); } catch (GameModel.EmptyHistoryException e) { e.printStackTrace(); } catch (GameModel.MaxUndosReachedException e) { caughtSuccessfully = true; } if (!caughtSuccessfully) throw new Exception("MaxUndosReachedException failed to throw"); } }
C++
ISO-8859-1
1,148
3.71875
4
[]
no_license
#include <algorithm> #include <iostream> #include <string> #include <ctype.h> #include <stdexcept> #include "Test.h" // Exemplo de classe a ser testada class Password { private: std::string value; public: void set(std::string pass) { auto check_alpha = [](char& c) -> void { if (!std::isalpha(c)) { throw std::invalid_argument("c isn't alpha"); } }; std::for_each(pass.begin(), pass.end(), check_alpha); value = pass; } std::string get() const { return value; } bool compare(std::string pass) const { return pass == value; } }; // Classe de test que herda TEST class Password_Test : public TEST { public: Password_Test() { set_name(typeid(this).name()); } void execution() override { Password p; assert_throw( [&]() { p.set("123"); }); assert_no_throw([&]() { p.set("abc"); }); } }; int main() { // Execuo do teste. Password_Test password_test; password_test.run(); }
Markdown
UTF-8
108
2.734375
3
[]
no_license
### 全模组电源上可能有两个主板输出口,要全部插上才能满足20+4pin的主板供电
C++
UTF-8
3,912
2.5625
3
[]
no_license
#ifndef paging_INC #define paging_INC #include <kernel/isr.hpp> #include <kernel/idt.hpp> //#include <kernel/kheap.hpp> #include <kernel/monitor.hpp> #include <kernel/kmalloc.hpp> #include <kernel/kpp/bitset.hpp> #include <isa_specific_code.hpp> #include <plataform_specific_code.hpp> #include <stdlib.h> typedef struct page{ uint32_t present : 1; // Page present in memory uint32_t rw : 1; // Read-only if clear, readwrite if set uint32_t user : 1; // Supervisor level only if clear uint32_t accessed : 1; // Has the page been accessed since last refresh? uint32_t dirty : 1; // Has the page been written to since last refresh? uint32_t unused : 7; // Amalgamation of unused and reserved bits uint32_t frame : 20; // Frame address (shifted right 12 bits) } page_t; typedef struct page_table{ page_t pages[1024]; } page_table_t; typedef struct page_directory{ /** Array of pointers to pagetables. **/ page_table_t *tables[1024]; /** Array of pointers to the pagetables above, but gives their *physical* location, for loading into the CR3 register. **/ uint32_t tablesPhysical[1024]; /** The physical address of tablesPhysical. This comes into play when we get our kernel heap allocated and the directory may be in a different location in virtual memory. **/ uint32_t physicalAddr; } page_directory_t; class Paging{ public: Paging( const size_t &mem_size, IDT &idt, const uint32_t &KHEAP_START, const uint32_t &KHEAP_INITIAL_SIZE ) : frame_size(0x1000), frame_qtd(mem_size/frame_size), frames(frame_qtd), idt(idt) { kernel_directory = (page_directory_t*)kmalloc_a(sizeof(page_directory_t)); memset(kernel_directory, 0, sizeof(page_directory_t)); // current_directory = kernel_directory; kernel_directory->physicalAddr = (uint32_t)(kernel_directory->tablesPhysical); // Map some pages in the kernel heap area. // Here we call get_page but not alloc_frame. This causes page_table_t's // to be created where necessary. We can't allocate frames yet because they // they need to be identity mapped first below, and yet we can't increase // placement_address between identity mapping and enabling the heap! uint32_t i=0; for (i = KHEAP_START; i<KHEAP_START+KHEAP_INITIAL_SIZE; i += 0x1000) get_page(i, 1, kernel_directory); i=0; while( i<end_malloc_addr()+0x1000 ){ // Kernel code is readable but not writeable from userspace. alloc_frame( get_page(i, 1, kernel_directory), false, false); i += 0x1000; } // Now allocate those pages we mapped earlier. for (i = KHEAP_START; i<KHEAP_START+KHEAP_INITIAL_SIZE; i += 0x1000) alloc_frame( get_page(i, 1, kernel_directory), false, false); } /** * Sets up the environment, page directories etc and * enables paging. **/ void install(); /** * Causes the specified page directory to be loaded into the * CR3 register. **/ void switch_page_directory(page_directory_t *new_page); /** Makes a copy of a page directory. **/ page_directory_t *clone_directory(page_directory_t *src); page_table_t *clone_table(page_table_t *src, uint32_t *physAddr); /** * Retrieves a pointer to the page required. * If make == 1, if the page-table in which this page should * reside isn't created, create it! **/ page_t *get_page(uint32_t address, int make, page_directory_t *dir); /** * Handler for page faults. **/ static void page_fault(struct regs *r); page_directory_t *kernel_directory; page_directory_t *current_directory; void alloc_frame(page_t *page, const bool &is_kernel, const bool &is_writeable); void free_frame(page_t *page); ~Paging(){ // kprintf("~Paging()\n"); } private: const uint32_t frame_size; const uint32_t frame_qtd; bitset frames; IDT &idt; }; #endif /* ----- #ifndef paging_INC ----- */
C#
UTF-8
2,093
3.109375
3
[]
no_license
using System; using System.ComponentModel; using System.Diagnostics; using System.IO.Ports; namespace SimWinO.Arduino { public class ArduinoHelper : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public bool IsConnected { get; set; } public SerialPort Port { get; set; } public int BaudRate { get; set; } = 115200; public string PortName { get; set; } public int ReadTimeout { get; set; } = 250; public int WriteTimeout { get; set; } = 250; public void Connect() { try { InitPort(); Port.Open(); IsConnected = Port.IsOpen; if (IsConnected) { Port.WriteLine("S911"); // On allume la Led de l'Arduino pour lui indiquer qu'on est là ! Port.WriteLine("S201"); // On active toutes les entrées dispo sur l'arduino } } catch (Exception e) { IsConnected = false; Debug.Write(e.Message); } } public void Disconnect() { if (Port != null && Port.IsOpen) { try { Port.WriteLine("S200"); Port.WriteLine("S910"); Port.Close(); Port.Dispose(); IsConnected = false; } catch (Exception e) { Debug.Write(e.Message); } } } private void InitPort() { // TODO Check param Port = new SerialPort { PortName = PortName, BaudRate = BaudRate, ReadTimeout = ReadTimeout, WriteTimeout = WriteTimeout }; } public void SendCommandToArduino(string command) { Port.WriteLine(command); } } }
Python
UTF-8
2,108
2.6875
3
[]
no_license
import pymysql conn = pymysql.connect( host='10.141.221.73', port=3306, user='root', passwd='root', db='fdroid', charset='utf8' ) def read_data(): lists = [] try: with conn.cursor() as cur: sql = 'select class_id, detail_description from jdk_class where class_id < 8265' #sql = 'select class_id, detail_description from jdk_class where class_id = 1632' cur.execute(sql) lists = cur.fetchall() #for each in lists: # print(each) except: conn.rollback() return lists def data_clean(data_list): result = [] for each in data_list: if each[1] != None: temp = [] description = each[1] while description.find('<') != -1: description = tag_remove(description) # print(description) description = description.replace('\n', '').replace(' ', ' ').strip() temp.append(each[0]) temp.append(description) print(temp) result.append(temp) return result def tag_remove(sentence): left_bracket_index = sentence.find('<') right_bracket_index = sentence.find('>') while sentence[left_bracket_index + 1: right_bracket_index + 1].find('<') != -1: left_bracket_index = left_bracket_index + sentence[left_bracket_index + 1: right_bracket_index + 1].find('<') + 1 tag = sentence[left_bracket_index: right_bracket_index + 1] #print(tag) sentence = sentence.replace(tag, '') return sentence def update_data(result_list): try: with conn.cursor() as cur: for each in result_list: cur.execute('update jdk_class set handled_description = %s where class_id = %s', (each[1], each[0])) print(str(each[0]) + " has saved in database") conn.commit() except: conn.rollback() if __name__ == '__main__': data_list = read_data() result = data_clean(data_list) for each in result: print(each) update_data(result)
Python
UTF-8
218
3.328125
3
[]
no_license
from utils import is_palindrome def problem4(): max = 0 for i in range(100, 1000): for j in range(100, 1000): if is_palindrome(i*j) and i*j > max: max = i*j print(max)
Java
UTF-8
913
1.859375
2
[]
no_license
package com.jinguduo.spider.data.table; import lombok.Data; import org.hibernate.validator.constraints.NotBlank; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; import java.io.Serializable; /** * 版权所有:北京金骨朵文化传播有限公司 * * @TODO * @DATE 19/05/2017 17:18 */ @Entity @Table @Data public class ScreenshotLogs implements Serializable { private static final long serialVersionUID = 8581701214157288229L; @Id @GeneratedValue private Integer id; private String code; @NotBlank private String uuid; @Lob @Basic(fetch= FetchType.LAZY) @Column(name = "content" ,columnDefinition = "TEXT") private String content; }
Java
UTF-8
6,655
2.34375
2
[ "MIT" ]
permissive
package gr.uom.java.xmi; import com.intellij.openapi.editor.Document; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import gr.uom.java.xmi.diff.CodeRange; import org.jetbrains.annotations.NotNull; /** * Provides an information about the element's location in the file. */ public class LocationInfo { private final String filePath; private final int startOffset; private final int endOffset; private final int startLine; private final int endLine; private final int startColumn; private final int endColumn; private final CodeElementType codeElementType; public LocationInfo(@NotNull PsiFile file, @NotNull String filePath, @NotNull PsiElement node, @NotNull CodeElementType codeElementType) { this.filePath = filePath; this.codeElementType = codeElementType; TextRange range = node.getTextRange(); this.startOffset = range.getStartOffset(); this.endOffset = range.getEndOffset(); Document document = file.getViewProvider().getDocument(); if (document != null) { this.startLine = document.getLineNumber(startOffset) + 1; this.endLine = document.getLineNumber(endOffset) + 1; this.startColumn = startOffset - document.getLineStartOffset(startLine - 1) + 1; this.endColumn = endOffset - document.getLineStartOffset(endLine - 1) + 1; } else { this.startLine = 0; this.endLine = 0; this.startColumn = 0; this.endColumn = 0; } } public int getStartOffset() { return startOffset; } public int getEndOffset() { return endOffset; } public int getLength() { return endOffset - startOffset; } public CodeRange codeRange() { return new CodeRange(getFilePath(), getStartLine(), getEndLine(), getStartColumn(), getEndColumn(), getCodeElementType()); } public String getFilePath() { return filePath; } public int getStartLine() { return startLine; } public int getStartColumn() { return startColumn; } public int getEndLine() { return endLine; } public int getEndColumn() { return endColumn; } public CodeElementType getCodeElementType() { return codeElementType; } public boolean subsumes(LocationInfo other) { return this.filePath.equals(other.filePath) && this.startOffset <= other.startOffset && this.endOffset >= other.endOffset; } public boolean sameLine(LocationInfo other) { return this.filePath.equals(other.filePath) && this.startLine == other.startLine && this.endLine == other.endLine; } public boolean nextLine(LocationInfo other) { return this.filePath.equals(other.filePath) && this.startLine == other.endLine + 1; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + endColumn; result = prime * result + endLine; result = prime * result + endOffset; result = prime * result + ((filePath == null) ? 0 : filePath.hashCode()); result = prime * result + startColumn; result = prime * result + startLine; result = prime * result + startOffset; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LocationInfo other = (LocationInfo) obj; if (endColumn != other.endColumn) return false; if (endLine != other.endLine) return false; if (endOffset != other.endOffset) return false; if (filePath == null) { if (other.filePath != null) return false; } else if (!filePath.equals(other.filePath)) return false; if (startColumn != other.startColumn) return false; if (startLine != other.startLine) return false; return startOffset == other.startOffset; } public enum CodeElementType { TYPE_DECLARATION, METHOD_DECLARATION, FIELD_DECLARATION, SINGLE_VARIABLE_DECLARATION, VARIABLE_DECLARATION_STATEMENT, VARIABLE_DECLARATION_EXPRESSION, VARIABLE_DECLARATION_INITIALIZER, ANONYMOUS_CLASS_DECLARATION, LAMBDA_EXPRESSION, LAMBDA_EXPRESSION_BODY, CLASS_INSTANCE_CREATION, ARRAY_CREATION, METHOD_INVOCATION, SUPER_METHOD_INVOCATION, TERNARY_OPERATOR_CONDITION, TERNARY_OPERATOR_THEN_EXPRESSION, TERNARY_OPERATOR_ELSE_EXPRESSION, LABELED_STATEMENT, FOR_STATEMENT("for"), FOR_STATEMENT_CONDITION, FOR_STATEMENT_INITIALIZER, FOR_STATEMENT_UPDATER, ENHANCED_FOR_STATEMENT("for"), ENHANCED_FOR_STATEMENT_PARAMETER_NAME, ENHANCED_FOR_STATEMENT_EXPRESSION, WHILE_STATEMENT("while"), WHILE_STATEMENT_CONDITION, IF_STATEMENT("if"), IF_STATEMENT_CONDITION, DO_STATEMENT("do"), DO_STATEMENT_CONDITION, SWITCH_STATEMENT("switch"), SWITCH_STATEMENT_CONDITION, SYNCHRONIZED_STATEMENT("synchronized"), SYNCHRONIZED_STATEMENT_EXPRESSION, TRY_STATEMENT("try"), TRY_STATEMENT_RESOURCE, CATCH_CLAUSE("catch"), CATCH_CLAUSE_EXCEPTION_NAME, EXPRESSION_STATEMENT, SWITCH_CASE, ASSERT_STATEMENT, RETURN_STATEMENT, THROW_STATEMENT, CONSTRUCTOR_INVOCATION, SUPER_CONSTRUCTOR_INVOCATION, BREAK_STATEMENT, CONTINUE_STATEMENT, EMPTY_STATEMENT, BLOCK("{"), FINALLY_BLOCK("finally"), TYPE, LIST_OF_STATEMENTS, ANNOTATION, SINGLE_MEMBER_ANNOTATION_VALUE, NORMAL_ANNOTATION_MEMBER_VALUE_PAIR, ENUM_CONSTANT_DECLARATION, JAVADOC, LINE_COMMENT, BLOCK_COMMENT; private String name; CodeElementType() { } CodeElementType(String name) { this.name = name; } public String getName() { return name; } public CodeElementType setName(String name) { this.name = name; return this; } } }
PHP
UTF-8
452
4
4
[]
no_license
<?php class Cat { public $sound; public $color; public $gender; function __construct( $sound , $color , $gender) { $this->sound = $sound; $this->color = $color; $this->gender = $gender; } function walk() { return " my Cat likes to walk, it is a " . $this->gender; } function sound() { return " my Cat makes a sound, it sounds like a" . $this->sound; } } $Kitty = new Cat ("meow", "black" , "female"); echo $Kitty->walk(); ?>
JavaScript
UTF-8
637
4.03125
4
[]
no_license
var person = { firstName: "Alex", sayHi: function() { return "Hi " + this.firstName }, determineContext: function() { return this === person }, father: { sayHi: function() { return "Hello " + this.firstName }, determineContext: function() { return this === person } } } // "Hi Alex" console.log(person.sayHi()); // "Hello undefined" -- firstName is not defined for father console.log(person.father.sayHi()); // true console.log(person.determineContext()); // false console.log(person.father.determineContext());
C++
WINDOWS-1251
743
3.359375
3
[]
no_license
// . #include "Function.h" // . void main(void) { float x1 = 2.5, x2 = 3.5, x3 = 5.0; float y = Avg(x1, x2, x3); // . // cout << "x1=" << x1 << " x2=" << x2 << " x3=" << x3 << " Y=" << y << endl; y = Avg(2., 3., 7.); // . // . y = Avg(x1, 5, x3 / 2); // . // . Table(0, 3.14, 12); }
Java
UTF-8
292
1.84375
2
[]
no_license
package com.group8.dalsmartteamwork.courseadmin.models; import com.group8.dalsmartteamwork.courseadmin.dao.IStudentEnrollmentDao; public interface IStudentEnrollmentFactory { IStudentEnrollmentDao getStudentEnrollmentDaoObject(); IPasswordGenerator getPasswordGeneratorObject(); }
Shell
UTF-8
4,035
3.21875
3
[]
no_license
#!/bin/bash set -e -x NN=4 # default number of processors if [ $# -gt 0 ] ; then NN="$1" fi # default interpolation method is conservative IMETHOD=bil if [ $# -gt 1 ] ; then # if user says "./hirham2epsg3413.sh N con" then first order conservative remapping is used IMETHOD=$2 fi METHOD=`echo $IMETHOD | tr [a-z] [A-Z]` HIRHAMMASK=glmask_geog.nc HIRHAMUSURF=topo_geog.nc SERVER=aaschwanden@chinook.alaska.edu:/center/d/ICESHEET/HIRHAM5 STARTY=1980 ENDY=2014 DMIPREFIX=DMI-HIRHAM5_GL2 PREFIX=${DMIPREFIX}_ERAI_${STARTY}_${ENDY} TARFILE=HIRHAM5_ERAI_${STARTY}_${ENDY}_DM.tar #source ./prepare_files.sh for INPUT in $HIRHAMMASK $HIRHAMUSURF; do if [ -e "$INPUT" ] ; then # check if file exist echo "$SCRIPTNAME input $INPUT (found)" else echo "$SCRIPTNAME input $INPUT (MISSING!!)" echo fi done for GRID in 9000; do PISMGRID=epsg3413_${GRID}m_grid.nc create_greenland_ext_epsg3413_grid.py -g $GRID $PISMGRID for INPUT in $PISMGRID; do if [ -e "$INPUT" ] ; then # check if file exist echo "$SCRIPTNAME input $INPUT (found)" else echo "$SCRIPTNAME input $INPUT (MISSING!!)" echo fi done for VAR in "TAS"; do INFILEMM=${PREFIX}_${VAR}_MM.nc for INPUT in $INFILEMM; do if [ -e "$INPUT" ] ; then # check if file exist echo "$SCRIPTNAME input $INPUT (found)" else echo "$SCRIPTNAME input $INPUT (MISSING!!)" echo fi done OUTFILEMM=pism_${PREFIX}_${VAR}_${GRID}M_${METHOD}_MM.nc TMPFILE=tmp_$INFILEMM # just copy over to a tmp file, preserve original ncks -O $INFILEMM $TMPFILE ncrename -d x,rlon -d y,rlat -O $TMPFILE $TMPFILE # ncatted -a units,time,o,c,"days since 1989-01-01" $TMPFILE if [ "$VAR" == "SMB" ]; then MASK=icemask.nc ncks -O $HIRHAMMASK $MASK ncwa -O -a height $MASK $MASK ncks -O -v height -x $MASK $MASK ncwa -O -a time $MASK $MASK ncks -O -v time -x $MASK $MASK python make_greenland_mask.py -v var232 $MASK $TMPFILE ncap2 -O -s "where(mask==0) smb=-9999;" $TMPFILE $TMPFILE ncatted -a _FillValue,smb,o,f,-9999 $TMPFILE fi if [[ $NN == 1 ]] ; then cdo remap${IMETHOD},$PISMGRID -setgrid,rotated_grid.txt $TMPFILE $OUTFILEMM else cdo -P $NN remap${IMETHOD},$PISMGRID -setgrid,rotated_grid.txt $TMPFILE $OUTFILEMM fi # Remap mask using nearest neighbor TMPMASK=tmp_smb_mask.nc if [ "$VAR" == "SMB" ]; then if [[ $NN == 1 ]] ; then cdo remapnn,$PISMGRID -setgrid,rotated_grid.txt -selvar,mask $TMPFILE $TMPMASK else cdo -P $NN remapnn,$PISMGRID -setgrid,rotated_grid.txt -selvar,mask $TMPFILE $TMPMASK fi ncks -A -v x,y $PISMGRID $TMPMASK ncks -A -v mask $TMPMASK $OUTFILEMM fi # let's get rid of the 'height' variable ncwa -O -a height $OUTFILEMM $OUTFILEMM ncks -O -v height -x $OUTFILEMM $OUTFILEMM done # deal with the ice upper surface elevation TMPFILE=tmp_topo.nc USURFFILE=hirham_usurf.nc ncks -O $HIRHAMUSURF $TMPFILE cdo -v remap${IMETHOD},$PISMGRID $TMPFILE $USURFFILE ncpdq -O -a y,x $USURFFILE $USURFFILE ncwa -O -a height $USURFFILE $USURFFILE ncks -O -v height -x $USURFFILE $USURFFILE ncwa -O -a time $USURFFILE $USURFFILE ncks -O -v time -x $USURFFILE $USURFFILE ncrename -O -v var6,usurf $USURFFILE $USURFFILE ncatted -O -a table,,d,, -a units,usurf,o,c,"m" -a long_name,usurf,o,c,"ice upper surface elevation" -a standard_name,usurf,o,c,"surface_altitude" $USURFFILE rm $TMPFILE # now create the forcing files for use with PISM's direct forcing classes. PPREFIX=pism_${PREFIX} done
Java
UTF-8
377
2.078125
2
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
package astli.db; /** * * @author Christof Rabensteiner <christof.rabensteiner@gmail.com> */ public class JdbcProperties { public final String url; public final String username; public final String password; public JdbcProperties(String url, String username, String password) { this.url = url; this.username = username; this.password = password; } }
Java
UTF-8
1,695
3.453125
3
[]
no_license
import java.util.ArrayList; import java.util.Scanner; import tiles.Tile; public class Main { public static void main(String args[]) { /* Hand myHand = new Hand(); Parser parser = new Parser(); Scanner sc = new Scanner(System.in); for (int i = 0; i < Hand.MAX_TILES; i++) { Tile current = parser.parse(sc.next()); myHand = myHand.add(current); } */ Hand myHand = Hand.createSampleHand(); ArrayList<Tile> result = myHand.solve(); String message = resultMessage(result); System.out.println(message); } private static String resultMessage(ArrayList<Tile> winnableTiles) { if (winnableTiles.isEmpty()) { return "No winnable tiles!"; } StringBuilder result = new StringBuilder(); int numberOfWinnableTiles = (int) getNumberOfWinnableTiles(winnableTiles); appendHeaderWithCount(result, numberOfWinnableTiles); appendTilesToMessage(result, winnableTiles); return trimNewline(result); } private static void appendHeaderWithCount(StringBuilder message, int count) { message.append("Winnable tiles: " + count + "\n"); } private static long getNumberOfWinnableTiles(ArrayList<Tile> tiles) { return tiles.stream().filter(tile -> tile != null).count(); } private static void appendTilesToMessage(StringBuilder message, ArrayList<Tile> tiles) { tiles.stream().forEach(tile -> message.append(tile + "\n")); } private static String trimNewline(StringBuilder string) { return string.toString().substring(0, string.toString().length() - 1); } }
Java
UTF-8
1,251
2.328125
2
[]
no_license
package br.com.fabricam8.seniorsapp.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import br.com.fabricam8.seniorsapp.R; import br.com.fabricam8.seniorsapp.domain.Consultation; /** * Created by Aercio on 2/12/15. */ public class ConsultationEventItemAdaper extends ArrayAdapter { private Context mContext; private LayoutInflater mInflater; private List<Consultation> mItems; public ConsultationEventItemAdaper(Context context, List<Consultation> items) { super(context, R.layout.pager_events_consultation_list_item, items); this.mContext = context; this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.mItems = items; } public View getView(int position, View convertView, ViewGroup parent) { View row = mInflater.inflate(R.layout.pager_events_consultation_list_item, null, true); TextView txtName = (TextView) row.findViewById(R.id.appointments_item_name); txtName.setText(mItems.get(position).getName()); return row; } }
PHP
UTF-8
6,991
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Ind_rendimiento extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Ind_rendimientoModel'); $this->load->helper('url'); } function index($nivel = 1, $establecimiento = 99) { $data = array(); $data['establecimiento'] = $establecimiento; $data['nivel'] = $nivel; $this->generaEtiquetas($data, $nivel, $establecimiento); $data['periodos'] = $this->Ind_rendimientoModel->getAllPeriods(); $data['trimestres'] = $this->Ind_rendimientoModel->getAllTrimestres(); $this->load->view('/ind_rendimiento/index.php', $data); } public function getFilterIndRendimiento() { $periodo=$_POST['periodo_lectivo']; $aula=$_POST['curso']; // realmente es un item $trimestre=$_POST['trimestre']; $nivel=$_POST['nivel']; if($nivel == 3) // parche para reutilizar en rol de supervisor { $nivel = 1; $aula = "-"; } $establecimiento=$_POST['establecimiento']; $data['totalRegistros'] = $this->Ind_rendimientoModel->totalRegistros($periodo, $aula, $trimestre, $nivel, $establecimiento); $materias = $this->Ind_rendimientoModel->getAllMaterias($aula, $nivel); $total = 0; $RegValuesGraph = $this->getValuesByMaterias($data['totalRegistros'], $materias, $total, $nivel); $result = array( 'Materias' => array(), 'Criticos' => array(), 'Riesgo' => array() ); $this->getPercentByMaterias($RegValuesGraph, $total, $result); echo json_encode($result); } public function getValuesByMaterias($totalRegistros, $materias, &$total, $nivel) { /* * Crea un array multidimensional que contiene la cantidad de notas Criticas, en Riesgo * y un Promedio de cada materia. * Promedio se utiliza en caso del nivel secundario para mostrar los peores 5 rendimientos * ID_MATERIA1 => CRITICOS = x * => RIESGO = y * => PROMEDIO = z * => MATERIA = NOMBRE_MATERIA * */ $RendimientoMaterias = array(); foreach ($materias as $key => $value) // Defino el arreglo multidimiensional $RendimientoMaterias[$value['id']] = array('Materia'=>"vacio", 'Criticos'=>0, 'Riesgo'=>0, 'Promedio'=>0); foreach ($totalRegistros as $key => $value) { $total++; $mat_id = $value['mat_id']; if($value['not_nota'] <= 5) $RendimientoMaterias[$mat_id]['Materia'] = $value['mat_descripcion']; if($value['not_nota'] < 4) $RendimientoMaterias[$mat_id]['Criticos'] = $RendimientoMaterias[$mat_id]['Criticos'] + 1; if (($value['not_nota'] >= 4) && ($value['not_nota'] <= 5) ) $RendimientoMaterias[$mat_id]['Riesgo'] = $RendimientoMaterias[$mat_id]['Riesgo'] + 1; } foreach ($RendimientoMaterias as $key => $value) { $RendimientoMaterias[$key]['Promedio'] = ($value['Riesgo'] + $value['Criticos'])/2; } $temporal = $this->filtroMaterias($RendimientoMaterias, $nivel); return $temporal; } public function getPercentByMaterias($RegValuesGraph, $total, &$result) /* * Cargo el arreglo $result, con los porcentajes a graficar junto con los nombres * de las materias. */ { foreach ($RegValuesGraph as $key => $value) { if ($total <= 0 ) break; array_push($result['Criticos'], round(($value['Criticos'] * 100) / $total, 2)); array_push($result['Riesgo'], round(($value['Riesgo'] * 100) / $total, 2)); array_push($result['Materias'], $key); } } private function filtroMaterias($RendimientoMaterias, $nivel) { /* * Funcion encargada de filtar las materias que seran graficadas, en caso del nivel primario * no requiere ningun calculo (se especifican implicitamente en la documentacion de requermientos), * no asi para el nivel secundario. * Tambien se descartan las materias que no contienen valores (criticos/riesgo) */ $aux = array(); if($nivel == 1) $materiasporfiltrar = array('LENGUA', 'MATEMATICA', 'CIENCIAS NATURALES', 'CIENCIAS SOCIALES'); else if($nivel == 2) { foreach ($RendimientoMaterias as $key => $value) { $vecPromedio[$key] = $value['Promedio']; $materiasporfiltrar[$key] = $value['Materia']; } array_multisort($vecPromedio, SORT_DESC, $materiasporfiltrar); array_splice($materiasporfiltrar, 5); } foreach ($RendimientoMaterias as $key => $value) if(in_array($value['Materia'], $materiasporfiltrar)) { if(($value['Promedio']) > 0 ) // segun requerimientos, no muestra valores en cero { $aux[$value['Materia']]['Criticos'] = $value['Criticos']?$value['Criticos']:0; $aux[$value['Materia']]['Riesgo'] = $value['Riesgo']?$value['Riesgo']:0; } } return $aux; } public function generaEtiquetas(&$data, $nivel, $establecimiento) { switch ($nivel) { case 1: $data['titulo'] = "Director - Nivel Primario"; $data['item'] = "Grado: "; $data['todos'] = "Todos los grados"; $data['cursos'] = $this->Ind_rendimientoModel->getAllClassroom($nivel); $nombre_establecimiento = $this->Ind_rendimientoModel->getNameEstablecimiento($establecimiento); $data['nombre_establecimiento'] = "Establecimiento: ".$nombre_establecimiento[0]['name']; break; case 2: $data['titulo'] = "Director - Nivel Secundario"; $data['item'] = "Curso: "; $data['todos'] = "Todos los cursos"; $data['cursos'] = $this->Ind_rendimientoModel->getAllClassroom($nivel); $nombre_establecimiento = $this->Ind_rendimientoModel->getNameEstablecimiento($establecimiento); $data['nombre_establecimiento'] = "Establecimiento: ".$nombre_establecimiento[0]['name']; break; case 3: $data['titulo'] = "Supervisor - Nivel Primario"; $data['item'] = "Establecimiento: "; $data['todos'] = "Elija un Establecimiento"; $data['cursos'] = $this->Ind_rendimientoModel->getAllEstablecimientos(); $data['nombre_establecimiento'] = ""; break; default: # code... break; } } }
Python
UTF-8
1,097
3.625
4
[]
no_license
import turtle import random loadWindow = turtle.Screen() loadWindow.setup(width=1000, height=1000) loadWindow.bgcolor("black") turtle.speed(0) turtle.colormode(255) turtle.pensize(3) def draw_grid(STEP,LENGTH,COLOR): circleStart = 0 for i in range(-500, LENGTH, STEP): if COLOR: r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) turtle.pencolor(r,g,b) else: turtle.pencolor('black') #vertical lines turtle.penup() #start position turtle.setpos(-500, LENGTH/2) turtle.pendown() #ending position turtle.setpos(-LENGTH/2 + i, -LENGTH/2) #horizontal lines turtle.penup() #start position turtle.setpos(LENGTH/2, -400) turtle.pendown() #ending position turtle.setpos(-500, -LENGTH/2 + i) turtle.goto(0,0) turtle.circle(circleStart+i) x = 25 y = 800 color = True while x > 0 or y < 0: draw_grid(x,y,color) color = not color loadWindow.update()
C#
UTF-8
5,151
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Diagnostics; namespace Code { class Program { static void Main(string[] args) { string NameImage = ""; Console.WriteLine("Avec quelle photo souhaitez-vous faire des modifications ?"); Console.WriteLine("1- coco (tapez 1)"); Console.WriteLine("2- lac en montagne (tapez 2)"); Console.WriteLine("3- lena (tapez 3)"); Console.WriteLine("4- Image test (tapez 4)"); Console.WriteLine("5- Fractale (tapez 5)"); char touche = Convert.ToChar(Console.ReadLine()); while (touche != '1' && touche != '2' && touche != '3' && touche != '4') { Console.Write("Votre saisie est erronée. Veuillez réessayer : "); touche = Convert.ToChar(Console.ReadLine()); } if (touche == '1') { NameImage = "coco.bmp"; } if (touche == '2') { NameImage = "lac_en_montagne.bmp"; } if (touche == '3') { NameImage = "lena.bmp"; } if (touche == '4') { NameImage = "Test.bmp"; } if (touche == '5') { byte Hauteur = Convert.ToByte(400); byte Largeur = Convert.ToByte(800); Fractale fractale= new Fractale (Hauteur,Largeur); byte [] CodeImage =fractale.CreationCodeImage(); Pixel[,] Image = fractale.CreationImage(CodeImage); fractale.ConstruireFractale(Image); Console.ReadLine(); } MyImage NewImage = new MyImage(NameImage); NewImage.From_Image_To_File(NameImage); Console.WriteLine(); Console.WriteLine("Que voulez-vous faire avec cette image ?"); Console.WriteLine("1- La mettre en noir et blanc "); Console.WriteLine("2- La mettre en niveaux de gris "); Console.WriteLine("3- La faire tourner (90°, 180°, 270°) "); Console.WriteLine("4- La tourner en mode miroir "); Console.WriteLine("5- L'agrandir "); Console.WriteLine("6- La rétrécir "); Console.WriteLine("7- La rendre floue, Renforcer ses bords, Détecter ses contours, Fonction repoussage"); char selection = Convert.ToChar(Console.ReadLine()); while (selection != '1' && selection != '2' && selection != '3' && selection != '4' && selection != '5' && selection != '6' && selection != '7') { Console.Write("Votre saisie est erronée. Veuillez réessayer : "); selection = Convert.ToChar(Console.ReadLine()); } if (selection == '1') { NewImage.NoirEtBlanc(); } if (selection == '2') { NewImage.PassageGris(); } if (selection == '3') { Console.WriteLine("De combien de degré voulez vous faire tourner l'image ?"); Console.WriteLine("1- 90° "); Console.WriteLine("2- 180° "); Console.WriteLine("3- 270° "); char rotation = Convert.ToChar(Console.ReadLine()); while (selection != '1' && selection != '2' && selection != '3') { Console.Write("Votre saisie est erronée. Veuillez réessayer : "); touche = Convert.ToChar(Console.ReadLine()); } if (selection == '1') { NewImage.Rotation90(); } if (selection == '2') { NewImage.Rotation90(); NewImage.Rotation90(); } if (selection == '3') { NewImage.Rotation90(); NewImage.Rotation90(); NewImage.Rotation90(); } } if (selection == '4') { NewImage.Miroir(); } if (selection == '5') { Console.Write("Par quel facteur voulez vous agrandir votre image? (Veuillez saisir un entier compris entre 1 et 100) "); int facteurA = Convert.ToInt32(Console.ReadLine()); NewImage.Agrandir(facteurA); } if (selection == '6') { Console.Write("Par quel facteur voulez vous agrandir votre image? (Veuillez saisir un entier compris entre 1 et 100) "); int facteurR = Convert.ToInt32(Console.ReadLine()); NewImage.Retrecir(facteurR); } if (selection == '7') { NewImage.MatriceFiltre(); } Process.Start(NameImage); } } }
Markdown
UTF-8
1,938
3.28125
3
[ "CC-BY-ND-4.0", "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Števniki Števniki so navedeni v Dodatku in med novimi besedami lekcije. Večja števila se oblikujejo s kombiniranjem osnovnih števil na naslednji način: - 1 238 – *mil du-cent tri-dek ok* - 153 837 – *cent kvin-dek tri mil ok-cent tri-dek sep* - seštevanje: 8 + 3 = 11 – *ok plus tri estas dek-unu* - odštevanje: 15 - 6 = 9 – *dek-kvin minus ses estas naŭ* # Tožilnik smeri Esperantskim predlogom normalno sledi samostalnik v imenovalniku: - *post mi* – za mano - *sen ŝi* – brez nje - *en domo* – v hiši Vendar, ko gre za premikanje v neki smeri, predlogu, ki opisuje kraj, sledi tožilnik za prikaz gibanja, npr: - *Mi iras en la domo__n__.* – Grem v hišo. - (Primejaj: *Ili manĝas en la domo.* – Jedo v hiši.) Drug primer: - *La kato saltis sur la tablo__n__.* – Mačka je skočila na mizo. - *La kato saltis sur la tablo.* – Mačka skače okoli mize. # Zaimek *oni* Nedoločni zaimek *oni* prevajamo z našim "se" in ga uporabljamo, ko ni znan subjekt. Primera: - *__Oni__ manĝas.* – Je se. - *__Oni__ sidas.* – Sedi se. # Povratni osebni zaimek *si* Povratni osebni zaimek *si* (akuzativ *sin*) pomeni se, toda samo v primerih, ko glagol kaže, da se dejanje izvaja na samem subjektu (tj. vrača se na njega): Examples: - *Li lavas __sin__.* – On se umiva. - *Ŝi rigardas __sin__.* – Ona se gleda. - *Ili kantas al __si__.* – Pojejo sebi. *si* se uporablja samo v 3. osebi ednine in množine. - *Mi rigardas min.* – Gledam se. - *Vi rigardas vin.* - Ti se gledaš. Vi se gledate. - *Li,ŝi, ĝi rigardas sin.* - On, ona, ono se gleda. - *Ni rigardas nin.* - Mi se gledamo. - *Ili rigardas sin.* – Oni se gledajo. # Predpona *re-* Pomeni - "ponovno" - "spet" - "vrnitev". Primeri: - *__re__vidi* – ponovno videti - *__re__doni* – dati nazaj, vrniti - *__re__meti* – ponovno postaviti vrniti nazaj
JavaScript
UTF-8
1,079
3.015625
3
[]
no_license
let Halo = class { constructor () { for (let i = 0; i < Halo.num; i++) { Halo.alive[i] = false Halo.r[i] = 0 } } born (x, y) { for (let i = 0; i < Halo.num; i++) { if (Halo.alive[i] === false) { Halo.alive[i] = true Halo.r[i] = 10 Halo.x[i] = x Halo.y[i] = y break } } } draw (context) { context.save() context.shadowBlur = 20 context.shadowColor = '#FFFF00' context.lineWidth = 2 for (let i = 0; i < Halo.num; i++) { if (Halo.alive[i] === true) { Halo.r[i] += 1 if (Halo.r[i] > 100) { Halo.alive[i] = false break } let alpha = 1 - Halo.r[i] / 100 context.beginPath() context.arc(Halo.x[i], Halo.y[i], Halo.r[i], 0, 2 * Math.PI) context.strokeStyle = 'rgba(255, 69, 0, ' + alpha + ')' context.stroke() } } context.restore() } } Halo.x = [] Halo.y = [] Halo.alive = [] Halo.r = [] Halo.num = 5 export default Halo
SQL
UTF-8
4,947
3.09375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.6.4 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Apr 19, 2017 at 08:20 AM -- Server version: 5.6.28 -- PHP Version: 7.0.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `db678294987` -- -- -------------------------------------------------------- -- -- Table structure for table `emoji` -- CREATE TABLE `emoji` ( `emoji_id` int(11) NOT NULL, `emoji_image` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `emoji` -- INSERT INTO `emoji` (`emoji_id`, `emoji_image`) VALUES (1, 'awful.png'), (2, 'sad.png'), (3, 'normal.png'), (4, 'good.png'), (5, 'rad.png'); -- -------------------------------------------------------- -- -- Table structure for table `upload` -- CREATE TABLE `upload` ( `date_id` int(11) NOT NULL, `date` date NOT NULL, `user_name` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `emoji_id` int(11) NOT NULL, `story` text NOT NULL, `picturename` varchar(40) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `upload` -- INSERT INTO `upload` (`date_id`, `date`, `user_name`, `emoji_id`, `story`, `picturename`) VALUES (21, '2017-02-14', 'Lulu', 5, 'Happy to meet Andrew.', 'ASLK.jpg'), (22, '2017-04-01', 'Lulu', 5, 'hhhhhhh', 'hhh.png'), (23, '2017-03-28', 'Lulu', 3, '"The person who deserves most pity is a lonesome one on a rainy day who doesn\'t know how to read.” ― Benjamin Franklin', 'rainy.jpg'), (24, '2017-03-05', 'Lulu', 4, 'Got my favourite green tea frap. ', 'frap.jpg'), (25, '2017-04-18', 'Lulu', 2, 'So awful for being sick....', 'sick.jpg'), (26, '2017-04-02', 'Mengsi', 4, 'Duo is a good place for dessert. Cakes are delicious!', 'duo.jpg'), (27, '2017-04-05', 'Mengsi', 1, 'Epic fail. We failed to escpe the room! T.T', 'fail.jpg'), (28, '2017-04-11', 'Mengsi', 5, 'Today is my mum\'s birthday. Made a floral box as a gift for her.', 'floral.jpg'), (29, '2017-04-13', 'Mengsi', 3, 'Special brunch today. Cold plate.', 'meal.jpg'), (30, '2017-04-18', 'Mengsi', 4, 'Picture day for IMM 2017 class, we had so much fun taking pictures!', 'photo.jpg'), (31, '2017-03-02', 'Linus', 5, 'No work today!', 'happy.png'), (32, '2017-03-21', 'Linus', 1, 'I lost my job T.T', 'lost.png'), (33, '2017-04-03', 'Linus', 3, 'Just a normal day.', 'normal.jpg'), (34, '2017-04-06', 'Linus', 2, 'I miss my cat...', 'sad.png'), (35, '2017-04-14', 'Linus', 4, 'Workout makes me happy!', 'workout.png'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `user_id` int(11) NOT NULL COMMENT 'auto incrementing user_id of each user, unique index', `user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s name, unique', `user_password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s password in salted and hashed format', `user_email` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s email, unique' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='user data'; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `user_name`, `user_password_hash`, `user_email`) VALUES (1, 'Linus', '$2y$10$XJQkxmntCth086SP8TSYCuqHE3NssJfRRQn9N1V3OlrFzr3uK6nmi', 'cupzhen@sina.com'), (6, 'Lulu', '$2y$10$tDiDIh0cF2Vfh6u8JqQWHODUi6afiQ8dUAohlW7MZoCbHIllSQx1m', 'aaa@sina.com'), (13, 'Daisy', '$2y$10$FNOLOazTOuRO8/k2RDefSejQ8oG1F/7/Q3Te/wJ7rCuZmisKP3k4a', 'daisy@sina.com'), (14, 'Mengsi', '$2y$10$hmWzi/eTTHy6xjd.xvPa0OJPCnm3.wIKGCXvwaS0If.jUKBIWu2gO', 'mengsi@gmail.com'); -- -- Indexes for dumped tables -- -- -- Indexes for table `emoji` -- ALTER TABLE `emoji` ADD PRIMARY KEY (`emoji_id`); -- -- Indexes for table `upload` -- ALTER TABLE `upload` ADD PRIMARY KEY (`date_id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`), ADD UNIQUE KEY `user_name` (`user_name`), ADD UNIQUE KEY `user_email` (`user_email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `emoji` -- ALTER TABLE `emoji` MODIFY `emoji_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `upload` -- ALTER TABLE `upload` MODIFY `date_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=36; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing user_id of each user, unique index', AUTO_INCREMENT=15; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
PHP
UTF-8
4,558
2.578125
3
[]
no_license
<?php include_once("generic_class/class.PGDAO.php"); include_once("generic_class/class.BSN.php"); include_once("generic_class/class.maper.php"); include_once("clases/class.contacto.php"); include_once("clases/class.contactoPGDAO.php"); include_once("clases/class.fechas.php"); class ContactoBSN extends BSN { protected $clase = "Contacto"; protected $nombreId = "Id_cont"; protected $contacto; protected $arrayTipoResponsable=array('Inscripto','No Inscripto','Excento','Monotributo'); public function __construct($_contacto=0){ ContactoBSN::seteaMapa(); if ($_contacto instanceof Contacto ){ ContactoBSN::creaObjeto(); ContactoBSN::seteaBSN($_contacto); } else { if (is_numeric($_contacto)){ ContactoBSN::creaObjeto(); if($_contacto!=0){ ContactoBSN::cargaById($_contacto); } } } } public function getId(){ return $this->contacto->getId_cont(); } public function setId($id){ $this->contacto->setId_cont($id); } public function cargaColeccionByRazon($razon){ $contacto=new Contacto(); $contacto->setRazon($razon); $contactoBSN= new ContactoBSN($contacto); $datoDB = new ContactoPGDAO($contactoBSN->getArrayTabla()); $arrayDB=$this->leeDBArray($datoDB->findByRazon()); return $arrayDB; } public function controlDuplicado(){ $retorno=false; $datoDB=new ContactoPGDAO($this->getArrayTabla()); $arrayDB=$this->leeDBArray($datoDB->findByClave()); if(sizeof($arrayDB[0])>0){ $retorno=true; } return $retorno; } /** * Retorna un array con los datos de los contactos que pertenecen a un rubro determinado * @param int $id_rubro -> identificador del rubro * @return string[] -> array conteniendo los datos de la coleccion de contactos */ public function cargaColeccionByRubro($id_rubro=0){ $contacto=new Contacto(); $contacto->setId_rubro($id_rubro); $contactoBSN= new ContactoBSN($contacto); $datoDB = new ContactoPGDAO($contactoBSN->getArrayTabla()); $arrayDB=$this->leeDBArray($datoDB->coleccionByRubro()); return $arrayDB; } /** * Retorna un array con los datos de los contactos que pertenecen a un rubro o poseen cierto texto en la razon o nombre * @param string $texto -> texto a buscar dentro de la razon o del nombre * @param int $id_rubro -> identificador del rubro * @return string[] -> array conteniendo los datos de la coleccion de contactos */ public function cargaColeccionFiltro($texto='',$id_rubro=0){ $datoDB = new ContactoPGDAO(); $arrayDB=$this->leeDBArray($datoDB->coleccionFiltro($texto,$id_rubro)); return $arrayDB; } public function comboContactoCarteles($valor='',$campo="id_cont",$class="campos_btn"){ $perfil=$this->cargaColeccionByRubro(1); $this->armaOpcionesCombo($perfil,$valor,$campo,$class); } public function comboContactoInmobiliaria($valor='',$campo="id_cont",$class="campos_btn"){ $perfil=$this->cargaColeccionByRubro(2); $this->armaOpcionesCombo($perfil,$valor,$campo,$class); } protected function armaOpcionesCombo($coleccion='',$valor='',$campo="id_cont",$class="campos_btn"){ print "<select name='".$campo."' id='".$campo."' class='".$class."'>\n"; print "<option value='0'"; if ($valor==''){ print " SELECTED "; } print ">Seleccione una opcion</option>\n"; for ($pos=0;$pos<sizeof($coleccion);$pos++){ print "<option value='".$coleccion[$pos]['id_cont']."'"; if ($coleccion[$pos]['id_cont']==$valor){ print " SELECTED "; } print ">".$coleccion[$pos]['razon']." - ".$coleccion[$pos]['nombre']." ".$coleccion[$pos]['apellido']."</option>\n"; } print "</select>\n"; } public function comboContactos($valor='',$campo="id_cont",$class="campos_btn"){ $perfil=$this->cargaColeccionForm(); $this->armaOpcionesCombo($perfil,$valor,$campo,$class); } public function comboContactosByRubro($valor='',$rubro=0,$campo="id_cont",$class="campos_btn"){ $perfil=$this->cargaColeccionByRubro($rubro); $this->armaOpcionesCombo($perfil,$valor,$campo,$class); } /* public function comboTipoResponsable($valor='',$campo="tipo_responsable",$class="campos_btn"){ $tipo=$this->arrayTipoResponsable; print "<select name='".$campo."' id='".$campo."' class='".$class."'>\n"; print "<option value='0'"; if ($valor==''){ print " SELECTED "; } print ">Seleccione una opcion</option>\n"; for ($pos=0;$pos<sizeof($tipo);$pos++){ print "<option value='".$tipo[$pos]."'"; if ($tipo[$pos]==$valor){ print " SELECTED "; } print ">".$tipo[$pos]."</option>\n"; } print "</select>\n"; } */ } // Fin clase ?>
Markdown
UTF-8
2,633
2.703125
3
[ "Unlicense" ]
permissive
# 新規プロジェクト(リポジトリ)を作るには aozorahackは青空文庫をハックしたい人の集まりです。 何か新しいものをハックするために、新たなプロジェクト(GitHub上のリポジトリ)を作ることもできます。その場合、以下の流れで作成します。 ## (1) Issueを作る https://github.com/aozorahack/aozorahack/issues/new より新しいissueを登録してください。 Issueには、以下の項目を記入してください。 * リポジトリ名(日本語) * リポジトリのパス名(URLに使うやつ) * リポジトリの紹介文 その他、何をしたいか等の説明も書いておくと、後述の賛同者を募りやすいと思います。 ## (2) 賛同者を募る 新しく作られたissueを見て、「これは作ってもよいかも」と思った方は、コメントに:+1:を記入してください。 ## (3) リポジトリを作る issueを立てた本人以外に :+1: がつけば、リポジトリを作ります。リポジトリのオーナーは特にissueの中で提案がなければissueを作った人にします。 ## この方針についての覚え書き * 新規プロジェクトを作りたい、というissueに対して反対意見が出ても(例えば :-1: がついたりしても)、賛同者がいれば気にせずリポジトリを作ることにします。リポジトリの作成数の上限はないため、余程のことがない限り作って困ることはないためです。 * すでに類似のリポジトリが存在していても、何か異なることがあれば新しく作ってもかまいません。例えば同じようなツールを別言語で作りたい、という場合には、それぞれでプロジェクト(リポジトリ)を作って、それぞれのポリシーに従って活動すればよいでしょう(もちろん協力しあってもよいでしょう)。 * そもそも新しくリポジトリを作る/作らないといった判断を誰かが行ったり、誰かに行わせること自体が大きなコストとなる可能性があります。そのようなコストを最小限にしたい、というのがこのポリシーの背景にあります。やりたい人がやりたいことをできるように・助けたい人が助けられるようにしておいて、重要性・必要性が高いとみんなが思うプロジェクトは盛り上がり、そうではないプロジェクトは結果として自然に淘汰されていく、ということを期待しています。
Python
UTF-8
167
2.625
3
[]
no_license
def sangsu(va): return (va // 100) + (va % 100 // 10) * 10 + (va % 100 % 10) * 100 a, b = map(int, input().split()) a, b = sangsu(a), sangsu(b) print(max(a, b))
Java
UTF-8
11,005
2.265625
2
[]
no_license
package com.dudkovlad.CalcTDP; import android.content.Context; import android.content.SharedPreferences; import java.util.ArrayList; /** * Created by vlad on 27.09.2014. */ public class Data { public static SharedPreferences prefs; public static ArrayList<HistoryItem> history_items; public static int pages_count, pages_mainpage; public static int pages_columnline_count[][]; public static String pages_button_value[][]; public static boolean del_but_show, pages_vertical_slide; public static int del_but_prcnt; public static int color_theme; public static boolean result_show_float; public static void Load_Data(SharedPreferences __prefs, Context context) { prefs = __prefs; boolean first_run = prefs.getBoolean("first_run", true); int history_count = prefs.getInt("history_count",1); history_items = new ArrayList<>(history_count); HistoryItem histitem; for(int i = 0; i < history_count; i++) { histitem = new HistoryItem( prefs.getString("history_src" + i, "2+2"), prefs.getString("history_result" + i, "4"), prefs.getInt("history_num_sys" + i, 10), prefs.getBoolean("history_radians"+ i, true)); history_items.add(histitem); } result_show_float = prefs.getBoolean("result_show_float", false); color_theme = prefs.getInt("color_theme", GRAY); del_but_show = prefs.getBoolean("del_but_show", true); del_but_prcnt = prefs.getInt("del_but_prcnt", 25); pages_vertical_slide = prefs.getBoolean("pages_vertical_slide", false); pages_count = prefs.getInt("pages_count", 3); pages_columnline_count = new int [pages_count][2]; pages_mainpage = prefs.getInt("pages_mainpage", 2); int max=0; for (int i = 0; !first_run&&i < pages_count; i++) { pages_columnline_count[i][0] = prefs.getInt("pages_columnline_count"+i+"/"+"0", 4); pages_columnline_count[i][1] = prefs.getInt("pages_columnline_count"+i+"/"+"1", 4); if(pages_columnline_count[i][0]*pages_columnline_count[i][1]>max) max = pages_columnline_count[i][0]*pages_columnline_count[i][1]; } if(!first_run) pages_button_value = new String [pages_count][max]; for (int i = 0; !first_run&&i < pages_count; i++) { for (int j = 0; j < pages_columnline_count[i][0] * pages_columnline_count[i][1]; j++) { pages_button_value[i][j] = prefs.getString("pages_button_value" + i + "/" + String.valueOf(j), ""); } } if (first_run) { pages_columnline_count = new int [][] { {4,4},{4,4},{4,4} }; pages_button_value = new String[][] { { "Sin(","Cos(","Tan(","i", "Ln(","Log(","π","e", "%","!","√","^", "(",")","|","Y" }, { "7","8","9","÷", "4","5","6","×", "1","2","3","-", ".","0","=","+" }, { "∩","∪","∆","\\", "bin","oct","5 + ((1 + 2) × 4) - 3=14","Cos(1+3/4^2)+(8+2×5)÷(1+3×2-4)=6.373979630824", "A","B","(8+2×5)÷(1+3×2-4)=6","³√", "D","E","|5+|5-10|-30|=20","X^2+Y^2=Z" } }; } } public static void Save () { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("first_run", false); editor.putInt("history_count", history_items.size()); for(int i = 0; i < history_items.size(); i++) { editor.putString("history_src" +i, history_items.get(i).getHistory_src()); editor.putString("history_result" +i, history_items.get(i).getHistory_result()); editor.putInt("history_num_sys" +i, history_items.get(i).getHistory_num_sys()); editor.putBoolean("history_radians" +i, history_items.get(i).getHistory_radians()); } editor.putBoolean("result_show_float", result_show_float); editor.putInt("color_theme", color_theme); editor.putBoolean("del_but_show", del_but_show); editor.putInt("del_but_prcnt", del_but_prcnt); editor.putBoolean("pages_vertical_slide", pages_vertical_slide); editor.putInt("pages_count", pages_count); editor.putInt("pages_mainpage", pages_mainpage); for (int i = 0; i < pages_count; i++) { editor.putInt("pages_columnline_count"+i+"/"+"0", pages_columnline_count[i][0]); editor.putInt("pages_columnline_count"+i+"/"+"1", pages_columnline_count[i][1]); for (int j = 0; j < pages_columnline_count[i][0] * pages_columnline_count[i][1]; j++) editor.putString("pages_button_value" + i + "/" + String.valueOf(j), pages_button_value[i][j]); } editor.apply(); } public static void HistoryNext (HistoryItem item) { if ((history_items.size() > 0 && !history_items.get(0).getHistory_src().equals(""))||history_items.size() == 0) history_items.add(0, item); else HistoryChange(item); for (int i = history_items.size()-1; i > 0; i--) { if ( item.equals(history_items.get(i)) ) history_items.remove(i); } } public static void HistoryRemove (int i) { if (history_items.size() > i) history_items.remove(i); } public static void HistoryChange (HistoryItem item) { if (history_items.size() > 0) { history_items.remove(0); history_items.add(0, item); for (int i = history_items.size()-1; i > 0; i--) { if ( item.equals(history_items.get(i)) ) history_items.remove(i); } } else HistoryNext(item); } public static int RED = 0; public static int PINK = 1; public static int PURPLE = 2; public static int DEEP_PURPLE = 3; public static int INDIGO = 4; public static int BLUE = 5; public static int LIGHT_BLUE = 6; public static int CYAN = 7; public static int TEAL = 8; public static int GREEN = 9; public static int LIGHT_GREEN = 10; public static int LIME = 11; public static int YELLOW = 12; public static int AMBER = 13; public static int ORANGE = 14; public static int DEEP_ORANGE = 15; public static int BROWN = 16; public static int GRAY = 17; public static int BLUE_GRAY = 18; public static int BLACK_WHITE = 19; public static int OWN = 20; public static int[][] colors = new int [][] { {0xFFFFEBEE, 0xFFFFCDD2, 0xFFEF9A9A, 0xFFE57373, 0xFFEF5350, 0xFFF44336, 0xFFE53935, 0xFFD32F2F, 0xFFC62828, 0xFFB71C1C, 0xFFFF8A80, 0xFFFF5252, 0xFFFF1744, 0xFFD50000}, {0xFFFCE4EC, 0xFFF8BBD0, 0xFFF48FB1, 0xFFF06292, 0xFFEC407A, 0xFFE91E63, 0xFFD81B60, 0xFFC2185B, 0xFFAD1457, 0xFF880E4F, 0xFFFF80AB, 0xFFFF4081, 0xFFF50057, 0xFFC51162}, {0xFFF3E5F5, 0xFFE1BEE7, 0xFFCE93D8, 0xFFBA68C8, 0xFFAB47BC, 0xFF9C27B0, 0xFF8E24AA, 0xFF7B1FA2, 0xFF6A1B9A, 0xFF4A148C, 0xFFEA80FC, 0xFFE040FB, 0xFFD500F9, 0xFFAA00FF}, {0xFFEDE7F6, 0xFFD1C4E9, 0xFFB39DDB, 0xFF9575CD, 0xFF7E57C2, 0xFF673AB7, 0xFF5E35B1, 0xFF512DA8, 0xFF4527A0, 0xFF311B92, 0xFFB388FF, 0xFF7C4DFF, 0xFF651FFF, 0xFF6200EA}, {0xFFE8EAF6, 0xFFC5CAE9, 0xFF9FA8DA, 0xFF7986CB, 0xFF5C6BC0, 0xFF3F51B5, 0xFF3949AB, 0xFF303F9F, 0xFF283593, 0xFF1A237E, 0xFF8C9EFF, 0xFF536DFE, 0xFF3D5AFE, 0xFF304FFE}, {0xFFE3F2FD, 0xFFBBDEFB, 0xFF90CAF9, 0xFF64B5F6, 0xFF42A5F5, 0xFF2196F3, 0xFF1E88E5, 0xFF1976D2, 0xFF1565C0, 0xFF0D47A1, 0xFF82B1FF, 0xFF448AFF, 0xFF2979FF, 0xFF2962FF}, {0xFFE1F5FE, 0xFFB3E5FC, 0xFF81D4FA, 0xFF4FC3F7, 0xFF29B6F6, 0xFF03A9F4, 0xFF039BE5, 0xFF0288D1, 0xFF0277BD, 0xFF01579B, 0xFF80D8FF, 0xFF40C4FF, 0xFF00B0FF, 0xFF0091EA}, {0xFFE0F7FA, 0xFFB2EBF2, 0xFF80DEEA, 0xFF4DD0E1, 0xFF26C6DA, 0xFF00BCD4, 0xFF00ACC1, 0xFF0097A7, 0xFF00838F, 0xFF006064, 0xFF84FFFF, 0xFF18FFFF, 0xFF00E5FF, 0xFF00B8D4}, {0xFFE0F2F1, 0xFFB2DFDB, 0xFF80CBC4, 0xFF4DB6AC, 0xFF26A69A, 0xFF009688, 0xFF00897B, 0xFF00796B, 0xFF00695C, 0xFF004D40, 0xFFA7FFEB, 0xFF64FFDA, 0xFF1DE9B6, 0xFF00BFA5}, {0xFFE8F5E9, 0xFFC8E6C9, 0xFFA5D6A7, 0xFF81C784, 0xFF66BB6A, 0xFF4CAF50, 0xFF43A047, 0xFF388E3C, 0xFF2E7D32, 0xFF1B5E20, 0xFFB9F6CA, 0xFF69F0AE, 0xFF00E676, 0xFF00C853}, {0xFFF1F8E9, 0xFFDCEDC8, 0xFFC5E1A5, 0xFFAED581, 0xFF9CCC65, 0xFF8BC34A, 0xFF7CB342, 0xFF689F38, 0xFF558B2F, 0xFF33691E, 0xFFCCFF90, 0xFFB2FF59, 0xFF76FF03, 0xFF64DD17}, {0xFFF9FBE7, 0xFFF0F4C3, 0xFFE6EE9C, 0xFFDCE775, 0xFFD4E157, 0xFFCDDC39, 0xFFC0CA33, 0xFFAFB42B, 0xFF9E9D24, 0xFF827717, 0xFFF4FF81, 0xFFEEFF41, 0xFFC6FF00, 0xFFAEEA00}, {0xFFFFFDE7, 0xFFFFF9C4, 0xFFFFF59D, 0xFFFFF176, 0xFFFFEE58, 0xFFFFEB3B, 0xFFFDD835, 0xFFFBC02D, 0xFFF9A825, 0xFFF57F17, 0xFFFFFF8D, 0xFFFFFF00, 0xFFFFEA00, 0xFFFFD600}, {0xFFFFF8E1, 0xFFFFECB3, 0xFFFFE082, 0xFFFFD54F, 0xFFFFCA28, 0xFFFFC107, 0xFFFFB300, 0xFFFFA000, 0xFFFF8F00, 0xFFFF6F00, 0xFFFFE57F, 0xFFFFD740, 0xFFFFC400, 0xFFFFAB00}, {0xFFFFF3E0, 0xFFFFE0B2, 0xFFFFCC80, 0xFFFFB74D, 0xFFFFA726, 0xFFFF9800, 0xFFFB8C00, 0xFFF57C00, 0xFFEF6C00, 0xFFE65100, 0xFFFFD180, 0xFFFFAB40, 0xFFFF9100, 0xFFFF6D00}, {0xFFFBE9E7, 0xFFFFCCBC, 0xFFFFAB91, 0xFFFF8A65, 0xFFFF7043, 0xFFFF5722, 0xFFF4511E, 0xFFE64A19, 0xFFD84315, 0xFFBF360C, 0xFFFF9E80, 0xFFFF6E40, 0xFFFF3D00, 0xFFDD2C00}, {0xFFEFEBE9, 0xFFD7CCC8, 0xFFBCAAA4, 0xFFA1887F, 0xFF8D6E63, 0xFF795548, 0xFF6D4C41, 0xFF5D4037, 0xFF4E342E, 0xFF3E2723}, {0xFFFAFAFA, 0xFFF5F5F5, 0xFFEEEEEE, 0xFFE0E0E0, 0xFFBDBDBD, 0xFF9E9E9E, 0xFF757575, 0xFF616161, 0xFF424242, 0xFF212121}, {0xFFECEFF1, 0xFFCFD8DC, 0xFFB0BEC5, 0xFF90A4AE, 0xFF78909C, 0xFF607D8B, 0xFF546E7A, 0xFF455A64, 0xFF37474F, 0xFF263238}, {0xFF000000, 0xFFFFFFFF}, {0xFFFFF8E1, 0xFFFFECB3, 0xFFFFE082, 0xFFFFD54F, 0xFFFFCA28, 0xFFFFC107, 0xFFFFB300, 0xFFFFA000, 0xFFFF8F00, 0xFFFF6F00, 0xFFFFE57F, 0xFFFFD740, 0xFFFFC400, 0xFFFFAB00}, }; }
Python
UTF-8
1,045
2.921875
3
[]
no_license
from sklearn import datasets import numpy as np def findirs(n,target,argsortlist): targetlist =[] for i in range(n): targetlist.append(target[argsortlist[i]]) sum0 =0 sum1 =0 sum2 =0 for i in targetlist: if i == 0: sum0 = sum0+1 elif i ==1: sum1 =sum1+1 elif i==2: sum2 = sum2+1 sortlsit =np.array([sum0,sum1,sum2]) num = sortlsit.argsort()[-1] if num ==0: print("分类0") elif num ==1: print("分类1") elif num ==2: print("分类2") if __name__ == '__main__': data1 = datasets.load_iris() data = data1.data target = data1.target xtest = [5, 3, 1.5, 0.3] score = [] for content in data: score.append(np.sqrt((content[0] - xtest[0]) ** 2 + (content[1] - xtest[1]) ** 2 + (content[2] - xtest[2]) ** 2 + (content[3] - xtest[3]) ** 2)) argsortlist = np.array(score).argsort() findirs(3,target,argsortlist)
Java
UTF-8
1,346
2.71875
3
[]
no_license
package view.menuBar; import javax.swing.AbstractButton; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import controller.menu.AddPlayerListener; import controller.menu.RemovePlayerButton; import model.playerStatus.PlayerStatus; import view.mainUI.ApplicationFrame; import view.toolBar.ToolBar; public class MenuBar extends JMenuBar { private AbstractButton addPlayerButton; private AbstractButton removePlayerButton; public MenuBar(ApplicationFrame frame, ToolBar toolBar) { JMenu menu = new JMenu("Player"); this.add(menu); this.setVisible(true); this.addPlayerButton = new JMenuItem(); this.addPlayerButton.setText("Add Player"); // addPlayerButton.setPreferredSize(new Dimension(100, 35)); this.addPlayerButton.addActionListener(new AddPlayerListener(frame)); menu.add(this.addPlayerButton); this.removePlayerButton = new JMenuItem(); this.removePlayerButton.setText("Remove Player"); this.removePlayerButton.setEnabled(false); // removePlayerButton.setPreferredSize(new Dimension(100, 35)); this.removePlayerButton.addActionListener(new RemovePlayerButton(frame)); menu.add(this.removePlayerButton); } public void enableButtons(PlayerStatus playerStatus) { this.removePlayerButton.setEnabled(playerStatus.isRemoveable() && playerStatus.getRemoveButton()); } }
Swift
UTF-8
809
3.828125
4
[]
no_license
import UIKit struct StringStack { private var array: [String] = [] func peek() -> String { guard let topElement = array.first else { fatalError("The stack is empty.")} return topElement } mutating func pop() -> String { return array.removeFirst() } mutating func push(_ element: String) { array.insert(element, at: 0) } } var nameStack = StringStack() nameStack.push("Calab") nameStack.push("Mark") nameStack.push("Jacob") print(nameStack) nameStack.peek() nameStack.pop() print(nameStack) extension StringStack: CustomStringConvertible { var description: String { let topDivider = "---Stack---\n" let bottomDivider = "\n------------\n" let stackElements = array.joined(separator: "\n") return topDivider * stackElements * bottomDivider } }
SQL
UTF-8
220
3.515625
4
[]
no_license
#---V1-- SELECT E.last_name, E.first_name, D.dept_no FROM dept_emp D INNER JOIN employees E USING(emp_no); #---V2-- SELECT E.last_name, E.first_name, D.dept_no FROM dept_emp D, employees E WHERE D.emp_no = E.emp_no;
C
UTF-8
1,273
2.78125
3
[]
no_license
/* ** EPITECH PROJECT, 2019 ** minishel ** File description: ** fonction.other */ #include <stdlib.h> #include "include.h" int init_compar(ar_t *comp) { comp->cond = 3; comp->buffer = malloc(sizeof(char) * comp->cond); comp->buffer[0] = "exit"; comp->buffer[1] = "echo"; comp->buffer[2] = "cd"; } void modif_pwd(char **env) { char compar[] = "PWD="; char *recup; int i = 0; write(1, "cc\n", 3); for (i = 0; env[i] != 0; i++) { if (my_str_compare1(env[i], compar) == 1) { recup = my_calloc(sizeof(char) * (my_strlen1(env[i]))); recup = env[i]; } } } int other_fuction(ar_t separ, char **env, int val, ar_t *comp) { char pwd[100]; char compar[] = "PWD"; char empty[] = ".."; int size = 0; if (val == 2) { if (separ.buffer[1] == 0 || separ.buffer[1] == " "){ if (chdir(empty) == -1) write(1, "ERROR\n", 6); size++; } if (chdir(separ.buffer[1]) == -1 && size == 0){ write(1, separ.buffer[1], my_strlen1(separ.buffer[1])); write(1, ": No such file or directory\n", 28); return (1); size++; } if (size > 0) modif_pwd(env); } }
Java
UTF-8
1,032
2.0625
2
[]
no_license
package kr.co.momstudy.admin.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import kr.co.momstudy.common.db.MyAppSqlConfig; import kr.co.momstudy.repository.dao.AdminDAO; import kr.co.momstudy.repository.vo.User; @WebServlet("/admin/ban.do") public class UserBanController extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AdminDAO dao = MyAppSqlConfig.getSqlSessionInstance().getMapper(AdminDAO.class); resp.setContentType("text/html;charset=UTF-8"); req.setCharacterEncoding("UTF-8"); User user = new User(); user.setBan(Integer.parseInt(req.getParameter("banDate"))); user.setEmail(req.getParameter("email")); dao.updateBanDate(user); resp.sendRedirect(req.getContextPath() + "/admin/user.do"); } }
JavaScript
UTF-8
289
3.171875
3
[]
no_license
/* Collin Mullis Ch.4 Range Array Homework CMP 237 */ var range = function(start, end) { var rangeArray = []; for (var numRange = start; numRange <= end; numRange = numRange + 1) if (numRange <= end) rangeArray.push(numRange); return rangeArray; } console.log(range(1,6));
C#
UTF-8
3,827
2.609375
3
[]
no_license
using System; using System.Configuration; using System.Reflection; namespace DeviceAbriDoor.Configs { public class AppConfigSection : ConfigurationSection { private static AppConfigSection instance = null; private static readonly object lob = new object(); private static string configFilePath = null; private const string SectionName = "system"; public static AppConfigSection GetInstance() { if (instance == null) { lock (lob) { if (instance == null) { configFilePath = Assembly.GetEntryAssembly().Location; if (configFilePath.EndsWith(".config", StringComparison.InvariantCultureIgnoreCase)) { configFilePath = configFilePath.Remove(configFilePath.Length - 7); } Configuration config = ConfigurationManager.OpenExeConfiguration(configFilePath); if (config.Sections[SectionName] == null) { instance = new AppConfigSection(); config.Sections.Add(SectionName, instance); config.Save(ConfigurationSaveMode.Modified); } else { instance = (AppConfigSection)config.Sections[SectionName]; } } } } return instance; } public void Save() { Configuration config = ConfigurationManager.OpenExeConfiguration(configFilePath); AppConfigSection section = (AppConfigSection)config.Sections[SectionName]; section.WebApi = this.WebApi; section.Device = this.Device; section.Scheduler = this.Scheduler; section.AppMode = this.AppMode; config.Save(ConfigurationSaveMode.Modified); } [ConfigurationProperty("appMode", DefaultValue = "NO", IsRequired = true)] [RegexStringValidator("^(Yes|yEs|yeS|YEs|YeS|yES|YES|yes|No|NO|no)$")] private string appMode { get { return this["appMode"].ToString(); } set { this["appMode"] = value; } } public bool AppMode { get { return appMode.ToUpper().Equals("YES"); } set { string temp = value ? "YES" : "NO"; if (!temp.Equals(appMode)) { appMode = temp; } } } [ConfigurationProperty("scheduler", IsRequired = true)] public SchedulerConfigElement Scheduler { get { return (SchedulerConfigElement)this["scheduler"]; } set { this["scheduler"] = value; } } [ConfigurationProperty("web-api", IsRequired = true)] public WebApiConfigElement WebApi { get { return (WebApiConfigElement)this["web-api"]; } set { this["web-api"] = value; } } [ConfigurationProperty("device", IsRequired = true)] public DeviceConfigElement Device { get { return (DeviceConfigElement)this["device"]; } set { this["device"] = value; } } } }
Python
UTF-8
844
2.578125
3
[]
no_license
from django.db import models from django.utils import timezone class Post(models.Model): rut = models.CharField(max_length=10) nomCompleto = models.CharField(max_length=100) fecNac = models.DateTimeField() email = models.CharField(max_length=100) telefono = models.CharField(max_length=10) region = models.CharField(max_length=30) ciudad = models.CharField(max_length=30) vivienda = models.CharField(max_length=30) sexo = models.CharField(max_length=1, blank=False, null=False, default='M') def publish(self): self.save() #guarda los cambios en la bd def __str__(self): # lo mismo que toString return self.rut + ' - ' + self.nomCompleto + ' - ' + str(self.fecNac) + ' - ' + self.email + ' - ' + self.telefono + ' - ' + self.region + ' - ' + self.ciudad + ' - ' + self.vivienda
Java
UTF-8
1,056
3.921875
4
[]
no_license
import java.util.Scanner; import java.util.Arrays; public class IdenticalArrays { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("How many inputs in the first array? "); int first [] = new int [input.nextInt()]; System.out.println ("Enter the inputs: "); for (int i = 0; i < first.length; i++) { first[i]=input.nextInt(); System.out.println("How many inputs in the second array? "); int second [] = new int [input.nextInt()]; System.out.println ("Enter the inputs: "); for (int j = 0; j < second.length; j++) { second[j]=input.nextInt(); if (equal(first,second)) System.out.println("Arrays are equal"); else System.out.println("Arrays are not equal"); } } input.close(); } public static boolean equal(int[] x, int[] y) { if (x.length != y.length) { return false; } Arrays.sort(x); Arrays.sort(y); for (int i = 0; i < x.length; i++) { if (x[i] != y[i]) return false; } return true; } }
Python
UTF-8
2,758
2.9375
3
[]
no_license
expectedHeader = ['Name', 'Company', 'Customer Type','Email', 'Phone', 'Mobile', 'Fax', 'Website', 'Street', 'City','State', 'ZIP', 'Country', 'Opening Balance', 'Date', 'Resale Number'] expectedExportHeader = ['Customer', 'Company', 'Street Address', 'City', 'State', 'Country', 'Zip', 'Phone', 'Email', 'Attachments', 'Open Balance', 'Notes'] def verifyHeader(headerToVerify): isHeaderOkay = True errorList = [] for headerE, headerV in zip(expectedExportHeader, headerToVerify): if headerV != headerE: isHeaderOkay = False errorList.append(headerV) return isHeaderOkay, errorList def removeDuplicates(listOfOrderedDict): listWithoutDuplicates = [] for row in listOfOrderedDict: isMatch = False for entry in listWithoutDuplicates: if(entry['Name'] == row['Name']): isMatch = True if(not isMatch): listWithoutDuplicates.append(row) return listWithoutDuplicates def removeMatchesFromEmployeeDojo(qboList, employeeDojoList): #build a list of OrderedDict objects that do not exist #in the qboList listWithoutMatches = [] for row in employeeDojoList: #grab the next entry in the employeeDojoList isMatch = False #cycle through each record in the qboList #until either the end of the list or if a match is found for entry in qboList: #first remove any extra spaces in the name fields customer = entry['Customer'].replace(" ", "") name = row['Name'].replace(" ", "") if( customer == name): isMatch = True break #found a match so stop looking #if match is still false, then add the record to the list if(not isMatch): listWithoutMatches.append(row) return listWithoutMatches def removeMatchesFromQBO(qboList, employeeDojoList): #build a list of OrderedDict objects that do not exist #in the employeeDojoList listWithoutMatches = [] for entry in qboList: #grab the next entry in the qboList isMatch = False #cycle through each record in the employeeDojoList #until either the end of the list or if a match is found for row in employeeDojoList: #first remove any extra spaces in the name fields customer = entry['Customer'].replace(" ", "") name = row['Name'].replace(" ", "") if( customer == name): isMatch = True break #found a match so stop looking #if match is still false, then add the record to the list if(not isMatch): listWithoutMatches.append(entry) return listWithoutMatches
Rust
UTF-8
2,794
2.9375
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Optional `Secret` wrapper type for the `bytes::BytesMut` crate. use super::ExposeSecret; use bytes::BytesMut; use core::fmt; use zeroize::Zeroize; #[cfg(all(feature = "bytes", feature = "serde"))] use serde::de::{self, Deserialize}; /// Instance of [`BytesMut`] protected by a type that impls the [`ExposeSecret`] /// trait like `Secret<T>`. /// /// Because of the nature of how the `BytesMut` type works, it needs some special /// care in order to have a proper zeroizing drop handler. #[derive(Clone)] pub struct SecretBytesMut(BytesMut); impl SecretBytesMut { /// Wrap bytes in `SecretBytesMut` pub fn new(bytes: impl Into<BytesMut>) -> SecretBytesMut { SecretBytesMut(bytes.into()) } } impl ExposeSecret<BytesMut> for SecretBytesMut { fn expose_secret(&self) -> &BytesMut { &self.0 } } impl fmt::Debug for SecretBytesMut { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SecretBytesMut([REDACTED])") } } impl From<BytesMut> for SecretBytesMut { fn from(bytes: BytesMut) -> SecretBytesMut { SecretBytesMut::new(bytes) } } impl Drop for SecretBytesMut { fn drop(&mut self) { self.0.resize(self.0.capacity(), 0); self.0.as_mut().zeroize(); debug_assert!(self.0.as_ref().iter().all(|b| *b == 0)); } } #[cfg(all(feature = "bytes", feature = "serde"))] impl<'de> Deserialize<'de> for SecretBytesMut { fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct SecretBytesVisitor; impl<'de> de::Visitor<'de> for SecretBytesVisitor { type Value = SecretBytesMut; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("byte array") } #[inline] fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where E: de::Error, { let mut bytes = BytesMut::with_capacity(v.len()); bytes.extend_from_slice(v); Ok(SecretBytesMut(bytes)) } #[inline] fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error> where V: de::SeqAccess<'de>, { // 4096 is cargo culted from upstream let len = core::cmp::min(seq.size_hint().unwrap_or(0), 4096); let mut bytes = BytesMut::with_capacity(len); use bytes::BufMut; while let Some(value) = seq.next_element()? { bytes.put_u8(value); } Ok(SecretBytesMut(bytes)) } } deserializer.deserialize_bytes(SecretBytesVisitor) } }
Markdown
UTF-8
5,784
2.671875
3
[]
no_license
+++ categories = ["programming"] date = "2016-12-18T01:41:28+09:00" slug = "image-encoding-intro" tags = ["Javascript", "Encoding"] title = "Node.jsのFile Systemで画像を扱うときの出力方法" type = "programming" +++ Electronを使っていると、けっこう使うFile Systemモジュールですが、画像を扱う際にバイナリとかバッファとかBase64などのエンコーディングでてきますよね?エンコードまわりと基本的なfsモジュールの出力操作について触れたいと思います。 ## バイナリとは 2進法で表現したデータのことです。2進法とは数字の0と1をつかって数を表す方法です。「デジタルは0と1でできている」とどこの誰かが言ったりしますが、機械は2進法でプログラムを読み取ります。なぜ2進法かというと、単純に計算がし易いからではないかと思います。 日常的にボクたちが使っているのは0~9の10個の数字で表す10進法ですが、コンピュータにとっては理解するのがすこし遠い言語になってしまうわけです。0と1の組み合わせは◯(マル)か☓(バツ)かみたいな判断をしていくことと同じなので、シンプルですね。 つまり、画像データでバイナリということは、色やピクセルの配置、その他画像に含まれる情報がすべて0と1で表現されたデータということです。アプリケーションなんかを作る場合、操作性を意識しますから、バイナリデータを変数に格納して入出力したりすることで、処理が早くなるというメリットがあります。 ただ、注意しなくてはならないのは、ブラウザなどのフロント側ではバイナリデータを直接読み込んで表示するわけではないので、バイナリデータを処理で使用する場合は、jpgやpngなどに変換する作業を挟まないといけません。まぁ小さい画像くらいならいいのですが、大きいサイズの画像や動画とかになったら処理が重たくなりがちなので通信するデータサイズを縮小し、CPUやGPUなどの負荷を小さくするためにバイナリデータをうまく使っていくといいみたいです。 ## バッファとは バッファとは、入出力処理において、プログラム処理中のタイムラグを補う目的で実装されたデータを一時的に保存する記憶領域のことを指します。英語では「緩衝記憶装置」「緩衝物」を意味する単語みたいです。 イメージしやすいと思いますが、一時ファイルを扱うので、データを気軽に扱うことができます。あまりに大きなデータを扱うには向きませんが、さらっと「ちょっとこれ持ってて!」くらいのデータだったら柄どころが結構あるのではないでしょうか。 Vimをやっている人ならバッファの概念はお手の物だと思いますが、たとえば、音楽の録音ソフトとかで「バッファサイズが足りません」とかってでる、あれもバッファですね。要するにそうしたエラーがでるのは、「両手塞がってるからもう無理!」という状態のことですね。扱うデータ量の最大値を想像して設計しないとああした自体に陥ります。 手軽なデータに使いましょう。 ## Base64とは バイナリデータを「A-Z,a-z,0-9,+,/」の64文字で表現するエンコード規格とのことです。64進数ということですね。◯進数とは「◯文字でデータを表現するのか」ということに近いと思うので、ざっくり覚えたいかたはそう覚えておきましょう。 さて、バイナリデータが軽やかであるという話がでたのに、なぜあわざわざBase64のデータを使うシチュエーションが生まれるのでしょうか? 答えをさきに言うと、ボクたちが日々使うメールのために作られた規格のようです。メール送信でSMTPって聞いたことありますかね?これは送信メールの通信規格なんですけど、当時このSMTPではASCIIデータという7Byteで表現される英数字しか送れなかったようです。日本語とかを扱うためにゴニョゴニョ最適化でもしたのでしょうか。それで、画像や音声のデータをこれじゃ送れないってことで、Base64というデータ変換方式が作られたとさ。 プログラミングにおいては、正規表現などをつかってデータをフィルタリングしたりするのに一貫性のあるデータの方が使いやすいって理由でBase64が使わたり、画像データとしてブラウザでも表示できるので、そのような用途がある場合に使用されたりしています。 パフォーマンスというよりはデータの整形や表示が楽というメリットがあります。 ## それらを踏まえていざwriteFile ここまでは前置きでしたが、本題はそう長くありません。扱うデータをいづれかにするというだけなので、はっきりいって結論だけなら10行で終わりでした。前置きを伸ばしたお陰で記事っぽくなってよかったです。 書き方はこうです。 ``` const fs = require('fs'); fs.writeFile(public, data, {encoding: '指定'}, function(err){ // Any Code }); ``` 指定部分には - binary - buffer - base64 とかがはいったりしますね。 あとは適当に試行錯誤してみると良いと思います。 では。
SQL
UHC
9,133
4.4375
4
[]
no_license
Ѱ , ϳ ÷ ϴ ex: ü ޿ , smith μ μȣ WHERE 밡 WHERE deptno = 10 ==> μȣ 10 Ȥ 30 WHERE deptno IN(10,30) WHERE deptno = 10 OR deptno = 30 * ȸϴ = ڸ Ұ WHERE deptno = (10,30) ϸ WHERE deptno IN ( ϰ, ϳ ÷ ̷ ) , ÷ ϳ ==> 밡 IN(̾, ߿), (ANY,ALL(󵵰 )) IN : TRUE WHERE ÷|ǥ IN() ANY: ڸ ϴ ϳ TRUE WHERE ÷|ǥ ANY() ALL: ڸ TRUE WHERE ÷|ǥ ANY() **SMITH ALLEN μ ٹϴ ȸ 1. : ΰ 1-1] SMITH, ALLEN μ μȣ Ȯϴ SELECT deptno FROM emp WHERE ename IN ('SMITH', 'ALLEN'); 1-2] 1-1] μȣ IN ش μ ϴ ȸ SELECT deptno FROM emp WHERE deptno IN(20, 30); ==> ̿ϸ ϳ SQL డ SELECT deptno FROM emp WHERE deptno IN (SELECT deptno FROM emp WHERE ename IN ('SMITH', 'ALLEN')); sub 3] SELECT * FROM emp WHERE deptno IN (SELECT deptno FROM emp WHERE ename IN('SMITH', 'WARD')); **ANY, ALL SMITH(800) WARD(1250) ޿ ƹ ޿ ޴ ȸ ==> sal < 1250 SELECT * FROM emp WHERE sal < ANY(SELECT sal FROM emp WHERE ename IN ('SMITH', 'WARD')); SMITH(800) WARD(1250) ޿ ޿ ޴ ȸ ==> sal > 1250 SELECT * FROM emp WHERE sal > ALL(SELECT sal FROM emp WHERE ename IN ('SMITH', 'WARD')); IN ҼӺμ 20, Ȥ 30 WHERE deptno IN(20,30) ҼӺμ 20, Ȥ 30 ʴ WHERE deptno NOT IN(20,30) NOT IN ڸ NULL ִ ΰ ߿ ==> NULL ۵ Ʒ ȸϴ  ǹΰ? ޴ ƴ NULL SELECT * FROM emp WHERE empno NOT IN (SELECT mgr FROM emp WHERE mgr IS NOT NULL); NULLó Լ ʴ ġȯ SELECT * FROM emp WHERE empno NOT IN (SELECT NVL(mgr, -1) FROM emp); ÷ ϴ ==> ÷ ϴ **PAIRWISE () ==> ÿ ϴ !! SELECT ename, mgr, deptno FROM emp WHERE empno IN (7499, 7782); -- IN ȿ ϳ ͵ ȸ 7499, 7782 ( μ, Ŵ) ȸ Ŵ 7698 ̸鼭 ҼӺμ 30 Ŵ 7839 ̸鼭 ҼӺμ 10 ̰Ŵ (7698, 10) (7839, 30) mgr ÷ deptno ÷ (mgr, deptno) (7698, 10) (7698, 30) (7839, 10) (7839, 30); SELECT * FROM emp WHERE mgr IN (7698, 7839) AND deptno IN (10, 30); PAIRWISE ( Ѱ ) SELECT * FROM emp WHERE (mgr, deptno) IN (SELECT mgr, deptno FROM emp WHERE empno IN(7499, 7782)); -ġ SELECT - Į FROM - ζ WHERE - - ȯϴ , ÷ ÷(Į ÷ ϴ) ÷ ÷( ) ÷ Į SELCT ǥǴ ÷ ϴ ϳ ÷ó ν; Į 밡 ϳ ϳ ÷ SELECT SYSDATE FROM dual; SELECT 'X', (SELECT SYSDATE FROM dual) FROM dual; Į ϳ , ϳ ÷ ȯ ؾ Ѵ * ϳ ÷ 2 SELECT 'X', (SELECT empno, ename FROM emp WHERE ename = 'SMITH') FROM dual; * ϳ ÷ ϴ Į ==> SELECT 'X', (SELECT empno, ename FROM emp) FROM dual; emp ̺ ش Ҽ μ ̸ ==> ׷ Ȱ Ư μ μ ̸ ȸϴ SELECT dname FROM dept WHERE deptno = 10; SELECT empno, ename, e.deptno, dname FROM emp e , dept d WHERE Į SELECT empno, ename, dept.deptno, dname FROM emp, dept WHERE emp.deptno = dept.deptno; Į SELECT empno, ename, emp.deptno, (SELECT dname FROM dept WHERE deptno = emp.deptno) --, μ̸ FROM emp; --ȣ |---------------------------------------------| - ÷ ϴ ο ȣ (corelated sub query) . Ǿ ϴ ȣ (non-corelated sub query) .main ̺ ȸ ְ sub ̺ ȸ ִ ==> Ŭ Ǵ ɻ ޿ ޿ ޴ ȸϴ ۼϼ ( ̿) SELECT * FROM emp WHERE sal > (SELECT AVG(sal) FROM emp); غ , ȣ ΰ? ȣ ΰ? ȣ ̴ ֳĸ ʾƼ μ ޿ պ ޿ ޴ ü ޿ ==> μ ޿ Ưμ(10) ޿ ϴ SQL SELECT AVG(sal) FROM emp WHERE deptno = 10; SELECT * FROM emp e WHERE sal > (SELECT AVG(sal) FROM emp WHERE deptno = e.deptno); SELECT * FROM dept; INSERT INTO dept VALUES (99, 'ddit', 'daejeon'); ִ° emp ̺ ϵ 10, 20, 30 μ Ҽ Ǿ Ҽӵ μ: 40,99 SELECT * FROM dept WHERE deptno NOT IN (10,20,30); SELECT * FROM dept WHERE deptno IN (40,99); SELECT * FROM dept WHERE deptno NOT IN(SELECT deptno FROM emp WHERE deptno); ̿Ͽ INڸ ġϴ ִ ־ () WHERE deptno IN (10,10,10); WHERE deptno = 10, OR deptno = 10, OR deptno = 10; sub 5] SELECT c.pid, p.pnm FROM cycle c, product p WHERE c.pid = p.pid and c.cid=1 NOT IN (SELECT pnm FROM product); SELECT * FROM product WHERE pid NOT IN (SELECT pid FROM cycle WHERE cid = 1); SELECT p.pid, p.pnm FROM product p WHERE cid = 1 NOT IN (SELECT p.pid, pnm FROM cycle, product); sub 6] SELECT * FROM cycle WHERE cid = 1 AND pid IN (SELECT pid FROM cycle WHERE cid = 2); sub 7] *** ̿ !!!÷ տ Ī ߺٿ!!! SELECT c.cid, cnm, cy.pid, pnm, day, cnt FROM customer c, cycle cy, product p WHERE c.cid = cy.cid AND cy.pid = p.pid AND c.cid = 1 AND cy.pid IN (SELECT pid FROM cycle WHERE cid = 2); ***Į ̿ - 6 ȴ (Ʈ ȣ) -- ̿ϴ° ȣϴ ̴. SELECT cid, (SELECT cnm FROM customer WHERE cid = cycle.cid) cnm, pid, (SELECT pnm FROM product WHERE pid = cycle.pid) pnm, day, cnt FROM cycle WHERE cid = 1 AND pid IN (SELECT pid FROM cycle WHERE cid = 2); select pnm from product where cid = cycle.cid;
Java
UTF-8
3,298
2.71875
3
[]
no_license
package svkreml.challange8; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Hex; import svkreml.FileManager; import svkreml.challenge1.HexBase64Converter; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import java.io.File; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Security; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class AESDetector { public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException { Security.addProvider(new BouncyCastleProvider()); Cipher cipher = Cipher.getInstance("AES"); byte[] keyBytes = "YELLOW SUBMARINE".getBytes(); String algorithm = "RawBytes"; SecretKeySpec key = new SecretKeySpec(keyBytes, algorithm); // cipher.init(Cipher.ENCRYPT_MODE, key); // byte[] plainText = "abcdefghijklmnopqrstuvwxyz".getBytes("UTF-8"); // byte[] cipherText = cipher.doFinal(plainText); cipher.init(Cipher.DECRYPT_MODE, key); byte[] bytes = FileManager.read(new File("Set1\\src\\main\\resources\\" + "svkreml\\challange8\\8.txt")); String[] lines = new String(bytes).split("\n"); ArrayList<byte[]> byteLines = new ArrayList<>(); for (String line : lines) { byteLines.add(HexBase64Converter.hexToBytes(line)); } // todo https://thmsdnnr.com/tutorials/javascript/cryptopals/2017/09/22/cryptopals-set1-challenge-8-detecting-aes-in-ecb-mode.html for (int i = 0; i < byteLines.size(); i++) { System.out.println("----------------------"); byte[] byteLine = byteLines.get(i); Set<SetBytes> blocks = new HashSet<>(); for (int j = 0; j < byteLine.length; j+=16) { byte[] copyOfRange = Arrays.copyOfRange(byteLine, j, j + 16); blocks.add(new SetBytes(copyOfRange)); System.out.println(Hex.toHexString(copyOfRange)); } System.out.println(String.format("%6s, %4d", i, blocks.size())); /* try { System.out.println(i + "; " + byteLine.length); byte[] cipherText = cipher.doFinal(byteLine); System.out.println(i + "; " + new String(cipherText)); } catch (IllegalBlockSizeException | BadPaddingException e) { System.out.println(i + "; " + e.getMessage()); }*/ } } } class SetBytes{ byte[] bytes; public SetBytes(byte[] bytes) { this.bytes = bytes; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SetBytes setBytes = (SetBytes) o; return Arrays.equals(bytes, setBytes.bytes); } @Override public int hashCode() { return Arrays.hashCode(bytes); } }
TypeScript
UTF-8
2,685
2.984375
3
[ "MIT" ]
permissive
/* * Extra rules for Eslint * * https://www.npmjs.com/package/eslint-plugin-more */ export default { plugins: ["more"], rules: { /* * Prohibits an empty line at the beggining of a class body * * https://github.com/WebbyLab/eslint-plugin-more/blob/HEAD/docs/classbody-starts-with-newline.md */ "more/classbody-starts-with-newline": ["error", "always"], /* * Forces the use of native methods instead of lodash/underscore * * https://github.com/WebbyLab/eslint-plugin-more/blob/HEAD/docs/force-native-methods.md */ "more/force-native-methods": "error", /* * Prohibits the use of 'For loop' with ++ or += * * https://github.com/WebbyLab/eslint-plugin-more/blob/HEAD/docs/no-c-like-loops.md */ "more/no-c-like-loops": "error", /* * Prohibits the duplication of long chains like this.props.user.name * * https://github.com/WebbyLab/eslint-plugin-more/blob/HEAD/docs/no-duplicated-chains.md */ "more/no-duplicated-chains": "error", /* * Prohibits using Array.prototype.filter to find one element and asks to use 'find' instead. * * https://github.com/WebbyLab/eslint-plugin-more/blob/HEAD/docs/no-filter-instead-of-find.md */ "more/no-filter-instead-of-find": "error", /* * Prohibits the use of variables that end in numerics. * * https://github.com/WebbyLab/eslint-plugin-more/blob/HEAD/docs/no-numeric-endings-for-variables.md */ "more/no-numeric-endings-for-variables": "error", /* * Forces the use of async / await instead of then * * https://github.com/WebbyLab/eslint-plugin-more/blob/HEAD/docs/no-then.md */ "more/no-then": "error", /* * Prohibits the use of array.map without variable or property * * https://github.com/WebbyLab/eslint-plugin-more/blob/HEAD/docs/no-void-map.md */ "more/no-void-map": "error", /* * Prohibits the usage of window global * * Off because we need to use window * * https://github.com/WebbyLab/eslint-plugin-more/blob/HEAD/docs/no-window.md */ "more/no-window": "off", /* * Prohibits the use of comparison array.indexOf() == -1 and ask to use 'includes' instead * * https://github.com/WebbyLab/eslint-plugin-more/blob/HEAD/docs/prefer-includes.md */ "more/prefer-includes": "error" } };
Markdown
UTF-8
673
2.65625
3
[]
no_license
# Vika 14, 22.–28. nóvember 2021 **Þessi vikuáætlun hefur ekki verið uppfærð, hér er aðeins afrit frá [vefforritun 1, 2020](https://github.com/vefforritun/vef1-2020).** ## Fyrirlestrar [Fyrirlestur 13.1: HTML upprifjun](13.1.html.md), [vídeó](https://youtu.be/IEwV6h2K_Ww) [Fyrirlestur 13.2: CSS upprifjun](13.2.css.md), [vídeó](https://youtu.be/k5EZ9NYPQAA) [Fyrirlestur 13.3: Tæki og tól upprifjun](13.4.tools.md), [vídeó](https://youtu.be/yof2DU1kwQI) [Fyrirlestur 13.4: JavaScript upprifjun](13.3.javascript.md), [vídeó](https://youtu.be/Paj0JsYcqOY) [Fyrirlestur 13.5: Lokapróf](13.5.lokaprof.md), [vídeó](https://youtu.be/8AO-JrjhRhw)
Markdown
UTF-8
2,139
2.84375
3
[]
no_license
### Hi there 👋 <!-- **najamsk/najamsk** is a ✨ _special_ ✨ repository because its `README.md` (this file) appears on your GitHub profile. Here are some ideas to get you started: - 🔭 I’m currently working on ... - 🌱 I’m currently learning ... - 👯 I’m looking to collaborate on ... - 🤔 I’m looking for help with ... - 💬 Ask me about ... - 📫 How to reach me: ... - 😄 Pronouns: ... - ⚡ Fun fact: ... --> - 🔭 I’m currently working on Golang, GraphQL and GRPC - 🌱 I’m currently exploring event driven architecture, kafka, redis, Kubernetes and service mesh. - 👯 I’m looking to collaborate on Golang and microservices - 🤔 I’m looking for help with kubernetes and different cloud providers like GCP and AWS - 💬 Ask me about golang, front-end, graphQL - 📫 How to reach me: twitter: [@najamsikander](https://twitter.com/najamsikander) - ⚡ Fun fact: Like reading books, video games, humor and tech. I am deeply passionate about technology and have always been driven to apply my knowledge and skills to real-world applications. After completing my studies in computer science, I began my career as a web developer, focusing on both front-end and back-end technologies. I am constantly seeking ways to improve my craft and stay current with the latest developments in the field. I am also fascinated by the diverse approaches that people in various roles, such as developers, product owners, designers, and managers, take to solve problems and am always looking for opportunities to learn from them. I am excited about the prospect of creating new work opportunities and further advancing my skills in the tech industry. Looking forward to creating work opportunities and further enhancement of my skills. - Status: Full stack Web Engineer, Product Manager. - Fields: Project Management, Software Development, Consulting. - Web Technologies: Golang, MQTT, Web Sockets, WebRTC ,Revel, Gin-Gonic, Node.js. - DataBases: RethinkDB, CockroachDB, Cassandra, Sql Server, Oracle. - Infrastructure: Docker, Kubernetes, Kafka, Redis, GCP, Gitlab, Teamcity, Octopus Deploy, Nginx, IIS
Java
UTF-8
611
2.265625
2
[]
no_license
package com.abstraites.exercice; public class Test { public static void main(String[] args) { AgentAccueil aa = new AgentAccueil("Agent"); VeilleurDeNuit vn = new VeilleurDeNuit("Veilleur"); Administratif admin = new Administratif("administratif"); Resident res = new Resident("Georges", "go@pop.fr", 0); aa.negocierContrat(); vn.demanderConge(9); admin.declarerHTravail(35); aa.donnerAvertissement(res); System.out.println("---------------"); admin.verserSalaire(vn, 2100f); System.out.println(res); aa.affecterChambre(res, 102); System.out.println(res); vn.faireTour(); } }
Python
UTF-8
8,192
2.859375
3
[]
no_license
import tensorflow as tf import pylab import numpy import sys import wave from scipy.stats import mode from collections import deque from PIL import Image, ImageChops from ConfigParser import ConfigParser """ This script will be given a file and will classify audio frame-to-frame. Usage: TODO """ def read_and_predict(model_path, wav_path, frame_length, deque_size): # set up variables for model to be read into tensor_size, num_classes, classnames = get_config_data(model_path) x = tf.placeholder(tf.float32, [None, tensor_size]) W = tf.Variable(tf.zeros([tensor_size, num_classes]), name="weights") b = tf.Variable(tf.zeros([num_classes]), name="bias") y = tf.nn.softmax(tf.matmul(x, W) + b) prediction = tf.argmax(y,1) sess = tf.Session() #restore trained & saved tensorflow model saver = tf.train.Saver() saver.restore(sess, model_path) # information about the wav file wav = wave.open(wav_path, 'r') num_frames = wav.getnframes() sample_rate = wav.getframerate() num_windows = num_frames/frame_length # variables for analysis predictions = deque([], deque_size) time_per_class = dict((classname, 0) for classname in classnames) predictions_this_sec = [] samples_remaining_this_sec = sample_rate frames_examined_this_sec = 0 crt_sec = 0 seconds_ignored = 0 print crt_sec print 'Starting classification... Examining ' + str(num_windows) + ' windows.' while (wav.tell() + frame_length) < num_frames: #print 'current second: ' + str(crt_sec) + ', wav.tell: ' + str(wav.tell()) + ', samples remaining: ' + str(samples_remaining_this_sec) """ if get_second(sample_rate, wav.tell()) != crt_sec: seconds_ignored += 1 predictions_this_sec = [] samples_remaining_this_sec = sample_rate frames_examined_this_sec = 0 crt_sec = get_second(sample_rate, wav.tell()) print crt_sec """ frames = wav.readframes(frame_length) sound_info = pylab.fromstring(frames, 'Int16') amps = numpy.absolute(sound_info) # samples_remaining_this_sec -= frame_length # ignore frames with low amplitudes if (amps.mean() < 1000): continue # print 'DING!' # frames_examined_this_sec += 1 flat_spectro = create_flat_spectrogram(sound_info, frame_length, sample_rate) predicted = prediction.eval(session=sess, feed_dict={x: flat_spectro}) predictions.append(predicted[0]) #predictions_this_sec.append(predicted[0]) #if len(predictions) > deque_size/2 and True == False: if len(predictions) > deque_size/2: m = mode(predictions) print '------------------------------------------------' print get_crt_time_string(sample_rate, wav.tell()) print 'mode of prediction list: ' + classnames[m.mode[0]] print 'predictions list: ' + str(predictions) """ # second-to-second logic if frames_examined_this_sec > 2 and float(mode(predictions_this_sec).count[0]) / float(len(predictions_this_sec)) >= 0.8: time_per_class[classnames[mode(predictions_this_sec).mode[0]]] += 1 print '----------------------------------------' print 'second elapsed: ' + str(crt_sec) print time_per_class # print stats and exit if not enough samples left for another frame if wav.tell() + samples_remaining_this_sec >= num_frames: output_stats(crt_sec, seconds_ignored, time_per_class) return if crt_sec > 0 and crt_sec % 60 == 0: m = mode(predictions) print '=============================================' print get_readable_time(crt_sec) + ', currently speaking: ' + classnames[m.mode[0]] prettyprint_time_dict(time_per_class) print '=============================================' # print time_per_class wav.setpos(wav.tell() + samples_remaining_this_sec) predictions_this_sec = [] samples_remaining_this_sec = sample_rate frames_examined_this_sec = 0 crt_sec += 1 print crt_sec continue """ # output_stats(crt_sec, seconds_ignored, time_per_class) return def get_config_data(model_path): config = ConfigParser() config.read(model_path + '-config.ini') tensor_size = int(config.get('Sizes', 'tensor_size')) num_classes = int(config.get('Sizes', 'num_classes')) classnames_str = config.get('Classnames', 'classnames') classnames = classnames_str.split(',') return tensor_size, num_classes, classnames def create_flat_spectrogram(sound_info, frame_length, sample_rate): pylab.figure(num=None, figsize=(19, 12)) pylab.axis('off') pylab.specgram(sound_info, NFFT=frame_length, Fs=sample_rate) pylab.savefig('crt.png') pylab.close() spectro = Image.open('crt.png') spectro = squarify(spectro, 256) flat_spectro = flatten(spectro) return flat_spectro def flatten(im): data = numpy.array(im) flat = data.flatten() # tensor placeholder will expect floats flat = flat.astype(numpy.float32) flat = numpy.multiply(flat, 1.0 / 255.0) flat_in_array = [] flat_in_array.append(flat) return flat_in_array def squarify(im, image_size): bg = Image.new(im.mode, im.size, im.getpixel((0,0))) diff = ImageChops.difference(im, bg) diff = ImageChops.add(diff, diff, 2.0, -100) bbox = diff.getbbox() if bbox: im = im.crop(bbox) im = im.resize((image_size, image_size)) return im def get_crt_time_string(sample_rate, current_pos): if (current_pos % sample_rate == 0): milli = 0 else: milli = int((1.0 / (float(sample_rate) / float(current_pos % sample_rate))) * 100.0) sec = (current_pos / sample_rate) % 60 minute = ((current_pos / sample_rate) - sec) / 60 if (milli < 10): milli_str = '00' + str(milli) elif (milli < 100): milli_str = '0' + str(milli) else: milli_str = str(milli) sec_str = '0' + str(sec) if sec < 10 else str(sec) minute_str = '0' + str(minute) if minute < 10 else str(minute) return minute_str + ':' + sec_str + '.' + milli_str def get_second(sample_rate, current_pos): return current_pos / sample_rate def update_sec_dict(sec_dict, second): if second not in sec_dict: sec_dict[second] = 1 return sec_dict[second] += 1 return def output_stats(crt_sec, seconds_ignored, time_per_class): print '======================STATS=======================' print 'Total time of recording ' + get_readable_time(crt_sec) print '--------------------------------------------------' print 'Total time ignored ' + get_readable_time(seconds_ignored) print '--------------------------------------------------' prettyprint_time_dict(time_per_class) print '==================================================' def get_readable_time(total_seconds): seconds = '0' + str(total_seconds % 60) if total_seconds % 60 < 10 else str(total_seconds % 60) total_minutes = total_seconds / 60 minutes = '0' + str(total_minutes % 60) if total_minutes % 60 < 10 else str(total_minutes % 60) total_hours = total_minutes / 60 hours = '0' + str(total_hours % 24) if total_hours % 24 < 10 else str(total_hours % 24) return str(hours) + ':' + str(minutes) + ':' + str(seconds) def prettyprint_time_dict(time_dict): for key, value in time_dict.iteritems(): print '------------------------------------------------' print key + ' spoke for ' + get_readable_time(value) if __name__ == "__main__": if len(sys.argv) < 3: print "Incorrect usage, please see top of file." exit() model_path = sys.argv[1] wav_path = sys.argv[2] frame_length = int(sys.argv[3]) deque_size = int(sys.argv[4]) # frame_length = sys.argv[3] read_and_predict(model_path, wav_path, frame_length, deque_size)
Python
UTF-8
1,387
2.75
3
[]
no_license
from dwave.system.samplers import DWaveSampler from dwave.system.composites import EmbeddingComposite from itertools import combinations Sampler = EmbeddingComposite(DWaveSampler()) #Traveling Salesman problem distance = [4,6,5,1,4,7] E = len(distance) N = int((1+(1+E*8)**0.5)/2) #calculate based on edges cities = list(range(N)) gamma = 15.0 chainstrength = 10 numruns = 100 edges = list(combinations(cities,2)) print (edges) #x_ij=1 if city i is in the jth stop #path to minimize, for each pair (from stop 1 to stop2) : sum_ij(x_i,1*xj,2*d_ij)... sum for all pairs->d_ij #constraint: each city is visited only once: #gamma*(sum_ij x_ij -1)^2= gamma*sum_ij (x_ij^2)-gamma*2*sum_ij(x_ij)+sum_ij 1-> gamma -2gamma= -gamma #constraint: only one visit in each stop: #->-gamma Q = {(a,b): 0 for a in range(E) for b in range(E)} #init every pair to zero for i in range(E): Q[(i,i)] = distance[i]-(6*gamma) for i in range(E): for j in range((i+1), E): row_edges = edges[i] col_edges = edges[j] if row_edges[0] in col_edges or row_edges[1] in col_edges: Q[(i,j)] = 2*gamma print(Q) Response = EmbeddingComposite(DWaveSampler()).sample_qubo(Q, chain_strength=chainstrength, num_reads=numruns) print(Response) for index in range(len(Response.record.sample)): print("Sample:", Response.record.sample[index], "\tEnergy: ", Response.record.energy[index])
C++
UTF-8
939
3.125
3
[]
no_license
#include "ThreadSafeQueue.h" #include<iostream> #include <syncstream> #include<string> int main() { using namespace std::this_thread; using namespace std::chrono_literals; TSQ::ThreadsafeQueue<int> queue { }; std::thread prod1 { [&] { sleep_for(10ms); // demonstration only for (int j = 0; j < 10; ++j) { queue.push(j); yield(); sleep_for(1ms); } } }; std::thread prod2 { [&] { sleep_for(9ms); // demonstration only for (int i = 0; i < 10; ++i) { queue.push(i * 11); yield(); sleep_for(1ms); } } }; std::thread cons { [&] { sleep_for(15ms); // demonstration only do { std::osyncstream { std::cout } << "consume: " << queue.pop() << '\n'; yield(); } while (!queue.empty()); } }; prod1.join(), prod2.join(), cons.join(); std::cout << "non-processed elements:\n"; while (!queue.empty()) { std::cout << queue.pop() << '\n'; } }
PHP
UTF-8
2,119
2.71875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; use yii\base\Model; class Organization extends Model { private static $arrStructure = array( '西北农林科技大学' => array( '信息工程学院', '农学院', '植保学院', '理学院', '生命科学院', ), '校外用户' => array(), ); private static $arrMap = array( 1 => '西北农林科技大学', 10 => '信息工程学院', 11 => '农学院', 12 => '植保学院', 13 => '理学院', 14 => '生命科学院', 2 => '校外用户', ); public static function _getOrganizationStructure() { return self::$arrStructure; } public static function _getOrganizationMap() { return self::$arrMap; } public static function _getOrganizationByIds($arrId) { $arrRet = array(); foreach ($arrId as $intId) { $arrRet[$intId] = self::_getOrganizationName($intId); } return $arrRet; } private static function _getOrganizationName($intId) { $arrMap = array( 1 => '西北农林科技大学', 2 => '校外用户', 10 => '信息工程学院', 11 => '农学院', 12 => '植保学院', 13 => '理学院', 14 => '生命科学院', ); if (!isset($arrMap[$intId])){ return '未知'; } $strName = self::$arrMap[$intId]; $strOrganization = ''; foreach (self::$arrStructure as $strSchool => $tmpArr) { if ($strSchool == $strName){ $strOrganization = $strSchool; } if ($strSchool != $strName && is_array($tmpArr)){ foreach ($tmpArr as $item){ if ($item == $strName){ $strOrganization = $strSchool . '--' .$item; break 2; } } } } return $strOrganization; } }
Markdown
UTF-8
16,198
2.90625
3
[ "Apache-2.0" ]
permissive
## FID查询 ### 示例功能 本示例在二维视图中加载显示一个地图文档服务数据,坐标系为`Web墨卡托`,使用`FID查询`MapGIS矢量图层中地图要素相关的信息。 ### 示例实现 本示例需要使用include-mapboxgl-local.js开发库实现,通过关键接口`Zondy.Service.QueryLayerFeature()`实现MapGIS矢量图层的`FID查询`功能。 > 开发库使用请参见**首页**-**概述**-**原生JS调用**内容 > MapGIS IGServer发布地图文档服务请参见`MapGIS IGServer`目录下的`地图-EPSG3857`示例的说明部分 ### 实现步骤 1. 引用开发库,本示例通过本地离线include-mapboxgl-local.js脚本引入开发库; 2. 创建`id="map"`的div作为地图容器,并设置其样式; 3. 创建地图对象,设置地图的必要参数,如地图div容器、缩放层级、中心点等,以及在地图中添加地图文档图层,具体操作参考`MapGIS IGServer`目录下的`地图-EPSG3857`示例; 4. 创建**矢量图层查询服务对象**,并使用该对象执行查询操作; * 设置查询包含的信息结构 ```javascript //初始化查询结构对象,设置查询结构包含几何信息 var queryStruct = new Zondy.Service.QueryFeatureStruct({ IncludeGeometry: true,//是否包含几何图形信息 IncludeAttribute: true,//是否包含属性信息 IncludeWebGraphic: false//是否包含图形显示参数 }); ``` * 设置查询参数 ```javascript //实例化查询参数对象 var queryParam = new Zondy.Service.QueryByLayerParameter("gdbp://MapGisLocal/ClientTheme/ds/epsg4326/sfcls/湖北省市级区划2", { objectIds: "4,5", pageIndex: 0, recordNumber: 50, struct: queryStruct, }); ``` * 创建矢量图层查询服务对象,执行查询操作 ```javascript //实例化地图文档查询服务对象 var queryService = new Zondy.Service.QueryLayerFeature(queryParam, { //IP地址 ip: "develop.smaryun.com", //端口号 port: "6163" }); //执行查询操作,querySuccess为成功回调,queryError为失败回调 queryService.query(querySuccess, queryError); ``` 5. 查询结果展示,在查询成功的回调函数中将查询结果格式化为<a href="https://geojson.org/" target="_blank">GeoJSON</a>格式,以图层的方式添加到地图中; ```javascript var feature = { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [finaldots] } } features.push(feature); //用geojson创建一个多边形 var geometryPolygon = { "type": "FeatureCollection", "features": features }; var source = { "type": "geojson", "data": geometryPolygon }; map.addLayer({ //此id可随意设置,但是要唯一 "id": "highlayer", //指定类型为fill(填充区域) "type": "fill", //设置数据来源 "source": source, //设置绘制参数 "paint": { //设置填充颜色 "fill-color": '#7FFF00', //设置透明度 "fill-opacity": 0.5, "fill-outline-color": '#FFA500' } }); ``` ### 关键接口 #### 1.【指定查询获取的要素包含的信息结构】QueryFeatureStruct ##### `Zondy.Service.QueryFeatureStruct(opt_options)`:查询要素信息结构的构造函数 通过这个接口指定查询获取的要素包含的信息结构,该信息结构由MapGIS矢量要素的几何、空间、图形组成 > `QueryFeatureStruct`主要参数 | 参数名 | 类型 | 说明 | | ----------- | ------ | ------------------------------------------------------------ | | opt_options | Object | (可选)设置其他属性键值对对象。对象中的属性来自本类的属性。例如:{key1:value1, key2:value2 …} | > `opt_options`属性参数说明 | 属性 | 类型 | 默认值 | 描述 | | ----------------- | ------- | ------ | -------------------- | | IncludeAttribute | Boolean | TRUE | 是否包含属性值 | | IncludeGeometry | Boolean | FALSE | 是否包含几何图形信息 | | IncludeWebGraphic | Boolean | FALSE | 颜色的R值 | #### 2.【基于矢量图层的查询参数】QueryByLayerParameter ##### `Zondy.Service.QueryByLayerParameter(gdbp, opt_options)`:矢量图层查询参数的构造函数 创建矢量图层查询参数,参数中包含几何描述、查询SQL语句、FID(OID)等查询条件,通过这些条件查询MapGIS中矢量图层的信息 > `QueryByLayerParameter`主要参数 | 参数名 | 类型 | 描述 | | ----------- | ------ | ------------------------------------------------------------ | | gdbp | String | 矢量图层URL地址信息(包括源要素类存储路径与名称),用户根据语法设置URL地址,或在数据库中图层节点上右击选择“复制URL”获得。 | | opt_options | Object | (可选)设置其他属性键值对对象。对象中的属性来自本类的属性和 <a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.QueryParameter.html" target="_blank">Zondy.Service.QueryParameter</a> 类、 <a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.QueryParameterBase.html" target="_blank">Zondy.Service.QueryParameterBase </a>类的属性。例如:{key1: value1, key2 :value2 …} | > `opt_options`属性参数说明(来自<a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.QueryParameterBase.html" target="_blank">Zondy.Service.QueryParameterBase</a>) | 属性 | 类型 | 默认值 | 描述 | | ------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | | geometry | <a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Object.Tangram.html" target="_blank">Zondy.Object.Tangram</a> | Null | 用于查询的几何描述 | | where | String | Null | 条件查询的SQL语句,如果为空,则表示为单一的几何查询;如果取值,表示为几何和条件混合查询。当SQL语句永为真时,如“1>0”,表示查询全部。 | | rule | <a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.QueryFeatureRule.html" target="_blank">Zondy.Service.<br/>QueryFeatureRule</a> | Null | 几何查询的规则 | | objectIds | String | Null | 需要查询的要素OID号,多个间用‘,’分隔,如”OID1,OID2…”。如果此参数有值,查询将默认转化为使用要素ID查询,而忽略条件查询。 | | pageIndex | Number | 0 | 分页号 | | recordNumber | Number | 20 | 每页记录数 | | resultFormat | String | json | 查询结果的序列化形式,取值为:json\|\|xml\|kml\|gml\|georss,对于xml,kml,gml或者georss格式的类xml类型将以text文本返回,如需要可调用$.parseXML(text)得到其xml形式。 | | struct | <a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.QueryFeatureStruct.html" target="_blank">Zondy.Service.<br/>QueryFeatureStruct</a> | Null | 指定查询返回结果所包含的要素信息 | | orderField | String | Null | 指定查询返回结果的排序字段,只有当isAsc=true时才有效。 | | isAsc | Boolean | FALSE | 是否升序排列,与orderField配合使用。 | | guid | String | Null | 地图缓存唯一标识,一般情况下无需赋值。 | | cursorType | String | Null | 光标类型 | | fields | String | Null | 过滤字段 | | dataService | String | Null | 查询的地图文档的名称(主要用于时空云) | | layerIdxs | Number | Null | 图层索引号,默认从0开始。 | #### 3.【矢量图层的查询服务】QueryLayerFeature ##### (1)`Zondy.Service.QueryLayerFeature(queryParam, opt_options)`:矢量图层查询服务的构造函数 创建矢量图层的查询服务,主要用于查询MapGIS中矢量图层的信息 > `QueryLayerFeature`主要参数 | 参数名 | 类型 | 描述 | | ----------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | queryParam | <a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.QueryParameter.html" target="_blank">Zondy.Object.QueryParameter</a> | 查询参数信息 | | opt_options | Object | (可选)设置其他属性键值对对象。对象中的属性来自本类的属性和 <a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.QueryServiceBase.html" target="_blank">Zondy.Service.QueryServiceBase</a> 类、 <a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.HttpRequest.html" target="_blank">Zondy.Service.HttpRequest</a> 类的属性。例如:{key1: value1, key2 :value2 …} | > `opt_options`属性参数说明(来自<a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.QueryServiceBase.html" target="_blank">Zondy.Service.QueryServiceBase</a>) | 属性 | 类型 | 默认值 | 描述 | | -------------- | ------------------------------------------------------------ | ------ | ------------------------------------- | | resultCallBack | String | Null | 查询结果返回格式,取值为:json\|xml。 | | queryParam | <a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.QueryParameter.html" target="_blank">Zondy.Service.QueryParameter</a> | Null | 基于矢量地图文档的查询参数 | | requestType | String | GET | 请求方式,取值为:GET\|POST。 | > `opt_options`属性参数说明(来自<a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.HttpRequest.html" target="_blank">Zondy.Service.HttpRequest</a>) | 属性 | 类型 | 默认值 | 描述 | | ------------ | ------ | --------- | ------------------------------------------------------------ | | ip | String | localhost | 服务器ip地址,如本地默认为“127.0.0.1”或“localhost” | | port | String | 6163 | 服务器端口号 | | ProxyHost | String | Null | 使用代理的地址 | | resultFormat | String | json | 请求成功时回调结果格式,取值为'json','xml','kml','gml',georss',默认为‘json’。对于resultFormat参数为xml,kml,gml或者georss格式,将以text文本返回,如需要可以调用$.parseXML(text)得到其xml格式。 | ##### (2)query(onSuccess,onError,requestType,options):矢量图层查询服务执行查询操作的函数 > `query`主要参数(来自<a href="http://develop.smaryun.com:8899/docs/mapboxgl/Zondy.Service.QueryServiceBase.html" target="_blank">Zondy.Service.QueryServiceBase</a>) | 参数名 | 类型 | 说明 | | ----------- | -------- | ------------------------------------ | | onSuccess | Function | 成功回调函数 | | onError | Function | 失败回调函数 | | requestType | String | 请求方式,取值为:GET\|POST | | options | Object | (可选)设置其他扩展ajax请求补充参数 | #### 4.【MapBox样式规范】source 数据源表明地图应显示哪些数据。 使用“type”属性指定数据源的类型,该属性必须是`vector`,`raster`,`raster-dem`,`geojson`,`image`,`video`之一。 添加数据源不足以使数据显示在地图上,因为数据源不包含颜色或宽度等样式细节。 图层通过指定数据源及设置相关的样式进行可视化表达。 这样就可以用不同的方式对同一数据源进行样式设置,例如在高速公路图层中区分不同类型的道路。 示例中使用`geojson`类型数据源,数据必须通过`data`属性提供,其值可以是URL或内联`geojson`。 内联geojson: ```json "geojson-marker": { "type": "geojson", "data": { "type": "Feature", "geometry": { "type": "Point", "coordinates": [-77.0323, 38.9131] }, "properties": { "title": "Mapbox DC", "marker-symbol": "monument" } } } ``` 通过URL方式加载geojson: ```json "geojson-lines": { "type": "geojson", "data": "./lines.geojson" } ``` > `geojson`类型的source属性说明 | 属性 | 类型 | 默认值 | 描述 | | -------------- | -------------- | ------ | ------------------------------------------------------------ | | data | string\|object | 无 | GeoJSON文件的URL或内联GeoJSON | | maxzoom | number | 18 | 创建矢量切片的最大缩放级别(更高意味着在高缩放级别更高的细节) | | attribution | string | 无 | 包含向用户显示地图时要显示的属性 | | buffer | number | 128 | 每侧的瓦片缓冲区的大小。0不产生缓冲区,512会生成与瓦片本身一样宽的缓冲区。较大的值会在拼贴边缘附近产生较少的渲染瑕疵,并且性能较慢 | | tolerance | number | 0.375 | Douglas-Peucker简化公差(更高意味着更简单的几何形状和更快的性能) | | cluster | boolean | 512 | 如果数据是点要素的集合,则将此设置为true会将点数据按半径聚合分组 | | clusterRadius | enum | 50 | 如果启用了聚合,该参数为每个聚合结果的半径,值大于等于0。512表示半径等于瓦片的宽度 | | clusterMaxZoom | string | 无 | 如果启用了聚合,则最大缩放以聚集点。默认为小于maxzoom的一个缩放(以便最后缩放功能不会聚集) | | lineMetrics | boolean | FALSE | 是否计算行距离度量。对于指定行渐变值的线图层,这是必需的 | | generateId | boolean | FALSE | 是否为geojson功能生成id。启用后,将根据feature数组中的索引自动分配feature.id属性,覆盖以前的任何值 |
Shell
UTF-8
790
3.65625
4
[]
no_license
# -*-shell-script-*- # # both ~/.bashrc and ~/.bash_profile are symbolic links to this # file. I have the same settings for login and non-login shells. # # debug # set -ux etcpath="${HOME}/etc" interactive=$(echo $- | grep -vc i) if [ $interactive -eq 0 ]; then echo "$0: Interactive session. Turning on output." fi ts-source-parts () { local files files=$(find "$1" -regextype grep -type f -iregex '.*/[0-9]\{2\}[a-z]\+$' |\ sort -df) for f in $files; do test -r "$f" && \ if [ $interactive -eq 0 ] ; then echo "$f"; fi && \ . "$f" done } sourcedir="${etcpath}/bash.d" ts-source-parts "${sourcedir}" interactivedir="${etcpath}/bash-interactive.d" if [ $interactive -eq 0 ]; then ts-source-parts "${interactivedir}" fi
Java
UTF-8
785
2.34375
2
[]
no_license
package com.video.vip.basics.exception; /** * Created by yanghongtao1 on 2019/1/8. */ public class DependencyException extends RuntimeException { private static final long serialVersionUID = 936915964862903634L; private Type type; private Throwable causeThrowable; public DependencyException(Type type, String message, Throwable e) { super(message); this.type = type; this.causeThrowable = e; } public DependencyException(Type type, String message) { this(type, message, null); } public Type type() { return type; } public Throwable causeThrowable() { return causeThrowable; } public enum Type { DEPEND_REQUEST_TYPE, DEPEND_ERROR_CODE_TYPE, NULL_RESULT_ERROR; } }
Markdown
UTF-8
818
2.734375
3
[]
no_license
# spirl-readings A collection of reading material for the [Workshop on "Structure &amp; Priors in Reinforcement Learning" (SPiRL)](https://eringrant.github.io/spirl). To contribute a reference, follow the instructions below to make a pull request. ### Pull Request Instructions 1. Find the BibTeX entry for the reference. 2. Validate the entry using https://biblatex-linter.herokuapp.com/. 3. Add the BibTeX entry to [all.bib](all.bib). 4. Add a reference to the BibTeX entry using its key to the appropriate section in [readings.md](readings.md). 5. Submit the pull request. See [this commit](https://github.com/eringrant/spirl-readings/commit/134c77bbebf67e3e34cc0a4277b4a841340b62a3) for an example. Your reference will be compiled to the website after your pull request is merged. Thank you for contributing!
JavaScript
UTF-8
5,957
2.75
3
[]
no_license
/* eslint-disable prefer-const */ /* eslint-disable no-unneeded-ternary */ /* eslint-disable react/jsx-key */ /* eslint-disable no-useless-return */ /* eslint-disable react/prop-types */ /* eslint-disable lines-between-class-members */ /* eslint-disable no-useless-constructor */ /* eslint-disable react/jsx-no-undef */ /* eslint-disable indent */ /* eslint-disable react/no-unknown-property */ import React from 'react' import ReactDOM from 'react-dom' import './style.css' import './img/close.svg' class CompleteStatus extends React.Component { constructor (props) { super(props) this.ChangeToAll = this.ChangeToAll.bind(this) this.ChangeToActive = this.ChangeToActive.bind(this) this.ChangeToCompleted = this.ChangeToCompleted.bind(this) } ChangeToAll () { this.props.StatusChosen('all') console.log(this.props) } ChangeToActive () { this.props.StatusChosen('active') console.log(this.props) } ChangeToCompleted () { this.props.StatusChosen('completed') console.log(this.props) } render () { return ( <div className="complete-status"> <button onClick={this.ChangeToAll}>All</button> <button onClick={this.ChangeToActive}>Active</button> <button onClick={this.ChangeToCompleted}>Completed</button> </div> ) } } class List extends React.Component { constructor (props) { super(props) // this.state = { items: [], text: '' } this.HandleClick = this.HandleClick.bind(this) this.ClicktoClose = this.ClicktoClose.bind(this) } HandleClick (event) { // console.log(this.props) // console.log(this.props.items) // console.log(event.target.checked) this.props.CompleteStatus(event.target.id) } ClicktoClose (event) { this.props.CloseItem(event.target.id) } render () { let items = this.props.items let newItem = [] console.log(this.props) if (this.props.status === 'completed') { console.log('completed ya') for (let i = 0; i < this.props.items.length; i++) { if (items[i].completed === true) { newItem.push(items[i]) } } console.log(items) console.log(newItem) } else if (this.props.status === 'active') { console.log('active ya') console.log(this.props.items) for (let i = 0; i < this.props.items.length; i++) { if (items[i].completed === false) { newItem.push(items[i]) } } console.log(items) console.log(newItem) } else { console.log('all ya') newItem = this.props.items console.log(newItem) } return ( <form className="to-do-list"> {newItem.map(newItem => ( <label className="to-do-item" key={newItem.id}> <span>{newItem.text}</span> <input type="checkbox" checked={newItem.completed} onChange={this.HandleClick} id={newItem.id}/> <span className="checkmark"></span> <div className="close" onClick={this.ClicktoClose} id={newItem.id}></div> </label> ))} </form> ) } } class ToDoApp extends React.Component { constructor (props) { super(props) this.state = { items: [], text: '', status: 'all', itemsSelect: [] } this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } handleChange (event) { this.setState({ text: event.target.value }) } handleSubmit (event) { console.log(this.state.text) // 如果事件可以被取消,就取消事件(即取消事件的預設行為)。不會影響事件傳遞 event.preventDefault() if (this.state.text.length === 0) { return } const newItem = { text: this.state.text, id: Date.now(), completed: false } console.log(newItem) this.setState(state => ({ items: state.items.concat(newItem), text: '' })) } CompleteStatus (id) { for (let i = 0; i < this.state.items.length; i++) { if (id === String(this.state.items[i].id)) { this.setState((prevState) => { const checkedItem = prevState.items[i] checkedItem.completed = checkedItem.completed === true ? false : true return { items: prevState.items } }) } } console.log(this.state) } CloseItem (id) { for (let i = 0; i < this.state.items.length; i++) { if (id === String(this.state.items[i].id)) { this.setState((prevState) => { const closeItem = prevState.items return closeItem.splice(i, 1) }) } } console.log(this.state) } StatusChosen (statusChosen) { console.log(statusChosen) if (statusChosen === 'active') { this.setState({ status: 'active' }, () => { console.log(this.state.status) }) } else if (statusChosen === 'completed') { this.setState({ status: 'completed' }, () => { console.log(this.state.status) }) } else { this.setState({ status: 'all' }, () => { console.log(this.state.status) }) } } render () { return ( <div className="to-dos"> <h1>To Dos</h1> <List items = {this.state.items} status = {this.state.status} CompleteStatus = {this.CompleteStatus.bind(this)} CloseItem = {this.CloseItem.bind(this)} /> <div className="content"> <input type="text" className="key-in" value={this.state.text} onChange={this.handleChange} /> <button onClick={this.handleSubmit}>Enter</button> </div> <CompleteStatus // no need to pass items & status, in case you want to check items & status value // items={this.state.items} // status={this.state.status} StatusChosen = {this.StatusChosen.bind(this)} /> </div> ) } } ReactDOM.render(<ToDoApp />, document.querySelector('#root'))
Java
UTF-8
739
2.375
2
[]
no_license
import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class SolutionTest { Solution solution = new Solution(); @Test public void test_1() throws Exception { // int s = solution.solution(new int[]{-1, 3, -4, 5, 1, -6, 2, 1}); // Assert.assertEquals(1, s); // Assert.assertEquals(0, solution.solution(new int[]{-1, 1,-1})); int ans = Solution.totalScore(new String[]{"5", "-2", "4", "Z", "X", "9", "+", "+"}, 8); Assert.assertEquals(27, ans); int ans1 = Solution.totalScore(new String[]{"1", "2","+", "Z"}, 4); Assert.assertEquals(3, ans1); } }
Java
UTF-8
524
2.15625
2
[]
no_license
package tool; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.github.cage.Cage; import com.github.cage.IGenerator; @Component public class MyCage extends Cage { public MyCage() { } @Autowired public MyCage(@Qualifier("myTokenGenerator") IGenerator<String> myTokenGenerator) { super(null, null, null, null, null, myTokenGenerator, null); } }
C++
UTF-8
603
2.71875
3
[]
no_license
#include<iostream> #include<string> using namespace std; string alp[] = { "c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z=" }; int ans; int main(void) { ios::sync_with_stdio(NULL); cin.tie(NULL); cout.tie(NULL); string str; cin >> str; ans = 0; for (int i = 0; i < str.size(); i++) { ++ans; for (int j = 0; j < 8; j++) { int size = alp[j].size(), idx; if (i + size > str.size())continue; bool flag = true; for (idx = i; idx < i + size; idx++) if (str[idx] != alp[j][idx - i])flag = false; if (flag) { i = idx - 1; break; } } } cout << ans; return 0; }
Java
UTF-8
1,141
2.046875
2
[]
no_license
package printfsm.revisitor.operations.printfsm.impl; import fsm.FinalState; import fsm.revisitor.FsmRevisitor; import printfsm.revisitor.operations.printfsm.FinalStateOperation; import printfsm.revisitor.operations.printfsm.InitialStateOperation; import printfsm.revisitor.operations.printfsm.MachineOperation; import printfsm.revisitor.operations.printfsm.StateOperation; import printfsm.revisitor.operations.printfsm.TransitionOperation; import printfsm.revisitor.operations.printfsm.impl.StateOperationImpl; @SuppressWarnings("all") public class FinalStateOperationImpl extends StateOperationImpl implements FinalStateOperation { private FinalState obj; private FsmRevisitor<? extends FinalStateOperation, ? extends InitialStateOperation, ? extends MachineOperation, ? extends StateOperation, ? extends TransitionOperation> alg; public FinalStateOperationImpl(final FinalState obj, final FsmRevisitor<? extends FinalStateOperation, ? extends InitialStateOperation, ? extends MachineOperation, ? extends StateOperation, ? extends TransitionOperation> alg) { super(obj, alg); this.obj = obj; this.alg = alg; } }
Java
UTF-8
997
2.328125
2
[]
no_license
package bg.softuni.andreys.persistence; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import bg.softuni.andreys.common.enums.CategoryType; import bg.softuni.andreys.persistence.entities.JpaCategory; import bg.softuni.andreys.persistence.repositories.CategoryRepository; @Component public class DataInitialization implements CommandLineRunner { private CategoryRepository categoryRepo; @Autowired public DataInitialization(CategoryRepository categoryRepo) { this.categoryRepo = categoryRepo; } @Override public void run(String... args) throws Exception { if (this.categoryRepo.count() == 0) { this.categoryRepo.saveAll(Set.of(new JpaCategory(CategoryType.DENIM, "Denim"), new JpaCategory(CategoryType.JACKET, "Jacket"), new JpaCategory(CategoryType.SHIRT, "Shirt"), new JpaCategory(CategoryType.SHORTS, "Shorts"))); } } }