language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 5,747 | 2.625 | 3 |
[] |
no_license
|
# EGL OrientDB CRUD Generator
Epsilon EGL demo project to generate OrientDB CRUD implementation using the Graph API
## DISCLAIMER
I am **NOT** an experienced DB programer and thus the generated code will most likely be "ugly"; incorrect separation of concerns, incorrect use of Frames and Pipes, inefficent, wrong design pattern, etc. The purpose is to ilustrate how EVL can be used to generate CRUD code for a DB, not how to write CRUD code ;). Ergo, this code (the EVL tempaltes) would probably need improvements to make it production ready.
## Requirements
You need an Eclipse IDE with EMF and Epsilon installed as minimum. The easiest way is to get one from the Epsilon website, [here](https://eclipse.org/epsilon/download/).
You need then to import the plugins in this repo to your Eclipse workspace:
File -> Import -> Existing Projects into Workspace (follow the instructions)
**Note:** I have not commited any of the generated code so after importing your projects will most likely won't compile and you will get a lot of 'The import xxx cannot be resolved' errors.
## Running the generators
We need to generate two pieces of code: the Data Model (defined by the business layer) and the DB code (used in the data layer). The Data Model code is generated using EMF's generator model.
1. Open the ExecutionTrace.genmodel (org.eclipse.epsilon.orientdb.business/model). Right click on the first element in the tree view and select: Generate Model Code. A bunch of files should have been generated in the emf-gen folder. Note that the EMF genmodel uses it's own internal generators.
2. Locate the EcoreToOrientDB_Demo.launch at the root of the org.eclipse.epsilon.orientdb.data project. Right click on it and select Run as.. > EcoreToOrientDB_Demo. You should see a *GenDone* message in the console and a bunch of pacakges and files should have been generated in the src-gen folder.
## The generated code
1. The EMF generator model generates the Data Model API. Basically, we are interested in the Interfaces generated in org.eclipse.epsilon.orientdb.business/emf-gen/org/eclipse/epsilon/orientdb/business/trace/. POJOs implementing this interfaces are intended to be used to move data between the layers. For example, the generated OrientDB code provides classes that implement these interfaces.
2. The EcoreToOrientDB_Demo launch executes the org.eclipse.epsilon.orientdb.data/src/org/eclipse/epsilon/orientdb/data/generation/EcoreToOrientDB.egx EGX Script. This script is responsible for orchestrating the different EVL scripts that generate the DB code. The DB code includes Vertex and Edge definitions to provide a DB schema (sr-gen/org.eclipse.epsilon.orientdb.data.trace), implementations of the Data Model that delegate to DB objects (srg-gen/org.eclipse.epsilon.orientdb.data.trace.impl/) and a DAO class that provides the CRUD methods for each of the Data Model classes (src-gen/org.eclipse.epsilon.orientdb.data.execute/TraceOrientDbDAO.java)
Both projects should compile and be free of errors. However, this code is not production ready!!! If you want to see how the generated code works, you can instantiate the /org.eclipse.epsilon.orientdb.data/src/org/eclipse/epsilon/orientdb/data/OrientDbTraceManager.java class and use its API to create new traces on the DB and query for existing traces.
**Note:** The provided code only has support for connecting to In-Memory databases.
The next sections explain how the generators work so you can modify them for your own Data Model, improve the CRUD code and provide better sinergy with your project.
You would proably want to understand the Data Model modelling first and then dive into understanding the templates.
**Note:** There are a few places (mainly the import statements) in which the templates are harcoded to point to the packages used in this example (e.g. the Data Model interfaces are expected to be in the org.eclipse.epsilon.orientdb.business.trace pacakge. You will need to adjust this, or improve the templates so that the import statements are also created dynamically. :)
## Customizaing the Generators
[The Data Model](data_model.md)
[The EVL Templates](evl_templates.md)
# The Static Code
For the sake of completeness two non-generated classes are included. One is the business to data connection and the other is a DB utility class with connection helper methods (and a class wrapper for the delagating classes).
## OrientDbTraceManager.java
This class implements the IExecutionTraceManager interface defined in the business layer. This class uses an instance of the automatically generated DAO class to work with the DB objects and provide the business logic. Initially I was hoping the aquire, get/find and create methods could be automatically generated, but for each class there are different conditions on what is needed to aquire/get/create an instance... I did not manage to craete a simple way to define this in the metamodel (e.g. another annotation that provides the details). For example, for classes with index the get could be trivial, but for the Trace class you need to match a pattern in order to find it. I think it would require a "pattern language" or something to be used in the annotation to be able to express the complex interactions between the nodes in order to find somehting (e.g. that when looking for a trace youe need to match the element and the property, given a particualr module on a given context...). For this "small" demo it was too much work and probably not worth it. With the DAO implementation in place, writing the aquire/get/create methods was pretty simple. Just remember that templates usually excel at generating similar repetitive code and the business logic is not it :).
|
C
|
UTF-8
| 352 | 3.46875 | 3 |
[] |
no_license
|
#include<stdio.h>
int main()
{
int k;
int r = 0;
int s = 0;
int t = 0;
printf("Unesite magicni broj k: ");
scanf_s("%d", &k);
switch (k)
{
case 0:
r++;
break;
case 1:
s++;
break;
case 2: case 3: case 4:
t++;
break;
default:
break;
}
printf("r = %d\n", r);
printf("s = %d\n", s);
printf("t = %d\n", t);
return 0;
}
|
C++
|
UTF-8
| 20,624 | 3.03125 | 3 |
[] |
no_license
|
#include "PJCalibDetector.h"
/* Constructor */
PJCalibDetector::PJCalibDetector(Mat* image)
{
this->image = image;
/* Split image in Red Green & Blue */
split(*this->image, this->rgbPlanes);
/* Threshold the blue image */
this->blueThreshold = new Mat;
this->greenThreshold = new Mat;
this->redThreshold = new Mat;
this->redImage = &this->rgbPlanes[0];
this->greenImage = &this->rgbPlanes[1];
this->blueImage = &this->rgbPlanes[2];
/*Mat imageHSV, imageBlue;
cvtColor(*this->image, imageHSV, CV_RGB2HSV);
inRange(imageHSV, Scalar(155, 0, 0), Scalar(185, 255, 255), imageBlue);
imshow("HSV", imageBlue);*/
//*this->blueThreshold = imageBlue;
threshold(this->rgbPlanes[2], *this->blueThreshold, 80, 255, 0);
}
/* Most important function */
void PJCalibDetector::FindBlueRectangle(vector<Point> &blueRectangle)
{
/* Apply Canny filter to find lines */
Mat cannyDest, Blur;
blur(*blueThreshold, Blur, Size(3,3));
Canny(Blur, cannyDest, 5, 255, 3);
/* Apply Hough filter to find straight lines */
vector<Vec4i> Lines;
HoughLinesP(cannyDest, Lines, 0.5, CV_PI/180, 5, 35.0, 4.0);
/* Slope Filter: Only lines with at least 2 perpendiculars and 2 parallels remain */
Lines = this->SlopeFilter(Lines, 0.3, 0.9, 10.0);
/* Check if every detected line is the edge of a blue border */
Lines = this->BlueBorderCheck(Lines, *this->blueThreshold);
/* Make sure that every line segment is closed in by 2 intersections */
Lines = this->AllLineSegmentsWithinTheirIntersections(Lines);
/* Get the perpendicular intersections between these lines */
vector<Point> intersections = this->GetAllIntersections(Lines);
/* Organize the intersections in 4 groups */
vector<vector<Point> > intersectionGroups(10);
vector<Point> barryCenters;
barryCenters.assign(10, Point(0,0));
for(int i=0; i < intersections.size(); i++)
{
for(int j=0; j < intersectionGroups.size(); j++)
{
if(sqrt(pow((double)intersections[i].x - (double)barryCenters[j].x, 2) + pow((double)intersections[i].y - (double)barryCenters[j].y, 2)) < 30.0 && intersectionGroups[j].size() != 0)
{
// Add the element to the group (sort with respect to x: small first, then big)
int s = intersectionGroups[j].size();
intersectionGroups[j].push_back(Point(0,0));
while(s > 0 && intersections[i].x < intersectionGroups[j][s-1].x)
{
intersectionGroups[j][s] = intersectionGroups[j][s-1];
s--;
}
intersectionGroups[j][s] = intersections[i];
// Update the barry-center
barryCenters[j].x += intersections[i].x;
barryCenters[j].x /= 2;
barryCenters[j].y += intersections[i].y;
barryCenters[j].y /= 2;
break;
}
else if (intersectionGroups[j].size() == 0)
{
// Add the element to the group
intersectionGroups[j].push_back(intersections[i]);
// Update the barry-center
barryCenters[j].x += intersections[i].x;
barryCenters[j].y += intersections[i].y;
break;
}
}
}
if(barryCenters.size() > 4) // TO DO: Create a filter that filters out the best 4 points
barryCenters.erase(barryCenters.begin() + 4, barryCenters.end());
/* If one group appears to be empty, bail */
if(intersectionGroups[3].size() == 0 || intersectionGroups[2].size() == 0 || intersectionGroups[1].size() == 0 || intersectionGroups[0].size() == 0)
{
//throw exception("Not enough points are detected!");
}
/* Arrange barry centers */
vector<int> xArrangement, yArrangement;
vector<Point> mediumXArr = barryCenters, mediumYArr = barryCenters;
int temp;
xArrangement.assign(4,0);
yArrangement.assign(4,0);
Point temp2;
for(int i=0; i<barryCenters.size(); i++)
xArrangement[i] = yArrangement[i] = i;
for(int i=0; i<barryCenters.size(); i++)
{
for(int j=(i+1); j<barryCenters.size(); j++)
{
if(mediumXArr[i].x > mediumXArr[j].x)
{
temp = xArrangement[i];
xArrangement[i] = j;
xArrangement[j] = temp;
temp2 = mediumXArr[i];
mediumXArr[i] = mediumXArr[j];
mediumXArr[j] = temp2;
}
if(mediumYArr[i].y > mediumYArr[j].y)
{
temp = yArrangement[i];
yArrangement[i] = j;
yArrangement[j] = temp;
temp2 = mediumYArr[i];
mediumYArr[i] = mediumYArr[j];
mediumYArr[j] = temp2;
}
}
}
Point tempPoint;
/* First corner (lowest x) */
blueRectangle.push_back(Point(intersectionGroups[xArrangement[3]][intersectionGroups[xArrangement[3]].size()-1].x, intersectionGroups[xArrangement[3]][intersectionGroups[xArrangement[3]].size()-1].y));
/* Second corner (highest y -> resort the group for y) */
for(int i=0; i<intersectionGroups[yArrangement[0]].size(); i++)
{
for(int j=(i+1); j < intersectionGroups[yArrangement[0]].size(); j++)
{
if(intersectionGroups[yArrangement[0]][i].y > intersectionGroups[yArrangement[0]][j].y)
{
tempPoint = intersectionGroups[yArrangement[0]][i];
intersectionGroups[yArrangement[0]][i] = intersectionGroups[yArrangement[0]][j];
intersectionGroups[yArrangement[0]][j] = tempPoint;
}
}
}
blueRectangle.push_back(Point(intersectionGroups[yArrangement[0]][0].x, intersectionGroups[yArrangement[0]][0].y));
/* Third corner (highest x) */
blueRectangle.push_back(Point(intersectionGroups[xArrangement[0]][0].x, intersectionGroups[xArrangement[0]][0].y));
/* Fourth corner (lowest y -> resort the group for y) */
for(int i=0; i<intersectionGroups[yArrangement[3]].size(); i++)
{
for(int j=(i+1); j < intersectionGroups[yArrangement[3]].size(); j++)
{
if(intersectionGroups[yArrangement[3]][i].y > intersectionGroups[yArrangement[3]][j].y)
{
tempPoint = intersectionGroups[yArrangement[3]][i];
intersectionGroups[yArrangement[3]][i] = intersectionGroups[yArrangement[3]][j];
intersectionGroups[yArrangement[3]][j] = tempPoint;
}
}
}
blueRectangle.push_back(Point(intersectionGroups[yArrangement[3]][intersectionGroups[yArrangement[3]].size()-1].x, intersectionGroups[yArrangement[3]][intersectionGroups[yArrangement[3]].size()-1].y));
}
/* Help Functions */
vector<Vec4i> PJCalibDetector::SlopeFilter(vector<Vec4i> Lines, double parallel, double perpendicular, double merge)
{
Vec4i combinedLine;
Point p1, p2, p1c, p2c, midPoint;
double m1, m2, distance1, distance2, distance3, distance4, x, y, distanceIntersectionMidPoint;
for(int i=0; i<Lines.size(); i++)
{
int parallelMatches = 0;
int perpendicularMatches = 0;
p1 = Point(Lines[i][0], Lines[i][1]);
p2 = Point(Lines[i][2], Lines[i][3]);
m1 = ((double)p2.y-(double)p1.y)/((double)p2.x-(double)p1.x);
/* Parallel check */
for(int j=0; j<Lines.size(); j++)
{
if(j != i)
{
p1c = Point(Lines[j][0], Lines[j][1]);
p2c = Point(Lines[j][2], Lines[j][3]);
m2 = ((double)p2c.y-(double)p1c.y)/((double)p2c.x-(double)p1c.x);
if(abs(m1-m2) < parallel)
{
parallelMatches++; // Lines are parallel
/* Now check if these lines have the same carrier (if they are very parallel!) */
if(abs(m1-m2) < parallel/4.0)
{
x = m1*(double)p1.x - (double)p1.y - m2*double(p1c.x) + (double)p1c.y;
x /= (m1 - m2);
y = m1*(x-(double)p1.x) + (double)p1.y;
distance1 = sqrt(pow((double)p1.x - (double)p1c.x, 2) + pow((double)p1.y - (double)p1c.y, 2));
distance2 = sqrt(pow((double)p1.x - (double)p2c.x, 2) + pow((double)p1.y - (double)p2c.y, 2));
distance3 = sqrt(pow((double)p2.x - (double)p1c.x, 2) + pow((double)p2.y - (double)p1c.y, 2));
distance4 = sqrt(pow((double)p2.x - (double)p2c.x, 2) + pow((double)p2.y - (double)p2c.y, 2));
if(distance1 < distance2 && distance1 < distance3 && distance1 < distance4 /*&& distance1 < 20*/)
midPoint = Point(((double)p1.x + (double)p1c.x)/2.0, ((double)p1.y + (double)p1c.y)/2.0);
else if(distance2 < distance1 && distance2 < distance3 && distance2 < distance4 /*&& distance2 < 20*/)
midPoint = Point(((double)p1.x + (double)p2c.x)/2.0, ((double)p1.y + (double)p2c.y)/2.0);
else if(distance3 < distance1 && distance3 < distance2 && distance3 < distance4 /*&& distance3 < 20*/)
midPoint = Point(((double)p2.x + (double)p1c.x)/2.0, ((double)p2.y + (double)p1c.y)/2.0);
else if(distance4 < distance1 && distance4 < distance2 && distance4 < distance3 /*&& distance4 < 20*/)
midPoint = Point(((double)p2.x + (double)p2c.x)/2.0, ((double)p2.y + (double)p2c.y)/2.0);
distanceIntersectionMidPoint = sqrt(pow((double)midPoint.x - (double)x, 2) + pow((double)midPoint.y - (double)y, 2));
if(distanceIntersectionMidPoint < merge)
{
if(distance1 > distance2 && distance1 > distance3 && distance1 > distance4)
combinedLine = Vec4i(p1.x, p1.y, p1c.x, p1c.y);
else if(distance2 > distance1 && distance2 > distance3 && distance2 > distance4)
combinedLine = Vec4i(p1.x, p1.y, p2c.x, p2c.y);
else if(distance3 > distance1 && distance3 > distance2 && distance3 > distance4)
combinedLine = Vec4i(p2.x, p2.y, p1c.x, p1c.y);
else if(distance4 > distance1 && distance4 > distance2 && distance4 > distance3)
combinedLine = Vec4i(p2.x, p2.y, p2c.x, p2c.y);
Lines.erase(Lines.begin() + i);
if(j > i)
Lines.erase(Lines.begin() + (j-1));
else
{
Lines.erase(Lines.begin() + j);
i--;
}
Lines.push_back(combinedLine);
i--;
//cout << "Two lines with the same carrier where combined." << endl;
break; // The lines are removed, get the fuck out of here!
}
}
}
else if(abs(m1*m2+1) < perpendicular)
{
perpendicularMatches++; // Lines are perpendicular
}
}
}
if(!(parallelMatches >= 2 && perpendicularMatches >=2)) // Every line needs at least one parallels and 2 perpendiculars (rectangle)
{
//cout << "Removed line with " << parallelMatches << " parallels and " << perpendicularMatches << " perpendiculars." << endl;
Lines.erase(Lines.begin()+i);
i--;
}
}
return Lines;
}
bool PJCalibDetector::BlueBorderFound(Point testPoint, double slope, Mat blueThreshold, double &borderWidth)
{
double angle = atan(slope);
Point currentTestPoint;
int grayValueCurrent, grayValuePrevious;
bool transition1 = false, transition2 = false;
int transition1Row = -100, transition2Row = -100;
int nrCols=5, nrRows = 20;
for(int row=0; row<nrRows; row++)
{
borderWidth = 0;
grayValueCurrent = 0;
for(int col = 0; col<nrCols; col++)
{
currentTestPoint = Point(testPoint.x + (row-(nrRows/2))*sin(angle) + (col-(nrCols/2))*cos(angle), testPoint.y - (row-(nrRows/2))*cos(angle) + (col-(nrCols/2))*sin(angle));
if(testPoint.x > 0 && testPoint.x < 630 && testPoint.y > 0 && testPoint.y < 470)
{
grayValueCurrent += blueThreshold.at<uchar>(currentTestPoint);
}
else
{
return false;
}
Scalar color;
if(transition1 && !transition2)
color = CV_RGB(255, 0, 0);
else
color = CV_RGB(0, 255, 0);
//circle(*this->image, currentTestPoint, 1, color, 1, 1);
}
grayValueCurrent /= nrCols;
int value = 150;
if(row!=0)
{
if((!transition1) && (grayValueCurrent - grayValuePrevious < -value)) // Going into the white border
{
transition1 = true;
transition1Row = row;
}
else if((transition1) && (!transition2) && (grayValueCurrent - grayValuePrevious > value)) // Coming out of the white border
{
transition2 = true;
transition2Row = row;
}
}
grayValuePrevious = grayValueCurrent;
}
int rowValue = 1;
if(((transition1Row-10) >= -rowValue && (transition1Row-10) <= rowValue) || ((transition2Row-10) >= -rowValue && (transition2Row-10) <= rowValue))
if(transition1 && transition2)
{
borderWidth = abs((double)transition2Row - (double)transition1Row);
return true;
}
else
return false;
else
return false;
}
vector<Vec4i> PJCalibDetector::BlueBorderCheck(vector<Vec4i> Lines, Mat blueThreshold)
{
double m, borderWidth = 0, averageBorderWidth = 0;
Point testPoint;
double succesFrequency;
for(int i=0; i < Lines.size(); i++)
{
succesFrequency = 0;
averageBorderWidth = 0;
m = ((double)Lines[i][1] - (double)Lines[i][3])/((double)(Lines[i][0]-(double)Lines[i][2]));
double distance = sqrt(pow((double)Lines[i][0] - (double)Lines[i][2], 2) + pow((double)Lines[i][1] - (double)Lines[i][3], 2));
int numberOfSamples = distance/5; // 5 cols
for(int j=0; j < numberOfSamples; j++)
{
testPoint = Point(Lines[i][0] + j*(distance/numberOfSamples)*cos(atan(m)), Lines[i][1] + j*(distance/numberOfSamples)*sin(atan(m)));
if(this->BlueBorderFound(testPoint, m, blueThreshold, borderWidth))
{
averageBorderWidth += borderWidth;
succesFrequency++;
}
}
averageBorderWidth /= (double)numberOfSamples;
if(averageBorderWidth <= 1.0 || succesFrequency < numberOfSamples/5)
{
Lines.erase(Lines.begin() + i);
i--;
//cout << "Removed line because the average border width was too small." << endl;
}
}
return Lines;
}
/* ROI Funtions */
Mat PJCalibDetector::SetROIFromPolygon(Mat* inputImage, vector<Point> polygon)
{
/* ROI by creating mask for the parallelogram */
Mat mask = cvCreateMat(480, 640, CV_8UC1); // Create black image with the same size as the original
for(int i=0; i<mask.cols; i++)
for(int j=0; j<mask.rows; j++)
mask.at<uchar>(Point(i,j)) = 0;
vector<Point> approxedRectangle;
approxPolyDP(polygon, approxedRectangle, 1.0, true);
fillConvexPoly(mask, &approxedRectangle[0], approxedRectangle.size(), 255, 8, 0);
Mat imageDest = cvCreateMat(480, 640, CV_8UC3);
inputImage->copyTo(imageDest, mask);
return imageDest;
}
vector<vector<Point> > PJCalibDetector::GetCornerROIs(vector<Point> polygon)
{
vector<vector<Point> > ROIs(4);
/* Create parallellogram in each corner of the plate */
int s = 0, t = 0;
for(int i=0; i<4; i++)
{
(i < 3) ? s = i+1 : s = 3 - i;
(i == 0) ? t = i+3 :t= i-1;
ROIs[i].push_back(polygon[i]);
double Distance = sqrt(pow(((double)polygon[i].x - (double)polygon[s].x), 2) + pow(((double)polygon[i].y - (double)polygon[s].y),2));
double m1 = ((double)polygon[s].y - (double)polygon[i].y)/((double)polygon[s].x - (double)polygon[i].x);
double Angle = atan(m1);
(polygon[s].x < polygon[i].x) ? Angle += CV_PI : Angle = Angle;
ROIs[i].push_back(Point(polygon[i].x + cos(Angle)*Distance/4.0, polygon[i].y + sin(Angle)*Distance/4.0));
Distance = sqrt(pow(((double)polygon[i].x - (double)polygon[t].x), 2) + pow(((double)polygon[i].y - (double)polygon[t].y),2));
double m2 = ((double)polygon[t].y - (double)polygon[i].y)/((double)polygon[t].x - (double)polygon[i].x);
Angle = atan(m2);
(polygon[t].x < polygon[i].x) ? Angle += CV_PI : Angle = Angle;
ROIs[i].push_back(Point(polygon[i].x + cos(Angle)*Distance/4.0, polygon[i].y + sin(Angle)*Distance/4.0));
double x = m2*(double)ROIs[i][1].x - (double)ROIs[i][1].y - m1*double(ROIs[i][2].x) + (double)ROIs[i][2].y;
x /= (m2 - m1);
double y = m2*(x-(double)ROIs[i][1].x) + (double)ROIs[i][1].y;
ROIs[i].push_back(Point(x, y));
Point tempPoint = ROIs[i][1];
ROIs[i][1] = ROIs[i][0];
ROIs[i][0] = tempPoint;
}
return ROIs;
}
/* IntersectionCheck */
vector<Point> PJCalibDetector::GetLineIntersections(Vec4i line, vector<Vec4i> allLines)
{
vector<Point> intersections;
Point p1(line[0], line[1]);
Point p2(line[2], line[3]);
double x, y, m1, m2;
Point p1c, p2c;
m1 = ((double)p2.y-(double)p1.y)/((double)p2.x-(double)p1.x);
for(int i=0; i < allLines.size(); i++)
{
x = y = 0;
p1c = Point(allLines[i][0], allLines[i][1]);
p2c = Point(allLines[i][2], allLines[i][3]);
m2 = ((double)p2c.y-(double)p1c.y)/((double)p2c.x-(double)p1c.x);
if((m1 - m2) != 0 && (m1*m2 + 1) < 1.0) // Get only the perpendicular ones!
{
x = m1*(double)p1.x - (double)p1.y - m2*double(p1c.x) + (double)p1c.y;
x /= (m1 - m2);
y = m1*(x-(double)p1.x) + (double)p1.y;
intersections.push_back(Point(x, y));
}
}
return intersections;
}
vector<Point> PJCalibDetector::GetAllIntersections(vector<Vec4i> Lines)
{
/* Calculate the intersections */
Point p1, p2, p1c, p2c;
vector<Point> intersections;
vector<Point> intersectionsTemp;
for(int i=0; i < Lines.size(); i++)
{
intersectionsTemp = this->GetLineIntersections(Lines[i], Lines);
for(int j=0; j < intersectionsTemp.size(); j++)
intersections.push_back(intersectionsTemp[j]);
}
return intersections;
}
bool PJCalibDetector::PointOnLineSegment(Vec4i line, Point point)
{
/* Check if point lies on the line carrier */
double m = ((double)line[3] - (double)line[1])/((double)line[2] - (double)line[0]);
if(abs(((double)point.y - (double)line[1])/((double)point.x - (double)line[0]) - m) > 0.05)
return false;
/* Check if point lies within the segment */
if((point.x >= (double)line[0] && point.x <= (double)line[2]) || (point.x <= (double)line[0] && point.x >= (double)line[2]))
return true;
else
return false;
}
vector<Vec4i> PJCalibDetector::AllLineSegmentsWithinTheirIntersections(vector<Vec4i> allLines)
{
vector<Point> lineIntersections;
for(int s=0; s < allLines.size(); s++)
{
lineIntersections = this->GetLineIntersections(allLines[s], allLines);
bool midPointOnLine;
bool succes = false;
Vec4i intersectionSegment; // line between the two selected intersection points
Vec4i line = allLines[s];
Point midPoint;
for(int i=0; i<lineIntersections.size();i++)
{
for(int j=0; j<lineIntersections.size();j++)
{
if(i!=j)
{
intersectionSegment = Vec4i(lineIntersections[i].x, lineIntersections[i].y, lineIntersections[j].x, lineIntersections[j].y);
midPoint = Point(((double)line[0]+(double)line[2])/2.0, ((double)line[1] + (double)line[3])/2.0);
midPointOnLine = this->PointOnLineSegment(intersectionSegment, midPoint);
if(midPointOnLine)
succes = true;
}
}
}
if(!succes)
{
allLines.erase(allLines.begin() + s);
s--;
}
}
return allLines;
}
/* Order Rectangle */
vector<Point> PJCalibDetector::OrderCorners(Mat* image, vector<Point> blueRectangle)
{
Mat imageReduced;
vector<vector<Point> > ROIs;
ROIs = this->GetCornerROIs(blueRectangle);
/* Find the green cross */
for(int i=0; i<blueRectangle.size(); i++)
{
// TO DO
this->FindGreenCross(ROIs[i]);
//this->FindRedSquare(ROIs[i]);
//this->FindOrangeCircle(ROIs[i]);
}
imshow("Test", *this->image);
return blueRectangle;
}
bool PJCalibDetector::FindGreenCross(vector<Point> ROI)
{
Mat imageReducedThres;
Mat imageReduced = this->SetROIFromPolygon(this->greenImage, ROI);
double ROIarea = contourArea(ROI);
RotatedRect rotatedRect;
vector<vector<Point> > contours;
double area, boxedArea, boxRatio, ROIratio, whRatio;
vector<Point> greenCross;
Mat superBlur;
for(int j=45; j < 100; j = j+5)
{
threshold(imageReduced, imageReducedThres, j, 255, 0);
if(j > 70)
blur(imageReducedThres, imageReducedThres, Size(5, 2));
else
blur(imageReducedThres, imageReducedThres, Size(5, 1));
findContours(imageReducedThres, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
for(int i=0; i<contours.size(); i++)
{
approxPolyDP(contours[i], greenCross, 0.8, true);
area = contourArea(greenCross);
if(greenCross.size() < 35 && greenCross.size() >= 12 && area > 25.0) // The cross has 12 vertices, the approximation will usually have more ...
{
rotatedRect = minAreaRect(greenCross);
boxedArea = rotatedRect.size.area();
boxRatio = area/boxedArea; // Ratio of the area with that of the bounding box
ROIratio = area/ROIarea; // Ratio with the ROI to have an idea how small/big the mark is
whRatio = rotatedRect.size.width/rotatedRect.size.height; // Width-Height ratio of the bounding box
/*if(j == 50)
{
imshow("test", imageReducedThres);
cout << "ROIratio: " << ROIratio << endl;
cout << "BoxRatio: " << boxRatio << endl;
cout << "WH: " << whRatio << endl;
}*/
if((boxRatio < 0.70 && boxRatio > 0.30) && (ROIratio < 0.20 && ROIratio > 0.03) && abs(whRatio-1) < 0.6)
{
fillConvexPoly(*this->image, &greenCross[0], greenCross.size(), CV_RGB(0, 255, 0), 8);
return true; // Green cross has been found
}
}
}
}
return false;
}
bool PJCalibDetector::FindRedSquare(vector<Point> ROI)
{
Mat imageReduced = this->SetROIFromPolygon(this->redImage, ROI);
threshold(imageReduced, imageReduced, 40, 255, 1);
vector<vector<Point> > contours;
findContours(imageReduced, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
// TO DO
return false;
}
bool PJCalibDetector::FindOrangeCircle(vector<Point> ROI)
{
// TO DO
return false;
}
|
Java
|
UTF-8
| 479 | 1.9375 | 2 |
[] |
no_license
|
package nanifarfalla.app.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import nanifarfalla.app.model.Contrato;
@Repository
public interface ContratoRepository extends JpaRepository<Contrato, Integer> {
@Query(value = "select c.codigo_contrato from contrato c order by codigo_contrato DESC LIMIT 1", nativeQuery = true)
int lastcode();
}
|
Markdown
|
UTF-8
| 6,282 | 2.71875 | 3 |
[] |
no_license
|
---
description: Découverte de Framework7
---
# M4B103-seance-3
Framework7 va vous offrir tout un arsenal d'outils pour développer votre appli mobile avec des popups, des menus déroulants, des panneaux , des formulaires, des calendriers... le tout adapté aux mobiles et à son ergonomie, à travers des classes CSS et du javascript . \( comme bootstrap pour le dev web\) . La partie dev js est structurée un peu comme du vuejs. Vous avez aussi la même \(ou presque\) syntaxe que jquery pour accéder aux éléméents du DOM: $$\("\#idElement"\).html\(...\) ...
[https://framework7.io/docs/](https://framework7.io/docs/)
Remarque: tout comme bootstrap, il faut apprendre à connaitre les différentes classes des différents éléments \(popup, bouton, panel...\) ainsi que la structuration des éléments \(équivalent des rows/cols et grids sous bootstrap par exemple\)
### Exercice 1:
#### utilisation de framework7 pour "looker" l'application en mode mobile
Avec l'outils monaca, créez un projet en choisissant un model basique basé sous Framework7 \(permet d'installer tous les packages nécessaires en un clique\)


### application créée par ce projet:
tester l'ergonomie de cette application sur l'émulateur et sur votre mobile

structure de l'application avec ses librairies de Framework7 installées:

sauvegardez sur votre machine le source html proposé \(pour garder l'exemple\) et remplacez le par le code minimum suivant:
```text
...
<body>
<div id="app">
<div class="view view-main ios-edges">
<div class="page" data-name="home">
<div class="page-content">
Top Run Game ...
</div>
</div>
</div>
</div>
</body>
...
```
ceci est le corps minimum d'une appli FrameWork7
Maintenant vous pouvez ajouter des éléments type mobile \(panneau latéraux, fenetre popup...\). Ces éléments d'ajoute en début d'application \(app\) sous forme de div avec des classe spécifique \(ex: panel panel left pour un panneau latéral gauche\)
vous pouvez ajouter des panneaux latéraux gauche et/ou droit:
```text
...
<div id="app">
<div class="panel panel-left panel-reveal theme-dark">
<div class="view">
<div class="page">
<div class="page-content">
ici un debut de panneau gauche...
</div>
</div>
</div>
</div>
....
```
dans la page principale vous devez rajouter un 'bouton' pour "actionner le panneau gauche:
```text
<a href="#" class="button button-raised button-fill panel-open" data-panel="left">
ouvrir le panneau de gauche
</a>
```
ajout d'un popup mobile: \(et de son bouton de fermeture\)
```text
...
<div id="app">
<div class="popup" id="mon-popup">
<div class="view">
<div class="page">
<div class="page-content">
<p>Bob</p>
<p><a href="#" class="link popup-close">Close</a></p>
</div>
</div>
</div>
</div>
...
```
ajouter un lien sur la 'page principale' pour activer le popup
```text
<a href="#" class="button button-raised button-fill popup-open" data-popup="#mon-popup">
Ouvrir mon Popup
</a>
```
vous pouvez ajouter une barre de navigation à votre application:
à insérer juste avant <div class="page" data-name="home">
```text
<div class="navbar">
<div class="navbar-inner">
<div class="title sliding">MMI Power</div>
</div>
</div>
```
Vous pouvez aussi lancer une fonction lors du clique sur un bouton. Pour cela vous pouvez mettre un id \(ex: 'monBouton' \)au bouton et dans le fichier app.js ajouter
```text
$$('#monBouton').on('click', function () {
alert('Hello les MMI');
});
```
vous pouvez accéder aux éléments du DOM comme avec jquery:
```text
$$('#monBouton').on('click', function () {
$$('#maZoneMessage').html("hello");
});
```
#### en résumer: simplifier les fichiers proposés \(js et html\) avant de commencer votre application
```text
...
<body>
<div id="app">
<!-- Your main view, should have "view-main" class -->
<div class="view view-main ios-edges">
<!-- Page, data-name contains page name which can be used in callbacks -->
<div class="page" data-name="home">
<!-- Top Navbar -->
<div class="navbar">
<div class="navbar-inner">
<div class="title sliding">MMI Power</div>
</div>
</div>
<!-- Scrollable page content-->
<div class="page-content">
<div class="block block-strong">
<p>Top Run Game</p>
</div>
<div class="row">
<div class="col-50">
<a href="#" class="button button-raised button-fill panel-open" data-panel="left">Un peu d'info</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Framework7 library -->
<script src="framework7/js/framework7.min.js"></script>
<!-- Monaca JS library -->
<script src="components/loader.js"></script>
<!-- App routes -->
<script src="js/routes.js"></script>
<!-- Your custom app scripts -->
<script src="js/app.js"></script>
</body>
...
```
faites la même chose avec le fichier app.js:
```text
// Dom7
var $$ = Dom7;
// Framework7 App main instance
var app = new Framework7({
root: '#app', // App root element
id: 'io.framework7.mmi', // App bundle ID
name: 'MMI', // App name
theme: 'auto', // Automatic theme detection
// App routes
routes: routes
});
// Init/Create main view
var mainView = app.views.create('.view-main', {
url: '/'
});
```
### Exercice 2:
en partant de ce projet simplifié, relookez votre application "Game of Run"
* utilisez un panel left pour changer le temps maxi et le choix de l'orientation du déplacement \(nord/sud/est/ouest\)
* vous pouvez reprendre le code source proposé au démarrage par le projet monaca pour tester les différents éléments \(popups, menu, barre de nav ...\) et leurs codes sources.
|
Python
|
UTF-8
| 190 | 3.40625 | 3 |
[] |
no_license
|
# sum of n natural nrmbers
# ask a user for natural numbe(n)
# print total from 1 to n
num = int(input("enter number to sum "))
i = 1
sum = 0
while i<=num:
sum += i
i +=1
print(sum)
|
C#
|
UTF-8
| 6,112 | 2.78125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MachinesRUs.Machines;
using MachinesRUs.Observer;
using MachinesRUs.Controls;
using MachinesRUs.Dialogs;
namespace MachinesRUs
{
public partial class ClientForm : Form
{
// The list of machines in the form.
private List<IMachine> machines = new List<IMachine>();
// A dictionary containing lists of Machine types for constructing a Composite
// machine.
private Dictionary<string, string[]> compositeMachines;
/// <summary>
/// Sets the state of the machines stored in the machines list.
/// </summary>
private bool Started
{
set
{
// Determine if the machines should be stopped or started.
if (value)
MachineList.StartMachines();
else
MachineList.StopMachines();
// Enable/Disable the appropriate controls.
startToolStripMenuItem.Enabled = !value;
StartButton.Enabled = !value;
stopToolStripMenuItem.Enabled = value;
StopButton.Enabled = value;
}
}
public ClientForm()
{
InitializeComponent();
compositeMachines = new Dictionary<string, string[]>();
// Load all of the AtomicMachine implementations in the AtomicMachine
// list.
AtomicMachineList.LoadAtomicMachines();
}
/// <summary>
/// Called when an AddMachineButton from the AtomicMachineList is clicked.
/// </summary>
private void AddMachineButton_Click(object sender, EventArgs e)
{
// Ensure an AddMachineButton called was the sender.
if (!(sender is AddMachineButton))
return;
// Ensure the machines are stopped.
Started = false;
// Cast the sender to its correct type.
var addMachineButton = (AddMachineButton)sender;
// Retrieve the type of machine from the button.
var machineType = addMachineButton.MachineType;
// Create a new machine of the specified type.
var machineFactory = MachineFactory.GetInstance();
var machine = machineFactory.CreateMachine(machineType);
// Add the machine to the MachineList.
MachineList.AddMachine(machine);
}
/// <summary>
/// Called when the form is being closed.
/// </summary>
private void ClientForm_FormClosing(object sender, FormClosingEventArgs e)
{
// Stop all of the machines.
MachineList.StopMachines();
}
/// <summary>
/// Called when the NewCompositeButton is clicked.
/// </summary>
private void NewCompositeButton_Click(object sender, EventArgs e)
{
// Display a CompositemachineDialog.
var dialog = new CompositeMachineDialog();
dialog.ShowDialog();
// Ensure the user chose to save the result.
if (dialog.DialogResult == DialogResult.Cancel)
return;
// Ensure the name the user chose is not already taken.
String[] machineTypes;
if (compositeMachines.TryGetValue(dialog.MachineName, out machineTypes))
{
MessageBox.Show(
"The name " + dialog.MachineName + " is already in use.",
"Name Taken",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
return;
}
// Add the composite machine definition to the dictionary.
compositeMachines.Add(dialog.MachineName, dialog.MachineTypes);
// Add an AddMachineButton for the new machine type.
CompositeMachineList.AddButton(dialog.MachineName);
}
/// <summary>
/// Called when an AddMachineButton in the composite list is clicked.
/// </summary>
private void CompositeMachineList_AddMachine(object sender, EventArgs e)
{
// Ensure an AddMachineButton sent the event.
if (!(sender is AddMachineButton))
return;
// Ensure the machines are stopped.
Started = false;
// Retrieve the button reference.
var button = (AddMachineButton)sender;
// Retrieve the name of the machine type.
var name = button.MachineType;
// Retrive the list of machine types in the composite machine with the specified name.
string[] types = compositeMachines[name];
// Construct an array of AtomicMachines using the composite machine's types.
var atomicMachines = new AtomicMachine[types.Length];
for (var i = 0; i < atomicMachines.Length; i++)
atomicMachines[i] = (AtomicMachine)MachineFactory.GetInstance().CreateMachine(types[i]);
// Create a new composite machine with the constructed array of machines.
var compositeMachine = new CompositeMachine(atomicMachines);
// Add the composite machine to the machine list.
MachineList.AddMachine(compositeMachine, name);
}
/// <summary>
/// Called when a start option is clicked.
/// </summary>
private void startToolStripMenuItem_Click(object sender, EventArgs e)
{
// Start the machines.
Started = true;
}
/// <summary>
/// Called when the stop option is clicked.
/// </summary>
private void stopToolStripMenuItem_Click(object sender, EventArgs e)
{
// Stop the machines.
Started = false;
}
}
}
|
C++
|
UTF-8
| 10,456 | 2.578125 | 3 |
[] |
no_license
|
#include "slackRemover.h"
void slackInfo::allDirFilesdum(const string tDir){
const string newtDir = tDir;
allDirFiles(newtDir);
}
// good function to pthread
void slackInfo::allDirFiles(const string& tDir){
//fileStat hfile;
namespace fs = boost::filesystem;
fs::path targetDir(tDir);
fs::directory_iterator it(targetDir), eod;
/*** pass files into fileCreate or recurse back into folders***/
BOOST_FOREACH(fs::path const &p, std::make_pair(it, eod)){
if (is_regular_file(p)){
cout<<"File directory: " << p << endl;
string result = p.string();
/*hfile = */BOOL results = ClearSlack(fileCreate(result));
if(results == 0 ){
cout<<"Could not clear slackspace."<<endl;
}
}
else if (is_directory(p)){
//put it back
string result = p.string();
cout << "\n\nFolder: "<<result <<endl<< endl;
allDirFiles(result);
}
//ADD ERROR HANDLER for none file or dir
else
cout<<p<<" is not a file or directory."<<endl;
}
/***************************************************************/
}
fileStat slackInfo::fileCreatedum(const string targetFile){
const string targetFilez = targetFile;
return fileCreate(targetFilez);
}
fileStat slackInfo::fileCreate(const string& targetFile){
fileStat filez;
/*********call fileStat struct and check if file exist************/
fstream file(targetFile.c_str());
if (!file){
cout << "File does not exist" << endl;
}
/****************************************************************/
/************convert string from comand line to LPCWSTR********/
wstring stemp = strChange(targetFile);
LPCWSTR result = stemp.c_str();
/****************************************************************/
/**************** Path of the file ******************************/
wchar_t pathBuffer[MAX_PATH];
HRESULT hr =::StringCchCopy(pathBuffer,
_countof(pathBuffer),
stemp.c_str());
if (!::PathStripToRoot(pathBuffer)){
cout << "error with PathStripToRoot" << endl;
}
wstring root = wstring(pathBuffer);
//wcout << "This is the path " << root << endl;
//input path string for CreateFile
int wstringln =sizeof(&root);
root[2] = '\0';
wstring newroot = L"\\\\.\\"+root;
LPCWSTR pathz = newroot.c_str();
/****************************************************************/
/**********CreateFile of user input file ************************/
HANDLE hFile = INVALID_HANDLE_VALUE;
hFile = CreateFile(result,
GENERIC_READ | GENERIC_WRITE |FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
0);
if (hFile == INVALID_HANDLE_VALUE) {
cout << "File does not exist" << endl;
CloseHandle(hFile);
//system("pause");
}
//cout << "You opened/created the file succesfully: " << hFile << endl;
/****************************************************************/
/********************** Find the File size *********************/
WIN32_FILE_ATTRIBUTE_DATA fdata;
if(!GetFileAttributesEx(result,GetFileExInfoStandard,&fdata)){
cout<< "Error with GetFileAtributesEx " <<endl;
}
LARGE_INTEGER fSize;
fSize.HighPart = fdata.nFileSizeHigh;
fSize.LowPart = fdata.nFileSizeLow;
//cout<< "This is the GetFileAttributesEx file size: " <<fSize.QuadPart<<endl;
/****************************************************************/
/******* Find information on disk (SectorPerCluster etc) ********/
DWORD dwSectPerClust,
dwBytesPerSect,
dwFreeClusters,
dwTotalClusters;
int diskClust = 0;
diskClust = GetDiskFreeSpace(root.c_str(),
&dwSectPerClust,
&dwBytesPerSect,
&dwFreeClusters,
&dwTotalClusters);
if (diskClust == 0){
cout << "error in function diskInfo with GetDiskFreeSpace" << endl;
}
/*
cout << "Sectors Per Cluster: " << dwSectPerClust << endl;
cout << "Bytes Per Sector: " << dwBytesPerSect << endl;
cout << "Free Clusters: " << dwFreeClusters << endl;
cout << "Total Clusters: " << dwTotalClusters << endl<<endl<<endl;
*/
filez.volBufData.BytesPerCluster = dwBytesPerSect * dwSectPerClust;
filez.volBufData.NumberSectors.QuadPart = dwTotalClusters;
filez.volBufData.NumberSectors.QuadPart *= dwSectPerClust;
/******************************************************************/
/*********************** Find the slack Space **********************/
// File size / cluster size(in butes) = # of clusters needed
// if (File size % cluster size !=0) then you need 1 more cluster
// # of clusters + 1 = total clusters used
DWORD extraCluster;
if (fSize.QuadPart % filez.volBufData.BytesPerCluster != 0){
extraCluster = 1;
}
else{
extraCluster = 0;
}
DWORD clustersNeed = (fSize.QuadPart / filez.volBufData.BytesPerCluster) + (extraCluster);
/*cout << "This file size " << fSize.QuadPart<< " / Cluster size " << filez.volBufData.BytesPerCluster
<< "= # of clusters needed: " << clustersNeed << endl;*/
// slack space = (totals clusters * cluster size) - File size
DWORD slackSpaces = clustersNeed * filez.volBufData.BytesPerCluster - fSize.QuadPart;
/*cout << "The total slack space is clusters needed: " << clustersNeed << " * Cluster size: " << filez.volBufData.BytesPerCluster
<< " - file size: " << fSize.QuadPart << " = total slack space: " << slackSpaces << endl << endl << endl;*/
/********************************************************************/
/****** set temp file endpoint *******/
HANDLE hFileOrg = INVALID_HANDLE_VALUE;
hFileOrg = CreateFile(result,
GENERIC_READ | GENERIC_WRITE |FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if (hFileOrg == INVALID_HANDLE_VALUE) {
cout << "File does not exist" << endl;
//CloseHandle(hFileOrg);
//system("pause");
}
/********************************************************************/
filez.fileName = result;
filez.tempHan = hFileOrg;
filez.slackSpace = slackSpaces;
filez.hanFile = hFile;
filez.filePath = root;
filez.fileSize = fSize;
filez.Volpath = pathz;
filez.bytePerSec = dwBytesPerSect;
return filez;
}
/**** Convert string into wstring *****/
wstring slackInfo::strChange(const string& s)
{
int len,slength;
slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
wstring r(buf);
delete[] buf;
return r;
}
void slackInfo::ClearSlackdum (fileStat in){
ClearSlack(in);
}
BOOL slackInfo::ClearSlack( fileStat info) {
cout<< "File size: " <<info.fileSize.QuadPart<<endl;
cout<< "Amount of SlackSpace: "<<info.slackSpace<<endl;
BOOL returnz = SetFilePointer(info.tempHan, info.fileSize.QuadPart,NULL,FILE_BEGIN);
if(returnz ==0){
cout<<"Error with SetFilePointer"<<endl;
}
DWORD dwBytesWritten;
cout<<"Clearing File's slack space..."<<endl;
/******************* Loop to write random 0s and 1s to the end of the file **********/
for( int a = 2; a<6;a++){
//Alternate 0s and 1s
int b,c;
b = 2;
c = a%b;
char * wfileBuff = new char[info.slackSpace];
memset (wfileBuff,c,info.slackSpace);
returnz = SetFilePointer(info.hanFile, info.fileSize.QuadPart,NULL,FILE_BEGIN);
if(returnz ==0){
cout<<"Error with SetFilePointer"<<endl;
return 0;
}
/**** Lock file, Write data, Unlock file *******/
if(LockFile(info.hanFile, returnz, 0, info.slackSpace, 0) != 0)
returnz =WriteFile(info.hanFile, wfileBuff, info.slackSpace, &dwBytesWritten, NULL);
if(returnz ==0){
cout<<"There is an error with WriteFile"<<endl;
cout<<"Error: "<<GetLastError()<<endl;
return 0;
}
if(UnlockFile(info.hanFile, returnz, 0, info.slackSpace, 0) != 0);
/***********************************************/
//cout<<dwBytesWritten<<endl<<endl;
//system("pause");
//Cut out the extra data written from the file
if(!SetEndOfFile(info.tempHan)){
cout<<"Error seting the end of the file"<<endl;
return 0;
}
}
/****************************************************************************************/
cout<<"Slackspace overwritten successfully.\n\n\n";
return 1;
}
//function needs some more test(function is an extra feature and has nothing to do with removing slackspace)
void slackInfo::volumeInfo (fileStat inf ){
/******************* CreateFile for volume ***********************/
/*
***Note***
The following two functions(CreateFile and DeviceIoControl) will
not work unless the application is ran as admin. However, these
two functions are not needed to write over file slackspace.
*/
HANDLE hDevice = INVALID_HANDLE_VALUE;
hDevice = CreateFile(inf.Volpath,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hDevice == INVALID_HANDLE_VALUE){ // cannot open the drive
//wcout << "error at hDevice with path: "<< endl;
DWORD error = GetLastError();
if (error == ERROR_ACCESS_DENIED){
//cout << "error_access_denied" << endl;
}
//cout << error << endl;
//system("pause");
}
/******************************************************************/
/********** Get extent information on the volume **********************/
VOLUME_DISK_EXTENTS volExtent;
DWORD bytesReturned = 0;
BOOL check = 0;
check = DeviceIoControl(hDevice,
IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
NULL,
0,
&volExtent,
sizeof(volExtent),
&bytesReturned,
NULL);
if(check == 0){
//cout<<"Error with DeviceIoControl with control code IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS"<<endl;
}
DWORD beginCluster = 0;
DWORD beginRoot = 0;
LONGLONG volumeSize = inf.volBufData.NumberSectors.QuadPart * inf.bytePerSec;
LONGLONG volumeStartSector = volExtent.Extents[0].StartingOffset.QuadPart / inf.bytePerSec;
STARTING_VCN_INPUT_BUFFER inputVcnBuff;
RETRIEVAL_POINTERS_BUFFER rtPtrBuff;
memset(&inputVcnBuff, 0 , sizeof(STARTING_VCN_INPUT_BUFFER));
memset(&rtPtrBuff, 0 , sizeof(RETRIEVAL_POINTERS_BUFFER));
cout<<"Volume Size: "<<volumeSize<<endl;
cout<<"Volume start Sector: "<<volumeStartSector<<endl;
/***********************************************************************************************************/
}
|
PHP
|
UTF-8
| 2,409 | 2.640625 | 3 |
[] |
no_license
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $t) {
$t->increments('id');
$t->string('name');
$t->string('email')->unique();
$t->string('password');
$t->rememberToken();
$t->timestamps();
});
Schema::create('categories', function (Blueprint $t) {
$t->increments('id');
$t->string('name');
$t->timestamps();
});
Schema::create('topics', function (Blueprint $t) {
$t->increments('id');
$t->unsignedInteger('user_id');
$t->unsignedInteger('category_id');
$t->string('title');
$t->text('content');
$t->string('tags');
$t->timestamps();
$t->foreign('user_id')->references('id')->on('users');
$t->foreign('category_id')->references('id')->on('categories');
});
Schema::create('comments', function (Blueprint $t) {
$t->increments('id');
$t->unsignedInteger('user_id');
$t->unsignedInteger('topic_id');
$t->text('content');
$t->timestamps();
$t->foreign('user_id')->references('id')->on('users');
$t->foreign('topic_id')->references('id')->on('topics');
});
Schema::create('votes', function (Blueprint $t) {
$t->increments('id');
$t->unsignedInteger('user_id');
$t->boolean('type');
$t->string('target');
$t->unsignedInteger('topic_id')->nullable();
$t->unsignedInteger('comment_id')->nullable();
$t->timestamps();
$t->foreign('user_id')->references('id')->on('users');
$t->foreign('topic_id')->references('id')->on('topics');
$t->foreign('comment_id')->references('id')->on('comments');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('votes');
Schema::drop('comments');
Schema::drop('topics');
Schema::drop('categories');
Schema::drop('users');
}
}
|
Python
|
UTF-8
| 2,179 | 3.21875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#!/usr/bin/env python3
"""Basic demo on how to run a Finger Robot with torque control."""
import os
import numpy as np
from ament_index_python.packages import get_package_share_directory
import robot_interfaces
import robot_fingers
def get_random_torque():
"""Generate a random torque within a save range."""
torque_min = np.array([-0.2, -0.2, -0.2])
torque_max = np.array([0.2, 0.2, 0.2])
return np.random.uniform(torque_min, torque_max)
def demo_torque_control():
# Use the default configuration file from the robot_fingers package
config_file_path = os.path.join(
get_package_share_directory("robot_fingers"), "config", "finger.yml"
)
# Storage for all observations, actions, etc.
robot_data = robot_interfaces.finger.SingleProcessData()
# The backend takes care of communication with the robot hardware.
robot_backend = robot_fingers.create_real_finger_backend(
robot_data, config_file_path
)
# The frontend is used by the user to get observations and send actions
robot_frontend = robot_interfaces.finger.Frontend(robot_data)
# Initializes the robot (e.g. performs homing).
robot_backend.initialize()
while True:
# Run a torque controller that randomly changes the desired torque
# every 500 steps. One time step corresponds to roughly 1 ms.
desired_torque = get_random_torque()
for _ in range(500):
# Appends a torque command ("action") to the action queue.
# Returns the time step at which the action is going to be
# executed.
action = robot_interfaces.finger.Action(torque=desired_torque)
t = robot_frontend.append_desired_action(action)
# wait until the action is executed
robot_frontend.wait_until_timeindex(t)
# print observation of the current time step
observation = robot_frontend.get_observation(t)
print("-----")
print("Position: %s" % observation.position)
print("Velocity: %s" % observation.velocity)
print("Torque: %s" % observation.torque)
if __name__ == "__main__":
demo_torque_control()
|
Go
|
UTF-8
| 345 | 3.078125 | 3 |
[] |
no_license
|
package main
import "fmt"
func main() {
// var (
// ia int = 1
// fb float64 = 1.0
// )
// fmt.Printf("%p, %p\n", &ia, &fb)
var flag string = "I will hard-working in ByteDance."
ptr := &flag
fmt.Printf("ptr is %T\n", ptr)
fmt.Printf("%s\n", *ptr)
value := *ptr
fmt.Printf("value is %T\n", value)
fmt.Printf("%s\n", value)
}
|
Java
|
UTF-8
| 2,693 | 2.34375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package foundation.base.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wu_jian on 2015/7/30.
*/
public abstract class CommonListAdapter<T> extends android.widget.BaseAdapter {
protected List<T> list;
protected int layoutId;
protected Context context;
protected LayoutInflater inflater;
private View _emptyView = getEmptyView();
private ListView listView;
public CommonListAdapter(Context context, int layoutId, List<T> list) {
this.list = list;
this.layoutId = layoutId;
this.context = context;
inflater = LayoutInflater.from(context);
}
public CommonListAdapter(ListView listView,Context context, int layoutId, List<T> list) {
this.list = list;
this.layoutId = layoutId;
this.context = context;
this.listView=listView;
inflater = LayoutInflater.from(context);
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
_emptyView = getEmptyView();
}
public void addList(ArrayList<T> list) {
if (list == null) {
return;
}
if (this.list != null) {
this.list.addAll(list);
} else {
this.list = list;
}
}
public void removeAll( ){
if (this.list != null) {
this.list.clear();
}
}
@Override
public int getCount() {
if (list.size() == 0 && _emptyView != null ){
return 1;
}else if(list.size() == 0 || list == null){
return 0;
}else{
return list.size();
}
}
private View getEmptyView() {
View v = emptyView();
if (v != null) {
v.setMinimumHeight(listView.getHeight());
return v;
}
return null;
}
protected View emptyView() {
return null;
}
@Override
public T getItem(int arg0) {
return list.get(arg0);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (list.size() == 0 && _emptyView != null)
return _emptyView;
ViewHolder viewHolder = ViewHolder.getViewHolder(context, position, layoutId, convertView, parent);
convert(viewHolder, getItem(position),position);
return viewHolder.getConvertView();
}
public abstract void convert(ViewHolder holder, T t,int position);
}
|
Markdown
|
UTF-8
| 856 | 2.625 | 3 |
[] |
no_license
|
# Yii2 [Tabler](https://github.com/tabler/tabler) Theme (Bootstrap 4)
It is a free admin template for backend of yii framework 2 based on [Tabler](https://github.com/tabler/tabler) theme. Tabler is free and open-source HTML Dashboard UI Kit built on Bootstrap 4
This extension consists assets bundles,, some page views and a layout example.
# Installation
The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
Either run
```
php composer.phar require --prefer-dist synamen/yii2-tabler-theme "~1.0"
```
or add
```
synamen/yii2-tabler-theme": "~1.0"
```
to the require section of your `composer.json` file.
#Usage
All you need to to is copy views folder from vendor/synamen/views and paste into your app views folder
or with command
cp -R vendor/synamen/yii2-tabler-theme/views/* backend/views/
|
C
|
UTF-8
| 1,818 | 2.640625 | 3 |
[] |
no_license
|
/**
******************************************************************************
* @文件 ci100x_ir.c
* @作者 chipintelli软件团队
* @版本 V1.0.0
* @日期 2016-4-9
* @概要 这个文件提供接口函数来控制chipintelli公司的CI100X芯片的红外发送接收模块.
******************************************************************************
* @注意
*
* 版权归chipintelli公司所有,未经允许不得使用或修改
*
******************************************************************************
*/
#include "ci100x_ir.h"
/**
* @功能:初始化红外模块
* @注意:在使用前需调用SCU相关接口初始化对应管脚
* @参数:无
* @返回值:无
*/
void IR_Init(void)
{
SMT_IR->REM_CR = 0xc;
}
/**
* @功能:使能或禁用红外模块
* @注意:无
* @参数:state 0:禁用红外模块 1:使能红外模块
* @返回值:无
*/
void IR_Cmd(unsigned int state)
{
if(state==0)
{
SMT_IR->REM_CR &= ~(0x1 << 0);
}
else
{
SMT_IR->REM_CR |= (0x1 << 0);
}
}
/**
* @功能:配置红外模块发送单笔数据
* @注意:无
* @参数:data0:8bit用户码data1:8bit用户码或反码,data2:8bit数据
* @返回值:无
*/
void IR_SendData(unsigned char data0,unsigned char data1,unsigned char data2)
{
SMT_IR->REM_TX_DATA = ((data0 & 0xff) << 16) | ((data1 & 0xff) << 8) | (data2 & 0xff);
}
/**
* @功能:配置IR 接收 单笔数据
* @注意:无
* @参数:无
* @返回值:接收到的数据
*/
unsigned char IR_ReceiveData(void)
{
unsigned char data;
data = (SMT_IR->REM_RX_DATA >> 7) & 0xff;
return data;
}
/***************** (C) COPYRIGHT Chipintelli Technology Co., Ltd. *****END OF FILE****/
|
Markdown
|
UTF-8
| 6,366 | 3.53125 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
---
alias: [Strike Price]
created: 2021-03-02T23:45:25 (UTC +11:00)
tags: [Strike Price Definition, Strike Price Definition]
source: https://www.investopedia.com/terms/s/strikeprice.asp
author: Jason Fernando
---
# Strike Price Definition
> ## Excerpt
> Strike price is the price at which a derivative contract can be bought or sold (exercised).
---
Strike Price Definition
## What Is a Strike Price?
A strike price is the set price at which a derivative contract can be bought or sold when it is [exercised](https://www.investopedia.com/terms/e/exerciseprice.asp). For [call options](https://www.investopedia.com/terms/c/calloption.asp), the strike price is where the security can be bought by the option holder; for [put options](https://www.investopedia.com/terms/p/putoption.asp), the strike price is the price at which the security can be sold.
Strike price is also known as the [exercise price](https://www.investopedia.com/terms/e/exerciseprice.asp).
### Key Takeaways
- Strike price is the price at which a derivative contract can be bought or sold (exercised).
- Derivatives are financial products whose value is based (derived) on the underlying asset, usually another financial instrument.
- The strike price, also known as the exercise price, is the most important determinant of option value.
## Understanding Strike Prices
Strike prices are used in [derivatives](https://www.investopedia.com/terms/d/derivative.asp) (mainly options) trading. Derivatives are financial products whose value is based (derived) on the underlying asset, usually another financial instrument. The strike price is a key variable of call and put options. For example, the buyer of a stock option call would have the right, but not the obligation, to buy that stock in the future at the strike price. Similarly, the buyer of a stock option put would have the right, but not the obligation, to sell that stock in the future at the strike price.
The strike or exercise price is the most important determinant of option value. Strike prices are established when a contract is first written. It tells the investor what price the underlying asset must reach before the option is [in-the-money](https://www.investopedia.com/terms/i/inthemoney.asp) (ITM). Strike prices are standardized, meaning they are at fixed dollar amounts, such as $31, $32, $33, $102.50, $105, and so on.
[The price difference](https://www.investopedia.com/ask/answers/042715/what-difference-between-money-and-out-money.asp) between the underlying stock price and the strike price determines an option's value. For buyers of a call option, if the strike price is above the underlying stock price, the option is [out of the money](https://www.investopedia.com/terms/o/outofthemoney.asp) (OTM). In this case, the option doesn't have [intrinsic value](https://www.investopedia.com/terms/i/intrinsicvalue.asp), but it may still have value based on volatility and time until expiration as either of these two factors could put the option in the money in the future. Conversely, If the underlying stock price is above the strike price, the option will have intrinsic value and be in the money.
A buyer of a put option will be in the money when the underlying stock price is below the strike price and be out of the money when the underlying stock price is above the strike price. Again, an OTM option won't have intrinsic value, but it may still have value based on the volatility of the underlying asset and the time left until option expiration.
## Strike Price Example
Assume there are two option contracts. One is a call option with a $100 strike price. The other is a call option with a $150 strike price. The current price of the underlying stock is $145. Assume both call options are the same, the only difference is the strike price.
At expiration, the first contract is worth $45. That is, it is in the money by $45. This is because the stock is trading $45 higher than the strike price.
The second contract is out of the money by $5. If the price of the underlying asset is below the call's strike price at expiration, the option expires worthless.
If we have two put options, both about to expire, and one has a strike price of $40 and the other has a strike price of $50, we can look to the current stock price to see which option has value. If the underlying stock is trading at $45, the $50 put option has a $5 value. This is because the underlying stock is below the strike price of the put.
The $40 put option has no value, because the underlying stock is above the strike price. Recall that put options allow the option buyer to sell at the strike price. There is no point using the option to sell at $40 when they can sell at $45 in the stock market. Therefore, the $40 strike price put is worthless at expiration.
## Frequently Asked Questions
### What is a strike price?
The term strike price refers to the price at which an option or other derivative contract can be exercised. For example, if a call option entitles the option holder to buy a given security at a price of $20 per share, its strike price would be $20. If exercising an option would generate profit for the option holder, then that option is referred to as being “in the money”. If exercising the option would not generate profit, then the option is referred to as “out of the money”.
### Are some strike prices more desirable than others?
The question of what strike price is most desirable will depend on factors such as the risk tolerance of the investor and the options premiums available from the market. For example, most investors will look for options whose strike prices are relatively close to the current market price of the security, based on the logic that those options have a higher probability of being exercised at a profit. At the same time, some investors will deliberately seek out options that are far out of the money—that is, options whose strike prices are very far from the market price—in the hopes of realizing very large returns if the options do become profitable.
### Are strike prices and exercise prices the same?
Yes, the terms strike price and exercise price are synonymous. Some traders will use one term over the other, and may use the terms interchangeably, but their meanings are the same. Both terms are widely used in derivatives trading.
|
Java
|
UTF-8
| 1,858 | 2.234375 | 2 |
[] |
no_license
|
package basic.booking.controller;
import basic.booking.domain.Reserve;
import basic.booking.domain.User;
import basic.booking.repos.ReserveRepo;
import basic.booking.repos.SubjectRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.sql.Date;
import java.util.List;
import java.util.Map;
@Controller
public class ReservationController {
@Autowired
private ReserveRepo reserveRepo;
@Autowired
private SubjectRepo subjectRepo;
@GetMapping("/reservation/{IDSubjectForReserve}")
public String reserveSubject(
@PathVariable Integer IDSubjectForReserve, Map<String, Integer> model){
model.put("IDSubjectForReserve",IDSubjectForReserve);
return "reservation";
}
@PostMapping("/reservation/**")
public String submitReserve(
@RequestParam Date wanteddate,
@RequestParam Integer IDSubjectForReserve,
@AuthenticationPrincipal User user,
Map<String, Object> model){
List<Reserve> res = reserveRepo.tryReserves(wanteddate,subjectRepo.findByIDSubject(IDSubjectForReserve));
if (res.size()==0) {
Reserve reserve = new Reserve(wanteddate, subjectRepo.findByIDSubject(IDSubjectForReserve), user);
reserveRepo.save(reserve);
return "reserve-go";
} else {
return "reserve-no";
}
}
@GetMapping("/reservation")
public String addNewObject(){return "reservation";}
}
|
Java
|
UTF-8
| 418 | 2.46875 | 2 |
[
"MIT"
] |
permissive
|
package exitIT;
import org.junit.Test;
import static org.junit.Assert.*;
import exit.*;
import place.*;
public class OneWayDoorIT {
@Test
public void getNextPlace() {
Place p = new Room(null,null,0,null,null);
Place p2 = new Room(null,null,0,null,null);
OneWayDoor e = new OneWayDoor(p,p2);
assertNull(e.getNextPlace(p2));
assertEquals(e.getNextPlace(p),p2);
}
}
|
JavaScript
|
UTF-8
| 3,252 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
/* jshint unused: false */
define([ 'underscore', 'dungcarv' ], function(_, dungCarv) {
"use strict";
var bits = {
0x01: 'NW',
0x02: 'N',
0x04: 'NE',
0x08: 'E',
0x10: 'SE',
0x20: 'S',
0x40: 'SW',
0x80: 'W'
};
var toDirection = {
0x01 : { x: -1, y: -1 },
0x02 : { x: 0, y: -1 },
0x04 : { x: 1, y: -1 },
0x08 : { x: 1, y: 0 },
0x10 : { x: 1, y: 1 },
0x20 : { x: 0, y: 1 },
0x40 : { x: -1, y: 1 },
0x80 : { x: -1, y: 0 }
};
var cells = {
WALL: 0,
CORRIDOR: 1,
ROOM: 2,
DOOR: 3,
ENTRANCE: 4,
EXIT: 5
};
function Map(params) {
params = params || {};
this.walkables = [];
if (params.map) {
this.width = params.width;
this.height = params.height;
this.map = params.map;
} else {
this.width = params.width || 5;
this.height = params.height || 5;
var r = dungCarv({
mapWidth: this.width,
mapHeight: this.height,
padding: 1,
randomness: 10 / 100.0,
twistness: 20 / 100.0,
rooms: 25 / 100.0,
roomSize: [
{ min: 4, max: 10, prob: 1 }
],
roomRound: false,
loops: 0 / 100.0,
spaces: 0,
loopSpaceRepeat: 2,
eraseRoomDeadEnds: true,
spacesBeforeLoops: false
});
this.map = r.map;
}
if (!this.width || !this.height) {
throw new Error('You must provide both a width and height value');
}
for (var i in this.map) {
if (this.map.hasOwnProperty(i)) {
if (this.map[i] === cells.ENTRANCE) {
this.entrance = i;
} else if (this.map[i] === cells.EXIT) {
this.exit = i;
}
if (this.map[i] !== cells.WALL) {
this.walkables.push(i);
}
}
}
}
Map.prototype.getBits = function(idx) {
var x = idx % this.width,
y = Math.floor(idx / this.height),
mask = 0;
_.each(toDirection, function(pos, bit) {
var tx = x + pos.x,
ty = y + pos.y,
idx = ty * this.height + tx;
if (tx > 0 && tx < this.width - 1 && ty > 0 && ty < this.height - 1) {
if (this.map[idx] !== cells.WALL) {
mask = mask | parseInt(bit, 10);
}
}
}, this);
return mask;
};
Map.prototype.getEntrance = function() {
return this.get(this.entrance);
};
Map.prototype.getExit = function() {
return this.get(this.exit);
};
Map.prototype.getRandomWalkable = function() {
return this.get(this.walkables[Math.floor(Math.random() * this.walkables.length)]);
};
Map.prototype.each = function(fn) {
for (var i = 0; i < this.map.length; i++) {
fn(this.get(i), parseInt(i, 10));
}
};
Map.prototype.get = function(idx) {
var tile = this.map[idx],
position = this._getPosition(idx),
bits = this.getBits(idx);
return {
idx: parseInt(idx, 10),
position: position,
tile: tile,
bits: bits,
walkable: tile !== cells.WALL
};
};
Map.prototype._getPosition = function(idx) {
var position = { x: idx % this.width,
y: Math.floor(idx / this.width) };
return position;
};
return Map;
});
|
C++
|
UTF-8
| 5,406 | 2.546875 | 3 |
[] |
no_license
|
#include "mygui_osgtexture.h"
#include <osg/Texture2D>
#include <osgDB/ReadFile>
#include <MyGUI_Gui.h>
#include "log.hpp"
#include "mygui_osgdiagnostic.h"
#include "mygui_osgrendermanager.h"
namespace TK
{
OSGTexture::OSGTexture(const std::string &name)
: mName(name)
, mFormat(MyGUI::PixelFormat::Unknow)
, mUsage(MyGUI::TextureUsage::Default)
, mNumElemBytes(0)
{
}
OSGTexture::~OSGTexture()
{
}
void OSGTexture::createManual(int width, int height, MyGUI::TextureUsage usage, MyGUI::PixelFormat format)
{
GLenum glfmt = GL_NONE;
size_t numelems = 0;
switch(format.getValue())
{
case MyGUI::PixelFormat::L8:
glfmt = GL_LUMINANCE;
numelems = 1;
break;
case MyGUI::PixelFormat::L8A8:
glfmt = GL_LUMINANCE_ALPHA;
numelems = 2;
break;
case MyGUI::PixelFormat::R8G8B8:
glfmt = GL_RGB;
numelems = 3;
break;
case MyGUI::PixelFormat::R8G8B8A8:
glfmt = GL_RGBA;
numelems = 4;
break;
}
if(glfmt == GL_NONE)
throw std::runtime_error("Texture format not supported");
mTexture = new osg::Texture2D();
mTexture->setTextureSize(width, height);
mTexture->setSourceFormat(glfmt);
mTexture->setSourceType(GL_UNSIGNED_BYTE);
mTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
mTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
mTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
mTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
mFormat = format;
mUsage = usage;
mNumElemBytes = numelems;
}
void OSGTexture::destroy()
{
mTexture = nullptr;
mFormat = MyGUI::PixelFormat::Unknow;
mUsage = MyGUI::TextureUsage::Default;
mNumElemBytes = 0;
}
void OSGTexture::loadFromFile(const std::string &fname)
{
osg::ref_ptr<osg::Image> image = osgDB::readImageFile(fname);
if(!image.valid())
throw std::runtime_error("Failed to load image "+fname);
if(image->getDataType() != GL_UNSIGNED_BYTE)
throw std::runtime_error("Unsupported pixel type");
MyGUI::PixelFormat format;
size_t numelems;
switch(image->getPixelFormat())
{
case GL_ALPHA:
/* FIXME: Alpha as luminance? Or maybe convert to luminance+alpha
* with full luminance? */
image->setPixelFormat(GL_LUMINANCE);
/* fall-through */
case GL_LUMINANCE:
format = MyGUI::PixelFormat::L8;
numelems = 1;
break;
case GL_LUMINANCE_ALPHA:
format = MyGUI::PixelFormat::L8A8;
numelems = 2;
break;
case GL_RGB:
format = MyGUI::PixelFormat::R8G8B8;
numelems = 3;
break;
case GL_RGBA:
format = MyGUI::PixelFormat::R8G8B8A8;
numelems = 4;
break;
default:
throw std::runtime_error("Unsupported pixel format");
}
image->flipVertical();
mTexture = new osg::Texture2D(image.get());
mTexture->setUnRefImageDataAfterApply(true);
mTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
mTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
mTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
mTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
mFormat = format;
mUsage = MyGUI::TextureUsage::Static | MyGUI::TextureUsage::Write;
mNumElemBytes = numelems;
}
void OSGTexture::saveToFile(const std::string &fname)
{
Log::get().message("Would save image to file "+fname, Log::Level_Error);
}
int OSGTexture::getWidth()
{
if(!mTexture.valid())
return 0;
osg::Image *image = mTexture->getImage();
if(image) return image->s();
return mTexture->getTextureWidth();
}
int OSGTexture::getHeight()
{
if(!mTexture.valid())
return 0;
osg::Image *image = mTexture->getImage();
if(image) return image->t();
return mTexture->getTextureHeight();
}
void *OSGTexture::lock(MyGUI::TextureUsage /*access*/)
{
MYGUI_PLATFORM_ASSERT(mTexture.valid(), "Texture is not created");
MYGUI_PLATFORM_ASSERT(!mLockedImage.valid(), "Texture already locked");
mLockedImage = mTexture->getImage();
if(!mLockedImage.valid())
{
mLockedImage = new osg::Image();
mLockedImage->allocateImage(
mTexture->getTextureWidth(), mTexture->getTextureHeight(), mTexture->getTextureDepth(),
mTexture->getSourceFormat(), mTexture->getSourceType()
);
}
return mLockedImage->data();
}
void OSGTexture::unlock()
{
MYGUI_PLATFORM_ASSERT(mLockedImage.valid(), "Texture not locked");
// Tell the texture it can get rid of the image for static textures (since
// they aren't expected to update much at all).
mTexture->setImage(mLockedImage.get());
mTexture->setUnRefImageDataAfterApply(mUsage.isValue(MyGUI::TextureUsage::Static) ? true : false);
mTexture->dirtyTextureObject();
mLockedImage = nullptr;
}
bool OSGTexture::isLocked()
{
return mLockedImage.valid();
}
// FIXME: Render-to-texture not currently implemented.
MyGUI::IRenderTarget* OSGTexture::getRenderTarget()
{
return nullptr;
}
} // namespace TK
|
Java
|
UTF-8
| 1,483 | 2.40625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package io.smartcat.cassandra.diagnostics.info;
/**
* Thread pool stats info class.
*/
public class TPStatsInfo {
/**
* Thread pool name.
*/
public final String threadPool;
/**
* Thread pool active tasks.
*/
public final long activeTasks;
/**
* Thread pool pending tasks.
*/
public final long pendingTasks;
/**
* Thread pool completed tasks.
*/
public final long completedTasks;
/**
* Thread pool blocked tasks.
*/
public final long currentlyBlockedTasks;
/**
* Thread pool all time blocked tasks.
*/
public final long totalBlockedTasks;
/**
* Thread pool stats info.
*
* @param threadPool thread pool name
* @param activeTasks active tasks
* @param pendingTasks pending tasks
* @param completedTasks completed tasks
* @param currentlyBlockedTasks currently blocked tasks
* @param totalBlockedTasks total blocked tasks
*/
public TPStatsInfo(String threadPool, long activeTasks, long pendingTasks, long completedTasks,
long currentlyBlockedTasks, long totalBlockedTasks) {
this.threadPool = threadPool;
this.activeTasks = activeTasks;
this.pendingTasks = pendingTasks;
this.completedTasks = completedTasks;
this.currentlyBlockedTasks = currentlyBlockedTasks;
this.totalBlockedTasks = totalBlockedTasks;
}
}
|
Java
|
UTF-8
| 2,279 | 3.078125 | 3 |
[] |
no_license
|
package com.swedbank.entry_test.util;
import com.swedbank.entry_test.util.data.DecathlonResultEntry;
import com.swedbank.entry_test.util.data.Position;
import java.util.*;
/**
* @author ben
* @version 1.0
*/
public class DecathlonEntryOrganiser {
private final DecathlonPointsCounter counter;
public DecathlonEntryOrganiser(DecathlonPointsCounter counter) {
this.counter = counter;
}
/**
* Counts points and position for each entry, and then returns them ordered by points
*
* @param entries entries to organise
*/
public Collection<DecathlonResultEntry> organise(Collection<DecathlonResultEntry> entries) {
// A tree set to order the entries in descending order
final TreeSet<DecathlonResultEntry> entriesTree = new TreeSet<>(
(Comparator<DecathlonResultEntry>) (a, b) -> {
int res = b.getPoints().compareTo(a.getPoints());
if (res == 0) {
return -1;
}
return res;
}
);
// Maps points to positions
final TreeMap<Integer, Collection<Position>> sharingPlaces = new TreeMap<>(
(a,b) -> b.compareTo(a)
);
//Count points for entries
for (DecathlonResultEntry entry : entries) {
Integer points = counter.countPoints(entry);
entry.setPoints(points);
Position position = new Position();
entry.setPosition(position);
// Add entry to a tree
entriesTree.add(entry);
// Update sharing places
if (sharingPlaces.containsKey(points)) {
sharingPlaces.get(points).add(position);
} else {
sharingPlaces.put(points, new LinkedList<>(Arrays.asList(position)));
}
}
// Write position data
int place = 1;
for (Collection<Position> positions : sharingPlaces.values()) {
int count = positions.size();
for (Position position : positions) {
position.setFrom(place);
position.setTo(place+count-1);
}
place+= count;
}
return entriesTree;
}
}
|
Java
|
UTF-8
| 876 | 2.84375 | 3 |
[] |
no_license
|
package com.example.solitare2114.controller;
import java.util.ArrayList;
import java.util.List;
import com.example.solitare2114.GameView;
public class GameController extends Controller
{
public GameController(GameView gv)
{
super(gv);
myControllers = new ArrayList<Controller>();
}
List<Controller> myControllers;
@Override
public void onTouchDown(float x, float y)
{
for(Controller c : myControllers)
c.onTouchDown(x, y);
}
@Override
public void onTouchMove(float x, float y)
{
for(Controller c : myControllers)
c.onTouchMove(x, y);
}
@Override
public void onTouchUp(float x, float y)
{
for(Controller c : myControllers)
c.onTouchUp(x, y);
}
public void addController(Controller in) {
myControllers.add(in);
}
}
|
Java
|
UTF-8
| 2,490 | 2.59375 | 3 |
[] |
no_license
|
package pt.ulisboa.tecnico.sirs;
import pt.ulisboa.tecnico.sirs.exception.SecurityLibraryException;
import pt.ulisboa.tecnico.sirs.security.Signable;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import static pt.ulisboa.tecnico.sirs.Entity.concat;
import static pt.ulisboa.tecnico.sirs.Entity.toBase64;
/**
* Abstract class that defines the structure of a patient record
*/
public abstract class Record implements Serializable, Signable {
private final Certificate doctorCertificate;
private final Certificate patientCertificate;
private final long date;
private final String record;
public Record(final Certificate doctorCertificate, final Certificate patientCertificate, final String record) {
this.doctorCertificate = doctorCertificate;
this.patientCertificate = patientCertificate;
this.date = System.currentTimeMillis();
this.record = record;
}
/**
* This will be useful to sign records
* @return byte array which corresponds to this array
*/
public byte[] getBytes() throws SecurityLibraryException {
try {
return concat(
doctorCertificate.getEncoded(),
patientCertificate.getEncoded(),
ByteBuffer.allocate(Long.BYTES).putLong(date).array(),
record.getBytes()
);
} catch (CertificateEncodingException e) {
throw new SecurityLibraryException(e);
}
}
public Certificate getDoctorCertificate() {
return doctorCertificate;
}
public Certificate getPatientCertificate() {
return patientCertificate;
}
public PublicKey getPatientPublicKey() {
return patientCertificate.getPublicKey();
}
public PublicKey getDoctorPublicKey() {
return doctorCertificate.getPublicKey();
}
public long getDate() {
return date;
}
public String getRecord() {
return record;
}
@Override
public String toString() {
return "Record{" +
"doctorKey=" + toBase64(doctorCertificate.getPublicKey().getEncoded()) +
", patientKey=" + toBase64(doctorCertificate.getPublicKey().getEncoded()) +
", date=" + date +
", record='" + record + '\'' +
'}';
}
}
|
C++
|
UTF-8
| 704 | 2.71875 | 3 |
[] |
no_license
|
/*#define bzz 2
#define rl 1
int option;
int led = 6;
void setup(){
Serial.begin(115200);
pinMode(led, OUTPUT);
pinMode(bzz, OUTPUT);
pinMode(rl,OUTPUT);
}
void loop(){
//si existe información pendiente
if (Serial.available()>0){
//leeemos la opcion
char option = Serial.read();
//si la opcion esta entre '1' y '9'
if (option >= '1' && option <= '9')
{
//restamos el valor '0' para obtener el numeroenviado
option -= '0';
for(int i=0;i<option;i++){
digitalWrite(led, HIGH);
delay(500);
digitalWrite(led, LOW);
delay(300);
Buzzer();
relay();
}
}
}
}*/
|
C++
|
UTF-8
| 688 | 2.96875 | 3 |
[] |
no_license
|
#pragma once
#include<string>
class Client{
public:
Client();
Client(std::string nom, std::string prenom ,int nbr_reservation=1);
//Client(std::string nom, std::string prenom, int nbr_reservation=1);
// Les setters permettront d'entrer les informations du client ou de les modifier
void setId(int id) ;
void setNom(std::string nom) ;
void setPrenom(std::string prenom) ;
void setNbrReservation(int nbr_reservation);
int getNbrReservation() const;
std::string getNom() const;
std::string getPrenom() const;
int getId() const;
void affichage() const;
private:
std::string m_nom;
std::string m_prenom;
int m_id;
int m_nbr_reservation;
int identifiant_auto_int();
};
|
Python
|
UTF-8
| 275 | 3.921875 | 4 |
[
"CC0-1.0"
] |
permissive
|
upper = int(input("Enter the num"))
print("primes under", upper)
for num in range(upper):
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,"is a prime number")
|
PHP
|
UTF-8
| 96 | 2.78125 | 3 |
[] |
no_license
|
<?php
namespace strategy;
interface StrategyInterface
{
public function caculatePrice();
}
|
PHP
|
UTF-8
| 609 | 2.515625 | 3 |
[] |
no_license
|
<?php
namespace controller\dashboard;
class home extends \SUP\controller {
function __invoke($request, $response, $args) {
if ($this->container->auth->getUser()->is(ROLE_ADMIN)) {
return $this->sendResponse($request, $response, "dash/admin.phtml");
} else if ($this->container->auth->getUser()->is(ROLE_TEACHER)) {
return $this->sendResponse($request, $response, "dash/teacher.phtml");
} else if ($this->container->auth->getUser()->is(ROLE_STUDENT)) {
return $this->sendResponse($request, $response, "dash/student.phtml");
}
}
}
|
Java
|
UTF-8
| 1,159 | 1.914063 | 2 |
[] |
no_license
|
package in.mangoo.mangooonlinefooddelivery.ViewHolder;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import in.mangoo.mangooonlinefooddelivery.Interface.ItemClickListener;
import in.mangoo.mangooonlinefooddelivery.R;
import info.hoang8f.widget.FButton;
import xyz.hanks.library.bang.SmallBangView;
public class CouponViewHolder extends RecyclerView.ViewHolder {
public TextView code, desc, date, apply;
public ImageView coupon_image;
private ItemClickListener itemClickListener;
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
public CouponViewHolder(@NonNull View itemView) {
super(itemView);
code = (TextView) itemView.findViewById(R.id.coupon_code);
desc = (TextView) itemView.findViewById(R.id.coupon_description);
date = (TextView) itemView.findViewById(R.id.coupon_expiry);
apply = itemView.findViewById(R.id.apply_coupon_btn);
}
}
|
Java
|
UTF-8
| 531 | 2.609375 | 3 |
[] |
no_license
|
package com.company;
public class Main {
public static void main(String[] args) {
bank bank = new bank("Hieudz");
bank.addBranch("Ha Noi");
bank.addBranch("Hcm");
bank.addCustomer("Ha Noi","Hieu",100);
bank.addCustomer("Ha Noi","Nam",200);
bank.addCustomer("Ha Noi","Ha",100);
bank.addTransaction("Ha Noi","Hieu",200);
bank.addTransaction("Ha Noi","Hieu",300);
bank.addTransaction("Ha Noi","Nam",200);
bank.listCustomer("Ha Noi",false);
}
}
|
Python
|
UTF-8
| 2,610 | 2.6875 | 3 |
[] |
no_license
|
import copy
import numpy as np
# import pandas as pd
# from blur_map import first_generation_particles,resampling
def read_pgm(map_path):
"""Return a raster of integers from a PGM as a list of lists."""
pgmf = open(map_path, 'rb')
a = pgmf.readline()
assert a == b'P5\n'
(width, height) = [int(i) for i in pgmf.readline().split()]
depth = int(pgmf.readline())
assert depth <= 255
raster = []
for i in range(height):
row = []
for j in range(width):
row.append(ord(pgmf.read(1)))
raster.append(np.array(row))
return np.array(raster)
def print_matrix(matrix):
for i in range(len(matrix)):
row = ""
for j in range(len(matrix[i])):
row += str(matrix[i][j]) + "\t"
print(row)
print()
def paint(matrix, i, j):
matrix[i][j] = 0
def isPainted(matrix, i, j):
try:
if matrix[i][j] == 0:
return True
except:
# print("ERROR EN IS PAINTED",i,j)
return True
return False
def isPaintedOrUnexplored(matrix, i, j):
try:
if matrix[i][j] < 255:
return True
except:
# print("ERROR EN IS PAINTED OR UNEXPLORED",i,j)
return True
return False
def isUnexplored(matrix,i,j):
if i < 0 or j < 0:
return True
try:
if matrix[i][j] == 205:
return True
except:
# print("ERROR IN IS UNEXPLORED")
return True
return False
def paintNeighbours(matrix, i, j, radius, acc):
acc += 1
if acc <= radius:
if not isPainted(matrix, i+1, j):
paint(matrix, i+1, j)
paintNeighbours(matrix, i+1, j, radius, acc)
if not isPainted(matrix, i, j+1):
paint(matrix, i, j+1)
paintNeighbours(matrix, i, j+1, radius, acc)
if not isPainted(matrix, i-1, j):
paint(matrix, i-1, j)
paintNeighbours(matrix, i-1, j, radius, acc)
if not isPainted(matrix, i, j-1):
paint(matrix, i, j-1)
paintNeighbours(matrix, i, j-1, radius, acc)
if __name__ == "__main__":
pass
# matrix = read_pgm(map_path)
# matrix_original = copy.deepcopy(matrix)
# pgmf.close()
# c_space(matrix_original, matrix, radius=2)
# # print_matrix(matrix)
# # particles = first_generation_particles(100,np.array(matrix),[0,0],0.1)
# # prob = [0.4,0.2,0.3,0.1,0]
# # print(dic)
# # print("")
# print(particles)
# new_dic,new_part = resampling(100,matrix,prob,particles)
# print(new_dic)
# print("")
# print(new_part)
|
C#
|
UTF-8
| 1,949 | 2.59375 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Display the contents of the inventory in the agents UI, except for the flags
/// which continue to be rendered
/// </summary>
public class InventoryDisplay : MonoBehaviour
{
public GameObject ItemSprite;
public GameObject Inventory;
private InventoryController _inventoryScript;
const string TransparentSprite = "TransparentSprite";
private List<GameObject> _inventoryImages = new List<GameObject>();
private Sprite _emptySprite;
// Use this for initialization
void Start ()
{
_inventoryScript = Inventory.GetComponent<InventoryController>();
_inventoryImages.Capacity = _inventoryScript.Capacity;
// This is needed to ensure empty inventory slots are invisible
_emptySprite = Resources.Load< Sprite>(TransparentSprite);
for (int i = 0; i < _inventoryImages.Capacity; i++)
{
_inventoryImages.Add(Instantiate(ItemSprite));
_inventoryImages[i].transform.SetParent( gameObject.transform, false);
}
}
private void OnGUI()
{
int i = 0;
// Display a sprite for each item in the inventory, as this is a dictionary we have to use foreach
foreach (KeyValuePair<string, GameObject> item in _inventoryScript.Items)
{
//Dont display flags in the inventory display
if (!item.Value.tag.Equals(Tags.Flag))
{
Sprite uiSprite = item.Value.GetComponent<InventorySprite>().UiSprite;
_inventoryImages[i].GetComponent<Image>().sprite = uiSprite;
i++;
}
}
// Ensure any remaining slots are invisible
for (int j = i; j < _inventoryImages.Capacity; j++)
{
_inventoryImages[j].GetComponent<Image>().sprite = _emptySprite;
}
}
}
|
Go
|
UTF-8
| 3,666 | 2.515625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
// Copyright 2022 uTLS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tls
import (
"golang.org/x/crypto/cryptobyte"
)
// Only implemented client-side, for server certificates.
// Alternate certificate message formats (https://datatracker.ietf.org/doc/html/rfc7250) are not
// supported.
// https://datatracker.ietf.org/doc/html/rfc8879
type utlsCompressedCertificateMsg struct {
raw []byte
algorithm uint16
uncompressedLength uint32 // uint24
compressedCertificateMessage []byte
}
func (m *utlsCompressedCertificateMsg) marshal() ([]byte, error) {
if m.raw != nil {
return m.raw, nil
}
var b cryptobyte.Builder
b.AddUint8(utlsTypeCompressedCertificate)
b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddUint16(m.algorithm)
b.AddUint24(m.uncompressedLength)
b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes(m.compressedCertificateMessage)
})
})
var err error
m.raw, err = b.Bytes()
return m.raw, err
}
func (m *utlsCompressedCertificateMsg) unmarshal(data []byte) bool {
*m = utlsCompressedCertificateMsg{raw: data}
s := cryptobyte.String(data)
if !s.Skip(4) || // message type and uint24 length field
!s.ReadUint16(&m.algorithm) ||
!s.ReadUint24(&m.uncompressedLength) ||
!readUint24LengthPrefixed(&s, &m.compressedCertificateMessage) {
return false
}
return true
}
type utlsEncryptedExtensionsMsgExtraFields struct {
hasApplicationSettings bool
applicationSettings []byte
customExtension []byte
}
func (m *encryptedExtensionsMsg) utlsUnmarshal(extension uint16, extData cryptobyte.String) bool {
switch extension {
case utlsExtensionApplicationSettings:
m.utls.hasApplicationSettings = true
m.utls.applicationSettings = []byte(extData)
}
return true // success/unknown extension
}
type utlsClientEncryptedExtensionsMsg struct {
raw []byte
applicationSettings []byte
hasApplicationSettings bool
customExtension []byte
}
func (m *utlsClientEncryptedExtensionsMsg) marshal() (x []byte, err error) {
if m.raw != nil {
return m.raw, nil
}
var builder cryptobyte.Builder
builder.AddUint8(typeEncryptedExtensions)
builder.AddUint24LengthPrefixed(func(body *cryptobyte.Builder) {
body.AddUint16LengthPrefixed(func(extensions *cryptobyte.Builder) {
if m.hasApplicationSettings {
extensions.AddUint16(utlsExtensionApplicationSettings)
extensions.AddUint16LengthPrefixed(func(msg *cryptobyte.Builder) {
msg.AddBytes(m.applicationSettings)
})
}
if len(m.customExtension) > 0 {
extensions.AddUint16(utlsFakeExtensionCustom)
extensions.AddUint16LengthPrefixed(func(msg *cryptobyte.Builder) {
msg.AddBytes(m.customExtension)
})
}
})
})
m.raw, err = builder.Bytes()
return m.raw, err
}
func (m *utlsClientEncryptedExtensionsMsg) unmarshal(data []byte) bool {
*m = utlsClientEncryptedExtensionsMsg{raw: data}
s := cryptobyte.String(data)
var extensions cryptobyte.String
if !s.Skip(4) || // message type and uint24 length field
!s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() {
return false
}
for !extensions.Empty() {
var extension uint16
var extData cryptobyte.String
if !extensions.ReadUint16(&extension) ||
!extensions.ReadUint16LengthPrefixed(&extData) {
return false
}
switch extension {
case utlsExtensionApplicationSettings:
m.hasApplicationSettings = true
m.applicationSettings = []byte(extData)
default:
// Unknown extensions are illegal in EncryptedExtensions.
return false
}
}
return true
}
|
Java
|
UTF-8
| 4,264 | 1.820313 | 2 |
[] |
no_license
|
package com.tencent.mm.plugin.backup.h;
import com.tencent.mm.bp.a;
import e.a.a.b;
import java.util.LinkedList;
public final class r extends a {
public String ID;
public long kyX;
public int kza;
public int kzb;
public int kzc;
public long kzd;
public long kze;
public LinkedList<t> kzp = new LinkedList();
public LinkedList<t> kzq = new LinkedList();
protected final int a(int i, Object... objArr) {
int h;
byte[] bArr;
if (i == 0) {
e.a.a.c.a aVar = (e.a.a.c.a) objArr[0];
if (this.ID == null) {
throw new b("Not all required fields were included: ID");
}
if (this.ID != null) {
aVar.g(1, this.ID);
}
aVar.fX(2, this.kza);
aVar.fX(3, this.kzb);
aVar.fX(4, this.kzc);
aVar.S(5, this.kyX);
aVar.S(6, this.kzd);
aVar.S(7, this.kze);
aVar.d(8, 8, this.kzp);
aVar.d(9, 8, this.kzq);
return 0;
} else if (i == 1) {
if (this.ID != null) {
h = e.a.a.b.b.a.h(1, this.ID) + 0;
} else {
h = 0;
}
return (((((((h + e.a.a.a.fU(2, this.kza)) + e.a.a.a.fU(3, this.kzb)) + e.a.a.a.fU(4, this.kzc)) + e.a.a.a.R(5, this.kyX)) + e.a.a.a.R(6, this.kzd)) + e.a.a.a.R(7, this.kze)) + e.a.a.a.c(8, 8, this.kzp)) + e.a.a.a.c(9, 8, this.kzq);
} else if (i == 2) {
bArr = (byte[]) objArr[0];
this.kzp.clear();
this.kzq.clear();
e.a.a.a.a aVar2 = new e.a.a.a.a(bArr, unknownTagHandler);
for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) {
if (!super.a(aVar2, this, h)) {
aVar2.cKx();
}
}
if (this.ID != null) {
return 0;
}
throw new b("Not all required fields were included: ID");
} else if (i != 3) {
return -1;
} else {
e.a.a.a.a aVar3 = (e.a.a.a.a) objArr[0];
r rVar = (r) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList JD;
int size;
a tVar;
e.a.a.a.a aVar4;
boolean z;
switch (intValue) {
case 1:
rVar.ID = aVar3.AEQ.readString();
return 0;
case 2:
rVar.kza = aVar3.AEQ.rz();
return 0;
case 3:
rVar.kzb = aVar3.AEQ.rz();
return 0;
case 4:
rVar.kzc = aVar3.AEQ.rz();
return 0;
case 5:
rVar.kyX = aVar3.AEQ.rA();
return 0;
case 6:
rVar.kzd = aVar3.AEQ.rA();
return 0;
case 7:
rVar.kze = aVar3.AEQ.rA();
return 0;
case 8:
JD = aVar3.JD(intValue);
size = JD.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) JD.get(intValue);
tVar = new t();
aVar4 = new e.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = tVar.a(aVar4, tVar, a.a(aVar4))) {
}
rVar.kzp.add(tVar);
}
return 0;
case 9:
JD = aVar3.JD(intValue);
size = JD.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) JD.get(intValue);
tVar = new t();
aVar4 = new e.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = tVar.a(aVar4, tVar, a.a(aVar4))) {
}
rVar.kzq.add(tVar);
}
return 0;
default:
return -1;
}
}
}
}
|
JavaScript
|
UTF-8
| 1,555 | 2.625 | 3 |
[] |
no_license
|
class TallyMap {
constructor(brain, key) {
this.brain = brain;
this.key = key;
}
forUser(uid) {
const userMap = this.brain.get(this.key) || {};
return userMap[uid] || {};
}
modifyTally(uid, key, delta) {
const userMap = this.brain.get(this.key) || {};
const userTally = userMap[uid] || {};
userTally[key] = (userTally[key] || 0) + delta;
if (userTally[key] <= 0) {
delete userTally[key];
}
userMap[uid] = userTally;
this.brain.set(this.key, userMap);
}
topForUser(uid, n, callback) {
const userMap = this.forUser(uid);
const pairs = [];
for (const k in userMap) {
pairs.push([k, userMap[k]]);
}
pairs.sort((a, b) => b[1] - a[1]);
let count = 0;
for (const pair of pairs) {
if (count >= n) {
return;
}
callback(null, ...pair);
count++;
}
}
topForKey(key, n, callback) {
const userMap = this.brain.get(this.key) || {};
const perUserPairs = [];
for (const uid in userMap) {
const tally = userMap[uid][key] || 0;
perUserPairs.push([uid, tally]);
}
perUserPairs.sort((a, b) => b[1] - a[1]);
let count = 0;
for (const pair of perUserPairs) {
if (count >= n) {
return;
}
callback(null, ...pair);
count++;
}
}
static reactionsReceived(robot) {
return new TallyMap(robot.brain, "reactionsReceived");
}
static reactionsGiven(robot) {
return new TallyMap(robot.brain, "reactionsGiven");
}
}
module.exports = {TallyMap};
|
Python
|
UTF-8
| 889 | 2.640625 | 3 |
[] |
no_license
|
# import CoronaEDA2 as ceda
# print(ceda.cities_of_state('Kerala'))
def sum(a, b):
return a + b
# print(sum(3, 3))
# app5 = DjangoDash('vaccine_1')
# vaccine1 = ceda.vaccine_administered('India')
# app5.layout = html.Div(children=[
# html.Br(),
# html.Div(className='card', id='div5', style={'text-align': 'center'}, children=[
# dcc.Graph(figure=vaccine1)
# ]),
# ])
# app6 = DjangoDash('vaccine_2')
# vaccine2 = ceda.vaccine_total_doses('India')
# app6.layout = html.Div(children=[
# html.Br(),
# html.Div(className='card', id='div8', style={'text-align': 'center'}, children=[
# dcc.Graph(figure=vaccine2)
# ]),
# ])
# app7 = DjangoDash('vaccine_3')
# vaccine3 = ceda.aefi('India')
# app7.layout = html.Div(children=[
# html.Br(),
# html.Div(className='card', id='div7', style={'text-align': 'center'}, children=[
# dcc.Graph(figure=vaccine3)
# ]),
# # ])
|
Markdown
|
UTF-8
| 1,040 | 2.890625 | 3 |
[] |
no_license
|
## ScareBnB
[ScareBnB](https://scarebnb-aa.herokuapp.com/) allows users to host or book haunted locations around the world. This website is a mobile first web application using Ruby on Rails for the backend with a Postgres DB. The frontend is built using ReactJS and JQuery.
ScareBnB is a personal project by Hunter Houston
## Stack
- [ ] Ruby on Rails
- [ ] ReactJS
- [ ] Postgres DB
## Landing Page
![ScareBnB Home Page][home page]
## Place
![Detail Page][place show]
## Search
![Search][search]
## Features
- Hosting on Heroku
- Create new accounts and login
- Hosting for Place
- Bookings for Places
- Search (by Location & Availability) with Google Maps
- Reviews
## Design Docs
* [View Wireframes](docs/wireframes)
* [Components Hierarchy](components-hierarchy.md)
* [API endpoints](api-endpoints.md)
* [DB schema](db-schema.md)
* [Sample State](sample-state.md)
[home page]: ./docs/images/home.png "ScareBnB Home Page"
[place show]: ./docs/images/place-show.png "Place Detail Page"
[search]: ./docs/images/search.png "Search"
|
C
|
UTF-8
| 191 | 3.65625 | 4 |
[] |
no_license
|
#include<stdio.h>
int main(){
int n, fat=1;
printf("Digite um núemro inteiro: ");
scanf("%d", &n);
for(int i=n; i>=1; i--){
fat = fat*i;
}
printf("Fatorial = %d\n", fat);
}
|
PHP
|
UTF-8
| 290 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Libraries\Attachmentable;
use App\Attachment;
trait HasAttachments
{
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function attachments()
{
return $this->morphMany(Attachment::class, 'attachmentable');
}
}
|
Python
|
UTF-8
| 217 | 3.15625 | 3 |
[] |
no_license
|
# function to reverse the number
def revNum(n):
pass
# function to check whether the number is prime or not
def isPrime(n):
pass
def main():
# take input
pass
if __name__ == "__main__":
main()
|
C
|
UTF-8
| 491 | 3.28125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void main(){
int n[10];
int i, n_max = 0, n_min = 10;
srand((unsigned)time(NULL));
for(i = 1; i <= 10; i++){
n[i] = rand() % 10 + 1;
printf("%d ", n[i]);
if(n[i] >= n_max){
n_max = n[i];
}
if(n[i] <= n_min){
n_min = n[i];
}
}
printf("\n");
printf("\n");
printf("最大値:%d\n", n_max);
printf("最小値:%d\n", n_min);
}
|
C++
|
UTF-8
| 1,955 | 2.96875 | 3 |
[] |
no_license
|
//
// Created by Florian on 06.12.17.
//
#include "AirConditioner.h"
AirConditioner::AirConditioner(uint8_t dhtPin, uint8_t heatPadPin, uint8_t fanPin, float desiredTemperature,
float temperatureOffset, unsigned long updateTime) {
this->heatPadPin = heatPadPin;
this->fanPin = fanPin;
this->desiredTemperature = desiredTemperature;
this->offset = temperatureOffset;
timer = new Timer(updateTime);
dht = new DHT(dhtPin, DHT_TYPE);
}
void AirConditioner::setup() {
BaseController::setup();
dht->begin();
pinMode(heatPadPin, OUTPUT);
pinMode(fanPin, OUTPUT);
// set everything to off
updateState();
}
void AirConditioner::loop() {
BaseController::loop();
if (timer->elapsed()) {
measure();
updateState();
}
}
void AirConditioner::updateState() {
if (state == ConditionerState::STEADY) {
analogWrite(heatPadPin, 0);
analogWrite(fanPin, 0);
}
if (state == ConditionerState::HEATING) {
analogWrite(heatPadPin, 255);
analogWrite(fanPin, 0);
}
if (state == ConditionerState::COOLING) {
analogWrite(heatPadPin, 0);
analogWrite(fanPin, 255);
}
}
void AirConditioner::measure() {
// reset state
state = ConditionerState::STEADY;
float h = dht->readHumidity();
float t = dht->readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
heatIndex = static_cast<float>(dht->computeHeatIndex(t, h, false));
// check if is range
if (heatIndex < (desiredTemperature - offset))
state = ConditionerState::HEATING;
if (heatIndex > (desiredTemperature + offset))
state = ConditionerState::COOLING;
}
float AirConditioner::getHeatIndex() const {
return heatIndex;
}
AirConditioner::ConditionerState AirConditioner::getState() const {
return state;
}
|
Python
|
UTF-8
| 1,842 | 2.53125 | 3 |
[] |
no_license
|
from selenium import webdriver
from pages.loginfunc.login_page import LoginPage
from utilities.status import Status
import unittest
import pytest
@pytest.mark.usefixtures("oneTimeSetUp", "setUp")
class LoginTests(unittest.TestCase):
@pytest.fixture(autouse=True)
def classSetup(self, oneTimeSetUp):
self.lp = LoginPage(self.driver)
self.ts = Status(self.driver)
# Need to verify two verification points
# 1 fails, code will not go to the next verification point
# If assert fails, it stops current test execution and
# moves toaceEmail() the next test method
@pytest.mark.run(order=1)
def test_invalidLogin(self):
self.lp.login_popup()
self.lp.login("jlmm83@hotmail.com", "test123")
result = self.lp.verifyLoginFailed()
self.ts.mark(result, "error message visible")
result2 = self.lp.verify_forgot_msg("Har du glömt ditt lösenord?")
self.ts.mark(result2, "forgot password msg visible")
#result2 = self.lp.verifyErrorMsg()
#self.ts.markFinal("test_invalidLogin", result, "error does text not visible")
@pytest.mark.run(order=2)
def test_empty_field_error_msg(self):
self.lp.clearfields()
email_required = self.lp.verifyEmailRequired()
self.ts.mark(email_required, "email required msg exist")
password_required = self.lp.verifyPasswordRequired()
self.ts.mark(password_required, "email required mesg exists")
@pytest.mark.run(order=3)
def test_invalid_email(self):
self.lp.enter_invalid_email("jlmm83...", "test123")
email_invalid_msg = self.lp.verifyInvalidEmailMsg()
self.ts.mark(email_invalid_msg, "invalid required msg doesn't exist")
self.ts.markFinal("test_invalid_email", email_invalid_msg, " invalid required email msg doesn't exist")
|
Java
|
UTF-8
| 321 | 2.984375 | 3 |
[] |
no_license
|
package basic_Input;
import java.util.Scanner;
public class B_109 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
System.out.printf("sum = %d%navg = %d", num1+num2+num3, (num1+num2+num3)/3);
}
}
|
Java
|
UTF-8
| 3,424 | 2.671875 | 3 |
[] |
no_license
|
package com.hdlink.online.model;
import com.hdlink.online.defines.ServiceFilterType;
import java.util.*;
/**
* Created by zhongqiling on 14-11-6.
*/
public class CarServiceCenter {
static public String WHOLE = "whole";
//客户端暂存得全部服务
public List<CarService> services = new ArrayList<CarService>();
private List<String> availableSort = Arrays.asList(ServiceFilterType.SORT_DEFAULT,
ServiceFilterType.SORT_DISTANCE, ServiceFilterType.SORT_PRICE);
private String typeCond = ServiceFilterType.ALL;
private String districtCond = ServiceFilterType.ALL;
private String sortCond = ServiceFilterType.SORT_DEFAULT;
static private CarServiceCenter instance = new CarServiceCenter();
static public CarServiceCenter shared(){
return instance;
}
public CarServiceCenter(){
for(int i = 0; i < 3; i++){
services.add(new CarService("111", "洗车", 100, 200));
}
for(int i = 0; i < 5; i++){
services.add(new CarService("222", "保养", 120, 250));
}
services.add(new CarService("333", "维修", 130, 120));
services.add(new CarService("333", "维修", 135, 180));
services.add(new CarService("333", "维修", 160, 400));
}
public List<CarService> get(String sortType){
return get(sortType, null);
}
public List<CarService> get(String filterType, String data){
List<CarService> sortServices = new ArrayList<CarService>();
if(data == null && availableSort.contains(filterType)){
sortCond = filterType;
}
else if(filterType.equals(ServiceFilterType.CARSERVICE_TYPE)){
typeCond = data;
}
else if(filterType.equals(ServiceFilterType.DISTRICT)){
districtCond = data;
}
return get();
}
public List<CarService> get(){
List<CarService> filterServices = new ArrayList<CarService>();
for(CarService service : services) {
if (typeCond != null && !typeCond.equals(ServiceFilterType.ALL) && service.typeId.equals(typeCond))
filterServices.add(service);
}
if(filterServices.size() == 0)
filterServices = services;
if(availableSort.contains(sortCond) && !sortCond.equals(ServiceFilterType.SORT_DEFAULT))
Collections.sort(filterServices, new Comparator<CarService>() {
@Override
public int compare(CarService lhs, CarService rhs) {
int rValue = 0;
int lValue = 0;
if(sortCond.equals(ServiceFilterType.SORT_DISTANCE)){
rValue = rhs.distance;
lValue = lhs.distance;
}
else if(sortCond.equals(ServiceFilterType.SORT_PRICE)){
lValue = lhs.price;
rValue = rhs.price;
}
if(lValue >= 0 && rValue >= 0)
return lhs.distance - rhs.distance;
else if(lhs.distance >= 0)
return -1;
else if(rhs.distance >= 0)
return 1;
else
return 0;
}
});
return filterServices;
}
}
|
Java
|
GB18030
| 870 | 2.390625 | 2 |
[] |
no_license
|
package springloz;
import java.io.Serializable;
/**
* @ԭ maintenanceQuality_table
* @ԭ reason String
@ intflag int --------nochange
*/
public class MaintenanceReason implements Serializable {
private String reason;
private String intflag;
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getIntflag() {
return intflag;
}
public void setIntflag(String intflag) {
this.intflag = intflag;
}
@Override
public String toString() {
return "MaintenanceReason [reason=" + reason + ", intflag=" + intflag
+ "]";
}
public MaintenanceReason(String reason, String intflag) {
super();
this.reason = reason;
this.intflag = intflag;
}
public MaintenanceReason() {
super();
// TODO Auto-generated constructor stub
}
}
|
Java
|
UTF-8
| 1,262 | 3.046875 | 3 |
[] |
no_license
|
package com.interlan.test.test;
import java.time.Clock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Producer {
private SharedTable sharedTable;
public Producer(SharedTable sharedTable) {
// TODO Auto-generated constructor stub
this.sharedTable = sharedTable;
}
public void produce(){
ExecutorService executor = Executors.newFixedThreadPool(10);
for(int i=0; i<10; i++){
executor.submit(new Task());
}
executor.shutdown();
}
public class Task implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized(sharedTable){
System.out.println("Cheking whether table is empty to place the cookie...");
while(!sharedTable.isEmpty()){
try {
System.out.println("table is not empty, so wait for a while");
sharedTable.wait();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Yes, table is empty now, can place the cookeie...");
sharedTable.setCookie("my cookie");
System.out.println("placed the cookie at "+System.currentTimeMillis());
}
}
}
}
}
|
C++
|
UTF-8
| 7,529 | 2.859375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <cmath>
#include "Object.h"
#define REACTION_TIME 0.01
#define GRAVITATION 700
#define sqr(x) (x) * (x)
sf::RenderWindow *Window = nullptr;
Object::Object ():
pos_ (sf::Vector2f ()),
v_ (sf::Vector2f ()),
size_ (sf::Vector2f ()),
m_ (),
friction_ (),
sprite_ (sf::Sprite ())
{
sf::FloatRect size = sprite_.getLocalBounds ();
size_ = {size.width, size.height};
}
Object::Object (sf::Vector2f pos, sf::Vector2f v, float m, float friction, sf::Sprite sprite):
pos_ (pos),
v_ (v),
size_ (sf::Vector2f ()),
m_ (m),
friction_ (friction),
sprite_ (sprite)
{
sf::FloatRect size = sprite_.getLocalBounds ();
size_ = {size.width, size.height};
}
void Object::Draw (sf::RenderWindow *win) const
{
sf::Sprite sprite = sprite_;
sprite.setOrigin (size_.x / 2, size_.y / 2);
sprite.setPosition (pos_);
win->draw (sprite);
}
sf::Vector2f Object::GetNewPosition (float dt) const
{
return sf::Vector2f (pos_.x + v_.x * dt, pos_.y + v_.y * dt + GRAVITATION * dt * dt / 2);
}
sf::Vector2f Object::GetNewSpeed (float dt) const
{
return sf::Vector2f (v_.x, v_.y + GRAVITATION * dt);
}
void Object::Move (float dt, sf::RenderWindow *win)
{
pos_ = GetNewPosition (dt);
v_ = GetNewSpeed (dt);
if ( (GetNewPosition (REACTION_TIME).x - size_.x / 2 <= 0) ||
(GetNewPosition (REACTION_TIME).x + size_.x / 2 >= win->getSize ().x) )
{
v_.x *= -1;
}
if ( (GetNewPosition (REACTION_TIME).y - size_.y / 2 <= 0) ||
(GetNewPosition (REACTION_TIME).y + size_.y / 2 >= win->getSize ().y) )
{
v_.y *= -1;
}
v_.x *= (1 - friction_);
v_.y *= (1 - friction_);
}
void Object::Collide (Object *obstacle)
{
sf::Vector2f diff ({pos_.x - obstacle->pos_.x, pos_.y - obstacle->pos_.y});
sf::Vector2f future_diff ({ GetNewPosition (REACTION_TIME).x - obstacle->GetNewPosition (REACTION_TIME).x,
GetNewPosition (REACTION_TIME).y - obstacle->GetNewPosition (REACTION_TIME).y});
sf::Vector2f momentum ( m_ * v_.x + obstacle->m_ * obstacle->v_.x,
m_ * v_.y + obstacle->m_ * obstacle->v_.y);
sf::Vector2f mass_center_velocity ( momentum.x / (m_ + obstacle->m_),
momentum.y / (m_ + obstacle->m_));
if (size_.x / 2 + obstacle->size_.x / 2 >= abs (future_diff.x) &&
size_.x / 2 + obstacle->size_.x / 2 < abs (diff.x) &&
size_.y / 2 + obstacle->size_.y / 2 >= abs (diff.y))
{
v_.x = - v_.x + 2 * mass_center_velocity.x;
obstacle->v_.x = - obstacle->v_.x + 2 * mass_center_velocity.x;
}
if (size_.y / 2 + obstacle->size_.y / 2 >= abs (future_diff.y) &&
size_.y / 2 + obstacle->size_.y / 2 < abs (diff.y) &&
size_.x / 2 + obstacle->size_.x / 2 >= abs (diff.x))
{
v_.y = - v_.y + 2 * mass_center_velocity.y;
obstacle->v_.y = - obstacle->v_.y + 2 * mass_center_velocity.y;
}
/*
sf::Vector2f diff ({pos_.x - obstacle->pos_.x, pos_.y - obstacle->pos_.y});
sf::Vector2f future_diff ({ pos_.x + v_.x * REACTION_TIME -
( obstacle->pos_.x + obstacle->v_.x * REACTION_TIME),
pos_.y + v_.y * REACTION_TIME -
( obstacle->pos_.y + obstacle->v_.y * REACTION_TIME)});
if (sqr (size_.x / 2 + obstacle->size_.x / 2) +
sqr (size_.y / 2 + obstacle->size_.y / 2) >=
sqr (future_diff.x) + sqr (future_diff.y))
{
std::cout << "{" << future_diff.x << ", " << future_diff.y << "}\n";
if (size_.x / 2 + obstacle->size_.x / 2 >= abs (future_diff.x) &&
size_.x / 2 + obstacle->size_.x / 2 < abs (diff.x))
{
std::cout << i++ << ") x collision\n";
v_.x *= -1;
}
if (size_.y / 2 + obstacle->size_.y / 2 >= abs (future_diff.y) &&
size_.y / 2 + obstacle->size_.y / 2 < abs (diff.y))
{
std::cout << i++ << ") y collision\n";
v_.y *= -1;
}
}
*/
/*
static sf::Clock clock_x, clock_y;
sf::Vector2f diff ({pos_.x - obstacle->pos_.x, pos_.y - obstacle->pos_.y});
sf::Vector2f future_diff ({ pos_.x + v_.x * REACTION_TIME -
( obstacle->pos_.x + obstacle->v_.x * REACTION_TIME),
pos_.y + v_.y * REACTION_TIME -
( obstacle->pos_.y + obstacle->v_.y * REACTION_TIME)});
if (sqr (size_.x / 2 + obstacle->size_.x / 2) +
sqr (size_.y / 2 + obstacle->size_.y / 2) >=
sqr (future_diff.x) + sqr (future_diff.y))
{
float time_x = clock_x.getElapsedTime ().asSeconds ();
float time_y = clock_y.getElapsedTime ().asSeconds ();
std::cout << "{" << future_diff.x << ", " << future_diff.y << "}\n";
std::cout << "time_x: " << time_x << ", time_y: " << time_y << "\n";
if (size_.x / 2 + obstacle->size_.x / 2 >= abs (future_diff.x) &&
size_.x / 2 + obstacle->size_.x / 2 < abs (diff.x) &&
time_x >= REACTION_TIME)
{
std::cout << i++ << ") x collision\n";
v_.x *= -1;
clock_x.restart ();
}
if (size_.y / 2 + obstacle->size_.y / 2 >= abs (future_diff.y) &&
size_.y / 2 + obstacle->size_.y / 2 < abs (diff.y) &&
time_y >= REACTION_TIME)
{
std::cout << i++ << ") y collision\n";
v_.y *= -1;
clock_y.restart ();
}
}
*/
/*
sf::Vector2f diff ({pos_.x - obstacle->pos_.x, pos_.y - obstacle->pos_.y});
// std::cout << "{" << diff.x << ", " << diff.y << "}\n";
if (sqr (size_.x / 2 + obstacle->size_.x / 2) +
sqr (size_.y / 2 + obstacle->size_.y / 2) >=
sqr (diff.x) + sqr (diff.y))
{
if (size_.x / 2 + obstacle->size_.x / 2 >= abs (diff.x))
{
std::cout << "x collision\n";
v_.x *= -1;
}
if (size_.y / 2 + obstacle->size_.y / 2 >= abs (diff.y))
{
std::cout << "y collision\n";
v_.y *= -1;
}
}
*/
}
Killable::Killable ():
Object (),
hp_ ()
{
sf::FloatRect size = sprite_.getLocalBounds ();
size_ = {size.width, size.height};
}
Killable::Killable (sf::Vector2f pos, sf::Vector2f v, float m, float friction, int hp, sf::Sprite sprite):
Object (pos, v, m, friction, sprite),
hp_ (hp)
{
sf::FloatRect size = sprite_.getLocalBounds ();
size_ = {size.width, size.height};
}
void Killable::Move (float dt, sf::RenderWindow *win)
{
pos_ = GetNewPosition (dt);
v_ = GetNewSpeed (dt);
if ( (GetNewPosition (REACTION_TIME).x - size_.x / 2 <= 0) ||
(GetNewPosition (REACTION_TIME).x + size_.x / 2 >= win->getSize ().x) )
{
v_.x *= -1;
hp_--;
}
if ( (GetNewPosition (REACTION_TIME).y - size_.y / 2 <= 0) ||
(GetNewPosition (REACTION_TIME).y + size_.y / 2 >= win->getSize ().y) )
{
v_.y *= -1;
hp_--;
}
v_.x *= (1 - friction_);
v_.y *= (1 - friction_);
}
void Killable::Collide (Object *obstacle)
{
sf::Vector2f diff ({pos_.x - obstacle->pos_.x, pos_.y - obstacle->pos_.y});
sf::Vector2f future_diff ({ GetNewPosition (REACTION_TIME).x - obstacle->GetNewPosition (REACTION_TIME).x,
GetNewPosition (REACTION_TIME).y - obstacle->GetNewPosition (REACTION_TIME).y});
sf::Vector2f momentum ( m_ * v_.x + obstacle->m_ * obstacle->v_.x,
m_ * v_.y + obstacle->m_ * obstacle->v_.y);
sf::Vector2f mass_center_velocity ( momentum.x / (m_ + obstacle->m_),
momentum.y / (m_ + obstacle->m_));
if (size_.x / 2 + obstacle->size_.x / 2 >= abs (future_diff.x) &&
size_.x / 2 + obstacle->size_.x / 2 < abs (diff.x) &&
size_.y / 2 + obstacle->size_.y / 2 >= abs (diff.y))
{
v_.x = - v_.x + 2 * mass_center_velocity.x;
obstacle->v_.x = - obstacle->v_.x + 2 * mass_center_velocity.x;
}
if (size_.y / 2 + obstacle->size_.y / 2 >= abs (future_diff.y) &&
size_.y / 2 + obstacle->size_.y / 2 < abs (diff.y) &&
size_.x / 2 + obstacle->size_.x / 2 >= abs (diff.x))
{
v_.y = - v_.y + 2 * mass_center_velocity.y;
obstacle->v_.y = - obstacle->v_.y + 2 * mass_center_velocity.y;
}
}
|
Java
|
UTF-8
| 4,514 | 2.25 | 2 |
[
"MIT"
] |
permissive
|
package org.kelab.admin.ke.role;
import java.util.ArrayList;
import java.util.List;
import org.kelab.admin.ke.menu.MenuAdminService;
import org.kelab.admin.ke.user.UserAdminService;
import org.kelab.model.KeRole;
import org.kelab.model.KeRoleMenu;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
public class RoleAdminService {
public static final RoleAdminService me = new RoleAdminService();
public static MenuAdminService menuSrv = new MenuAdminService();
final static KeRole dao = new KeRole().dao();
final String roleCacheName = "keRole";
/**
* 加载
* @param roleid
* @return 如果roleid为0,则返回所有
*/
public List<KeRole> findByRoleId(int roleId){
List<KeRole> roleL = new ArrayList<KeRole>();
String sql ="";
if(roleId == 0){
sql = "select * from ke_role order by id asc";
roleL = dao.find(sql);
}else
roleL.add(dao.findById(roleId));
for(KeRole keRole : roleL){
keRole.put("menuL",menuSrv.findMenuByRoleId(keRole.getId()));
keRole.put("userCount",UserAdminService.me.findUserByRoleId(keRole.getId()).size());
}
return roleL;
}
/**
* 保存信息
* @param keROle对象
* @return 结果信息
*/
public Ret save(KeRole keRole, String[] roleMenu){
if (isExists(keRole,0)) {
return Ret.fail("msg", "该名称已经存在");
}
keRole.save();
//保存菜单关联
int currRoleId = findLastOne().getId();
for(String menuId : roleMenu){
int currMenuId = Integer.parseInt(menuId);
new KeRoleMenu().set("role_id",currRoleId)
.set("menu_id",currMenuId).save();
}
if(keRole.getId() != null)
RoleAdminService.me.clearCache(); // 清缓存
return Ret.ok();
}
/**
* 更新
* @param keRole
* @result 结果
*/
public Ret update(KeRole keRole, String[] roleMenu){
if(isExists(keRole,keRole.getId())){
return Ret.fail("msg","改名成已经存在");
}
keRole.update();
List<KeRoleMenu> reMeL = KeRoleMenu.dao.find("select * from ke_role_menu where role_id =?",keRole.getId());
for(String newId: roleMenu){//检查新增
int newMeId = Integer.parseInt(newId);
boolean isHave = false;
for(KeRoleMenu oldRM : reMeL){
if(newMeId == oldRM.getMenuId()){
isHave = true;
break;
}
}
if(!isHave){
new KeRoleMenu().set("role_id", keRole.getId())
.set("menu_id", newMeId).save();
}
}
for(KeRoleMenu oldRM : reMeL){//检查删除
boolean isHave = false;
for(String newId: roleMenu){
int newMeId = Integer.parseInt(newId);
if(newMeId == oldRM.getMenuId()){
isHave = true;
break;
}
}
if(!isHave){
oldRM.delete();
}
}
return Ret.ok();
}
/**
* 检查是否存在
* @param keRole
* @param oldId,旧的ID,如果为0,则为新增,否则检查除自己以外的是否有重复
* @return 是否存在重复名称
*/
private boolean isExists(KeRole keRole, int oldId) {
String strWhere = "";
if(oldId > 0)
strWhere = " and id <>" + oldId;
String sql = "select id from ke_role where role_name=? "+strWhere+" limit 1";
return Db.queryInt(sql , keRole.getRoleName()) != null;
}
/**
* 找到最新一条信息
*/
public KeRole findLastOne(){
String sql = "select * from ke_role order by id desc limit 1";
List<KeRole> roleL = dao.find(sql);
if(roleL.size()>0)
return roleL.get(0);
else
return null;
}
/**
* 删除指定id的信息
* @param id
* @return 删除结果
*/
public Ret delete(String ids){
int rt = 0;
String msg = "";
for(String obj :ids.split(",")){
int id = Integer.parseInt(obj);
String checkSql = "select * from ke_user where user_role_id = ?";
if(id > 0 && Db.find(checkSql,id).size() == 0){
Db.update("delete from ke_role_menu where role_id=?",id);
Db.update("delete from ke_role where id=?",id);
rt=1;
}else{
rt = 0;
msg = "部分记录关联数据,不能删除!";
}
}
if(rt == 1)
return Ret.ok();
else
return Ret.fail("msg", msg);
}
public List<KeRoleMenu> findRoleMenu(int menuId, int roleId){
String sql = "select * from ke_role_menu where role_id =? and menu_id = ?";
return KeRoleMenu.dao.find(sql,roleId,menuId);
}
public void clearCache() {
CacheKit.removeAll(roleCacheName);
}
}
|
Python
|
UTF-8
| 6,239 | 2.53125 | 3 |
[
"BSD-3-Clause",
"CC0-1.0",
"MIT",
"Unlicense",
"Apache-2.0"
] |
permissive
|
#!python3
#encoding:utf-8
import dataset
from bs4 import BeautifulSoup
import time
import os.path
import requests
class GnuSite(object):
def __init__(self, path_gnu_licenses_sqlite3):
self.__db_license = dataset.connect('sqlite:///' + path_gnu_licenses_sqlite3)
def GetAll(self):
for lang in self.__GetAllLanguages():
self.processing_language_code = lang
soup = BeautifulSoup(self.__GetHtmlString(lang), 'html.parser')
for div in soup.select('div.big-section'):
typeName = self.__GetSection(div)
print(typeName)
def __GetAllLanguages(self):
langs = []
soup = BeautifulSoup(self.__GetHtmlString('en'), 'html.parser')
for span in soup.find('div', id='translations').find('p').find_all('span'):
langs.append(span.find('a').get('lang'))
print(span.find('a').get('lang'))
return langs
def __GetHtmlString(self, lang):
url = 'https://www.gnu.org/licenses/license-list.{0}.html'.format(lang)
path_this_dir = os.path.abspath(os.path.dirname(__file__))
file_name = os.path.basename(url)
file_path = os.path.join(path_this_dir, file_name)
if os.path.isfile(file_path):
print('ファイル読み込み-----------------------')
with open(file_path, 'rb') as f:
html_str = f.read()
else:
print('HTTPリクエスト-----------------------')
time.sleep(2)
r = requests.get(url)
html_str = r.content
with open(file_path, 'wb') as f:
f.write(html_str)
return html_str
def __GetSection(self, div):
h3Id = div.find('h3').get('id')
print('{0},{1}'.format(h3Id, div.find('h3').string.strip()))
if 'SoftwareLicenses' == h3Id:
for sub in div.find_all_next('div', class_='big-subsection'):
h4Id = sub.find('h4').get('id')
if 'GPLCompatibleLicenses' == h4Id:
self.__GetDl(sub, 'software')
elif 'GPLIncompatibleLicenses' == h4Id:
self.__GetDl(sub, 'software')
elif 'NonFreeSoftwareLicenses' == h4Id:
self.__GetDl(sub, 'software')
else:
break
elif 'DocumentationLicenses' == h3Id:
for sub in div.find_all_next('div', class_='big-subsection'):
h4Id = sub.find('h4').get('id')
if 'FreeDocumentationLicenses' == h4Id:
self.__GetDl(sub, 'document')
elif 'NonFreeDocumentationLicenses' == h4Id:
self.__GetDl(sub, 'document')
else:
break
elif 'OtherLicenses' == h3Id:
for sub in div.find_all_next('div', class_='big-subsection'):
h4Id = sub.find('span').find('a').get('href')
if None is not sub.find('h4').string:
print('{0},{1}'.format(h4Id, sub.find('h4').string.strip()))
else:
print('{0},{1}'.format(h4Id, sub.find('h4').string))
if '#OtherLicenses' == h4Id:
print(h4Id + '---------------')
dl = self.__GetDl(sub, 'other')
dl = self.__GetDl(dl, 'other')
dl = self.__GetDl(dl, 'other')
dl = self.__GetDl(dl, 'other')
elif '#Fonts' == h4Id:
print(h4Id + '---------------')
dl = self.__GetDl(sub, 'other.font')
dl = self.__GetDl(dl, 'other.font')
elif '#OpinionLicenses' == h4Id:
print(h4Id + '---------------')
self.__GetDl(sub, 'other.opinion')
elif '#Designs' == h4Id:
print(h4Id + '---------------')
self.__GetDl(sub, 'other.design')
def __GetDl(self, div, targetValue):
dl = div.find_next('dl')
if None is dl:
return
print("dtの数={0}".format(len(dl.find_all('dt'))))
print("ddの数={0}".format(len(dl.find_all('dd'))))
for dt in dl.find_all('dt'):
for a in dt.find_all('a'):
if None is not a.string:
name = a.string.strip().replace('\n', '')
try:
if 'en' == self.processing_language_code:
self.__db_license['Licenses'].insert(self.__CreateLicense(dl, dt, targetValue))
license = self.__db_license['Licenses'].find_one(HeaderId=self.__GetHeaderId(dt))
if None is self.__db_license['Multilingual'].find_one(LicenseId=license['Id'], LanguageCode=self.processing_language_code):
self.__db_license['Multilingual'].insert(self.__CreateMultilingual(dt, name, self.__db_license['Licenses'].find_one(HeaderId=self.__GetHeaderId(dt))['Id']))
except Exception as e:
print('%r' % e)
return dl
def __CreateLicense(self, dl, dt, targetValue):
print(self.__GetHeaderId(dt))
record = dict(
HeaderId=self.__GetHeaderId(dt),
ColorId=self.__db_license['Colors'].find_one(Key=dl.get('class'))['Id'],
Target=targetValue,
Url=dt.find('a').get('href')
)
print(record)
return record
def __CreateMultilingual(self, dt, name, license_id):
record = dict(
LicenseId=license_id,
LanguageCode=self.processing_language_code,
Name=name,
Description=dt.find_next('dd').decode_contents(formatter="html").strip(),
)
print(record)
return record
def __GetHeaderId(self, dt):
headerId = ''
if None is dt.find('span'):
return None
for a in dt.find('span').find_all('a'):
headerId += a.string + ','
return headerId[:-1]
if __name__ == '__main__':
gnu = GnuSite(
path_gnu_licenses_sqlite3 = './GNU.Licenses.sqlite3'
)
gnu.GetAll()
|
Swift
|
UTF-8
| 1,124 | 2.734375 | 3 |
[] |
no_license
|
//
// options.swift
// Game jr.
//
// Created by WALLS BENAJMIN A on 4/11/16.
// Copyright © 2016 WALLS BENAJMIN A. All rights reserved.
//
import Foundation
import SpriteKit
class OptionsMenu : SKScene {
var backButton : SKLabelNode?
override func didMoveToView(view: SKView) {
backButton = self.childNodeWithName("SKLbackToMain") as! SKLabelNode!
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
print("X:\(location.x) Y:\(location.y)")
print(nodeAtPoint(location).name)
if nodeAtPoint(location).name == backButton!.name {
print("back button clicked")
//load options scene
let mainScene = MainMenu(fileNamed: "MainMenu")
mainScene?.scaleMode = .AspectFill
self.view?.presentScene(mainScene!, transition: SKTransition.doorsCloseHorizontalWithDuration(0.9))
}
}
}
}
|
Python
|
UTF-8
| 1,501 | 2.640625 | 3 |
[] |
no_license
|
import numpy as np
def compute_essential_matrix(points_1, points_2, k_1, k_2, normalize=True):
f = fundamental_eight_point(points_1, points_2, normalize)
return np.matmul(k_2.T, np.matmul(f, k_1))
def fundamental_eight_point(points_1, points_2, normalize):
if normalize:
t_1, t_2 = normalization_transforms(points_1, points_2)
points_1_norm = np.matmul(t_1, points_1.T).T
points_2_norm = np.matmul(t_2, points_2.T).T
else:
points_1_norm = points_1
points_2_norm = points_2
n_points = points_1_norm.shape[0]
q = np.zeros((n_points, 9), dtype=np.float)
for i, (point_1, point_2) in enumerate(zip(points_1_norm, points_2_norm)):
q[i, :] = np.kron(point_1, point_2)
_, _, vh = np.linalg.svd(q)
f = vh[-1, :].reshape((3, 3))
u, s, vt = np.linalg.svd(f)
s[-1] = 0.0
f = np.matmul(u, np.matmul(np.diag(s), vt))
if normalize:
f = np.matmul(t_2.T, np.matmul(f, t_1))
return f / f[-1, -1]
def normalization_transforms(points_1, points_2):
mu_1 = np.mean(points_1[:, :-1], axis=0)
s_1 = np.sqrt(2) / np.std(points_1[:, :-1])
mu_2 = np.mean(points_2[:, :-1], axis=0)
s_2 = np.sqrt(2) / np.std(points_2[:, :-1])
t_1 = np.array([[s_1, 0, -s_1 * mu_1[0]],
[0, s_1, -s_1 * mu_1[1]],
[0, 0, 1]])
t_2 = np.array([[s_2, 0, -s_2 * mu_2[0]],
[0, s_2, -s_2 * mu_2[1]],
[0, 0, 1]])
return t_1, t_2
|
Java
|
UTF-8
| 889 | 2.109375 | 2 |
[] |
no_license
|
import allen.dao.UserMapper;
import allen.pojo.User;
import allen.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
/**
* @author Allen
* @date 2020/11/13 10:59
*/
public class UserMapperTest {
@Test
public void getUserList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void deleteById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.deleteById(8);
sqlSession.commit();
sqlSession.close();
}
}
|
Markdown
|
UTF-8
| 9,684 | 2.71875 | 3 |
[] |
no_license
|
---
layout: default
title: "2789.周恩来在卫生系统“打倒老爷卫生部大会”上的讲话"
weight: 2789
---
1967-9-27
周恩来在卫生系统“打倒老爷卫生部大会”上的讲话
周恩来
1967.09.27
同志们,战友们:
在我们今天这个联合大会上,我应该首先代表我们伟大领袖毛主席和他的亲密战友林副主席(热烈鼓掌)、代表党中央、国务院、中央军委、中央文革小组问你们好!祝贺你们。(热烈鼓掌,口号)你们这次由卫生部的两派进行在大批判的运动当中,进行了革命的大联合,也推动了卫生系统的革命大联合。这是由于你们过去坚持反对我们党内一小撮的走资派,刘、邓、陶,同时结合到他们在卫生系统的一些黑指示,特别是要打垮老爷卫生部。在这样的一个基础上,所以你们有利于团结,有利于联合啦。(热烈鼓掌,口号)
但是,虽然你们总的、主要的矛头是对准党内一小撮的走资派和老爷卫生部,但是呢,对卫生系统的一个时期执行反动路线这个问题上,双方争论不休,这样一个问题,互相打架,势不两立(众笑),因此我想了一个办法,到农村去接近,我们那个地方最人口少而医疗人员又少、医药又少的地区,去接触我们最劳苦的贫下中农的广大群众,派了两个医疗队,当时还是分开来派的。每方三百多人,搞了接近两个多月,这样一个实践推动了你们认识了如何怎么深入到农村实现毛主席所号召的我们要为全国广大占85%以上的农民服务。而不是留在城市里头,组织老爷的卫生部,只为高级人员服务。你们真正做到了这个实践,就推动了你们认识革命的大联合的必要了。(口号)我这个指示就是毛主席的指示吆!你们亲自去实践了,但这仅仅是开始。现在第二个医疗队,又是从两个方面、两大派派出去的,可是这次不同了,到了××得了消息,毛主席的号召在大方向是一致的、在毛泽东思想的基础上,应该实现大联合,不要势不两立。因此他们首先在××就通过了两个医疗队合成一个医疗队了。(热烈鼓掌,口号)这就是毛主席的思想。毛主席告诉我们要改正错误的思想,要批判反动路线,就要自己在实践斗争中证明认识。因此,卫生系统应该集中力量、集中目标、响应毛主席的伟大战略部署,紧紧地跟着毛主席,牢牢地掌握革命斗争大方向,把你们的斗争矛头对准党内一小撮的走资派刘、邓、陶,特别是把他们在卫生系统一些黑指示,一些错误的东西,揭发出来。这样子来结合你们本单位的斗批改。
第二,就是要真正打垮老爷卫生部。这不是用一句话,一个口号或仅仅批判几个人就够了的。应该从头、从上而下,都要把老爷卫生部的作风都要打倒。所以具体的对象是打倒卫生系统的几个头头,具体的工作呢,就是真正的把我们卫生系统的,不管是行政单位的,医疗单位的,教育单位的,生产单位的,都要按照毛主席的最高指示到广大的贫苦群众中去,到那个没有医生、没有医药的地方,农村中去,或是缺少医药缺少卫生的农村中去。这是你们最主要的服务的方向。当然啦,也要留一部分在城市里为城市里广大的劳动人民服务啦,为机关工作人员服务啦。但是这个经常地不要忘记,每一个医务行政人员、医务医疗人员都要记住,你们一年都要以一定的时间,规定出来,到农村去服务。从这样的实践中,就懂得怎么样子来改造、斗批改了,就是改造我们卫生系统的组织编制,怎么来改造我们卫生的教育,改造我们医疗制度。这一切都是属于打倒老爷卫生部的范围。只批倒几个人,只是打垮老爷卫生部的开始。更重要的是在实践中联系到本单位的斗批改,把我们整个卫生系统,过去学了苏联的那一套不适合为广大群众服务的制度,给以彻底的改造。只有这样子,才能彻底打垮老爷卫生部!(热烈鼓掌,口号)
当然,同时,第三也要批判你们本单位过去执行的那些执行反动路线的那些负责人。但是这个只要他不是属于修正主义分子,而是一个时期在执行上头的反动路线的错误,应该容许人家自我批评,容许人家改正错误。不能跟前两种看成一起。
要作这样一些工作,那就要照我们伟大领袖最近从外地巡视回来告诉我们的因为革命大联合一定要在我们伟大的毛泽东思想的原则基础上,一定要按照毛主席指示的大方向,就是我们革命斗争大方向一致的基础上来大联合。而做到这点,并不是要等待这一切都做好了才能联合,就是要在实践中来联合,所以毛主席指示,我们的工人阶级不需要一定要形成两个势不两立的两大派嘛,组织可以有多种多样,但是在这个按高举毛泽东思想伟大红旗,紧紧地跟随毛主席的伟大战略部署,牢牢地掌握革命斗争的大方向,这是我们大联合的基础和前提嘛!但是怎么样来证明我们是这样呢?就是通过实践。通过实践呢,毛主席提出了四个字,勉励我们,要实现大联合的时候,就是要“斗私,批修”。(热烈鼓掌,口号)另外,我们卫生系统的也好,其他的系统也好,甚至于就在工厂里产业工人也好,他们不能不受社会上各种思潮的影响,何况我们。就是本单位也还有走资派也许还没有抓出来,或者还有后头有坏人挑拨。如果这样,“私”字就很容易在各种革命组织里发展起来,在人们头脑里存在着。因此我们一定要认识,这种“私”字,这种小资产阶级派性,在我们许多革命组织中存在的。个人主义呀,小团体主义呀,山头主义呀,派别观念呀,甚至发展到怀疑一切,打倒一切啦,无政府思潮啦等等。这些都是一种“私”字,都从资产阶级教育那里受得来的,或者社会受影响的,或者社会上旧的习惯势力影响我们的。不把这个“私”字去掉,就很难真正地高举毛泽东思想伟大红旗,就很难做到无产阶级党性高于一切,所以就必须首先斗掉“私”,首先斗掉自己头脑里的、工作上、作风上的“私”字(热烈鼓掌,口号)。而斗争这个“私”字呢,办法应该一般的革命组织互相的关系和在革命组织内部的相互关系,应该照人民内部矛盾来解决嘛。按照毛主席指示的方针嘛,“团结──批评──团结”。只要我们本着在毛泽东思想原则基础上团结起来的愿望,那我们就必须通过批评,而批评主要是自我批评。毛主席告诉我们,对立的两方,如果是人民内部矛盾,应该先批评自己的错误,多看人家的长处,对方也是如此。这样子就可以取人家之长,去自己之短,取长补短嘛。双方都如此,不就可以联合起来了吗!(热烈鼓掌,口号)所以,在这个“斗私”的方面,要靠两大派的群众组织相互的批评自己,团结别人,这个团结是要在毛泽东思想原则基础上,通过批评、自我批评,这样推动了大家在新的基础上,因为这样才真正地站到我们伟大的毛泽东思想红旗之下嘛!在这样的基础上就能够真正达到新的团结啦。
有这样的基础,有这样的实践,那你“批修”也就会批得彻底了。所以第二两个字“批修”,批这一小撮党内走资派,刘、邓、陶,结合到卫生系统的刘邓的、陶的一些黑指示,也结合本单位的斗批改,也结合整个卫生系统的打垮老爷卫生部。这样子就是“批修”的问题嘛。因此,“斗私,批修”就是这次主席回来指示我们,要告诉大家的。(热烈鼓掌,口号)所以要在真正的“斗私,批修”的这样一个伟大的毛泽东思想基础上,你们才真正能够表现出自己能够称得起做一个无产阶级革命派。(热烈鼓掌)否则毛主席说了,你们自封为无产阶级革命派,或者以自己为核心,这些办法都是不对的,这个是做不通的。(热烈鼓掌)一定要在毛主席最高指示这样一个原则基础上联合起来,这才能真正的实现了无产阶级革命派联合起来的口号。(热烈鼓掌)
当然啦,当前还有你们很急迫的任务了,因为面临着国庆节,你们要为国庆节服务。所有卫生系统工作的都更忙一些。抓革命促业务在你们这个地方特别是促生产,卫生的、医药卫生材料上的生产,那更急迫了。因此,所以你们的时间宝贵。我们时间也不多,就说到这儿为止。(热烈鼓掌,口号)好!(口号)
让我们高举伟大的毛泽东思想红旗,在毛主席最高指示“斗私,批修”的基础上,无产阶级革命派联合起来!(热烈鼓掌,口号)
我们高呼:
毛主席的无产阶级革命路线胜利万岁!
无产阶级文化大革命胜利万岁!
无产阶级专政万岁!
伟大的战无不胜的毛泽东思想万岁!
伟大的中国共产党万岁!
我们伟大的领袖毛主席万岁!万岁!万万岁!
(一九六七年九月二十七日)卫生部无产阶级革命派联合总部整理
CCRADB
|
Markdown
|
UTF-8
| 5,606 | 2.625 | 3 |
[] |
no_license
|
# Parameters
A default parameter configuration is available in `default.yaml`. The parameters are categorized after model components where e.g. `asr.opt` contains parameters relvant for the ASR optimizer, `asr.mdl` contains ASR model parameters and `asr` contains other parameters in general.
A couple of other hyperparameters that are related to preprocessing and more technial details of training are found in `./src/preprocess.py`.
## Common parameters
These parameters should be configured for each model component indvidually.
Parameter | Description
------------ | --------------
opt.type | The optimizer to use for training, see PyTorch documentation for more information
opt.learning_rate | The initial learning rate to use for the optimizer. Depending on the optimizer used, this might not be applicable but is sufficient for e.g. ADAM or ADADELTA.
train_index * | Path to training index produced by `./src/preprocess.py`.
valid_index * | Path to validation index
test_index * | Path to test index
(*) Currently, the baseline ASR is the only model that supports testing. It is important that these indexes are correctly sorted since we use `torch.pack_padded_sequences` which speeds up training. The sequences to train on must be sorted in decreasing order of original length on the padded axis. So, for e.g. the baseline ASR the index must be sorted by `unpadded_num_frames` and `.src.preprocess.sort_index() can be used exactly for this.
In most cases the index should be sorted by `unpadded_num_frames` but if training is performed on padded text tokens, then sort the index by `s_len` using the same function.
Some additional parameters can be set for each model component seperately and have default values if not set.
Parameter | Description | Default value
------------ | -------------- | --------------
valid_step | Number of steps between validation measurements | 500
save_step | Number of steps between saving the most current version of the model | 1000
logging_step | Number of steps between verbose logging. Type of training determines what type of logging is output | 250
train_batch_size | Training batch size | 32
valid_batch_size | Validation batch size | 32
test_batch_size | Test batch size | 1
n_epohcs | Number of training epochs | 5
## ASR baseline specific parameters
Parameter | Description
------------ | --------------
mdl.encoder_state_size | The state size of each pBLSTM unit in the ASR encoder
mdl.mlp_out_size | Output dimensions of the Φ and Ψ attention projection networks
mdl.decoder_state_size | The state sie of each LSTM unit in the ASR decoder
mdl.tf_rate | Teacher forcing rate of the decoder
mdl.feature_dim | The feature dimension of the input. This should match with `.src.preprocess.N_DIMS`
decode_beam_size | Number of hypothesis to consider at each level of beam search
decode_lm_weight | The weight that determines the influence of the language model during decoding. See thesis for more information
wer_step | The number of steps between each measure of WER on the training set.
## Speech Autoencoder specific parameters
The speech autoencoder contains a CNN encoder. Here we only consider CNNs with 3 layers of convolutional -> batch norm -> RELU -> max pool.
Parameter | Description
------------ | --------------
mdl.kernel_sizes | The 2D kernel sizes of each convolutional layer.
mdl.num_filters | The number of filters in each convolutional layer
mdl.pool_kernel_sizes | The 2D pooling kernels in each pooling layer. We aim to pool over the entire feature in the last pooling layer so the last pool kernel size has to be chosen with that in mind. In the default configuration we choose [2000, 40] since it approximately the size of the largest Malromur utterance.
## Text Autoencoder specific parameters
Parameter | Description
------------ | --------------
mdl.state_size | The state size of each BLSTM unit in the text encoder
mdl.emb_dim | The character embedding dimensionality
mdl.num_layers | Number of BLSTM layers in the encoder
## Adversarial training specific parameters
For adversarial training we configure the optimizers of both the discriminator, __D_optimizer__, and the generator, __G_optimizer__.
Parameter | Description
------------ | --------------
mdl.hidden_dim | The hidden dimension of the simple discriminator.
## Language model specific parameters
Parameter | Description
------------ | --------------
mdl.hidden_size | The state size of the RNN used in the language model. This is also used as the output dimension of the character embeddings used in the language model.
mdl.tf_rate | The teacher forcing rate used during decoding.
chunk_size | The size of each training sample.
## Seed training
Parameter | Description
------------ | --------------
its | The number of iterations of the main training loop to perform
## Preprocessing parameters
This is a short description of the parameters that are found in `./src/preprocess.py`.
Parameter | Description
------------ | --------------
CHARS | The latin alphabet and digits
ICE_CHARS | Special Icelandic characters
SPECIAL_CHARS | Some tokens that are likely to affect pronounciation.
SOS_TKN | Appended to the start of each sentence
EOS_TKN | Appended to the end of each sentence
UNK_TKN | Tokens in the unprocessed text that are not covered by CHARS/ICE_CHARS/SPECIAL_CHARS are replaced with this token
N_JOBS | no. jobs to run in parallel when writing the index
N_DIMS | no. frequency coefficients in the spectrograms
WIN_SIZE | size of window in STFT
STRIDE | stride of the window
TEXT_XTSN |extension of token files (if applicable)
|
Go
|
UTF-8
| 1,029 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"time"
"github.com/valyala/fasthttp"
)
func convertPDF(ctx *fasthttp.RequestCtx) {
if string(ctx.Method()) != "POST" {
ctx.Error("post only", 405)
return
}
if ctx.PostBody() == nil {
ctx.Error("Body is missing", 400)
return
}
tmpFileName := "/tmp/pdftotext.tmp" + time.Now().String()
bodyBytes := ctx.PostBody()
err := ioutil.WriteFile(tmpFileName, bodyBytes, 0600)
if err != nil {
ctx.Error("Failed to open the file for writing", 500)
return
}
defer os.Remove(tmpFileName)
// log.Printf("File uploaded successfully.")
body, err := exec.Command("pdftotext", "-nopgbrk", "-enc", "UTF-8", tmpFileName, "-").Output()
if err != nil {
log.Printf("pdftotext error: %s", err)
ctx.Error(err.Error(), 500)
}
fmt.Fprintf(ctx, string(body))
// log.Printf("File successfully converted.")
}
func main() {
h := convertPDF
if err := fasthttp.ListenAndServe(":5000", h); err != nil {
log.Fatalf("Error in ListenAndServe: %s", err)
}
}
|
C++
|
UTF-8
| 1,960 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
////////////////////////////////////////////////////////////////
// MSDN Magazine -- July 2001
// If this code works, it was written by Paul DiLascia.
// If not, I don't know who wrote it.
// Compiles with Visual C++ 6.0. Runs on Win 98 and probably Win 2000 too.
// Set tabsize = 3 in your editor.
//
#include "WinMgr.h"
//////////////////
// Construct from args
//
WINRECT::WINRECT(WORD f, int id, LONG p)
{
memset(this, 0, sizeof(WINRECT));
flags = f;
nID = (UINT)id;
param = p;
}
//////////////////
// Get the parent of a given WINRECT. To find the parent, chase the prev
// pointer to the start of the list, then take the item before that in
// memory.
//
WINRECT* WINRECT::Parent()
{
WINRECT* pEntry = NULL;
for (pEntry=this; pEntry->Prev(); pEntry=pEntry->Prev()) {
; // go backwards to the end
}
// the entry before the first child is the group
WINRECT *parent = pEntry-1;
assert(parent->IsGroup());
return parent;
}
//////////////////
// Get group margins
//
BOOL WINRECT::GetMargins(int& w, int& h)
{
if (IsGroup()) {
w=(short)LOWORD(param);
h=(short)HIWORD(param);
return TRUE;
}
w=h=0;
return FALSE;
}
//////////////////
// Initialize map: set up all the next/prev pointers. This converts the
// linear array to a more convenient linked list. Called from END_WINDOW_MAP.
//
WINRECT* WINRECT::InitMap(WINRECT* pWinMap, WINRECT* parent)
{
assert(pWinMap);
WINRECT* pwrc = pWinMap; // current table entry
WINRECT* prev = NULL; // previous entry starts out none
while (!pwrc->IsEndGroup()) {
pwrc->prev=prev;
pwrc->next=NULL;
if (prev)
prev->next = pwrc;
prev = pwrc;
if (pwrc->IsGroup()) {
pwrc = InitMap(pwrc+1,pwrc); // recurse! Returns end-of-grp
assert(pwrc->IsEndGroup());
}
++pwrc;
}
// safety checks
assert(pwrc->IsEndGroup());
assert(prev);
assert(prev->next==NULL);
return parent ? pwrc : NULL;
}
|
Python
|
UTF-8
| 548 | 3.796875 | 4 |
[] |
no_license
|
import random
def get_valid(message):
value = int(input(message))
while not(value > 0):
value = int(input('Введите корректное (целое, положительное) значение: '))
return value
def play():
#print('Удадайте число от 0 до 100')
number = random.randint(0, 101)
if number == get_valid('Удадайте число от 0 до 100: '):
print('Угадали')
else:
print('Не угадали, было загадоно число', number)
|
TypeScript
|
UTF-8
| 8,278 | 3.09375 | 3 |
[
"MIT",
"BSD-2-Clause"
] |
permissive
|
import { RuleTester } from '@typescript-eslint/rule-tester';
import rule from '../../src/rules/dot-notation';
import { getFixturesRootDir } from '../RuleTester';
const rootPath = getFixturesRootDir();
const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
parserOptions: {
sourceType: 'module',
tsconfigRootDir: rootPath,
project: './tsconfig.json',
},
});
/**
* Quote a string in "double quotes" because it’s painful
* with a double-quoted string literal
*/
function q(str: string): string {
return `"${str}"`;
}
ruleTester.run('dot-notation', rule, {
valid: [
// baseRule
'a.b;',
'a.b.c;',
"a['12'];",
'a[b];',
'a[0];',
{ code: 'a.b.c;', options: [{ allowKeywords: false }] },
{ code: 'a.arguments;', options: [{ allowKeywords: false }] },
{ code: 'a.let;', options: [{ allowKeywords: false }] },
{ code: 'a.yield;', options: [{ allowKeywords: false }] },
{ code: 'a.eval;', options: [{ allowKeywords: false }] },
{ code: 'a[0];', options: [{ allowKeywords: false }] },
{ code: "a['while'];", options: [{ allowKeywords: false }] },
{ code: "a['true'];", options: [{ allowKeywords: false }] },
{ code: "a['null'];", options: [{ allowKeywords: false }] },
{ code: 'a[true];', options: [{ allowKeywords: false }] },
{ code: 'a[null];', options: [{ allowKeywords: false }] },
{ code: 'a.true;', options: [{ allowKeywords: true }] },
{ code: 'a.null;', options: [{ allowKeywords: true }] },
{
code: "a['snake_case'];",
options: [{ allowPattern: '^[a-z]+(_[a-z]+)+$' }],
},
{
code: "a['lots_of_snake_case'];",
options: [{ allowPattern: '^[a-z]+(_[a-z]+)+$' }],
},
{ code: 'a[`time${range}`];', parserOptions: { ecmaVersion: 6 } },
{
code: 'a[`while`];',
options: [{ allowKeywords: false }],
parserOptions: { ecmaVersion: 6 },
},
{ code: 'a[`time range`];', parserOptions: { ecmaVersion: 6 } },
'a.true;',
'a.null;',
'a[undefined];',
'a[void 0];',
'a[b()];',
{ code: 'a[/(?<zero>0)/];', parserOptions: { ecmaVersion: 2018 } },
{
code: `
class X {
private priv_prop = 123;
}
const x = new X();
x['priv_prop'] = 123;
`,
options: [{ allowPrivateClassPropertyAccess: true }],
},
{
code: `
class X {
protected protected_prop = 123;
}
const x = new X();
x['protected_prop'] = 123;
`,
options: [{ allowProtectedClassPropertyAccess: true }],
},
{
code: `
class X {
prop: string;
[key: string]: number;
}
const x = new X();
x['hello'] = 3;
`,
options: [{ allowIndexSignaturePropertyAccess: true }],
},
{
code: `
interface Nested {
property: string;
[key: string]: number | string;
}
class Dingus {
nested: Nested;
}
let dingus: Dingus | undefined;
dingus?.nested.property;
dingus?.nested['hello'];
`,
options: [{ allowIndexSignaturePropertyAccess: true }],
parserOptions: { ecmaVersion: 2020 },
},
],
invalid: [
{
code: `
class X {
private priv_prop = 123;
}
const x = new X();
x['priv_prop'] = 123;
`,
options: [{ allowPrivateClassPropertyAccess: false }],
output: `
class X {
private priv_prop = 123;
}
const x = new X();
x.priv_prop = 123;
`,
errors: [{ messageId: 'useDot' }],
},
{
code: `
class X {
public pub_prop = 123;
}
const x = new X();
x['pub_prop'] = 123;
`,
output: `
class X {
public pub_prop = 123;
}
const x = new X();
x.pub_prop = 123;
`,
errors: [{ messageId: 'useDot' }],
},
// baseRule
// {
// code: 'a.true;',
// output: "a['true'];",
// options: [{ allowKeywords: false }],
// errors: [{ messageId: "useBrackets", data: { key: "true" } }],
// },
{
code: "a['true'];",
output: 'a.true;',
errors: [{ messageId: 'useDot', data: { key: q('true') } }],
},
{
code: "a['time'];",
output: 'a.time;',
parserOptions: { ecmaVersion: 6 },
errors: [{ messageId: 'useDot', data: { key: '"time"' } }],
},
{
code: 'a[null];',
output: 'a.null;',
errors: [{ messageId: 'useDot', data: { key: 'null' } }],
},
{
code: 'a[true];',
output: 'a.true;',
errors: [{ messageId: 'useDot', data: { key: 'true' } }],
},
{
code: 'a[false];',
output: 'a.false;',
errors: [{ messageId: 'useDot', data: { key: 'false' } }],
},
{
code: "a['b'];",
output: 'a.b;',
errors: [{ messageId: 'useDot', data: { key: q('b') } }],
},
{
code: "a.b['c'];",
output: 'a.b.c;',
errors: [{ messageId: 'useDot', data: { key: q('c') } }],
},
{
code: "a['_dangle'];",
output: 'a._dangle;',
options: [{ allowPattern: '^[a-z]+(_[a-z]+)+$' }],
errors: [{ messageId: 'useDot', data: { key: q('_dangle') } }],
},
{
code: "a['SHOUT_CASE'];",
output: 'a.SHOUT_CASE;',
options: [{ allowPattern: '^[a-z]+(_[a-z]+)+$' }],
errors: [{ messageId: 'useDot', data: { key: q('SHOUT_CASE') } }],
},
{
code: 'a\n' + " ['SHOUT_CASE'];",
output: 'a\n' + ' .SHOUT_CASE;',
errors: [
{
messageId: 'useDot',
data: { key: q('SHOUT_CASE') },
line: 2,
column: 4,
},
],
},
{
code:
'getResource()\n' +
' .then(function(){})\n' +
' ["catch"](function(){})\n' +
' .then(function(){})\n' +
' ["catch"](function(){});',
output:
'getResource()\n' +
' .then(function(){})\n' +
' .catch(function(){})\n' +
' .then(function(){})\n' +
' .catch(function(){});',
errors: [
{
messageId: 'useDot',
data: { key: q('catch') },
line: 3,
column: 6,
},
{
messageId: 'useDot',
data: { key: q('catch') },
line: 5,
column: 6,
},
],
},
{
code: 'foo\n' + ' .while;',
output: 'foo\n' + ' ["while"];',
options: [{ allowKeywords: false }],
errors: [{ messageId: 'useBrackets', data: { key: 'while' } }],
},
{
code: "foo[/* comment */ 'bar'];",
output: null, // Not fixed due to comment
errors: [{ messageId: 'useDot', data: { key: q('bar') } }],
},
{
code: "foo['bar' /* comment */];",
output: null, // Not fixed due to comment
errors: [{ messageId: 'useDot', data: { key: q('bar') } }],
},
{
code: "foo['bar'];",
output: 'foo.bar;',
errors: [{ messageId: 'useDot', data: { key: q('bar') } }],
},
{
code: 'foo./* comment */ while;',
output: null, // Not fixed due to comment
options: [{ allowKeywords: false }],
errors: [{ messageId: 'useBrackets', data: { key: 'while' } }],
},
{
code: 'foo[null];',
output: 'foo.null;',
errors: [{ messageId: 'useDot', data: { key: 'null' } }],
},
{
code: "foo['bar'] instanceof baz;",
output: 'foo.bar instanceof baz;',
errors: [{ messageId: 'useDot', data: { key: q('bar') } }],
},
{
code: 'let.if();',
output: null, // `let["if"]()` is a syntax error because `let[` indicates a destructuring variable declaration
options: [{ allowKeywords: false }],
errors: [{ messageId: 'useBrackets', data: { key: 'if' } }],
},
{
code: `
class X {
protected protected_prop = 123;
}
const x = new X();
x['protected_prop'] = 123;
`,
options: [{ allowProtectedClassPropertyAccess: false }],
output: `
class X {
protected protected_prop = 123;
}
const x = new X();
x.protected_prop = 123;
`,
errors: [{ messageId: 'useDot' }],
},
{
code: `
class X {
prop: string;
[key: string]: number;
}
const x = new X();
x['prop'] = 'hello';
`,
options: [{ allowIndexSignaturePropertyAccess: true }],
errors: [{ messageId: 'useDot' }],
output: `
class X {
prop: string;
[key: string]: number;
}
const x = new X();
x.prop = 'hello';
`,
},
],
});
|
Markdown
|
UTF-8
| 3,002 | 3.203125 | 3 |
[] |
no_license
|
# Summary from https://thrift-tutorial.readthedocs.io/en/latest/thrift-types.html
# Thrift type system
include base types like **bool, byte, double, string and integer** but also special types like **binary** and it also supports **structs**(equivalent to classes but without inheritance) and also **containers**(list, set, map) that correspond to commonly available in all programming languages and omits types that are specific to only some programming languages.
## Base types
- bool
- byte
- i16
- i32
- i64
- double
- string
Note: There is no support for unsigned integer types.
## Special Types
- binary: a sequence of unencoded of bytes.
## Structs
A struct has a set of strongly typed fileds, each with a unique name identifier. The look very similar to C-like structs.
```
struct Example {
1: i32 number=10,
2: i64 bigNumber,
3: double decimals,
4: string name="thrifty",
}
```
## Containers
- list
- set
- map
## Exceptions
exception InvalidOperation {
1: i32 what,
2: string why
}
## Services
A service consists of a set of named function, each with a list of parameters and a return type. It is semantically equivalent to defining an interface or a pure virtual abstract class.
```
service <name> {
<returntype> <name>(<arguments>) [throws (exceptions)]
...
}
An example:
service StringCache {
void set(1:i32 key, 2:string value),
string get(1:i32 key) throws (1:KeyNotFound knf),
void delete(1: i32 key)
}
```
# Important Info, summary from proto/tutorial.thrift
- ```include "shared.thrift"``` means you can access shared.SharedObject in this .thrift that defined in another .thrift file.
- ```const i32 INT32CONSTANT = 1993``` thrift also let you define constants use across languages.
- or more complex ```const map<string, string> MAPCONSTANT = {"hello": "world", "name": "kaku"}``` types and structs are specified using JSON notation.
- enums you can define, which are just 32 bit integers. Values are optional and start at 1 if not supplied, C style again.
```
enum Operation {
ADD = 1
SUBTRACT = 2
MULTIPLY = 3
DIVIDE = 4
}
```
- Stucts are the basic complex data structures. They are comprised of fileds which each have an integer identifier, a type, a symbolic name, and an optional default value. you can define optional field. eg:
```
struct Work {
1: i32 num1 = 0,
2: i32 num2,
3: Operation op,
4: optional string comment,
}
```
- Structs can also be excetions, if they are nasty.
exception InvalidOperation {
1: i32 whatOp,
2: string why
}
- Define a service, Services just need a name and can optionally inherit from another service using the extends keywork. ```oneway``` method means only makes a request and does not listen for any response at all.
```
service Calculate extends shared.SharedService {
void ping(),
i32 add(1: i32 num1, 2: i32 num2),
i32 calculate(1: i32 logid, 2: Work w) throws (1: InvalidOperation),
oneway void zip()
}
```
|
Python
|
UTF-8
| 1,204 | 4.03125 | 4 |
[] |
no_license
|
print("\tStock Transaction Program ")
print("Total number of Stocks joe purchase was 1000 ")
print("Share purchase amount per stock 32.87$")
Invest = 32.87 * 1000
print("Joe invest " + str(Invest) + "$ last month")
Commission_for_Broker = (2/100)* Invest
print("Commission for stock broker is 2% from total amount which is " + str(Commission_for_Broker) + "$")
Total_Invest_amount = Invest + Commission_for_Broker
print("Total amount invested before " + str(Total_Invest_amount) + "$\n")
print("Joe sold 1000 stocks for 33.92$ ")
Balance = 1000*33.92
print("Joe get " + str(Balance) + "$ after sold ")
Broker_Amount = (2/100) * Balance
print("Joe paid " + str(Broker_Amount) + "$ after sold stocks")
Total_Amount_after_sold = Balance - Broker_Amount
print("Joe amount after sold " + str(Total_Amount_after_sold) + "$")
Final_amount = (Total_Amount_after_sold - Total_Invest_amount)
print("\nRemain amount " + str(Final_amount) +"$")
Final_amount = (Total_Amount_after_sold - Total_Invest_amount)<0
print("\nJoe is in Loss "+ str(Final_amount))
Final_amount = (Total_Amount_after_sold - Total_Invest_amount)>0
print("Joe made a Profit "+ str(Final_amount))
|
JavaScript
|
UTF-8
| 99 | 2.8125 | 3 |
[] |
no_license
|
let elementH1 = document.querySelector("h1");
let myName = "Simon Gørtz";
elementH1.innerHTML = myName;
|
Java
|
UTF-8
| 2,148 | 2.78125 | 3 |
[] |
no_license
|
package org.simpleframework.mvc.processor.impl;
import lombok.extern.slf4j.Slf4j;
import org.simpleframework.mvc.processor.RequestProcessor;
import org.simpleframework.mvc.processor.RequestProcessorChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
/**
* 静态资源请求处理,包括但不限于图片、css、以及js文件等
* 负责对静态资源请求的处理————遇到静态资源 转发给tomcat的 defaultServlet
* @author malaka
* @create 2020-12-21 11:19
*/
@Slf4j
public class StaticResourceRequestProcessor implements RequestProcessor {
//tomcat默认请求派发器RequestDispatcher的名称
private RequestDispatcher defaultDispatcher;
private final String Default_TOMCAT_SERVLET = "default";
private final String STATIC_RESOURCE_PREFIX = "/static/";
public StaticResourceRequestProcessor(ServletContext servletContext) {
//使用默认的处理器
this.defaultDispatcher = servletContext.getNamedDispatcher(Default_TOMCAT_SERVLET);
if (this.defaultDispatcher == null){
throw new RuntimeException("There is no default tomcat servlet, 获取Tomcat默认servlet失败");
}
log.info("The default servlet for static resource is {}", Default_TOMCAT_SERVLET);
}
@Override
public boolean process(RequestProcessorChain requestProcessorChain) throws Exception {
//1.通过请求路径判断是否是请求的静态资源webapp/static
if (isStaticResource(requestProcessorChain.getRequestPath()) == true){
//2.如果是静态资源,则将请求转发给default servlet处理
defaultDispatcher.forward(requestProcessorChain.getRequest(), requestProcessorChain.getResponse());
//静态资源请求 不需要后序处理
return false;
}
return true;
}
/**
* 通过请求路径前缀(目录)是否为静态资源/static/
* @param requestPath
* @return
*/
private boolean isStaticResource(String requestPath) {
return requestPath.startsWith(STATIC_RESOURCE_PREFIX);
}
}
|
C#
|
UTF-8
| 2,854 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using OMSAPI.DataContext;
using OMSAPI.Interfaces;
using OMSAPI.Models;
namespace OMSAPI.Services
{
class SalesOrderHeaderService : ISalesOrderHeader
{
private OMSDbContext _context;
public SalesOrderHeaderService(OMSDbContext context) {
_context = context;
}
public void Delete(SalesOrderHeader salesOrderHeader)
{
if(salesOrderHeader == null) throw new ArgumentNullException(nameof(salesOrderHeader));
_context.SalesOrderHeaders.Remove(salesOrderHeader);
}
public SalesOrderHeader Get(int id)
{
return _context.SalesOrderHeaders
.Include(h => h.Customer)
.Include(h => h.Address)
.Include(h => h.Lines).ThenInclude(line => line.Item)
.Where(h => h.Id == id)
.First();
}
public IEnumerable<SalesOrderHeader> GetAll()
{
return _context.SalesOrderHeaders
.Include(header => header.Customer)
.Include(header => header.Address)
.ToList();
}
public void Create(SalesOrderHeader salesOrderHeader)
{
if(salesOrderHeader == null) throw new ArgumentNullException(nameof(salesOrderHeader));
_context.SalesOrderHeaders.Add(salesOrderHeader);
}
public void Update(SalesOrderHeader salesOrderHeader)
{
_context.Entry(salesOrderHeader).State = EntityState.Modified;
}
public bool SaveChanges() {
return _context.SaveChanges() >= 0;
}
public bool UpdateProfit(int headerId) {
try {
var res = _context.Database.ExecuteSqlInterpolated($"CALL public.\"CalcSalesOrderProfit\"({headerId});");
}
catch(Exception e) {
Console.WriteLine(e.Message);
return false;
}
return true;
}
private void Validate(SalesOrderHeader header) {
if (_context.Addresses.Find(header.AddressId) == null) {
header.AddressId = null;
}
if (_context.Customers.Find(header.CustomerId) == null) {
header.CustomerId = null;
}
if (header.OrderDate == default(DateTime)) {
header.OrderDate = DateTime.Now;
}
if (header.ShipmentDate == default(DateTime)) {
if (header.OrderDate != default(DateTime)) {
header.ShipmentDate = header.OrderDate;
} else {
header.ShipmentDate = DateTime.Now;
}
}
}
}
}
|
Java
|
UTF-8
| 1,230 | 3.421875 | 3 |
[] |
no_license
|
package oop;
public class Test {
public static void main(String[] args) {
Teacher teacher1=new Teacher();//decaring and creating object...
// teacher1.setInformation("Sumaiya Islam","Female",1712);
teacher1.displayInformation();
/* teacher1.name="Sumaiya Islam";
teacher1.gender="Female";
teacher1.phone=1712;
System.out.println("Name :"+ teacher1.name);
System.out.println("Gender :"+ teacher1.gender);
System.out.println("Phone :"+ teacher1.phone);*/
System.out.println();
Teacher teacher2=new Teacher("Sumaiya Sweety","Female");//decaring and creating object...
// teacher2.setInformation("Sumaiya Sweety","Female",17122);
teacher2.displayInformation();
/* teacher2.name="Sumaiya Sweety";
teacher2.gender="Female";
teacher2.phone=1712;
System.out.println("Name :"+ teacher2.name);
System.out.println("Gender :"+ teacher2.gender);
System.out.println("Phone :"+ teacher2.phone);*/
System.out.println();
Teacher teacher3=new Teacher("Sumaiya Islam Sweety","Female",17122);
teacher3.displayInformation();
}
}
|
Java
|
UTF-8
| 1,061 | 3.34375 | 3 |
[] |
no_license
|
package _03_array_method.thuchanh;
import java.util.Scanner;
public class DaoNguocPhanTuCuaMang {
public static void main(String[] args) {
int size;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("moi ban nhap chieu dai mang");
size = scanner.nextInt();
if (size>20) {
System.out.println("vuot qua so luong");
}
}while (size>20);
int[] arr = new int[size];
for (int i = 0 ; i<arr.length;i++) {
System.out.println("moi ban nhap phan tu thu " +i);
arr[i]=scanner.nextInt();
}
for (int i =0; i<arr.length;i++) {
System.out.println(arr[i]+"");
}
int dau = 0;
int cuoi = arr.length-1;
while (dau<cuoi) {
int b = arr[dau];
arr[dau]=arr[cuoi];
arr[cuoi] = b;
dau++;
cuoi--;
}
for (int i = 0;i<arr.length;i++) {
System.out.print(" "+arr[i]);
}
}
}
|
SQL
|
UTF-8
| 690 | 3.53125 | 4 |
[] |
no_license
|
--코딩테스트 연습>JOIN>보호소에서 중성화한 동물
-- MySQL 코드를 입력하세요
SELECT i.animal_id, i.animal_type, i.name
FROM animal_ins i
JOIN animal_outs o ON i.animal_id = o.animal_id
WHERE i.sex_upon_intake LIKE 'Intact%'
AND (o.sex_upon_outcome LIKE 'Spayed%'
OR o.sex_upon_outcome LIKE 'Neutered%'
)
ORDER BY i.animal_id;
-- Oracle 코드를 입력하세요
SELECT i.animal_id, i.animal_type, i.name
FROM animal_ins i
JOIN animal_outs o ON i.animal_id = o.animal_id
WHERE i.sex_upon_intake LIKE 'Intact%'
AND (o.sex_upon_outcome LIKE 'Spayed%'
OR o.sex_upon_outcome LIKE 'Neutered%'
)
ORDER BY i.animal_id;
|
Python
|
UTF-8
| 691 | 3 | 3 |
[] |
no_license
|
#!/usr/bin/python3
# closing a window with a button
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QToolTip)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
qbtn = QPushButton('Quit', self)
qbtn.clicked.connect(QApplication.instance().quit)
qbtn.resize(qbtn.sizeHint())
qbtn.setToolTip('To exit the window')
qbtn.move(50, 50)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Quit Button')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
|
Java
|
GB18030
| 5,596 | 2.046875 | 2 |
[] |
no_license
|
package com.oa.dispatch.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.oa.common.BaseDao;
import com.oa.common.DateFormatUtil;
import com.oa.deskTop.entity.Shortmessage;
import com.oa.deskTop.serviceImpl.ShortmessageServiceImpl;
import com.oa.dispatch.entity.DisDetail;
import com.oa.dispatch.entity.Dispatch;
import com.oa.dispatch.serviceImpl.DispatchServiceImpl;
import com.oa.personnel.entity.Employee;
import com.oa.personnel.entity.UserInfo;
import com.oa.personnel.serviceImpl.EmployeeServiceImpl;
import com.oa.personnel.serviceImpl.FormNoServiceImpl;
import com.oa.travel.entity.WorkStream;
import com.oa.travel.serviceImpl.WorkStreamServiceImpl;
public class SaveOrSubmitDispatchServlet extends HttpServlet {
private BaseDao basedao = new BaseDao();
private EmployeeServiceImpl empImpl = new EmployeeServiceImpl();
private FormNoServiceImpl fnsImpl = new FormNoServiceImpl();
private DispatchServiceImpl dispatchImpl = new DispatchServiceImpl();
private WorkStreamServiceImpl wsImpl = new WorkStreamServiceImpl();
/**
* Constructor of the object.
*/
public SaveOrSubmitDispatchServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
private ShortmessageServiceImpl shortmessageServiceImpl=new ShortmessageServiceImpl();
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String disMoney = request.getParameter("disMoney");
String disReason = request.getParameter("disReason");
String state=request.getParameter("state");
String[] detailMoneyArr = request.getParameterValues("detailMoney");
String[] descriptionArr = request.getParameterValues("description");
String[] proIdArr = request.getParameterValues("proName");
HttpSession session = request.getSession();
UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
int empId = userInfo.getEmpId();
int disNo = fnsImpl.searchDisNo();
fnsImpl.updateDisNo(disNo + 1);
String formNo = "BX" + (disNo + 1);
Employee emp = empImpl.SearchById(empId);
int deptId = emp.getDeptId();
DateFormatUtil util = new DateFormatUtil();
int add = 0;
if (disMoney != null && !disMoney.equals("") && disReason != null
&& !disReason.equals("")) {
List<DisDetail> details = new ArrayList<DisDetail>();
for (int i = 0; i < descriptionArr.length; i++) {
if (proIdArr[i] != null && !proIdArr[i].equals("")
&& detailMoneyArr[i] != null
&& !detailMoneyArr[i].equals("")
&& descriptionArr[i] != null
&& !descriptionArr[i].equals("")) {
DisDetail detail = new DisDetail();
detail.setDescription(descriptionArr[i]);
detail
.setDetailMoney(Double
.parseDouble(detailMoneyArr[i]));
detail.setProId(Integer.parseInt(proIdArr[i]));
details.add(detail);
}
}
Dispatch dis = new Dispatch();
dis.setFormNo(formNo);
dis.setDeptId(deptId);
dis.setCreateTime(new Date());
dis.setDisMoney(Double.parseDouble(disMoney));
dis.setEmpId(empId);
dis.setDisReason(disReason);
if (state.equals("2")) {
dis.setState(2);
WorkStream ws = new WorkStream();
ws.setFormNo(formNo);
ws.setHasApproved(false);
Employee emp2 = empImpl.searchByDeptId(deptId, "ž");
ws.setToId(emp2.getEmpId());
ws.setFromId(empId);
add = dispatchImpl.add(dis, details, ws);
Shortmessage shortmessage=new Shortmessage();
shortmessage.setReceiveEmail(emp2.getEmpEmail());
shortmessage.setSendEmail(userInfo.getComEmail());
shortmessage.setContents("д˵ı");
shortmessage.setTitle("д˵ı");
shortmessage.setSendTime(new Date());
shortmessage.setUnread(true);
shortmessageServiceImpl.send(shortmessage);
}
else{
dis.setState(1);
add=dispatchImpl.add(dis, details);
}
}
request.getRequestDispatcher("SerachDisServlet?pageNo=1").forward(request,
response);
}
}
|
Java
|
UTF-8
| 349 | 2.546875 | 3 |
[] |
no_license
|
package thinking.in.patterns.singleton.p1;
/**
* Created by Administrator on 2016/11/7.
*/
public class SingletonLazy {
private SingletonLazy(){}
private static class Holder{
private static SingletonLazy instance = new SingletonLazy();
}
public static SingletonLazy getInstance(){
return Holder.instance;
}
}
|
Java
|
UTF-8
| 1,091 | 2.625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.edison;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by wangzhengfei on 16/7/5.
*/
public class ExecutorCompletionServiceTest extends ThreadPool {
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println(ThreadLocalRandom.current().nextLong());
ExecutorCompletionService service = new ExecutorCompletionService(getExecutor(), new LinkedBlockingQueue<Future>());
List<Future> futures = new ArrayList<Future>();
int totalTaskCount = 18;
for (int i = 0; i < totalTaskCount; i++) {
service.submit(new Task(i));
}
for(;;){
System.out.println(service.take().get());
}
}
private static Executor getExecutor() {
return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue(5), new NamedThreadFactory("AAA", false), new RejectedExecutionHandlerA()/*ThreadPoolExecutor.AbortPolicy()*/);
}
}
|
C#
|
UTF-8
| 594 | 2.59375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace KingBellyCore.Models
{
public class RestaurantList
{
public List<Restaurant> Restaurants { get; set; }
public RestaurantList()
{
Restaurants = getRestaurants();
}
private List<Restaurant> getRestaurants()
{
List<Restaurant> Restaurants = new List<Restaurant>();
Restaurants.Add(new Restaurant("Shie Sushio", 4, "asdsa", "It was greaaaaat!"));
return Restaurants;
}
}
}
|
JavaScript
|
UTF-8
| 759 | 2.546875 | 3 |
[] |
no_license
|
var jwt=require("jsonwebtoken");
module.exports=function(req,res,next){
var bearerHeader = req.headers["authorization"];
if(typeof bearerHeader!== 'undefined'){
var bearerToken = bearerHeader.split(" ")[1];
//req.token=bearerToken;
jwt.verify(bearerToken,process.env.SECRET, function(err,decoded){
if(err) {
return res.status(403).send("Invalid Token");
}
req.decoded = decoded;
next();
});
}
else{
// not authorized
console.log("not authorized..no token was sent");
return res.status(403).send({
success: false,
message:"No token was sent"
});
}
}
|
C#
|
UTF-8
| 917 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MapGenerator
{
public enum TileType
{
WALL,
FLOOR,
GROUND,
DOOR,
}
public class Map
{
public TileType[,] tiles;
public List<Rect> rooms;
public Map(int gridSize)
{
tiles = new TileType[gridSize, gridSize];
}
public static Map BuildRandom(int gridSize, int maxRooms, int minRoomSize, int maxRoomSize)
{
return new SimpleMapBuilder().build(gridSize, maxRooms, minRoomSize, maxRoomSize);
}
public int CountWalls()
{
int count = 0;
foreach (var tile in tiles)
{
if (tile == TileType.WALL)
{
count++;
}
}
return count;
}
}
}
|
C++
|
UTF-8
| 859 | 2.6875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
string st1 = "", st2 = "";
cin >> st1 >> st2;
vector<vector<int> > d;
d.resize(st1.size() + 1);
for (int i = 0; i < d.size(); i++)
d[i].resize(st2.size() + 1);
for (int i = 0; i <= st1.size(); i++)
d[i][0] = i;
for (int i = 0; i <= st2.size(); i++)
d[0][i] = i;
for (int i = 1; i < d.size(); i++)
for (int j = 1; j < d[i].size(); j++)
if (st1[i - 1] == st2[j - 1])
d[i][j] = d[i - 1][j - 1];
else
d[i][j] = min(min(d[i][j - 1], d[i - 1][j]), d[i - 1][j - 1]) + 1;
cout << d[st1.size()][st2.size()];
/*for (int i = 0; i < d.size(); i++)
{
for (int j = 0; j < d[i].size(); j++)
cout << d[i][j] << " ";
cout << endl;
}*/
return 0;
}
|
Shell
|
UTF-8
| 330 | 2.546875 | 3 |
[] |
no_license
|
#!/bin/bash
app=cg
for x in coreconstrained fair
do
for y in `seq 1 1 112`
do
../scripts/get-num-threads.py $app.$x.$y.log >> $app.$x.threads
done
done
for x in poweraware slackaware
do
for y in `seq 30 5 330`
do
../scripts/get-num-threads.py $app.$x.$y.log >> $app.$x.threads
done
done
|
Markdown
|
UTF-8
| 565 | 2.90625 | 3 |
[] |
no_license
|
---
title: How to start the time machine?
keywords: time machine, tachyon, 4d
---
So, you found yourself [into the lab](070-lab.md). You need some help with it. Look at the time machine and then go to lecture hall. The students will help you.
# I need...
You need:
- [4D glasses](100-4d-glasses.md)
- [Something that emits tachyons (feta cheese?)](120-goat.md)
# I have them
Now, in the lab. Use the 4D glasses. The portal appears.
# Neat
After the portal is visible insert the feta cheese into the tachyon tank.
# And then?
Pump the tank multiple of times.
|
PHP
|
UTF-8
| 2,412 | 2.890625 | 3 |
[] |
no_license
|
<?php
namespace PicqerImporter;
class OrderImporter {
protected $picqerclient;
protected $config;
public function __construct($picqerclient, $config)
{
$this->picqerclient = $picqerclient;
$this->config = $config;
}
public function importOrders($orders, $reference)
{
$orderids = array();
foreach ($orders as $customerid => $products) {
$orderids[] = $this->createOrder($customerid, $products, $reference);
}
return $orderids;
}
public function createOrder($customerid, $products, $reference)
{
$idcustomer = $this->getIdcustomer($customerid);
$products = $this->changeProductcodeToIdproduct($products);
$order = array(
'idcustomer' => $idcustomer,
'reference' => $reference,
'products' => array()
);
foreach ($products as $idproduct => $amount) {
$order['products'][] = array(
'idproduct' => $idproduct,
'amount' => $amount
);
}
$result = $this->picqerclient->addOrder($order);
if (isset($result['data']['idorder'])) {
if ($this->config['picqer-close-orders']) {
$this->picqerclient->closeOrder($result['data']['idorder']);
}
return $result['data']['orderid'];
} else {
throw new \Exception('Could not create order in Picqer');
}
}
public function getIdcustomer($customerid)
{
$result = $this->picqerclient->getCustomerByCustomerid($customerid);
if (isset($result['data']['idcustomer'])) {
return $result['data']['idcustomer'];
} else {
throw new \Exception('Could not get matching idcustomer from Picqer');
}
}
public function changeProductcodeToIdproduct($products)
{
$newProducts = array();
foreach ($products as $productcode => $amount) {
$productresult = $this->picqerclient->getProductByProductcode($productcode);
if (isset($productresult['data'])) {
$newProducts[$productresult['data']['idproduct']] = $amount;
}
}
if (count($products) != count($newProducts)) {
throw new \Exception('Could not get matching products from Picqer');
}
return $newProducts;
}
}
|
C++
|
UTF-8
| 2,210 | 3.40625 | 3 |
[] |
no_license
|
#include "fixed_sz_allocator.hpp"
#include <gtest/gtest.h>
#include <iostream>
TEST(allocator, base_operations) {
using T = double;
constexpr size_t n = 15;
reserve_allocator<T, n> fxd_alloc;
// Elements can be allocates just one per request
for (size_t i = 2; i < n; ++i) {
EXPECT_THROW(fxd_alloc.allocate(i), std::out_of_range);
}
// The number of allocated elements can not exceed n
for (size_t i = 0; i < n; ++i) {
EXPECT_NO_THROW(fxd_alloc.allocate(1));
}
// One more allocation should fail
EXPECT_THROW(fxd_alloc.allocate(1), std::out_of_range);
}
TEST(allocator, insert_operations) {
using T = double;
constexpr size_t n = 15;
reserve_allocator<T, n> fxd_alloc;
T * base_addr = fxd_alloc.allocate(1);
for (size_t i = 1; i < n; ++i) {
T * next_addr = fxd_alloc.allocate(1);
EXPECT_EQ((next_addr - base_addr), n - i);
}
}
TEST(allocator, remove_operations) {
using T = int;
constexpr size_t n = 10;
reserve_allocator<T, n> fxd_alloc;
// 0123456789| <-- free
T * addr0 = fxd_alloc.allocate(1); // 0
// 912345678|0
T * addr1 = fxd_alloc.allocate(1); // 9
// 81234567|90
T * addr2 = fxd_alloc.allocate(1); // 8
// 7123456|890
T * addr3 = fxd_alloc.allocate(1); // 7
// 612345|7890
T * addr4 = fxd_alloc.allocate(1); // 6
// 51234|67890
T * addr5 = fxd_alloc.allocate(1); // 5
// 4123|567890
fxd_alloc.construct(addr4, 33);
EXPECT_EQ(*addr4, 33);
fxd_alloc.destroy(addr4);
// 4123|567890
fxd_alloc.deallocate(addr4, 1); // addr4 == 6
addr4 = nullptr;
// 41236|67890
fxd_alloc.deallocate(addr2, 1); // addr2 == 8
addr2 = nullptr;
// 412368|7890
// 412368|7890
T * addr6 = fxd_alloc.allocate(1); // 4
// 81236|47890
T * addr7 = fxd_alloc.allocate(1); // 8
// 6123|847890
T * addr8 = fxd_alloc.allocate(1); // 6
// 312|6847890
EXPECT_EQ(addr6 - addr0, 4);
EXPECT_EQ(addr7 - addr0, 8);
EXPECT_EQ(addr8 - addr0, 6);
}
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
// End of the file
|
JavaScript
|
UTF-8
| 3,329 | 3.921875 | 4 |
[] |
no_license
|
//Codigo del cuadrado
console.group('Cuadrados');
function perimetroCuadrado(lado){
return lado * 4;
};
function areaCuadrado(lado){
return lado * lado;
};
console.groupEnd();
//Codigo del triangulo
console.group('Triangulos');
function perimetroTriangulo(lado1,lado2,base){
return lado1 + lado2 + base;
};
function areaTriangulo(base,altura){
return (base * altura) / 2;
};
function alturaTrianguloIsoceles(lado1,lado2,base){
return (Math.sqrt( (lado1 * lado2) - ((base * base) / 2)));
};
console.groupEnd();
//Codigo del circulo
console.group('Circulos');
// Diametro
function diametroCirculo(radio){
return radio * 2;
};
// PI
const PI = Math.PI;
// Circunferencia
function perimetroCirculo(radio){
const diametro = diametroCirculo(radio);
return diametro * PI;
};
// Area
function areaCirculo(radio){
return (radio * radio) * PI;
};
console.groupEnd();
// Aqui interactuamos con el html
function calcularPerimetroCuadrado() {
const input = document.getElementById('InputCuadrado');
const value = input.value;
const perimetro = perimetroCuadrado(value);
alert(perimetro);
};
function calcularAreaCuadrado() {
const input = document.getElementById('InputCuadrado');
const value = input.value;
const area = areaCuadrado(value);
alert(area);
};
function calcularPerimetroTriangulo(){
const inputLado1 = document.getElementById('InputTrianguloLado1');
const inputLado2 = document.getElementById('InputTrianguloLado2');
const inputBase = document.getElementById('InputTrianguloBase');
const valueLado1 = inputLado1.value;
const valueLado2 = inputLado2.value;
const valueBase = inputBase.value;
const perimetro = perimetroTriangulo(valueLado1, valueLado2, valueBase);
alert(perimetro);
};
function calcularAreaTriangulo(){
const inputBase = document.getElementById('InputTrianguloBaseArea');
const inputAltura = document.getElementById('InputTrianguloAltura');
const valueBase = inputBase.value;
const valueAltura = inputAltura.value;
const area = areaTriangulo(valueBase, valueAltura);
alert(area);
};
function calcularDiametroCirculo(){
const inputRadio = document.getElementById('InputCirculoRadio');
const radio = inputRadio.value;
const diametro = diametroCirculo(radio);
alert(diametro);
};
function calcularCircunferenciaCirculo(){
const inputRadio = document.getElementById('InputCirculoRadio');
const radio = inputRadio.value;
const circunferencia = perimetroCirculo(radio);
alert(circunferencia);
};
function calcularAreaCirculo(){
const inputRadio = document.getElementById('InputCirculoRadio');
const radio = inputRadio.value;
const area = areaCirculo(radio);
alert(area);
};
function calcularAlturaTrianguloIsoceles(){
const inputLado1 = document.getElementById('InputTrianguloLado1Altura');
const inputLado2 = document.getElementById('InputTrianguloLado2Altura');
const inputBase = document.getElementById('InputTrianguloBaseAltura');
const lado1 = inputLado1.value;
const lado2 = inputLado2.value;
const base = inputBase.value;
if (lado1 === lado2 && lado1 != base){
const alturaIsoceles = alturaTrianguloIsoceles(lado1,lado2,base);
alert(alturaIsoceles);
} else {
alert('Los lados tienen que ser iguales para que pueda dar una respuesta, intentar de nuevo');
}
};
|
C++
|
UTF-8
| 939 | 3.125 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* prev;
node(int x){
this->data = x;
this->prev = NULL;
}
};
void multiply(node *tail, int n)
{
node *temp=tail;
node *prevNode=tail;
int carry=0;
while(temp!=NULL){
int data=temp->data * n + carry;
temp->data=data%10;
carry=data/10;
prevNode=temp;
temp=temp->prev;
}
while(carry!=0){
prevNode->prev= new node((int)(carry%10));
carry/=10;
prevNode=prevNode->prev;
}
}
void print(struct node *tail)
{
if(tail==NULL)
return;
print(tail->prev);
cout<<tail->data<<" ";
}
int main()
{
int t;
cin>>t;
while(t--){
int n;
cin>>n;
node* tail = new node(1);
for(int i=2;i<=n;i++){
multiply(tail,i);
}
print(tail);
cout<<endl;
}
return 0;
}
|
Python
|
UTF-8
| 826 | 3.546875 | 4 |
[] |
no_license
|
#!/usr/bin/python3
"""Module and function must be documented"""
def island_perimeter(grid):
"""returns perimeter"""
if len(grid) == 0 or grid is None:
return 0
height = len(grid)
lenght = len(grid[0])
perimeter = 0
for lists in grid:
for items in lists:
if type(items) is not int:
return
for y in range(height):
for x in range(lenght):
if grid[y][x] == 0:
continue
if y == 0 or grid[y - 1][x] == 0:
perimeter += 1
if y == height - 1 or grid[y + 1][x] == 0:
perimeter += 1
if x == 0 or grid[y][x - 1] == 0:
perimeter += 1
if x == lenght - 1 or grid[y][x + 1] == 0:
perimeter += 1
return perimeter
|
JavaScript
|
UTF-8
| 565 | 3.34375 | 3 |
[] |
no_license
|
(function nameList() {
var i;
var arr = [];
for (i = 1; i <= 5; i++) {
arr.push(prompt('Введите имя №' + i));
}
var name = prompt('Введите ваше имя пользователя');
function nameCompare(name) {
for (var i = 0; i < nameList.length; ++i) {
if (nameList[i] === name) {
return "Your name: " + nameList[i]
}
}
return false;
}
(arr.indexOf(name) != -1) ? (alert(name+', вы успешно вошли')) : (alert('Имя '+name+' не найдено'));
})();
|
PHP
|
UTF-8
| 11,192 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
<?php
session_start();
include '../PHP/Conexion.php';
include 'plantilla2.php';
$string = $_POST['periodo1'];
$arreglo = explode('-', $string, 3);
$arreglo2 = explode('-',$_POST['periodo2'],3);
$mes = "error semantico";
$mes2 = "" ;
//$opcion = $arreglo[1];
switch ($arreglo[1]) {
case 1:
$mes = "Enero";
break;
case 2:
$mes = "Febrero";
break;
case 3:
$mes = "Marzo";
break;
case 4:
$mes = "Abril";
break;
case 5:
$mes = "Mayo";
break;
case 6:
$mes = "Junio";
break;
case 7:
$mes = "Julio";
break;
case 8:
$mes = "Agosto";
break;
case 9:
$mes = "Septiembre";
break;
case 10:
$mes = "Octubre";
break;
case 11:
$mes = "Noviembre";
break;
case 12:
$mes = "Diciembre";
break;
}
switch ($arreglo2[1]) {
case 1:
$mes2 = "Enero";
break;
case 2:
$mes2 = "Febrero";
break;
case 3:
$mes2 = "Marzo";
break;
case 4:
$mes2 = "Abril";
break;
case 5:
$mes2 = "Mayo";
break;
case 6:
$mes2 = "Junio";
break;
case 7:
$mes2 = "Julio";
break;
case 8:
$mes2 = "Agosto";
break;
case 9:
$mes2 = "Septiembre";
break;
case 10:
$mes2 = "Octubre";
break;
case 11:
$mes2 = "Noviembre";
break;
case 12:
$mes2 = "Diciembre";
break;
}
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->AddFont('Soberana','','SoberanaSans-Regular.php');
$pdf->AddFont('Soberana','B','SoberanaSans-Black.php');
$pdf->AddFont('Soberana','Bl','SoberanaSans-Bold.php');
$pdf->SetFont('Soberana','Bl',16);
$pdf->Cell(0,10,'',0,0,'C');
$pdf->Ln();
$pdf->Cell(0,10,utf8_decode('INFORME TÉCNICO FINAL PARA PROYECTOS FINANCIADOS POR EL'),0,1,'C');
$pdf->Cell(0,10,utf8_decode('TECNOLÓGICO NACIONAL DE MÉXICO'),0,1,'C');
//agrega una celda al $pdf
//recibe varios parametros, el primero es el largo de la celda
//el segundo sera el alto de la celda
//el 3ro sera el texto
//el 4to si tendra borde , 1 significa que si y 0 que nel
//el 5to significa si llevara salto de linea
//el 6to es la posicion de la celda , R right, L left C center
$pdf->SetFont('Soberana','B',12);
$pdf->Cell(0,10,utf8_decode('I. Identificación del Proyecto'),0,1,'L');
//$pdf->Ln();
$pdf->SetFont('Soberana','',10);
$pdf->Cell(0,10,utf8_decode('Institución:'),0,1,'C');
$pdf->Cell(20,7,utf8_decode(''),0,0,'C');
$pdf->Cell(150,7,utf8_decode('Instituto Tecnológico de Culiacán'),1,0,'C');
$pdf->Cell(20,7,utf8_decode(''),0,1,'C');
$pdf->Ln();
$pdf->Cell(0,10,utf8_decode('Responsable Técnico del Proyecto:'),0,1,'C');
$pdf->setX(60);
$pdf->Cell(90,15,utf8_decode($_POST['respon']),1,1,'C');
$pdf->Ln();
//////////////////////////////////////////////////////
$pdf->Cell(35,5,utf8_decode('Clave del proyecto:'),0,0,'L');
$pdf->Cell(20,10,utf8_decode($_POST['cve']),1,1,'L');
$pdf->Cell(35,5,utf8_decode('Titulo del proyecto: '),0,0,'L');
$pdf->setX(45);
$pdf->multicell(0,5,utf8_decode($_POST['titproy']),1,'C',0);
$pdf->Ln();
//////////////////////////////////////////////////////////////////////////
$pdf->Cell(0,10,utf8_decode('Tipo de investigación: '.$_POST['TipoInv']),0,1,'L');
$pdf->Cell(0,10,utf8_decode('Duración del proyecto: '.$_POST['Duracion']),0,1,'L');
$pdf->Cell(51,5,utf8_decode('Fecha de inicio del proyecto:'),0,0,'L');
$pdf->Cell(45,5,$arreglo[2].' De '.$mes.' Del '.$arreglo[0],'B',1,'L');
$pdf->Cell(55,5,utf8_decode('Fecha de término del proyecto:'),0,0,'L');
$pdf->Cell(45,5,$arreglo2[2].' De '.$mes2.' Del '.$arreglo2[0],'B',1,'L');
$pdf->Ln();
$pdf->SetFont('Soberana','B',12);
$pdf->Cell(0,10,utf8_decode('II. Resultados'),0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,'1. Resumen del proyecto',0,1,'L');
//$pdf->Ln();
$pdf->SetFont('Soberana','Bl',9);
$pdf->Cell(0,10,utf8_decode('Introducción'),0,1,'L');
$pdf->SetFont('Arial','',6);
$pdf->Cell(0,10,utf8_decode('Contiene una descripcion general de la problematica que aborda el proyecto de investigacion'),0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(0,10,utf8_decode($_POST['resumen']),0,'J',0);
$pdf->SetFont('Soberana','Bl',9);
$pdf->Cell(0,10,'Objetivos',0,1,'L');
$pdf->SetFont('Arial','',6);
$pdf->Cell(0,10,'Contiene el esclarecimiento de los obetivos que se cumplieron con el desarrollo del proyecto de forma cualitativa.',0,1,'L');
$pdf->SetFont('Soberana','',11);
$pdf->Cell(0,10,'GENERAL',0,1,'L');
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['general']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','',11);
$pdf->Cell(0,10,'ESPECIFICOS',0,1,'L');
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['especificos']),0,'J',0);
$pdf->Cell(0,10,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',9);
$pdf->Cell(0,10,'Metas',0,1,'L');
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Arial','',6);
$pdf->multicell(190,10,utf8_decode('Contiente los resultados concretos obtenidos en forma cuantitativa respecto a tesis desarrolladas, publicaciones, trabajos de residercera profesional. Patentes en tramite, participación de eventos, etc.'),0,'J',0);
//utf8_decode($_POST['resumem'])
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['metas']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',9);
$pdf->Cell(0,10,'Desarrollo y Resultados del proyecto:',0,1,'L');
$pdf->SetFont('Arial','',6);
$pdf->Cell(0,10,'Contiene una explicacion de los procedimientos seguidos para el cumpliento de los objetivos y metas que conforman el proyecto',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['DesarrolloProyecto']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',9);
$pdf->cell(0,10,'Resultados del proyecto',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->cell(0,10,'Durante el periodo reportado se lograron los entregables siguientes:',0,1,'L');
$pdf->multicell(190,10,utf8_decode($_POST['entregables']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',9);
$pdf->cell(0,10,'Conclusiones/Observaciones',0,1,'L');
$pdf->SetFont('Arial','',6);
$pdf->cell(0,10,'Contiene comentarios al respecto del proyecto desarrollado.',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['conclusiones']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,'2. Objetivo del proyecto',0,1,'L');
$pdf->SetFont('Soberana','',11);
$pdf->Cell(0,10,'Grado de cumpliento del objetivo propuesto:'.utf8_decode($_POST['gradoCumplimiento']),0,1,'C');
$pdf->SetFont('Soberana','',9);
$pdf->Cell(0,10,'GENERAL:',0,1,'L');
$pdf->multicell(190,10,utf8_decode($_POST['ObjetivoGeneral']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->Cell(0,10,'ESPECIFICOS:',0,1,'L');
$pdf->multicell(190,10,utf8_decode($_POST['ObjetivoEspecifico']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,'3. Metas',0,1,'L');
$pdf->SetFont('Soberana','',11);
$pdf->Cell(0,10,'Grado de cumplimiento de las metas propuestas: '.utf8_decode($_POST['grado']),0,1,'C');
$pdf->SetFont('Soberana','Bl',9);
$pdf->Cell(0,10,'Cumplimiento de metas',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['CumplimientoMetas']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',9);
$pdf->Cell(0,10,'Metas cumplidas',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['MetasCumplidas']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,'4. Metodologia',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->Cell(0,10,'Descripcion de la metodologia empleada para el alcance de los objetivos',0,1,'L');
$pdf->SetFont('Soberana','',10);
$pdf->multicell(190,10,utf8_decode($_POST['metodologia']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,utf8_decode('5. Colaboración y Participación'),0,1,'L');
$pdf->SetFont('Arial','',6);
$pdf->multicell(190,10,utf8_decode('Descripción de la participación e integración del grupo de trabajo, indicando el desempeño y las actividades realizadas. Tambien se indica si hubo cambios en la participación de los investigadores, el grado de afectacion del proyecto.'),0,'J',0);
$pdf->SetFont('Soberana','',9);
$pdf->cell(0,10,utf8_decode('Integrantes del proyecto'),0,1,'C');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['IntegrantesProyecto']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->cell(0,10,utf8_decode('Colaboración con externos'),0,1,'C');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['IntegrantesExternos']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->cell(0,10,utf8_decode('Participación de Estudiantes'),0,1,'C');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['IntegrantesEstudiantes']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,utf8_decode('6. Desviaciones y Monto'),0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(190,10,utf8_decode($_POST['desviaciones']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,'7. Productos Transferidos',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(0,10,utf8_decode($_POST['productos']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,'8. Difusion',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(0,10,utf8_decode($_POST['difusion']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,'9. Recurso Ejercido',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(0,10,'$0.00 PESOS ',0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,'10. Beneficios y Problemas',0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(0,10,utf8_decode($_POST['beneficiosProblemas']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Soberana','Bl',10);
$pdf->Cell(0,10,utf8_decode('11. Información Adicional'),0,1,'L');
$pdf->SetFont('Soberana','',9);
$pdf->multicell(0,10,utf8_decode($_POST['InformacionAdicional']),0,'J',0);
$pdf->Cell(0,5,'',0,1,'L');
$pdf->SetFont('Arial','',9);
$pdf->Cell(180,15,'','B',1,'L');
$pdf->Cell(60,10,'Responsable Tecnico','LR',0,'C');
$pdf->Cell(60,10,'Jefe de la DEPI o subdirector Academico','LR',0,'C');
$pdf->Cell(60,10,'Director del plantel','LR',1,'C');
$pdf->Cell(60,10,'','LR',0,'C');
$pdf->Cell(60,10,'','LR',0,'C');
$pdf->Cell(60,10,'','LR',1,'C');
$pdf->Cell(60,10,'','LR',0,'C');
$pdf->Cell(60,10,'','LR',0,'C');
$pdf->Cell(60,10,'','LR',1,'C');
$pdf->Cell(60,10,'Nombre y Firma','LRB',0,'C');
$pdf->Cell(60,10,'Nombre y Firma','LRB',0,'C');
$pdf->Cell(60,10,'Nombre y Firma','LRB',1,'C');
$pdf->output();
?>
|
Java
|
UTF-8
| 7,346 | 1.90625 | 2 |
[] |
no_license
|
package com.onethousandprojects.appoeira.serverStuff.methods;
import android.location.Location;
import android.util.Pair;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.onethousandprojects.appoeira.R;
import com.onethousandprojects.appoeira.commonThings.Constants;
import com.onethousandprojects.appoeira.commonThings.SharedPreferencesManager;
import com.onethousandprojects.appoeira.rodaListView.RodaListActivity;
import com.onethousandprojects.appoeira.rodaListView.fragments.RodaFragment;
import com.onethousandprojects.appoeira.rodaListView.fragments.RodaMapsFragment;
import com.onethousandprojects.appoeira.serverStuff.rodaList.ClientLocationRodasRequest;
import com.onethousandprojects.appoeira.serverStuff.rodaList.ServerLocationRodaResponse;
import com.onethousandprojects.appoeira.serverStuff.sendEmail.ClientSendEmailRequest;
import com.onethousandprojects.appoeira.serverStuff.sendEmail.ServerSendEmailResponse;
import com.onethousandprojects.appoeira.serverStuff.serverAndClient.Client;
import com.onethousandprojects.appoeira.serverStuff.serverAndClient.Server;
import java.util.List;
import java.util.Objects;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class RodaListServer {
private List<ServerLocationRodaResponse> serverLocationRodaResponse;
private List<ServerLocationRodaResponse> serverLocationRodaMapsResponse;
private ServerSendEmailResponse serverSendEmailResponse;
private boolean createdFragment = false;
Client Client;
Server Server;
public RodaListServer() {
super();
Client = Client.getInstance();
Server = Client.getServer();
}
public void sendLocationToServer(RodaListActivity RodaListActivity, Location location, Integer distance) {
ClientLocationRodasRequest clientLocationRodasRequest = new ClientLocationRodasRequest(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), distance);
Call<List<ServerLocationRodaResponse>> call = Server.post_location_rodas(clientLocationRodasRequest);
call.enqueue(new Callback<List<ServerLocationRodaResponse>>() {
@Override
public void onResponse(@NonNull Call<List<ServerLocationRodaResponse>> call, @NonNull Response<List<ServerLocationRodaResponse>> response) {
if (response.isSuccessful()){
serverLocationRodaResponse = response.body();
assert serverLocationRodaResponse != null;
if (!createdFragment) {
createdFragment = true;
RodaListActivity.getSupportFragmentManager().beginTransaction().add(R.id.ListLayout, new RodaFragment(), "RodaListFragment").commit();
} else {
RodaListActivity.getSupportFragmentManager().beginTransaction().remove(Objects.requireNonNull(RodaListActivity.getSupportFragmentManager().findFragmentByTag("RodaListFragment"))).commit();
RodaListActivity.getSupportFragmentManager().beginTransaction().add(R.id.ListLayout, new RodaFragment(), "RodaListFragment").commit();
}
RodaListActivity.srRodaList.setRefreshing(false);
} else {
Toast.makeText(RodaListActivity,R.string.failed, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(@NonNull Call<List<ServerLocationRodaResponse>> call,
@NonNull Throwable t) {
Toast.makeText(RodaListActivity, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public List<ServerLocationRodaResponse> getServerLocationRodaResponse() {
return serverLocationRodaResponse;
}
public void sendMapsLocationToServer(RodaMapsFragment rodaMapsFragment, Location location, Integer distance) {
ClientLocationRodasRequest clientLocationRodasRequest = new ClientLocationRodasRequest(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), distance);
Call<List<ServerLocationRodaResponse>> call = Server.post_location_rodas(clientLocationRodasRequest);
call.enqueue(new Callback<List<ServerLocationRodaResponse>>() {
@Override
public void onResponse(@NonNull Call<List<ServerLocationRodaResponse>> call, @NonNull Response<List<ServerLocationRodaResponse>> response) {
if (response.isSuccessful()){
serverLocationRodaMapsResponse = response.body();
assert serverLocationRodaMapsResponse != null;
for(int i = 0; i < serverLocationRodaMapsResponse.size(); i++) {
// googleMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(image)).position(marker).title(myResponse.get(i).getName()));
Marker marker = rodaMapsFragment.rodasMap.addMarker(new MarkerOptions().position(new LatLng(serverLocationRodaMapsResponse.get(i).getLatitude(), serverLocationRodaMapsResponse.get(i).getLongitude())).title(serverLocationRodaMapsResponse.get(i).getName()));
Pair<String, Integer> pair = new Pair<> (serverLocationRodaMapsResponse.get(i).getPicUrl(), serverLocationRodaMapsResponse.get(i).getId());
marker.setTag(pair);
}
}
}
@Override
public void onFailure(@NonNull Call<List<ServerLocationRodaResponse>> call, @NonNull Throwable t) {
}
});
}
public List<ServerLocationRodaResponse> getServerLocationRodaMapsResponse() {
return serverLocationRodaMapsResponse;
}
public void sendVerificationEmail(RodaListActivity RodaListActivity, Integer type, Integer firstId, Integer secondId) {
ClientSendEmailRequest clientSendEmailRequest = new ClientSendEmailRequest(SharedPreferencesManager.getStringValue(Constants.PERF_TOKEN), type, firstId, secondId);
Call<ServerSendEmailResponse> call = Server.post_send_email(clientSendEmailRequest);
call.enqueue(new Callback<ServerSendEmailResponse>() {
@Override
public void onResponse(@NonNull Call<ServerSendEmailResponse> call, @NonNull Response<ServerSendEmailResponse> response) {
if (response.isSuccessful()){
serverSendEmailResponse = response.body();
assert serverSendEmailResponse != null;
if (serverSendEmailResponse.isOk()) {
Toast.makeText(RodaListActivity,R.string.checkYourEmail, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(RodaListActivity,R.string.failed, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(@NonNull Call<ServerSendEmailResponse> call,
@NonNull Throwable t) {
Toast.makeText(RodaListActivity, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
|
SQL
|
UTF-8
| 347 | 3.90625 | 4 |
[] |
no_license
|
SELECT IL.NAME, I.DESCRIPTION
FROM ISSUESLISTS IL, ISSUES I
WHERE IL.ID = I.ISSUESLIST_ID;
SELECT U.FIRSTNAME, U.LASTNAME, I.DESCRIPTION
FROM USERS U, ISSUES I
WHERE U.ID = I.USER_ID_ASSIGNEDTO;
SELECT U.FIRSTNAME, U.LASTNAME, COUNT(*) AS ISSUES
FROM ISSUES I, USERS U
WHERE U.ID = I.USER_ID_ASSIGNEDTO
GROUP BY U.FIRSTNAME
HAVING COUNT(*) > 0;
|
C++
|
UTF-8
| 3,070 | 2.734375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
vector<vector<int>> field;
vector<vector<int>> minLength;
vector<vector<int>> used;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int w, h;
int x1, y1;
int x2, y2;
cin >> w >> h >> x1 >> y1 >> x2 >> y2;
x1--;
y1--;
x2--;
y2--;
field.assign(h, vector<int>(w));
minLength.assign(h, vector<int>(w, INT_MAX));
used.assign(h, vector<int>(w, 0));
for (int i = 0; i < h; i++) {
char string1[1000];
cin >> string1;
for (int j = 0; j < w; j ++) {
if (string1[j] == '.') {
field[i][j] = 1; //проходима
}
else if (string1[j] == '*') {
field[i][j] = 0; //непроходима
}
}
}
queue<pair<int, int>> q;
q.push(make_pair(x1, y1));
minLength[y1][x1] = 0;
used[y1][x1] = 1;
// bfs
while (!q.empty())
{
pair<int, int> p = q.front();
q.pop();
int currX = p.first;
int currY = p.second;
int currMinLen = minLength[currY][currX];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
for (int k = 0; k < 4; k++)
{
int ix = currX + dx[k];
int iy = currY + dy[k];
if (ix >= 0 && iy >= 0 && ix < w && iy < h && field[iy][ix])
{
minLength[iy][ix] = min(minLength[iy][ix], currMinLen + 1);
if (!used[iy][ix])
{
q.push(make_pair(ix, iy));
used[iy][ix] = 1;
}
}
}
}
int currLen = minLength[y2][x2];
if (currLen == INT_MAX)
cout << "NO\n";
else
{
cout << "YES\n";
stack<pair<int, int>> path;
path.push(make_pair(x2, y2));
while(currLen >= 0) {
pair<int ,int> currCell = path.top();
int currX = currCell.first;
int currY = currCell.second;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
for (int k = 0; k < 4; k++)
{
int ix = currX + dx[k];
int iy = currY + dy[k];
if (ix >= 0 && iy >= 0 && ix < w && iy < h)
{
if (minLength[iy][ix] == currLen - 1)
{
path.push(make_pair(ix, iy));
break;
}
}
}
currLen--;
}
cout << "\n";
while (!path.empty())
{
pair<int ,int> currCell = path.top();
path.pop();
int currX = currCell.first + 1;
int currY = currCell.second + 1;
cout << currX << ' ' << currY << ' ';
}
}
return 0;
}
|
C++
|
UTF-8
| 493 | 3.046875 | 3 |
[] |
no_license
|
/*
ID: ishan-sang
PROG: Reverse integer
LANG: C++
*/
int Solution::reverse(int A)
{
int sign = 0;
if(A<0)
sign = 1;
A = abs(A);
long long int N = 0;
while(A)
{
N = N*10 + A%10;
A/=10;
}
if(sign == 0)
{
if(N>INT_MAX)
return 0;
return N;
}
if(sign == 1)
{
N *= -1;
if(N < INT_MIN)
return 0;
return N;
}
}
|
C#
|
UTF-8
| 1,534 | 3.34375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BasicExam19December2014
{
class Program
{
static void Main(string[] args)
{
string yearType = Console.ReadLine();
if(yearType == "leap")
{
int travelMonths = int.Parse(Console.ReadLine());
int homeMonths = int.Parse(Console.ReadLine());
double normalMonths = (12 * (12 - (travelMonths + homeMonths))) *((double)3 / 5);
travelMonths = 12 * travelMonths;
homeMonths = 4 * homeMonths;
double percent = (normalMonths + travelMonths + homeMonths) * ((double)5 / 100);
normalMonths = normalMonths + travelMonths + homeMonths + percent;
int result = (int)normalMonths;
Console.WriteLine(result);
}
if (yearType == "normal")
{
int travelMonths = int.Parse(Console.ReadLine());
int homeMonths = int.Parse(Console.ReadLine());
double normalMonths = (12 * (12 - (travelMonths + homeMonths))) * ((double)3 / 5);
travelMonths = 12 * travelMonths;
homeMonths = 4 * homeMonths;
normalMonths = normalMonths + travelMonths + homeMonths;
int result = (int)normalMonths;
Console.WriteLine(result);
}
}
}
}
|
C++
|
UTF-8
| 2,532 | 3.46875 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <stack>
#include <queue>
#include <string>
#include "data.h"
using namespace std;
int main() {
cout << "" << endl;
Data GHG_Emission;
stack <Data> Stack;
queue <Data> Queue;
priority_queue <Data> finalsortedList;
ofstream myfile;
myfile.open("../test.txt");
myfile << "Writing this to a file.\n";
myfile.close();
ifstream inFile; //create input stream and out put streams
inFile.open("../emission data.csv");
ofstream stacked;
stacked.open("../stacked.txt");
ofstream queued;
queued.open("../queued.txt");
ofstream sorted;
sorted.open("../sorted.txt");
if (!inFile.is_open()){ // open check for files
cout << "Fail to open input file" << endl;
return 1;
}
if (!stacked.is_open()){ //different exceptions
cout << "Fail to open stack file" << endl;
return 10;
}
if (!queued.is_open()){
cout << "Fail to open queue file" << endl;
return 100;
}
if (!sorted.is_open()){
cout << "Fail to open sort file" << endl;
return 1000;
}
cout << "All Good." << endl;
cout << "...Reading emission data.csv..." << endl;
while (!inFile.eof()) {
string Country1;
getline(inFile, Country1, ',');
string Year1;
getline(inFile,Year1, ',');
string GHG_Emission_tonnes1;
getline(inFile, GHG_Emission_tonnes1, ',');
int year = stoi(Year1); //turn string into int
int GHG_E = stoi(GHG_Emission_tonnes1);
Data nextCountry = Data(Country1, year, GHG_E);
Stack.push(nextCountry);
Queue.push(nextCountry);//push tail for queue
finalsortedList.push(nextCountry); //insert in sorted for sorted list
}
cout << "Writing data in stack into Stack.txt" << endl;
while (!Stack.empty()){
stacked << Stack.top() << endl;
Stack.pop();
}
//prints then removes the element from queue
cout << "Writing data in queue into Queue.txt" << endl;
while (!Queue.empty()){
queued << Queue.front() << endl;
Queue.pop();
}
//prints then removes the element from the priority queue
cout << "Writing data in priority queue into Sorted.txt" << endl;
while (!finalsortedList.empty()){
sorted << finalsortedList.top() << endl;
finalsortedList.pop();
}
inFile.close ();
stacked.close();
queued.close ();
sorted.close ();
return 0;
}
|
JavaScript
|
UTF-8
| 2,459 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
$.getScript("./JS/util.js");
$(document).ready(function () {
aboutUsAnimation();
headerAnimation();
});
/**
* hide about us
* show about us
*/
function aboutUsAnimation() {
$("#aboutUsClosed").on('click', function () {
$('#aboutUsContents').fadeOut('slow');
$('.aboutUsClosed').fadeOut('slow');
$('#aboutUsOpened').show('slow');
});
$("#aboutUsOpened").on('click', function () {
$('#aboutUsContents').fadeIn('slow');
$('.aboutUsClosed').fadeIn('slow');
$('#aboutUsOpened').hide('slow');
});
}
/**
* change header layout
* scroll action
* resize windows action
*/
function headerAnimation() {
var width = $(window).width();
var top = $(window).scrollTop();
if (width > 1150 && top > 540) {
$('#nav').css({"position": "fixed", "top": "0"});
$('#navLogo').css("display", "block");
$('#navDetails').css("display", "block");
} else if (width < 1150 && top > 540) {
$('#nav').css('display', 'none');
} else {
$('#nav').css({"display": "block", "position": "relative", "top": "none"});
$('#navLogo').css("display", "none");
$('#navDetails').css("display", "none");
}
//codes running when page load or reload
$(document).on('scroll', function () {
var width = $(window).width();
var top = $(window).scrollTop();
if (width > 1150 && top > 540) {
$('#nav').css({"position": "fixed", "top": "0"});
$('#navLogo').css("display", "block");
$('#navDetails').css("display", "block");
} else if (width < 1150 && top > 540) {
$('#nav').css('display', 'none');
} else {
$('#nav').css({"display": "block", "position": "relative", "top": "none"});
$('#navLogo').css("display", "none");
$('#navDetails').css("display", "none");
}
});
//change nav when windows resize
$(window).resize(function () {
var top = $(window).scrollTop();
var scrollTop = $(this).scrollTop();
var width = $(this).width();
var height = $(this).height();
if (width < 1150 && top > 540) {
$('#nav').css('display', 'none');
} else if (width > 1150 && top < 540) {
$('#nav').css('display', 'block');
} else if (width > 1150 && top > 540) {
$('#nav').css('display', 'block');
}
});
}
|
Python
|
UTF-8
| 408 | 2.984375 | 3 |
[] |
no_license
|
class UDPFileSender(object):
def __init__(self, sender):
self.sender = sender
def readFile2bytes(self, file_name):
file_bytes = None
try:
f = open(file_name, 'rb')
file_bytes = f.read()
except IOError:
print("无法打开文件 -> ", file_name)
return file_bytes
def send(self, file_name, address=None):
pass
|
C#
|
UTF-8
| 2,323 | 2.953125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSRunner.Base
{
public class Events : IDisposable
{
protected bool disposed;
internal Events()
{ }
event RunnerEvent runnerEvent;
internal event RunnerEvent RunnerEvent
{
add
{
this.runnerEvent += value;
}
remove
{
this.runnerEvent -= value;
}
}
public void Info(string message, params object[] parameters)
{
if (null != runnerEvent)
runnerEvent(RunnerEventType.Info, message, parameters);
}
public void Error(string message, params object[] parameters)
{
if (null != runnerEvent)
runnerEvent(RunnerEventType.Error, message, parameters);
}
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
/*if (!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// Dispose managed resources.
//this.environment.Dispose();
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
//CloseHandle(handle);
//handle = IntPtr.Zero;
// Note disposing has been done.
disposed = true;
}*/
disposed = true;
}
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
~Events()
{
Dispose(false);
}
}
}
|
Java
|
UTF-8
| 821 | 1.585938 | 2 |
[] |
no_license
|
package com.github.client;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author dujf
*/
@EnableEurekaClient
@EnableSwagger2Doc
@EnableSwagger2
@MapperScan("com.github")
@SpringBootApplication(scanBasePackages = "com.github")
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
String line = "============================================";
System.out.println(line + "\n http://localhost:8011 \n" + line);
}
}
|
C++
|
UTF-8
| 7,424 | 2.609375 | 3 |
[] |
no_license
|
#include <stan/math.hpp>
#include <gtest/gtest.h>
#include <dist/bicop_BB1_log.hpp>
#include <dist/bicop_survival_BB1_log.hpp>
#include <dist/bicop_r90_BB1_log.hpp>
#include <dist/bicop_r270_BB1_log.hpp>
#include <iostream>
TEST(Copula_density, BB1_copula_v) {
using stan::math::var;
double v_val = 0.8;
var v(v_val);
var lp1(0.0);
lp1 += vifcopula::bicop_BB1_log<false>(0.1, v, 0.5, 1.5);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = v.adj();
EXPECT_FLOAT_EQ(lp1val,-1.679066);
EXPECT_FLOAT_EQ(lp1adj,-4.55145);
}
TEST(Copula_density, BB1_copula_u) {
using stan::math::var;
double v_val = 0.05;
var v(v_val);
var lp1(0.0);
lp1 += vifcopula::bicop_BB1_log<false>(v, 0.7, 0.5, 1.5);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = v.adj();
EXPECT_FLOAT_EQ(lp1val,-1.838721);
EXPECT_FLOAT_EQ(lp1adj,16.320076);
}
TEST(Copula_density, BB1_copula_theta) {
using stan::math::var;
double theta_val = 0.5;
var theta(theta_val);
var lp1(0.0);
lp1 += vifcopula::bicop_BB1_log<false>(0.1, 0.5, theta, 2.);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = theta.adj();
EXPECT_FLOAT_EQ(lp1val,-1.048868);
EXPECT_FLOAT_EQ(lp1adj,-1.683259);
}
TEST(Copula_density, BB1_copula_delta) {
using stan::math::var;
double theta_val = 2;
var theta(theta_val);
var lp1(0.0);
lp1 += vifcopula::bicop_BB1_log<false>(0.1, 0.5, 0.5, theta);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = theta.adj();
EXPECT_FLOAT_EQ(lp1val,-1.048868);
EXPECT_FLOAT_EQ(lp1adj,-1.176625);
}
TEST(Copula_density, survival_BB1_copula_u) {
using stan::math::var;
double v_val = 0.05;
var v(v_val);
var lp1(0.0);
lp1 += vifcopula::bicop_survival_BB1_log<false>(v, 0.7, 0.5, 1.5);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = v.adj();
EXPECT_FLOAT_EQ(lp1val,-1.546346);
EXPECT_FLOAT_EQ(lp1adj,11.630591);
}
TEST(Copula_density, survival_BB1_copula_v) {
using stan::math::var;
double v_val = 0.8;
var v(v_val);
var lp1(0.0);
lp1 += vifcopula::bicop_survival_BB1_log<false>(0.1, v, 0.5, 1.5);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = v.adj();
EXPECT_FLOAT_EQ(lp1val,-1.562345);
EXPECT_FLOAT_EQ(lp1adj,-5.118207);
}
TEST(Copula_density, survival_BB1_copula_theta) {
using stan::math::var;
double theta_val = 0.5;
var theta(theta_val);
var lp1(0.0);
lp1 += vifcopula::bicop_survival_BB1_log<false>(0.1, 0.5, theta, 2.);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = theta.adj();
EXPECT_FLOAT_EQ(lp1val,-1.088868);
EXPECT_FLOAT_EQ(lp1adj,-0.4009556);
}
TEST(Copula_density, survival_BB1_copula_delta) {
using stan::math::var;
double theta_val = 2;
var theta(theta_val);
var lp1(0.0);
lp1 += vifcopula::bicop_survival_BB1_log<false>(0.1, 0.5, 0.5, theta);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = theta.adj();
EXPECT_FLOAT_EQ(lp1val,-1.088868);
EXPECT_FLOAT_EQ(lp1adj,-1.446326);
}
TEST(Copula_density, r90_BB1_copula_u) {
using stan::math::var;
double v_val = 0.05;
var v(v_val);
var lp1(0.0);
lp1 += vifcopula::bicop_r90_BB1_log<false>(v, 0.7, -0.5, -1.5);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = v.adj();
EXPECT_FLOAT_EQ(lp1val,-0.06685771);
EXPECT_FLOAT_EQ(lp1adj,9.9650469);
}
TEST(Copula_density, r90_BB1_copula_v) {
using stan::math::var;
double v_val = 0.8;
var v(v_val);
var lp1(0.0);
lp1 += vifcopula::bicop_r90_BB1_log<false>(0.1, v, -0.5, -1.5);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = v.adj();
EXPECT_FLOAT_EQ(lp1val,0.6518384);
EXPECT_FLOAT_EQ(lp1adj,4.1926026);
}
TEST(Copula_density, r90_BB1_copula_theta) {
using stan::math::var;
double theta_val = -0.5;
var theta(theta_val);
var lp1(0.0);
lp1 += vifcopula::bicop_r90_BB1_log<false>(0.5, 0.5, theta, -2.);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = theta.adj();
EXPECT_FLOAT_EQ(lp1val,0.5905375);
EXPECT_FLOAT_EQ(lp1adj,-0.32509);
}
TEST(Copula_density, r90_BB1_copula_delta) {
using stan::math::var;
double theta_val = -2.;
var theta(theta_val);
var lp1(0.0);
lp1 += vifcopula::bicop_r90_BB1_log<false>(0.1, 0.5, -0.5, theta);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = theta.adj();
EXPECT_FLOAT_EQ(lp1val,-1.088868);
EXPECT_FLOAT_EQ(lp1adj,1.44594);
}
TEST(Copula_density, r270_BB1_copula_u) {
using stan::math::var;
double v_val = 0.05;
var v(v_val);
var lp1(0.0);
lp1 += vifcopula::bicop_r270_BB1_log<false>(v, 0.7, -0.5, -1.5);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = v.adj();
EXPECT_FLOAT_EQ(lp1val,-0.11505394);
EXPECT_FLOAT_EQ(lp1adj,11.944067);
}
TEST(Copula_density, r270_BB1_copula_v) {
using stan::math::var;
double v_val = 0.8;
var v(v_val);
var lp1(0.0);
lp1 += vifcopula::bicop_r270_BB1_log<false>(0.1, v, -0.5, -1.5);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = v.adj();
EXPECT_FLOAT_EQ(lp1val,0.6750373);
EXPECT_FLOAT_EQ(lp1adj,4.3265877);
}
TEST(Copula_density, r270_BB1_copula_theta) {
using stan::math::var;
double theta_val = -0.5;
var theta(theta_val);
var lp1(0.0);
lp1 += vifcopula::bicop_r270_BB1_log<false>(0.1, 0.5, theta, -2.);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = theta.adj();
EXPECT_FLOAT_EQ(lp1val,-1.048868);
EXPECT_FLOAT_EQ(lp1adj,1.682212);
}
TEST(Copula_density, r270_BB1_copula_delta) {
using stan::math::var;
double theta_val = -2;
var theta(theta_val);
var lp1(0.0);
lp1 += vifcopula::bicop_r270_BB1_log<false>(0.1, 0.5, -0.5, theta);
double lp1val = lp1.val();
lp1.grad();
double lp1adj = theta.adj();
EXPECT_FLOAT_EQ(lp1val,-1.048868);
EXPECT_FLOAT_EQ(lp1adj,1.176264);
}
//TEST(Copula_density, BB1_copula_v_50) {
// using stan::math::var;
//
// double v_val = 0.5;
// var v(v_val);
// var lp1(0.0);
// lp1 += vifcopula::bicop_BB1_log<false>(0.1, v, 50);
// double lp1val = lp1.val();
//
// lp1.grad();
// double lp1adj = v.adj();
//
// EXPECT_FLOAT_EQ(lp1val,-75.84692);
// EXPECT_FLOAT_EQ(lp1adj,-102);
//}
//
//TEST(Copula_density, BB1_copula_theta_50) {
// using stan::math::var;
//
// double theta_val = 50;
// var theta(theta_val);
// var lp1(0.0);
// lp1 += vifcopula::bicop_BB1_log<false>(0.1, 0.5, theta);
// double lp1val = lp1.val();
//
// lp1.grad();
// double lp1adj = theta.adj();
//
//
// EXPECT_FLOAT_EQ(lp1adj,-1.58983);
//}
|
C++
|
UTF-8
| 3,600 | 3.484375 | 3 |
[] |
no_license
|
//
// CircularBufferTest.cpp
// PROI-LAB1
//
// Created by Michał Świętochowski on 07.11.2013.
// Copyright (c) 2013 Michal Swietochowski. All rights reserved.
//
#include "CircularBufferTest.h"
void CircularBufferTest::runTests()
{
cout << "0. Initial buffer (test of << operator):" << endl << buffer << endl << endl;
//test 1
cout << "1. Trying to read from empty buffer...";
Element* element;
if ((element = buffer.read())) {
cout << " Result: " << element->intVal << endl << endl;
} else {
cout << " Result: NULL" << endl << endl;
}
//test 2
int val = 123;
cout << "2. Write " << val << " using write() method..." << endl << endl;
Element element2;
element2.intVal = val;
buffer.write(element2);
//test 3
cout << "3. Read using read() method... Result: " << buffer.read()->intVal << endl << endl;
//test 4
cout << "4. Filling buffer with integers (using write method)..." << endl;
for (int i = 0; i < BUFFER_SIZE; i++) {
Element element;
element.intVal = i * 3;
buffer.write(element);
}
cout << buffer << endl << endl;
//test 5
cout << "5. Reading all buffer elements (using read method)...";
Element* element3 = buffer.read();
while (element3) {
cout << element3->intVal << ", ";
element3 = buffer.read();
};
cout << endl << buffer << endl << endl;
//test 6
val = 8;
cout << "6. CircularBuffer << int(" << val << ")..." << endl << endl;
buffer << val;
//test 7
val = 16;
Element element5;
element5.intVal = val;
cout << "7. CircularBuffer << Element(" << element5.intVal << ")..." << endl << endl;
buffer << element5;
//read
Element element4;
cout << "Read last two elements...";
buffer >> element4;
cout << " Results: " << element4.intVal;
Element element6;
buffer >> element6;
cout << " " << element6.intVal << endl << endl;
//test 8
val = 32;
cout << "8. CircularBuffer += int(" << val << ")..." << endl << endl;
buffer += val;
//test 9
val = 64;
Element element8;
element8.intVal = val;
cout << "9. CircularBuffer += Element(" << element8.intVal << ")..." << endl << endl;
buffer << element8;
//read
Element element9;
cout << "Read last two elements...";
buffer >> element9;
cout << " Results: " << element9.intVal;
Element element10;
buffer >> element10;
cout << " " << element10.intVal << endl << endl;
//test 10
val = 128;
cout << "10. CircularBuffer = CircularBuffer + int(" << val << ")..." << endl << endl;
buffer = buffer + val;
//test 11
val = 256;
cout << "11. CircularBuffer = int(" << val << ") + CircularBuffer..." << endl << endl;
buffer = val + buffer;
//test 12
val = 512;
Element element11;
element11.intVal = val;
cout << "12. CircularBuffer = CircularBuffer + Element(" << element11.intVal << ")..." << endl << endl;
buffer = buffer + element11;
//test 13
val = 1024;
Element element12;
element12.intVal = val;
cout << "13. CircularBuffer = Element(" << element12.intVal << ") + CircularBuffer..." << endl << endl;
buffer = buffer + element12;
cout << buffer << endl << endl;
//test 14
cout << "14. Clear buffer..." << endl;
buffer.clear();
cout << buffer << endl << endl;
cout << endl << "Press ENTER to continue...";
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}
|
Java
|
UTF-8
| 4,398 | 2.265625 | 2 |
[] |
no_license
|
package com.qiushui.base.security.aspect;
import java.lang.reflect.Field;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import com.qiushui.base.constants.Chars;
import com.qiushui.base.exception.BusinessException;
import com.qiushui.base.model.AutoIncrementEntity;
import com.qiushui.base.model.UuidEntity;
import com.qiushui.base.security.annotations.Log;
import com.qiushui.base.security.annotations.LogField;
import com.qiushui.base.security.entity.BnLogEntity;
import com.qiushui.base.security.service.AbstractBnLogger;
import com.qiushui.base.util.BeanUtils;
import com.qiushui.base.util.SpringUtils;
import com.qiushui.base.util.StringUtils;
/**
* 日志切面。
*/
@Aspect
public class LogAspect {
/**
* 环绕填充业务日志。
*
* @param joinPoint
* 切入点
* @throws Throwable
* 切入方法执行失败时抛出异常。
*/
@Around("@annotation(com.qiushui.base.security.annotations.Log)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
return processEntity(joinPoint);
}
/**
* 处理业务实体类型的日志。
*
* @param joinPoint
* 切入点
* @throws Throwable
* 切入方法执行失败时抛出异常。
*/
private Object processEntity(ProceedingJoinPoint joinPoint)
throws Throwable {
Log log = getLogs(joinPoint);
AbstractBnLogger<? extends BnLogEntity> bnLogger = SpringUtils
.getBean("bnLogger");
BnLogEntity bnLog = bnLogger.newBnLog();
bnLog.setLogType(log.type());
bnLog.setMethod(joinPoint.getSignature().getName());
Object[] os = joinPoint.getArgs();
bnLog.setMessage(log.code() + Chars.COLON);
bnLog.setMessage(Chars.OPEN_BRACE);
if (log.target() > 0) {
Object o = joinPoint.getArgs()[log.target()];
bnLog.setMessage(getMessage(o));
} else {
for (Object o : os) {
bnLog.setMessage(getMessage(o));
}
}
bnLog.setMessage(Chars.CLOSE_BRACE);
bnLogger.fill(bnLog);
try {
Object result = joinPoint.proceed();
bnLog.setSuccess(true);
bnLogger.fill(bnLog);
return result;
} catch (BusinessException e) {
bnLog.setExceptionMsg(e.getMessage());
throw e;
} catch (Exception e) {
bnLog.setExceptionMsg(e.getClass().getName());
throw e;
} finally {
bnLogger.log(bnLog);
}
}
/**
* 获取切入方法上的注解。
*
* @param joinPoint
* 切入点
* @return 返回切入方法上的注解。
*/
private Log getLogs(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint
.getSignature();
return methodSignature.getMethod().getAnnotation(Log.class);
}
/**
* 获取日志信息。
*
* @param target
* 日志目标对象
* @param log
* 日志注解
* @return 返回日志信息。
*/
private String getMessage(Object target) {
try {
if (target != null) {
StringBuilder sb = new StringBuilder();
sb.append(Chars.OPEN_BRACKET);
if (target instanceof UuidEntity
|| target instanceof AutoIncrementEntity) {
List<Field> fields = BeanUtils.findField(target.getClass(),
LogField.class);
if (fields != null && fields.size() > 0) {
for (Field f : fields) {
boolean isac = f.isAccessible();
f.setAccessible(true);
LogField fa = f.getAnnotation(LogField.class);
String fname = fa.text();
if (!StringUtils.hasText(fname)) {
fname = f.getName();
}
sb.append(fname).append(Chars.COLON)
.append(f.get(target))
.append(Chars.SEMICOLON);
f.setAccessible(isac);
}
} else {
Field idfield = BeanUtils.findField(target.getClass(),
"id");
if (idfield != null) {
Object id = BeanUtils.getField(target, idfield);
sb.append("id:").append(id).append(Chars.SEMICOLON);
}
}
} else {
sb.append(target.toString());
}
sb.append(Chars.CLOSE_BRACKET);
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
C++
|
UTF-8
| 2,017 | 3 | 3 |
[] |
no_license
|
#include <string>
#include <iostream>
#include "Building.h"
#include "GameBoard.h"
#include "AcademicBuilding.h"
using namespace std;
AcademicBuilding::AcademicBuilding(std::string n, int i, GameBoard *g,
int c, int ic, int t0, int t1, int t2, int t3, int t4, int t5, int b):
Building{n, i, g, c}, currentLevel{0}, improvementCost{ic}, block{b}{
tuition[0] = t0;
tuition[1] = t1;
tuition[2] = t2;
tuition[3] = t3;
tuition[4] = t4;
tuition[5] = t5;
}
AcademicBuilding::~AcademicBuilding(){}
int AcademicBuilding::getBlock(){
return block;
}
int AcademicBuilding::getImprovementCost(){
return improvementCost;
}
int AcademicBuilding::getTuition(){
if((owner->checkMonopoly(block)) && (currentLevel == 0)){
cout << "The monopoly is owned by the owner." << endl;
return tuition[0] * 2;
} else {
cout << "The current improvement level is: " << currentLevel << "." << endl;
return tuition[currentLevel];
}
}
int AcademicBuilding::getCurrentLevel(){
return currentLevel;
}
void AcademicBuilding::doEvent(Player *p){
cout << "You are currently on " << getName() << "." << endl;
if(owner == nullptr){
g->buy(this);
} else if(getMortgage() == true){
cout << getName() << " is mortgaged." << endl;
} else if(owner->getName() == p->getName()){
cout << getName() << " is owned by you." << endl;
} else {
cout << getName() << " is owned by " << owner->getName() << ".";
int temp = getTuition();
cout << "You paid $" << temp << " tuition fee to the owner." << endl;
if(g->checkBankrupt(temp)){
g->bankrupt(owner);
} else {
p->changeCash(-temp);
owner->changeCash(temp);
}
}
}
void AcademicBuilding::changeLevel(int level){
int newLevel = currentLevel + level;
if(newLevel >= 0 && newLevel <= 5) currentLevel = newLevel;
}
void AcademicBuilding::setImprovements(int i){ // for load
if(i == -1){
setMortgage(true);
} else {
currentLevel = i;
}
}
|
Markdown
|
UTF-8
| 8,566 | 2.953125 | 3 |
[] |
no_license
|
## IMPORTANT
Read this ENTIRE document before beginning work.
## Collaboration
ONE person from the group will fork this repo from ACA. That person will give everyone else permissions as a "collaborator". From that point on, you will all clone THE ONE repo and your changes will be in the form of __pull requests__. For each change/ticket you will create a new branch and work from there. Remember to always pull the latest from the master branch before you being on a new task.
_Adding a collaborator_
<br />
https://stackoverflow.com/questions/7920320/adding-a-collaborator-to-my-free-github-account
_Creating a new branch_
<br />
`git checkout -b <BRANCH_NAME>`
_Pulling from master_
* Make sure you are on the master branch (`git checkout master`)
* Pull the latest changes (`git pull origin master` or `git pull` for short)
While ONE person is working on this, ANOTHER person can begin work on [database setup](#database-setup)
## Instructions
You will work as a group to create APIs from the very beginning. Notice that there is currently no code. Not a single file. Follow the steps below to make this happen. Please keep in mind that not all tasks are parallizable.. that means that some things will need to happen before others and there are points where the rest of the group may need to wait for one person to complete a task in order to move on. That's fine. Give that person support and collaborate together to unblock each other.
_Note: Many tasks are intentionally vague. It's up to you to learn/google some of these_
## Database setup
#### Download MySQL
1. https://dev.mysql.com/downloads/mysql/
2. Choose download file
3. Next page click "No thanks, just start my download" at the bottom
4. Once downloaded, install the application
5. Type `mysql` in a new terminal
6. If you get a "command not found error you need to add the command to your path. Run the following command to do that: `export PATH=$PATH:/usr/local/mysql/bin`
#### Connect to Google Cloud
We will use ONE person's Google Cloud database for this assignment. The steps for connecting to the database will follow.
1. Use the following command to connect to your Google Cloud database
* `mysql -u root -h <HOST IP FROM WORKBENCH> -p`
* You wil be prompted for a password
* This is very similar to connecting through MySQL Workbench
* [Additional information](https://stackoverflow.com/questions/15872543/access-mysql-remote-database-from-command-line)
2. Type `quit` when you want to exit the process
#### Import data
We are going to use sample data given to use by MySQL. An overview of the process exists here: https://dev.mysql.com/doc/employee/en/
1. Git clone the following repo in a new directory (NOT THIS ONE)
* https://github.com/datacharmer/test_db.git
2. cd into that directory
3. Run the connect command followed by `< employees.sql` to load that database
* `mysql -u root -h <HOST IP FROM WORKBENCH> -p < employees.sql`
4. After the operation is complete (may take a couple mins) you should have automatically been exited from the `mysql` command
5. Pull up MySQL Workbench so that we can work with a familiar interface
6. You should see an "employees" database on the left hand side
7. Double-click that database
8. Open a new query and run `select * from employees;`
9. You should have retrieved 1000 employee rows
10. You should see 6 tables under this database. There are over 2 million records among those two tables
11. Start tinkering with the data via SELECT statements to get familiar with it. We will use this data with our API
## Creating APIs
Let's get started...
### STEPS
#### 1. Initialize your project
* In this folder run `npm init`. Accept all the defaults (press enter a bunch of times)
* You should now have a `package.json` file
* Npm install the following packages: `express body-parser nodemon mysql`
* You should now have a `package-lock.json` file and a `node_modules` folder
* Create an `index.js` file and type `console.log('testing')` on the first line
* Open the package.json file and add a new `start` script. The value should be `nodemon ./index.js`
* Type `npm start` in the terminal. Did you see the log?
* Change the work "testing" to "re-testing". Did it re-load with the new log?
* Setup is complete
* Stop and commit/push work. Everyone else pull the updated code
#### 2. Basic Express
* Remove the "console.log" from the index.js file
* On the first line, import express: `const express = require('express')`
* Initialize the app on the second line: `const app = express()`
* Have the app listen on port 4001
* Re-run the `npm start` command if necessary.. is the app running?
* Navigate to `http://localhost:4001` in the browser to check if the app is running
* Before the "app.listen", add a default GET route and `res.send` the text: "Welcome to our API"
* Congratulations, we have a server running
#### 3. Express routes - BEGINNING
* Create a new folder called `routes`
* In the routes folder, create a new file called `employees.js`
* Create a router and make GET routes for `/, /:id, firstname/:first_name`
* For right now, use `res.send` to send back the text "getting employees..." for each route. We will update this later
* Export the router and import it into the `index.js` file. Use it with the prefix of "employees" so that each route above starts with "employees"
#### 4. Express controllers - BEGINNING
* Create a new folder called `controllers`
* In the controllers folder, create a new file called `employees.js`
* Create the following functions `getEmployees, getEmployeesById, getEmployeesByFirstName`
* Move the logic (everything after the route path) from the employees router into these functions
* Export these functions: `module.exports = { getEmployees, getEmployeesById, getEmployeesByFirstName }`
* Import these functions back into the employees router and use them `router.get('/:id', controller.getEmployeesById)`
* Everything should have stayed the same. If you navigate to `http://localhost:4001/employees/5` you should see the text "getting employees..."
#### 5. Hooking up MySQL
* Create a new folder called `mysql`
* In the mysql folder, create a new file called `connection.js`
* Import `mysql` at the top of the file
* Create a function (_singleton_) that creates a connection pool (if it doesn't already exist) and returns it. Export this function
* Remember to use the appropriate credentials from the ONE database we are currently sharing and make sure the "database" field in the connection pool is set to "employees"
* Import the previous function into whichever file needs it. This will usually be the controller. You will import this connection as `pool` and use `pool.query` to query the database. Remember that the first argument to this function is a SELECT statement and the second argument is a callback with `(err, results)` parameters
* If at any point (in any file) we find an `err` when using `pool.query`, return a 500 status code and the text, "something went wrong"
#### 6. Employees controller - CONTINUED
* Import the `pool` function from `mysql/connection` at the top of the file (controllers/employees.js). Additionally import the general `mysql` package
* Update the `getEmployees` function so that it calls the database, __selecting all fields from the employees table but limiting the results to 50__. Use `res.json` to return the results to the user
* Update the `getEmployeesById` function so that it calls the database, __selecting all fields from the employees table where the emp_no matches the id query parameter__. The should return one result. Use `res.json` to return the result to the user
* Update the `getEmployeesByFirstName` function so that it calls the database, __selecting all fields from the employees table where the first_name matches the first_name query parameter__. The could return multiple results. Use `res.json` to return the results to the user
#### Salaries and Departments
* Repeat steps 3-6 to create three more routes tying employee information to their current salaries or departments. New routes, controllers and queries will need to be created. You are free to collaboratively name these routes/controller functions anything you wish.
#### QA
All routes should be returning data from the database visibile through either the browser or Postman.
## Summary
When complete, there should be a fully functioning API integrated with an external MySQL database. This is most of the work required to create an API. Congratulations!
|
Java
|
UTF-8
| 129,449 | 1.976563 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bill;
import Database.DBconnection;
import Storage.stockDetails;
import home.HomeOverView;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.DefaultTableModel;
import model.bill;
import model.products;
import net.proteanit.sql.DbUtils;
import product.home;
/**
*
* @author Haran
*/
public class billDetails extends javax.swing.JFrame {
private final Connection con;
private PreparedStatement ps;
private ResultSet rs,rs1;
private Statement st;
private SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
private DefaultTableModel model,model1,model2;
private int Xloc,Yloc;
private String bill_id;
private String current_check_val;
private String current_count_value;
private String Customer_bill_id;
/**
* Creates new form billDetails
*/
public billDetails() {
initComponents();
count_error.setText("");
bill_error.setText("");
date_error.setText("");
this.setOpacity(0.95f);
con=DBconnection.connectDB();
combo_product.removeAllItems();
setCombo();
bill_table.getTableHeader().setFont(new Font("Segoe UI",Font.BOLD,12));
bill_table.getTableHeader().setOpaque(false);
bill_table.getTableHeader().setBackground(Color.LIGHT_GRAY);
bill_table.getTableHeader().setForeground(Color.BLACK);
bill_table.setRowHeight(25);
customer_bill_table.getTableHeader().setFont(new Font("Segoe UI",Font.BOLD,12));
customer_bill_table.getTableHeader().setOpaque(false);
customer_bill_table.getTableHeader().setBackground(Color.LIGHT_GRAY);
customer_bill_table.getTableHeader().setForeground(Color.BLACK);
customer_bill_table.setRowHeight(25);
display();
display_customer_bill_table();
btn_delete.setVisible(false);
btn_cancel.setVisible(false);
btn_bill_details.setVisible(false);
btn_update.setVisible(false);
lbl_result.setText("");
btn_update.setVisible(false);
lbl_bill_number_error.setText("");
lbl_customerName_error.setText("");
lbl_customer_paid_error.setText("");
lbl_amount_error.setText("");
btn_delete_bill_details.setVisible(false);
btn_update_bill_details.setVisible(false);
btn_cancel_bill_details.setVisible(false);
}
private void display(){
String sql = "SELECT * FROM bill_details where check_val=0";
try{
st=con.createStatement();
rs=st.executeQuery(sql);
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
finally{
bill_table.setModel(DbUtils.resultSetToTableModel(rs));//show all employee details in a table
model=(DefaultTableModel)bill_table.getModel();//currently add
try {
st.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void setCombo(){
String sql="SELECT * FROM products where name!=All(select pname from bill_details where check_val=0)";
try{
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
combo_product.addItem(rs.getString(2));
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(rootPane, e);
}
finally{
try {
ps.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* 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() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
bill_table = new javax.swing.JTable();
jPanel3 = new javax.swing.JPanel();
btn_delete = new javax.swing.JPanel();
lbl_delete = new javax.swing.JLabel();
btn_cancel = new javax.swing.JPanel();
lbl_cancel = new javax.swing.JLabel();
btn_update = new javax.swing.JPanel();
lbl_update = new javax.swing.JLabel();
txt_billno_search = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
lbl_result = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
lbl_bill = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txt_count = new javax.swing.JTextField();
combo_product = new javax.swing.JComboBox<>();
txt_date = new com.toedter.calendar.JDateChooser();
txt_billno = new javax.swing.JTextField();
bill_error = new javax.swing.JLabel();
date_error = new javax.swing.JLabel();
count_error = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jSeparator2 = new javax.swing.JSeparator();
jPanel4 = new javax.swing.JPanel();
btn_add = new javax.swing.JPanel();
lbl_add = new javax.swing.JLabel();
btn_bill_details = new javax.swing.JPanel();
lbl_current_bill_details = new javax.swing.JLabel();
btn_stock_details = new javax.swing.JPanel();
lbl_stock_details = new javax.swing.JLabel();
btn_add_bill = new javax.swing.JPanel();
lbl_add_bill = new javax.swing.JLabel();
btn_finished = new javax.swing.JPanel();
lbl_finish = new javax.swing.JLabel();
jPanel7 = new javax.swing.JPanel();
jPanel8 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
txt_bill_number1 = new javax.swing.JTextField();
txt_customer_name = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
txt_amount = new javax.swing.JTextField();
jSeparator4 = new javax.swing.JSeparator();
jSeparator5 = new javax.swing.JSeparator();
jSeparator6 = new javax.swing.JSeparator();
lbl_bill_number_error = new javax.swing.JLabel();
lbl_customerName_error = new javax.swing.JLabel();
lbl_amount_error = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
txt_customer_paid = new javax.swing.JTextField();
jSeparator7 = new javax.swing.JSeparator();
lbl_customer_paid_error = new javax.swing.JLabel();
jPanel9 = new javax.swing.JPanel();
btn_add_bill_details = new javax.swing.JPanel();
lbl_add_bill_details = new javax.swing.JLabel();
btn_update_bill_details = new javax.swing.JPanel();
lbl_update_bill_details = new javax.swing.JLabel();
btn_delete_bill_details = new javax.swing.JPanel();
lbl_delete_bill_details = new javax.swing.JLabel();
btn_cancel_bill_details = new javax.swing.JPanel();
lbl_cancel_bill_details = new javax.swing.JLabel();
jPanel14 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
txt_customer_bill_search = new javax.swing.JTextField();
lbl_customer_bill_results = new javax.swing.JLabel();
jPanel10 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
customer_bill_table = new javax.swing.JTable();
jPanel5 = new javax.swing.JPanel();
btn_close = new javax.swing.JPanel();
lbl_close = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
btn_home = new javax.swing.JPanel();
lbl_home = new javax.swing.JLabel();
panel_stock = new javax.swing.JPanel();
lbl_stock = new javax.swing.JLabel();
panel_free = new javax.swing.JPanel();
lbl_free = new javax.swing.JLabel();
panel_exit = new javax.swing.JPanel();
lbl_exit = new javax.swing.JLabel();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setExtendedState(5);
setUndecorated(true);
jTabbedPane1.setBackground(new java.awt.Color(255, 255, 255));
jTabbedPane1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
bill_table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
bill_table.setRowHeight(25);
bill_table.setSelectionBackground(new java.awt.Color(255, 51, 51));
bill_table.getTableHeader().setReorderingAllowed(false);
bill_table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
bill_tableMouseClicked(evt);
}
});
bill_table.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
bill_tableKeyReleased(evt);
}
});
jScrollPane1.setViewportView(bill_table);
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_delete.setBackground(new java.awt.Color(255, 255, 255));
btn_delete.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_delete.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_deleteMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_deleteMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_deleteMouseExited(evt);
}
});
lbl_delete.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
lbl_delete.setText(" Delete");
javax.swing.GroupLayout btn_deleteLayout = new javax.swing.GroupLayout(btn_delete);
btn_delete.setLayout(btn_deleteLayout);
btn_deleteLayout.setHorizontalGroup(
btn_deleteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_delete, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
);
btn_deleteLayout.setVerticalGroup(
btn_deleteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_delete, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
);
btn_cancel.setBackground(new java.awt.Color(255, 255, 255));
btn_cancel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_cancel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_cancelMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_cancelMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_cancelMouseExited(evt);
}
});
lbl_cancel.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
lbl_cancel.setText(" Cancel");
javax.swing.GroupLayout btn_cancelLayout = new javax.swing.GroupLayout(btn_cancel);
btn_cancel.setLayout(btn_cancelLayout);
btn_cancelLayout.setHorizontalGroup(
btn_cancelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_cancel, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
);
btn_cancelLayout.setVerticalGroup(
btn_cancelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_cancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
btn_update.setBackground(new java.awt.Color(255, 255, 255));
btn_update.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_update.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_updateMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_updateMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_updateMouseExited(evt);
}
});
lbl_update.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
lbl_update.setText(" Update");
javax.swing.GroupLayout btn_updateLayout = new javax.swing.GroupLayout(btn_update);
btn_update.setLayout(btn_updateLayout);
btn_updateLayout.setHorizontalGroup(
btn_updateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_update, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
);
btn_updateLayout.setVerticalGroup(
btn_updateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_update, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
);
txt_billno_search.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txt_billno_searchKeyReleased(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel4.setText(" Search Bill Number");
lbl_result.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lbl_result.setText(" Results");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(btn_delete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btn_cancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(53, 53, 53)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txt_billno_search, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(lbl_result, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(btn_update, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(36, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btn_delete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_cancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btn_update, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txt_billno_search, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbl_result)
.addGap(29, 29, 29))
);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
lbl_bill.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lbl_bill.setText("Bill_No");
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel5.setText("Date");
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("Products");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel2.setText("count");
txt_count.setBorder(null);
txt_count.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txt_countKeyReleased(evt);
}
});
combo_product.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { " " }));
txt_billno.setBorder(null);
txt_billno.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txt_billnoKeyReleased(evt);
}
});
bill_error.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
bill_error.setForeground(new java.awt.Color(255, 0, 0));
bill_error.setText("Error");
date_error.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
date_error.setForeground(new java.awt.Color(255, 0, 0));
date_error.setText("Error");
count_error.setBackground(new java.awt.Color(255, 255, 255));
count_error.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
count_error.setForeground(new java.awt.Color(255, 0, 0));
count_error.setText("Error");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(19, 19, 19))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(lbl_bill, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator2)
.addComponent(txt_count)
.addComponent(txt_date, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
.addComponent(jSeparator1)
.addComponent(txt_billno)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
.addComponent(combo_product, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(date_error, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE)
.addComponent(count_error, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bill_error, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_billno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_bill)
.addComponent(bill_error))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(63, 63, 63)
.addComponent(count_error))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(combo_product, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_count, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(46, 46, 46)
.addComponent(date_error)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_add.setBackground(new java.awt.Color(255, 255, 255));
btn_add.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_add.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_addMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_addMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_addMouseExited(evt);
}
});
lbl_add.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lbl_add.setText(" Add");
javax.swing.GroupLayout btn_addLayout = new javax.swing.GroupLayout(btn_add);
btn_add.setLayout(btn_addLayout);
btn_addLayout.setHorizontalGroup(
btn_addLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_add, javax.swing.GroupLayout.DEFAULT_SIZE, 63, Short.MAX_VALUE)
);
btn_addLayout.setVerticalGroup(
btn_addLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_add, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
);
btn_bill_details.setBackground(new java.awt.Color(255, 255, 255));
btn_bill_details.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_bill_details.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_bill_detailsMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_bill_detailsMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_bill_detailsMouseExited(evt);
}
});
lbl_current_bill_details.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lbl_current_bill_details.setText(" current_bill_details");
javax.swing.GroupLayout btn_bill_detailsLayout = new javax.swing.GroupLayout(btn_bill_details);
btn_bill_details.setLayout(btn_bill_detailsLayout);
btn_bill_detailsLayout.setHorizontalGroup(
btn_bill_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_current_bill_details, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
);
btn_bill_detailsLayout.setVerticalGroup(
btn_bill_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_current_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
);
btn_stock_details.setBackground(new java.awt.Color(255, 255, 255));
btn_stock_details.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_stock_details.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_stock_detailsMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_stock_detailsMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_stock_detailsMouseExited(evt);
}
});
lbl_stock_details.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lbl_stock_details.setText(" Stock Details");
javax.swing.GroupLayout btn_stock_detailsLayout = new javax.swing.GroupLayout(btn_stock_details);
btn_stock_details.setLayout(btn_stock_detailsLayout);
btn_stock_detailsLayout.setHorizontalGroup(
btn_stock_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_stock_details, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
);
btn_stock_detailsLayout.setVerticalGroup(
btn_stock_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_stock_details, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
btn_add_bill.setBackground(new java.awt.Color(255, 255, 255));
btn_add_bill.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_add_bill.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_add_billMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_add_billMouseExited(evt);
}
});
lbl_add_bill.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lbl_add_bill.setText(" Add Bill");
javax.swing.GroupLayout btn_add_billLayout = new javax.swing.GroupLayout(btn_add_bill);
btn_add_bill.setLayout(btn_add_billLayout);
btn_add_billLayout.setHorizontalGroup(
btn_add_billLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_add_bill, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
);
btn_add_billLayout.setVerticalGroup(
btn_add_billLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_add_bill, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
);
btn_finished.setBackground(new java.awt.Color(255, 255, 255));
btn_finished.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_finished.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_finishedMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_finishedMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_finishedMouseExited(evt);
}
});
lbl_finish.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lbl_finish.setText(" Finished");
javax.swing.GroupLayout btn_finishedLayout = new javax.swing.GroupLayout(btn_finished);
btn_finished.setLayout(btn_finishedLayout);
btn_finishedLayout.setHorizontalGroup(
btn_finishedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_finish, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
);
btn_finishedLayout.setVerticalGroup(
btn_finishedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_finish, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(btn_add, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38)
.addComponent(btn_finished, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(btn_bill_details, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(39, 39, 39)
.addComponent(btn_stock_details, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40)
.addComponent(btn_add_bill, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btn_bill_details, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn_finished, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_add, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(btn_stock_details, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_add_bill, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(50, Short.MAX_VALUE))
.addComponent(jScrollPane1)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Bill Entry", jPanel2);
jPanel7.setBackground(new java.awt.Color(255, 255, 255));
jPanel8.setBackground(new java.awt.Color(255, 255, 255));
jPanel8.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel3.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
jLabel3.setText("Bill Number");
jLabel6.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
jLabel6.setText("Customer Name");
txt_bill_number1.setBorder(null);
txt_customer_name.setBorder(null);
jLabel7.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
jLabel7.setText("Amount");
txt_amount.setBorder(null);
lbl_bill_number_error.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
lbl_bill_number_error.setForeground(new java.awt.Color(255, 0, 0));
lbl_bill_number_error.setText("Error");
lbl_customerName_error.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
lbl_customerName_error.setForeground(new java.awt.Color(255, 0, 0));
lbl_customerName_error.setText("Error");
lbl_amount_error.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
lbl_amount_error.setForeground(new java.awt.Color(255, 0, 0));
lbl_amount_error.setText("Error");
jLabel11.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
jLabel11.setText("Customer Paid");
txt_customer_paid.setBorder(null);
lbl_customer_paid_error.setBackground(new java.awt.Color(255, 255, 255));
lbl_customer_paid_error.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
lbl_customer_paid_error.setForeground(new java.awt.Color(255, 0, 0));
lbl_customer_paid_error.setText("Error");
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator4)
.addComponent(txt_bill_number1, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)))
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jLabel11))
.addGap(18, 18, 18)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator7)
.addComponent(jSeparator5)
.addComponent(txt_customer_name)
.addComponent(txt_amount)
.addComponent(jSeparator6)
.addComponent(txt_customer_paid, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE))))
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(58, 58, 58)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_customerName_error, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_bill_number_error, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbl_amount_error, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
.addComponent(lbl_customer_paid_error, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_bill_number1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_bill_number_error))
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel6)
.addComponent(txt_customer_name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_customerName_error))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_amount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_amount_error))
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 27, Short.MAX_VALUE)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_customer_paid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_customer_paid_error)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator7, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(22, 22, 22))
);
jPanel9.setBackground(new java.awt.Color(255, 255, 255));
jPanel9.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_add_bill_details.setBackground(new java.awt.Color(255, 255, 255));
btn_add_bill_details.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_add_bill_details.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_add_bill_detailsMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_add_bill_detailsMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_add_bill_detailsMouseExited(evt);
}
});
lbl_add_bill_details.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
lbl_add_bill_details.setText(" Add");
javax.swing.GroupLayout btn_add_bill_detailsLayout = new javax.swing.GroupLayout(btn_add_bill_details);
btn_add_bill_details.setLayout(btn_add_bill_detailsLayout);
btn_add_bill_detailsLayout.setHorizontalGroup(
btn_add_bill_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_add_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
);
btn_add_bill_detailsLayout.setVerticalGroup(
btn_add_bill_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_add_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
);
btn_update_bill_details.setBackground(new java.awt.Color(255, 255, 255));
btn_update_bill_details.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_update_bill_details.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_update_bill_detailsMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_update_bill_detailsMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_update_bill_detailsMouseExited(evt);
}
});
lbl_update_bill_details.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
lbl_update_bill_details.setText(" Update");
javax.swing.GroupLayout btn_update_bill_detailsLayout = new javax.swing.GroupLayout(btn_update_bill_details);
btn_update_bill_details.setLayout(btn_update_bill_detailsLayout);
btn_update_bill_detailsLayout.setHorizontalGroup(
btn_update_bill_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_update_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
);
btn_update_bill_detailsLayout.setVerticalGroup(
btn_update_bill_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_update_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
btn_delete_bill_details.setBackground(new java.awt.Color(255, 255, 255));
btn_delete_bill_details.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_delete_bill_details.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_delete_bill_detailsMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_delete_bill_detailsMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_delete_bill_detailsMouseExited(evt);
}
});
lbl_delete_bill_details.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
lbl_delete_bill_details.setText(" Delete");
javax.swing.GroupLayout btn_delete_bill_detailsLayout = new javax.swing.GroupLayout(btn_delete_bill_details);
btn_delete_bill_details.setLayout(btn_delete_bill_detailsLayout);
btn_delete_bill_detailsLayout.setHorizontalGroup(
btn_delete_bill_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_delete_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
);
btn_delete_bill_detailsLayout.setVerticalGroup(
btn_delete_bill_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_delete_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
btn_cancel_bill_details.setBackground(new java.awt.Color(255, 255, 255));
btn_cancel_bill_details.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_cancel_bill_details.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_cancel_bill_detailsMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_cancel_bill_detailsMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_cancel_bill_detailsMouseExited(evt);
}
});
lbl_cancel_bill_details.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
lbl_cancel_bill_details.setText(" Cancel");
javax.swing.GroupLayout btn_cancel_bill_detailsLayout = new javax.swing.GroupLayout(btn_cancel_bill_details);
btn_cancel_bill_details.setLayout(btn_cancel_bill_detailsLayout);
btn_cancel_bill_detailsLayout.setHorizontalGroup(
btn_cancel_bill_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_cancel_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
);
btn_cancel_bill_detailsLayout.setVerticalGroup(
btn_cancel_bill_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_cancel_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addComponent(btn_add_bill_details, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(21, 21, 21)
.addComponent(btn_update_bill_details, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(22, 22, 22)
.addComponent(btn_delete_bill_details, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(btn_cancel_bill_details, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(12, Short.MAX_VALUE))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btn_cancel_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_add_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_update_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_delete_bill_details, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(7, Short.MAX_VALUE))
);
jPanel14.setBackground(new java.awt.Color(255, 255, 255));
jPanel14.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel8.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
jLabel8.setText("Search Bill Number");
txt_customer_bill_search.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txt_customer_bill_searchKeyReleased(evt);
}
});
lbl_customer_bill_results.setFont(new java.awt.Font("Consolas", 1, 14)); // NOI18N
lbl_customer_bill_results.setForeground(new java.awt.Color(0, 0, 204));
lbl_customer_bill_results.setText("Results Found");
jPanel10.setBackground(new java.awt.Color(255, 255, 255));
jPanel10.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel10.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
jLabel10.setText("Bill Number");
jTextField1.setEditable(false);
jLabel12.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
jLabel12.setText("Amount");
jButton1.setText("Settle");
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jTextField1)
.addComponent(jTextField2)))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(45, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addGap(69, 69, 69)
.addComponent(jLabel8))
.addGroup(jPanel14Layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(txt_customer_bill_search, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel14Layout.createSequentialGroup()
.addGap(74, 74, 74)
.addComponent(lbl_customer_bill_results)))
.addContainerGap(21, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel14Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jLabel8)
.addGap(18, 18, 18)
.addComponent(txt_customer_bill_search, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(lbl_customer_bill_results)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
customer_bill_table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
customer_bill_table.setRowHeight(25);
customer_bill_table.setSelectionBackground(new java.awt.Color(255, 51, 51));
customer_bill_table.getTableHeader().setReorderingAllowed(false);
customer_bill_table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
customer_bill_tableMouseClicked(evt);
}
});
customer_bill_table.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
customer_bill_tableKeyReleased(evt);
}
});
jScrollPane3.setViewportView(customer_bill_table);
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, 645, Short.MAX_VALUE)
.addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jScrollPane3))
.addContainerGap())
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Bill ", jPanel7);
jPanel5.setBackground(new java.awt.Color(51, 102, 255));
jPanel5.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
jPanel5MouseDragged(evt);
}
});
jPanel5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jPanel5MousePressed(evt);
}
});
btn_close.setBackground(new java.awt.Color(255, 255, 255));
btn_close.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btn_close.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_closeMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_closeMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_closeMouseExited(evt);
}
});
lbl_close.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
lbl_close.setText(" x");
javax.swing.GroupLayout btn_closeLayout = new javax.swing.GroupLayout(btn_close);
btn_close.setLayout(btn_closeLayout);
btn_closeLayout.setHorizontalGroup(
btn_closeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_close, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE)
);
btn_closeLayout.setVerticalGroup(
btn_closeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_close, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
);
jLabel9.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("Bill Details");
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(442, 442, 442)
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_close, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel9)
.addComponent(btn_close, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jPanel6.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_home.setBackground(new java.awt.Color(255, 255, 255));
btn_home.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btn_home.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_homeMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_homeMouseExited(evt);
}
});
lbl_home.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lbl_home.setText(" Home");
javax.swing.GroupLayout btn_homeLayout = new javax.swing.GroupLayout(btn_home);
btn_home.setLayout(btn_homeLayout);
btn_homeLayout.setHorizontalGroup(
btn_homeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_home, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
);
btn_homeLayout.setVerticalGroup(
btn_homeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_home, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
);
panel_stock.setBackground(new java.awt.Color(255, 255, 255));
panel_stock.setBorder(javax.swing.BorderFactory.createEtchedBorder());
panel_stock.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
panel_stockMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
panel_stockMouseExited(evt);
}
});
lbl_stock.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lbl_stock.setText(" Stock");
javax.swing.GroupLayout panel_stockLayout = new javax.swing.GroupLayout(panel_stock);
panel_stock.setLayout(panel_stockLayout);
panel_stockLayout.setHorizontalGroup(
panel_stockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_stock, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
panel_stockLayout.setVerticalGroup(
panel_stockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_stock, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
);
panel_free.setBackground(new java.awt.Color(255, 255, 255));
panel_free.setBorder(javax.swing.BorderFactory.createEtchedBorder());
panel_free.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
panel_freeMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
panel_freeMouseExited(evt);
}
});
lbl_free.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lbl_free.setText(" Free");
javax.swing.GroupLayout panel_freeLayout = new javax.swing.GroupLayout(panel_free);
panel_free.setLayout(panel_freeLayout);
panel_freeLayout.setHorizontalGroup(
panel_freeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_free, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
panel_freeLayout.setVerticalGroup(
panel_freeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_free, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
);
panel_exit.setBackground(new java.awt.Color(255, 255, 255));
panel_exit.setBorder(javax.swing.BorderFactory.createEtchedBorder());
panel_exit.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
panel_exitMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
panel_exitMouseExited(evt);
}
});
lbl_exit.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lbl_exit.setText(" Exit");
javax.swing.GroupLayout panel_exitLayout = new javax.swing.GroupLayout(panel_exit);
panel_exit.setLayout(panel_exitLayout);
panel_exitLayout.setHorizontalGroup(
panel_exitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_exit, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
panel_exitLayout.setVerticalGroup(
panel_exitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_exit, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(panel_free, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panel_stock, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_home, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panel_exit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(39, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(btn_home, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(72, 72, 72)
.addComponent(panel_stock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(71, 71, 71)
.addComponent(panel_free, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(61, 61, 61)
.addComponent(panel_exit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 919, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 558, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btn_closeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_closeMouseClicked
this.processWindowEvent(
new WindowEvent(
this, WindowEvent.WINDOW_CLOSING));
HomeOverView hm=new HomeOverView();
hm.setVisible(true);
}//GEN-LAST:event_btn_closeMouseClicked
private void btn_closeMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_closeMouseEntered
lbl_close.setForeground(Color.WHITE);
btn_close.setBackground(Color.BLACK);
//System.out.println("MouseEntered");
}//GEN-LAST:event_btn_closeMouseEntered
private void btn_closeMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_closeMouseExited
lbl_close.setForeground(Color.BLACK);
btn_close.setBackground(Color.WHITE);
System.out.println("MouseExisted");
}//GEN-LAST:event_btn_closeMouseExited
private void btn_homeMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_homeMouseEntered
lbl_home.setForeground(Color.WHITE);
btn_home.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_homeMouseEntered
private void btn_homeMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_homeMouseExited
lbl_home.setForeground(Color.BLACK);
btn_home.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_homeMouseExited
private void panel_stockMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_panel_stockMouseEntered
lbl_stock.setForeground(Color.WHITE);
panel_stock.setBackground(Color.BLACK);
}//GEN-LAST:event_panel_stockMouseEntered
private void panel_stockMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_panel_stockMouseExited
lbl_stock.setForeground(Color.BLACK);
panel_stock.setBackground(Color.WHITE);
}//GEN-LAST:event_panel_stockMouseExited
private void panel_freeMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_panel_freeMouseEntered
lbl_free.setForeground(Color.WHITE);
panel_free.setBackground(Color.BLACK);
}//GEN-LAST:event_panel_freeMouseEntered
private void panel_freeMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_panel_freeMouseExited
lbl_free.setForeground(Color.BLACK);
panel_free.setBackground(Color.WHITE);
}//GEN-LAST:event_panel_freeMouseExited
private void panel_exitMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_panel_exitMouseEntered
lbl_exit.setForeground(Color.WHITE);
panel_exit.setBackground(Color.BLACK);
}//GEN-LAST:event_panel_exitMouseEntered
private void panel_exitMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_panel_exitMouseExited
lbl_exit.setForeground(Color.BLACK);
panel_exit.setBackground(Color.WHITE);
}//GEN-LAST:event_panel_exitMouseExited
private void jPanel5MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel5MouseDragged
int X=evt.getXOnScreen();
int Y=evt.getYOnScreen();
setLocation(X-Xloc, Y-Yloc);
}//GEN-LAST:event_jPanel5MouseDragged
private void jPanel5MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel5MousePressed
Xloc=evt.getX();
Yloc=evt.getY();
}//GEN-LAST:event_jPanel5MousePressed
private void btn_finishedMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_finishedMouseExited
lbl_finish.setForeground(Color.BLACK);
btn_finished.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_finishedMouseExited
private void btn_finishedMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_finishedMouseEntered
lbl_finish.setForeground(Color.WHITE);
btn_finished.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_finishedMouseEntered
private void btn_finishedMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_finishedMouseClicked
update_stock_details(get_current_bill_details());
String sql="update bill_details set check_val =1 where check_val=0";
try {
ps=con.prepareStatement(sql);
ps.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
ps.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
txt_count.setText("");
combo_product.removeAllItems();
setCombo();
display();
txt_billno.setText("");
}//GEN-LAST:event_btn_finishedMouseClicked
private void btn_add_billMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_add_billMouseExited
lbl_add_bill.setForeground(Color.BLACK);
btn_add_bill.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_add_billMouseExited
private void btn_add_billMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_add_billMouseEntered
lbl_add_bill.setForeground(Color.WHITE);
btn_add_bill.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_add_billMouseEntered
private void btn_stock_detailsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_stock_detailsMouseExited
lbl_stock_details.setForeground(Color.BLACK);
btn_stock_details.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_stock_detailsMouseExited
private void btn_stock_detailsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_stock_detailsMouseEntered
lbl_stock_details.setForeground(Color.WHITE);
btn_stock_details.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_stock_detailsMouseEntered
private void btn_stock_detailsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_stock_detailsMouseClicked
btn_bill_details.setVisible(true);
btn_stock_details.setVisible(false);
set_current_stock_details();
combo_product.removeAllItems();
setCombo();
btn_delete.setVisible(false);
btn_cancel.setVisible(false);
btn_add.setVisible(true);
btn_update.setVisible(false);
txt_billno_search.setText("");
txt_billno.setText("");
txt_count.setText("");
txt_date.setDate(null);
lbl_result.setText("");
getAvailableStock();
}//GEN-LAST:event_btn_stock_detailsMouseClicked
private void btn_bill_detailsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_bill_detailsMouseExited
lbl_current_bill_details.setForeground(Color.BLACK);
btn_bill_details.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_bill_detailsMouseExited
private void btn_bill_detailsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_bill_detailsMouseEntered
lbl_current_bill_details.setForeground(Color.WHITE);
btn_bill_details.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_bill_detailsMouseEntered
private void btn_bill_detailsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_bill_detailsMouseClicked
btn_bill_details.setVisible(false);
btn_stock_details.setVisible(true);
combo_product.removeAllItems();
setCombo();
btn_delete.setVisible(false);
btn_cancel.setVisible(false);
btn_add.setVisible(true);
btn_update.setVisible(false);
txt_billno_search.setText("");
txt_billno.setText("");
txt_count.setText("");
txt_date.setDate(null);
lbl_result.setText("");
getAvailableStock();
display();
}//GEN-LAST:event_btn_bill_detailsMouseClicked
private void btn_addMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_addMouseExited
lbl_add.setForeground(Color.BLACK);
btn_add.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_addMouseExited
private void btn_addMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_addMouseEntered
lbl_add.setForeground(Color.WHITE);
btn_add.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_addMouseEntered
private void btn_addMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_addMouseClicked
if(check()){
String sql="insert into bill_details(bill_no,pname,count,date) values(?,?,?,?)";
try {
ps=con.prepareStatement(sql);
ps.setString(1,txt_billno.getText());
ps.setString(2,combo_product.getSelectedItem().toString());
ps.setString(3,txt_count.getText());
ps.setString(4,formatter.format(txt_date.getDate()));
ps.execute();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
ps.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
txt_count.setText("");
combo_product.removeAllItems();
setCombo();
display();
}
}//GEN-LAST:event_btn_addMouseClicked
private void txt_billnoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_billnoKeyReleased
String value=txt_billno.getText();
try{
Double.parseDouble(value);
}
catch(NumberFormatException e){
txt_billno.setText("");
JOptionPane.showMessageDialog(null,"Field should include only numbers");
}
}//GEN-LAST:event_txt_billnoKeyReleased
private void txt_countKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_countKeyReleased
boolean ExceptionFound=false;
boolean isExceed=false;
int total=0;
String value=txt_count.getText();
try{
Double.parseDouble(value);
}
catch(NumberFormatException e){
ExceptionFound=true;
txt_count.setText("");
//JOptionPane.showMessageDialog(rootPane,"Field should include only numbers");
count_error.setText("Field should include only numbers");
}
if(!ExceptionFound){
String sql="select * from current_stocks where product_name=?";
try {
ps=con.prepareStatement(sql);
ps.setString(1,combo_product.getSelectedItem().toString());
rs=ps.executeQuery();
while(rs.next()){
total=rs.getInt(4);
}
if(Integer.parseInt(txt_count.getText()) > total){
isExceed=true;
txt_count.setText("");
count_error.setText(combo_product.getSelectedItem().toString()+" has only "+total +" in stock");
}
else{
count_error.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
ps.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// if(!isExceed){
//
// }
}//GEN-LAST:event_txt_countKeyReleased
private void txt_billno_searchKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_billno_searchKeyReleased
btn_stock_details.setVisible(true);
btn_bill_details.setVisible(false);
display();
view_current_records("1");
try {
String sql1="select * from bill_details where bill_no like '"+txt_billno_search.getText()+"%' and check_val=1";
st=con.createStatement();
rs=st.executeQuery(sql1);
int size =0;
if (rs != null)
{
rs.last();
size = rs.getRow();
}
if(size == 0){
lbl_result.setForeground(Color.red);
}
else{
lbl_result.setForeground(Color.GREEN);
}
lbl_result.setText(String.valueOf(size)+" Results Found");
} catch (SQLException ex) {
Logger.getLogger(stockDetails.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
st.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(stockDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_txt_billno_searchKeyReleased
private void btn_updateMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_updateMouseExited
lbl_update.setForeground(Color.BLACK);
btn_update.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_updateMouseExited
private void btn_updateMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_updateMouseEntered
lbl_update.setForeground(Color.WHITE);
btn_update.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_updateMouseEntered
private void btn_updateMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_updateMouseClicked
if(check()){
if(current_check_val.equals("0")){
update_details();
show_table("0");
}
else{
update_details();
try{
String sql="update current_stocks set available=available - '"+txt_count.getText()+"' + '"+current_count_value+"' where product_name='"+combo_product.getSelectedItem().toString()+"'";
st=con.createStatement();
st.execute(sql);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally{
try {
st.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
show_table("1");
current_count_value=txt_count.getText();
}
}
}//GEN-LAST:event_btn_updateMouseClicked
private void btn_cancelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_cancelMouseExited
lbl_cancel.setForeground(Color.BLACK);
btn_cancel.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_cancelMouseExited
private void btn_cancelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_cancelMouseEntered
lbl_cancel.setForeground(Color.WHITE);
btn_cancel.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_cancelMouseEntered
private void btn_cancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_cancelMouseClicked
combo_product.removeAllItems();
setCombo();
btn_delete.setVisible(false);
btn_cancel.setVisible(false);
btn_add.setVisible(true);
btn_update.setVisible(false);
txt_billno_search.setText("");
txt_billno.setText("");
txt_count.setText("");
txt_date.setDate(null);
lbl_result.setText("");
getAvailableStock();
if(btn_stock_details.isVisible()){
btn_stock_details.setVisible(true);
btn_bill_details.setVisible(false);
display();
}
else{
display();
}
}//GEN-LAST:event_btn_cancelMouseClicked
private void btn_deleteMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_deleteMouseExited
lbl_delete.setForeground(Color.BLACK);
btn_delete.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_deleteMouseExited
private void btn_deleteMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_deleteMouseEntered
lbl_delete.setForeground(Color.WHITE);
btn_delete.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_deleteMouseEntered
private void btn_deleteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_deleteMouseClicked
if(current_check_val.equals("0")){
deleteRecords("0");
}
else{
try{
String sql="update current_stocks set available=available + '"+txt_count.getText()+"' where product_name='"+combo_product.getSelectedItem().toString()+"'";
st=con.createStatement();
st.execute(sql);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally{
try {
st.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
deleteRecords("1");
}
}//GEN-LAST:event_btn_deleteMouseClicked
private void bill_tableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bill_tableKeyReleased
if(evt.getKeyCode()==KeyEvent.VK_DOWN || evt.getKeyCode()==KeyEvent.VK_UP){
if(btn_stock_details.isVisible()){
btn_update.setVisible(true);
combo_product.removeAllItems();
btn_cancel.setVisible(true);
btn_delete.setVisible(true);
btn_add.setVisible(false);
bill_id=(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),0)));
current_count_value=(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),3)));
txt_billno.setText(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),1)));
txt_count.setText(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),3)));
Date dateValue3=null;
SimpleDateFormat date3 = new SimpleDateFormat("dd/MM/yyyy");
try {
dateValue3 = date3.parse(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),4)));
txt_date.setDate(dateValue3);
} catch (ParseException ex) {
JOptionPane.showMessageDialog(null, ex);
}
combo_product.addItem(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),2)));
current_check_val=(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),5)));
getAvailableStock();
}
}
}//GEN-LAST:event_bill_tableKeyReleased
private void bill_tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bill_tableMouseClicked
if(btn_stock_details.isVisible()){
combo_product.removeAllItems();
bill_id=(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),0)));
txt_billno.setText(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),1)));
Date dateValue3=null;
SimpleDateFormat date3 = new SimpleDateFormat("dd/MM/yyyy");
try {
dateValue3 = date3.parse(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),4)));
txt_date.setDate(dateValue3);
} catch (ParseException ex) {
JOptionPane.showMessageDialog(null, ex);
}
current_count_value=(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),3)));
txt_count.setText(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),3)));
combo_product.addItem(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),2)));
btn_delete.setVisible(true);
btn_cancel.setVisible(true);
btn_add.setVisible(false);
btn_update.setVisible(true);
current_check_val=(String.valueOf(model.getValueAt(bill_table.getSelectedRow(),5)));
getAvailableStock();
}
}//GEN-LAST:event_bill_tableMouseClicked
private void btn_update_bill_detailsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_update_bill_detailsMouseEntered
lbl_update_bill_details.setForeground(Color.WHITE);
btn_update_bill_details.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_update_bill_detailsMouseEntered
private void btn_update_bill_detailsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_update_bill_detailsMouseExited
lbl_update_bill_details.setForeground(Color.BLACK);
btn_update_bill_details.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_update_bill_detailsMouseExited
private void btn_delete_bill_detailsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_delete_bill_detailsMouseEntered
lbl_delete_bill_details.setForeground(Color.WHITE);
btn_delete_bill_details.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_delete_bill_detailsMouseEntered
private void btn_delete_bill_detailsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_delete_bill_detailsMouseExited
lbl_delete_bill_details.setForeground(Color.BLACK);
btn_delete_bill_details.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_delete_bill_detailsMouseExited
private void btn_cancel_bill_detailsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_cancel_bill_detailsMouseEntered
lbl_cancel_bill_details.setForeground(Color.WHITE);
btn_cancel_bill_details.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_cancel_bill_detailsMouseEntered
private void btn_cancel_bill_detailsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_cancel_bill_detailsMouseExited
lbl_cancel_bill_details.setForeground(Color.BLACK);
btn_cancel_bill_details.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_cancel_bill_detailsMouseExited
private void display_customer_bill_table(){
String sql = "SELECT * FROM customer_bill";
try{
st=con.createStatement();
rs=st.executeQuery(sql);
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
finally{
customer_bill_table.setModel(DbUtils.resultSetToTableModel(rs));//show all bill details in a table
model2=(DefaultTableModel)customer_bill_table.getModel();//currently add
try {
st.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private boolean check_customer_details(){
boolean isValidated=true;
if(txt_bill_number1.getText().isEmpty()){
lbl_bill_number_error.setText("Bill Number is Required");
isValidated=false;
}
else{
lbl_bill_number_error.setText("");
}
if(txt_customer_name.getText().isEmpty()){
lbl_customerName_error.setText("Customer name is Required");
isValidated=false;
}
else{
lbl_customerName_error.setText("");
}
if(txt_customer_paid.getText().isEmpty()){
lbl_customer_paid_error.setText(" Paid Amount is Required");
isValidated=false;
}
else{
lbl_customer_paid_error.setText("");
}
if(txt_amount.getText().isEmpty()){
lbl_amount_error.setText("Amount is Required");
isValidated=false;
}
else{
lbl_amount_error.setText("");
}
return isValidated;
}
private void btn_add_bill_detailsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_add_bill_detailsMouseClicked
if(check_customer_details()){
try{
String sql="insert into customer_bill(id,name,price,paid) values(?,?,?,?)";
ps=con.prepareStatement(sql);
ps.setString(1, txt_bill_number1.getText());
ps.setString(2,txt_customer_name.getText());
ps.setString(3,txt_amount.getText());
ps.setString(4,txt_customer_paid.getText());
ps.execute();
JOptionPane.showMessageDialog(null,"Sucessfully Inserted");
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
finally{
try {
ps.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
txt_bill_number1.setText("");
txt_customer_name.setText("");
txt_customer_paid.setText("");
txt_amount.setText("");
display_customer_bill_table();
}
}//GEN-LAST:event_btn_add_bill_detailsMouseClicked
private void btn_add_bill_detailsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_add_bill_detailsMouseEntered
lbl_add_bill_details.setForeground(Color.WHITE);
btn_add_bill_details.setBackground(Color.BLACK);
}//GEN-LAST:event_btn_add_bill_detailsMouseEntered
private void btn_add_bill_detailsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_add_bill_detailsMouseExited
lbl_add_bill_details.setForeground(Color.BLACK);
btn_add_bill_details.setBackground(Color.WHITE);
}//GEN-LAST:event_btn_add_bill_detailsMouseExited
private void customer_bill_tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_customer_bill_tableMouseClicked
lbl_bill_number_error.setText("");
lbl_customerName_error.setText("");
lbl_amount_error.setText("");
lbl_customer_paid_error.setText("");
txt_bill_number1.setText(String.valueOf(model2.getValueAt(customer_bill_table.getSelectedRow(),0)));
txt_customer_name.setText(String.valueOf(model2.getValueAt(customer_bill_table.getSelectedRow(),1)));
txt_amount.setText(String.valueOf(model2.getValueAt(customer_bill_table.getSelectedRow(),2)));
txt_customer_paid.setText(String.valueOf(model2.getValueAt(customer_bill_table.getSelectedRow(),3)));
Customer_bill_id=String.valueOf(model2.getValueAt(customer_bill_table.getSelectedRow(),0));
btn_add_bill_details.setVisible(false);
btn_delete_bill_details.setVisible(true);
btn_update_bill_details.setVisible(true);
btn_delete_bill_details.setVisible(true);
btn_cancel_bill_details.setVisible(true);
}//GEN-LAST:event_customer_bill_tableMouseClicked
private void customer_bill_tableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_customer_bill_tableKeyReleased
if(evt.getKeyCode()==KeyEvent.VK_DOWN || evt.getKeyCode()==KeyEvent.VK_UP){
lbl_bill_number_error.setText("");
lbl_customerName_error.setText("");
lbl_amount_error.setText("");
lbl_customer_paid_error.setText("");
txt_bill_number1.setText(String.valueOf(model2.getValueAt(customer_bill_table.getSelectedRow(),0)));
txt_customer_name.setText(String.valueOf(model2.getValueAt(customer_bill_table.getSelectedRow(),1)));
txt_amount.setText(String.valueOf(model2.getValueAt(customer_bill_table.getSelectedRow(),2)));
txt_customer_paid.setText(String.valueOf(model2.getValueAt(customer_bill_table.getSelectedRow(),3)));
Customer_bill_id=String.valueOf(model2.getValueAt(customer_bill_table.getSelectedRow(),0));
btn_add_bill_details.setVisible(false);
btn_delete_bill_details.setVisible(true);
btn_update_bill_details.setVisible(true);
btn_delete_bill_details.setVisible(true);
btn_cancel_bill_details.setVisible(true);
}
}//GEN-LAST:event_customer_bill_tableKeyReleased
private void btn_cancel_bill_detailsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_cancel_bill_detailsMouseClicked
btn_add_bill_details.setVisible(true);
btn_delete_bill_details.setVisible(false);
btn_update_bill_details.setVisible(false);
btn_delete_bill_details.setVisible(false);
btn_cancel_bill_details.setVisible(false);
txt_bill_number1.setText("");
txt_customer_name.setText("");
txt_customer_paid.setText("");
txt_amount.setText("");
}//GEN-LAST:event_btn_cancel_bill_detailsMouseClicked
private void btn_delete_bill_detailsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_delete_bill_detailsMouseClicked
// TODO add your handling code here:
try{
String sql="delete from customer_bill where id=?";
ps=con.prepareStatement(sql);
ps.setString(1, txt_bill_number1.getText());
ps.executeUpdate();
JOptionPane.showMessageDialog(null,"Deleted Successfully");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally{
try {
ps.close();
display_customer_bill_table();
set_customer_bill_details();
}
catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_btn_delete_bill_detailsMouseClicked
private void btn_update_bill_detailsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_update_bill_detailsMouseClicked
if(check_customer_details()){
try{
String sql="update customer_bill set id=?,name=?,price=?,paid=? where id='"+ Customer_bill_id+"'";
ps=con.prepareStatement(sql);
ps.setString(1,txt_bill_number1.getText());
ps.setString(2,txt_customer_name.getText());
ps.setString(3,txt_amount.getText());
ps.setString(4,txt_customer_paid.getText());
ps.execute();
JOptionPane.showMessageDialog(null,"Update Sucessfully");
}
catch(SQLException e1){
JOptionPane.showMessageDialog(null, "Bill id already in use..");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally{
try {
ps.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
display_customer_bill_table();
}
}
}//GEN-LAST:event_btn_update_bill_detailsMouseClicked
private void txt_customer_bill_searchKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_customer_bill_searchKeyReleased
try{
String sql="select * from customer_bill where id like '"+txt_customer_bill_search.getText()+"%'";
st=con.createStatement();
rs=st.executeQuery(sql);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally{
customer_bill_table.setModel(DbUtils.resultSetToTableModel(rs));//show all employee details in a table
model2=(DefaultTableModel)customer_bill_table.getModel();//currently add
try {
st.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
String sql1="select * from customer_bill where id like '"+txt_customer_bill_search.getText()+"%'";
st=con.createStatement();
rs=st.executeQuery(sql1);
int size =0;
if (rs != null)
{
rs.last();
size = rs.getRow();
}
if(size == 0){
lbl_customer_bill_results.setForeground(Color.red);
}
else{
lbl_customer_bill_results.setForeground(Color.GREEN);
}
lbl_customer_bill_results.setText(String.valueOf(size)+" Results Found");
} catch (SQLException ex) {
Logger.getLogger(stockDetails.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
st.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(stockDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_txt_customer_bill_searchKeyReleased
private void set_customer_bill_details(){
String sql = "SELECT * FROM customer_bill";
try{
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs.next()){
txt_bill_number1.setText(rs.getString(1));
txt_customer_name.setText(rs.getString(2));
txt_amount.setText(rs.getString(3));
txt_customer_name.setText(rs.getString(4));
}
else{
txt_bill_number1.setText("");
txt_customer_name.setText("");
txt_customer_paid.setText("");
txt_amount.setText("");
btn_update_bill_details.setVisible(false);
btn_delete_bill_details.setVisible(false);
btn_cancel_bill_details.setVisible(false);
btn_add_bill_details.setVisible(true);
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
finally{
try {
st.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void getAvailableStock(){
int total=0;
count_error.setForeground(Color.BLUE);
String sql="select * from current_stocks where product_name=?";
try {
ps=con.prepareStatement(sql);
ps.setString(1,combo_product.getSelectedItem().toString());
rs=ps.executeQuery();
while(rs.next()){
total=rs.getInt(4);
}
count_error.setText(combo_product.getSelectedItem().toString()+" has only "+total +" in stock");
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
ps.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void view_current_records(String value){
try{
String sql="select * from bill_details where bill_no like '"+txt_billno_search.getText()+"%' and check_val='"+value+"'";
st=con.createStatement();
rs=st.executeQuery(sql);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally{
bill_table.setModel(DbUtils.resultSetToTableModel(rs));//show all employee details in a table
model=(DefaultTableModel)bill_table.getModel();//currently add
try {
st.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void show_table(String value){
try {
String sql1="select * from bill_details where bill_no like '"+txt_billno_search.getText()+"%' and check_val='"+value+"'";
st=con.createStatement();
rs=st.executeQuery(sql1);
int size =0;
if (rs != null)
{
rs.last();
size = rs.getRow();
}
if(size == 0){
display();
}
else{
view_current_records("1");
}
} catch (SQLException ex) {
Logger.getLogger(stockDetails.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
st.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(stockDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void deleteRecords(String value){
try{
String sql="delete from bill_details where id=?";
ps=con.prepareStatement(sql);
ps.setString(1, bill_id);
ps.executeUpdate();
JOptionPane.showMessageDialog(null,"Deleted Successfully");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally{
try {
ps.close();
show_table(value);
}
catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
} private void update_details(){
try{
String sql="update bill_details set bill_no=?,count=?,date=? where id='"+bill_id+"'";
ps=con.prepareStatement(sql);
ps.setString(1, txt_billno.getText());
ps.setString(2,txt_count.getText());
ps.setString(3,formatter.format(txt_date.getDate()));
ps.execute();
JOptionPane.showMessageDialog(null,"Sucessfully Updated");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally{
try {
ps.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
} private boolean check(){
boolean isCorrect=true;
if(txt_count.getText().isEmpty()){
isCorrect=false;
count_error.setText("Field is Empty");
}
else{
count_error.setText("");
}
if(txt_billno.getText().isEmpty()){
isCorrect=false;
bill_error.setText("bill number is Empty");
}
else{
bill_error.setText("");
}
if(txt_date.getDate()==null){
isCorrect=false;
date_error.setText("Date is Empty");
}
else{
date_error.setText("");
}
return isCorrect;
}
private ArrayList<products> get_current_bill_details(){
ArrayList<products> bill_list=new ArrayList<>();
String sql="SELECT b.*,c.available,c.pid FROM bill_details b,current_stocks c where b.pname=c.product_name and b.check_val=0";
try {
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
products p1=new products();
p1.setProduct_id(rs.getString(7));
p1.setProduct_name(rs.getString(3));
p1.setCount(rs.getString(4));
p1.setAvailable(rs.getString(6));
bill_list.add(p1);
}
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
ps.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
return bill_list;
}
private void update_stock_details(ArrayList<products> bill_list){
String sql="update current_stocks set available=? where pid=?";
bill_list.forEach(new Consumer<products>() {
@Override
public void accept(products p1) {
try {
ps=con.prepareStatement(sql);
ps.setString(1, String.valueOf(Integer.parseInt(p1.getAvailable())-Integer.parseInt(p1.getCount())));
ps.setString(2,p1.getProduct_id());
ps.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
ps.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(billDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
} private void set_current_stock_details(){
model1= new DefaultTableModel(new String[]{"product_id", "product_name", "Instock"}, 0);
String sql="select * from current_stocks";
try {
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
model1.addRow(new Object[]{rs.getString(2),rs.getString(3),rs.getString(4)});
}
} catch (SQLException ex) {
Logger.getLogger(stockDetails.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
ps.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(stockDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
bill_table.setModel(model1);
}
/**
* @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(billDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(billDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(billDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(billDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new billDetails().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel bill_error;
private javax.swing.JTable bill_table;
private javax.swing.JPanel btn_add;
private javax.swing.JPanel btn_add_bill;
private javax.swing.JPanel btn_add_bill_details;
private javax.swing.JPanel btn_bill_details;
private javax.swing.JPanel btn_cancel;
private javax.swing.JPanel btn_cancel_bill_details;
private javax.swing.JPanel btn_close;
private javax.swing.JPanel btn_delete;
private javax.swing.JPanel btn_delete_bill_details;
private javax.swing.JPanel btn_finished;
private javax.swing.JPanel btn_home;
private javax.swing.JPanel btn_stock_details;
private javax.swing.JPanel btn_update;
private javax.swing.JPanel btn_update_bill_details;
private javax.swing.JComboBox<String> combo_product;
private javax.swing.JLabel count_error;
private javax.swing.JTable customer_bill_table;
private javax.swing.JLabel date_error;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
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.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JSeparator jSeparator6;
private javax.swing.JSeparator jSeparator7;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JLabel lbl_add;
private javax.swing.JLabel lbl_add_bill;
private javax.swing.JLabel lbl_add_bill_details;
private javax.swing.JLabel lbl_amount_error;
private javax.swing.JLabel lbl_bill;
private javax.swing.JLabel lbl_bill_number_error;
private javax.swing.JLabel lbl_cancel;
private javax.swing.JLabel lbl_cancel_bill_details;
private javax.swing.JLabel lbl_close;
private javax.swing.JLabel lbl_current_bill_details;
private javax.swing.JLabel lbl_customerName_error;
private javax.swing.JLabel lbl_customer_bill_results;
private javax.swing.JLabel lbl_customer_paid_error;
private javax.swing.JLabel lbl_delete;
private javax.swing.JLabel lbl_delete_bill_details;
private javax.swing.JLabel lbl_exit;
private javax.swing.JLabel lbl_finish;
private javax.swing.JLabel lbl_free;
private javax.swing.JLabel lbl_home;
private javax.swing.JLabel lbl_result;
private javax.swing.JLabel lbl_stock;
private javax.swing.JLabel lbl_stock_details;
private javax.swing.JLabel lbl_update;
private javax.swing.JLabel lbl_update_bill_details;
private javax.swing.JPanel panel_exit;
private javax.swing.JPanel panel_free;
private javax.swing.JPanel panel_stock;
private javax.swing.JTextField txt_amount;
private javax.swing.JTextField txt_bill_number1;
private javax.swing.JTextField txt_billno;
private javax.swing.JTextField txt_billno_search;
private javax.swing.JTextField txt_count;
private javax.swing.JTextField txt_customer_bill_search;
private javax.swing.JTextField txt_customer_name;
private javax.swing.JTextField txt_customer_paid;
private com.toedter.calendar.JDateChooser txt_date;
// End of variables declaration//GEN-END:variables
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.