blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
1eae55ef865f21dfee861146a1a06c8445f4a1f4 | Java | acslocum/testInvocationSpeed | /src/info/sample/Looper.java | UTF-8 | 1,072 | 3.09375 | 3 | [] | no_license | package info.sample;
import java.util.Random;
public class Looper {
static long seed;
public Looper(long aSeed) {
seed = aSeed;
}
public boolean loopDynamic(int count) {
Random rand = new Random(seed);
boolean result = false;
for(int i=0; i<count; i++){
if(rand.nextBoolean()) {
result = new Bar().doY(rand.nextDouble() > 0.5);
} else {
result = new Foo().doX(rand.nextDouble() > 0.5);
}
}
return result;
}
public boolean loopStatic(int count) {
Random rand = new Random(seed);
boolean result = false;
for(int i=0; i<count; i++){
if(rand.nextBoolean()) {
result = StaticBar.doY(rand.nextDouble() > 0.5);
} else {
result = StaticFoo.doX(rand.nextDouble() > 0.5);
}
}
return result;
}
public boolean loopSubclass(int count) {
Random rand = new Random(seed);
boolean result = false;
for(int i=0; i<count; i++){
if(rand.nextBoolean()) {
result = new SubBar().doY(rand.nextDouble() > 0.5);
} else {
result = new SubFoo().doX(rand.nextDouble() > 0.5);
}
}
return result;
}
}
| true |
17e9ee858ebe51e1f64cdd01a2bf89075e2572fc | Java | thegauravjawla/pepCoding | /java/07.07.19/subSequence.java | UTF-8 | 543 | 3.1875 | 3 | [] | no_license | import java.util.*;
public class subSequence
{
public static void seq(String s, String ans)
{
if(s.length() == 0)
{
System.out.println(ans);
return;
}
char firstChar = s.charAt(0);
String restString = s.substring(1, s.length());
seq(restString, ans + firstChar);
seq(restString, ans + "-");
}
public static void main(String[] argc)
{
Scanner scn = new Scanner(System.in);
String s = scn.nextLine();
seq(s, "");
}
} | true |
c8aa9e154b642012c536f28257d0cc1d74e2a1b6 | Java | Vyacheslav-Lapin/SpringFundamentals4 | /src/main/java/BankApplication.java | UTF-8 | 272 | 2.453125 | 2 | [] | no_license | public class BankApplication {
private CompanyReport companyReport;
public void setCompanyReport(CompanyReport companyReport) {
this.companyReport = companyReport;
}
public CompanyReport getCompanyReport() {
return companyReport;
}
}
| true |
9b633fcce4c729400ad395f635bcb9f29ed7e3a3 | Java | Lamashino/Teaching-B4J-Spanish | /Tema 19 - Proyecto Final/Tema 19 - Solución/B4J/Objects/src/b4j/example/anotherprogressbar.java | UTF-8 | 32,703 | 1.828125 | 2 | [
"CC-BY-4.0"
] | permissive | package b4j.example;
import anywheresoftware.b4a.debug.*;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.B4AClass;
public class anotherprogressbar extends B4AClass.ImplB4AClass implements BA.SubDelegator{
public static java.util.HashMap<String, java.lang.reflect.Method> htSubs;
private void innerInitialize(BA _ba) throws Exception {
if (ba == null) {
ba = new anywheresoftware.b4a.shell.ShellBA("b4j.example", "b4j.example.anotherprogressbar", this);
if (htSubs == null) {
ba.loadHtSubs(this.getClass());
htSubs = ba.htSubs;
}
ba.htSubs = htSubs;
}
if (BA.isShellModeRuntimeCheck(ba))
this.getClass().getMethod("_class_globals", b4j.example.anotherprogressbar.class).invoke(this, new Object[] {null});
else
ba.raiseEvent2(null, true, "class_globals", false);
}
public void innerInitializeHelper(anywheresoftware.b4a.BA _ba) throws Exception{
innerInitialize(_ba);
}
public Object callSub(String sub, Object sender, Object[] args) throws Exception {
return BA.SubDelegator.SubNotFound;
}
public anywheresoftware.b4a.keywords.Common __c = null;
public String _meventname = "";
public Object _mcallback = null;
public anywheresoftware.b4a.objects.B4XViewWrapper _mbase = null;
public anywheresoftware.b4a.objects.B4XViewWrapper.XUI _xui = null;
public b4j.example.bcpath._bcbrush _busybrush = null;
public int _backgroundcolor = 0;
public int _busyindex = 0;
public b4j.example.bitmapcreator _bc = null;
public anywheresoftware.b4a.objects.B4XViewWrapper _miv = null;
public b4j.example.bcpath._bcbrush _transparentbrush = null;
public boolean _vertical = false;
public float _currentvalue = 0f;
public int _emptycolor = 0;
public b4j.example.bcpath._bcbrush _emptybrush = null;
public int _mvalue = 0;
public Object _tag = null;
public float _valuechangepersecond = 0f;
public int _cornerradius = 0;
public int _brushoffsetdelta = 0;
public b4j.example.dateutils _dateutils = null;
public b4j.example.cssutils _cssutils = null;
public b4j.example.main _main = null;
public b4j.example.b4xpages _b4xpages = null;
public b4j.example.b4xcollections _b4xcollections = null;
public b4j.example.xuiviewsutils _xuiviewsutils = null;
public String _base_resize(b4j.example.anotherprogressbar __ref,double _width,double _height) throws Exception{
__ref = this;
RDebugUtils.currentModule="anotherprogressbar";
if (Debug.shouldDelegate(ba, "base_resize", true))
{return ((String) Debug.delegate(ba, "base_resize", new Object[] {_width,_height}));}
anywheresoftware.b4a.objects.B4XViewWrapper _v = null;
RDebugUtils.currentLine=12779520;
//BA.debugLineNum = 12779520;BA.debugLine="Private Sub Base_Resize (Width As Double, Height A";
RDebugUtils.currentLine=12779521;
//BA.debugLineNum = 12779521;BA.debugLine="For Each v As B4XView In mBase.GetAllViewsRecursi";
_v = new anywheresoftware.b4a.objects.B4XViewWrapper();
{
final anywheresoftware.b4a.BA.IterableList group1 = __ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .GetAllViewsRecursive();
final int groupLen1 = group1.getSize()
;int index1 = 0;
;
for (; index1 < groupLen1;index1++){
_v = (anywheresoftware.b4a.objects.B4XViewWrapper) anywheresoftware.b4a.AbsObjectWrapper.ConvertToWrapper(new anywheresoftware.b4a.objects.B4XViewWrapper(), (java.lang.Object)(group1.Get(index1)));
RDebugUtils.currentLine=12779522;
//BA.debugLineNum = 12779522;BA.debugLine="v.SetLayoutAnimated(0, 0, 0, Width, Height)";
_v.SetLayoutAnimated((int) (0),0,0,_width,_height);
}
};
RDebugUtils.currentLine=12779524;
//BA.debugLineNum = 12779524;BA.debugLine="bc.Initialize(mBase.Width / xui.Scale, mBase.Heig";
__ref._bc /*b4j.example.bitmapcreator*/ ._initialize(ba,(int) (__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getWidth()/(double)__ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .getScale()),(int) (__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getHeight()/(double)__ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .getScale()));
RDebugUtils.currentLine=12779525;
//BA.debugLineNum = 12779525;BA.debugLine="Vertical = mBase.Height > mBase.Width";
__ref._vertical /*boolean*/ = __ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getHeight()>__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getWidth();
RDebugUtils.currentLine=12779526;
//BA.debugLineNum = 12779526;BA.debugLine="UpdateGraphics";
__ref._updategraphics /*String*/ (null);
RDebugUtils.currentLine=12779528;
//BA.debugLineNum = 12779528;BA.debugLine="End Sub";
return "";
}
public String _updategraphics(b4j.example.anotherprogressbar __ref) throws Exception{
__ref = this;
RDebugUtils.currentModule="anotherprogressbar";
if (Debug.shouldDelegate(ba, "updategraphics", true))
{return ((String) Debug.delegate(ba, "updategraphics", null));}
int _width = 0;
b4j.example.bitmapcreator _template = null;
b4j.example.bitmapcreator._argbcolor _bcolor = null;
RDebugUtils.currentLine=12910592;
//BA.debugLineNum = 12910592;BA.debugLine="Public Sub UpdateGraphics";
RDebugUtils.currentLine=12910593;
//BA.debugLineNum = 12910593;BA.debugLine="EmptyBrush = bc.CreateBrushFromColor(EmptyColor)";
__ref._emptybrush /*b4j.example.bcpath._bcbrush*/ = __ref._bc /*b4j.example.bitmapcreator*/ ._createbrushfromcolor(__ref._emptycolor /*int*/ );
RDebugUtils.currentLine=12910594;
//BA.debugLineNum = 12910594;BA.debugLine="TransparentBrush = bc.CreateBrushFromColor(xui.Co";
__ref._transparentbrush /*b4j.example.bcpath._bcbrush*/ = __ref._bc /*b4j.example.bitmapcreator*/ ._createbrushfromcolor(__ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .Color_Transparent);
RDebugUtils.currentLine=12910595;
//BA.debugLineNum = 12910595;BA.debugLine="Dim Width As Int = 40";
_width = (int) (40);
RDebugUtils.currentLine=12910596;
//BA.debugLineNum = 12910596;BA.debugLine="Dim Template As BitmapCreator";
_template = new b4j.example.bitmapcreator();
RDebugUtils.currentLine=12910597;
//BA.debugLineNum = 12910597;BA.debugLine="Dim bcolor As ARGBColor";
_bcolor = new b4j.example.bitmapcreator._argbcolor();
RDebugUtils.currentLine=12910598;
//BA.debugLineNum = 12910598;BA.debugLine="bc.ColorToARGB(BackgroundColor, bcolor)";
__ref._bc /*b4j.example.bitmapcreator*/ ._colortoargb(__ref._backgroundcolor /*int*/ ,_bcolor);
RDebugUtils.currentLine=12910599;
//BA.debugLineNum = 12910599;BA.debugLine="bcolor.r = Min(255, bcolor.r * 1.5)";
_bcolor.r = (int) (__c.Min(255,_bcolor.r*1.5));
RDebugUtils.currentLine=12910600;
//BA.debugLineNum = 12910600;BA.debugLine="bcolor.g = Min(255, bcolor.g * 1.5)";
_bcolor.g = (int) (__c.Min(255,_bcolor.g*1.5));
RDebugUtils.currentLine=12910601;
//BA.debugLineNum = 12910601;BA.debugLine="bcolor.b = Min(255, bcolor.b * 1.5)";
_bcolor.b = (int) (__c.Min(255,_bcolor.b*1.5));
RDebugUtils.currentLine=12910602;
//BA.debugLineNum = 12910602;BA.debugLine="If Vertical Then";
if (__ref._vertical /*boolean*/ ) {
RDebugUtils.currentLine=12910603;
//BA.debugLineNum = 12910603;BA.debugLine="Template.Initialize(mBase.Width / xui.Scale, mBa";
_template._initialize(ba,(int) (__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getWidth()/(double)__ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .getScale()),(int) (__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getWidth()/(double)__ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .getScale()+_width));
}else {
RDebugUtils.currentLine=12910605;
//BA.debugLineNum = 12910605;BA.debugLine="Template.Initialize(mBase.Height / xui.Scale + W";
_template._initialize(ba,(int) (__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getHeight()/(double)__ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .getScale()+_width),(int) (__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getHeight()/(double)__ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .getScale()));
};
RDebugUtils.currentLine=12910608;
//BA.debugLineNum = 12910608;BA.debugLine="Template.DrawRect(Template.TargetRect, Background";
_template._drawrect(_template._targetrect,__ref._backgroundcolor /*int*/ ,__c.True,(int) (0));
RDebugUtils.currentLine=12910609;
//BA.debugLineNum = 12910609;BA.debugLine="If Vertical Then";
if (__ref._vertical /*boolean*/ ) {
RDebugUtils.currentLine=12910610;
//BA.debugLineNum = 12910610;BA.debugLine="Template.DrawLine(-Width / 2, Width / 2, Templat";
_template._drawline((float) (-_width/(double)2),(float) (_width/(double)2),(float) (_template._mwidth+_width/(double)2),(float) (_template._mheight-_width/(double)2),__ref._bc /*b4j.example.bitmapcreator*/ ._argbtocolor(_bcolor),_width);
}else {
RDebugUtils.currentLine=12910612;
//BA.debugLineNum = 12910612;BA.debugLine="Template.DrawLine(Width / 2, -Width / 2, Templat";
_template._drawline((float) (_width/(double)2),(float) (-_width/(double)2),(float) (_template._mwidth-_width/(double)2),(float) (_template._mheight+_width/(double)2),__ref._bc /*b4j.example.bitmapcreator*/ ._argbtocolor(_bcolor),_width);
};
RDebugUtils.currentLine=12910614;
//BA.debugLineNum = 12910614;BA.debugLine="BusyBrush = bc.CreateBrushFromBitmapCreator(Templ";
__ref._busybrush /*b4j.example.bcpath._bcbrush*/ = __ref._bc /*b4j.example.bitmapcreator*/ ._createbrushfrombitmapcreator(_template);
RDebugUtils.currentLine=12910615;
//BA.debugLineNum = 12910615;BA.debugLine="If mValue = 100 Then";
if (__ref._mvalue /*int*/ ==100) {
RDebugUtils.currentLine=12910616;
//BA.debugLineNum = 12910616;BA.debugLine="bc.DrawRectRounded(bc.TargetRect, BackgroundColo";
__ref._bc /*b4j.example.bitmapcreator*/ ._drawrectrounded(__ref._bc /*b4j.example.bitmapcreator*/ ._targetrect,__ref._backgroundcolor /*int*/ ,__c.True,(int) (0),(int) (15));
}else {
RDebugUtils.currentLine=12910618;
//BA.debugLineNum = 12910618;BA.debugLine="bc.DrawRectRounded2(bc.TargetRect, EmptyBrush, T";
__ref._bc /*b4j.example.bitmapcreator*/ ._drawrectrounded2(__ref._bc /*b4j.example.bitmapcreator*/ ._targetrect,__ref._emptybrush /*b4j.example.bcpath._bcbrush*/ ,__c.True,(int) (0),(int) (15));
};
RDebugUtils.currentLine=12910620;
//BA.debugLineNum = 12910620;BA.debugLine="bc.SetBitmapToImageView(bc.Bitmap, mIV)";
__ref._bc /*b4j.example.bitmapcreator*/ ._setbitmaptoimageview(__ref._bc /*b4j.example.bitmapcreator*/ ._getbitmap(),__ref._miv /*anywheresoftware.b4a.objects.B4XViewWrapper*/ );
RDebugUtils.currentLine=12910621;
//BA.debugLineNum = 12910621;BA.debugLine="setVisible(mBase.Visible)";
__ref._setvisible /*String*/ (null,__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getVisible());
RDebugUtils.currentLine=12910622;
//BA.debugLineNum = 12910622;BA.debugLine="End Sub";
return "";
}
public void _busyloop(b4j.example.anotherprogressbar __ref) throws Exception{
RDebugUtils.currentModule="anotherprogressbar";
if (Debug.shouldDelegate(ba, "busyloop", true))
{Debug.delegate(ba, "busyloop", null); return;}
ResumableSub_BusyLoop rsub = new ResumableSub_BusyLoop(this,__ref);
rsub.resume(ba, null);
}
public static class ResumableSub_BusyLoop extends BA.ResumableSub {
public ResumableSub_BusyLoop(b4j.example.anotherprogressbar parent,b4j.example.anotherprogressbar __ref) {
this.parent = parent;
this.__ref = __ref;
this.__ref = parent;
}
b4j.example.anotherprogressbar __ref;
b4j.example.anotherprogressbar parent;
int _myindex = 0;
anywheresoftware.b4a.objects.B4XCanvas.B4XRect _r = null;
long _lasttime = 0L;
anywheresoftware.b4a.objects.collections.List _tasks = null;
float _delta = 0f;
float _change = 0f;
anywheresoftware.b4a.objects.B4XViewWrapper.B4XBitmapWrapper _bmp = null;
@Override
public void resume(BA ba, Object[] result) throws Exception{
RDebugUtils.currentModule="anotherprogressbar";
while (true) {
switch (state) {
case -1:
return;
case 0:
//C
this.state = 1;
RDebugUtils.currentLine=12845057;
//BA.debugLineNum = 12845057;BA.debugLine="Dim MyIndex As Int = BusyIndex";
_myindex = __ref._busyindex /*int*/ ;
RDebugUtils.currentLine=12845058;
//BA.debugLineNum = 12845058;BA.debugLine="Dim r As B4XRect";
_r = new anywheresoftware.b4a.objects.B4XCanvas.B4XRect();
RDebugUtils.currentLine=12845059;
//BA.debugLineNum = 12845059;BA.debugLine="r.Initialize(0, 0, bc.mWidth, bc.mHeight)";
_r.Initialize((float) (0),(float) (0),(float) (__ref._bc /*b4j.example.bitmapcreator*/ ._mwidth),(float) (__ref._bc /*b4j.example.bitmapcreator*/ ._mheight));
RDebugUtils.currentLine=12845060;
//BA.debugLineNum = 12845060;BA.debugLine="Dim LastTime As Long = DateTime.Now";
_lasttime = parent.__c.DateTime.getNow();
RDebugUtils.currentLine=12845061;
//BA.debugLineNum = 12845061;BA.debugLine="Do While MyIndex = BusyIndex";
if (true) break;
case 1:
//do while
this.state = 37;
while (_myindex==__ref._busyindex /*int*/ ) {
this.state = 3;
if (true) break;
}
if (true) break;
case 3:
//C
this.state = 4;
RDebugUtils.currentLine=12845062;
//BA.debugLineNum = 12845062;BA.debugLine="If Vertical Then";
if (true) break;
case 4:
//if
this.state = 9;
if (__ref._vertical /*boolean*/ ) {
this.state = 6;
}else {
this.state = 8;
}if (true) break;
case 6:
//C
this.state = 9;
RDebugUtils.currentLine=12845063;
//BA.debugLineNum = 12845063;BA.debugLine="BusyBrush.SrcOffsetY = BusyBrush.SrcOffsetY + B";
__ref._busybrush /*b4j.example.bcpath._bcbrush*/ .SrcOffsetY = (int) (__ref._busybrush /*b4j.example.bcpath._bcbrush*/ .SrcOffsetY+__ref._brushoffsetdelta /*int*/ );
if (true) break;
case 8:
//C
this.state = 9;
RDebugUtils.currentLine=12845065;
//BA.debugLineNum = 12845065;BA.debugLine="BusyBrush.SrcOffsetX = BusyBrush.SrcOffsetX + B";
__ref._busybrush /*b4j.example.bcpath._bcbrush*/ .SrcOffsetX = (int) (__ref._busybrush /*b4j.example.bcpath._bcbrush*/ .SrcOffsetX+__ref._brushoffsetdelta /*int*/ );
if (true) break;
case 9:
//C
this.state = 10;
;
RDebugUtils.currentLine=12845067;
//BA.debugLineNum = 12845067;BA.debugLine="Dim tasks As List";
_tasks = new anywheresoftware.b4a.objects.collections.List();
RDebugUtils.currentLine=12845068;
//BA.debugLineNum = 12845068;BA.debugLine="tasks.Initialize";
_tasks.Initialize();
RDebugUtils.currentLine=12845069;
//BA.debugLineNum = 12845069;BA.debugLine="tasks.Add(bc.AsyncDrawRect(bc.TargetRect, Transp";
_tasks.Add((Object)(__ref._bc /*b4j.example.bitmapcreator*/ ._asyncdrawrect(__ref._bc /*b4j.example.bitmapcreator*/ ._targetrect,__ref._transparentbrush /*b4j.example.bcpath._bcbrush*/ ,parent.__c.True,(int) (0))));
RDebugUtils.currentLine=12845070;
//BA.debugLineNum = 12845070;BA.debugLine="Dim delta As Float = mValue - CurrentValue";
_delta = (float) (__ref._mvalue /*int*/ -__ref._currentvalue /*float*/ );
RDebugUtils.currentLine=12845071;
//BA.debugLineNum = 12845071;BA.debugLine="If Abs(delta) <= 1 Then";
if (true) break;
case 10:
//if
this.state = 21;
if (parent.__c.Abs(_delta)<=1) {
this.state = 12;
}else {
this.state = 14;
}if (true) break;
case 12:
//C
this.state = 21;
RDebugUtils.currentLine=12845072;
//BA.debugLineNum = 12845072;BA.debugLine="CurrentValue = mValue";
__ref._currentvalue /*float*/ = (float) (__ref._mvalue /*int*/ );
if (true) break;
case 14:
//C
this.state = 15;
RDebugUtils.currentLine=12845074;
//BA.debugLineNum = 12845074;BA.debugLine="Dim change As Float = (DateTime.Now - LastTime)";
_change = (float) ((parent.__c.DateTime.getNow()-_lasttime)/(double)1000*__ref._valuechangepersecond /*float*/ );
RDebugUtils.currentLine=12845075;
//BA.debugLineNum = 12845075;BA.debugLine="If delta > 0 Then";
if (true) break;
case 15:
//if
this.state = 20;
if (_delta>0) {
this.state = 17;
}else {
this.state = 19;
}if (true) break;
case 17:
//C
this.state = 20;
RDebugUtils.currentLine=12845076;
//BA.debugLineNum = 12845076;BA.debugLine="CurrentValue = CurrentValue + Min(change, mVal";
__ref._currentvalue /*float*/ = (float) (__ref._currentvalue /*float*/ +parent.__c.Min(_change,__ref._mvalue /*int*/ -__ref._currentvalue /*float*/ ));
if (true) break;
case 19:
//C
this.state = 20;
RDebugUtils.currentLine=12845078;
//BA.debugLineNum = 12845078;BA.debugLine="CurrentValue = CurrentValue - Min(change, Curr";
__ref._currentvalue /*float*/ = (float) (__ref._currentvalue /*float*/ -parent.__c.Min(_change,__ref._currentvalue /*float*/ -__ref._mvalue /*int*/ ));
if (true) break;
case 20:
//C
this.state = 21;
;
if (true) break;
case 21:
//C
this.state = 22;
;
RDebugUtils.currentLine=12845081;
//BA.debugLineNum = 12845081;BA.debugLine="LastTime = DateTime.Now";
_lasttime = parent.__c.DateTime.getNow();
RDebugUtils.currentLine=12845082;
//BA.debugLineNum = 12845082;BA.debugLine="If CurrentValue < 100 Then";
if (true) break;
case 22:
//if
this.state = 25;
if (__ref._currentvalue /*float*/ <100) {
this.state = 24;
}if (true) break;
case 24:
//C
this.state = 25;
RDebugUtils.currentLine=12845083;
//BA.debugLineNum = 12845083;BA.debugLine="tasks.Add(bc.AsyncDrawRectRounded(bc.TargetRect";
_tasks.Add((Object)(__ref._bc /*b4j.example.bitmapcreator*/ ._asyncdrawrectrounded(__ref._bc /*b4j.example.bitmapcreator*/ ._targetrect,__ref._emptybrush /*b4j.example.bcpath._bcbrush*/ ,parent.__c.True,(int) (0),__ref._cornerradius /*int*/ )));
if (true) break;
;
RDebugUtils.currentLine=12845085;
//BA.debugLineNum = 12845085;BA.debugLine="If Vertical Then";
case 25:
//if
this.state = 30;
if (__ref._vertical /*boolean*/ ) {
this.state = 27;
}else {
this.state = 29;
}if (true) break;
case 27:
//C
this.state = 30;
RDebugUtils.currentLine=12845086;
//BA.debugLineNum = 12845086;BA.debugLine="r.Bottom = Round(CurrentValue / 100 * bc.mHeigh";
_r.setBottom((float) (parent.__c.Round(__ref._currentvalue /*float*/ /(double)100*__ref._bc /*b4j.example.bitmapcreator*/ ._mheight)));
if (true) break;
case 29:
//C
this.state = 30;
RDebugUtils.currentLine=12845088;
//BA.debugLineNum = 12845088;BA.debugLine="r.Right = Round(CurrentValue / 100 * bc.mWidth)";
_r.setRight((float) (parent.__c.Round(__ref._currentvalue /*float*/ /(double)100*__ref._bc /*b4j.example.bitmapcreator*/ ._mwidth)));
if (true) break;
case 30:
//C
this.state = 31;
;
RDebugUtils.currentLine=12845091;
//BA.debugLineNum = 12845091;BA.debugLine="tasks.Add(bc.AsyncDrawRectRounded(r, BusyBrush,";
_tasks.Add((Object)(__ref._bc /*b4j.example.bitmapcreator*/ ._asyncdrawrectrounded(_r,__ref._busybrush /*b4j.example.bcpath._bcbrush*/ ,parent.__c.True,(int) (0),__ref._cornerradius /*int*/ )));
RDebugUtils.currentLine=12845092;
//BA.debugLineNum = 12845092;BA.debugLine="bc.DrawBitmapCreatorsAsync(Me, \"BC\", tasks)";
__ref._bc /*b4j.example.bitmapcreator*/ ._drawbitmapcreatorsasync(parent,"BC",_tasks);
RDebugUtils.currentLine=12845093;
//BA.debugLineNum = 12845093;BA.debugLine="Wait For BC_BitmapReady (bmp As B4XBitmap)";
parent.__c.WaitFor("bc_bitmapready", ba, new anywheresoftware.b4a.shell.DebugResumableSub.DelegatableResumableSub(this, "anotherprogressbar", "busyloop"), null);
this.state = 38;
return;
case 38:
//C
this.state = 31;
_bmp = (anywheresoftware.b4a.objects.B4XViewWrapper.B4XBitmapWrapper) result[1];
;
RDebugUtils.currentLine=12845094;
//BA.debugLineNum = 12845094;BA.debugLine="If xui.IsB4J Then bmp = bc.Bitmap";
if (true) break;
case 31:
//if
this.state = 36;
if (__ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .getIsB4J()) {
this.state = 33;
;}if (true) break;
case 33:
//C
this.state = 36;
_bmp = __ref._bc /*b4j.example.bitmapcreator*/ ._getbitmap();
if (true) break;
case 36:
//C
this.state = 1;
;
RDebugUtils.currentLine=12845095;
//BA.debugLineNum = 12845095;BA.debugLine="bc.SetBitmapToImageView(bmp, mIV)";
__ref._bc /*b4j.example.bitmapcreator*/ ._setbitmaptoimageview(_bmp,__ref._miv /*anywheresoftware.b4a.objects.B4XViewWrapper*/ );
RDebugUtils.currentLine=12845096;
//BA.debugLineNum = 12845096;BA.debugLine="Sleep(30)";
parent.__c.Sleep(ba,new anywheresoftware.b4a.shell.DebugResumableSub.DelegatableResumableSub(this, "anotherprogressbar", "busyloop"),(int) (30));
this.state = 39;
return;
case 39:
//C
this.state = 1;
;
if (true) break;
case 37:
//C
this.state = -1;
;
RDebugUtils.currentLine=12845098;
//BA.debugLineNum = 12845098;BA.debugLine="End Sub";
if (true) break;
}
}
}
}
public String _class_globals(b4j.example.anotherprogressbar __ref) throws Exception{
__ref = this;
RDebugUtils.currentModule="anotherprogressbar";
RDebugUtils.currentLine=12582912;
//BA.debugLineNum = 12582912;BA.debugLine="Sub Class_Globals";
RDebugUtils.currentLine=12582913;
//BA.debugLineNum = 12582913;BA.debugLine="Private mEventName As String 'ignore";
_meventname = "";
RDebugUtils.currentLine=12582914;
//BA.debugLineNum = 12582914;BA.debugLine="Private mCallBack As Object 'ignore";
_mcallback = new Object();
RDebugUtils.currentLine=12582915;
//BA.debugLineNum = 12582915;BA.debugLine="Public mBase As B4XView 'ignore";
_mbase = new anywheresoftware.b4a.objects.B4XViewWrapper();
RDebugUtils.currentLine=12582916;
//BA.debugLineNum = 12582916;BA.debugLine="Private xui As XUI 'ignore";
_xui = new anywheresoftware.b4a.objects.B4XViewWrapper.XUI();
RDebugUtils.currentLine=12582917;
//BA.debugLineNum = 12582917;BA.debugLine="Private BusyBrush As BCBrush";
_busybrush = new b4j.example.bcpath._bcbrush();
RDebugUtils.currentLine=12582918;
//BA.debugLineNum = 12582918;BA.debugLine="Private BackgroundColor As Int";
_backgroundcolor = 0;
RDebugUtils.currentLine=12582919;
//BA.debugLineNum = 12582919;BA.debugLine="Private BusyIndex As Int";
_busyindex = 0;
RDebugUtils.currentLine=12582920;
//BA.debugLineNum = 12582920;BA.debugLine="Private bc As BitmapCreator";
_bc = new b4j.example.bitmapcreator();
RDebugUtils.currentLine=12582921;
//BA.debugLineNum = 12582921;BA.debugLine="Private mIV As B4XView";
_miv = new anywheresoftware.b4a.objects.B4XViewWrapper();
RDebugUtils.currentLine=12582922;
//BA.debugLineNum = 12582922;BA.debugLine="Private TransparentBrush As BCBrush";
_transparentbrush = new b4j.example.bcpath._bcbrush();
RDebugUtils.currentLine=12582923;
//BA.debugLineNum = 12582923;BA.debugLine="Private Vertical As Boolean";
_vertical = false;
RDebugUtils.currentLine=12582924;
//BA.debugLineNum = 12582924;BA.debugLine="Private CurrentValue As Float";
_currentvalue = 0f;
RDebugUtils.currentLine=12582925;
//BA.debugLineNum = 12582925;BA.debugLine="Public EmptyColor As Int = xui.Color_White";
_emptycolor = __ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .Color_White;
RDebugUtils.currentLine=12582926;
//BA.debugLineNum = 12582926;BA.debugLine="Private EmptyBrush As BCBrush";
_emptybrush = new b4j.example.bcpath._bcbrush();
RDebugUtils.currentLine=12582927;
//BA.debugLineNum = 12582927;BA.debugLine="Private mValue As Int";
_mvalue = 0;
RDebugUtils.currentLine=12582928;
//BA.debugLineNum = 12582928;BA.debugLine="Public Tag As Object";
_tag = new Object();
RDebugUtils.currentLine=12582929;
//BA.debugLineNum = 12582929;BA.debugLine="Public ValueChangePerSecond As Float = 60";
_valuechangepersecond = (float) (60);
RDebugUtils.currentLine=12582930;
//BA.debugLineNum = 12582930;BA.debugLine="Public CornerRadius As Int";
_cornerradius = 0;
RDebugUtils.currentLine=12582931;
//BA.debugLineNum = 12582931;BA.debugLine="Public BrushOffsetDelta As Int = 3";
_brushoffsetdelta = (int) (3);
RDebugUtils.currentLine=12582932;
//BA.debugLineNum = 12582932;BA.debugLine="End Sub";
return "";
}
public String _designercreateview(b4j.example.anotherprogressbar __ref,Object _base,anywheresoftware.b4j.objects.LabelWrapper _lbl,anywheresoftware.b4a.objects.collections.Map _props) throws Exception{
__ref = this;
RDebugUtils.currentModule="anotherprogressbar";
if (Debug.shouldDelegate(ba, "designercreateview", true))
{return ((String) Debug.delegate(ba, "designercreateview", new Object[] {_base,_lbl,_props}));}
anywheresoftware.b4j.objects.ImageViewWrapper _iv = null;
RDebugUtils.currentLine=12713984;
//BA.debugLineNum = 12713984;BA.debugLine="Public Sub DesignerCreateView (Base As Object, lbl";
RDebugUtils.currentLine=12713985;
//BA.debugLineNum = 12713985;BA.debugLine="mBase = Base";
__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ = (anywheresoftware.b4a.objects.B4XViewWrapper) anywheresoftware.b4a.AbsObjectWrapper.ConvertToWrapper(new anywheresoftware.b4a.objects.B4XViewWrapper(), (java.lang.Object)(_base));
RDebugUtils.currentLine=12713986;
//BA.debugLineNum = 12713986;BA.debugLine="Tag = mBase.Tag : mBase.Tag = Me";
__ref._tag /*Object*/ = __ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getTag();
RDebugUtils.currentLine=12713986;
//BA.debugLineNum = 12713986;BA.debugLine="Tag = mBase.Tag : mBase.Tag = Me";
__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .setTag(this);
RDebugUtils.currentLine=12713987;
//BA.debugLineNum = 12713987;BA.debugLine="Dim iv As ImageView";
_iv = new anywheresoftware.b4j.objects.ImageViewWrapper();
RDebugUtils.currentLine=12713988;
//BA.debugLineNum = 12713988;BA.debugLine="iv.Initialize(\"\")";
_iv.Initialize(ba,"");
RDebugUtils.currentLine=12713989;
//BA.debugLineNum = 12713989;BA.debugLine="mIV = iv";
__ref._miv /*anywheresoftware.b4a.objects.B4XViewWrapper*/ = (anywheresoftware.b4a.objects.B4XViewWrapper) anywheresoftware.b4a.AbsObjectWrapper.ConvertToWrapper(new anywheresoftware.b4a.objects.B4XViewWrapper(), (java.lang.Object)(_iv.getObject()));
RDebugUtils.currentLine=12713990;
//BA.debugLineNum = 12713990;BA.debugLine="mIV.Color = xui.Color_Transparent";
__ref._miv /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .setColor(__ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .Color_Transparent);
RDebugUtils.currentLine=12713991;
//BA.debugLineNum = 12713991;BA.debugLine="setValue(Props.GetDefault(\"Value\", 100))";
__ref._setvalue /*String*/ (null,(int)(BA.ObjectToNumber(_props.GetDefault((Object)("Value"),(Object)(100)))));
RDebugUtils.currentLine=12713992;
//BA.debugLineNum = 12713992;BA.debugLine="CurrentValue = mValue";
__ref._currentvalue /*float*/ = (float) (__ref._mvalue /*int*/ );
RDebugUtils.currentLine=12713993;
//BA.debugLineNum = 12713993;BA.debugLine="mBase.AddView(mIV, 0, 0, 0, 0)";
__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .AddView((javafx.scene.Node)(__ref._miv /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getObject()),0,0,0,0);
RDebugUtils.currentLine=12713994;
//BA.debugLineNum = 12713994;BA.debugLine="mBase.AddView(lbl, 0, 0, mBase.Width, mBase.Heigh";
__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .AddView((javafx.scene.Node)(_lbl.getObject()),0,0,__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getWidth(),__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getHeight());
RDebugUtils.currentLine=12713995;
//BA.debugLineNum = 12713995;BA.debugLine="mBase.SetColorAndBorder(xui.Color_Transparent, 0,";
__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .SetColorAndBorder(__ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .Color_Transparent,0,(int) (0),0);
RDebugUtils.currentLine=12713996;
//BA.debugLineNum = 12713996;BA.debugLine="BackgroundColor = xui.PaintOrColorToColor(Props.G";
__ref._backgroundcolor /*int*/ = __ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .PaintOrColorToColor(_props.Get((Object)("ProgressColor")));
RDebugUtils.currentLine=12713997;
//BA.debugLineNum = 12713997;BA.debugLine="CornerRadius = Props.GetDefault(\"CornerRadius\", 1";
__ref._cornerradius /*int*/ = (int)(BA.ObjectToNumber(_props.GetDefault((Object)("CornerRadius"),(Object)(15))));
RDebugUtils.currentLine=12713998;
//BA.debugLineNum = 12713998;BA.debugLine="Base_Resize(mBase.Width, mBase.Height)";
__ref._base_resize /*String*/ (null,__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getWidth(),__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getHeight());
RDebugUtils.currentLine=12713999;
//BA.debugLineNum = 12713999;BA.debugLine="End Sub";
return "";
}
public String _setvalue(b4j.example.anotherprogressbar __ref,int _v) throws Exception{
__ref = this;
RDebugUtils.currentModule="anotherprogressbar";
if (Debug.shouldDelegate(ba, "setvalue", true))
{return ((String) Debug.delegate(ba, "setvalue", new Object[] {_v}));}
RDebugUtils.currentLine=13172736;
//BA.debugLineNum = 13172736;BA.debugLine="Public Sub setValue (v As Int)";
RDebugUtils.currentLine=13172737;
//BA.debugLineNum = 13172737;BA.debugLine="mValue = Max(0, Min(100, v))";
__ref._mvalue /*int*/ = (int) (__c.Max(0,__c.Min(100,_v)));
RDebugUtils.currentLine=13172738;
//BA.debugLineNum = 13172738;BA.debugLine="End Sub";
return "";
}
public int _getvalue(b4j.example.anotherprogressbar __ref) throws Exception{
__ref = this;
RDebugUtils.currentModule="anotherprogressbar";
if (Debug.shouldDelegate(ba, "getvalue", true))
{return ((Integer) Debug.delegate(ba, "getvalue", null));}
RDebugUtils.currentLine=13107200;
//BA.debugLineNum = 13107200;BA.debugLine="Public Sub getValue As Int";
RDebugUtils.currentLine=13107201;
//BA.debugLineNum = 13107201;BA.debugLine="Return mValue";
if (true) return __ref._mvalue /*int*/ ;
RDebugUtils.currentLine=13107202;
//BA.debugLineNum = 13107202;BA.debugLine="End Sub";
return 0;
}
public boolean _getvisible(b4j.example.anotherprogressbar __ref) throws Exception{
__ref = this;
RDebugUtils.currentModule="anotherprogressbar";
if (Debug.shouldDelegate(ba, "getvisible", true))
{return ((Boolean) Debug.delegate(ba, "getvisible", null));}
RDebugUtils.currentLine=13041664;
//BA.debugLineNum = 13041664;BA.debugLine="Public Sub getVisible As Boolean";
RDebugUtils.currentLine=13041665;
//BA.debugLineNum = 13041665;BA.debugLine="Return mBase.Visible";
if (true) return __ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .getVisible();
RDebugUtils.currentLine=13041666;
//BA.debugLineNum = 13041666;BA.debugLine="End Sub";
return false;
}
public String _initialize(b4j.example.anotherprogressbar __ref,anywheresoftware.b4a.BA _ba,Object _callback,String _eventname) throws Exception{
__ref = this;
innerInitialize(_ba);
RDebugUtils.currentModule="anotherprogressbar";
if (Debug.shouldDelegate(ba, "initialize", true))
{return ((String) Debug.delegate(ba, "initialize", new Object[] {_ba,_callback,_eventname}));}
RDebugUtils.currentLine=12648448;
//BA.debugLineNum = 12648448;BA.debugLine="Public Sub Initialize (Callback As Object, EventNa";
RDebugUtils.currentLine=12648449;
//BA.debugLineNum = 12648449;BA.debugLine="mEventName = EventName";
__ref._meventname /*String*/ = _eventname;
RDebugUtils.currentLine=12648450;
//BA.debugLineNum = 12648450;BA.debugLine="mCallBack = Callback";
__ref._mcallback /*Object*/ = _callback;
RDebugUtils.currentLine=12648451;
//BA.debugLineNum = 12648451;BA.debugLine="End Sub";
return "";
}
public String _setvaluenoanimation(b4j.example.anotherprogressbar __ref,int _v) throws Exception{
__ref = this;
RDebugUtils.currentModule="anotherprogressbar";
if (Debug.shouldDelegate(ba, "setvaluenoanimation", true))
{return ((String) Debug.delegate(ba, "setvaluenoanimation", new Object[] {_v}));}
RDebugUtils.currentLine=13238272;
//BA.debugLineNum = 13238272;BA.debugLine="Public Sub SetValueNoAnimation (v As Int)";
RDebugUtils.currentLine=13238273;
//BA.debugLineNum = 13238273;BA.debugLine="setValue(v)";
__ref._setvalue /*String*/ (null,_v);
RDebugUtils.currentLine=13238274;
//BA.debugLineNum = 13238274;BA.debugLine="CurrentValue = mValue";
__ref._currentvalue /*float*/ = (float) (__ref._mvalue /*int*/ );
RDebugUtils.currentLine=13238275;
//BA.debugLineNum = 13238275;BA.debugLine="End Sub";
return "";
}
public String _setvisible(b4j.example.anotherprogressbar __ref,boolean _b) throws Exception{
__ref = this;
RDebugUtils.currentModule="anotherprogressbar";
if (Debug.shouldDelegate(ba, "setvisible", true))
{return ((String) Debug.delegate(ba, "setvisible", new Object[] {_b}));}
RDebugUtils.currentLine=12976128;
//BA.debugLineNum = 12976128;BA.debugLine="Public Sub setVisible(b As Boolean)";
RDebugUtils.currentLine=12976129;
//BA.debugLineNum = 12976129;BA.debugLine="BusyIndex = BusyIndex + 1";
__ref._busyindex /*int*/ = (int) (__ref._busyindex /*int*/ +1);
RDebugUtils.currentLine=12976130;
//BA.debugLineNum = 12976130;BA.debugLine="If b Then";
if (_b) {
RDebugUtils.currentLine=12976131;
//BA.debugLineNum = 12976131;BA.debugLine="BusyLoop";
__ref._busyloop /*void*/ (null);
};
RDebugUtils.currentLine=12976133;
//BA.debugLineNum = 12976133;BA.debugLine="mBase.Visible = b";
__ref._mbase /*anywheresoftware.b4a.objects.B4XViewWrapper*/ .setVisible(_b);
RDebugUtils.currentLine=12976134;
//BA.debugLineNum = 12976134;BA.debugLine="End Sub";
return "";
}
} | true |
d344025dc4768dac64bbb359f4d444f53af60cb8 | Java | AiRisska/JavaGameHeroes | /src/main/java/ru/game/Tank.java | UTF-8 | 271 | 2.265625 | 2 | [] | no_license | package ru.game;
public class Tank extends Avatar {
void Pers() {
proff = "Танк";
attribute = "CON";
attr = 1;
sayAboutPers();
}
void attack() {
skill = "Агр!";
attack(skill);
attr++;
}
}
| true |
55ffad4b3119792c1d1f7d43fb80238f6cb24299 | Java | EleonoraDM/HELL | /entities/heroes/Assassin.java | UTF-8 | 817 | 2.5625 | 3 | [] | no_license | package entities.heroes;
import common.Config;
public class Assassin extends HeroImpl {
public Assassin(String name) {
super(name);
this.setStrength(Config.ASSASSIN_DEFAULT_STRENGTH);
this.setAgility(Config.ASSASSIN_DEFAULT_AGILITY);
this.setIntelligence(Config.ASSASSIN_DEFAULT_INTELLIGENCE);
this.setHitPoints(Config.ASSASSIN_DEFAULT_HIT_POINTS);
this.setDamage(Config.ASSASSIN_DEFAULT_DAMAGE);
}
@Override
void setDefaultStats() {
this.setStrength(Config.ASSASSIN_DEFAULT_STRENGTH);
this.setAgility(Config.ASSASSIN_DEFAULT_AGILITY);
this.setIntelligence(Config.ASSASSIN_DEFAULT_INTELLIGENCE);
this.setHitPoints(Config.ASSASSIN_DEFAULT_HIT_POINTS);
this.setDamage(Config.ASSASSIN_DEFAULT_DAMAGE);
}
}
| true |
696248822abfc9bc122ac477976e2b6264eb7722 | Java | smali2/rest_core | /src/main/java/com/cp8202/project/calc_cloud/model/Memory.java | UTF-8 | 235 | 1.679688 | 2 | [] | no_license | package com.cp8202.project.calc_cloud.model;
import java.util.ArrayList;
public class Memory {
private static ArrayList<Double> saved = new ArrayList<>();
public static ArrayList<Double> getSaved() {
return saved;
}
}
| true |
b942e1577a56463245ced2e903ddcb5b790b1eda | Java | sonnylazuardi/react-native-android-tablayout | /src/main/java/com/xebia/reactnative/Installer.java | UTF-8 | 424 | 2.03125 | 2 | [] | no_license | package com.xebia.reactnative;
class Installer {
private GradleModifier groovyModifier = new GradleModifier();
private JavaModifier javaModifier = new JavaModifier();
public static void main(String[] args) throws Exception {
new Installer().run();
}
private void run() throws Exception {
groovyModifier.updateSettings();
groovyModifier.updateAppBuild();
javaModifier.updateMainActivity();
}
}
| true |
b1aefa7a609e3fe98d334c1dfce63b00e165798c | Java | aq1e/CSC207-Final-Project | /phase2/src/convention/exception/SpeakerDoubleBookingException.java | UTF-8 | 479 | 2.578125 | 3 | [] | no_license | package convention.exception;
import convention.calendar.TimeRange;
import java.util.UUID;
/**
* Thrown when a speaker is scheduled to be at more than one event concurrently
*/
public class SpeakerDoubleBookingException extends RuntimeException {
public SpeakerDoubleBookingException(UUID speakerUUID, TimeRange timeRange) {
super(String.format("Speaker %s is already scheduled to be at another event at the given time (%s).", speakerUUID, timeRange));
}
}
| true |
0880d00929d89bb9f99ce17f72dc95875d5ee8b3 | Java | sethcg/EMNIST-Digit-Predictor | /src/main/java/emnist_digit_predictor/Cell.java | UTF-8 | 3,370 | 3.328125 | 3 | [] | no_license | package emnist_digit_predictor;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
public class Cell extends StackPane{
private int row;
private int column;
private boolean isColored;
private BufferedImage mnistImage;
public Cell(int row, int column, BufferedImage mnistImage) {
this.row = row;
this.column = column;
this.mnistImage = mnistImage;
this.getStyleClass().add("cell");
this.setId("cell");
// Listener for the hover
this.hoverProperty().addListener(new ChangeListener<Boolean>(){
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue){
if(newValue){
setId("cell-hover-highlight");
}else{
setId("cell");
}
}
});
// Handler for Dragging while mouse held down
this.setOnDragDetected(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
Cell cell = (Cell) event.getSource();
cell.startFullDrag();
}
});
// Handler for Dragging to color/erase each square
this.setOnMousePressed(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
changeColorHelper(event);
}
});
// Handler for Dragging to color/erase each square
this.setOnMouseDragEntered(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
changeColorHelper(event);
}
});
}
// Helper Method for changing the Cell StackPane color
private void changeColorHelper(MouseEvent event){
Cell cell = (Cell) event.getSource();
if( event.isPrimaryButtonDown()) { // Left Mouse Button color the square
cell.setStyle("-fx-background-color: -fx-cell-black;");
this.setColor(true);
// Set a 2x2 for each cell colored
mnistImage.setRGB(row, column, Color.WHITE.getRGB());
mnistImage.setRGB(row + 1, column, Color.WHITE.getRGB());
mnistImage.setRGB(row, column + 1, Color.WHITE.getRGB());
mnistImage.setRGB(row + 1, column + 1, Color.WHITE.getRGB());
}else if( event.isSecondaryButtonDown()) { // Right Mouse Button erase the square
cell.setStyle("-fx-background-color: -fx-cell-white;");
this.setColor(false);
// Set a 2x2 for each cell erased
mnistImage.setRGB(row, column, Color.BLACK.getRGB());
mnistImage.setRGB(row + 1, column, Color.BLACK.getRGB());
mnistImage.setRGB(row, column + 1, Color.BLACK.getRGB());
mnistImage.setRGB(row + 1, column + 1, Color.BLACK.getRGB());
}
GridHelper.runPrediction();
}
// Getters and Setters
protected int getRow(){
return row;
}
protected int getColumn(){
return column;
}
protected void setColor(boolean color){
isColored = color;
}
public String toString() {
return "(" + this.row + "," + this.column + ")";
}
public boolean isColored() {
return isColored;
}
}
| true |
dd415a133cd0ac23d7a190aea8b6bc13d21400fa | Java | yelinag/GridDriver | /src/Exploration/RobotMap.java | UTF-8 | 10,416 | 2.796875 | 3 | [
"MIT"
] | permissive | package Exploration;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import Exploration.SimulationMain.Node;
public class RobotMap {
protected ArrayList<Grid> vertex;
// static CrunchifyLinkedList edges[] = new
// CrunchifyLinkedList[(TOTAL_HORIZONTAL_TILES-1) *
// (TOTAL_VERTICAL_TILES-1)];
private EdgeList edges[];
private int map[][];
private float mapValue[][];
private int mapCount[][];
protected int numExploredGrids = 0;
protected int obstacleCount = 0;
static final int dx[] = { 0, 1, 1, 1, 0, -1, -1, -1 };
static final int dy[] = { 1, 1, 0, -1, -1, -1, 0, 1 };
private int virtualMap[][];
public RobotMap() {
// vertex = new int[(Exploration.TOTAL_HORIZONTAL_TILES-1) *
// (Exploration.TOTAL_VERTICAL_TILES-1)];
// vertex = new Grid[Exploration.TOTAL_HORIZONTAL_TILES]
// [Exploration.TOTAL_VERTICAL_TILES];
virtualMap = map = new int[Exploration.TOTAL_HORIZONTAL_TILES][Exploration.TOTAL_VERTICAL_TILES];
mapValue = new float[Exploration.TOTAL_HORIZONTAL_TILES][Exploration.TOTAL_VERTICAL_TILES];
mapCount = new int[Exploration.TOTAL_HORIZONTAL_TILES][Exploration.TOTAL_VERTICAL_TILES];
for(int i = 0; i < Exploration.TOTAL_HORIZONTAL_TILES; i ++){
for(int j = 0; j < Exploration.TOTAL_VERTICAL_TILES; j++){
mapCount[i][j] = 0;
}
}
vertex = new ArrayList<Grid>();
for (int i = 0; i < Exploration.TOTAL_HORIZONTAL_TILES; i++) {
for (int j = 0; j < Exploration.TOTAL_VERTICAL_TILES; j++) {
vertex.add(new Grid(i, j));
}
}
edges = new EdgeList[(Exploration.TOTAL_HORIZONTAL_TILES - 1)
* (Exploration.TOTAL_VERTICAL_TILES - 1)];
map = new int[Exploration.TOTAL_HORIZONTAL_TILES][Exploration.TOTAL_VERTICAL_TILES];
for (int i = 0; i < Exploration.TOTAL_HORIZONTAL_TILES; i++) {
for (int j = 0; j < Exploration.TOTAL_VERTICAL_TILES; j++) {
map[i][j] = 2;
virtualMap[i][j] = 2;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
map[i][j] = 3;
virtualMap[i][j] = 3;
numExploredGrids++;
}
}
/*
* for(int i = Exploration.TOTAL_HORIZONTAL_TILES - 3; i <
* Exploration.TOTAL_HORIZONTAL_TILES; i++){ for(int j =
* Exploration.TOTAL_VERTICAL_TILES - 3; j <
* Exploration.TOTAL_VERTICAL_TILES; j++){ map[i][j] = 3;
* virtualMap[i][j] = 3; } }
*/
for (int i = 0; i < Exploration.TOTAL_HORIZONTAL_TILES; i++) {
for (int j = 0; j < Exploration.TOTAL_VERTICAL_TILES; j++) {
if (isGoalPt(i, j) || isStartingPt(i, j))
continue;
if (i == 0 || j == 0
|| i == Exploration.TOTAL_HORIZONTAL_TILES - 1
|| j == Exploration.TOTAL_VERTICAL_TILES - 1)
virtualMap[i][j] = 1;
}
}
// printMap();
// System.out.println();
// printVirtualMap();
}
private void CREATE_VIRTUAL_MAP(){
for(int i = 0; i < Exploration.TOTAL_HORIZONTAL_TILES; i++){
for(int j = 0; j < Exploration.TOTAL_VERTICAL_TILES; j++){
map[i][j] = 0;
}
}
map[7][2] =1;
map[11][4] =1;
map[12][4] =1;
map[13][4] =1;
map[1][5] =1;
map[5][8] =1;
map[6][8] =1;
map[7][8] =1;
map[10][10] =1;
map[0][13] =1;
map[1][13] =1;
map[2][13] =1;
map[3][13] =1;
map[4][13] =1;
map[5][13] =1;
map[11][14] =1;
map[12][14] =1;
map[13][14] =1;
map[7][17] =1;
}
public Grid nearestUnexplored(Grid inputGrid) {
Grid outputGrid = new Grid(2, 2);
/*
* for(int i = 1; i < Exploration.TOTAL_HORIZONTAL_TILES; i++){ int xInc
* = inputGrid.x + i; int xDec = inputGrid.x - i; int yInc = inputGrid.y
* + i; int yDec = inputGrid.y - i; if(xInc >=
* Exploration.TOTAL_HORIZONTAL_TILES -3) xInc =
* Exploration.TOTAL_HORIZONTAL_TILES - 3; if(xDec < 0) xDec = 0;
* if(yInc >= Exploration.TOTAL_VERTICAL_TILES -3) yInc =
* Exploration.TOTAL_VERTICAL_TILES - 3; if(yDec < 0) yDec = 0;
* if(map[xInc][yInc] == 2){ outputGrid = new Grid(xInc, yInc); break;
* }else if(map[xDec][yInc] == 2){ outputGrid = new Grid(xDec, yInc);
* break; }else if(map[xInc][yDec] == 2){ outputGrid = new Grid(xInc,
* yDec); break; }else if(map[xDec][yDec] == 2){ outputGrid = new
* Grid(xDec, yDec); break; }else if(map[inputGrid.x][yInc] == 2){
* outputGrid = new Grid(inputGrid.x, yInc); break; }else
* if(map[xInc][inputGrid.y] == 2){ outputGrid = new Grid(xInc,
* inputGrid.y); break; }else if(map[inputGrid.x][yDec] == 2){
* outputGrid = new Grid(inputGrid.x, yDec); break; }else
* if(map[xDec][inputGrid.y] == 2){ outputGrid = new Grid(xDec,
* inputGrid.y); break; }
*
* }
*/
for (int i = 0; i < Exploration.TOTAL_HORIZONTAL_TILES; i++) {
for (int j = 0; j < Exploration.TOTAL_VERTICAL_TILES; j++) {
if (map[i][j] == 2) {
Grid outGrid = new Grid(i, j);
return outGrid;
}
}
}
// outputGrid = vertex.get(0);
return outputGrid;
}
public boolean isObstacleThere(int corX, int corY) {
if (corX < 0
|| corY < 0
|| corX >= Exploration.TOTAL_HORIZONTAL_TILES
* Exploration.OBSTACLE_SIZE
|| corY > Exploration.TOTAL_VERTICAL_TILES
* Exploration.OBSTACLE_SIZE)
return false;
int[] xy = Exploration.coordinatesToGrid(corX, corY);
if (map[xy[0]][xy[1]] == 1)
return true;
return false;
}
public boolean isOkaytoMove(int xGrid, int yGrid) {
if (Exploration.isOutofBoundByGrid(xGrid, yGrid))
return false;
if (virtualMap[xGrid][yGrid] == 0 || virtualMap[xGrid][yGrid] == 3)
return true;
return false;
}
/*
* public boolean isOkaytoAdd(int xGrid, int yGrid){
* if(Exploration.isOutofArena(xGrid, yGrid)) return false;
* if(map[xGrid][yGrid] == 0 || map[xGrid][yGrid] == 3) return true; return
* false; }
*/
public void updateRobotMap(int horizontal, int vertical, int value) {
if (horizontal < 0
|| horizontal > Exploration.TOTAL_HORIZONTAL_TILES - 1
|| vertical < 0
|| vertical > Exploration.TOTAL_VERTICAL_TILES - 1)
return;
if (isStartingPt(horizontal, vertical))
return;
if (map[horizontal][vertical] == 2) {
numExploredGrids++;
mapValue[horizontal][vertical] = value;
mapCount[horizontal][vertical]++;
if (value == 1)
obstacleCount++;
}else{
mapValue[horizontal][vertical] = (mapValue[horizontal][vertical] * mapCount[horizontal][vertical] + value)/
(mapCount[horizontal][vertical] + 1);
mapCount[horizontal][vertical]++;
}
if(mapValue[horizontal][vertical] < 0.5)
map[horizontal][vertical] = 0;
else
map[horizontal][vertical] = 1;
if (horizontal >= Exploration.TOTAL_HORIZONTAL_TILES - 3
&& vertical >= Exploration.TOTAL_VERTICAL_TILES - 3)
map[horizontal][vertical] = 3;
updateVirtualMap();
for (int i = 0; i < vertex.size(); i++) {
Grid tempGrid = vertex.get(i);
if (tempGrid.x == horizontal && tempGrid.y == vertical) {
vertex.remove(tempGrid);
}
}
}
private void updateVirtualMap() {
for (int i = 0; i < Exploration.TOTAL_HORIZONTAL_TILES; i++) {
for (int j = 0; j < Exploration.TOTAL_VERTICAL_TILES; j++) {
if (virtualMap[i][j] != 1 && virtualMap[i][j] != 3)
virtualMap[i][j] = map[i][j];
if (map[i][j] == 1) {
for (int d = 0; d < 8; d++) {
int xTemp = i + dx[d];
int yTemp = j + dy[d];
if (xTemp < 1
|| yTemp < 1
|| xTemp >= Exploration.TOTAL_HORIZONTAL_TILES - 1
|| yTemp >= Exploration.TOTAL_VERTICAL_TILES - 1)
continue;
if (isGoalPt(xTemp, yTemp)
|| isStartingPt(xTemp, yTemp))
continue;
virtualMap[xTemp][yTemp] = 1;
}
}
}
}
}
public int[][] getMap() {
/*
* int[][] tempMap = new
* int[Exploration.TOTAL_HORIZONTAL_TILES][Exploration
* .TOTAL_VERTICAL_TILES]; for(int i = 0; i <
* Exploration.TOTAL_HORIZONTAL_TILES; i++){ for(int j = 0; j
* <Exploration.TOTAL_VERTICAL_TILES; j++){ tempMap[i][j] = map[i][j]; }
* } return tempMap;
*/
return map;
}
public int[][] getVirtualMap() {
/*
* int[][] temp2Map = new
* int[Exploration.TOTAL_HORIZONTAL_TILES][Exploration
* .TOTAL_VERTICAL_TILES]; for(int i = 0; i <
* Exploration.TOTAL_HORIZONTAL_TILES; i++){ for(int j = 0; j
* <Exploration.TOTAL_VERTICAL_TILES; j++){ temp2Map[i][j] =
* virtualMap[i][j]; } } return temp2Map;
*/
return virtualMap;
}
public boolean isGoalPt(int hor, int ver) {
if (hor >= Exploration.TOTAL_HORIZONTAL_TILES - 3
&& ver >= Exploration.TOTAL_VERTICAL_TILES - 3) {
return true;
}
return false;
}
public boolean isStartingPt(int hor, int ver) {
if (hor < 3 && ver < 3) {
return true;
}
return false;
}
public void printMap() {
System.out.println("Actual Map");
for (int i = 0; i < Exploration.TOTAL_VERTICAL_TILES; i++) {
for (int j = 0; j < Exploration.TOTAL_HORIZONTAL_TILES; j++) {
System.out.print(map[j][Exploration.TOTAL_VERTICAL_TILES - i
- 1]
+ ", ");
}
System.out.println();
}
}
public void printVirtualMap() {
System.out.println("Virtual Map");
for (int i = 0; i < Exploration.TOTAL_VERTICAL_TILES; i++) {
for (int j = 0; j < Exploration.TOTAL_HORIZONTAL_TILES; j++) {
System.out.print(virtualMap[j][Exploration.TOTAL_VERTICAL_TILES
- i - 1]
+ ", ");
}
System.out.println();
}
}
public String convertMapToBinary() {
String bin1 = "11";
String bin2 = "";
String hex1 = "";
String hex2 = "";
for (int j = 0; j < Exploration.TOTAL_VERTICAL_TILES; j++) {
for (int i = 0; i < Exploration.TOTAL_HORIZONTAL_TILES; i++) {
if (map[i][j] == 2) {
bin1 += "0";
} else {
bin1 += "1";
if (map[i][j] == 1)
bin2 += "1";
else
bin2 += "0";
}
}
}
bin1 += "11";
hex1 = Map.binToHex(bin1);
hex2 = Map.binToHex(bin2);
return hex1 + "\n" + hex2;
/*
* String bin1 = ""; String hex1 = ""; for(int i = 0; i<
* Exploration.TOTAL_HORIZONTAL_TILES; i++){ for(int j=0; j<
* Exploration.TOTAL_VERTICAL_TILES ; j++){ if(map[i][j] == 1){ bin1 +=
* "1"; } else{ bin1 += "0"; }
*
* } }
*
* hex1 = Map.encodeMap(bin1); return hex1;
*/
}
}
| true |
e4e322b35bcabc7430febb25b148b6cfd7fbb40b | Java | VatsalaAgrawal/Assignment | /LayeredArchitecture/src/com/techment/utitity/CollectionUtil.java | UTF-8 | 676 | 2.765625 | 3 | [] | no_license | package com.techment.utitity;
import java.util.HashMap;
import java.util.Map;
import com.techment.model.Employee1;
public class CollectionUtil {
static Map<Integer, Employee1> employees=new HashMap<Integer,Employee1>();
static {
employees.put(1,new Employee1(1,"Vatsala","hr",78000));
employees.put(2,new Employee1(2,"Rahul","Developer",700));
employees.put(3,new Employee1(3,"Kavya","hr",78099));
employees.put(4,new Employee1(4,"Rishita","Manager",60000));
}
/* this method is used to get the employee map,which we can initialised as static data*/
public static Map<Integer,Employee1> getEmployeeList(){
return employees;
}
}
| true |
f279356afef9845d7ef6e9fa4b8c063ee182a0d5 | Java | Trungri/estate-jsp-servlet-jdbc | /src/main/java/com/estate/utils/HttpClientUtils.java | UTF-8 | 1,141 | 2.6875 | 3 | [] | no_license | package com.estate.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
public class HttpClientUtils {
final static Logger logger = Logger.getLogger(HttpClientUtils.class);
public static String httpGet(String url){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(getRequest);
int statusCode = httpResponse.getStatusLine().getStatusCode();
String result = "";
if (statusCode >= 200 && statusCode < 300)
{
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
return result;
}
logger.info(result);
}catch (Exception e) {
logger.error("Error execute API : "+e.getMessage(), e);
}
return null;
}
}
| true |
94bd81fd6a16e078143b2ae4448b3fd6a2f244ca | Java | michelleDB/proyecto_DAM-DAW | /src/java/modelo/Usuario.java | UTF-8 | 4,823 | 2.3125 | 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 modelo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.codec.digest.DigestUtils;
/**
*
* @author Fresita
*/
public class Usuario {
String password_usuario,
email_cliente;
int id_rol = 2;
Cliente c;
Connection conexion;
public Usuario() throws Exception {
conect();
}
private Connection conect() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/laratitapresumida", "root", "");
} catch (Exception e) {
throw new Exception(e);
}
return conexion;
}
public int iniciarSesion(String password_usuario, String email_cliente) throws Exception {
Connection conn = null;
ResultSet result = null;
Statement statement = null;
try {
conn = conect();
statement = conn.createStatement();
System.out.println("contrasena normal"+password_usuario);
System.out.println("contrasena md5"+DigestUtils.md5Hex(password_usuario));
String dml = "SELECT * FROM USUARIOS WHERE password_usuario LIKE '" + DigestUtils.md5Hex(password_usuario) + "' && email_cliente LIKE '" + email_cliente + "' && id_rol LIKE " + 2;
result = statement.executeQuery(dml);
if (result.next()) {
return result.getInt("id_usuario");
} else {
return 0;
}
} catch (SQLException sqle) {
throw new Exception(sqle);
} finally {
if (result != null) {
try {
result.close();
} catch (SQLException sql) {
throw new Exception(sql);
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException sql) {
throw new Exception(sql);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException sql) {
throw new Exception(sql);
}
}
}
}
public boolean insertarUsuario(String password_usuario, String email_cliente) throws Exception {
Connection conn = null;
ResultSet result = null;
int registrosAfectados = 0;
PreparedStatement statement = null;
try {
Statement sentencia = conect().createStatement();
String dml = "INSERT INTO USUARIOS(password_usuario,email_cliente,id_rol) VALUES "
+ "('" + DigestUtils.md5Hex(password_usuario) + "','" + email_cliente + "'," + id_rol + ")";
registrosAfectados = sentencia.executeUpdate(dml);
if (registrosAfectados == 1) {
return true;
} else {
return false;
}
} catch (SQLException sqle) {
throw new Exception(sqle);
} finally {
if (result != null) {
try {
result.close();
} catch (SQLException sql) {
throw new Exception(sql);
}
} else {
}
if (statement != null) {
try {
statement.close();
} catch (SQLException sql) {
throw new Exception(sql);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException sql) {
throw new Exception(sql);
}
}
}
}
public String getPassword_usuario() {
return password_usuario;
}
public void setPassword_usuario(String password_usuario) {
this.password_usuario = password_usuario;
}
public String getEmail_cliente() {
return email_cliente;
}
public void setEmail_cliente(String email_cliente) {
this.email_cliente = email_cliente;
}
public int getId_rol() {
return id_rol;
}
public void setId_rol(int id_rol) {
this.id_rol = id_rol;
}
}
| true |
25dca03955b56791772394a473523cc140647694 | Java | JVMarks/Java_Projects | /lista_de_exercicios3/src/lista_de_exercicios3/Repeticao.java | UTF-8 | 751 | 3.15625 | 3 | [
"MIT"
] | permissive | package lista_de_exercicios3;
import java.util.Scanner;
public class Repeticao {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner teclado = new Scanner(System.in);
String usuario;
int contador;
do {
contador = 2;
while(contador <= 130 ){
System.out.println(contador);
contador = contador + 2;
}
System.out.println("escreva sim ou nao para continuar -->");
usuario = teclado.nextLine();
if(usuario.equalsIgnoreCase("nao")){
System.out.println("encerramos o codigo!!");
}
}while(usuario.equalsIgnoreCase("sim"));
teclado.close();
}
} | true |
d6b161d96305b2d2059f18f62aadd2e875a22b06 | Java | kuli4/otus-java-homework | /hw14-mvc/src/main/java/pro/kuli4/otus/java/hw14/services/DbServiceUserImpl.java | UTF-8 | 2,460 | 2.765625 | 3 | [
"MIT"
] | permissive | package pro.kuli4.otus.java.hw14.services;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import pro.kuli4.otus.java.hw14.dao.UserDao;
import pro.kuli4.otus.java.hw14.entities.AddressDataSet;
import pro.kuli4.otus.java.hw14.entities.PhoneDataSet;
import pro.kuli4.otus.java.hw14.entities.User;
import javax.annotation.PostConstruct;
import java.util.Optional;
@Slf4j
@Service
public class DbServiceUserImpl implements DbServiceUser {
private final UserDao userDao;
private final PassEncoder passEncoder;
public DbServiceUserImpl(UserDao userDao, PassEncoder passEncoder) {
this.userDao = userDao;
this.passEncoder = passEncoder;
}
@Override
public long saveUser(User user) {
userDao.insertOrUpdate(user);
return user.getId();
}
@Override
public Optional<User> getUser(long id) {
return userDao.findById(id);
}
@PostConstruct
void initDb() {
createUser(this, "Sergey", "serg", passEncoder.encode("1"), "Svetlaya");
createUser(this, "Alexander", "alex", passEncoder.encode("12"), "Lenina");
createUser(this, "Pavel", "pavel", passEncoder.encode("123"), "Tverskaya");
createUser(this, "Ivan", "ivan", passEncoder.encode("1234"), "Gagarina");
}
private void createUser(DbServiceUser dbServiceUser, String name, String login, String password, String street) {
// Create user
User user = new User();
user.setName(name);
user.setLogin(login);
user.setPassword(password);
// Create address
AddressDataSet address = new AddressDataSet();
address.setStreet(street + " street");
user.setAddress(address);
// Create two phones
PhoneDataSet mobilePhone = new PhoneDataSet();
mobilePhone.setNumber(phoneNumberGen());
user.getPhones().add(mobilePhone);
mobilePhone.setUser(user);
PhoneDataSet homePhone = new PhoneDataSet();
homePhone.setNumber(phoneNumberGen());
user.getPhones().add(homePhone);
homePhone.setUser(user);
log.debug("application user: {}", user);
dbServiceUser.saveUser(user);
}
private String phoneNumberGen() {
StringBuilder sb = new StringBuilder("+7");
for (int i = 0; i < 10; i++) {
sb.append(Math.round((Math.random() * 100) % 9));
}
return sb.toString();
}
} | true |
0fc0feef1fe1c52647c274d33f8de8b09e4be003 | Java | skjolber/xml-log-filter | /impl/stax-soap-header/src/main/java/com/github/skjolber/xmlfilter/stax/soap/AbstractSingleXPathStAXSoapHeaderXmlFilter.java | UTF-8 | 1,013 | 1.960938 | 2 | [
"Apache-2.0"
] | permissive | package com.github.skjolber.xmlfilter.stax.soap;
import org.codehaus.stax2.XMLInputFactory2;
import org.codehaus.stax2.XMLOutputFactory2;
import com.github.skjolber.indent.Indent;
import com.github.skjolber.xmlfilter.stax.AbstractSingleXPathStAXXmlFilter;
public class AbstractSingleXPathStAXSoapHeaderXmlFilter extends AbstractSingleXPathStAXXmlFilter {
public static final String BODY = "Body";
protected int filterMatches;
public AbstractSingleXPathStAXSoapHeaderXmlFilter(boolean declaration, Indent indentation, int maxTextNodeLength, int maxCDATANodeLength, String expression, FilterType type, int filterMatches, XMLInputFactory2 inputFactory, XMLOutputFactory2 outputFactory) {
super(declaration, indentation, maxTextNodeLength, maxCDATANodeLength, expression, type, inputFactory, outputFactory);
if(filterMatches == -1) {
this.filterMatches = Integer.MAX_VALUE;
} else {
this.filterMatches = filterMatches;
}
}
public int getFilterMatches() {
return filterMatches;
}
}
| true |
3f442fb63d4642cb0b3b3f53b26ac76f3acfcd39 | Java | tomPolesovsky/car-park | /carpark-service/src/main/java/cz/pa165/carpark/service/service/ReservationSettingsServiceImpl.java | UTF-8 | 2,306 | 2.546875 | 3 | [] | no_license | package cz.pa165.carpark.service.service;
import cz.pa165.carpark.persistence.dao.ReservationSettingsDao;
import cz.pa165.carpark.persistence.entity.Employee;
import cz.pa165.carpark.persistence.entity.ReservationSettings;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.util.List;
/**
* The reservation settings service's implementation.
*
* @author Jana Applova, 422352@mail.muni.cz
*/
@Service
public class ReservationSettingsServiceImpl implements ReservationSettingsService {
private ReservationSettingsDao reservationSettingsDao;
@Inject
public ReservationSettingsServiceImpl(ReservationSettingsDao reservationSettingsDao) {
this.reservationSettingsDao = reservationSettingsDao;
}
/**
* Find all the reservation settings for the specified employee
*
* @param employee
* @return list of reservations settings
*/
@Override
public ReservationSettings findByEmployee(Employee employee) {
return reservationSettingsDao.findByEmployee(employee);
}
/**
* Find the reservation settings with the specified id
*
* @param id unambiguous identification of entity
* @return reservation settings
*/
@Override
public ReservationSettings find(Long id) {
return reservationSettingsDao.find(id);
}
/**
* Find all reservation settings
*
* @return list of all reservation settings
*/
@Override
public List<ReservationSettings> findAll() {
return reservationSettingsDao.findAll();
}
/**
* Save the specified reservation settings
*
* @param reservationSettings
*/
@Override
public void save(ReservationSettings reservationSettings) {
reservationSettingsDao.save(reservationSettings);
}
/**
* Update the specified reservation settings
*
* @param reservationSettings
*/
@Override
public void update(ReservationSettings reservationSettings) {
reservationSettingsDao.update(reservationSettings);
}
/**
* Delete the reservation settings with the specified id
*
* @param id unambiguous identification of entity
*/
@Override
public void delete(Long id) {
reservationSettingsDao.delete(id);
}
}
| true |
11338fa5020b1ee7fc5d5d2b92b56a00fea552c7 | Java | ricardopereira33/FSD | /distobj/src/main/java/manager/Data/Context.java | UTF-8 | 1,177 | 2.40625 | 2 | [] | no_license | package manager.Data;
import io.atomix.catalyst.buffer.BufferInput;
import io.atomix.catalyst.buffer.BufferOutput;
import io.atomix.catalyst.serializer.CatalystSerializable;
import io.atomix.catalyst.serializer.Serializer;
import io.atomix.catalyst.transport.Address;
public class Context implements CatalystSerializable{
private int txid;
private Address address;
public Context(){ }
public Context(int txid, Address address){
this.txid = txid;
this.address = address;
}
public int getTxid() {
return txid;
}
public void setTxid(int txid) {
this.txid = txid;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public void writeObject(BufferOutput<?> bufferOutput, Serializer serializer) {
bufferOutput.writeInt(txid);
serializer.writeObject(address, bufferOutput);
}
@Override
public void readObject(BufferInput<?> bufferInput, Serializer serializer) {
txid = bufferInput.readInt();
address = serializer.readObject(bufferInput);
}
}
| true |
319ecb1e92498d7150b689576b63255899c94528 | Java | latbeo0/fast-delivery-application | /app/src/main/java/com/uniapp/fastdeliveryappilcation/viewholder/ActiveSubscriptionViewHolder.java | UTF-8 | 1,004 | 1.914063 | 2 | [] | no_license | package com.uniapp.fastdeliveryappilcation.viewholder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import com.uniapp.fastdeliveryappilcation.R;
import com.uniapp.fastdeliveryappilcation.adapter.ActiveSubscriptionAdapter;
public class ActiveSubscriptionViewHolder extends RecyclerView.ViewHolder {
public TextView subid,plan_name,start_date,end_date,noofdabba;
public Button done1;
public ActiveSubscriptionViewHolder(@NonNull View itemView) {
super(itemView);
subid=itemView.findViewById(R.id.subid);
plan_name=itemView.findViewById(R.id.plan_name);
start_date=itemView.findViewById(R.id.start);
end_date=itemView.findViewById(R.id.end);
done1=itemView.findViewById(R.id.done);
noofdabba=itemView.findViewById(R.id.noofdabba);
}
}
| true |
9877e4373c463a7b6ab0c374de0acaacb03a4ac7 | Java | WackyCoders/BlowThem-Server | /server/DataBaseConnector/DataBaseConnector.java | UTF-8 | 13,737 | 2.515625 | 3 | [] | no_license | package server.DataBaseConnector; /**
* Created by foban on 16.07.14.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.*;
import server.Garage.Purchase;
//import javax.servlet.*;
//import javax.servlet.http.*;
public class DataBaseConnector {
private final String driverName = "org.mariadb.jdbc.Driver"; //MariaBD
private Connection connection;
private String login;
private String password;
private void connect() throws DataBaseConnectorException {
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/blow_them", login, password);
}catch (Exception e) {
throw new DataBaseConnectorException("Connect exception: " + e.toString());
}
}
private ResultSet executeQuery(String sql) throws Exception {
Statement query = connection.createStatement();
return query.executeQuery(sql);
}
private int executeUpdate(String sql) throws Exception {
Statement query = connection.createStatement();
int m = query.executeUpdate(sql);
query.close();
return m;
}
private int getSomeInt(String sql, String column, String exception) throws DataBaseConnectorException {
int someInt;
try {
ResultSet rs = executeQuery(sql);
rs.next();
someInt = rs.getInt(column);
} catch (Exception e) {
throw new DataBaseConnectorException(exception + e.toString());
}
return someInt;
}
public ResultSet getAllUsers() throws Exception { //return fields id_user, username, scores, money
return executeQuery("SELECT id_user, username, scores, money FROM users");
}
public ResultSet getUserMail(int id_user) throws Exception { //return field mail
return executeQuery("SELECT mail FROM users WHERE id_user = " + id_user);
}
public ResultSet getUserInformation(int id_user) throws Exception { //return fields username, scores, money, tank(This tank was selected as the primary)
return executeQuery("SELECT username, scores, money, tank FROM users WHERE id_user = " + id_user);
}
public ResultSet getUserTanks(int id_user) throws Exception{ //tank, armor, engine, first_weapon, second_weapon, id_tank
return executeQuery("SELECT tank, armor, engine, first_weapon, second_weapon, id_tank FROM garage WHERE user = "+id_user);
}
public ResultSet getUserArmor(int id_user) throws Exception{ //armor
return executeQuery("SELECT armor FROM garage_armor WHERE user = "+id_user);
}
public ResultSet getUserEngine(int id_user) throws Exception{ //engine
return executeQuery("SELECT engine FROM garage_engine WHERE user = "+id_user);
}
public ResultSet getUserFirstWeapon(int id_user) throws Exception{ //first_weapon
return executeQuery("SELECT first_weapon FROM garage_first_weapon WHERE user = "+id_user);
}
public ResultSet getUserSecondWeapon(int id_user) throws Exception{ //second_weapon
return executeQuery("SELECT second_weapon FROM garage_second_weapon WHERE user = "+id_user);
}
private void setEquipment(String column, int id_tank, int id) throws DataBaseConnectorException {
try {
executeUpdate("UPDATE garage SET "+column+" = "+id+" WHERE id_tank = "+id_tank);
}
catch (Exception e){
throw new DataBaseConnectorException("Error when setting equipment: " + e.toString());
}
}
public void setTankArmor(int id_tank, int id_armor) throws DataBaseConnectorException {
setEquipment("armor", id_tank, id_armor);
}
public void setTankEngine (int id_tank, int id) throws DataBaseConnectorException {
setEquipment("engine", id_tank, id);
}
public void setTankFirstWeapon(int id_tank, int id) throws DataBaseConnectorException {
setEquipment("first_weapon", id_tank, id);
}
public void setTankSecondWeapon(int id_tank, int id) throws DataBaseConnectorException {
setEquipment("second_weapon", id_tank, id);
}
private int getCost(String table, String column, int id) throws DataBaseConnectorException {
return getSomeInt("SELECT cost FROM "+table+" WHERE "+column+" = " + id,"cost", "Error when try get cost: ");
}
public int getTankCost(int id_tank) throws DataBaseConnectorException {
return getCost("tanks", "id_tank", id_tank);
}
public int getArmorCost(int id_armor) throws DataBaseConnectorException {
return getCost("armor", "id_armor", id_armor);
}
public int getEngineCost(int id_engine) throws DataBaseConnectorException {
return getCost("engine", "id_engine", id_engine);
}
public int getFirstWeaponCost(int id_weapon) throws DataBaseConnectorException {
return getCost("first_weapon", "id_weapon", id_weapon);
}
public int getSecondWeaponCost(int id_weapon) throws DataBaseConnectorException {
return getCost("second_weapon", "id_weapon", id_weapon);
}
private void addEquipment(String type, int id_user, int id) throws DataBaseConnectorException {
try {
executeUpdate("insert into garage_"+type+" ("+type+", user ) values ("+id +", "+ id_user+")");
}
catch (Exception e){
throw new DataBaseConnectorException("Error when adding equipment: " + e.toString());
}
}
private int getUserTankID(int id_user, int id_tank) throws DataBaseConnectorException {
return getSomeInt("SELECT id_tank FROM garage WHERE user = "+id_user+" AND tank = " + id_tank, "id_tank","Error when try get tank id: " );
}
private Purchase addTankToGarage(int id_user, int id_tank) throws DataBaseConnectorException {
Purchase purchase = null;
try {
ResultSet tankInfo = executeQuery("SELECT first_weapon, second_weapon, armor, engine FROM tanks WHERE id_tank = "+id_tank);
tankInfo.next();
executeUpdate("insert into garage (user, tank, first_weapon, second_weapon, armor, engine) values (" +
id_user + ", " +
id_tank + ", " +
tankInfo.getInt("first_weapon") + ", " +
tankInfo.getInt("second_weapon") + ", " +
tankInfo.getInt("armor") + ", " +
tankInfo.getInt("engine") + ")"
);
addEquipment("first_weapon", id_user, tankInfo.getInt("first_weapon"));
addEquipment("second_weapon", id_user, tankInfo.getInt("second_weapon"));
addEquipment("armor", id_user, tankInfo.getInt("armor"));
addEquipment("engine", id_user, tankInfo.getInt("engine"));
purchase = new Purchase();
purchase.setArmor(tankInfo.getInt("armor"));
purchase.setEngine(tankInfo.getInt("engine"));
purchase.setSecondWeapon(tankInfo.getInt("second_weapon"));
purchase.setFirstWeapon(tankInfo.getInt("first_weapon"));
purchase.setTank(id_tank);
purchase.setID(getUserTankID(id_user,id_tank));
}
catch (Exception e){
throw new DataBaseConnectorException("Error when adding a tank: " + e.toString());
}
return purchase;
}
public Purchase makePurchase(int id_user, int cost, String type, int id) throws DataBaseConnectorException {
Purchase purchase = new Purchase();
try {
if(type == null){
throw new DataBaseConnectorException("Shopping error ^_^ (type == null): ");
}else if(type.equals("$tank$")){
purchase = addTankToGarage(id_user, id);
}else if(type.equals("$armor$")){
addEquipment("armor", id_user, id);
purchase.setArmor(id);
}else if(type.equals("$engine$")){
addEquipment("engine", id_user, id);
purchase.setEngine(id);
}else if(type.equals("$first_weapon$")){
addEquipment("first_weapon", id_user, id);
purchase.setFirstWeapon(id);
}else if(type.equals("$second_weapon$")){
addEquipment("second_weapon", id_user, id);
purchase.setSecondWeapon(id);
} else{
throw new DataBaseConnectorException("Shopping error ^_^ (wrong type): ");
}
executeUpdate("UPDATE users SET money = money - "+cost+" WHERE id_user = "+ id_user);
}
catch (Exception e){
throw new DataBaseConnectorException("Shopping error ^_^ : " + e.toString());
}
return purchase;
}
private int getTankIDForEquipment(String table, String column, int id) throws DataBaseConnectorException {
return getSomeInt("SELECT tank FROM "+table+" WHERE "+column+" = "+id, "tank", "Error when we try get tank for equipment: ");
}
public int getTankIDForArmor(int id) throws DataBaseConnectorException {
return getTankIDForEquipment("armor", "id_armor", id);
}
public int getTankIDForEngine(int id) throws DataBaseConnectorException {
return getTankIDForEquipment("engine", "id_engine", id);
}
public int getTankIDForFirstWeapon (int id) throws DataBaseConnectorException {
return getTankIDForEquipment("first_weapon", "id_weapon", id);
}
public int getTankIDForSecondWeapon(int id) throws DataBaseConnectorException {
return getTankIDForEquipment("second_weapon", "id_weapon", id);
}
public void setUserTank(int id_user, int id_tank) throws DataBaseConnectorException {
try {
executeUpdate("UPDATE users SET tank = "+id_tank+" WHERE id_user = "+id_user);
} catch (Exception e) {
throw new DataBaseConnectorException("Error in changing tank in table 'users' " + e.toString());
}
}
public void addScores(int id_user, int scores) throws DataBaseConnectorException {
try {
executeUpdate("UPDATE users SET scores = scores + " +scores+ " WHERE id_user = "+id_user);
} catch (Exception e) {
throw new DataBaseConnectorException("Error in changing scores in table 'users' " + e.toString());
}
}
public void addMoney(int id_user, int money) throws DataBaseConnectorException {
try {
if(money > 0){
executeUpdate("UPDATE users SET money = money + " +money+ " WHERE id_user = "+id_user);
}
else
throw new Exception("Wrong money add");
} catch (Exception e) {
throw new DataBaseConnectorException("Error in changing scores in table 'users' " + e.toString());
}
}
public String getUserName(int id_user) throws DataBaseConnectorException {
String username;
try {
ResultSet rs = executeQuery("SELECT username FROM users WHERE id_user = " + id_user);
rs.next();
username = rs.getString("username");
} catch (Exception e) {
throw new DataBaseConnectorException("Error in getting name: " + e.toString());
}
return username;
}
public void deleteUser(int id_user) throws DataBaseConnectorException {
try {
executeUpdate("delete from users where id_user = "+ id_user);
}
catch (Exception e){
throw new DataBaseConnectorException("Error we can't delete this User" + e.toString());
}
}
public void addUser(String username, String password, String mail) throws DataBaseConnectorException {
try {
executeUpdate("insert into users (username, password, mail) values (\"" + username + "\",\"" + password + "\",\"" + mail + "\");");
}
catch (SQLIntegrityConstraintViolationException e){
throw new DataBaseConnectorExistException("Such User \"" + username + "\" or mail \"" + mail + "\" already exist!");
}
catch (Exception e){
throw new DataBaseConnectorException("Error we can't add this User " + e.toString());
}
}
public int checkUser(String username, String password) throws DataBaseConnectorException {
return getSomeInt("SELECT id_user FROM users WHERE username = \"" + username + "\" AND password = \"" + password + "\";", "id_user", "");
}
public DataBaseConnector(String login, String password) throws ClassNotFoundException, DataBaseConnectorException {
Class.forName(driverName);
this.login = login;
this.password = password;
connect();
}
public static void main(String[] args){
DataBaseConnector test = null;
try {
System.out.println("Enter the password:");
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
String password = userInput.readLine();
test = new DataBaseConnector("root", password);
ResultSet rs = null, rm = null;
rs = test.getAllUsers();
test.getUserInformation(32);
test.getUserTanks(32);
//test.addEquipment("armor", 32, 1);
while(rs.next()){
System.out.print("Username: " + rs.getString("username") + "\tscores: " + rs.getString("scores") + "\tmoney: " + rs.getString("money"));
rm = test.getUserMail(rs.getInt("id_user"));
rm.next();
System.out.println(" mail: " + rm.getString("mail"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
8495a2bb1dc5604b016359141bbe17583c4591f5 | Java | dydolino/JavaEE2 | /Library/src/Funcions/LibraryRead.java | UTF-8 | 1,084 | 3.09375 | 3 | [] | no_license | package Funcions;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class LibraryRead {
public LibraryRead() {
}
public void read(Connection connection) {
Statement statement = null;
try {
statement = connection.createStatement();
String query = "select * from books";
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()) {
int id = resultSet.getInt("id");
String title = resultSet.getString("title");
String author = resultSet.getString("author");
String year = resultSet.getString("year");
String isbn = resultSet.getString("isbn");
System.out.println(" nr id: " + id + "\n Title: " + title + "\n Author: " + author + "\n Year: " + year + "\n ISBN: " + isbn + "\n");
}
} catch (SQLException var10) {
System.out.println("Nie można wczytać zawartości bazy");
}
}
}
| true |
f056cf2f8ddfac4e2e0a5f6813ba09a3657003b3 | Java | BartoszKonkol/projects | /RHN/1.6.2.1/event/ISignEvent.java | UTF-8 | 202 | 1.765625 | 2 | [] | no_license | package net.polishgames.rhenowar.util.event;
import org.bukkit.block.Sign;
import net.polishgames.rhenowar.util.Rhenowar;
public interface ISignEvent extends Rhenowar
{
public Sign giveSign();
}
| true |
addff1c2567e8c95153dc0448476602b07917025 | Java | Cargon16/AcideTFG | /src/acide/gui/menuBar/configurationMenu/menuMenu/AcideMenuMenu.java | ISO-8859-1 | 19,745 | 1.773438 | 2 | [] | no_license | /*
* ACIDE - A Configurable IDE
* Official web site: http://acide.sourceforge.net
*
* Copyright (C) 2007-2014
* Authors:
* - Fernando Senz Prez (Team Director).
* - Version from 0.1 to 0.6:
* - Diego Cardiel Freire.
* - Juan Jos Ortiz Snchez.
* - Delfn Ruprez Caas.
* - Version 0.7:
* - Miguel Martn Lzaro.
* - Version 0.8:
* - Javier Salcedo Gmez.
* - Version from 0.9 to 0.11:
* - Pablo Gutirrez Garca-Pardo.
* - Elena Tejeiro Prez de greda.
* - Andrs Vicente del Cura.
* - Version from 0.12 to 0.16
* - Semramis Gutirrez Quintana
* - Juan Jess Marqus Ortiz
* - Fernando Ords Lorente
* - Version 0.17
* - Sergio Domnguez Fuentes
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package acide.gui.menuBar.configurationMenu.menuMenu;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import acide.configuration.menu.AcideInsertedItem;
import acide.configuration.menu.AcideInsertedItemListener;
import acide.configuration.menu.AcideInsertedMenu;
import acide.configuration.menu.AcideMenuConfiguration;
import acide.configuration.menu.AcideMenuItemConfiguration;
import acide.configuration.menu.AcideMenuItemsConfiguration;
import acide.configuration.menu.AcideMenuObjectConfiguration;
import acide.configuration.menu.AcideMenuSubmenuConfiguration;
import acide.gui.menuBar.configurationMenu.AcideConfigurationMenu;
import acide.gui.menuBar.configurationMenu.menuMenu.listeners.AcideLoadMenuMenuItemListener;
import acide.gui.menuBar.configurationMenu.menuMenu.listeners.AcideModifyMenuMenuItemListener;
import acide.gui.menuBar.configurationMenu.menuMenu.listeners.AcideNewMenuMenuItemListener;
import acide.gui.menuBar.configurationMenu.menuMenu.listeners.AcideSaveMenuAsMenuItemListener;
import acide.gui.menuBar.configurationMenu.menuMenu.listeners.AcideSaveMenuMenuItemListener;
import acide.gui.menuBar.listeners.AcideMenuBarMouseClickListener;
import acide.language.AcideLanguageManager;
import acide.log.AcideLog;
import acide.resources.AcideResourceManager;
import acide.utils.IconsUtils;
/**
* ACIDE - A Configurable IDE menu menu.
*
* @version 0.11
* @see JMenu
*/
public class AcideMenuMenu extends JMenu {
/**
* ACIDE - A Configurable IDE menu menu class serial version UID.
*/
private static final long serialVersionUID = 1L;
/**
* ACIDE - A Configurable IDE menu menu name.
*/
public final static String MENU_MENU_NAME = "Menu";
/**
* ACIDE - A Configurable IDE menu menu new menu menu item name.
*/
public static final String NEW_MENU_NAME = "New Menu";
/**
* ACIDE - A Configurable IDE menu menu new menu menu item name.
*/
public static final String LOAD_MENU_NAME = "Load Menu";
/**
* ACIDE - A Configurable IDE menu menu modify menu menu item name.
*/
public static final String MODIFY_MENU_NAME = "Modify Menu";
/**
* ACIDE - A Configurable IDE menu menu save menu menu item name.
*/
public static final String SAVE_MENU_NAME = "Save Menu";
/**
* ACIDE - A Configurable IDE menu menu save menu as menu item name.
*/
public static final String SAVE_MENU_AS_NAME = "Save Menu As";
/**
* ACIDE - A Configurable IDE menu menu new menu menu item.
*/
private JMenuItem _newMenuMenuItem;
/**
* ACIDE - A Configurable IDE menu menu new menu menu item has been inserted.
*/
private boolean _newMenuInserted;
/**
* ACIDE - A Configurable IDE menu menu load menu menu item.
*/
private JMenuItem _loadMenuMenuItem;
/**
* ACIDE - A Configurable IDE menu menu load menu menu item has been inserted.
*/
private boolean _loadMenuInserted;
/**
* ACIDE - A Configurable IDE menu menu modify menu menu item.
*/
private JMenuItem _modifyMenuMenuItem;
/**
* ACIDE - A Configurable IDE menu menu modify menu menu item has been inserted.
*/
private boolean _modifyMenuInserted;
/**
* ACIDE - A Configurable IDE menu menu save menu menu item.
*/
private JMenuItem _saveMenuMenuItem;
/**
* ACIDE - A Configurable IDE menu menu save menu menu item has been inserted.
*/
private boolean _saveMenuInserted;
/**
* ACIDE - A Configurable IDE menu menu save menu as menu item.
*/
private JMenuItem _saveMenuAsMenuItem;
/**
* ACIDE - A Configurable IDE menu menu save menu as menu item has been inserted.
*/
private boolean _saveMenuAsInserted;
/**
* ACIDE - A Configurable IDE menu menu configuration menu.
*/
private AcideMenuSubmenuConfiguration _menuSubmenuConfiguration;
/**
* ACIDE - A Configurable IDE inserted menus hashmap.
*/
private HashMap<String, AcideInsertedMenu> _insertedMenus;
/**
* ACIDE - A Configurable IDE inserted items hashmap.
*/
private HashMap<String, AcideInsertedItem> _insertedItems;
/**
* ACIDE - A Configurable IDE array list of inserted objects.
*/
private ArrayList<AcideMenuObjectConfiguration> _insertedObjects;
/**
* Creates a new ACIDE - A Configurable IDE menu menu.
*/
public AcideMenuMenu() {
_newMenuInserted = false;
_loadMenuInserted = false;
_modifyMenuInserted = false;
_saveMenuInserted = false;
_saveMenuAsInserted = false;
_insertedItems = new HashMap<String, AcideInsertedItem>();
_insertedMenus = new HashMap<String, AcideInsertedMenu>();
_insertedObjects = new ArrayList<AcideMenuObjectConfiguration>();
// Builds the menu components
buildComponents();
// Adds the components to the menu
addComponents();
// Sets the text of the menu menu components
setTextOfMenuComponents();
}
/**
* Adds the components to the ACIDE - A Configurable IDE menu menu.
*/
private void addComponents() {
Iterator<Object> it = AcideMenuItemsConfiguration.getInstance()
.getMenuItemsManager().getSubmenu(AcideConfigurationMenu.CONFIGURATION_MENU_NAME)
.getItemsManager().getSubmenu(MENU_MENU_NAME).getItemsManager().managerIterator();
;
while (it.hasNext()){
AcideMenuObjectConfiguration ob = (AcideMenuObjectConfiguration) it.next();
String name = ob.getName();
if (name.equals(NEW_MENU_NAME)){
// Adds the new menu menu item
add(_newMenuMenuItem);
_newMenuInserted = true;
}else if (name.equals(LOAD_MENU_NAME)){
// Adds the load menu menu item
add(_loadMenuMenuItem);
_loadMenuInserted = true;
}else if (name.equals(MODIFY_MENU_NAME)){
// Adds the modify menu menu item
add(_modifyMenuMenuItem);
_modifyMenuInserted = true;
}else if (name.equals(SAVE_MENU_NAME)){
// Adds the save menu menu item
add(_saveMenuMenuItem);
_saveMenuInserted = true;
}else if (name.equals(SAVE_MENU_AS_NAME)){
// Adds the save menu as menu item
add(_saveMenuAsMenuItem);
_saveMenuAsInserted = true;
}else {
if (ob.isSubmenu()){
add(_insertedMenus.get(ob.getName()));
}else{
add(_insertedItems.get(ob.getName()));
}
}
}
if (!_newMenuInserted)
add(_newMenuMenuItem);
if (!_loadMenuInserted)
add(_loadMenuMenuItem);
if (!_modifyMenuInserted)
add(_modifyMenuMenuItem);
if (!_saveMenuInserted)
add(_saveMenuMenuItem);
if (!_saveMenuAsInserted)
add(_saveMenuAsMenuItem);
}
/**
* Builds the ACIDE - A Configurable IDE menu menu components.
*/
private void buildComponents() {
if (!AcideMenuItemsConfiguration.getInstance().getMenuItemsManager()
.getSubmenu(AcideConfigurationMenu.CONFIGURATION_MENU_NAME).hasSubmenu(MENU_MENU_NAME)){
AcideMenuItemsConfiguration.getInstance().getMenuItemsManager()
.getSubmenu(AcideConfigurationMenu.CONFIGURATION_MENU_NAME)
.insertObject(new AcideMenuSubmenuConfiguration(MENU_MENU_NAME));
}
Iterator<Object> it = AcideMenuItemsConfiguration.getInstance()
.getMenuItemsManager().getSubmenu(AcideConfigurationMenu.CONFIGURATION_MENU_NAME)
.getItemsManager().getSubmenu(MENU_MENU_NAME).getItemsManager().managerIterator();
while (it.hasNext()){
AcideMenuObjectConfiguration ob = (AcideMenuObjectConfiguration) it.next();
String name = ob.getName();
if (isOriginal(name)){
_insertedObjects.add(ob);
if (ob.isSubmenu()){
AcideMenuSubmenuConfiguration obSubmenu = (AcideMenuSubmenuConfiguration) ob;
_insertedMenus.put(ob.getName(), new AcideInsertedMenu(obSubmenu));
}else {
AcideMenuItemConfiguration obItem = (AcideMenuItemConfiguration) ob;
_insertedItems.put(obItem.getName(), new AcideInsertedItem(IconsUtils.getIcon(
obItem.getImage()), obItem));
}
}
}
// Creates the new menu menu item
ImageIcon icon = IconsUtils.getIcon(AcideMenuItemsConfiguration.getInstance()
.getMenuItemsManager().getSubmenu(AcideConfigurationMenu.CONFIGURATION_MENU_NAME)
.getSubmenu(MENU_MENU_NAME).getItem(NEW_MENU_NAME).getImage());
if (icon != null)
_newMenuMenuItem = new JMenuItem(icon);
else
_newMenuMenuItem = new JMenuItem();
// Sets the new menu menu item name
_newMenuMenuItem.setName(NEW_MENU_NAME);
// Creates the load menu menu item
icon = IconsUtils.getIcon(AcideMenuItemsConfiguration.getInstance()
.getMenuItemsManager().getSubmenu(AcideConfigurationMenu.CONFIGURATION_MENU_NAME)
.getSubmenu(MENU_MENU_NAME).getItem(LOAD_MENU_NAME).getImage());
if (icon != null)
_loadMenuMenuItem = new JMenuItem(icon);
else
_loadMenuMenuItem = new JMenuItem();
// Sets the load menu menu item name
_loadMenuMenuItem.setName(LOAD_MENU_NAME);
// Creates the modify menu menu item
icon = IconsUtils.getIcon(AcideMenuItemsConfiguration.getInstance()
.getMenuItemsManager().getSubmenu(AcideConfigurationMenu.CONFIGURATION_MENU_NAME)
.getSubmenu(MENU_MENU_NAME).getItem(MODIFY_MENU_NAME).getImage());
if (icon != null)
_modifyMenuMenuItem = new JMenuItem(icon);
else
_modifyMenuMenuItem = new JMenuItem();
// Sets the modify menu menu item name
_modifyMenuMenuItem.setName(MODIFY_MENU_NAME);
// Creates the save menu menu item
icon = IconsUtils.getIcon(AcideMenuItemsConfiguration.getInstance()
.getMenuItemsManager().getSubmenu(AcideConfigurationMenu.CONFIGURATION_MENU_NAME)
.getSubmenu(MENU_MENU_NAME).getItem(SAVE_MENU_NAME).getImage());
if (icon != null)
_saveMenuMenuItem = new JMenuItem(icon);
else
_saveMenuMenuItem = new JMenuItem();
// Sets the save menu menu item name
_saveMenuMenuItem.setName(SAVE_MENU_NAME);
// Disables the save menu menu item
_saveMenuMenuItem.setEnabled(false);
// Creates the save menu as menu item
icon = IconsUtils.getIcon(AcideMenuItemsConfiguration.getInstance()
.getMenuItemsManager().getSubmenu(AcideConfigurationMenu.CONFIGURATION_MENU_NAME)
.getSubmenu(MENU_MENU_NAME).getItem(SAVE_MENU_AS_NAME).getImage());
if (icon != null)
_saveMenuAsMenuItem = new JMenuItem(icon);
else
_saveMenuAsMenuItem = new JMenuItem();
// Sets the save menu as menu item name
_saveMenuAsMenuItem.setName(SAVE_MENU_AS_NAME);
}
/**
* Sets the text of the ACIDE - A Configurable IDE menu menu components with
* the labels in the selected language to display.
*/
public void setTextOfMenuComponents() {
// Sets the new menu menu item text
_newMenuMenuItem.setText(AcideLanguageManager.getInstance().getLabels()
.getString("s275"));
// Sets the load menu menu item text
_loadMenuMenuItem.setText(AcideLanguageManager.getInstance()
.getLabels().getString("s276"));
// Sets the modify menu menu item text
_modifyMenuMenuItem.setText(AcideLanguageManager.getInstance()
.getLabels().getString("s277"));
// Sets the save menu menu item text
_saveMenuMenuItem.setText(AcideLanguageManager.getInstance()
.getLabels().getString("s278"));
// Sets the save menu as menu item text
_saveMenuAsMenuItem.setText(AcideLanguageManager.getInstance()
.getLabels().getString("s279"));
Iterator<AcideMenuObjectConfiguration> it = _insertedObjects.iterator();
while (it.hasNext()){
AcideMenuObjectConfiguration ob = it.next();
if (ob.isSubmenu()){
_insertedMenus.get(ob.getName()).setText(ob.getName());
_insertedMenus.get(ob.getName()).setTextOfMenuComponents();
}else{
_insertedItems.get(ob.getName()).setText(ob.getName());
}
}
}
/**
* Updates the ACIDE - A Configurable IDE menu menu components visibility
* with the menu configuration.
*/
public void updateComponentsVisibility() {
AcideMenuItemConfiguration newMenuConfiguration;
AcideMenuItemConfiguration loadMenuConfiguration;
AcideMenuItemConfiguration modifyMenuConfiguration;
AcideMenuItemConfiguration saveMenuConfiguration;
AcideMenuItemConfiguration saveMenuAsConfiguration;
_menuSubmenuConfiguration = AcideMenuItemsConfiguration.getInstance()
.getSubmenu(AcideConfigurationMenu.CONFIGURATION_MENU_NAME).getSubmenu(MENU_MENU_NAME);
// Sets the new menu menu item to visible or not visible
newMenuConfiguration = _menuSubmenuConfiguration.getItem(NEW_MENU_NAME);
_newMenuMenuItem.setVisible(newMenuConfiguration.isVisible());
// Sets the load menu menu item to visible or not visible
loadMenuConfiguration = _menuSubmenuConfiguration.getItem(LOAD_MENU_NAME);
_loadMenuMenuItem.setVisible(loadMenuConfiguration.isVisible());
// Sets the modify menu menu item to visible or not visible
modifyMenuConfiguration = _menuSubmenuConfiguration.getItem(MODIFY_MENU_NAME);
_modifyMenuMenuItem.setVisible(modifyMenuConfiguration.isVisible());
// Sets the save menu menu item to visible or not visible
saveMenuConfiguration = _menuSubmenuConfiguration.getItem(SAVE_MENU_NAME);
_saveMenuMenuItem.setVisible(saveMenuConfiguration.isVisible());
// Sets the save as menu menu item to visible or not visible
saveMenuAsConfiguration = _menuSubmenuConfiguration.getItem(SAVE_MENU_AS_NAME);
_saveMenuAsMenuItem.setVisible(saveMenuAsConfiguration.isVisible());
Iterator<AcideMenuObjectConfiguration> it = _insertedObjects.iterator();
while (it.hasNext()){
AcideMenuObjectConfiguration ob = it.next();
if (ob.isSubmenu()){
_insertedMenus.get(ob.getName()).updateComponentsVisibility();
_insertedMenus.get(ob.getName()).setVisible(ob.isVisible());
}else{
_insertedItems.get(ob.getName()).setVisible(ob.isVisible());
}
}
// Sets the menu menu to visible or not visible
_menuSubmenuConfiguration.setVisible(_newMenuMenuItem.isVisible()
|| _loadMenuMenuItem.isVisible()
|| _modifyMenuMenuItem.isVisible()
|| _saveMenuMenuItem.isVisible()
|| _saveMenuAsMenuItem.isVisible());
_menuSubmenuConfiguration.setErasable(false);
try{
//Save the configuration for the menu that could have been modified
AcideMenuConfiguration.getInstance()
.saveMenuConfigurationFile("./configuration/menu/lastModified.menuConfig");
// Gets the the ACIDE - A Configurable IDE current menu
// configuration
String currentMenuConfiguration = AcideResourceManager
.getInstance().getProperty("currentMenuConfiguration");
if (!currentMenuConfiguration
.endsWith("lastModified.menuConfig")
&& !currentMenuConfiguration
.endsWith("newMenu.menuConfig")) {
// Updates the the ACIDE - A Configurable IDE previous
// menu
// configuration
AcideResourceManager.getInstance().setProperty(
"previousMenuConfiguration",
currentMenuConfiguration);
}
// Updates the the ACIDE - A Configurable IDE current menu
// configuration
AcideResourceManager.getInstance().setProperty(
"currentMenuConfiguration", "./configuration/menu/lastModified.menuConfig");
}
catch (Exception exception2) {
// Updates the log
AcideLog.getLog().error(exception2.getMessage());
exception2.printStackTrace();
}
}
/**
* Gets if the menu name given as parameter is original
* @param name
* the name we want to check
* @return
* if the name given as parameter is original
*/
public boolean isOriginal(String name){
if (!(name.equals(NEW_MENU_NAME))
&& !(name.equals(LOAD_MENU_NAME))
&& !(name.equals(MODIFY_MENU_NAME))
&& !(name.equals(SAVE_MENU_NAME))
&& !(name.equals(SAVE_MENU_AS_NAME))){
return true;
}else{
return false;
}
}
/**
* Set the ACIDE - A Configurable IDE menu menu item listeners.
*/
public void setListeners() {
// Sets the new menu menu item action listener
_newMenuMenuItem.addActionListener(new AcideNewMenuMenuItemListener());
// Sets the load menu menu item action listener
_loadMenuMenuItem
.addActionListener(new AcideLoadMenuMenuItemListener());
// Sets the modify menu menu item action listener
_modifyMenuMenuItem
.addActionListener(new AcideModifyMenuMenuItemListener());
// Sets the save menu menu item action listener
_saveMenuMenuItem
.addActionListener(new AcideSaveMenuMenuItemListener());
// Sets the save menu as menu item action listener
_saveMenuAsMenuItem
.addActionListener(new AcideSaveMenuAsMenuItemListener());
Iterator<AcideMenuObjectConfiguration> it = _insertedObjects.iterator();
while (it.hasNext()){
AcideMenuObjectConfiguration ob = it.next();
if (ob.isSubmenu()){
_insertedMenus.get(ob.getName()).addMouseListener(new AcideMenuBarMouseClickListener());
_insertedMenus.get(ob.getName()).setListeners();
}else{
AcideInsertedItem aux = _insertedItems.get(ob.getName());
aux.addActionListener((new AcideInsertedItemListener(aux)));
}
}
}
/**
* Returns the ACIDE - A Configurable IDE menu menu new menu menu item.
*
* @return the ACIDE - A Configurable IDE menu menu new menu menu item.
*/
public JMenuItem getNewMenuMenuItem() {
return _newMenuMenuItem;
}
/**
* Returns the ACIDE - A Configurable IDE menu menu load menu menu item.
*
* @return the ACIDE - A Configurable IDE menu menu load menu menu item.
*/
public JMenuItem getLoadMenuMenuItem() {
return _loadMenuMenuItem;
}
/**
* Returns the ACIDE - A Configurable IDE menu menu modify menu menu item.
*
* @return the ACIDE - A Configurable IDE menu menu modify menu menu item.
*/
public JMenuItem getModifyMenuMenuItem() {
return _modifyMenuMenuItem;
}
/**
* Returns the ACIDE - A Configurable IDE menu menu save menu menu item.
*
* @return the ACIDE - A Configurable IDE menu menu save menu menu item.
*/
public JMenuItem getSaveMenuMenuItem() {
return _saveMenuMenuItem;
}
/**
* Returns the ACIDE - A Configurable IDE menu menu save menu as menu item
*
* @return the ACIDE - A Configurable IDE menu menu save menu as menu item
*/
public JMenuItem getSaveMenuAsMenuItem() {
return _saveMenuAsMenuItem;
}
}
| true |
a31b9e5a656c69133203d209db6f21258ac52c9a | Java | ericwang094/leetcode | /src/LeetcodeGeneral/LRUCache_SinglyLinkedList_146.java | UTF-8 | 2,242 | 3.28125 | 3 | [] | no_license | package LeetcodeGeneral;
import java.util.HashMap;
import java.util.Map;
import TwoPointers.ListNode;
import java.util.HashMap;
import java.util.Map;
public class LRUCache_SinglyLinkedList_146 {
public class LRUCache {
private class ListNode {
int val;
int key;
ListNode next;
public ListNode(int key, int val) {
this.val = val;
this.key = key;
}
}
int capacity;
Map<Integer, ListNode> mapKToPrev;
ListNode head;
ListNode tail;
public LRUCache(int capacity) {
this.capacity = capacity;
this.mapKToPrev = new HashMap<>();
this.head = new ListNode(-1, -1);
this.tail = new ListNode(-2, -2);
mapKToPrev.put(tail.key, head);
head.next = tail;
}
public int get(int key) {
if (!mapKToPrev.containsKey(key)) {
return -1;
}
ListNode prevNode = mapKToPrev.get(key);
ListNode currentNode = prevNode.next;
prevNode.next = prevNode.next.next;
mapKToPrev.put(prevNode.next.key, prevNode);
ListNode lastEle = mapKToPrev.get(this.tail.key);
lastEle.next = currentNode;
mapKToPrev.put(currentNode.key, lastEle);
currentNode.next = tail;
mapKToPrev.put(tail.key, currentNode);
return currentNode.val;
}
public void put(int key, int value) {
if (this.get(key) != -1) {
mapKToPrev.get(key).next.val = value;
return;
}
if (this.capacity == mapKToPrev.size() - 1) {
mapKToPrev.remove(mapKToPrev.get(head.next.key).next.key);
this.head.next = this.head.next.next;
mapKToPrev.put(head.next.key, head);
}
ListNode newNode = new ListNode(key, value);
ListNode lastEle = mapKToPrev.get(this.tail.key);
lastEle.next = newNode;
newNode.next = tail;
mapKToPrev.put(key, lastEle);
mapKToPrev.put(tail.key, newNode);
}
}
public static void main(String[] args) {
LRUCache_SinglyLinkedList_146 test = new LRUCache_SinglyLinkedList_146();
LRUCache_SinglyLinkedList_146.LRUCache realTest = test.new LRUCache(3);
realTest.put(1, 1);
realTest.put(2, 2);
realTest.put(3, 3);
realTest.put(4, 4);
realTest.get(4);
realTest.get(3);
realTest.get(2);
realTest.get(1);
realTest.put(5, 5);
realTest.get(1);
realTest.get(2);
realTest.get(3);
realTest.get(4);
realTest.get(5);
}
}
| true |
983cb5eb6af12c33d7fb3a0ea987a234b213bbdb | Java | cduvvuri18/EmbeddedHornetQSpringExample | /src/main/java/com/bioimagene/iii/ims/messaging/publish/ImsMessagePublisher.java | UTF-8 | 148 | 1.65625 | 2 | [] | no_license | package com.bioimagene.iii.ims.messaging.publish;
public interface ImsMessagePublisher {
void publishToConnectVOutboundQueue( String text );
}
| true |
4cec642a5a1754ae0f814e206156fcb76682cc31 | Java | vamshigunda1/ReportCenterAutomation | /reportceneter_pom/src/test/java/com/truven/advantagesuite/testcase/CrossTabReport.java | UTF-8 | 2,054 | 1.875 | 2 | [] | no_license | package com.truven.advantagesuite.testcase;
import org.testng.annotations.Test;
import com.truven.advantagesuite.pages.AHRW;
import com.truven.advantagesuite.pages.LoginPage;
import com.truven.advantagesuite.pages.PackageSelection;
import com.truven.advantagesuite.pages.RunNSaveReport;
import com.truven.advantagesuite.pages.SearchMeasureOrSubset;
import com.truven.advantagesuite.pages.SelectTimePeriod;
import org.testng.annotations.BeforeTest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
public class CrossTabReport {
WebDriver driver;
@BeforeTest
public void setup () {
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://trvlapp2063/cognos/cgi-bin/cognos.cgi");
//"http://trvlapp2063/cognos/cgi-bin/cognos.cgi");
//https://ahrwqa-libra.truvenhealth.com/
}
@Test
public void CrossTabRep() throws IOException, InterruptedException, Exception {
LoginPage lpage = new LoginPage(driver);
lpage.login(false);
AHRW reportwriter = new AHRW(driver);
reportwriter.openAdhocRW();
PackageSelection selector = new PackageSelection(driver);
selector.PackageSelector("Adv zero six five new demo data build Package");
//"Zero Two Two One New Commercial Demo build Package");
SearchMeasureOrSubset rcs = new SearchMeasureOrSubset(driver);
rcs.SearchMeasure("Patients BMI Assessment Adult Num {QM}");
rcs.SearchMeasure("Patients BMI Assessment Adult Den {QM}");
rcs.SearchMeasure("Body Mass Index Adult Rate {QM}");
rcs.SearchSubset("Body Mass Index Assessment Adult {QS}");
SelectTimePeriod tp = new SelectTimePeriod(driver);
tp.TimePeriod();
RunNSaveReport rs = new RunNSaveReport(driver);
rs.runReport();
rs.saveReport();
}
@AfterTest
public void teardown () {
//driver.quit();
}
}
| true |
10493d5f801c0f9d6acd721a64c5f3a3b67ec603 | Java | cjhox/Rupert | /Code/Projekt Rupert/src/shared/com/UpdateHealth.java | ISO-8859-1 | 560 | 2.1875 | 2 | [] | no_license | package shared.com;
/**
* UpdateHealth ist das Serialisierbare Objekt, welches nach der Kampfphase vom
* Server an den Client gesendet wird. UpdateHealth enthlt eine List, welche
* alle vom Server durchgefhrten Zge in der korrekten Reihenfolge enthlt
* damit der Client seine Units entsprechend konsistent Updaten kann.
*/
public class UpdateHealth extends Update<UpdateHealthData> {
private static final long serialVersionUID = -2761411205881230248L;
@Override
public String toString() {
return "UpdateHealth [datas=" + datas + "]";
}
}
| true |
8747a9875735210a89dad817af3ebfd1310ab4de | Java | valdemirsm/projetos | /EstudoAlgaWorks/src/br/com/valdemir/converter/ClienteConverter.java | UTF-8 | 1,049 | 2.3125 | 2 | [] | no_license | package br.com.valdemir.converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import br.com.valdemir.model.Cliente;
import br.com.valdemir.repository.ClienteRepository;
import br.com.valdemir.util.cdi.CDIServiceLocator;
@FacesConverter(forClass = Cliente.class)
public class ClienteConverter implements Converter{
//@Inject
private ClienteRepository clientes;
public ClienteConverter() {
this.clientes = (ClienteRepository) CDIServiceLocator.getBean(ClienteRepository.class);
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
Cliente retorno = null;
if (value != null) {
retorno = this.clientes.porId(new Long(value));
}
return retorno;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value != null) {
return ((Cliente) value).getId().toString();
}
return "";
}
}
| true |
9f0a07d1d7fd0c511184ea6b9a50a58d197d2fc6 | Java | Valarath/Java-SE-2-homework | /src/main/java/cz/unicorncollege/bt/commands/MeetingRoomCommandName.java | UTF-8 | 1,406 | 2.484375 | 2 | [] | no_license | package cz.unicorncollege.bt.commands;
import cz.unicorncollege.bt.commands.meeting.room.AddRoom;
import cz.unicorncollege.bt.commands.meeting.room.EditRoom;
import cz.unicorncollege.bt.commands.meeting.room.ShowRooms;
import cz.unicorncollege.bt.commands.support.Process;
import cz.unicorncollege.bt.model.MeetingCentre;
import java.util.LinkedHashMap;
import java.util.Map;
public enum MeetingRoomCommandName implements CommandName {
SHOW_ROOMS("Show rooms"),
ADD("Add room"),
EDIT("Edit room"),
BACK("Go back");
private String description;
MeetingRoomCommandName(String description) {
this.description = description;
}
public static MeetingRoomCommandName getCommandByNumber(int commandNumber){
return CommandName.getCommandByNumber(MeetingRoomCommandName.class,commandNumber);
}
public static Map<MeetingRoomCommandName, Command> initCommands(Process process){
Map<MeetingRoomCommandName, Command> commands = new LinkedHashMap<>();
commands.put(MeetingRoomCommandName.SHOW_ROOMS,new ShowRooms());
commands.put(MeetingRoomCommandName.ADD,new AddRoom());
commands.put(MeetingRoomCommandName.EDIT,new EditRoom());
commands.put(MeetingRoomCommandName.BACK,new KillProccess(process));
return commands;
}
@Override
public String getDescription() {
return description;
}
}
| true |
4cb41325d123cca6bbeb8b8cbe20dce525637ca3 | Java | stephen1706/astro | /app/src/main/java/com/stephen/astro/Constants.java | UTF-8 | 426 | 2.03125 | 2 | [] | no_license | package com.stephen.astro;
import java.util.concurrent.TimeUnit;
/**
* Created by stephenadipradhana on 12/28/16.
*/
public interface Constants {
long SERVER_TIMEZONE = TimeUnit.HOURS.toMillis(8);//server time is +8 GMT, request must be in +8 not in UTC
String REALM_DATABASE_NAME = "weather.realm";
int SORT_NUMBER = 0;
int SORT_NAME = 1;
int SORT_FAVOURITE = 2;
int PAGINATION_LENGTH = 15;
}
| true |
e37fda224f9dca59e830d08dd7a8a298366e32cd | Java | boricles/aemet | /tools/VisualizadorAemet/src/main/java/es/upm/fi/dia/oeg/map4rdf/client/widget/StatisticsSelectionDialog.java | MacCentralEurope | 3,787 | 2.046875 | 2 | [
"MIT"
] | permissive | /**
* Copyright (c) 2011 Ontology Engineering Group,
* Departamento de Inteligencia Artificial,
* Facultad de Informtica, Universidad
* Politcnica de Madrid, Spain
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package es.upm.fi.dia.oeg.map4rdf.client.widget;
import java.util.List;
import name.alexdeleon.lib.gwtblocks.client.widget.prettypopup.PrettyPopup;
import name.alexdeleon.lib.gwtblocks.client.widget.prettypopup.PrettyPopupStylesheetFactory;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ListBox;
import es.upm.fi.dia.oeg.map4rdf.client.resource.BrowserMessages;
import es.upm.fi.dia.oeg.map4rdf.client.util.LocaleUtil;
import es.upm.fi.dia.oeg.map4rdf.share.Resource;
import es.upm.fi.dia.oeg.map4rdf.share.StatisticDefinition;
/**
* @author Alexander De Leon
*/
public class StatisticsSelectionDialog extends PrettyPopup implements HasSelectionHandlers<StatisticDefinition> {
private final ListBox datasetList = new ListBox();
private final Button selectButton = new Button("Select");
private final BrowserMessages messages;
public StatisticsSelectionDialog(List<Resource> datasets, BrowserMessages messages) {
super(PrettyPopupStylesheetFactory.getDefaultStylesheet(), true);
this.messages = messages;
setModal(true);
initDatasetList(datasets);
createUi();
}
@Override
public HandlerRegistration addSelectionHandler(SelectionHandler<StatisticDefinition> handler) {
return addHandler(handler, SelectionEvent.getType());
}
protected String getSelectedDataset() {
return datasetList.getValue(datasetList.getSelectedIndex());
}
protected void initDatasetList(List<Resource> datasets) {
for (Resource dataset : datasets) {
datasetList.addItem(dataset.getLabel(LocaleUtil.getClientLanguage()), dataset.getUri());
}
}
private void createUi() {
getContentPanel().add(new HTML("<h2>" + messages.statistics() + ":</h2>"));
getContentPanel().add(datasetList);
getContentPanel().add(new HTML("<br />"));
selectButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
StatisticDefinition statistic = new StatisticDefinition(getSelectedDataset());
SelectionEvent.fire(StatisticsSelectionDialog.this, statistic);
hide();
}
});
selectButton.setText(messages.select());
getContentPanel().add(selectButton);
}
}
| true |
bd8ad9d91d90cc86436b8f52fdb4e1f654b4757b | Java | AmbroseNTK/GamelibGdxDemo1 | /core/src/kiet/nguyentuan/libgdx/demo1/GoldCoin.java | UTF-8 | 1,119 | 2.421875 | 2 | [] | no_license | package kiet.nguyentuan.libgdx.demo1;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
/**
* Created by nguye on 21/11/2016.
*/
public class GoldCoin extends AbstractGameObject {
private TextureRegion regGoldCoin;
public boolean collected;
public GoldCoin(){
init();
}
public void init(){
dimension.set(0.5f,0.5f);
regGoldCoin=Assets.instance.goldCoin.goldCoin;
bounds.set(0,0,dimension.x,dimension.y);
collected=false;
}
@Override
public void render(SpriteBatch batch) {
if(collected)return;
TextureRegion reg=null;
reg=regGoldCoin;
batch.draw(reg.getTexture(),
position.x,position.y,
origin.x,origin.y,
dimension.x,dimension.y,
scale.x,scale.y,
rotation,
reg.getRegionX(),reg.getRegionY(),
reg.getRegionWidth(),reg.getRegionHeight(),
false,
false);
}
public int getScore(){
return 100;
}
}
| true |
d6f61ba9441b2b2cf9794c92b7ce9e85d6a4388c | Java | DrXrayW/practice | /src/xray/leetcode/bits/GrayCode.java | UTF-8 | 675 | 3.265625 | 3 | [] | no_license | package xray.leetcode.bits;
import java.util.ArrayList;
import java.util.List;
/*
* 00 - 0
01 - 1
11 - 3
10 - 2
IN SHORT:
long gray = i^(i>>1) ;
*/
public class GrayCode {
public List<Integer> grayCode(int n) {
List<Integer> result = new ArrayList<Integer>();
int N = 32;
if((n<=0)||(n>N)){
result.add(0); //OJ needs this, for n=0, want a 0 in the list
return result;
}
long size = 1 << n;
for(long i=0;i<size;i++){
long gray = i^(i>>1) ; //This is the trick: gray code = n ^ (n/2)
result.add((int)gray);
}
return result;
}
}
| true |
b3d2015cf85dc25b474b2ab3ee3c815ae5945ca6 | Java | Vince-Lu177/practice | /JavaTest/Tree2str.java | UTF-8 | 1,691 | 4.03125 | 4 | [] | no_license | package practice.practice.JavaTest;
public class Tree2str {
class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
//二叉树创建字符串
//根据先序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串,空节点则用一对空括号"()"表示
//而且你需要省略所有不影响字符与原始二叉树之间的一对一的映射关系的空括号对
//括号省略的注意事项:
//1.如果一个树的左右子树都为空,括号可以省略
//2.如果一个树的左子树为空,右子树不为空,括号不可以省略
//3.如果一个树的右子树为空,左子树不为空,括号可以省略
private StringBuilder sb = new StringBuilder();
//使用sb表示最终得到字符串的结果
//递归过程中得到的局部结构都往sb中追加
public String tree2str(TreeNode t){
if(t == null){
//空树返回一个空的字符串
return "";
}
//借助helper方法递归进行前序遍历
helper(t);
sb.deleteCharAt(0);
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
private void helper(TreeNode t) {
if(t == null){
return;
}
//访问根节点,此处的访问把访问操作追加到sb中即可
sb.append("(");
sb.append(t.val);
helper(t.left);
if(t.left == null && t.right != null){
sb.append("()");
}
helper(t.right);
sb.append(")");
}
}
| true |
2f81cce8f8eeed786c5e3b243c8c01c044bbbb81 | Java | GameDevCompanyName/AndroidProject | /app/src/main/java/ru/gdcn/beastmaster64revelations/GameClass/Actions/BasicHeal.java | UTF-8 | 1,311 | 2.65625 | 3 | [] | no_license | package ru.gdcn.beastmaster64revelations.GameClass.Actions;
import ru.gdcn.beastmaster64revelations.GameInterface.Action.Action;
import ru.gdcn.beastmaster64revelations.GameInterface.Action.ActionResult;
import ru.gdcn.beastmaster64revelations.GameInterface.Action.ActionType;
import ru.gdcn.beastmaster64revelations.GameInterface.Character.Character;
public class BasicHeal implements Action {
protected final String name;
// protected final Integer AP;
@SuppressWarnings("WeakerAccess")
protected final Integer pointsHealed;
public BasicHeal(String name, Integer pointsHealed){
this.name = name;
// this.AP = AP;
this.pointsHealed = pointsHealed;
}
@Override
public String getName() {
return name;
}
@Override
public Integer getRequiredAP() {
//TODO
return 0;
}
@Override
public ActionType getType() {
return ActionType.DEFENSE;
}
@Override
public ActionResult use(Character user, Character other) {
user.dealHeal(pointsHealed);
return ActionResult.HIT;
}
@Override
public String toString() {
return "АТАКА{" +
"name='" + name + '\'' +
", pointsHealed=" + pointsHealed +
'}';
}
}
| true |
6d1e7ab2bade589d911e2c0d4ccc2e3d1d81308e | Java | sungsikyang92/framework | /springIOC5-dbcp/src/model/AccountDAO.java | UTF-8 | 408 | 2.046875 | 2 | [] | no_license | package model;
import java.sql.SQLException;
public interface AccountDAO {
/* 메서드 오버라이딩 규칙: 메서드명, 매개변수 동일해야 하고
* 접근제어자는 하위로 갈수록 범위가 좁아져서는 안되고
* 상위 메서드에서 선언한 Exception 또는 하위 Exception만 throws 가능하다.
*/
public AccountVO findAccountById(String id) throws SQLException;
}
| true |
f5c47bd2b026d39825fafa2986e6c51b74471d85 | Java | tagban/bnubot | /BNUBot/src/net/bnubot/util/MirrorSelector.java | UTF-8 | 3,361 | 2.6875 | 3 | [] | no_license | /**
* This file is distributed under the GPL
* $Id$
*/
package net.bnubot.util;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import net.bnubot.logging.Out;
import net.bnubot.settings.GlobalSettings;
/**
* A class for picking the fastest address
* http://www.x86labs.org/forum/index.php/topic,10225.0.html
* @author Chavo
* @author scotta
*/
public class MirrorSelector {
private static final int MAX_TIME = 400; // timeout time in ms
private static final int IDEAL_LIMIT = 50;
private static final int MAX_TIME_TOTAL = 3000;
private static InetAddress selectMirror(InetAddress[] mirrors, int port) {
Socket s = new Socket();
long bestTime = MAX_TIME;
InetAddress bestHost = null;
long start = System.currentTimeMillis();
for (InetAddress mirror : mirrors) {
try {
s = new Socket();
long lap = System.currentTimeMillis();
s.connect(new InetSocketAddress(mirror, port), MAX_TIME);
long time = System.currentTimeMillis() - lap;
s.close();
if(Out.isDebug(MirrorSelector.class))
Out.debugAlways(MirrorSelector.class, "Connecting to " + mirror.getHostAddress() + " took " + time + "ms");
if(time <= IDEAL_LIMIT)
return mirror;
if (time < bestTime) {
bestTime = time;
bestHost = mirror;
}
} catch (SocketTimeoutException ste) {
Out.error(MirrorSelector.class, "Address " + mirror + " timed out");
} catch (ConnectException ce) {
Out.error(MirrorSelector.class, "Connect Exception: " + ce.getMessage() + " for " + mirror);
} catch (SocketException se) {
Out.error(MirrorSelector.class, "Unable to connect to " + mirror + ", there may be a problem with your network connection.");
} catch (IOException ioe) {
Out.error(MirrorSelector.class, "Error connecting to " + mirror);
Out.exception(ioe);
}
long elapsed = System.currentTimeMillis() - start;
if(elapsed > MAX_TIME_TOTAL) {
Out.info(MirrorSelector.class, "Mirror selection is taking too long; skipping.");
break;
}
}
if(bestHost == null) {
bestHost = random(mirrors);
Out.info(MirrorSelector.class, "There was no clear winner; randomly choosing " + bestHost.getHostAddress());
}
return bestHost;
}
private static InetAddress random(InetAddress[] hosts) {
return hosts[(int)(Math.random() * hosts.length)];
}
public static InetAddress getClosestMirror(String hostname, int port)
throws UnknownHostException {
InetAddress hosts[] = InetAddress.getAllByName(hostname);
if(true) {
// Remove IPv6 addresses from the list
int i = 0;
for(InetAddress ia : hosts) {
if(ia instanceof Inet4Address)
i++;
}
if(i < hosts.length) {
InetAddress[] newHosts = new InetAddress[i];
i = 0;
for(InetAddress ia : hosts) {
if(ia instanceof Inet4Address)
newHosts[i++] = ia;
}
hosts = newHosts;
}
}
if (hosts.length == 1)
return hosts[0];
if(!GlobalSettings.enableMirrorSelector)
return random(hosts);
Out.info(MirrorSelector.class, "Searching for fastest of " + hosts.length + " hosts for " + hostname);
return selectMirror(hosts, port);
}
} | true |
199424bb0f7f7cc97df8ef47e63ade5aadaa7a1a | Java | mTomczak/CustomerCreditApp | /Product/src/test/java/app/controller/ProductControllerTest.java | UTF-8 | 945 | 2.328125 | 2 | [] | no_license | package app.controller;
import app.model.Product;
import app.repository.ProductRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class ProductControllerTest {
@Autowired
ProductRepository productRepository;
@Autowired
ProductController productController;
@Autowired
Product product;
@Autowired
Product testProduct;
@Test
public void createProductAndGetProductTest(){
product.setProductName("Product");
product.setValue(15);
productController.createProduct(product);
testProduct = productController.getProduct("Product");
assertEquals(product.getProductName(), testProduct.getProductName());
assertEquals(product.getValue(), testProduct.getValue());
}
} | true |
ca6a5696b774d7f05f0109e1e1794a6a842167fa | Java | Ziongorlik/BuyMeProjectUpgraded | /src/test/java/pages/IntroPage.java | UTF-8 | 2,970 | 2.734375 | 3 | [] | no_license | package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import java.sql.SQLException;
import java.util.List;
/***
* Intro page management
*/
public class IntroPage extends BasePage{
public IntroPage() throws SQLException {
super();
}
/***
* Enters the Registration page.
* @param firstName The user's first name.
* @param email The user's email.
* @param password The user's password.
* @return Returns "true" or "false" whether the registration was successful
*/
public boolean register(String firstName, String email, String password){
clickElement(By.className("seperator-link"));
clickElement(By.cssSelector("span[class='text-link theme']"));
inputCredentials(firstName,email,password);
clickElement(By.cssSelector("button[type='submit']"));
return !waitForElement(By.className("login-error"));
}
/***
* Input the correct credentials and asserts them.
* @param firstName The user's first name.
* @param email The user's email.
* @param password The user's password.
*/
private void inputCredentials(String firstName, String email, String password) {
List<WebElement> credentialsTxtBoxes = getElementChildren(By.cssSelector("form[action='register']"),"input");
sendKeysToElement(credentialsTxtBoxes.get(0), firstName);
sendKeysToElement(credentialsTxtBoxes.get(1), email);
sendKeysToElement(credentialsTxtBoxes.get(2), password);
sendKeysToElement(credentialsTxtBoxes.get(3), password);
Assert.assertEquals(credentialsTxtBoxes.get(0).getAttribute("value"),firstName);
Assert.assertEquals(credentialsTxtBoxes.get(1).getAttribute("value"),email);
Assert.assertEquals(credentialsTxtBoxes.get(2).getAttribute("value"),password);
Assert.assertEquals(credentialsTxtBoxes.get(3).getAttribute("value"),password);
}
/***
* Login if the registration already done (email exist).
*/
public void login() {
clickElement(By.className("text-link"));
clickElement(By.cssSelector("button[type='submit']"));
}
/***
* Performs an empty login and asserts the error messages.
*/
public void emptyLogin(){
clickElement(By.className("seperator-link"));
clickElement(By.cssSelector("button[type='submit']"));
String emailErrorMsg = getElementAttribute(By.cssSelector("input[type=email]"),"data-parsley-required-message");
String passwordErrorMsg = getElementAttribute(By.cssSelector("input[type=password]"),"data-parsley-required-message");
String loginPageError = "כל המתנות מחכות לך! אבל קודם צריך מייל וסיסמה";
Assert.assertEquals(emailErrorMsg, loginPageError);
Assert.assertEquals(passwordErrorMsg, loginPageError);
clickElement(By.id("times"));
}
}
| true |
6c4cd78ac5cdd0d1a963d38d94c617f2ac3f8943 | Java | mathieu-ma/montagnesdor | /mdo-core/api/src/main/java/fr/mch/mdo/restaurant/dao/restaurants/IRestaurantReductionTablesDao.java | UTF-8 | 703 | 1.9375 | 2 | [] | no_license | package fr.mch.mdo.restaurant.dao.restaurants;
import java.util.List;
import fr.mch.mdo.restaurant.dao.IDaoServices;
import fr.mch.mdo.restaurant.dao.beans.RestaurantReductionTable;
import fr.mch.mdo.restaurant.exception.MdoException;
public interface IRestaurantReductionTablesDao extends IDaoServices
{
List<RestaurantReductionTable> findAll(Long restaurantId) throws MdoException;
List<RestaurantReductionTable> findAll(Long restaurantId, String typeName) throws MdoException;
List<RestaurantReductionTable> findOnlyReductionTables(Long restaurantId) throws MdoException;
RestaurantReductionTable findReductionTable(Long restaurantId, Long typeId) throws MdoException;
}
| true |
93f2d07b0fe15736a743dc3d176ec9113ed15070 | Java | wesjones15/CR-MacroLabs-OOP-ATM | /src/main/java/com/zipcodewilmington/Checking.java | UTF-8 | 196 | 1.953125 | 2 | [] | no_license | package com.zipcodewilmington;
public class Checking extends Account {
public Checking(Double balance, Integer userId, Integer accountId) {
super(balance, userId, accountId);
}
}
| true |
66ac78420b68948662c0db8815992ed4565ccbab | Java | Gregaryw/high-song | /common/common-mybatis/src/main/java/com/high/core/enums/FieldFill.java | UTF-8 | 229 | 1.734375 | 2 | [] | no_license | package com.high.core.enums;
/**
* @Author: HarlanW
* @Date: 2019/4/8 0008
* @Version: 1.0
*/
public enum FieldFill {
/**
*
*/
DEFAULT,
INSERT,
UPDATE,
INSERT_UPDATE;
FieldFill() {
}
}
| true |
fc8a251decd8361b2751097a52eb431765be8daa | Java | lon-io/consonance-java | /assignments/A2/Nim.java | UTF-8 | 2,430 | 3.59375 | 4 | [] | no_license | import java.util.Scanner;
public class NimGame {
public static void main(String[] args){
String player1, player2;
int A, B, C, check=0;
char pile1;
char pile2;
Scanner input = new Scanner(System.in);
// take in names from users
System.out.print("Player 1, enter your name: ");
player1 = input.nextLine();
System.out.print("Player 2, enter your name: ");
player2 = input.nextLine();
A = (int)(Math.random()*5 + 1);
B = (int)(Math.random()*5 + 1);
C = (int)(Math.random()*5 + 1);
//Display the piles
System.out.printf("\nA: %d\tB: %d\tC: %d\n", A, B, C);
do{
int remove;
do{
System.out.print("\n" + player1 + ", choose a pile: ");
pile1 = Character.toUpperCase(input.next().charAt(0));
switch(pile1){
case 'A':
check=A;
break;
case 'B':
check = B;
break;
case 'C':
check = C;
break;
}
}
while(check==0);
System.out.printf("How many to remove from pile %c: ", pile1);
remove = input.nextInt();
switch(pile1){
case 'A':
A = A - remove;
if(A < 0)
A=0;
break;
case 'B':
B = B - remove;
if(B < 0)
B=0;
break;
case 'C':
C = C - remove;
if(C < 0)
C=0;
break;
}
System.out.printf("\nA: %d\tB: %d\tC: %d\n", A, B, C);
switch(A +B + C ){
case 0:
System.out.println("\n" + player2 + ", there are no counters left, so you WIN!");
continue;
}
do{
System.out.print("\n" + player2 + ", choose a pile: ");
pile2 = Character.toUpperCase(input.next().charAt(0));
switch(pile2){
case 'A':
check=A;
break;
case 'B':
check = B;
break;
case 'C':
check = C;
break;
}
}
while(check==0);
System.out.printf("How many to remove from pile %c: ", pile2);
remove = input.nextInt();
switch(pile2){
case 'A':
A = A - remove;
if(A < 0)
A=0;
break;
case 'B':
B = B - remove;
if(B < 0)
B=0;
break;
case 'C':
C = C - remove;
if(C < 0)
C=0;
break;
}
System.out.printf("\nA: %d\tB: %d\tC: %d\n", A, B, C);
switch(A +B + C ){
case 0:
System.out.println("\n" + player1 + ", there are no counters left, so you WIN!");
break;
}
}
while((A+B+C)>0);
}
}
| true |
0178334eab67a0708add182568ea9862881547e0 | Java | crnk-project/crnk-framework | /crnk-core/src/main/java/io/crnk/core/module/internal/DefaultRepositoryInformationProviderContext.java | UTF-8 | 970 | 1.976563 | 2 | [
"Apache-2.0"
] | permissive | package io.crnk.core.module.internal;
import io.crnk.core.engine.information.InformationBuilder;
import io.crnk.core.engine.information.repository.RepositoryInformationProviderContext;
import io.crnk.core.engine.information.resource.ResourceInformationProvider;
import io.crnk.core.engine.parser.TypeParser;
import io.crnk.core.module.ModuleRegistry;
public class DefaultRepositoryInformationProviderContext implements RepositoryInformationProviderContext {
private ModuleRegistry moduleRegistry;
public DefaultRepositoryInformationProviderContext(ModuleRegistry moduleRegistry) {
this.moduleRegistry = moduleRegistry;
}
@Override
public ResourceInformationProvider getResourceInformationBuilder() {
return moduleRegistry.getResourceInformationBuilder();
}
@Override
public TypeParser getTypeParser() {
return moduleRegistry.getTypeParser();
}
@Override
public InformationBuilder builder() {
return moduleRegistry.getInformationBuilder();
}
}
| true |
c13727b91ef3f700ee55163345881d0dadc54d11 | Java | BinSlashBash/xcrumby | /src-v2/org/apache/commons/codec/language/bm/Languages.java | UTF-8 | 6,417 | 2.375 | 2 | [] | no_license | /*
* Decompiled with CFR 0_110.
*/
package org.apache.commons.codec.language.bm;
import java.io.InputStream;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.Set;
import org.apache.commons.codec.language.bm.NameType;
public class Languages {
public static final String ANY = "any";
public static final LanguageSet ANY_LANGUAGE;
private static final Map<NameType, Languages> LANGUAGES;
public static final LanguageSet NO_LANGUAGES;
private final Set<String> languages;
static {
LANGUAGES = new EnumMap<NameType, Languages>(NameType.class);
for (NameType nameType : NameType.values()) {
LANGUAGES.put(nameType, Languages.getInstance(Languages.langResourceName(nameType)));
}
NO_LANGUAGES = new LanguageSet(){
@Override
public boolean contains(String string2) {
return false;
}
@Override
public String getAny() {
throw new NoSuchElementException("Can't fetch any language from the empty language set.");
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public LanguageSet restrictTo(LanguageSet languageSet) {
return this;
}
public String toString() {
return "NO_LANGUAGES";
}
};
ANY_LANGUAGE = new LanguageSet(){
@Override
public boolean contains(String string2) {
return true;
}
@Override
public String getAny() {
throw new NoSuchElementException("Can't fetch any language from the any language set.");
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public LanguageSet restrictTo(LanguageSet languageSet) {
return languageSet;
}
public String toString() {
return "ANY_LANGUAGE";
}
};
}
private Languages(Set<String> set) {
this.languages = set;
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public static Languages getInstance(String object) {
HashSet<Object> hashSet = new HashSet<Object>();
Object object2 = Languages.class.getClassLoader().getResourceAsStream((String)object);
if (object2 == null) {
throw new IllegalArgumentException("Unable to resolve required resource: " + (String)object);
}
object = new Scanner((InputStream)object2, "UTF-8");
boolean bl2 = false;
try {
while (object.hasNextLine()) {
object2 = object.nextLine().trim();
if (bl2) {
if (!object2.endsWith("*/")) continue;
bl2 = false;
continue;
}
if (object2.startsWith("/*")) {
bl2 = true;
continue;
}
if (object2.length() <= 0) continue;
hashSet.add(object2);
}
return new Languages(Collections.unmodifiableSet(hashSet));
}
finally {
object.close();
}
}
public static Languages getInstance(NameType nameType) {
return LANGUAGES.get((Object)nameType);
}
private static String langResourceName(NameType nameType) {
return String.format("org/apache/commons/codec/language/bm/%s_languages.txt", nameType.getName());
}
public Set<String> getLanguages() {
return this.languages;
}
public static abstract class LanguageSet {
public static LanguageSet from(Set<String> set) {
if (set.isEmpty()) {
return Languages.NO_LANGUAGES;
}
return new SomeLanguages(set);
}
public abstract boolean contains(String var1);
public abstract String getAny();
public abstract boolean isEmpty();
public abstract boolean isSingleton();
public abstract LanguageSet restrictTo(LanguageSet var1);
}
public static final class SomeLanguages
extends LanguageSet {
private final Set<String> languages;
private SomeLanguages(Set<String> set) {
this.languages = Collections.unmodifiableSet(set);
}
@Override
public boolean contains(String string2) {
return this.languages.contains(string2);
}
@Override
public String getAny() {
return this.languages.iterator().next();
}
public Set<String> getLanguages() {
return this.languages;
}
@Override
public boolean isEmpty() {
return this.languages.isEmpty();
}
@Override
public boolean isSingleton() {
if (this.languages.size() == 1) {
return true;
}
return false;
}
@Override
public LanguageSet restrictTo(LanguageSet languageSet) {
if (languageSet == Languages.NO_LANGUAGES) {
return languageSet;
}
if (languageSet == Languages.ANY_LANGUAGE) {
return this;
}
languageSet = (SomeLanguages)languageSet;
HashSet<String> hashSet = new HashSet<String>(Math.min(this.languages.size(), languageSet.languages.size()));
for (String string2 : this.languages) {
if (!languageSet.languages.contains(string2)) continue;
hashSet.add(string2);
}
return SomeLanguages.from(hashSet);
}
public String toString() {
return "Languages(" + this.languages.toString() + ")";
}
}
}
| true |
ad7618cdc56ee4b8e04917aa457c84a01f770069 | Java | switchYello/wxutil | /src/main/java/com/github/wxutil/XmlUtils.java | UTF-8 | 2,024 | 2.5625 | 3 | [] | no_license | package com.github.wxutil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class XmlUtils {
private static DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
private XmlUtils() {
}
/*beanUtils 自定义类型转换*/
static {
df.setValidating(false);
df.setIgnoringElementContentWhitespace(true);
}
public static Map<String, String> parseWxMessageXml(String xml) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilder documentBuilder = df.newDocumentBuilder();
Document parse = documentBuilder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
Element xmlElement = parse.getDocumentElement();
NodeList childNodes = xmlElement.getChildNodes();
int length = childNodes.getLength();
Map<String, String> map = new HashMap<>();
for (int i = 0; i < length; i++) {
Node item = childNodes.item(i);
if (item.getNodeType() == Node.ELEMENT_NODE) {
map.put(lowCase(item.getNodeName()), item.getFirstChild().getNodeValue());
}
}
return map;
}
private static String lowCase(String src) {
return lowCase(src, 1);
}
private static String lowCase(String src, int count) {
if (src == null) {
return null;
}
if (count == 0) {
return src;
}
if (src.length() <= count) {
return src.toLowerCase();
}
return src.substring(0, count).toLowerCase().concat(src.substring(count));
}
}
| true |
bb87525f72a24b58c92a4e35da5cc1c208d11d06 | Java | dark-matter-org/dark-matter-mvw | /src/org/dmd/dmp/server/servlet/base/EventBusIF.java | UTF-8 | 2,303 | 2.015625 | 2 | [] | no_license | // ---------------------------------------------------------------------------
// dark-matter-data
// Copyright (c) 2012 dark-matter-data committers
// ---------------------------------------------------------------------------
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
// more details.
// You should have received a copy of the GNU Lesser General Public License along
// with this program; if not, see <http://www.gnu.org/licenses/lgpl.html>.
// ---------------------------------------------------------------------------
package org.dmd.dmp.server.servlet.base;
import org.dmd.dmc.DmcNamedObjectIF;
import org.dmd.dmc.DmcObject;
import org.dmd.dmp.server.extended.SetRequest;
/**
* The EventManagerIF interface defines an entity that acts as an event bus
* within the web server.
*/
public interface EventBusIF {
/**
* Fires an event that indicates that an object has been created. This
* is only valid for named objects.
* @param object the object that was created.
*/
public void fireCreateEvent(DmcNamedObjectIF object);
/**
* Fires an event that indicates that the specified object has been deleted.
* @param object the object that was deleted.
*/
public void fireDeleteEvent(DmcNamedObjectIF object);
/**
* Fires an event that indicates that an object has been modified by the
* specified SetRequest.
* @param request The request that modified the object.
*/
public void fireModifiedEvent(SetRequest request);
/**
* Fires an event that indicates that an object has been modified, usually by
* some mechanism within the server itself. The specified object MUST have
* a modifier associated with it e.g. the object is a modification recorder.
* @param object The modified object.
*/
public void fireModifiedEvent(DmcObject object);
}
| true |
d7ed578d3d3487c303fb79284a1c0bed9f7f7028 | Java | datasphere-oss/datasphere-integration | /Platform-4.0/src/com/datasphere/hdstore/base/HDStoreBase.java | UTF-8 | 917 | 2.546875 | 3 | [] | no_license | package com.datasphere.hdstore.base;
import java.util.*;
import com.datasphere.hdstore.*;
public abstract class HDStoreBase<T extends HDStoreManagerBase> implements HDStore
{
private final HDStoreManager manager;
private final String name;
private final Map<String, Object> properties;
protected HDStoreBase(final HDStoreManager manager, final String name, final Map<String, Object> properties) {
this.properties = new HashMap<String, Object>();
this.manager = manager;
this.name = name;
if (properties != null) {
this.properties.putAll(properties);
}
}
@Override
public HDStoreManager getManager() {
return this.manager;
}
@Override
public String getName() {
return this.name;
}
@Override
public Map<String, Object> getProperties() {
return this.properties;
}
}
| true |
e785b9610c96cc45392e6b232a5c636a9fc58ff7 | Java | ShwethaThammaiah/openmrs-module-muzimaforms-1 | /omod/src/main/java/org/openmrs/module/muzimaforms/resource/MuzimaFormResource.java | UTF-8 | 5,871 | 1.914063 | 2 | [] | no_license | package org.openmrs.module.muzimaforms.resource;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.annotation.Handler;
import org.openmrs.api.context.Context;
import org.openmrs.module.muzimaforms.MuzimaConstants;
import org.openmrs.module.muzimaforms.MuzimaForm;
import org.openmrs.module.muzimaforms.api.MuzimaFormService;
import org.openmrs.module.webservices.rest.web.RequestContext;
import org.openmrs.module.webservices.rest.web.RestConstants;
import org.openmrs.module.webservices.rest.web.annotation.Resource;
import org.openmrs.module.webservices.rest.web.representation.CustomRepresentation;
import org.openmrs.module.webservices.rest.web.representation.DefaultRepresentation;
import org.openmrs.module.webservices.rest.web.representation.RefRepresentation;
import org.openmrs.module.webservices.rest.web.representation.Representation;
import org.openmrs.module.webservices.rest.web.resource.api.PageableResult;
import org.openmrs.module.webservices.rest.web.resource.impl.DataDelegatingCrudResource;
import org.openmrs.module.webservices.rest.web.resource.impl.DelegatingResourceDescription;
import org.openmrs.module.webservices.rest.web.resource.impl.MetadataDelegatingCrudResource;
import org.openmrs.module.webservices.rest.web.resource.impl.NeedsPaging;
import org.openmrs.module.webservices.rest.web.response.ResourceDoesNotSupportOperationException;
import org.openmrs.module.webservices.rest.web.response.ResponseException;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Resource(name = RestConstants.VERSION_1 + "/" + MuzimaConstants.MODULE_ID + "/form",
supportedClass = MuzimaForm.class, supportedOpenmrsVersions = {"1.8.*", "1.9.*"})
@Handler(supports = MuzimaForm.class)
public class MuzimaFormResource extends MetadataDelegatingCrudResource<MuzimaForm> {
private static final Log log = LogFactory.getLog(MuzimaFormResource.class);
@Override
protected NeedsPaging<MuzimaForm> doGetAll(RequestContext context) throws ResponseException {
MuzimaFormService service = Context.getService(MuzimaFormService.class);
List<MuzimaForm> all = service.getAll();
return new NeedsPaging<MuzimaForm>(all, context);
}
private Date parseDate(final String iso8601String) {
if (!StringUtils.isNotBlank(iso8601String)) {
return null;
}
Date date = null;
try {
// String s = iso8601String.replace("Z", "+00:00");
// s = s.substring(0, 22) + s.substring(23);
// date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(s);
String s = iso8601String.substring(0, 10);
date = new SimpleDateFormat("yyyy-MM-dd").parse(s);
} catch (ParseException e) {
log.error("Unable to parse date information.");
}
return date;
}
@Override
protected PageableResult doSearch(final RequestContext context) {
HttpServletRequest request = context.getRequest();
String nameParameter = request.getParameter("q");
String syncDateParameter = request.getParameter("syncDate");
List<MuzimaForm> muzimaForms = new ArrayList<MuzimaForm>();
if (nameParameter != null) {
Date syncDate = parseDate(syncDateParameter);
muzimaForms = Context.getService(MuzimaFormService.class).findByName(nameParameter, syncDate);
}
return new NeedsPaging<MuzimaForm>(muzimaForms, context);
}
@Override
public MuzimaForm getByUniqueId(String uuid) {
MuzimaFormService service = Context.getService(MuzimaFormService.class);
return service.findByUniqueId(uuid);
}
@Override
public Object retrieve(String uuid, RequestContext context) throws ResponseException {
MuzimaFormService service = Context.getService(MuzimaFormService.class);
return asRepresentation(service.findByUniqueId(uuid), context.getRepresentation());
}
@Override
public void delete(MuzimaForm muzimaForm, String s, RequestContext requestContext) throws ResponseException {
throw new ResourceDoesNotSupportOperationException();
}
public MuzimaForm newDelegate() {
return new MuzimaForm();
}
public MuzimaForm save(MuzimaForm muzimaForm) {
MuzimaFormService service = Context.getService(MuzimaFormService.class);
try {
return service.save(muzimaForm);
} catch (Exception e) {
log.error(e);
}
return muzimaForm;
}
@Override
public void purge(MuzimaForm muzimaForm, RequestContext requestContext) throws ResponseException {
throw new ResourceDoesNotSupportOperationException();
}
public DelegatingResourceDescription getRepresentationDescription(Representation rep) {
DelegatingResourceDescription description = null;
if (rep instanceof DefaultRepresentation || rep instanceof RefRepresentation) {
description = new DelegatingResourceDescription();
description.addProperty("uuid");
description.addProperty("id");
description.addProperty("name");
description.addProperty("discriminator");
description.addProperty("description");
description.addProperty("model");
description.addProperty("html");
description.addProperty("modelJson");
description.addProperty("form");
description.addProperty("tags", new CustomRepresentation("(id,uuid,name)"));
description.addProperty("version");
description.addSelfLink();
}
return description;
}
}
| true |
420ad056b13a8590766e4c3597bf3013a11319c7 | Java | Flowy/space-find | /src/test/java/com/flowyk/spacefind/entity/SquareIteratorTest.java | UTF-8 | 822 | 2.90625 | 3 | [] | no_license | package com.flowyk.spacefind.entity;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class SquareIteratorTest {
@Test
public void oneRow() {
Room.SquareIterator iterator = new Room.SquareIterator(1, 4);
List<Position> result = new ArrayList<>();
while (iterator.hasNext()) {
result.add(iterator.next());
}
Assert.assertEquals("Number of positions", 4, result.size());
}
@Test
public void twoRows() {
Room.SquareIterator iterator = new Room.SquareIterator(2, 4);
List<Position> result = new ArrayList<>();
while (iterator.hasNext()) {
result.add(iterator.next());
}
Assert.assertEquals("Number of positions", 8, result.size());
}
}
| true |
5c71a28ca1bc71437b114652ea8c7ed1b0e36022 | Java | mobecco/java-blog-tutorials | /runnable-war/src/main/java/HelloServlet.java | UTF-8 | 680 | 2.34375 | 2 | [] | no_license | import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: Ulises Fasoli
* Date: 13.11.13
* Time: 14:03
*/
@WebServlet(name = "HelloServlet", urlPatterns = {"/"})
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
try {
httpServletResponse.getWriter().write("Hello from runnable war file");
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
eb2a9a046ef6fd09af74fd2d1a615ee373176dbe | Java | GuilhermeJWT/orange-talents-04-template-ecommerce | /src/main/java/br/com/zupacademy/guilhermesantos/mercadolivre/dto/ModelPagSeguroDTO.java | UTF-8 | 1,167 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package br.com.zupacademy.guilhermesantos.mercadolivre.dto;
import javax.validation.constraints.NotNull;
import br.com.zupacademy.guilhermesantos.mercadolivre.enums.StatusResponsePagSeguro;
import br.com.zupacademy.guilhermesantos.mercadolivre.model.ModelCompra;
import br.com.zupacademy.guilhermesantos.mercadolivre.model.ModelTransacao;
import br.com.zupacademy.guilhermesantos.mercadolivre.util.ModelRetornoGatewayPagamento;
public class ModelPagSeguroDTO implements ModelRetornoGatewayPagamento{
@NotNull(message = "O ID da Transação deve ser Informado!")
private String idTransacao;
@NotNull(message = "O Status deve ser Informado!")
private StatusResponsePagSeguro statusPagSeguro;
public ModelPagSeguroDTO(String idTransacao, StatusResponsePagSeguro statusPagSeguro) {
this.idTransacao = idTransacao;
this.statusPagSeguro = statusPagSeguro;
}
public String getIdTransacao() {
return idTransacao;
}
public StatusResponsePagSeguro getStatusPagSeguro() {
return statusPagSeguro;
}
public ModelTransacao toTransacao(ModelCompra modelCompra) {
return new ModelTransacao(statusPagSeguro.normaliza(), idTransacao, modelCompra);
}
}
| true |
4cc53429f24a5e0a29723c14f98edd9f222371f8 | Java | Wobum/JZOffer | /src/Chapter02/Algorithm08.java | UTF-8 | 1,574 | 3.453125 | 3 | [] | no_license | package Chapter02;
public class Algorithm08 {
/**
* @Auther: Wobum
* @Date: 2018/12/3 20:18
* @Description: 二叉树的下一个节点
*/
public static class Node{
public int value;
public Node left;
public Node right;
public Node father;
public Node(int value){
this.value = value;
}
}
public static Node findNextNode(Node node){
if (node == null){
return null;
}
Node cur = node;
if (cur.right != null){
cur = cur.right;
while (cur.left != null){
cur = cur.left;
}
return cur;
}else {
while (cur.father != null && cur.father.right == cur){ //
cur = cur.father;
}
return cur.father;
}
}
// for test
public static void main(String[] args) {
Node head = new Node(1);
head.father = null;
head.left = new Node(2);
head.left.father = head;
head.right = new Node(3);
head.right.father = head;
head.left.left = new Node(4);
head.left.left.father = head.left;
head.left.right = new Node(5);
head.left.right.father = head.left;
head.right.left = new Node(6);
head.right.left.father = head.right;
head.right.right = new Node(7);
head.right.right.father = head.right;
System.out.println(findNextNode(head.right.right));
}
}
| true |
9cc904cdb2e91f539ba211ac2fe8243495c98be2 | Java | dstack-group/Butterfly | /butterfly/sonarqube-producer/src/main/java/it/unipd/dstack/butterfly/producer/sonarqube/App.java | UTF-8 | 688 | 2.015625 | 2 | [
"MIT"
] | permissive | /**
* @project: Butterfly
* @author: DStack Group
* @module: sonarqube-producer
* @fileName: App.java
* @created: 2019-03-07
*
* --------------------------------------------------------------------------------------------
* Copyright (c) 2019 DStack Group.
* Licensed under the MIT License. See License.txt in the project root for license information.
* --------------------------------------------------------------------------------------------
*
* @description:
*/
package it.unipd.dstack.butterfly.producer.sonarqube;
/**
* Hello world!
*/
public class App {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
| true |
c0f5400674298db6b9d584dcaff561be0617ddc0 | Java | CodingPractise/HouseBooking | /src/com/psg/guesthousebooking/model/Guest.java | UTF-8 | 808 | 2.703125 | 3 | [] | no_license | package com.psg.guesthousebooking.model;
/**
* Used to represent the guests of the guest house
* @author Rajasri
*
*/
public class Guest {
private String address;
private String firstName;
private int guestId;
private String lastName;
private long mobileNo;
public Guest(String firstName, String lastName, String addressDetails, long mobileNo) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.address = addressDetails;
this.mobileNo = mobileNo;
}
public String getAddress() {
return address;
}
public String getFirstName() {
return firstName;
}
public int getGuestId() {
return guestId;
}
public String getLastName() {
return lastName;
}
public long getMobileNo() {
return mobileNo;
}
}
| true |
53d2f402272b6ac59af4e38e39b5a8b365cfd2bd | Java | ontopia/ontopia | /ontopia-navigator/src/main/java/net/ontopia/topicmaps/nav/utils/comparators/ContextNameGrabber.java | UTF-8 | 4,260 | 2.4375 | 2 | [
"Apache-2.0"
] | permissive | /*
* #!
* Ontopia Navigator
* #-
* Copyright (C) 2001 - 2013 The Ontopia Project
* #-
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* !#
*/
package net.ontopia.topicmaps.nav.utils.comparators;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.function.Function;
import java.util.function.Predicate;
import net.ontopia.utils.CollectionUtils;
import net.ontopia.topicmaps.core.NameIF;
import net.ontopia.topicmaps.core.TopicIF;
import net.ontopia.topicmaps.core.TopicNameIF;
import net.ontopia.topicmaps.core.VariantNameIF;
import net.ontopia.topicmaps.utils.ScopedIFComparator;
import net.ontopia.topicmaps.utils.IntersectionOfContextDecider;
/**
* INTERNAL: Grabber that grabs the most appropriate basename from a
* topic and then the most appropriate variant name, if one can be
* found. If no better variant name can be found, the base name is
* used. This class is much used for grabbing display and sort names.
*/
public class ContextNameGrabber implements Function<TopicIF, NameIF> {
protected Predicate<VariantNameIF> within;
protected Comparator<TopicNameIF> bnComparator;
protected Comparator<VariantNameIF> vnComparator;
/**
* INTERNAL: Creates a grabber; makes the comparators ScopedIFComparator
* for the given scopes.
*
* @param baseNameContext basename scope;
* a collection of TopicIF objects.
* @param variantNameContext variantname scope;
* a collection of TopicIF objects.
*/
public ContextNameGrabber(Collection<TopicIF> baseNameContext,
Collection<TopicIF> variantNameContext) {
this.within = new IntersectionOfContextDecider<VariantNameIF>(variantNameContext);
this.bnComparator = new ScopedIFComparator<TopicNameIF>(baseNameContext);
this.vnComparator = new ScopedIFComparator<VariantNameIF>(variantNameContext);
}
/**
* INTERNAL: Grabs the most appropriate base name for the given topic,
* using the comparator established at creation to compare available
* base names and if a sort variant is available it will be used.
*
* @param topic A topic; formally an Object, but must implement TopicIF.
* @return object of class TopicNameIF or VariantNameIF
* @exception throws OntopiaRuntimeException if the given topic is
* not a TopicIF object.
*/
@Override
public NameIF apply(TopicIF mytopic) {
// --- pick out best basename
Collection<TopicNameIF> basenames = mytopic.getTopicNames();
int basenames_size = basenames.size();
if (basenames_size == 0) {
return null;
}
TopicNameIF bestTopicName;
if (basenames_size == 1) {
// Pull out the only basename
bestTopicName = CollectionUtils.getFirstElement(basenames);
} else {
// Sort list of basenames
TopicNameIF[] mybasenames = basenames.toArray(new TopicNameIF[basenames.size()]);
Arrays.sort(mybasenames, bnComparator);
// Pull out the first basename
bestTopicName = mybasenames[0];
}
// --- pick out best variant name
Collection<VariantNameIF> variantnames = bestTopicName.getVariants();
int variantnames_size = variantnames.size();
// If there is no variant name return bestTopicName
if (variantnames_size == 0) {
return bestTopicName;
}
// If there is multiple basenames rank them.
VariantNameIF[] myvariantnames = variantnames.toArray(new VariantNameIF[variantnames.size()]);
if (variantnames_size > 1) {
Arrays.sort(myvariantnames, vnComparator);
}
// Test that first variant is within scope
if (within.test(myvariantnames[0])) {
return myvariantnames[0];
} else {
return bestTopicName;
}
}
}
| true |
0864b79e77e8142a6d06513ceefef4aff76075b5 | Java | jailcomfranssa/academico-JSF | /src/main/java/br/edu/ifpb/fcgp/academico/bean/CadastroCoodernadorBean.java | UTF-8 | 1,745 | 2.3125 | 2 | [] | no_license | package br.edu.ifpb.fcgp.academico.bean;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import br.edu.ifpb.fcgp.academico.controller.CoodernadorController;
import br.edu.ifpb.fcgp.academico.controller.UsuarioController;
import br.edu.ifpb.fcgp.academico.model.Coodernador;
import br.edu.ifpb.fcgp.academico.model.Usuario;
@Named(value = "cadCoodBean")
@ViewScoped
public class CadastroCoodernadorBean extends GenericAcademicoBean implements Serializable{
private static final long serialVersionUID = 1L;
@Inject
private Coodernador coodernador;
@Inject
private CoodernadorController codController;
@Inject
private UsuarioController userController;
@PostConstruct
public void init() {
Coodernador codFlash = (Coodernador) this.getFlash("coodernador");
if (codFlash != null) {
this.coodernador = codFlash;
}
}
public String cadastrar() {
// Usa o dao para inserir o aluno
Integer id = coodernador.getId();
codController.saveOrUpdate(coodernador);
this.keepMessages();
if (id == null) {
this.addInfoMessage("Coodernador cadatrado com sucesso!");
} else {
this.addInfoMessage("Coodernador atualizado com sucesso!");
}
// Limpa objeto do formulário
coodernador = new Coodernador();
// Retorna para mesma página
return "consulta?faces-redirect=true";
}
public List<Usuario> getUsuarioItems() {
List<Usuario> user = userController.findProf();
return user;
}
public Coodernador getCoodernador() {
return coodernador;
}
public void setCoodernador(Coodernador coodernador) {
this.coodernador = coodernador;
}
}
| true |
24f282a4f80ec11beac28e528eeb0dd4823e1c28 | Java | lenmoyouziJiangjun/JavaLearn | /DataStructuresAndAlgorithms/src/algorithms/leetcode/LeetCode40.java | UTF-8 | 3,324 | 3.484375 | 3 | [] | no_license | package algorithms.leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static algorithms.leetcode.LeetCodeTest.printList;
/**
* Version 1.0
* Created by lll on 2020-02-10.
* Description
*
* <pre>
*
* 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
*
*
* candidates 中的数字只能被选取一次。
*
* 说明:
*
* 所有数字(包括 target)都是正整数。
* 解集不能包含重复的组合。
* </pre>
* <p>
* copyright generalray4239@gmail.com
*/
public class LeetCode40 {
List<List<Integer>> result = new ArrayList<>();
int[] candidates;
int target;
/**
* <pre>
* 解题思路: 动态规划钱币找零的变形
*
* 1、暴力解法
* 2、回溯算法
* 3、递归
*
* </pre>
*
* @param nums
* @param target
* @return
*/
public List<List<Integer>> combinationSum(int[] nums, int target) {
if (nums == null || nums.length == 0 || target <= 0) {
throw new RuntimeException("the candidates must is not empty or target can not equals 0");
}
candidates = nums;
getNum2(target, 0, new ArrayList());
return result;
}
/**
* 暴力回溯解法: 出现重复数据
* 回溯算法的优化: 剪枝,去掉重复的
*
* @param totalReward 剩下的数量
* @param resultList
*/
private void get(int totalReward, ArrayList<Integer> resultList) {
if (totalReward == 0) { //如果剩下的数量为0,表示已经找到一组了
printList(resultList);
result.add(resultList);
return;
} else if (totalReward < 0) {
return;
} else {
for (int i = 0, len = candidates.length; i < len; i++) {
ArrayList<Integer> newResult = (ArrayList<Integer>) resultList.clone();
newResult.add(candidates[i]);
get(totalReward - candidates[i], newResult);
}
}
}
/**
* @param totalReward 剩余结果
* @param start 迭代开始位置,这样解决了重复计算
* @param resultList 临时数组
*/
private void getNum2(int totalReward, int start, ArrayList<Integer> resultList) {
if (totalReward == 0) { //如果剩下的数量为0,表示已经找到一组了
printList(resultList);
result.add(resultList);
return;
} else if (totalReward < 0) {
return;
} else {
//@todo 一个数字只能出现一次
for (int i = start, len = candidates.length; i < len && totalReward - candidates[i] >= 0; i++) {
ArrayList<Integer> newResult = (ArrayList<Integer>) resultList.clone();
newResult.add(candidates[i]);
getNum2(totalReward - candidates[i], i, newResult);
}
}
}
public void test() {
// int[] nums = new int[]{2, 3, 5}; //8
int[] nums = new int[]{10,1,2,7,6,1,5}; //8
// int[] nums = new int[]{2, 3, 6, 7}; //target 7
Arrays.sort(nums);
combinationSum(nums, 8);
}
}
| true |
36fd2aaa703218989f4a94973c7d2b88fee7fcfd | Java | xiaoma800820/MediaAndAdvert | /src/main/java/com/xiaoma/dao/SysAccountSettleRecordMapper.java | UTF-8 | 1,313 | 1.8125 | 2 | [] | no_license | package com.xiaoma.dao;
import com.xiaoma.bean.bo.SysAccountSettleRecordExample;
import com.xiaoma.bean.po.SysAccountSettleRecord;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import com.xiaoma.bean.vo.AdvertiserSettleVO;
import org.apache.ibatis.annotations.Param;
public interface SysAccountSettleRecordMapper {
int insertSettleList(List<SysAccountSettleRecord> records);
int countByExample(SysAccountSettleRecordExample example);
int insert(SysAccountSettleRecord record);
int insertSelective(SysAccountSettleRecord record);
List<SysAccountSettleRecord> selectByExample(SysAccountSettleRecordExample example);
SysAccountSettleRecord selectByPrimaryKey(Long accountSettleId);
int updateByExampleSelective(@Param("record") SysAccountSettleRecord record, @Param("example") SysAccountSettleRecordExample example);
int updateByExample(@Param("record") SysAccountSettleRecord record, @Param("example") SysAccountSettleRecordExample example);
int updateByPrimaryKeySelective(SysAccountSettleRecord record);
int updateByPrimaryKey(SysAccountSettleRecord record);
BigDecimal countTotalEarngings(String userId);
BigDecimal countCurrentEarnings(String userId);
List<AdvertiserSettleVO> selectAdvertiserList(Map paramMap);
} | true |
de28f313a26149940dc698a3de453343831862de | Java | Magueye717/GestionCommande | /src/main/java/com/GestionCommande/Service/CategorieRestController.java | UTF-8 | 1,243 | 2.171875 | 2 | [] | no_license | package com.GestionCommande.Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.GestionCommande.entities.Categorie;
import com.GestionCommande.metier.IcategorieMetier;
@RestController
@CrossOrigin
public class CategorieRestController {
@Autowired
private IcategorieMetier icategorieMetier;
@RequestMapping(value="/categories/{idCategorie}", method = RequestMethod.GET)
public Categorie getCategorie(@PathVariable Long idCategorie) {
return icategorieMetier.getCategorie(idCategorie);
}
@RequestMapping(value="/categories", method = RequestMethod.POST)
public void saveCategorie(@RequestBody Categorie c) {
icategorieMetier.saveCategorie(c);
}
@RequestMapping(value="/categories", method = RequestMethod.GET)
public List<Categorie> listCategorie() {
return icategorieMetier.listCategorie();
}
}
| true |
0f220edff71f1be3bca66061ec22f636587fe10f | Java | weiyu0424/ThinkInJava | /src/com/weiyu/thinkinginjava/huawei/Main.java | UTF-8 | 3,114 | 3.0625 | 3 | [] | no_license | package com.weiyu.thinkinginjava.huawei;
import java.util.Scanner;
public class Main {
private static int[] distance = null;
private static int[] pre = null;
public static void minPath(int[][] array, int nodes, int sourcenode){
boolean[] visit = new boolean[nodes];
for(int i = 0;i < nodes;i++){
distance[i] = array[sourcenode][i];
if(array[sourcenode][i] == 1000)
pre[i] = 0;
else
pre[i] = sourcenode;
}
visit[sourcenode] = true;
int u = sourcenode;
for(int i = 0;i < nodes - 1;i++){
int min = 1000;
for(int j = 0;j < nodes;j++){
if(!visit[j] && distance[j] < min){
min = distance[j];
u = j;
}
}
visit[u] = true;
for(int k = 0;k < nodes;k++){
if(!visit[k] && array[u][k] < 1000){
int temp = distance[u] + array[u][k];
if(temp < distance[k]){
distance[k] = temp;
pre[k] = u;
}
}
}
}
}
public static void visitPath(int[] pre, int node, int source){
int[] path = new int[pre.length];
int count = 0;
path[count++] = node;
int temp = pre[node];
while(temp != source){
path[count++] = temp;
temp = pre[temp];
}
path[count] = source;
System.out.print("[");
for(int i = count;i >= 0;i--){
if(i != 0) {
System.out.print((path[i] + 1) + ", ");
}else{
System.out.print((path[i] + 1));
}
}
System.out.println("]");
}
public static void main(String... args){
Scanner in = new Scanner(System.in);
int nodes = 6;
distance = new int[nodes];
pre = new int[nodes];
int[][] graphs = {
{0,2,10,5,3,1000},
{1000,0,12,1000,1000,10},
{1000,1000,0,1000,7,1000},
{2,1000,1000,0,2,1000},
{4,1000,1000,1,0,1000},
{3,1000,1,1000,2,0}
};
int source = 4;
int x = in.nextInt();
int y = in.nextInt();
if(x < 1 || x > 6){
return;
}
if(y < 0 || x > 6) {
return;
}
if(x == y){
System.out.println(1000);
System.out.println("[]");
return;
}
if(5 == y){
System.out.println(1000);
System.out.println("[]");
return;
}
x -= 1;
if(0 != y){
y -= 1;
for(int i = 0;i < 6;i++){
graphs[y][i] = 1000;
}
}
minPath(graphs,nodes,source);
if(distance[x] == 1000){
System.out.println(1000);
}else{
System.out.println(distance[x]);
}
visitPath(pre,x,source);
}
}
| true |
b321bbe8ef4193bcce6e4a08adfa8d212267aee7 | Java | lf2035724/aucross-commons | /src/main/java/com/ylink/ylpay/common/project/account/app/AccountOptAppService.java | UTF-8 | 2,060 | 2.171875 | 2 | [] | no_license | /**
* 版权所有(C) 2012 深圳市雁联计算系统有限公司
* 创建: Iquil 2012-10-30
*/
package com.ylink.ylpay.common.project.account.app;
import com.ylink.ylpay.common.project.account.dto.RegAccountReturnDTO;
import com.ylink.ylpay.common.project.account.dto.RegNormalAccountDTO;
import com.ylink.ylpay.common.project.account.dto.RegPayablesAccountDTO;
import com.ylink.ylpay.common.project.account.exception.AccountCheckedException;
/**
* @author Iquil
* @date 2012-10-30
* @description:账户操作服务接口
*/
public interface AccountOptAppService {
/**
* @description 开户接口
* @param custId
* @param subjectNo2(CustSubject.SHOP消费备付金;CustSubject.FUND基金备付金)
* @return RegAccountReturnDTO
* @throws AccountCheckedException
* @author Iquil
* @date 2012-10-30
*/
public RegAccountReturnDTO createCustAccount(String custId, String subjectNo2)
throws AccountCheckedException;
/**
* @description 应付款账户接口
* @param custId
* @param subjectNo2
* @param custType
* @throws AccountCheckedException
* @author ZhangDM(Mingly)
* @date 2012-12-26
*/
public void createCustPayablesAccount(
RegPayablesAccountDTO regPayablesAccountDTO) throws AccountCheckedException;
/**
* @description 冻结账户
* @param accountId
* @throws AccountCheckedException
* @author Iquil
* @date 2012-11-14
*/
public void freezeAccount(String accountId) throws AccountCheckedException;
/**
* @description 激活账户
* @param accountId
* @throws AccountCheckedException
* @author Iquil
* @date 2012-11-14
*/
public void activeAccount(String accountId) throws AccountCheckedException;
/**
* @description 创建普通账户
* @param regNormalAccountDTO
* @author Iquil
* @date 2013-2-21
*/
public void createNormalAccount(RegNormalAccountDTO regNormalAccountDTO);
/**
* @description 通过custId和subjectNo2更新accountName
*/
public void updateAccountName(String custId,String subjectNo2,String accountName);
}
| true |
4a20b76c83c3bf53c6fd6dc12c3c1385ad1593c2 | Java | LuckyBanana/UM2Client | /src/Client.java | ISO-8859-1 | 20,000 | 2.109375 | 2 | [] | no_license | import java.awt.Desktop;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.List;
import twitter4j.DirectMessage;
import twitter4j.HashtagEntity;
import twitter4j.MediaEntity;
import twitter4j.Paging;
import twitter4j.ProfileImage;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.RelatedResults;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.URLEntity;
import twitter4j.User;
import twitter4j.UserList;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
public class Client {
Account currentUser;
Twitter twitter = new TwitterFactory().getInstance();
protected StorageLovedTweets lovedTweets;
protected StorageHomeTimeline homeTimelineTweets;
protected StorageDirectMessages directMessage;
protected StorageFavorites favsTweets;
protected StorageMentions mentionTweet;
protected StorageUserTimeline currentUserTweets;
public Client() {
twitter.setOAuthConsumer("Z2zk13tMZFzNUiDxCs4Bw",
"HYk91Rol6BqiI0D2JdOiukZZYe6Nj9B0uFPFhSzmN7A");
createCacheDIR();
createCredentialsDB();
}
public void createCacheDIR() {
@SuppressWarnings("unused")
boolean file = new File("cache/").mkdir();
}
public void createCredentialsDB() {
try {
File file = new File("cache/storeCredentials.tw");
file.createNewFile();
} catch (IOException e) {
System.out.println("Impossible de crer le fichier");
}
}
public void loadStorageUnits() {
this.homeTimelineTweets = new StorageHomeTimeline(currentUser);
this.lovedTweets = new StorageLovedTweets(currentUser);
this.directMessage = new StorageDirectMessages(currentUser);
this.favsTweets = new StorageFavorites(currentUser);
this.mentionTweet = new StorageMentions(currentUser);
this.currentUserTweets = new StorageUserTimeline(currentUser, currentUser.userName);
}
// Step 1 : Create account
// Step 2 : Link account with pin
// Step 3 : Get authentication from twitter
// Step 4 : Store the new account in storeCredentials.tw
// Step 1 :
@SuppressWarnings("unused")
public Account createAccount(String userName, String password) throws UserAlreadyRegisteredException{
try {
FileInputStream fis;
fis = new FileInputStream(new File("cache/storeCredentials.tw"));
ObjectInputStream ois = new ObjectInputStream(fis);
AccountList credentials = new AccountList();
credentials.addAccount((Account) ois.readObject());
for(int i = 0; i < credentials.getList().size(); i++) {
if(credentials.getList().get(i).getUserName().equalsIgnoreCase(userName)) {
throw new UserAlreadyRegisteredException();
}
else {
Account newUser = new Account(userName, password);
return newUser;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch(EOFException e) {
Account newUser = new Account(userName, password);
return newUser;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return null;
}
// Step 2 :
public RequestToken requestPin() {
// use pin to get credentials
// opening browser to get pin
Desktop desk = null;
try {
RequestToken requestToken = twitter.getOAuthRequestToken();
URI auto = new URI(requestToken.getAuthorizationURL());
if (Desktop.isDesktopSupported()) {
desk = Desktop.getDesktop();
desk.browse(auto);
}
return requestToken;
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("ni");
// if return null - try again
return null;
}
}
// Step 3 & 4 :
public void loginWithPin(Account account, String pin, RequestToken requestToken,
int rememberMe) {
try {
//AccessToken accessToken = null;
// Entrer le pin
try {
if (pin.length() > 0) {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin);
System.out.println(accessToken);
System.out.println(account);
account.setUserAccessToken(accessToken);
account.setUser(twitter.verifyCredentials());
// credentials.ajouterCompte(newUser);
// update the new credentials list by adding the new object
// in the file
FileOutputStream fos = new FileOutputStream("cache/storeCredentials.tw");
ObjectOutputStream oos = new ObjectOutputStream(fos);
// create new user
oos.writeObject(account);
oos.close();
fos.close();
currentUser = account;
this.loadStorageUnits();
if (rememberMe == 1) {
createSession(account);
}
@SuppressWarnings("unused")
MainFrame main = new MainFrame(this);
System.out.println("Connect");
} else {
@SuppressWarnings("unused")
AccessToken accessToken = twitter.getOAuthAccessToken();
}
} catch (TwitterException te) {
if (401 == te.getStatusCode()) {
System.out.println("Unable to get the access token.");
} else {
te.printStackTrace();
}
}
} catch (Exception e) {
// oops sth went wrong
e.printStackTrace();
}
}
// Try to login
// Returns 0 : if username matches password
// Returns 1 : if username doesn't matches password
// Returns 2 : if username isn't in db
// Returns -1 : if storeCredentials.tw doesn't exist
// Returns -2 : if IO error
public int testLogin(String id, String pw) {
try {
FileInputStream fis = new FileInputStream(new File("cache/storeCredentials.tw"));
ObjectInputStream ois = new ObjectInputStream(fis);
AccountList credentials = new AccountList();
credentials.addAccount((Account) ois.readObject());
// User already registered ?
for (int i = 0; i < credentials.getList().size(); i++) {
if (credentials.getList().get(i).getUserName()
.equalsIgnoreCase(id)) {
if (credentials.getList().get(i).getPassword().equals(pw)) {
return 0;
} else {
// Wrong password
return 1;
}
}
}
// User not registered
ois.close();
fis.close();
return 2;
} catch (FileNotFoundException e) {
// storeCredentials.tw doesn't exists
System.out.println("sc.tw doesn't exists");
return -1;
} catch(EOFException e) {
return -1;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -2;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -2;
}
}
public void login(String user, int rememberMe) {
FileInputStream fis;
try {
fis = new FileInputStream(new File("cache/storeCredentials.tw"));
ObjectInputStream ois = new ObjectInputStream(fis);
AccountList credentials = new AccountList();
credentials.addAccount((Account) ois.readObject());
for (int i = 0; i < credentials.getList().size(); i++) {
if (credentials.getList().get(i).getUserName().equalsIgnoreCase(user)) {
AccessToken accessToken = credentials.getList().get(i).getUserAccessToken();
twitter.setOAuthAccessToken(accessToken);
currentUser = credentials.getList().get(i);
this.loadStorageUnits();
// loop exit
if (rememberMe == 1) {
createSession(credentials.getList().get(i));
}
throw new AuthOKException();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthOKException e) {
System.out.println("Connect.");
}
}
/*
* Sending Tweet & Direct Message
*/
public String sendTweet(String t) {
try {
twitter.updateStatus(t);
return("Your tweet has been post !");
} catch (TwitterException e) {
e.printStackTrace();
return("An error occured !");
// oops sth went wrong - try again later ?
}
}
public String sendDirectMessage(String user, String text) {
try {
twitter.sendDirectMessage(user, text);
return("Your direct message has been send");
} catch (TwitterException e) {
e.printStackTrace();
return("An error occured !");
// try again later ?
}
}
/*
* Retweet & Favorite & Reply & Delete Tweet
*/
public void createFavorite(long statusId) {
try {
twitter.createFavorite(statusId);
} catch (TwitterException e) {
e.printStackTrace();
// bad statusId ?
}
}
public void destroyFavorite(long statusId) {
try {
twitter.destroyFavorite(statusId);
} catch (TwitterException e) {
e.printStackTrace();
// bad statusId ?
}
}
public void retweet(long statusId) {
try {
twitter.retweetStatus(statusId);
} catch (TwitterException e) {
e.printStackTrace();
// bad statusId ?
}
}
public String reply(long statusId, long userId, String t) {
try {
twitter.updateStatus(new StatusUpdate("@"+ twitter.showUser(userId).getScreenName() +" "+ t).inReplyToStatusId(statusId));
return("Your reply has been send");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return("An error occured");
}
}
public String reply(Status status, String t) {
try {
twitter.updateStatus(new StatusUpdate(t).inReplyToStatusId(status.getId()));
return("Your reply has been send");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return("An error occured");
}
}
public String showUser(long statusId)
{
try {
return twitter.showUser(statusId).getScreenName();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public long showUserId(long statusId)
{
try{
return twitter.showUser(statusId).getId();
}
catch (TwitterException e) {
e.printStackTrace();
return 0;
}
}
public void deleteTweet(long statusId) {
try {
twitter.destroyStatus(statusId);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* Search by keyword
*/
public StorageList<Tweet> search(String t) {
Query query = new Query(t);
try {
StorageSearch searchTweets = new StorageSearch(currentUser, t);
QueryResult result = twitter.search(query);
searchTweets.statusList.addSearchList(result.getTweets());
return searchTweets.statusList;
} catch (TwitterException e) {
e.printStackTrace();
// oops sth went wrong
return null;
}
}
/*
* Getting Direct Messages
*/
public StorageList<DirectMessage> getDirectMessages() {
try {
StorageDirectMessages sdm = new StorageDirectMessages(currentUser);
ResponseList<DirectMessage> directMessages = twitter.getDirectMessages();
sdm.directMessages.addStatusList(directMessages);
sdm.saveTweets();
return sdm.directMessages;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public StorageList<DirectMessage> getDirectMessages(Paging p) {
try {
StorageDirectMessages sdm = new StorageDirectMessages(currentUser);
ResponseList<DirectMessage> directMessages = twitter.getDirectMessages();
sdm.directMessages.addStatusList(directMessages);
sdm.saveTweets();
return sdm.directMessages;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/*
* Getting Tweets
*/
// Home Timeline
public StorageList<Status> getHomeTimeline() {
try {
StorageHomeTimeline hts = new StorageHomeTimeline(currentUser);
ResponseList<Status> tweets = twitter.getHomeTimeline();
hts.statusList.addStatusList(tweets);
hts.saveTweets();
return hts.statusList;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public StorageList<Status> getHomeTimeline(Paging p) {
try {
StorageHomeTimeline hts = new StorageHomeTimeline(currentUser);
ResponseList<Status> tweets = twitter.getHomeTimeline(p);
hts.statusList.addStatusList(tweets);
hts.saveTweets();
System.out.println(tweets.getRateLimitStatus());
return hts.statusList;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
// Public Timeline twitter.getPublicTimeline()
public ResponseList<Status> getPublicTimeline() {
try {
StoragePublicTimeline pts = new StoragePublicTimeline();
ResponseList<Status> tweets = twitter.getUserTimeline();
pts.statusList.addStatusList(tweets);
return tweets;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
// Logged user Timeline
public ResponseList<Status> getUserTimeline() {
try {
StorageUserTimeline uts = new StorageUserTimeline(currentUser, currentUser.getUserName());
ResponseList<Status> tweets = twitter.getUserTimeline();
uts.statusList.addStatusList(tweets);
return tweets;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public StorageList<Status> getUserTimeline(Paging p) {
try {
StorageUserTimeline uts = new StorageUserTimeline(currentUser, currentUser.getUserName());
ResponseList<Status> tweets = twitter.getUserTimeline(p);
uts.statusList.addStatusList(tweets);
//uts.saveTweets();
return uts.statusList;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
// Retrieve user timeline by userId
public StorageList<Status> getUserTimelineById(long userId) {
try {
StorageUserTimeline uts = new StorageUserTimeline("user" + userId);
ResponseList<Status> tweets = twitter.getUserTimeline(userId);
uts.statusList.addStatusList(tweets);
uts.saveTweets();
return uts.statusList;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public ResponseList<Status> getUserTimelineById(long userId, Paging p) {
try {
StorageUserTimeline uts = new StorageUserTimeline("user" + userId);
ResponseList<Status> tweets = twitter.getUserTimeline(userId, p);
uts.statusList.addStatusList(tweets);
return tweets;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
// get user mentions
public StorageList<Status> getMentionsTimeline() {
try {
StorageMentions ms = new StorageMentions(currentUser);
ResponseList<Status> tweets = twitter.getMentions();
ms.statusList.addStatusList(tweets);
ms.saveTweets();
return ms.statusList;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public StorageList<Status> getMentionsTimeline(Paging p) {
try {
StorageMentions ms = new StorageMentions(currentUser);
ResponseList<Status> tweets = twitter.getMentions(p);
ms.statusList.addStatusList(tweets);
ms.saveTweets();
return ms.statusList;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
// get favorites
public StorageList<Status> getFavorites() {
try {
StorageFavorites sf = new StorageFavorites(currentUser);
ResponseList<Status> tweets = twitter.getFavorites();
sf.statusList.addStatusList(tweets);
sf.saveTweets();
return sf.statusList;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public StorageList<Status> getFavorites(Paging p) {
try {
StorageFavorites sf = new StorageFavorites(currentUser);
ResponseList<Status> tweets = twitter.getFavorites(p);
sf.statusList.addStatusList(tweets);
sf.saveTweets();
return sf.statusList;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
// ???
public StorageList<Status> getInteractionsTimeline() {
return null;
}
public StorageList<UserList> getUserLists() {
try {
StorageUserLists ms = new StorageUserLists(currentUser);
ResponseList<UserList> tweets = twitter.getUserLists(twitter.getId(), -1);
ms.userList.addStatusList(tweets);
ms.saveTweets();
return ms.userList;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public StorageList<Status> getListById() {
return null;
}
// :(
// Home ok, user ok, mentions, trends, search, favorite, DM ok, interaction, list
/*
* Session (remember me button) management
*/
public Account sessionTest() {
FileInputStream fis;
try {
fis = new FileInputStream("cache/session.tw");
ObjectInputStream ois = new ObjectInputStream(fis);
Account sessionUser = (Account) ois.readObject();
ois.close();
fis.close();
return sessionUser;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
public void createSession(Account c) {
FileOutputStream fos;
try {
fos = new FileOutputStream("cache/session.tw");
ObjectOutputStream oos = new ObjectOutputStream(fos);
// create new session
oos.writeObject(c);
oos.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void destroySession() {
File file = new File("cache/session.tw");
file.delete();
}
/*
* Image method
*/
public URL getUserBigAvatar() throws MalformedURLException {
User user;
URL url;
ProfileImage pi;
String url_n;
try {
user = twitter.showUser(twitter.getId());
pi = twitter.getProfileImage(user.getScreenName(), ProfileImage.ORIGINAL);
url_n = pi.getURL();
url_n = new StringBuffer(url_n).insert((url_n.length() - 4), "_reasonably_small").toString();
url = new URL(url_n);
return url;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/*
* Reply Tree
*/
public Node getReply(Status status) {
Node racine = new Node(status);
long statusId = status.getId();
RelatedResults related;
try {
related = twitter.getRelatedResults(statusId);
ResponseList<Status> tweets = null;
tweets = related.getTweetsWithConversation();
for (Status stat : tweets) {
racine.addSon(stat);
}
return racine;
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public Node getReplyTree(Status status, int depth) {
Node racine = getReply(status);
while (depth > 0) {
for (int i = 0; i < racine.getSons().size(); i++) {
getReplyTree(racine.getSons().get(i).getValue(), depth - 1);
}
}
return racine;
}
/*
* Get Entities (URL, Hashtag, Media)
*/
public URLEntity[] getURLEntities(Status status) {
return status.getURLEntities();
}
public HashtagEntity[] getHashtagEntities(Status status) {
return status.getHashtagEntities();
}
public MediaEntity[] getMediaEntities(Status status) {
return status.getMediaEntities();
}
}
| true |
c98afa46eb9f2865c45853319d5dd43a4577481e | Java | siddu427/NEWSRPINGBOOTWORKSPACE | /SpringBoot2ControllerToUiDataExListModels/src/main/java/in/nit/service/EmployeeService.java | UTF-8 | 353 | 2.359375 | 2 | [] | no_license | package in.nit.service;
import java.util.List;
import org.springframework.stereotype.Component;
import in.nit.model.Employee;
@Component
public class EmployeeService {
public List<Employee> getAllEmployees(){
return List.of(
new Employee(10,"A",3.3),
new Employee(11,"B",3.8),
new Employee(12,"C",4.3)
);
}
}
| true |
443a035e2effe6b410dc33ae46c0ec1d0668096a | Java | Gekkio/jawwa | /zk-highcharts/src/main/java/fi/jawsy/jawwa/zk/highcharts/impl/HighchartsImpl.java | UTF-8 | 400 | 1.757813 | 2 | [
"Apache-2.0"
] | permissive | package fi.jawsy.jawwa.zk.highcharts.impl;
import fi.jawsy.jawwa.zk.highcharts.Highcharts;
import fi.jawsy.jawwa.zk.highcharts.PointSeries.Point;
public final class HighchartsImpl {
private HighchartsImpl() {
}
public static Highcharts.Options createOptions() {
return new OptionsImpl();
}
public static Point createPoint() {
return new PointImpl();
}
}
| true |
ec454689ec3f14ffa9a241d7b7963f0fc431d8a7 | Java | parveensuyan/Health-and-Nutrition-Diet | /FlexibilityActivityList.java | UTF-8 | 4,880 | 2.28125 | 2 | [] | no_license | package com.example.parveen.healthconsultantsandnutrition;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class FlexibilityActivityList extends AppCompatActivity {
ListView flexibilitylist;
ArrayList list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flexibility_activity_list);
flexibilitylist = (ListView) findViewById(R.id.flexiblitylist);
list=new ArrayList();
list.add("Dynamic stretching");
list.add("Ballistic stretching");
list.add("Isometric stretching");
list.add("PNF stretching");
list.add("Shoulder & Chest");
// list.add("Arm Across Chest");
list.add("Triceps Stretch");
list.add("Glute Stretch");
list.add("Single Leg Hamstring");
list.add("Standing Quadriceps");
list.add(" Standing Calf");
list.add(" Ankle Bounces");
list.add(" Heel Raise");
list.add(" Smith Machine Pushups");
list.add(" Bench Dip");
list.add(" Die Bomber Pushups");
list.add("Alternative Toe Touch");
list.add("Double Crunch");
list.add("FOREARMS");
ArrayAdapter arrayAdapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1,list);
flexibilitylist.setAdapter(arrayAdapter);
flexibilitylist.setOnItemClickListener( new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position==0)
{
Intent myint=new Intent(FlexibilityActivityList.this,BalanceActivityVideo.class);
myint.putExtra("myvideo", position);
startActivity(myint);
}
if(position==1)
{
Intent myint=new Intent(FlexibilityActivityList.this,BalanceActivityVideo.class);
myint.putExtra("myvideo", position);
startActivity(myint);
}
if(position==2)
{
Intent myint=new Intent(FlexibilityActivityList.this,BalanceActivityVideo.class);
myint.putExtra("myvideo", position);
startActivity(myint);
}
if(position==3)
{
Intent myint=new Intent(FlexibilityActivityList.this,BalanceActivityVideo.class);
myint.putExtra("myvideo", position);
startActivity(myint);
}
if(position==4)
{
Intent myint=new Intent(FlexibilityActivityList.this,BalanceActivityVideo.class);
myint.putExtra("myvideo", position);
startActivity(myint);
}
if(position==5)
{
Intent myint=new Intent(FlexibilityActivityList.this,BalanceActivityVideo.class);
myint.putExtra("myvideo", position);
startActivity(myint);
} if(position==6)
{
Intent myint=new Intent(FlexibilityActivityList.this,BalanceActivityVideo.class);
myint.putExtra("myvideo", position);
startActivity(myint);
}
if(position==7)
{
Intent myint=new Intent(FlexibilityActivityList.this,BalanceActivityVideo.class);
myint.putExtra("myvideo", position);
startActivity(myint);
}
if(position==8)
{
Intent myint=new Intent(FlexibilityActivityList.this,BalanceActivityVideo.class);
myint.putExtra("myvideo", position);
startActivity(myint);
}
}
});
}
void fetch_list2(){
mydbhelper obj1=new mydbhelper(this);
obj1.open();
Cursor myresult;
myresult = obj1.mydb.rawQuery("select * from flexibilityexcercise",null);
while(myresult.moveToNext())
{
list.add(myresult.getString(myresult.getColumnIndex("name4")));
}
obj1.close1();
}
}
| true |
f1290f62b693a25bc591e2e2822153f4b39ff217 | Java | bra1nb3am3r/OneTapVideoDownload | /app/src/main/java/com/phantom/onetapvideodownload/DownloadsFragment.java | UTF-8 | 1,346 | 2.15625 | 2 | [] | no_license | package com.phantom.onetapvideodownload;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class DownloadsFragment extends Fragment {
private RecyclerView mRecyclerView;
private DownloadAdapter mDownloadAdapter;
public DownloadsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_downloads, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.downloadRecyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mDownloadAdapter = new DownloadAdapter(getActivity());
mRecyclerView.setAdapter(mDownloadAdapter);
return rootView;
}
@Override
public void onStop() {
super.onStop();
if (mDownloadAdapter != null) {
mDownloadAdapter.onStop();
}
}
}
| true |
cc3fb0e8b2a08a95e29654a7ace522bbac1adec6 | Java | Outbreak-AFA/outbreak-tactics | /Outbreak/src/com/surtados/outbreak/Models/Personagem.java | UTF-8 | 21,008 | 2.3125 | 2 | [
"MIT"
] | permissive | package com.surtados.outbreak.Models;
import com.surtados.outbreak.Utils.Dados;
import com.surtados.outbreak.components.FieldTile;
import com.surtados.outbreak.components.TeamBox;
import javafx.scene.layout.GridPane;
import java.util.ArrayList;
import static com.surtados.outbreak.Screens.Field.FieldController.getNodeByRowColumnIndex;
public abstract class Personagem {
private int playerId;
public Sprite sprite = new Sprite();
private String nome;
private int vida, mana, atk, def, agl;
private int surtoAcumulado;
private boolean surtado = false;
private int contadorSurto;
public Coordenada coord = new Coordenada();
public ArrayList<Item> inventario = new ArrayList<>();
private Item itemEspecial;
private boolean moveu = false, atacou = false;
private String atkNatural;
private String habilidadeEspecial;
private boolean suporte = false;
public Player dono;
public TeamBox teamBox;
public Personagem(Player p, String path) {
dono = p;
sprite.setPath(path);
}
public TeamBox getTeamBox() {
return teamBox;
}
public void setTeamBox(TeamBox teamBox) {
this.teamBox = teamBox;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getVida() {
return vida;
}
public void setVida(int vida) {
this.vida = vida;
}
public int getMana() {
return mana;
}
public void setMana(int mana) {
this.mana = mana;
}
public int getAtk() {
return atk;
}
public void setAtk(int atk) {
this.atk = atk;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
public int getAgl() {
return agl;
}
public void setAgl(int agl) {
this.agl = agl;
}
public int getSurtoAcumulado() {
return surtoAcumulado;
}
public void setSurtoAcumulado(int surtoAcumulado) {
this.surtoAcumulado = surtoAcumulado;
}
public void acumularSurto(int s) {
setSurtoAcumulado(getSurtoAcumulado() + s);
}
public boolean isSurtado() {
return surtado;
}
public void setSurtado(boolean surtado) {
this.surtado = surtado;
}
public int getContadorSurto() {
return contadorSurto;
}
public void setContadorSurto(int contadorSurto) {
this.contadorSurto = contadorSurto;
}
public int getPlayerId() {
return playerId;
}
public Item getItemEspecial() {
return itemEspecial;
}
public void setItemEspecial(Item itemEspecial) {
this.itemEspecial = itemEspecial;
}
public void setPlayerId(int playerId) {
this.playerId = playerId;
}
public String getAtkNatural() {
return atkNatural;
}
public void setAtkNatural(String atkNatural) {
this.atkNatural = atkNatural;
}
public String getHabilidadeEspecial() {
return habilidadeEspecial;
}
public void setHabilidadeEspecial(String habilidadeEspecial) {
this.habilidadeEspecial = habilidadeEspecial;
}
public boolean isSuporte() {
return suporte;
}
public void setSuporte(boolean suporte) {
this.suporte = suporte;
}
public abstract void atacarNatural(Personagem p);
public abstract void habilidadeEspecial(Personagem p);
public void modoSurto(int atk, int def, int agl) {
if (podeSurtar()) {
System.out.println(getNome() + " ativou o modo surto!");
setAtk(getAtk() + atk); setDef(getDef() + def); setAgl(getAgl() + agl);
setSurtado(true);
setContadorSurto(3);
setSurtoAcumulado(0);
} else System.out.println(getNome() + " não está com o modo surto disponível!\n" + "Faltam: " + (50 - getSurtoAcumulado()));
}
public void passarTurno() {
if(getContadorSurto() > 0) setContadorSurto(getContadorSurto() - 1);
setMoveu(false);
setAtacou(false);
}
public void andar(int x, int y) {
System.out.println(this.getNome() + " andou " + x + " e " + y);
}
public void retirarVida(int dano) {
setVida(getVida() - dano);
}
public int calcularDano(int danoMaximoOferecido, Personagem p) {
int probabilidadeCritico = Dados.random(20);
int probabilidadeDefesa = Dados.random(20);
// calcular o dano máximo possível
int dano = getAtk() * Dados.random(danoMaximoOferecido);
if (probabilidadeCritico >= 19) dano *= getAtk();
// calcular dano com a defesa
if (probabilidadeDefesa >= 19) {
dano -= Math.pow(p.getDef(), 2);
} else if (probabilidadeDefesa >= 10) {
dano -= p.getDef();
} else dano -= (int)(p.getDef() / 2);
if (dano < 0) dano = 0;
return dano;
}
public abstract void ativarModoSurto();
public boolean podeSurtar() {
if (getSurtoAcumulado() >= 20) return true;
return false;
}
public void aumentarSurto(int danoRecebido) {
setSurtoAcumulado(getSurtoAcumulado() + (danoRecebido * Dados.random(4) / 10));
}
public void mostrarStatus() {
System.out.println("========="+ getNome() +"=========");
System.out.println("Vida: " + getVida());
System.out.println("Mana: " + getMana());
System.out.println("ATK: " + getAtk());
System.out.println("DEF: " + getDef());
System.out.println("AGL: " + getAgl());
System.out.println("Surto acumulado: " + getSurtoAcumulado());
System.out.println("=======================================");
}
public void listarItens() {
for (Item i : inventario) {
System.out.println(inventario.indexOf(i) + ": " + i.getTipoDeItem());
}
}
public String usarItem(Item i) {
int valorDados = Dados.random(20) + Dados.random(20) + Dados.random(20);
switch (i.getTipoDeItem()) {
case "MANA":
setMana(getMana() + valorDados);
return getNome() + " recuperou " + valorDados + " de mana!";
case "CURA":
setVida(getVida() + valorDados);
return getNome() + " recuperou " + valorDados + " de vida!";
}
inventario.remove(i);
return "";
}
public boolean morreu() {
if (getVida() > 0) return false;
setVida(0);
return true;
}
public void mover(int linha, int coluna, Mapa mapa, GridPane tabuleiro) {
FieldTile fieldTile = (FieldTile) getNodeByRowColumnIndex(coord.getLinha(), coord.getColuna(), tabuleiro);
fieldTile.substituir(new FieldTile());
coord.setPosicao(linha, coluna);
FieldTile fieldTile2 = (FieldTile) getNodeByRowColumnIndex(linha, coluna, tabuleiro);
fieldTile2.substituir(new FieldTile(this));
// Item temp = null;
// for (Item i : mapa.items) {
// if (i != null && i.coord.equals(coord)) {
// if (i.getTipoDeItem().equals("CURA") || i.getTipoDeItem().equals("MANA")) {
// inventario.add(i);
// } else {
// temp = i;
// Sistema.adicionarConquista(i, dono);
// }
// }
// }
// if (temp != null) {
// mapa.removerItem(temp);
// }
setMoveu(true);
}
public abstract String descricao();
public String equiparItem(Item i) {
setItemEspecial(i);
if (i.getTipoDeItem().equals("ATK")) {
setAtk(getAtk() * 2);
return getNome() + " dobrou o seu ataque com " + i.getNome() + "!";
} else if (i.getTipoDeItem().equals("DEF")) {
setDef(getDef() * 2);
return getNome() + " dobrou o sua defesa com " + i.getNome() + "!";
} else if (i.getTipoDeItem().equals("AGL")) {
setAgl(getAgl() + 2);
return getNome() + " ganhou mais " + 2 + " pontos de agilidade com " + i.getNome() + "!";
}
return "Ocorreu um problema ao identificar o item :(";
}
public void preenchimentoPorInundacao(Mapa mapa, int lin, int col, ArrayList<Coordenada> proibidos, ArrayList<Coordenada> possiveis, boolean identificarPersonagem) {
int colMax = mapa.getColunaMax(), linMax = mapa.getLinhaMax();
if ((lin < 1|| lin >= linMax - 1) || (col < 1 || col >= colMax - 1) || ((!coord.equals(lin, col)) && (!mapa.posicaoVazia(lin, col, proibidos, identificarPersonagem))) || (!verificarPossiveis(possiveis, lin, col))) {
return;
} else {
Coordenada co = new Coordenada();
co.setPosicao(lin, col);
if (!coord.equals(lin, col)) {
possiveis.add(co.clone());
}
preenchimentoPorInundacao(mapa, (lin + 1), (col), proibidos, possiveis, identificarPersonagem);
preenchimentoPorInundacao(mapa, (lin - 1), (col), proibidos, possiveis, identificarPersonagem);
preenchimentoPorInundacao(mapa, (lin), (col + 1), proibidos, possiveis, identificarPersonagem);
preenchimentoPorInundacao(mapa, (lin), (col - 1), proibidos, possiveis, identificarPersonagem);
}
}
private boolean verificarPossiveis(ArrayList<Coordenada> possiveis, int lin, int col) {
for (Coordenada c : possiveis) {
if (c.equals(lin, col)) return false;
}
return true;
}
private ArrayList<Coordenada> getAlcanceProibido() {
ArrayList<Coordenada> proibidos = new ArrayList<>();
Coordenada temp = new Coordenada();
if (getAgl() == 2) {
//Agilidade nivel 2
for (int lin=-2; lin<=2; lin++) {
for (int col=-2; col<=2; col++) {
if (!((col == lin || col == -lin) ||
(col == 0 && (lin == -1 || lin == 1)) ||
(lin == 0 && (col == -1 || col == 1)))) {
temp.setPosicao(coord.getLinha() + lin, coord.getColuna() + col);
proibidos.add(temp.clone());
}
}
}
}
else if (getAgl() == 4) {
for (int lin=-2; lin<=2; lin++) {
for (int col=-2; col<=2; col++) {
if (!((col == lin || col == -lin) || (lin == 0 || col == 0))) {
temp.setPosicao(coord.getLinha() + lin, coord.getColuna() + col);
proibidos.add(temp.clone());
}
}
}
temp.setPosicao(coord.getLinha() - 3, coord.getColuna());
proibidos.add(temp.clone());
temp.setPosicao(coord.getLinha(), coord.getColuna() - 3);
proibidos.add(temp.clone());
temp.setPosicao(coord.getLinha(), coord.getColuna() + 3);
proibidos.add(temp.clone());
temp.setPosicao(coord.getLinha() + 3, coord.getColuna());
proibidos.add(temp.clone());
}
else if (getAgl() == 6) {
for (int lin=-3; lin<=3; lin++) {
for (int col=-3; col<=3; col++) {
if (!((col == lin || col == -lin) || (lin == 0 || col == 0) || ((lin == -3 || lin == 3) && (col == -2 || col == 2)) || (((col == -3 || col == 3) && (lin == -2 || lin == 2))))) {
temp.setPosicao(coord.getLinha() + lin, coord.getColuna() + col);
proibidos.add(temp.clone());
}
}
}
temp.setPosicao(coord.getLinha() - 4, coord.getColuna());
proibidos.add(temp.clone());
temp.setPosicao(coord.getLinha(), coord.getColuna() - 4);
proibidos.add(temp.clone());
temp.setPosicao(coord.getLinha(), coord.getColuna() + 4);
proibidos.add(temp.clone());
temp.setPosicao(coord.getLinha() + 4, coord.getColuna());
proibidos.add(temp.clone());
}
else if (getAgl() == 8) {
for (int lin=-3; lin<=3; lin++) {
for (int col=-3; col<=3; col++) {
if (!(((col == lin || col == -lin) && (col != -2 && col != 2)) || (lin == 0 || col == 0) ||
((lin == -3 || lin == 3) && (col == -2 || col == 2)) ||
(((col == -3 || col == 3) && (lin == -2 || lin == 2))) ||
((lin == -2 || lin == 2) && (col == -1 || col == 1)) ||
((col == -2 || col == 2) && (lin == -1 || lin == 1)))) {
temp.setPosicao(coord.getLinha() + lin, coord.getColuna() + col);
proibidos.add(temp.clone());
}
}
}
temp.setPosicao(coord.getLinha() - 4, coord.getColuna());
proibidos.add(temp.clone());
temp.setPosicao(coord.getLinha(), coord.getColuna() - 4);
proibidos.add(temp.clone());
temp.setPosicao(coord.getLinha(), coord.getColuna() + 4);
proibidos.add(temp.clone());
temp.setPosicao(coord.getLinha() + 4, coord.getColuna());
proibidos.add(temp.clone());
}
else if (getAgl() == 10) {
for (int lin=-4; lin<=4; lin++) {
for (int col=-4; col<=4; col++) {
if (!(col == lin || col == -lin) &&
(((lin == -4 || lin == 4))) ||
(((col == -4 || col == 4))) ) {
temp.setPosicao(coord.getLinha() + lin, coord.getColuna() + col);
proibidos.add(temp.clone());
}
}
}
}
return proibidos;
}
public ArrayList<Coordenada> getAlcance(Mapa mapa) {
ArrayList<Coordenada> proibidos = getAlcanceProibido();
ArrayList<Coordenada> possiveis = new ArrayList<>();
preenchimentoPorInundacao(mapa, coord.getLinha(), coord.getColuna(), proibidos, possiveis, true);
return possiveis;
}
public boolean moveu() {
return moveu;
}
public boolean atacou() {
return atacou;
}
public void setMoveu(boolean movimentou) {
moveu = movimentou;
}
public void setAtacou(boolean atk) {
atacou = atk;
}
public ArrayList<Coordenada> getAlcanceAtk(int opcao, Mapa mapa) {
ArrayList<Coordenada> proibidos = getAlcanceAtkProibido(opcao);
ArrayList<Coordenada> possiveis = new ArrayList<>();
preenchimentoPorInundacao(mapa, coord.getLinha(), coord.getColuna(), proibidos, possiveis, false);
return possiveis;
}
public abstract ArrayList<Coordenada> getAlcanceAtkProibido(int opcao);
// public void menuOpcoes(Mapa mapa) {
// System.out.println("===================================================");
// System.out.println("Escolha uma ação para " + getNome());
// System.out.println("[1] - Mover");
// System.out.println("[2] - Atacar");
// System.out.println("[3] - Item");
// System.out.println("[4] - Concluir");
// if (podeSurtar()) System.out.println("[5] - SURTAR");
// System.out.println("===================================================");
// System.out.print(">>> ");
// Scanner scan = new Scanner(System.in);
// int opcao = scan.nextInt();
// if (opcao == 1 && !moveu()) {
// ArrayList<Coordenada> alcance = getAlcance(mapa);
// System.out.println("Escolha a posição para a qual deseja mover: ");
// ArrayList<Obstaculo> obstaculos = new ArrayList<>();
// for (Coordenada c : alcance) {
//// Obstaculo obs = new Obstaculo(obs.sprite.getPath());
// obs.coord.setPosicao(c.getLinha(), c.getColuna());
// obstaculos.add(obs);
// mapa.inserirObsetaculo(obs);
// }
// mapa.plotarMatriz();
// System.out.println("Posição atual: " + "(" + coord.getLinha() + ", " + coord.getColuna() + ")");
// for (Coordenada co : alcance) {
// System.out.println("[" + (alcance.indexOf(co) + 1) + "] - (" + co.getLinha() + ", " + co.getColuna() + ")");
// }
// System.out.println("[" + (alcance.size()+1) + "] - Voltar menu.");
// int escolha = scan.nextInt();
// for (Obstaculo o : obstaculos) {
// mapa.removerObstaculo(o);
// }
// if (escolha == alcance.size() + 1) {
// System.out.println("Certo! Voltando para menu de ações.");
// menuOpcoes(mapa);
// return;
// }
// if (escolha < 1 || escolha > alcance.size()) {
// System.out.println("Opção inválida");
// menuOpcoes(mapa);
// return;
// }
// mover(alcance.get(escolha-1).getLinha(), alcance.get(escolha-1).getColuna(), mapa);
// menuOpcoes(mapa);
// return;
// } else if (opcao == 2 && !atacou()) {
// System.out.println("Ótimo! Escolha qual tipo de ataque realizar:");
// System.out.println("[1] - " + getAtkNatural());
// System.out.println("[2] - " + getHabilidadeEspecial());
// int optAtk = scan.nextInt();
//
// if (optAtk != 1 && optAtk != 2) {
// System.out.println("Opção Inválida!");
// menuOpcoes(mapa);
// return;
// }
//
// System.out.println("Escolha o oponente em que irá atacar: ");
// ArrayList<Coordenada> alcance = getAlcanceAtk(optAtk, mapa);
// ArrayList<Personagem> alvos = new ArrayList<>();
// for (Coordenada c : alcance) {
// Personagem p = mapa.getPosicaoPersonagem(c.getLinha(), c.getColuna());
// if (isSuporte() && optAtk == 2 && p != null) {
// alvos.add(p);
// }
// else if (p != null && p.getPlayerId() != getPlayerId()) alvos.add(p);
// }
//
// for (Personagem p : alvos) {
// System.out.println("[" + (alvos.indexOf(p) + 1) + "] - " + p.getNome());
// }
// System.out.println("["+ (alvos.size() + 1)+"] - Cancelar");
// System.out.print(">>> ");
// int vitima = scan.nextInt();
// if (vitima == alvos.size() + 1) {
// System.out.println("Certo! Voltando para menu de ações.");
// menuOpcoes(mapa);
// return;
// }
// if (vitima < 1 || vitima > alvos.size()) {
// System.out.println("Opção inválida");
// menuOpcoes(mapa);
// return;
// }
// if (optAtk == 1) atacarNatural(alvos.get(vitima-1));
// else if (optAtk == 2) habilidadeEspecial(alvos.get(vitima-1));
// setAtacou(true);
// menuOpcoes(mapa);
// return;
// }
// else if (opcao == 3 && !atacou()) {
// System.out.println("Abrindo o inventário de " + getNome() + "...");
// System.out.println("Escolha qual item utilizar: ");
// for (Item i : inventario) {
// System.out.println("[" + (inventario.indexOf(i) + 1) + "] - " + i.getNome());
// }
// System.out.println("[ "+ (inventario.size() + 1)+"] - Voltar");
// System.out.print(">>> ");
// int itemEscolhido = scan.nextInt();
//
// if (itemEscolhido == inventario.size() + 1) {
// System.out.println("Certo! Voltando para menu de ações.");
// menuOpcoes(mapa);
// return;
// }
// if (itemEscolhido < 1 || itemEscolhido > inventario.size()) {
// System.out.println("Opção inválida");
// menuOpcoes(mapa);
// return;
// }
// System.out.println(usarItem(inventario.get(itemEscolhido - 1)));
// menuOpcoes(mapa);
// return;
// }
// else if (opcao == 4) {
// passarTurno();
// }
// else if (opcao == 5 && podeSurtar()) {
// System.out.println(getNome() + " acumulou muitos os pontos de surto!!");
// System.out.println(getNome() + " está SURTANDOOOO");
// ativarModoSurto();
// menuOpcoes(mapa);
// return;
// }
// else {
// System.out.println("Essa opção ou é inválida ou já foi utilizada!");
// menuOpcoes(mapa);
// return;
// }
// }
}
| true |
b5009ffd4f04459fcdf8a8e61ba202c4a3de91a7 | Java | OnSunday/crud-plus | /src/main/java/com/jfeat/crud/plus/agent/CRUDServiceChildAgent.java | UTF-8 | 10,948 | 2.1875 | 2 | [] | no_license | package com.jfeat.crud.plus.agent;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jfeat.crud.base.exception.BusinessCode;
import com.jfeat.crud.base.exception.BusinessException;
import com.jfeat.crud.base.util.StrKit;
import com.jfeat.crud.plus.*;
/**
* Created by vincenthuang on 2017/8/11.
* Provide slave services for master
*/
public class CRUDServiceChildAgent<T, M extends T, C> implements CRUDServiceChild<C>,
CRUDServiceModelResult<T, M> {
/**
* just put child data into master child field
* @param masterObject
* @param childReference field reference in master table
* {
* "name":"",
* "profile_id": 100, //"this is childReference"
* }
* @param child
* @Param result save some result data
* @return
*/
//Integer updateChild(JSONObject masterObject, String childReference, C child);
/**
* Get the master field in child mapper/table
* @return
*/
protected BaseMapper<T> getMasterMapper;
protected BaseMapper<C> getChildMapper;
protected String childReferenceName; /// child reference field name referred in master table
/// Child Class Name
protected Class<C> childClassName;
public CRUDServiceChildAgent(BaseMapper<T> masterMapper, BaseMapper<C> childMapper,
String childReferenceName, Class<C> childClassName ) {
this.getMasterMapper = masterMapper;
this.getChildMapper = childMapper;
this.childReferenceName = childReferenceName;
this.childClassName = childClassName;
///
this.childReferenceNameCamelCase = StrKit.toCamelCase(childReferenceName);
}
/// Master Class Name
/// used to newInstance instead of select from database
private Class<T> masterClassName;
public Class<T> getMasterClassName() {
return masterClassName;
}
public void setMasterClassName(Class<T> masterClassName) {
this.masterClassName = masterClassName;
}
/// Master Object, used to skip query
//private JSONObject rawMasterObject;
private String childReferenceNameCamelCase;
@Override
public C getChild(long masterId) {
Long childId = getChildReference(masterId);
return getChildMapper.selectById(childId);
}
@Override
public Integer updateChild(long masterId, C child) {
T t = getMasterMapper.selectById(masterId);
//Integer affected = getMasterMapper.insert(m);
Integer affected = 0;
/// get child reference
JSONObject masterObject = CRUD.toJSONObject(t);
Long childReference = masterObject.getLong(childReferenceNameCamelCase);
JSONObject childObject = CRUD.toJSONObject(child);
if(childReference!=null) {
/// means update
childObject.put(CRUD.primaryKey, childReference);
C updatedChild = JSON.parseObject(childObject.toJSONString(), (Class<C>) child.getClass());
affected += getChildMapper.updateById(updatedChild);
}else{
//// means insert
affected += getChildMapper.insert(child);
masterObject.put(childReferenceNameCamelCase, CRUD.getPrimaryKey(child));
}
return affected;
}
@Override
public Integer deleteChild(long masterId) {
Integer affected = 0;
T t = getMasterMapper.selectById(masterId);
JSONObject jsonObject = CRUD.toJSONObject(t);
String childReferenceNameCamelCase = StrKit.toCamelCase(childReferenceName);
Long childId = jsonObject.getLong(childReferenceNameCamelCase);
if(childId!=null && childId > 0){
affected += getChildMapper.deleteById(childId);
}
/// update master filed
JSONObject toUpdate = new JSONObject();
toUpdate.put(childReferenceNameCamelCase, 0);
T updated = JSON.parseObject(toUpdate.toString(), (Class<T>) t.getClass());
affected += getMasterMapper.updateById(updated);
return affected;
}
public Integer updateChild(JSONObject masterObject, String childReference, C child) {
Long childId = masterObject.getLong(childReference);
/// if no child in childMapper, create one
Integer affected = 0;
if(childId==null || childId==0){
affected += getChildMapper.insert(child);
if(affected==1){
/// get here, we success, update master child field
childId = CRUD.getPrimaryKey(child);
/// update to master object
String childReferenceCamelCase = StrKit.toCamelCase(childReference);
masterObject.put(childReferenceCamelCase, childId);
/// update to mapper
try{
T t = masterClassName.newInstance();
t = CRUD.copyFrom(t, masterObject, true);
int isUpdated = getMasterMapper.updateById(t);
if (isUpdated == 0) {
throw new BusinessException(BusinessCode.CRUD_UPDATE_FAILURE);
}
}catch (IllegalAccessException e){
throw new RuntimeException(e);
}catch (InstantiationException e){
throw new RuntimeException(e);
}
}else {
throw new BusinessException(BusinessCode.CRUD_INSERT_FAILURE);
}
}else{
/// already has child, just update
affected += getChildMapper.update(child, new EntityWrapper<>(child).eq(CRUD.primaryKey, childId));
}
return affected;
}
/**
* belows for child CRUDServiceModel
*/
@Override
public Integer createMaster(M m, CRUDFilterResult<T> filter, String field, CRUDHandler<T,M> handler) {
if(handler!=null){
throw new RuntimeException("Must be handled by tool");
}
if(filter != null){
filter.filter(m, true);
}
//Integer affected = getMasterMapper.insert(m);
Integer affected = 0;
/// get the new inserted master id
JSONObject masterObject = CRUD.toJSONObject(m);
/// handle child item if contains child item key
if (masterObject.containsKey(field)) {
JSONObject childObject = masterObject.getJSONObject(field);
if(childObject!=null) {
/// convert json array into model
C child = JSON.toJavaObject(childObject, childClassName);
if (child != null) {
/// attach slave data into new class
affected += updateChild(masterObject, childReferenceName, child);
if(filter!=null) {
/// get the child id, and remember that in agent
filter.result().put(childReferenceNameCamelCase, masterObject.getLong(childReferenceNameCamelCase));
/// add primary key
if (!filter.result().containsKey(CRUD.primaryKey)) {
filter.result().put(CRUD.primaryKey, CRUD.getPrimaryKey(masterObject));
}
}
}
}
}
return affected;
}
@Override
public Integer updateMaster(M m, CRUDFilterResult<T> filter, String field, CRUDHandler<T,M> handler) {
if(handler!=null){
throw new RuntimeException("Must be handled by tool");
}
if(filter != null){
filter.filter(m, false);
}
JSONObject modelObject = CRUD.toJSONObject(m);
Integer affected = 0;
/// update child if it has
if(modelObject.containsKey(field)) {
JSONObject childObject = modelObject.getJSONObject(field);
if(childObject!=null) {
Long childReference = 0L;
/// check childReference exist first
if(!childObject.containsKey(CRUD.primaryKey)){
childReference = modelObject.getLong(childReferenceNameCamelCase);
childObject.put(CRUD.primaryKey, childReference);
}
/// update into database
C c = CRUD.castObject(childObject, childClassName);
affected += getChildMapper.updateById(c);
}
}
/// do not update master by child agent
/// do it by master
//affected += getMasterMapper.updateById(m);
return affected;
}
@Override
public CRUDObject<M> retrieveMaster(long masterId, CRUDFilterResult<T> filter, String field, CRUDHandler<T,M> handler) {
if(handler!=null){
throw new RuntimeException("Must be handled by tool");
}
JSONObject rawMasterObject = null;
if(rawMasterObject==null) {
T t = getMasterMapper.selectById(masterId);
rawMasterObject = CRUD.toJSONObject(t);
}
/// get child data if it has
if(rawMasterObject.containsKey(childReferenceNameCamelCase)) {
Long childReference = rawMasterObject.getLong(childReferenceNameCamelCase);
if(childReference!=null) {
C c = getChildMapper.selectById(childReference);
if(c!=null) {
JSONObject childObject = CRUD.toJSONObject(c);
JSONObject masterObject = (JSONObject) rawMasterObject.clone();
masterObject.put(field, childObject);
return new CRUDObject<M>().ignore(masterObject, filter==null? null: filter.ignore(true));
}
}
}else{
throw new RuntimeException("No child reference field found: "+ field);
}
return new CRUDObject<M>().ignore(rawMasterObject, filter==null?null:filter.ignore(true));
}
@Override
public Integer deleteMaster(long masterId, String field) {
/// delete child first
Long childReference = getChildReference(masterId);
Integer affected = 0;
if(childReference!=null){
affected += getChildMapper.deleteById(childReference);
}
/// delete master
/// fix: do not delete master, do it by master
///affected += getMasterMapper.deleteById(masterId);
return affected;
}
private Long getChildReference(long masterId){
T t = getMasterMapper.selectById(masterId);
JSONObject masterObject = CRUD.toJSONObject(t);
Long childReference = masterObject.getLong(childReferenceNameCamelCase);
return childReference;
}
}
| true |
127d123626ffe1744b37aa572441c0415f7197a3 | Java | atul-vyshnav/2021_IBM_Code_Challenge_StockIT | /src/StockIT-v1-release_source_from_JADX/sources/com/google/android/gms/internal/ads/zzcya.java | UTF-8 | 1,533 | 1.585938 | 2 | [
"Apache-2.0"
] | permissive | package com.google.android.gms.internal.ads;
import android.os.IBinder;
import com.google.android.gms.ads.AdError;
/* compiled from: com.google.android.gms:play-services-ads@@19.4.0 */
final class zzcya implements zzbvo {
private final /* synthetic */ zzctc zzgqq;
private boolean zzgrf = false;
private final /* synthetic */ zzbcg zzgrg;
private final /* synthetic */ zzcxv zzgrh;
zzcya(zzcxv zzcxv, zzctc zzctc, zzbcg zzbcg) {
this.zzgrh = zzcxv;
this.zzgqq = zzctc;
this.zzgrg = zzbcg;
}
public final void onAdFailedToLoad(int i) {
if (!this.zzgrf) {
zzm(new zzva(i, zzcxv.zza(this.zzgqq.zzcib, i), AdError.UNDEFINED_DOMAIN, (zzva) null, (IBinder) null));
}
}
public final synchronized void zzf(int i, String str) {
if (!this.zzgrf) {
this.zzgrf = true;
if (str == null) {
str = zzcxv.zza(this.zzgqq.zzcib, i);
}
zzm(new zzva(i, str, AdError.UNDEFINED_DOMAIN, (zzva) null, (IBinder) null));
}
}
public final synchronized void zzk(zzva zzva) {
this.zzgrf = true;
zzm(zzva);
}
private final void zzm(zzva zzva) {
zzdpg zzdpg = zzdpg.INTERNAL_ERROR;
if (((Boolean) zzwm.zzpx().zzd(zzabb.zzcux)).booleanValue()) {
zzdpg = zzdpg.NO_FILL;
}
this.zzgrg.setException(new zzcte(zzdpg, zzva));
}
public final synchronized void onAdLoaded() {
this.zzgrg.set(null);
}
}
| true |
e197582d84c3a073869dcce18ad71b12639aee51 | Java | cdosousa/scgos | /src/br/com/gfc/modelo/Lancamentos.java | UTF-8 | 13,541 | 2 | 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 br.com.gfc.modelo;
/**
*
* @author Cristiano de Oliveira Sousa
* @version 2018_03Alpha criado em 14/02/2017
*/
public class Lancamentos extends Portadores{
private String cdLancamento;
private int sequencial;
private String tipoLancamento; // Pre-Previsao, Tit-Título, Ad-Adiantmento
private String tipoMovimento; // Ad-Adiantamento, En-Entrada, Pg-Pagar, pR-Recebido(Pagamento Recebido), Re-Receber, rR-Recebido(Receber Recebido),Sa-Saida, Tr-Tranferência
private String titulo;
private int cdParcela;
private String cpfCnpj;
private String dataEmissao;
private String dataVencimento;
private String dataLiquidacao;
private double valorLancamento;
private double valorSaldo;
private String cdPortador;
private String tipoDocumento; // Ped-Pedido Comercial, OC-Ordem de Compra, OS-Ordem de Serviço, NFS-Nota Fiscal Saída, NFE-Nota Fiscal de Entrada, O-Outros
private String documento;
private String cdTipoPagamento;
private String nossoNumeroBanco;
private double valorJuros;
private double valorMulta;
private double valorAtualizado;
private String gerouArquivo;
private String cdContaReduzida;
private String cdCCusto;
private String contraPartida;
private String preparado;
private String cdHistorico;
private String complementoHistorico;
private String horaCadastro;
private String usuarioModificacao;
private String horaModificacao;
private String nomeRazaoSocial;
private String nomeTipoPagamento;
/**
* Contrutor padrão da classe
*/
public Lancamentos(){
}
public Lancamentos(String cdLancamento, int sequencial, String tipoLancamento, String tipoMovimento, String titulo, int cdParcela, String cpfCnpj, String dataEmissao, String dataVencimento, String dataLiquidacao,
double valorLancamento, double valorSaldo, String cdPortador, String tipoDocumento, String documento, String cdTipoPagamento, String nossoNumeroBanco,
double valorJuros, double valorMulta, double valorAtualizado, int diasCartorio, int diasLiquidacao, String gerouArquivo, String cdContaReduzida, String cdCCusto,
String contraPartida, String preparado, String cdHistorico, String complementoHistorico, String usuarioCadastro, String dataCadastro, String horaCadastro, String usuarioModificacao, String dataModificacao,
String horaModificacao, String situacao){
setCdLancamento(cdLancamento);
setSequencial(sequencial);
setTipoLancamento(tipoLancamento);
setTipoMovimento(tipoMovimento);
setTitulo(titulo);
setCdParcela(cdParcela);
setCpfCnpj(cpfCnpj);
setDataEmissao(dataEmissao);
setDataVencimento(dataVencimento);
setDataLiquidacao(dataLiquidacao);
setValorLancamento(valorLancamento);
setValorSaldo(valorSaldo);
setCdPortador(cdPortador);
setTipoDocumento(tipoDocumento);
setDocumento(documento);
setCdTipoPagamento(cdTipoPagamento);
setNossoNumeroBanco(nossoNumeroBanco);
setValorJuros(valorJuros);
setValorMulta(valorMulta);
setDiasCartorio(diasCartorio);
setDiasLiquidacao(diasLiquidacao);
setGerouArquivo(gerouArquivo);
setCdContaReduzida(cdContaReduzida);
setCdCCusto(cdCCusto);
setContraPartida(contraPartida);
setPreparado(preparado);
setCdHistorico(cdHistorico);
setComplementoHistorico(complementoHistorico);
setUsuarioCadastro(usuarioCadastro);
setDataCadastro(dataCadastro);
setHoraCadastro(horaCadastro);
setUsuarioModificacao(usuarioModificacao);
setDataModificacao(dataModificacao);
setHoraModificacao(horaModificacao);
setSituacao(situacao);
}
/**
* @return the cdLancamento
*/
public String getCdLancamento() {
return cdLancamento;
}
/**
* @param cdLancamento the cdLancamento to set
*/
public void setCdLancamento(String cdLancamento) {
this.cdLancamento = cdLancamento;
}
/**
* @return the tipoLancamento
*/
public String getTipoLancamento() {
return tipoLancamento;
}
/**
* @param tipoLancamento the tipoLancamento to set
*/
public void setTipoLancamento(String tipoLancamento) {
this.tipoLancamento = tipoLancamento;
}
/**
* @return the tipoMovimento
*/
public String getTipoMovimento() {
return tipoMovimento;
}
/**
* @param tipoMovimento the tipoMovimento to set
*/
public void setTipoMovimento(String tipoMovimento) {
this.tipoMovimento = tipoMovimento;
}
/**
* @return the cpfCnpj
*/
public String getCpfCnpj() {
return cpfCnpj;
}
/**
* @param cpfCnpj the cpfCnpj to set
*/
public void setCpfCnpj(String cpfCnpj) {
this.cpfCnpj = cpfCnpj;
}
/**
* @return the dataEmissao
*/
public String getDataEmissao() {
return dataEmissao;
}
/**
* @param dataEmissao the dataEmissao to set
*/
public void setDataEmissao(String dataEmissao) {
this.dataEmissao = dataEmissao;
}
/**
* @return the dataVencimento
*/
public String getDataVencimento() {
return dataVencimento;
}
/**
* @param dataVencimento the dataVencimento to set
*/
public void setDataVencimento(String dataVencimento) {
this.dataVencimento = dataVencimento;
}
/**
* @return the dataLiquidacao
*/
public String getDataLiquidacao() {
return dataLiquidacao;
}
/**
* @param dataLiquidacao the dataLiquidacao to set
*/
public void setDataLiquidacao(String dataLiquidacao) {
this.dataLiquidacao = dataLiquidacao;
}
/**
* @return the valorLancamento
*/
public double getValorLancamento() {
return valorLancamento;
}
/**
* @param valorLancamento the valorLancamento to set
*/
public void setValorLancamento(double valorLancamento) {
this.valorLancamento = valorLancamento;
}
/**
* @return the valorSaldo
*/
public double getValorSaldo() {
return valorSaldo;
}
/**
* @param valorSaldo the valorSaldo to set
*/
public void setValorSaldo(double valorSaldo) {
this.valorSaldo = valorSaldo;
}
/**
* @return the cdPortador
*/
public String getCdPortador() {
return cdPortador;
}
/**
* @param cdPortador the cdPortador to set
*/
public void setCdPortador(String cdPortador) {
this.cdPortador = cdPortador;
}
/**
* @return the tipoDocumento
*/
public String getTipoDocumento() {
return tipoDocumento;
}
/**
* @param tipoDocumento the tipoDocumento to set
*/
public void setTipoDocumento(String tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
/**
* @return the documento
*/
public String getDocumento() {
return documento;
}
/**
* @param documento the documento to set
*/
public void setDocumento(String documento) {
this.documento = documento;
}
/**
* @return the nossoNumeroBanco
*/
public String getNossoNumeroBanco() {
return nossoNumeroBanco;
}
/**
* @param nossoNumeroBanco the nossoNumeroBanco to set
*/
public void setNossoNumeroBanco(String nossoNumeroBanco) {
this.nossoNumeroBanco = nossoNumeroBanco;
}
/**
* @return the valorJuros
*/
public double getValorJuros() {
return valorJuros;
}
/**
* @param valorJuros the valorJuros to set
*/
public void setValorJuros(double valorJuros) {
this.valorJuros = valorJuros;
}
/**
* @return the valorMulta
*/
public double getValorMulta() {
return valorMulta;
}
/**
* @param valorMulta the valorMulta to set
*/
public void setValorMulta(double valorMulta) {
this.valorMulta = valorMulta;
}
/**
* @return the gerouArquivo
*/
public String getGerouArquivo() {
return gerouArquivo;
}
/**
* @param gerouArquivo the gerouArquivo to set
*/
public void setGerouArquivo(String gerouArquivo) {
this.gerouArquivo = gerouArquivo;
}
/**
* @return the cdCCusto
*/
public String getCdCCusto() {
return cdCCusto;
}
/**
* @param cdCCusto the cdCCusto to set
*/
public void setCdCCusto(String cdCCusto) {
this.cdCCusto = cdCCusto;
}
/**
* @return the contraPartida
*/
public String getContraPartida() {
return contraPartida;
}
/**
* @param contraPartida the contraPartida to set
*/
public void setContraPartida(String contraPartida) {
this.contraPartida = contraPartida;
}
/**
* @return the preparado
*/
public String getPreparado() {
return preparado;
}
/**
* @param preparado the preparado to set
*/
public void setPreparado(String preparado) {
this.preparado = preparado;
}
/**
* @return the cdHistorico
*/
public String getCdHistorico() {
return cdHistorico;
}
/**
* @param cdHistorico the cdHistorico to set
*/
public void setCdHistorico(String cdHistorico) {
this.cdHistorico = cdHistorico;
}
/**
* @return the complementoHistorico
*/
public String getComplementoHistorico() {
return complementoHistorico;
}
/**
* @param complementoHistorico the complementoHistorico to set
*/
public void setComplementoHistorico(String complementoHistorico) {
this.complementoHistorico = complementoHistorico;
}
/**
* @return the horaCadastro
*/
public String getHoraCadastro() {
return horaCadastro;
}
/**
* @param horaCadastro the horaCadastro to set
*/
public void setHoraCadastro(String horaCadastro) {
this.horaCadastro = horaCadastro;
}
/**
* @return the usuarioModificacao
*/
public String getUsuarioModificacao() {
return usuarioModificacao;
}
/**
* @param usuarioModificacao the usuarioModificacao to set
*/
public void setUsuarioModificacao(String usuarioModificacao) {
this.usuarioModificacao = usuarioModificacao;
}
/**
* @return the horaModificacao
*/
public String getHoraModificacao() {
return horaModificacao;
}
/**
* @param horaModificacao the horaModificacao to set
*/
public void setHoraModificacao(String horaModificacao) {
this.horaModificacao = horaModificacao;
}
/**
* @return the cdParcela
*/
public int getCdParcela() {
return cdParcela;
}
/**
* @param cdParcela the cdParcela to set
*/
public void setCdParcela(int cdParcela) {
this.cdParcela = cdParcela;
}
/**
* @return the cdContaReduzida
*/
public String getCdContaReduzida() {
return cdContaReduzida;
}
/**
* @param cdContaReduzida the cdContaReduzida to set
*/
public void setCdContaReduzida(String cdContaReduzida) {
this.cdContaReduzida = cdContaReduzida;
}
/**
* @return the nomeRazaoSocial
*/
public String getNomeRazaoSocial() {
return nomeRazaoSocial;
}
/**
* @param nomeRazaoSocial the nomeRazaoSocial to set
*/
public void setNomeRazaoSocial(String nomeRazaoSocial) {
this.nomeRazaoSocial = nomeRazaoSocial;
}
/**
* @return the titulo
*/
public String getTitulo() {
return titulo;
}
/**
* @param titulo the titulo to set
*/
public void setTitulo(String titulo) {
this.titulo = titulo;
}
/**
* @return the valorAtualizado
*/
public double getValorAtualizado() {
return valorAtualizado;
}
/**
* @param valorAtualizado the valorAtualizado to set
*/
public void setValorAtualizado(double valorAtualizado) {
this.valorAtualizado = valorAtualizado;
}
/**
* @return the cdTipoPagamento
*/
public String getCdTipoPagamento() {
return cdTipoPagamento;
}
/**
* @param cdTipoPagamento the cdTipoPagamento to set
*/
public void setCdTipoPagamento(String cdTipoPagamento) {
this.cdTipoPagamento = cdTipoPagamento;
}
/**
* @return the nomeTipoPagamento
*/
public String getNomeTipoPagamento() {
return nomeTipoPagamento;
}
/**
* @param nomeTipoPagamento the nomeTipoPagamento to set
*/
public void setNomeTipoPagamento(String nomeTipoPagamento) {
this.nomeTipoPagamento = nomeTipoPagamento;
}
/**
* @return the sequencial
*/
public int getSequencial() {
return sequencial;
}
/**
* @param sequencial the sequencial to set
*/
public void setSequencial(int sequencial) {
this.sequencial = sequencial;
}
} | true |
63dabf343e053caf01c6b6c4d2e8734045993c03 | Java | Hariae/Linked-List-1 | /RemoveNthNodeFromEnd.java | UTF-8 | 1,859 | 4.09375 | 4 | [] | no_license | /**
* Time Complexity: O(n)
* Space Complexity : O(1) no extra space
* Leetcode : Yes
* Idea:
* 1. Calculate size of list
* 2. Iterate till you find the position from end
* 3. Make the next node of previous point to current node's next
*/
class RemoveNthNodeFromEnd {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null) return null;
// size calc
int size = 0;
ListNode curr = head;
while(curr != null){
size++;
curr = curr.next;
}
curr = head;
int counter = 0;
ListNode prev = null;
while(curr != null){
// found the position - delete
if(counter == (size - n)){
if(prev == null){
head = curr.next;
}
else {
prev.next = curr.next;
}
}
counter++;
prev = curr;
curr = curr.next;
}
return head;
}
public void printList(ListNode head){
ListNode curr = head;
while(curr!= null){
System.out.print(curr.val + " ");
curr = curr.next;
}
}
public static void main(String[] args){
System.out.println("RemoveNthNodeFromEnd");
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
RemoveNthNodeFromEnd obj = new RemoveNthNodeFromEnd();
head = obj.removeNthFromEnd(head, 5);
obj.printList(head);
}
} | true |
50ca412bd3bbeb36fee8ac7f498e9ff20134bef4 | Java | CyrilTheAndroid/InformationsPositives | /app/src/main/java/com/pinalopes/informationspositives/storage/UserSettings.java | UTF-8 | 2,659 | 2.40625 | 2 | [] | no_license | package com.pinalopes.informationspositives.storage;
import com.pinalopes.informationspositives.R;
import java.util.ArrayList;
import java.util.List;
import static com.pinalopes.informationspositives.Constants.INDEX_OF_FAILURE;
public class UserSettings {
private final List<Integer> categoriesSelected;
private boolean isNotificationsEnabled;
private int currentTheme;
public UserSettings(Builder builder) {
if (builder.categoriesSelected != null) {
this.categoriesSelected = builder.categoriesSelected;
} else {
this.categoriesSelected = new ArrayList<>();
}
this.isNotificationsEnabled = builder.isNotificationsEnabled;
this.currentTheme = builder.currentTheme;
}
public void updateSelectedCategories(int idCategory, boolean isSelected) {
if (isSelected && !this.categoriesSelected.contains(idCategory)) {
this.categoriesSelected.add(idCategory);
} else if (!isSelected && this.categoriesSelected.contains(idCategory)) {
int index = this.categoriesSelected.indexOf(idCategory);
if (index != INDEX_OF_FAILURE) {
this.categoriesSelected.remove(index);
}
}
}
public List<Integer> getCategoriesSelected() {
return categoriesSelected;
}
public boolean isNotificationsEnabled() {
return isNotificationsEnabled;
}
public void modifyNotificationsState(boolean isChecked) {
this.isNotificationsEnabled = isChecked;
}
public int getCurrentTheme() {
return currentTheme;
}
public void modifyCurrentTheme() {
if (currentTheme == R.style.AppTheme_NoActionBar) {
currentTheme = R.style.AppTheme_Dark_NoActionBar;
} else {
currentTheme = R.style.AppTheme_NoActionBar;
}
}
static class Builder {
private List<Integer> categoriesSelected = new ArrayList<>();
private boolean isNotificationsEnabled;
private int currentTheme;
public Builder setCategoriesSelected(final List<Integer> categoriesSelected) {
this.categoriesSelected = categoriesSelected;
return this;
}
public Builder setNotificationsActivated(boolean notificationsActivated) {
this.isNotificationsEnabled = notificationsActivated;
return this;
}
public Builder setCurrentTheme(int currentTheme) {
this.currentTheme = currentTheme;
return this;
}
public UserSettings build() {
return new UserSettings(this);
}
}
}
| true |
cd6b8846c091f672f7b269a037cb713baca647f9 | Java | javajing/soa2 | /service/src/main/java/com/zjy/service/AppWorkOrderServiceImpl.java | UTF-8 | 401 | 1.820313 | 2 | [] | no_license | package com.zjy.service;
import com.zjy.enums.WorkOrderType;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
/**
*
*/
@Service
public class AppWorkOrderServiceImpl extends WorkOrderBaseServiceImpl implements AppWorkOrderService {
@PostConstruct
public void AfterSaleWorkOrderController() {
super.setWorkOrderType(WorkOrderType.APP);
}
}
| true |
158a75eaee993953dd3753508bba6ad970cb284d | Java | nicopaolillo/almacen-granate | /src/almacen/entidades/ItemCarrito.java | UTF-8 | 790 | 3.28125 | 3 | [] | no_license | package almacen.entidades;
public class ItemCarrito {
//atributos
private Articulo articulo;
private int cantidad;
//constructor
public ItemCarrito (Articulo articulo,int cantidad){
this.articulo=articulo;
this.cantidad=cantidad;
}
//get y set
public Articulo getArticulo() {
return articulo;
}
public void setArticulo(Articulo articulo) {
this.articulo = articulo;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
// 9) + calcularSubTotalItem():double
public double calcularSubTotalItem() {
double total = this.articulo.getPrecio() * this.cantidad;
return total;
}
public String toString() {
return "ItemCarrito: articulo: " + articulo + ", cantidad: " + cantidad;
}
}
| true |
a5fb63bf1d159aa3410626c311678db9c817f89f | Java | sven-zhou/sven_code | /coderobot/src/com/auto/coder/convert/ConvertType.java | UTF-8 | 162 | 1.578125 | 2 | [] | no_license | /**
*
*/
package com.auto.coder.convert;
/**
* @author hanman
*
*/
public interface ConvertType {
public String getType(String mysqlType);
}
| true |
a60ee44146878cf106025f97421b4c70529dd606 | Java | cha63506/CompSecurity | /youtube-source/src/com/google/android/apps/youtube/core/utils/ai.java | UTF-8 | 1,080 | 1.695313 | 2 | [] | no_license | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.apps.youtube.core.utils;
import android.content.ContentResolver;
import android.net.Uri;
import com.google.android.apps.youtube.common.fromguava.c;
import com.google.android.common.http.UrlRules;
public final class ai
{
private final ContentResolver a;
private final UrlRules b = null;
public ai(ContentResolver contentresolver)
{
a = (ContentResolver)c.a(contentresolver);
}
public final Uri a(Uri uri)
{
String s = uri.toString();
String s1 = a(s);
if (s.equals(s1))
{
return uri;
} else
{
return Uri.parse(s1);
}
}
public final String a(String s)
{
UrlRules urlrules;
if (b != null)
{
urlrules = b;
} else
{
urlrules = UrlRules.a(a);
}
return urlrules.a(s).a(s);
}
}
| true |
20f668c358f9944f98a18d7717fc4d149282bd5a | Java | michaelmosmann/wicket-praxis | /de.wicketpraxis--pom/webapp/src/main/java/de/wicketpraxis/web/converter/CustomConverterLocator.java | UTF-8 | 1,050 | 2.140625 | 2 | [] | no_license | /*****************************************
* Quelltexte zum Buch: Praxisbuch Wicket
* (http://www.hanser.de/978-3-446-41909-4)
*
* Autor: Michael Mosmann
* (michael@mosmann.de)
*****************************************/
package de.wicketpraxis.web.converter;
import java.util.HashMap;
import java.util.Map;
import org.apache.wicket.IConverterLocator;
import org.apache.wicket.util.convert.IConverter;
import de.wicketpraxis.web.thema.komponenten.converter.NamedColor;
import de.wicketpraxis.web.thema.komponenten.converter.NamedColorConverter;
public class CustomConverterLocator implements IConverterLocator {
IConverterLocator _fallback;
Map<Class<?>, IConverter> _customMap = new HashMap<Class<?>, IConverter>();
{
_customMap.put(NamedColor.class, NamedColorConverter.INSTANCE);
}
public CustomConverterLocator(IConverterLocator fallback) {
_fallback = fallback;
}
public <C> IConverter<C> getConverter(Class<C> type) {
IConverter<C> ret = _customMap.get(type);
if (ret == null)
ret = _fallback.getConverter(type);
return ret;
}
}
| true |
f41ea722c8aaed85a549ae5553fcbb89b866ea5f | Java | Gnod/Memo | /src/com/gnod/memo/tool/StringHelper.java | UTF-8 | 174 | 2.09375 | 2 | [] | no_license | package com.gnod.memo.tool;
public class StringHelper {
public static Boolean isNullOrEmpty(String input){
return (input == null || input.equalsIgnoreCase(""));
}
}
| true |
c065bc74427ab79fe3b5ee06f70a3496a71f2a51 | Java | lucasgenial/comunicav2 | /src/main/java/br/com/cicom/comunicacicom/DSPrimary/model/rh/Funcao.java | UTF-8 | 3,574 | 2.265625 | 2 | [] | no_license | package br.com.cicom.comunicacicom.DSPrimary.model.rh;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import br.com.cicom.comunicacicom.DSPrimary.model.sisEfetivo.TipoFuncao;
/**
* @author Lucas Matos
*/
@Entity
@Table(name = "FUNCAO")
@SuppressWarnings("serial")
public class Funcao implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", unique = true)
private Long id;
//@NotNull
@Size(min=3, max=120)
@Column(name = "NOME", unique = true)
private String nome;
@Column(name = "DESCRICAO")
private String descricao;
@NotNull
@Column(name="PRIORIDADE_MESA")
private boolean prioridade;
@Enumerated(EnumType.STRING)
@Column(name = "TIPO_FUNCAO")
private TipoFuncao tipoFuncao;
@NotNull
@Column(name="STATUS")
private boolean ativo;
public Funcao() {
this.ativo = true;
}
public Funcao(Long id, @Size(min = 3, max = 120) String nome, String descricao,
@NotNull boolean prioridade, @NotNull boolean ativo) {
super();
this.id = id;
this.nome = nome;
this.descricao = descricao;
this.prioridade = prioridade;
this.ativo = ativo;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public TipoFuncao getTipoFuncao() {
return tipoFuncao;
}
public void setTipoFuncao(TipoFuncao tipoFuncao) {
this.tipoFuncao = tipoFuncao;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome.toUpperCase();
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public boolean isPrioridade() {
return prioridade;
}
public void setPrioridade(boolean prioridade) {
this.prioridade = prioridade;
}
public boolean isAtivo() {
return ativo;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (ativo ? 1231 : 1237);
result = prime * result + ((descricao == null) ? 0 : descricao.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result + (prioridade ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Funcao other = (Funcao) obj;
if (ativo != other.ativo)
return false;
if (descricao == null) {
if (other.descricao != null)
return false;
} else if (!descricao.equals(other.descricao))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (prioridade != other.prioridade)
return false;
return true;
}
@Override
public String toString() {
return "Funcao [id=" + id + ", nome=" + nome + ", descricao=" + descricao + ", prioridade=" + prioridade
+ ", ativo=" + ativo + "]";
}
} | true |
51b0c11d1d4bed3c4f2d3ae331c16875ca68eacc | Java | dacom-utfpr-cm/atividade-4-semaforos-LuizASSilveira | /ex7/Main.java | UTF-8 | 1,051 | 3.75 | 4 | [] | no_license | package ex7;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;
/**
* Semáforos podem ser usadas para representar uma fila.Faça um código que implemente duas filas (F1 e F2) com
* semáforos. As threads colocadas na F1 sópodem executar se tiver um par na F2. Nesse caso, ambas
* as threads na primeira fila são executadas.
* @author luizASSilveira
*/
public class Main {
public static void main(String[] args) {
int numbThreadFila1 = 5;
int numbThreadFila2 = 2;
Semaphore fila1 = new Semaphore(1, true);
Semaphore fila2 = new Semaphore(1, true);
ArrayList<Thread> arrayThread = new ArrayList<>();
for (int i = 0; i < numbThreadFila1; i++) {
arrayThread.add(i, new Thread(new ThreadFilaPar( fila1, fila2 ))) ;
arrayThread.get(i).start();
}
for (int i = 0; i < numbThreadFila2; i++) {
arrayThread.add(i, new Thread(new ThreadFilaPar( fila2, fila1 ))) ;
arrayThread.get(i).start();
}
}
}
| true |
0de304b3f64c8a65ed5d6878682ab45a8cc0e417 | Java | mwagner19446/javaPracticeUCSC | /finalproject/src/finalproject/LetterGrader.java | UTF-8 | 22,279 | 3.5 | 4 | [] | no_license | package finalproject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
/**
* This is a solution for the Final for CMPR.x412 at UCSC for Beginning Java.
*
* The LetterGrader class has five public methods and three private subclasses
*
* The readScore method reads the input file and stores the scores in the Score Array.
* The calcLetterGrade reads the scores from the Score Array and calculates a Letter grade
* The printLetterGrade method prints the Letter grade to the Output file.
* The displayAverages calculates the average, min, and max scores for the quizzes and exams and prints them in the console.
* The doCleanup closes all the open streams that were used throughout.
*
* The LetterGrade private class manages the functions and data around the letterGrades for the Students.
* The Scores private class manages the functions and the data around the scores for each exam and quiz.
* The Analytics private class manages the functions and the data around average, min, and max scores for each quiz and exam.
*
* Requirements and Assumptions:
* The program assumes the input file will structure its rows with 8 tokens (and 7 delimiters).
* It assumes the delimiters will be commas.
* It will accept any number of rows.
* If there are not 8 tokens, the program will skip the line
* If the final 7 tokens are not numeric (These were intended to be scores), the program will change the value to 0.
*
* @author michael
* @date 10/25/2020
*/
public class LetterGrader {
LetterGrade letterGrade1; //creates a LetterGrade object. This is used to create and store the letter grades for each student.
Scores scores1; //creates a Scores object. This is used to create and store the scores.
Analytics analytics1; //creates an Analytics object. This is used to create and store average, min, and max values for each exam.
PrintWriter textPrintStream;// creates a PrintWriter object. This is used to write to a file.
String inputFileName; //Captures the name of the inputFile. Used in the error messages.
String outputFileName; //Captures the name of the outputFile. Used in the error messages.
File inputFile; //Creates a file object for the inputFile.
File outputFile; //Creates a file object for the outputFile.
Integer lineCount; //Tracks the line being evaluated in the input file.
Integer scorePosition; //Tracks the score position in the arrays.
Double rawScore; //Tracks the rawScore for the class. This is used to calculate the letterGrade. NOTE: Wrapper class is used over primitive to allow casting.
Scanner readInput; //Creates the file to read
StringTokenizer newLine; //Creates a new line for the StringTokenizer to evaluate.
/*
* Short description: The LetterGrader constructor creates an object. <p>
* Long description: The LetterGrader constructor creates an object. It creates two file objects from the inputs as well as defines the fileNames for each. <p>
* It is referenced by: {@link #TestLetterGrader.main} method <br>
* It references: No other methods. <br>
* @param input and output. Both are command arguments.
* @return NONE. Constructor method
*/
LetterGrader(String input, String output){
inputFileName=input;
outputFileName=output;
inputFile= new File(input);//input_final.txt parameters
outputFile= new File(output);//output_final.txt parameters
} //end LetterGrader constructor
/*
* Short description: The readFile private method reads the contents of a file. <p>
* Long description: The readFile private method reads the contents of a file.
* It creates a Scanner object of the input file.
* It has exceptions for FileNotFound, IOException, and General Exception.
* It is referenced by: {@link #readScore} method <br>
* It references: No other methods. <br>
* @param NONE. Consumes the objects inputFile value.
* @return NONE. Creates a Scanner Object called readInput.
*/
private void readFile() {
try {
this.readInput = new Scanner(this.inputFile);
}//end try
catch (FileNotFoundException e) {//File Not Found
System.out.println("File: " + this.inputFileName + "not found");
} // end catch
catch (IOException e) {//IO Exception
System.out.println("Error Reading from file: "+ this.inputFileName + e.getMessage());
} // end catch
catch (Exception e) {//General Exception
System.out.println(e);
} // end catch
}//end readFile
/*
* Short description: The determineNumberStudents private method counts the number of students scores in order to create arrays to store them. <p>
* Long description: The determineNumberStudents private method counts the number of students scores in order to create arrays to store them.
* It creates a StringTokenizer Object and iterates through each row of the Scanner Object.
* For every row that has the correct criteria (8 tokens, it increments)
* It is referenced by: {@link #readScore} method <br>
* It references: None. However it does instantiate three other ojects <br>
* @param NONE. Consumes the objects inputFile value.
* @return NONE. Creates a Scanner Object called readInput.
*/
private void determineNumberStudents() {
this.lineCount=0; //explicitly sets the lineCount to 0
while(this.readInput.hasNextLine()) {
this.newLine= new StringTokenizer(this.readInput.nextLine(),","); //Creates a StringTokenizer object from the next line
if(this.newLine.countTokens()==8) {//ensures only rows with 8 values (1 name and 7 scores) are counted.
this.lineCount++; //increments the lineCount
}//end if
}//end while
scores1=new Scores(this.lineCount); //creates new scores object. This will create the correct sized array.
letterGrade1=new LetterGrade(this.lineCount); //creates new letterGrade object. This will create the correct sized array.
analytics1=new Analytics(); //creates new analytics object.
}//end method determineNumberStudents
/*
* Short description: The readScore method takes reads the inputFile and stores the scores. <br>
* Long description: The readScore method takes reads the inputFile and stores the scores. <br>
* The method reads the LetterGrader's inputFile Object.
* The method uses the StringTokenizer Object to separate the values.
* The scores are stored in the scores array, a multi-dimensional array with the sub-arrays created for the individual students. <br>
* It is referenced by: {@link #main} method <br>
* It references: No other methods. <br>
* @param None. Consumes the LetterGrader's inputFile Object.
* Creates a StringTokenizer to separate the values. <br>
* @return NONE. Modifies the scores array <br>
*/
public void readScore(){
this.readFile(); //Reads the file to determine the number of students
this.determineNumberStudents(); //Creates the appropriate array
this.readFile(); //Reads the file to determine scores
scores1.readScore(this.readInput); //Creates the scoresArray
//scores1.cleanNonNumeric()
}//end method readScore;
/*
* Short description: The calcLetterGrade method calculates a letterGrade based on the rawScores <br>
* Long description: The calcLetterGrade method calculates a letterGrade based on the rawScores <br>
* It is referenced by: {@link #main} method <br>
* It references: {@link #LetterGrade.updateLetterGradeArray()} method <br>
* @param None. <br>
* @return NONE. <br>
*/
public void calcLetterGrade(){
letterGrade1.updateLetterGradeArray(scores1);
}//end method calcLetterGrade;
/*
* Short description: The printLetterGrade method prints the letterGrade to the outputFile. <br>
* Long description: The printLetterGrade method prints the letterGrade to the outputFile.
* The method will create a new file with the file name (if not already created)
* The method will sort the LetterGrade output alphabetically
* The method will write the contents to the output file.
* It is referenced by: {@link #main} method <br>
* It references: {@link #LetterGrade.sortLetterGradeArray } method <br>
* {@link #LetterGrade.printLetterGrade } method <br>
* @param None. <br>
* @return NONE. Modifies the outputFile <br>
*/
public void printLetterGrade(){
try {//Create the objects from the files
outputFile.createNewFile(); //if file already exists, will do nothing
textPrintStream = new PrintWriter(new FileOutputStream(outputFile)); //Creates a TextStream for the second file
letterGrade1.sortLetterGradeArray(); //sorts the array
letterGrade1.printLetterGrade(textPrintStream); //prints the array to the output file
}//end try
catch (FileNotFoundException e) { //no file
System.out.println("Error opening the file " + outputFileName + "\n" + e.getMessage());
System.exit(0);
}//end catch
catch (IOException e) {//IO Exception
System.out.println("Error Reading from file: "+ outputFileName + e.getMessage());
} // end catch
catch (Exception e) {//General Exception
System.out.println(e);
} // end catch
textPrintStream.close();
}//end method printGrade
/*
* Short description: The displayAnalytics method calculates and displays the averages in the console.<br>
* Long description: The displayAnalytics method calculates and displays the averages in the console.
* It is referenced by: {@link #main} method <br>
* It references: {@link #Analytics.calculateGradeAnalytics} method <br>
* {@link #Analytics.printGradeAnalytics} method <br>
* @param None. <br>
* @return NONE. <br>
*/
public void displayAnalytics(){
analytics1.calculateGradeAnalytics(scores1); //determines the min, max, and avg values for each of the quizzes and exams
analytics1.printGradeAnalytics(); //prints the results to the console
}//end method displayAnalytics
/*
* Short description: The doCleanup method closes any open IO streams<br>
* It is referenced by: {@link #main} method <br>
* It references: NONE<br>
* @param None. <br>
* @return NONE. <br>
*/
public void doCleanup() {
readInput.close(); //Close the Scanner Object
textPrintStream.close(); //Close the PrintWriter Object
}//end method do Cleanup
/*
* The Scores class stores values for the Student Scores and has methods for modifying the scoresArray.
* Storage Variables:
* scoresArray: A multi-dimensional array to store the student scores. The size is dynamically set by the input file.
* studentPosition: Tracks the Student being evaluated. This determines which nested array to update.
* scorePosition: Tracks the score being stored. This determines the position within the nested array to update
* rawScore: Tracks the weighted score for the class. This is used to determine the letter grade.
*
* Methods:
* readScore: This method reads the score from Scanner Object and stores it in the scoresArray
* calWeightedGrade: This method returns a weighted grade based on the values in the scoresArray.
*/
private class Scores{
private String [][]scoresArray;//Creates an array of arrays for Student Scores.
private Integer studentPosition; //Tracks the line being evaluated in the input file.
private Integer scorePosition; //Tracks the score position in the arrays.
private Double weightedScore; //Tracks the weighted score for student. This is used to determine the letter grade.
Scores(int studentCount){
scoresArray=new String[studentCount][8]; // instantiates a scoresArray with a number of arrays matching students.
}//end Scores constructor
/*
* Short description: The readScore method takes the input file and stores the values in the scoresArray.<br>
* Long description: The readScore method takes a Scanner Object (input file) and stores the values in the scoresArray.
* The method creates stringTokenizer Object
* It only evaluates lines with 8 tokens.
* It evaluates each token (Excluding the first, which is the student name) and replaces non-numeric values with "0"
* It is referenced by: {@link #LetterGrader.readScore} method <br>
* It references: None.<br>
* @param None. <br>
* @return None. <br>
*/
private void readScore(Scanner readInput) {
studentPosition=1;
scorePosition=0;
do{
StringTokenizer newLine= new StringTokenizer(readInput.nextLine(),","); //Creates a StringTokenizer object from the next line
if(newLine.countTokens()==8) {//only works on lines with 8 values.
while (newLine.hasMoreTokens()) {//iterate when there are more scores
String nextToken=newLine.nextToken();
scoresArray[studentPosition-1][scorePosition]=(nextToken.chars().allMatch(Character::isDigit)||scorePosition==0)?nextToken:"0";//if the nextToken is a Digit or the position is "0" (meaning it is the student name) insert the value to the array. Otherwise change to "0".
scorePosition++; //iterate on scoreNumber
}//end while hasMoreTokens()
studentPosition++; //iterate on lineCount
}//end if
scorePosition=0; //reset score number
}while(readInput.hasNextLine());//end do-while hasNextLine()
}//end method readScore
/*
* Short description: The calcWeightedGrade method takes a student position and returns a weighted grade for the class. <br>
* Long description: The calcWeightedGrade method takes a student position and returns a weighted grade for the class.
* The method accepts a value for student position.
* The method calculates the weighted grade, using the scoresArray.
* It is referenced by: {@link #LetterGrader.readScore} method <br>
* It references: None.<br>
* @param None. <br>
* @return None. <br>
*/
private double calcWeightedGrade(int studentPosition) {
weightedScore=(Double.parseDouble(scoresArray[studentPosition][1])*.10)+ //first quiz is weighted 10%
(Double.parseDouble(scoresArray[studentPosition][2])*.10)+ //second quiz is weighted 10%
(Double.parseDouble(scoresArray[studentPosition][3])*.10)+ //third quiz is weighted 10%
(Double.parseDouble(scoresArray[studentPosition][4])*.10)+ //fourth quiz is weighted 10%
(Double.parseDouble(scoresArray[studentPosition][5])*.20)+ //midterm 1 is weighted 20%
(Double.parseDouble(scoresArray[studentPosition][6])*.15)+ //midterm 2 is weighted 15%
(Double.parseDouble(scoresArray[studentPosition][7])*.25); //final is weighted 25%
return weightedScore;
}//end method calcWeightedGrade
}//end Scores class
/*
* The LetterGrade stores values for the LetterGrades for Students and has methods for modifying the letterGrade Object.
* Storage Variables:
* letterGradeArray, which is a multi-dimensional array storing the studentName and their letterGrade
*
* Methods:
* updateLetterGradeArray: Updates the letterGradeArray
* sortLetterGradeArray: Sorts the letterGradeArray
* printLetterGrade: Prints the letterGradeArray
*/
private class LetterGrade{
private String [][]letterGradeArray;//Creates an array of arrays for the Student Letter Grade Scores.
LetterGrade(int studentCount){
letterGradeArray=new String[studentCount][2];
}//end LetterGrade constructor
/*
* Short description: The updateLetterGradeArray method updates the letterGradeArray based on the weighted score <br>
* Long description: The updateLetterGradeArray method updates the letterGradeArray based on the weighted score
* The method accepts a rawScore and uses a waterfall If statement to assign a Letter Grade.
* It is referenced by: {@link #LetterGrader.calcLetterGrade} method <br>
* It references: None.<br>
* @param position
* @param studentName
* @param rawScore
* @return None. <br>
*/
private void updateLetterGradeArray(Scores scores1) {
for(int i=0; i<scores1.scoresArray.length; i++) {//iterate through outer array
letterGradeArray[i][0]=scores1.scoresArray[i][0]; //set the first element as the studentName
rawScore=scores1.calcWeightedGrade(i); //calculate the weighted Grade
if(rawScore>=89.45) {//rounding up to the nearest letterGrade
letterGradeArray[i][1]="A";
}// end if
else if(rawScore>=79.45){//rounding up to the nearest letterGrade
letterGradeArray[i][1]="B";
}//end else if
else if(rawScore>=69.45){//rounding up to the nearest letterGrade
letterGradeArray[i][1]="C";
}//end else if
else if(rawScore>=59.45){//rounding up to the nearest letterGrade
letterGradeArray[i][1]="D";
}//end else if
else {
letterGradeArray[i][1]="F";
}//end else
}//end for loop
}//end method updateLetterGradeArray
//The sortLetterGradeArray sorts the array alphabetically.
//It is used by the LetterGrader.printLetterGrade()
private void sortLetterGradeArray() {
Arrays.sort(this.letterGradeArray,java.util.Comparator.comparing(a->a[0])); //sorts the multi-dimensional array by the first value
}//end method sortLetterGradeArray
//The printLetterGrade method prints the letterGradeArray to the output file.
private void printLetterGrade(PrintWriter textPrintStream) {
textPrintStream.println("Letter grade for "+letterGradeArray.length+" students given in "+inputFileName+" is:"); //prints values file.
textPrintStream.println(" ");
for(int i=0; i<letterGradeArray.length; i++) { //iterates through the letterGradeArray
String format="%-40s%s%n"; //formats 40 spaces between the two strings with a line break at the end.
String student= letterGradeArray[i][0]+":"; //creates the first string for the student name
String grade=letterGradeArray[i][1]; //creates the second string with the letter grade
textPrintStream.printf(format, student,grade);
}//end for loop
System.out.println("Letter grade has been calculated for students listed in input file: "+inputFileName); //prints confirmation in console
System.out.println("Results have been written to outputfile: "+outputFileName);
System.out.println(" ");
}//end method printLetterGrade
}//end LetterGrade class
/*
* The Analytics class stores values for the class-level statistical observations for the quizzes and exams (ie: average, min, and max)
* Storage Variables:
* avgGrade Array: stores the average grade for each of the 7 quizzes and exams
* miGrade Array: stores the minimum grade for each of the 7 quizzes and exams
* maxGrade Array: stores the maximum grade for each of the 7 quizzes and exams
* Scores Object: relates Analytics Object to the Scores Object that the arrays are reflecting
*
* Methods:
* calculateGradeAnalytics: Calculates the min,max, and average values for the quizzes and exams
* printGradeAnalytics: Prints the min, max, and average values for the quizzes and exams.
*
*/
private class Analytics{
Double avgGrade[]=new Double[7]; //Creates an array for the averages on each quiz or exam. NOTE: Wrapper class is used over primitive to allow casting.
Integer minGrade[]=new Integer[7]; //Creates an array for the minimum on each quiz or exam. NOTE: Wrapper class is used over primitive to allow casting.
Integer maxGrade[]=new Integer[7]; //Creates an array for the maximum on each quiz or exam. NOTE: Wrapper class is used over primitive to allow casting.
//The calculateGradeAnalytics method determines the min, max, and average for the Scores Object.
//The method is used by the LetterGrader.displayAnalytics.
private void calculateGradeAnalytics(Scores scores1) {
Double gradeTotal;
for(int i=1; i<8; i++) {//iterates through each exam/ scorePosition. There are 7 exams
gradeTotal=0.0; //resets the gradeTotal
for (int j=0; j<scores1.scoresArray.length; j++) {//iterate through each student
if(j==0) {//sets the first score as the min and max
minGrade[i-1]=Integer.parseInt(scores1.scoresArray[j][i]);
maxGrade[i-1]=Integer.parseInt(scores1.scoresArray[j][i]);
}//end if
gradeTotal+=Double.parseDouble(scores1.scoresArray[j][i]); //Accumulates the aggregate temperature during the week. Used to capture the average below.
minGrade[i-1]=(minGrade[i-1]<Integer.parseInt(scores1.scoresArray[j][i]))?minGrade[i-1]:Integer.parseInt(scores1.scoresArray[j][i]); //Determine the min. Replaces the Min value if the current value is lesser.
maxGrade[i-1]=(maxGrade[i-1]>Integer.parseInt(scores1.scoresArray[j][i]))?maxGrade[i-1]:Integer.parseInt(scores1.scoresArray[j][i]); //Determine the max. Replaces the Max value if the current value is greater.
if(j==scores1.scoresArray.length-1) {//calculates the average grade after the final student
avgGrade[i-1]=gradeTotal/scores1.scoresArray.length;
}//end if
}//end inner for loop for students-- iterating through the same position in each array.
} //end outer for loop for exam scorePosition-- iterating through each array.
}//end method calculateGradeAnalytics()
//The printGradeAnalytics method prints the average, min, and max values in the console.
//The method is used by the LetterGrader.displayAnalytics.
private void printGradeAnalytics() {
System.out.println("Here is the class averages: ");
String formatString="%-15s%-8s%-8s%-8s%-8s%-8s%-8s%-8s%n"; //8 leading spaces
String formatFloat="%-15s%-8.2f%-8.2f%-8.2f%-8.2f%-8.2f%-8.2f%-8.2f%n"; //8 leading spaces with 2 decimals
System.out.printf(formatString," ","Q1","Q2","Q3","Q4","Mid1","Mid2","Final");
System.out.printf(formatFloat,"Average:",avgGrade[0],avgGrade[1],avgGrade[2],avgGrade[3],avgGrade[4],avgGrade[5],avgGrade[6]);
System.out.printf(formatString,"Minimum:",minGrade[0],minGrade[1],minGrade[2],minGrade[3],minGrade[4],minGrade[5],minGrade[6]);
System.out.printf(formatString,"Maximum:",maxGrade[0],maxGrade[1],maxGrade[2],maxGrade[3],maxGrade[4],maxGrade[5],maxGrade[6]);
}//end method printGradeAnalytics
}//end Analytics class
}//end LetterGrader class
| true |
74d573fdeffe646ab25d2f854a598af9c1c1f211 | Java | Grise/DDS_Videoclub | /DDS_Videoclub/src/presentacion/control/ControladorAdministracion.java | UTF-8 | 1,905 | 2.453125 | 2 | [] | no_license | package presentacion.control;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.net.URL;
import java.util.ResourceBundle;
import presentacion.control.ControladorCasoDeUso;
public class ControladorAdministracion extends ControladorCasoDeUso {
private static final String MENU_CREAR_PELICULA = "/presentacion/vista/CrearPelicula.fxml";
private static final String MENU_CREAR_GENERO = "/presentacion/vista/CrearGenero.fxml";
private static final String MENU_CREAR_DIRECTOR = "/presentacion/vista/CrearDirector.fxml";
private static final String MENU_CREAR_USUARIO = "/presentacion/vista/CrearUsuario.fxml";
@FXML
private Stage primaryStage;
@FXML
private Button anadirUsuario;
@FXML
private Button anadirPelicula;
@FXML
private Button anadirGenero;
@FXML
private Button anadirDirector;
@Override
public void initialize(URL location, ResourceBundle resources) {
stage = new Stage(StageStyle.DECORATED);
stage.initModality(Modality.APPLICATION_MODAL);
stage.setTitle("Administración");
anadirPelicula.setOnMouseClicked(event -> initCasoDeUso(MENU_CREAR_PELICULA, ControladorCrearPelicula.class).show());
anadirGenero.setOnMouseClicked(event -> initCasoDeUso(MENU_CREAR_GENERO, ControladorCrearGenero.class).show());
anadirDirector.setOnMouseClicked(event -> initCasoDeUso(MENU_CREAR_DIRECTOR, ControladorCrearDirector.class).show());
anadirUsuario.setOnMouseClicked(event -> initCasoDeUso(MENU_CREAR_USUARIO, ControladorCrearUsuario.class).show());
}
private <T extends ControladorCasoDeUso> T initCasoDeUso(String urlVista, Class<T> controlClass) {
return ControladorCasoDeUso.initCasoDeUso(urlVista, controlClass, primaryStage, this);
}
}
| true |
b48515c79003f900802fa54f7e43d0146fccbf5d | Java | JAAC8/-Pr-ctica-de-laboratorio-05-Gesti-n-de-Tickets-Parqueadero- | /src/main/java/ec/edu/ec/dao/DAOVehiculo.java | UTF-8 | 2,012 | 2.640625 | 3 | [
"MIT"
] | permissive | /*
* 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 ec.edu.ec.dao;
import ec.edu.ec.modelo.Cliente;
import ec.edu.ec.modelo.Vehiculo;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
/**
*
* @author José Andrés Abad
*/
public class DAOVehiculo implements DAOVehiculoI {
private Set<Vehiculo> vehiculos;
private int cont;
public DAOVehiculo(){
this.vehiculos = new HashSet<Vehiculo>();
this.cont = 0;
}
@Override
public void create(Vehiculo v) {
this.vehiculos.add(v);
this.cont++;
}
@Override
public Vehiculo read(String placa) {
Iterator it = vehiculos.iterator();
while (it.hasNext()) {
Vehiculo v = (Vehiculo) it.next();
if(v.getPlaca().equals(placa)){
return v;
}
}
return null;
}
@Override
public void update(Vehiculo v) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void delete(String placa) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
this.cont--;
}
@Override
public void findAll() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public boolean buscar(String placa){
Iterator it = vehiculos.iterator();
while (it.hasNext()) {
Vehiculo v = (Vehiculo) it.next();
if(v.getPlaca().equals(placa)){
return true;
}
}
return false;
}
public int getNumeroVehiculos(){
return this.cont;
}
}
| true |
88e1bd1da261f1dbe84c6e8489b92f0aa774c420 | Java | Abdullah272056/GridView | /app/src/main/java/com/example/gridview/CustomAdapter.java | UTF-8 | 1,745 | 2.390625 | 2 | [] | no_license | package com.example.gridview;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter {
Context context;
int [] allahNameImage;
String [] nameText;
String [] nameMeaning;
private LayoutInflater inflater;
public CustomAdapter(Context context, int[] allahNameImage, String[] nameText, String[] nameMeaning) {
this.context = context;
this.allahNameImage = allahNameImage;
this.nameText = nameText;
this.nameMeaning = nameMeaning;
}
@Override
public int getCount() {
return allahNameImage.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView= inflater.inflate(R.layout.sample,parent,false);
TextView nameTextView=convertView.findViewById(R.id.nameTextViewId);
TextView nameMeaningTextView=convertView.findViewById(R.id.nameMeaningTextViewId);
ImageView imageView=convertView.findViewById(R.id.imageViewId);
imageView.setImageResource(allahNameImage[position]);
nameTextView.setText(nameText[position]);
nameMeaningTextView.setText(nameMeaning[position]);
}
return convertView;
}
}
| true |
a122503bbf182fb95ef7b0069e2c3460d63e6121 | Java | khshanovskyi/electron | /src/main/java/ua/electron/controller/order/OrderActionsController.java | UTF-8 | 3,037 | 2.140625 | 2 | [] | no_license | package ua.electron.controller.order;
import org.apache.log4j.Logger;
import ua.electron.entity.Constant;
import ua.electron.entity.Order;
import ua.electron.service.topLevel.orderService.IOrderService;
import ua.electron.service.topLevel.shoppingCartService.ICookieShoppingCartService;
import ua.electron.service.topLevel.shoppingCartService.impl.PresenterProductFromCookieServiceImpl;
import ua.electron.service.lowerLevel.orderCreator.IOrderCreator;
import ua.electron.service.lowerLevel.orderCreator.impl.OrderCreatorImpl;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;
@WebServlet("/order-actions")
public class OrderActionsController extends HttpServlet {
private static final Logger LOGGER = Logger.getLogger(OrderActionsController.class);
private IOrderService orderService;
private PresenterProductFromCookieServiceImpl presenterProductFromCookieService;
private ICookieShoppingCartService cookieShoppingCartService;
@Override
public void init() {
orderService = (IOrderService) getServletContext().getAttribute("orderService");
LOGGER.trace("orderService initialization");
presenterProductFromCookieService = (PresenterProductFromCookieServiceImpl) getServletContext().
getAttribute("presenterProductFromCookieService");
LOGGER.trace("presenterProductFromCookieService initialization");
cookieShoppingCartService = (ICookieShoppingCartService) getServletContext().getAttribute("cookieShoppingCartService");
LOGGER.trace("cookieShoppingCartService initialization");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HttpSession session = req.getSession();
if (session.getAttribute(String.valueOf(Constant.USER_IS_UNBLOCKED)) != null) {
IOrderCreator orderCreator = new OrderCreatorImpl();
if (req.getParameter("createOrder") != null) {
Optional<Order> orderOpt = orderCreator.orderValidatorAndCreator(req, presenterProductFromCookieService);
if (orderOpt.isPresent()) {
Order order = orderOpt.get();
orderService.createNewOrder(order);
cookieShoppingCartService.coolieRemoveAllProduct(req, resp);
LOGGER.info("Order created! All cookie removed!");
resp.sendRedirect(req.getContextPath() + "/order-success");
}
}
} else {
LOGGER.trace("User doesn't have authorization! Redirect to login page.");
resp.sendRedirect(req.getContextPath() + "/login");
}
}
}
| true |
70680e9cbdb0af29e6f9b4832f46ea2bf8ac8f53 | Java | aswini50/apiChallengesFramework | /tech-assesment/src/test/java/com/api/automation/testNG/HeartbeatTest.java | UTF-8 | 1,873 | 2.046875 | 2 | [] | no_license | package com.api.automation.testNG;
import org.testng.annotations.Test;
import com.api.automation.ApiChallengerUtil;
import junit.framework.Assert;
public class HeartbeatTest extends BaseTest {
public static String basePath;
@Test(priority = 1)
public void deleteHeartbeat() {
basePath = ApiChallengerUtil.props.getProperty("heartbeat.base.path");
try {
restActions.setBasePath(basePath);
restActions.addHeader(challengerId);
restActions.performRequest("delete");
System.out.println(restActions.getStatusCode());
System.out.println(restActions.getResponseAsString());
Assert.assertEquals(405, restActions.getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test(priority = 2)
public void patchHeartbeat() {
try {
restActions.setBasePath(basePath);
restActions.addHeader(challengerId);
restActions.performRequest("patch");
System.out.println(restActions.getStatusCode());
Assert.assertEquals(500, restActions.getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test(priority = 3, enabled = false)
public void traceHeartbeat() {
try {
restActions.setBasePath(basePath);
restActions.addHeader(challengerId);
restActions.performRequest("trace"); // Unable to create trace
// method
System.out.println(restActions.getStatusCode());
Assert.assertEquals(501, restActions.getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test(priority = 4)
public void getHeartbeat() {
try {
restActions.setBasePath(basePath);
restActions.addHeader(challengerId);
restActions.performRequest("get");
System.out.println(restActions.getStatusCode());
System.out.println(restActions.getResponseAsString());
Assert.assertEquals(204, restActions.getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
089e3066d4ab232e1cbb89d141df3b928eb2d4df | Java | zhongxingyu/Seer | /Diff-Raw-Data/3/3_6f202769d67f886362d83a2443d28b656ad57aaa/LayoutLib/3_6f202769d67f886362d83a2443d28b656ad57aaa_LayoutLib_t.java | UTF-8 | 33,186 | 1.898438 | 2 | [] | no_license | /* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: LayoutLib.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.generator.layout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.geometry.Orientation;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortCharacteristic;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.Connection;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.SizeOffset;
import com.sun.electric.technology.Technology;
import com.sun.electric.tool.io.FileType;
import com.sun.electric.tool.io.input.LibraryFiles;
import com.sun.electric.tool.io.output.Output;
import com.sun.electric.tool.user.ActivityLogger;
import com.sun.electric.tool.user.dialogs.OpenFile;
/*
* The LayoutLib class provides an assortment of methods that I
* found to be useful for programatic layout generation.
*/
public class LayoutLib {
// ---------------------------- public data ------------------------------
/** Use the default size. When a width or height argument has this
* value the object should be created with its default
* dimension. Note that -DEF_SIZE is also a legal
* constant. Negative dimensions specify mirroring for certain
* methods. */
public static final double DEF_SIZE = Double.POSITIVE_INFINITY;
public static enum Corner {
TL, TR, BL, BR;
}
// ---------------------------- public methods ---------------------------
/**
* Print a message, dump a stack trace, and throw a RuntimeException if
* errorHasOccurred argument is true.
*
* @param errorHasOccurred indicates a runtime error has been detected
* @param msg the message to print when an error occurs
* @throws RuntimeException if errorHasOccurred is true
*/
public static void error(boolean errorHasOccurred, String msg) {
if (!errorHasOccurred) return;
RuntimeException e = new RuntimeException(msg);
// The following prints a stack trace on the console
ActivityLogger.logException(e);
// The following prints a stack trace in the Electric messages window
throw e;
}
/**
* Open a library for reading. If a library is
* already open then return it. Otherwise look for the library
* file named libFileName and open that library.
*
* @param libFileName the fully qualified path name of the Library
* file on disk
* @return the open Library or null if it can't be found
*/
public static Library openLibForRead(String libFileName) {
URL libFileURL = TextUtils.makeURLToFile(libFileName);
String libName = TextUtils.getFileNameWithoutExtension(libFileURL);
Library lib = Library.findLibrary(libName);
FileType type = OpenFile.getOpenFileType(libFileName, FileType.DEFAULTLIB);
if (lib==null) {
lib = LibraryFiles.readLibrary(libFileURL, null, type, false);
}
error(lib==null, "can't open Library for reading: "+libFileName);
return lib;
}
/**
* Open a library for modification. If a library named libName is
* already open then return it. Otherwise look for the file named:
* libFileName and open that library. Finally, if all else fails
* create a new Library and return it.
*
* @param libName the name of the Library
* file on disk
* @return the desired library
*/
// This doesn't work anymore.
// public static Library openLibForModify(String libName, String libFileName) {
// // return an open Library if it exists
// Library lib = Library.findLibrary(libName);
// if (lib!=null) return lib;
//
// // open a Library file if it exists
// URL libFileURL = TextUtils.makeURLToFile(libFileName);
// lib = Input.readLibrary(libFileURL, OpenFile.Type.ELIB);
// if (lib!=null) return lib;
//
// // create a new Library
// lib = Library.newInstance(libName, libFileURL);
//
// error(lib==null, "can't open Library for modify: "+libName);
// return lib;
// }
public static Library openLibForWrite(String libName) {
// return an open Library if it exists
Library lib = Library.findLibrary(libName);
if (lib!=null) return lib;
// create a new Library
lib = Library.newInstance(libName, null);
URL libURL = TextUtils.makeURLToFile(libName);
lib.setLibFile(libURL);
error(lib==null, "can't open Library for modify: "+libName);
return lib;
}
/**
* Write a library in JELIB format.
* @param lib the library to be written.
*/
public static void writeLibrary(Library lib) {
Output.writeLibrary(lib, FileType.JELIB, false, false, false);
}
/**
* Get the width of an ArcInst. The getArcInstWidth method differs
* from ArcInst.getLambdaFullWidth() in that it subtracts off the "width
* offset". Hence, getArcInstWidth returns a width that matches
* that reported by the GUI.
*
* @param ai the ArcInst whose width is reported
* @return the width of the ArcInst.
*/
public static double getArcInstWidth(ArcInst ai) {
double w = ai.getLambdaBaseWidth();
return DBMath.round(w);
}
/** Get the default width of a NodeProto. The getNodeProtoWidth
* method differs from NodeProto.getDefWidth in that it subtracts
* off the "width offset". Hence getNodeProtoWidth returns a width
* that matches that reported by the GUI.
*
* @param np the NodeProto we want the width of.
* @return the width of the NodeProto. */
public static double getNodeProtoWidth(NodeProto np) {
SizeOffset so = np.getProtoSizeOffset();
double w = np.getDefWidth() - so.getLowXOffset() - so.getHighXOffset();
return DBMath.round(w);
}
/** Get the default height of a NodeProto. The getNodeProtoHeight
* method differs from NodeProto.getDefHeight in that it subtracts
* off the "height offset". Hence getNodeProtoHeight returns a
* height that matches that reported by the GUI.
*
* @param np the NodeProto we want the height of
* @return the height of the NodeProto */
public static double getNodeProtoHeight(NodeProto np) {
SizeOffset so = np.getProtoSizeOffset();
double h = np.getDefHeight() - so.getLowYOffset() - so.getHighYOffset();
return DBMath.round(h);
}
private static void prln(String msg) {System.out.println(msg);}
/**
* Find the width of the widest wire connected hierarchically to port.
*
* @param port the PortInst to check for attached wires.
* @return the width of the widest wire. This width excludes the
* "width offset" so it matches the width reported by the GUI.
* If no wire is attached to port then return DEF_SIZE.
*/
public static double widestWireWidth(PortInst port) {
// NodeInst ni = port.getNodeInst();
PortProto pp = port.getPortProto();
double maxWid = -1;
for (Iterator<ArcInst> arcs=getArcInstsOnPortInst(port); arcs.hasNext();) {
ArcInst ai = arcs.next();
//prln(" arc width: "+getArcInstWidth(ai));
maxWid = Math.max(maxWid, getArcInstWidth(ai));
}
if (pp instanceof Export) {
double lowerMax = widestWireWidth(((Export)pp).getOriginalPort());
if (lowerMax!=DEF_SIZE) maxWid = Math.max(maxWid, lowerMax);
}
if (maxWid < 0) return DEF_SIZE;
return DBMath.round(maxWid);
}
/** Return a list of ArcInsts attached to PortInst, pi.
* @param pi PortInst on which to find attached ArcInsts. */
public static Iterator<ArcInst> getArcInstsOnPortInst(PortInst pi) {
ArrayList<ArcInst> arcs = new ArrayList<ArcInst>();
// NodeInst ni = pi.getNodeInst();
for (Iterator<Connection> it=pi.getConnections(); it.hasNext();) {
Connection c = it.next();
arcs.add(c.getArc());
}
// for (Iterator it=ni.getConnections(); it.hasNext();) {
// Connection c = it.next();
// if (c.getPortInst()==pi) arcs.add(c.getArc());
// }
return arcs.iterator();
}
/** The center returned by bounds might have a slight amount of rounding
* error. Compensate for this by always rounding coordinates to a 103-4
* lambda grid when reading and writing the database. */
public static double roundCenterX(PortInst pi) {
return pi.getCenter().getX();
// return DBMath.round(pi.getBounds().getCenterX()); new way avoids rounding here
}
public static double roundCenterY(PortInst pi) {
return pi.getCenter().getY();
// return DBMath.round(pi.getBounds().getCenterY());
}
public static Rectangle2D calculateNodeInst(NodeProto np,
double x, double y,
double width, double height)
{
if (np instanceof Cell) {
width = (width<0 ? -1 : 1) * np.getDefWidth();
height = (height<0 ? -1 : 1) * np.getDefHeight();
} else {
SizeOffset so = np.getProtoSizeOffset();
// Take the default width or height if that's what the user wants.
// Otherwise adjust the user-specified width or height by the
// SizeOffset.
double signW = width<0 ? -1 : 1;
if (width==DEF_SIZE || width==-DEF_SIZE) {
width = signW * np.getDefWidth();
} else {
double hi = so.getHighXOffset();
double lo = so.getLowXOffset();
error(lo!=hi, "asymmetric X offset");
width = signW * (Math.abs(width) + hi+lo);
}
double signH = height<0 ? -1 : 1;
if (height==DEF_SIZE || height==-DEF_SIZE) {
height = signH * np.getDefHeight();
} else {
double hi = so.getHighYOffset();
double lo = so.getLowYOffset();
error(lo!=hi, "asymmetric Y offset");
height = signH * (Math.abs(height) + hi+lo);
}
}
// round all dimensions to a 10e-4 lambda grid
x = DBMath.round(x);
y = DBMath.round(y);
width = DBMath.round(width);
height = DBMath.round(height);
return new Rectangle2D.Double(x, y, width, height);
}
/**
* Create a new NodeInst. The following geometric transformations
* are performed upon the NodeProto in order to arrive at the
* final position of the NodeInst in the coordinate space of the
* parent:
* <ol>
* <li> Scale the NodeProto in x and y so that it has dimensions
* |width| and |height|. All scaling is performed about the
* NodeProto's origin, (0, 0).
* <li> If width<0 then mirror the preceding result about the
* y-axis.
* <li> If height<0 then mirror the preceding result about the
* x-axis.
* <li> Rotating the preceding result clockwise by angle degrees.
* <li> Translate the preceding result by (x, y). Note that the
* NodeProto's origin always ends up at (x, y) in the
* coordinate space of the parent.
* </ol>
*
* The newNodeInst method differs from NodeInst.newInstance in the
* following ways:
*
* <ul>
* <li>The "size offset" is added to the width and height
* arguments before the object is created. The result is a
* NodeInst that the GUI reports has dimensions: width x height.
* <li>The angle is in units of degrees but is rounded to the
* nearest tenth degree.
* <li>If np is a Cell then the width and height are taken from
* the Cell's defaults. The width and height arguments only
* specify mirroring.
* <li>If np is a Cell then rotation and mirroring are performed
* relative to the Cell's origin.
* <li>If np is a Cell then the NodeInst is positioned using the
* Cell's origin. That is, the resulting NodeInst will map the
* Cell's origin to (x, y) in the coordinate space of the parent.
* <li>If the width or height arguments are equal to DEF_SIZE then
* the NodeInst is created using the NodeProto's default
* dimensions. Eventually I will change this to <i>minimum</i>
* dimensions.
* </ul>
* @param np the NodeProto to instantiate
* @param width the desired width of the NodeInst
* @param height the desired height of the NodeInst
* @param x the desired x-coordinate of the NodeProto's origin in
* the coordinate space of the parent. If x is negative then the
* NodeInst mirrors about the y-axis.
* @param y the desired y-coordinate of the NodeProto's origin in
* the coordinate space of the parent. If y is negative then the
* NodeInst mirrors about the x-axis.
* @param angle the angle, in degrees, of rotation about the
* NodeProto's origin.
* @param parent the Cell that will contain the NodeInst.
* @return the new NodeInst.
*/
public static NodeInst newNodeInst(NodeProto np,
double x, double y,
double width, double height,
double angle, Cell parent) {
Rectangle2D rect = calculateNodeInst(np, x, y, width, height);
return newNodeInst(np, rect, angle, parent);
}
public static NodeInst newNodeInst(NodeProto np, Rectangle2D rect,
double angle, Cell parent)
{
double x = rect.getX();
double y = rect.getY();
double width = rect.getWidth();
double height = rect.getHeight();
Orientation orient = Orientation.fromJava((int)Math.round(angle*10), width < 0, height < 0);
NodeInst ni = NodeInst.newInstance(np, new Point2D.Double(x, y), Math.abs(width), Math.abs(height),
parent, orient, null, 0);
error(ni==null, "newNodeInst failed");
// adjust position so that translation is Cell-Center relative
if (np instanceof Cell) {
Point2D ref = getPosition(ni);
ni.move(x-ref.getX(), y-ref.getY());
}
return ni;
}
/**
* Modify the position of a NodeInst. The size and position of a
* NodeInst in the coordinate space of its parent cell is
* determined by 5 parameters: x, y, width, height, and angle, as
* described in the JavaDoc for newNodeInst. The modNodeInst
* method modifies those parameters.
* <p>The modNodeInst method differs from NodeInst.modifyInstance
* in the following ways:
* <ul>
* <li>If ni is an instance of a Cell then mirroring, rotation,
* and positioning are performed relative to the Cell's origin
* <li>The arguments dw and dh, are added to the absolute values
* of the NodeInst's x-size and y-size.
* <li>The arguments mirrorAboutXAxis and mirrorAboutYAxis are
* used to mirror the NodeInst about the x and y axes.
* </ul>
* @param ni the NodeInst to modify
* @param dx the amount by which to change the x-coordinate of the
* NodeInst's position
* @param dy the amount by which to change the y-coordinate of the
* NodeInst's position
* @param dw the amount by which to change to absolute value of
* the NodeInst's width
* @param dh the amount by which to change to absolute value of
* the NodeInst's height.
* @param mirrorAboutYAxis if true then toggle the mirroring of
* the NodeInst about the y-axis
* @param mirrorAboutXAxis if true then toggle the mirroring of
* the NodeInst about the x-axis
* @param dAngle the amount by which to change the NodeInst's angle
*/
public static void modNodeInst(NodeInst ni, double dx, double dy,
double dw, double dh,
boolean mirrorAboutYAxis,
boolean mirrorAboutXAxis,
double dAngle) {
// boolean oldMirX = ni.isMirroredAboutXAxis();
// boolean oldMirY = ni.isMirroredAboutYAxis();
// double oldXS = ni.getXSize() * (oldMirY ? -1 : 1);
// double oldYS = ni.getYSize() * (oldMirX ? -1 : 1);
double newX = getPosition(ni).getX() + dx;
double newY = getPosition(ni).getY() + dy;
// double newW = Math.max(ni.getXSize() + dw, 0);
// double newH = Math.max(ni.getYSize() + dh, 0);
//
// boolean newMirX = oldMirX ^ mirrorAboutXAxis;
// boolean newMirY = oldMirY ^ mirrorAboutYAxis;
//
// double newXS = newW * (newMirY ? -1 : 1);
// double newYS = newH * (newMirX ? -1 : 1);
Orientation dOrient = Orientation.fromJava((int)Math.rint(dAngle*10), mirrorAboutYAxis, mirrorAboutXAxis);
ni.modifyInstance(0, 0, dw, dh, dOrient);
// ni.modifyInstance(0, 0, newXS-oldXS, newYS-oldYS,
// (int)Math.rint(dAngle*10));
ni.move(newX-getPosition(ni).getX(), newY-getPosition(ni).getY());
}
/**
* Get the position of a NodeInst. In the coordinate space of the
* NodeInst's parent, get the x and y-coordinates of the origin of
* the NodeInst's NodeProto.
* @param ni the NodeInst we want the position of
* @return the x and y-coordinates of the origin of the
* NodeInst's NodeProto
*/
public static Point2D getPosition(NodeInst ni) {
NodeProto np = ni.getProto();
Point2D p;
if (np instanceof Cell) {
AffineTransform xForm = ni.transformOut();
p = xForm.transform(new Point2D.Double(0, 0), null);
} else {
p = ni.getAnchorCenter();
}
double x = DBMath.round(p.getX());
double y = DBMath.round(p.getY());
return new Point2D.Double(x,y);
}
/**
* Create a new ArcInst. This differs from ArcInst.newInstance in that
* the "width-offset" is added to the width parameter. The result is an
* ArcInst that the GUI reports is width wide.
* @param ap the ArcProto to instantiate
* @param width the desired width of the ArcInst
* @param head the head PortInst
* @param hX the x-coordinate of the head PortInst
* @param hY the y-coordinate of the head PortInst
* @param tail the tail PortInst
* @param tX the x-coordinate of the tail PortInst
* @param tY the y-coordinate of the tail PortInst
* @return the new ArcInst
*/
public static ArcInst newArcInst(ArcProto ap, double width,
PortInst head, double hX, double hY,
PortInst tail, double tX, double tY) {
// Take the default width if that's what the user wants.
// Otherwise adjust the user-specified width or height by the
// SizeOffset.
if (width==DEF_SIZE) {
width = ap.getDefaultLambdaBaseWidth();
// width = ap.getDefaultLambdaFullWidth();
// } else {
// width += ap.getLambdaWidthOffset();
}
hX = DBMath.round(hX);
hY = DBMath.round(hY);
tX = DBMath.round(tX);
tY = DBMath.round(tY);
width = DBMath.round(width);
ArcInst ai = ArcInst.newInstanceBase(ap, width,
// ArcInst ai = ArcInst.newInstanceFull(ap, width,
head, tail, new Point2D.Double(hX, hY),
new Point2D.Double(tX, tY),
null, 0);
error(ai==null, "newArcInst failed");
ai.setFixedAngle(true);
return ai;
}
/**
* Create a new ArcInst. This differs from ArcInst.newInstance in that
* the "width-offset" is added to the width parameter. The result is an
* ArcInst that the GUI reports is width wide.
*
* <p> Connect the new ArcInst to the centers of the PortInsts.
* If the centers don't share an X or y-coordinate then connect
* the head and the tail using two ArcInsts. The ArcInst attached
* to the head is horizontal and the ArcInst attached to the tail
* is vertical.
* @param ap the head PortInst
* @param width the desired width of the ArcInst
* @param head the head ArcInst
* @param tail the tail ArcInst
* @return the ArcInst connected to the tail.
*/
public static ArcInst newArcInst(ArcProto ap, double width,
PortInst head, PortInst tail) {
EPoint headP = head.getCenter();
double hX = headP.getX(); // roundCenterX(head);
double hY = headP.getY(); // roundCenterY(head);
EPoint tailP = tail.getCenter();
double tX = tailP.getX(); // roundCenterX(tail);
double tY = tailP.getY(); // roundCenterY(tail);
ArcInst ai;
if (hX==tX || hY==tY) {
// no jog necessary
ai = newArcInst(ap, width, head, hX, hY, tail, tX, tY);
} else {
Cell parent = head.getNodeInst().getParent();
NodeProto pinProto = ap.findOverridablePinProto();
PortInst pin = newNodeInst(pinProto, tX, hY, DEF_SIZE, DEF_SIZE, 0,
parent).getOnlyPortInst();
// debug
EPoint pinP = pin.getCenter();
double newX = pinP.getX(); // roundCenterX(pin);
double newY = pinP.getY(); // roundCenterY(pin);
if (newX!=tX || newY!=hY) {
Rectangle2D r = head.getBounds();
double loy = r.getMinY();
double hiy = r.getMaxY();
System.out.println(loy+" "+hiy);
error(true, "center moved");
}
ai = newArcInst(ap, width, head, pin);
ai.setFixedAngle(true);
ai = newArcInst(ap, width, pin, tail);
}
ai.setFixedAngle(true);
return ai;
}
/**
* Create an export for a particular layer.
*
* <p> At the coordinates <code>(x, y)</code> create a NodeInst of
* a layer-pin for the layer <code>ap</code>. Export that
* layer-pin's PortInst.
*
* <p> Attach an ArcInst of ArcProto ap to the layer-pin. The
* ArcInst is useful because Electric uses the widest ArcInst on a
* PortInst as a hint for the width to use for all future
* arcs. Because Electric doesn't use the size of layer-pins as
* width hints, the layer-pin is created in it's default size.
*
* <p> <code>newExport</code> seems very specialized, but it's
* nearly the only one I use when generating layout.
* @param cell the Cell to which to add the Export.
* @param name the name of the Export.
* @param role the Export's type.
* @param ap the ArcProto indicating the layer on which to create
* the Export.
* @param w width of the ArcInst serving as a hint.
* @param x the x-coordinate of the layer pin.
* @param y the y-coordinate of the layer pin.
*/
public static Export newExport(Cell cell, String name,
PortCharacteristic role,
ArcProto ap, double w, double x, double y) {
NodeProto np = ap.findOverridablePinProto();
error(np==null, "LayoutLib.newExport: This layer has no layer-pin");
double defSz = LayoutLib.DEF_SIZE;
NodeInst ni = LayoutLib.newNodeInst(np, x, y, defSz, defSz, 0, cell);
LayoutLib.newArcInst(ap, w, ni.getOnlyPortInst(), ni.getOnlyPortInst());
Export e = Export.newInstance(cell, ni.getOnlyPortInst(), name);
e.setCharacteristic(role);
return e;
}
public static Rectangle2D roundBounds(Rectangle2D r) {
double w = DBMath.round(r.getWidth());
double h = DBMath.round(r.getHeight());
double x = DBMath.round(r.getX());
double y = DBMath.round(r.getY());
return new Rectangle2D.Double(x,y,w,h);
}
/**
* Get the essential or regular bounds. If NodeInst
* <code>node</code> has an Essential Bounds then return
* it. Otherwise return the regular bounds.
* @param node the NodeInst.
* @return the Rectangle2D representing the bounds.
*/
public static Rectangle2D getBounds(NodeInst node) {
Rectangle2D bounds = node.findEssentialBounds();
if (bounds==null) bounds = node.getBounds();
return roundBounds(bounds);
}
/**
* Get the essential or regular bounds. If Cell c has an
* Essential Bounds then return it. Otherwise return the regular
* bounds.
* @param c the Cell.
* @return the Rectangle2D representing the bounds.
*/
public static Rectangle2D getBounds(Cell c) {
Rectangle2D bounds = c.findEssentialBounds();
if (bounds==null) bounds = c.getBounds();
return roundBounds(bounds);
}
// --------------------- Abutment methods ---------------------------------
// There are too many abutment methods. I need to figure out how
// to eliminate some.
/**
* Move NodeInst so it's left edge is at <code>leftX</code> and
* the y-coordinate of it's origin is at
* <code>originY</code>. Don't alter the NodeInst's scale or
* rotation.
* @param node the NodeInst
* @param leftX desired x-coordinate of left edge of <code>node</code>.
* @param originY desired y-coordinate of <code>node</code>'s origin
*/
public static void abutLeft(NodeInst node, double leftX, double originY) {
double cY = getPosition(node).getY();
Rectangle2D bd = node.findEssentialBounds();
error(bd==null,
"can't abut NodeInsts that don't have essential-bounds");
LayoutLib.modNodeInst(node, leftX-bd.getX(), originY-cY, 0, 0, false,
false, 0);
}
/**
* Abut an array of NodeInsts left to right. Move the 0th NodeInst
* so it's left edge is at <code>leftX</code> and it the
* y-coordinate of its origin is at <code>originY</code>. Abut the
* remaining nodes left to right. Don't alter any NodeInst's
* scale or rotation.
* @param leftX desired x-coordinate of left edge of 0th NodeInst.
* @param originY desired y-coordinate of all NodeInst origins
* @param nodeInsts the ArrayList of NodeInsts.
*/
public static void abutLeftRight(double leftX, double originY,
Collection<NodeInst> nodeInsts) {
NodeInst prev = null;
for (NodeInst ni : nodeInsts) {
if (prev==null) {
abutLeft(ni, leftX, originY);
} else {
abutLeftRight(prev, ni);
}
prev = ni;
}
}
/**
* Abut two NodeInsts left to right. Move <code>rightNode</code>
* so its left edge coincides with <code>leftNode</code>'s right
* edge, and the y-coordinate of <code>rightNode</code>'s is equal
* to the y-coordinate of <code>leftNode</code>'s origin. Don't
* move <code>leftNode</code>. Don't alter any node's scale or
* rotation.
* @param leftNode the NodeInst that doesn't move.
* @param rightNode the NodeInst that is moved to butt against
* leftNode.
*/
public static void abutLeftRight(NodeInst leftNode, NodeInst rightNode) {
abutLeft(rightNode, getBounds(leftNode).getMaxX(),
getPosition(leftNode).getY());
}
/**
* Abut an array of NodeInsts left to right. Don't move the 0th
* node. Abut remaining nodes left to right. Don't alter any
* NodeInst's scale or rotation.
* @param nodeInsts the ArrayList of NodeInsts */
public static void abutLeftRight(Collection<NodeInst> nodeInsts) {
NodeInst prev = null;
for (NodeInst ni : nodeInsts) {
if (prev!=null) abutLeftRight(prev, ni);
prev = ni;
}
}
/** Move a NodeInst so it's bottom edge is at <code>botY</code>.
*
* <p>Place <code>node</code>'s origin at
* <code>originX</code>. Don't alter <code>node</code>'s scale or
* rotation.
* @param node the NodeInst to move
* @param originX desired x-coordinate of NodeInst's origin
* @param botY desired y-coordinate of bottom edge of NodeInst
*/
public static void abutBottom(NodeInst node, double originX, double botY) {
double cX = getPosition(node).getX();
Rectangle2D eb = node.findEssentialBounds();
error(eb==null,
"can't abut a NodeInst that doesn't have Essential Bounds");
LayoutLib.modNodeInst(node, originX-cX, botY-eb.getMinY(), 0, 0,
false, false, 0);
}
/**
* Abut two NodeInsts bottom to top. Move <code>topNode</code> so
* its bottom edge coincides with <code>bottomNode</code>'s top
* edge, and the y-coordinate of <code>topNode</code>'s origin is
* equal to the y-coorinate of <code>bottomNode</code>'s
* origin. Don't move <code>bottomNode</code>. Don't alter any
* node's scale or rotation. */
public static void abutBottomTop(NodeInst bottomNode, double space,
NodeInst topNode) {
abutBottom(topNode, getPosition(bottomNode).getX(),
getBounds(bottomNode).getMaxY()+space);
}
/**
* Abut a list of NodeInsts bottom to top. Move 0th NodeInst so
* it's bottom edge is at botY and it's origin has the
* x-coordinate, originX. Abut remaining nodes bottom to top.
* Don't alter any NodeInst's scale or rotation.
* @param originX desired x-coordinate of all NodeInst reference points.
* Lambda units.
* @param botY desired y-coordinate of bottom edge of first NodeInst.
* @param nodeInsts Collection of NodeInsts to abut.
*/
public static void abutBottomTop(double originX, double botY,
Collection<NodeInst> nodeInsts,
double space) {
NodeInst prev = null;
for (NodeInst ni : nodeInsts) {
if (prev==null){
abutBottom(ni, originX, botY);
} else {
abutBottomTop(prev, space, ni);
}
prev = ni;
}
}
/**
* Abut a list of NodeInsts bottom to top. Don't alter position
* of 0th node. Abut the remaining nodes bottom to top. Don't
* alter any NodeInst's scale or rotation.
* @param nodeInsts the list of NodeInsts to abut.
*/
public static void abutBottomTop(Collection<NodeInst> nodeInsts,
double space) {
NodeInst prev = null;
for (NodeInst ni : nodeInsts) {
if (prev!=null) abutBottomTop(prev, space, ni);
prev = ni;
}
}
private static Point2D getPointAtCorner(NodeInst ni, Corner cnr) {
Rectangle2D b = ni.findEssentialBounds();
double x = (cnr==Corner.TL || cnr==Corner.BL) ?
b.getMinX()
:
b.getMaxX();
double y = (cnr==Corner.BL || cnr==Corner.BR) ?
b.getMinY()
:
b.getMaxY();
return new Point2D.Double(x, y);
}
public static void alignCorners(NodeInst niFixed, Corner cnrFixed,
NodeInst niMove, Corner cnrMove,
double offsetX, double offsetY) {
Point2D ptFixed = getPointAtCorner(niFixed, cnrFixed);
Point2D ptMove = getPointAtCorner(niMove, cnrMove);
double dx = ptFixed.getX() - ptMove.getX() + offsetX;
double dy = ptFixed.getY() - ptMove.getY() + offsetY;
niMove.move(dx, dy);
}
/**
* Get the bounding box for the layer in the Cell.
* Note this does not include geometry from sub-cells.
* @param cell the cell to examine
* @param function the layer's function
* @return a bounding box around all instances of the layer in the cell
*/
public static Rectangle2D getBounds(Cell cell, Layer.Function function) {
Rectangle2D bounds = null;
Technology tech = cell.getTechnology();
Layer.Function.Set thisFunction = new Layer.Function.Set(function);
// get layer from nodes
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
AffineTransform trans = ni.rotateOut();
Poly [] polys = tech.getShapeOfNode(ni, false, true, thisFunction);
if (polys == null) continue;
for (int i=0; i<polys.length; i++) {
if (polys[i] == null) continue;
if (polys[i].getLayer().getFunction() == function)
{
polys[i].transform(trans);
if (bounds == null)
bounds = polys[i].getBox();
else
bounds = bounds.createUnion(polys[i].getBox());
}
}
}
// get layer from arcs
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Poly [] polys = tech.getShapeOfArc(ai, thisFunction);
if (polys == null) continue;
for (int i=0; i<polys.length; i++) {
if (polys[i] == null) continue;
if (polys[i].getLayer().getFunction() == function) {
if (bounds == null)
bounds = polys[i].getBox();
else
bounds = bounds.createUnion(polys[i].getBox());
}
}
}
return bounds;
}
}
| true |
8229da3ff0edb86945e5f9563665383a899d5377 | Java | IvanStephenYuan/JRAP_Lease | /jrap-core/src/main/java/com/jingrui/jrap/testext/dto/UserDemo.java | UTF-8 | 3,717 | 1.765625 | 2 | [] | no_license | /*
* Copyright ZheJiang JingRui Co.,Ltd.
*/
package com.jingrui.jrap.testext.dto;
import java.util.Date;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.jingrui.jrap.core.annotation.MultiLanguage;
import com.jingrui.jrap.core.annotation.MultiLanguageField;
import com.jingrui.jrap.mybatis.annotation.ExtensionAttribute;
import com.jingrui.jrap.system.dto.BaseDTO;
/**
* @author shengyang.zhou@jingrui.com
*/
@MultiLanguage
@Table(name = "sys_user_demo_b")
@ExtensionAttribute(disable = true)
public class UserDemo extends BaseDTO {
public static final String USER_ID = "userId";
public static final String USER_CODE = "userCode";
public static final String USER_NAME = "userName";
public static final String USER_AGE = "userAge";
public static final String USER_SEX = "userSex";
public static final String USER_BIRTH = "userBirth";
public static final String USER_EMAIL = "userEmail";
//public static final String USER_PHONE = "userPhone";
public static final String ENABLE_FLAG = "enableFlag";
public static final String DESCRIPTION = "description";
public static final String ROLE_ID = "roleId";
public static final String ROLE_NAME = "roleName";
public static final String START_ACTIVE_TIME = "startActiveTime";
//public static final String END_ACTIVE_TIME = "endActiveTime";
@Id
@GeneratedValue
public Long getUserId() {
return innerGet(USER_ID);
}
public void setUserId(Long userId) {
innerSet(USER_ID, userId);
}
public String getUserCode() {
return innerGet(USER_CODE);
}
public void setUserCode(String userCode) {
innerSet(USER_CODE, userCode);
}
@MultiLanguageField
public String getUserName() {
return innerGet(USER_NAME);
}
public void setUserName(String userName) {
innerSet(USER_NAME, userName);
}
public String getUserSex() {
return innerGet(USER_SEX);
}
public void setUserSex(String sex) {
innerSet(USER_SEX, sex);
}
public Integer getUserAge() {
return innerGet(USER_AGE);
}
public void setUserAge(Integer userAge) {
innerSet(USER_AGE, userAge);
}
public Date getUserBirth() {
return innerGet(USER_BIRTH);
}
public void setUserBirth(Date userBirth) {
innerSet(USER_BIRTH, userBirth);
}
public String getUserEmail() {
return innerGet(USER_EMAIL);
}
public void setUserEmail(String userEmail) {
innerSet(USER_EMAIL, userEmail);
}
// public String getUserPhone() {
// return innerGet(USER_PHONE);
// }
//
// public void setUserPhone(String userPhone) {
// innerSet(USER_PHONE, userPhone);
// }
@MultiLanguageField
public String getDescription() {
return innerGet(DESCRIPTION);
}
public void setDescription(String description) {
innerSet(DESCRIPTION, description);
}
public String getEnableFlag() {
return innerGet(ENABLE_FLAG);
}
public void setEnableFlag(String enableFlag) {
innerSet(ENABLE_FLAG, enableFlag);
}
public Long getRoleId() {
return innerGet(ROLE_ID);
}
public void setRoleId(Long roleId) {
innerSet(ROLE_ID, roleId);
}
public String getRoleName() {
return innerGet(ROLE_NAME);
}
public void setRoleName(String roleName) {
innerSet(ROLE_NAME, roleName);
}
public Date getStartActiveTime() {
return innerGet(START_ACTIVE_TIME);
}
public void setStartActiveTime(Date date) {
innerSet(START_ACTIVE_TIME, date);
}
}
| true |
a88d51a4e93a05c0db07a1abb6cc613ef757ec28 | Java | kerrimov/modul | /modul1/src/Array/Array_main.java | UTF-8 | 912 | 3.578125 | 4 | [] | no_license | package Array;
import java.util.Scanner;
public class Array_main {
public static void main(String[] args) {
System.out.println("На сколько элементов массив?");
Scanner scr = new Scanner(System.in);
int n = scr.nextInt();
int[] mas = new int[n];
int count = 1;
int j;
for (int i = 0; i < mas.length - 1; i++) {
mas[i] = (int) (Math.random() * n);
}
for (int i = 0; i < mas.length - 1; i++) {
for (j = i + 1; j < mas.length; j++) {
if (mas[i] == mas[j]) {
break;
}
}
if (j == mas.length) {
count++;
}
System.out.print(mas[i] + " ");
System.out.print(" ");
}
System.out.println(" ");
System.out.println("Ответ: " + count);
}
}
| true |
7fd7161e3733d1447cffbdb0b62915a94a44ec3a | Java | woshijunbin/dtzf | /WEB-INF/src/module/map/entity/Fyxxb.java | UTF-8 | 9,276 | 2.078125 | 2 | [] | no_license | package module.map.entity;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author User
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "fyxxb", catalog = "undetermined")
public class Fyxxb implements java.io.Serializable {
@Id
@Column(name = "FYBH", unique = true, nullable = false, length = 50)
private String fybh;
/**
* 所在省份代码
*/
@Column(name = "SZSS")
private Integer szss;
/**
* 所在城市代码
*/
@Column(name = "CS")
private Integer cs;
@Column(name = "QX")
private Integer qx;
@Column(name = "QY")
private Integer qy;
/**
* 房屋位置
*/
@Column(name = "FWZL", length = 500)
private String fwzl;
/**
* 建筑面积
*/
@Column(name = "FWJZMJ", precision = 11)
private BigDecimal fwjzmj;
@Column(name = "FX", length = 100)
private String fx;
/**
* 所在楼层
*/
@Column(name = "SZLC")
private Integer szlc;
@Column(name = "SZZLC")
private Integer szzlc;
@Column(name = "FYCX", length = 100)
private String fycx;
@Column(name = "FWJG", length = 100)
private String fwjg;
@Column(name = "FWYT", length = 100)
private String fwyt;
@Column(name = "ZXCD", length = 100)
private String zxcd;
@Column(name = "FWZS_SBCL", length = 65535)
private String fwzsSbcl;
@Column(name = "FWWG", length = 100)
private String fwwg;
@Column(name = "JGNF")
private Integer jgnf;
@Column(name = "QSLB", length = 100)
private String qslb;
@Column(name = "SYXZ", length = 100)
private String syxz;
@Column(name = "GLFS", length = 50)
private String glfs;
@Column(name = "PTSS", length = 65535)
private String ptss;
@Column(name = "JTXL", length = 65535)
private String jtxl;
@Column(name = "TBSM", length = 65535)
private String tbsm;
@Column(name = "LPSQQK", length = 65535)
private String lpsqqk;
@Column(name = "WGQK", length = 65535)
private String wgqk;
@Column(name = "ZP", length = 800)
private String zp;
@Column(name = "ZPSL")
private Integer zpsl;
@Column(name = "LR_OPERATOR", length = 50)
private String lrOperator;
@Temporal(TemporalType.DATE)
@Column(name = "OPERATOR_DATE", length = 10)
private Date operatorDate;
/**
* 纬度
*/
@Column(name = "LNG", length = 50)
private String lng;
/**
* 经度
*/
@Column(name = "LAT", length = 50)
private String lat;
public Fyxxb() {
}
public Fyxxb(String fybh) {
this.fybh = fybh;
}
public Fyxxb(String fybh, Integer szss, Integer cs, Integer qx, Integer qy, String fwzl, BigDecimal fwjzmj,
String fx, Integer szlc, Integer szzlc, String fycx, String fwjg, String fwyt, String zxcd, String fwzsSbcl,
String fwwg, Integer jgnf, String qslb, String syxz, String glfs, String ptss, String jtxl, String tbsm,
String lpsqqk, String wgqk, String zp, Integer zpsl, String lrOperator, Date operatorDate, String lng,
String lat) {
this.fybh = fybh;
this.szss = szss;
this.cs = cs;
this.qx = qx;
this.qy = qy;
this.fwzl = fwzl;
this.fwjzmj = fwjzmj;
this.fx = fx;
this.szlc = szlc;
this.szzlc = szzlc;
this.fycx = fycx;
this.fwjg = fwjg;
this.fwyt = fwyt;
this.zxcd = zxcd;
this.fwzsSbcl = fwzsSbcl;
this.fwwg = fwwg;
this.jgnf = jgnf;
this.qslb = qslb;
this.syxz = syxz;
this.glfs = glfs;
this.ptss = ptss;
this.jtxl = jtxl;
this.tbsm = tbsm;
this.lpsqqk = lpsqqk;
this.wgqk = wgqk;
this.zp = zp;
this.zpsl = zpsl;
this.lrOperator = lrOperator;
this.operatorDate = operatorDate;
this.lng = lng;
this.lat = lat;
}
public String getFybh() {
return this.fybh;
}
public void setFybh(String fybh) {
this.fybh = fybh;
}
public Integer getSzss() {
return this.szss;
}
public void setSzss(Integer szss) {
this.szss = szss;
}
public Integer getCs() {
return this.cs;
}
public void setCs(Integer cs) {
this.cs = cs;
}
public Integer getQx() {
return this.qx;
}
public void setQx(Integer qx) {
this.qx = qx;
}
public Integer getQy() {
return this.qy;
}
public void setQy(Integer qy) {
this.qy = qy;
}
public String getFwzl() {
return this.fwzl;
}
public void setFwzl(String fwzl) {
this.fwzl = fwzl;
}
public BigDecimal getFwjzmj() {
return this.fwjzmj;
}
public void setFwjzmj(BigDecimal fwjzmj) {
this.fwjzmj = fwjzmj;
}
public String getFx() {
return this.fx;
}
public void setFx(String fx) {
this.fx = fx;
}
public Integer getSzlc() {
return this.szlc;
}
public void setSzlc(Integer szlc) {
this.szlc = szlc;
}
public Integer getSzzlc() {
return this.szzlc;
}
public void setSzzlc(Integer szzlc) {
this.szzlc = szzlc;
}
public String getFycx() {
return this.fycx;
}
public void setFycx(String fycx) {
this.fycx = fycx;
}
public String getFwjg() {
return this.fwjg;
}
public void setFwjg(String fwjg) {
this.fwjg = fwjg;
}
public String getFwyt() {
return this.fwyt;
}
public void setFwyt(String fwyt) {
this.fwyt = fwyt;
}
public String getZxcd() {
return this.zxcd;
}
public void setZxcd(String zxcd) {
this.zxcd = zxcd;
}
public String getFwzsSbcl() {
return this.fwzsSbcl;
}
public void setFwzsSbcl(String fwzsSbcl) {
this.fwzsSbcl = fwzsSbcl;
}
public String getFwwg() {
return this.fwwg;
}
public void setFwwg(String fwwg) {
this.fwwg = fwwg;
}
public Integer getJgnf() {
return this.jgnf;
}
public void setJgnf(Integer jgnf) {
this.jgnf = jgnf;
}
public String getQslb() {
return this.qslb;
}
public void setQslb(String qslb) {
this.qslb = qslb;
}
public String getSyxz() {
return this.syxz;
}
public void setSyxz(String syxz) {
this.syxz = syxz;
}
public String getGlfs() {
return this.glfs;
}
public void setGlfs(String glfs) {
this.glfs = glfs;
}
public String getPtss() {
return this.ptss;
}
public void setPtss(String ptss) {
this.ptss = ptss;
}
public String getJtxl() {
return this.jtxl;
}
public void setJtxl(String jtxl) {
this.jtxl = jtxl;
}
public String getTbsm() {
return this.tbsm;
}
public void setTbsm(String tbsm) {
this.tbsm = tbsm;
}
public String getLpsqqk() {
return this.lpsqqk;
}
public void setLpsqqk(String lpsqqk) {
this.lpsqqk = lpsqqk;
}
public String getWgqk() {
return this.wgqk;
}
public void setWgqk(String wgqk) {
this.wgqk = wgqk;
}
public String getZp() {
return this.zp;
}
public void setZp(String zp) {
this.zp = zp;
}
public Integer getZpsl() {
return this.zpsl;
}
public void setZpsl(Integer zpsl) {
this.zpsl = zpsl;
}
public String getLrOperator() {
return this.lrOperator;
}
public void setLrOperator(String lrOperator) {
this.lrOperator = lrOperator;
}
public Date getOperatorDate() {
return this.operatorDate;
}
public void setOperatorDate(Date operatorDate) {
this.operatorDate = operatorDate;
}
public String getLng() {
return this.lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getLat() {
return this.lat;
}
public void setLat(String lat) {
this.lat = lat;
}
}
| true |
310306f77c975269c8710b68078c2a0e805d4700 | Java | SamuelC98/Assignment1Part2 | /src/Vertex.java | UTF-8 | 845 | 2.84375 | 3 | [] | no_license | import java.util.NoSuchElementException;
public class Vertex<Type> {
public Type data;
public EdgeNode firstEdge;
public Vertex(Type d){
data = d;
firstEdge = null;
}
public Vertex() {
}
//set method
public void setData(Type data) {
if(data == "") throw new NoSuchElementException();
this.data = data;
}
//get method
public Type getData() {
return data;
}
public EdgeNode getFirstEdge(){
return firstEdge;
}
//get firstedgedest
public int getFirstEdgeDest(){
return firstEdge.getDest();
}
//get firstedgefee
public int getFirstEdgeFee(){
return firstEdge.getFee();
}
//get firstedgedistance
public int getFirstEdgeDistance(){
return firstEdge.getDistance();
}
} | true |
68322f55afdefe70e115eb2631165cbd5fd8c001 | Java | DiegoJL97/RL-Predictions | /RL-Predictions/src/main/java/diegojl97/rlpredictions/model/User.java | UTF-8 | 3,097 | 2.40625 | 2 | [] | no_license | package diegojl97.rlpredictions.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Entity
public class User implements Comparable<User>{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String username;
private String password;
@ElementCollection(fetch = FetchType.EAGER)
private List<String> roles;
private boolean madeNAPrediction;
@OneToOne(fetch=FetchType.EAGER)
private Prediction naPrediction;
private boolean madeEUPrediction;
@OneToOne(fetch=FetchType.EAGER)
private Prediction euPrediction;
private Integer points;
private Integer position;
public User() {
super();
}
public User(String username, String password) {
super();
this.username = username;
this.password = new BCryptPasswordEncoder().encode(password);
ArrayList<String> userRoles = new ArrayList<>();
userRoles.add("ROLE_USER");
this.roles = userRoles;
this.madeNAPrediction = false;
this.madeEUPrediction = false;
this.points = 0;
this.position = -1;
}
public User(String username, String password, List<String> roles) {
super();
this.username = username;
this.password = new BCryptPasswordEncoder().encode(password);
this.roles = roles;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
public boolean isMadeNAPrediction() {
return madeNAPrediction;
}
public void setMadeNAPrediction(boolean madeNAPrediction) {
this.madeNAPrediction = madeNAPrediction;
}
public Prediction getNaPrediction() {
return naPrediction;
}
public void setNaPrediction(Prediction naPrediction) {
this.naPrediction = naPrediction;
}
public boolean isMadeEUPrediction() {
return madeEUPrediction;
}
public void setMadeEUPrediction(boolean madeEUPrediction) {
this.madeEUPrediction = madeEUPrediction;
}
public Prediction getEuPrediction() {
return euPrediction;
}
public void setEuPrediction(Prediction euPrediction) {
this.euPrediction = euPrediction;
}
public Integer getPoints() {
return points;
}
public void setPoints(Integer points) {
this.points = points;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
@Override
public int compareTo(User arg0) {
return this.points - arg0.getPoints();
}
}
| true |
451cce57432a9b60409ba5221c72037f97707f99 | Java | javaljj/algorithm | /src/leetcode/array/字符串中的第一个唯一字符.java | UTF-8 | 664 | 3.5 | 4 | [] | no_license | package leetcode.array;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class 字符串中的第一个唯一字符 {
public int firstUniqChar(String s) {
Map<Character, Integer> maps = new LinkedHashMap<>();
for (int i = 0; i < s.length(); i++) {
maps.put(s.charAt(i), maps.getOrDefault(s.charAt(i), 0) + 1);
}
Set<Map.Entry<Character, Integer>> entries = maps.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
if(entry.getValue() == 1){
return s.indexOf(entry.getKey());
}
}
return -1;
}
}
| true |
fb4d2d280f7fafb68d69e80b0c81be0e56d437ed | Java | ShmulikChicvashvili/webcourse | /project/src/com/technion/coolie/ug/Server/ServerCourseToTrack.java | UTF-8 | 1,146 | 2.359375 | 2 | [] | no_license | package com.technion.coolie.ug.Server;
import java.util.List;
import com.technion.coolie.ug.model.Semester;
public class ServerCourseToTrack {
int id;
String courseId;
Semester semester;
List<String> trackingStudents;
int freePlaces;
public ServerCourseToTrack(final String courseId, final Semester semester,
final List<String> trackingStudents, final int freePlaces) {
super();
this.courseId = courseId;
this.semester = semester;
this.trackingStudents = trackingStudents;
this.freePlaces = freePlaces;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(final String courseId) {
this.courseId = courseId;
}
public Semester getSemester() {
return semester;
}
public void setSemester(final Semester semester) {
this.semester = semester;
}
public List<String> getTrackingStudents() {
return trackingStudents;
}
public void setTrackingStudents(final List<String> trackingStudents) {
this.trackingStudents = trackingStudents;
}
public int getFreePlaces() {
return freePlaces;
}
public void setFreePlaces(final int freePlaces) {
this.freePlaces = freePlaces;
}
}
| true |
0dec109d6664ab8d33499cb9796524d976f384b6 | Java | lrchao/FakeJob | /library/src/main/java/com/lrchao/fakejob/ui/activity/register/RegisterContract.java | UTF-8 | 443 | 1.851563 | 2 | [] | no_license | package com.lrchao.fakejob.ui.activity.register;
import com.lrchao.fakejob.mvp.MvpView;
/**
* Description:
*
* @author lrc19860926@gmail.com
* @date 2017/6/26 下午2:34
*/
public interface RegisterContract {
interface View extends MvpView {
void showToast(CharSequence s);
void finishPage();
}
interface Presenter {
void register(CharSequence phoneNumber, CharSequence code, CharSequence password);
}
}
| true |
2f976832f8519ea6c8f2fb351511f09faee4ceda | Java | xiaotdl/CodingInterview | /LeetCode/java/src/fibonacci/Solution.java | UTF-8 | 856 | 3.796875 | 4 | [] | no_license | package fibonacci;
/**
* Created by Xiaotian on 12/13/17.
*/
public class Solution {
// tag: math, dp, iterative
// time: O(n)
// space: O(1)
/*
* @param n: an integer
* @return: an integer f(n)
*/
public int fibonacci(int n) {
int a = 0;
int b = 1;
for (int i = 0; i < n - 1; i++) {
int c = a + b;
a = b;
b = c;
}
return a;
}
}
class SolutionII {
// Same as Solution
/*
* @param n: an integer
* @return: an ineger f(n)
*/
public int fibonacci(int n) {
if (n == 1) return 0;
if (n == 2) return 1;
int a = 0;
int b = 1;
int c = 0;
for (int i = 0; i < n - 2; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
| true |
c71c2bad3ce282760bb21eb1fe451c77eea78081 | Java | snsdTJ/order_dish | /src/com/example/orderservice/dao/OrderDetailDao.java | GB18030 | 5,492 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | /************************************************************
* Ȩ (c)2011, hxf<p>
* ļ TableInfoDao.java<p>
*
* ʱ 20151016 4:20:33
* ǰ汾ţv1.0
************************************************************/
package com.example.orderservice.dao;
import java.util.ArrayList;
import java.util.List;
import com.example.orderservice.model.OrderBean;
import com.example.orderservice.model.OrderDetailBean;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.UrlQuerySanitizer.ValueSanitizer;
/************************************************************
* ժҪ <p>
*
* hxf
* ʱ 20151016 4:20:33
* ǰ汾ţv1.0
* ʷ¼ :
* : 20151016 4:20:33 ˣ
* :
************************************************************/
public class OrderDetailDao {
private Context context;
/*
* ݿ
*/
public static final String DB_NAME = "orderdish";
/*
*
*/
public static final String TABLE_NAME = "T_ORDER_DETAIL";
/*
* ݿ汾
*/
public static final int VERSION = 1;
private static OrderDetailDao orderDetailDao;
private SQLiteDatabase db;
/*
* 췽˽л,ʵֵģʽ
* ʵʱContextҪõ
*/
private OrderDetailDao(Context context){
MyDatabaseHelper dbHelper = new MyDatabaseHelper(context, DB_NAME, null, VERSION);
db = dbHelper.getWritableDatabase();
this.context = context;
}
/*
* ȡOrderDetailDaoʵ
*/
public synchronized static OrderDetailDao getInstance(Context context){
if (orderDetailDao == null) {
orderDetailDao = new OrderDetailDao(context);
}
return orderDetailDao;
}
//CRUD------------------------------------------------
/*
* OrderDetailBeanʵT_ORDER_DETAIL
*/
public long saveOrderDetailBean(OrderDetailBean orderDetailBean){
long newRow = 0;
if (orderDetailBean != null) {
ContentValues values = new ContentValues();
values.put("ORDER_ID", orderDetailBean.getOrderId());
values.put("DISH_INFO_ID", orderDetailBean.getDishInfoId());
values.put("CURRENT_PRICE", orderDetailBean.getCurrentPrice());
values.put("DISH_NUMBER", orderDetailBean.getDishNumber());
newRow = db.insert(TABLE_NAME, null, values);
}
return newRow;
}
/*
* ָOrderDetailBeanӱɾ
*/
public boolean deleteOrderDetailBean(OrderDetailBean orderDetailBean){
if (orderDetailBean != null) {
int id = orderDetailBean.getId();
db.delete(TABLE_NAME, "ID = ?", new String[]{String.valueOf(id)});
return true;
}
return false;
}
/*
* ָORDER_IDдӱɾ//ORDER_IDT_ORDERеIDֶ
*/
public boolean deleteOrderDetailBean(int orderId){
if (orderId != 0) {
db.delete(TABLE_NAME, "ORDER_ID = ?", new String[]{String.valueOf(orderId)});
return true;
}
return false;
}
/*
* ָIDֵϢ
*/
public boolean modifyOrderDetailBean(OrderDetailBean orderDetailBean){
if (orderDetailBean != null) {
int id = orderDetailBean.getId();
ContentValues values = new ContentValues();
values.put("ORDER_ID", orderDetailBean.getOrderId());
values.put("DISH_INFO_ID", orderDetailBean.getDishInfoId());
values.put("CURRENT_PRICE", orderDetailBean.getCurrentPrice());
values.put("DISH_NUMBER", orderDetailBean.getDishNumber());
db.update(TABLE_NAME, values, "ID = ?", new String[]{String.valueOf(id)});
return true;
}
return false;
}
/*
* ȡOrderDetailBeanʵ
*/
public List<OrderDetailBean> loadOrderDetailBean(){
List<OrderDetailBean> list = new ArrayList<OrderDetailBean>();
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
OrderDetailBean orderDetailBean = new OrderDetailBean();
orderDetailBean.setId(cursor.getInt(cursor.getColumnIndex("ID")));
orderDetailBean.setOrderId(cursor.getInt(cursor.getColumnIndex("ORDER_ID")));
orderDetailBean.setDishInfoId(cursor.getInt(cursor.getColumnIndex("DISH_INFO_ID")));
orderDetailBean.setCurrentPrice(cursor.getFloat(cursor.getColumnIndex("CURRENT_PRICE")));
orderDetailBean.setDishNumber(cursor.getInt(cursor.getColumnIndex("DISH_NUMBER")));
//ѯDISH_INFO_IDӦ
int dishInfoId = cursor.getInt(cursor.getColumnIndex("DISH_INFO_ID"));
Cursor cursorDishInfoId = db.query("T_DISH_INFO", new String[]{"NAME"}, "ID = ?",
new String[]{String.valueOf(dishInfoId)}, null, null, null);
if (cursorDishInfoId.moveToNext()) {
orderDetailBean.setDishName(cursorDishInfoId.getString(cursorDishInfoId.getColumnIndex("NAME")));
}
cursorDishInfoId.close();
//ѯORDER_IDӦT_ORDERָID,
//ORDER_ID -- T_ORDER -- ID
int orderId = cursor.getInt(cursor.getColumnIndex("ORDER_ID"));
OrderBean orderBean = OrderDao.getInstance(context).getOrderBean(orderId);
orderDetailBean.setOrderBean(orderBean);
list.add(orderDetailBean);
} while (cursor.moveToNext());
}
return list;
}
}
| true |
68bf09e073b033d96806371e8fb7816bf0c58d32 | Java | Choukouali2014/CMSC-204 | /Thread Lab/CarQueue.java | UTF-8 | 845 | 3.109375 | 3 | [] | no_license | import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class CarQueue{
private Queue<Integer> queue;
private Random rdm = new Random();
public CarQueue() {
queue = new LinkedList<Integer>();
queue.add(rdm.nextInt(4));
queue.add(rdm.nextInt(4));
queue.add(rdm.nextInt(4));
queue.add(rdm.nextInt(4));
queue.add(rdm.nextInt(4));
queue.add(rdm.nextInt(4));
}
public void addToQueue() {
class addRunnable implements Runnable {
@Override
public void run() {
try {
while(true) {
queue.add(rdm.nextInt(4));
Thread.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
addRunnable run = new addRunnable();
Thread thread = new Thread(run);
thread.start();
}
public int deleteQueue() {
return queue.remove();
}
}
| true |