blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
a9c74c9f2dd514229e4443eef5dc828115b9c511
11,630,771,439,853
c01880cef40072b1de27cc5cbba1a7bfbce3b124
/LearningRendering/src/learningrendering/Display.java
19b5b8abe3bedd4d6a879ebc9dd1db7613132031
[]
no_license
CraigR8806/JavaNetBeans
https://github.com/CraigR8806/JavaNetBeans
49def8b4df883a76f9ddf3fe844bd56626da09c7
b2351860960b72d3ac7ebcc09f4b6681f536372a
refs/heads/master
2016-08-13T01:38:11.264000
2016-02-19T23:21:14
2016-02-19T23:21:14
51,473,089
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package learningrendering; import java.awt.Canvas; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Point; import java.awt.Toolkit; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import javax.swing.JFrame; import learningrendering.graphics.Screen; import learningrendering.userinput.InputHandler; public class Display extends Canvas implements Runnable{ private boolean FPS = false; public static boolean PosDebug = true; public static boolean Collision = false; private Game game; private Screen screen; private BufferedImage img; private int[] pixels; public int time; public int Width; public int Height; private InputHandler input; private int newMouseX = 0; private int oldMouseX = 0; public static boolean Left = false; public static boolean Right = false; private Thread thread; private boolean running = false; public Screen getScreen(){ return screen; } public BufferedImage getImg(){ return img; } public int[] getPixels(){ return pixels; } public void setScreen(Screen screen){ this.screen = screen; } public void setImg(BufferedImage img){ this.img = img; } public void setPixels(int[] pixels){ this.pixels = pixels; } public void setPixelsE(int pixel, int indx){ pixels[indx] = pixel; } public static void main(String[] args) { JFrame frame = new JFrame(); Display disp = new Display(800, 600); frame.add(disp); frame.requestFocus(); frame.pack(); frame.setSize(disp.Width, disp.Height); BufferedImage cursor = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); Cursor blank = Toolkit.getDefaultToolkit().createCustomCursor(cursor,new Point(0,0), "blank"); frame.setCursor(blank); frame.setVisible(true); disp.start(); } Display(int width, int height){ time = 0; Width = width; Height = height; game = new Game(); screen = new Screen(Height, Width); img = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_RGB); pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData(); input = new InputHandler(); addKeyListener(input); addFocusListener(input); addMouseListener(input); addMouseMotionListener(input); } public void start(){ if(running) return; running = true; thread = new Thread(this); thread.start(); } @Override public synchronized void run(){ int frames = 0; double unProcessed = 0.0; long previousTime = System.nanoTime(); double secondsPerTick = 1/60.0; int tickCount = 0; boolean ticked = false; while (running){ long currentTime = System.nanoTime(); long passedTime = currentTime - previousTime; previousTime = currentTime; unProcessed += passedTime / 1000000000.0; while(unProcessed > secondsPerTick){ unProcessed -= secondsPerTick; ticked = true; tickCount++; if(tickCount % 60 == 0){ if(FPS)System.out.println(frames + " fps"); previousTime += 1000; frames = 0; } } if(ticked){ render(); frames++; } //render(); frames++; tick(); requestFocus(); newMouseX = InputHandler.MouseX; if(newMouseX > oldMouseX){ Right = true; } if(newMouseX < oldMouseX){ Left = true; } if(newMouseX == oldMouseX){ Right = false; Left = false; } oldMouseX = newMouseX; } } public synchronized void stop(){ if(!running) return; running = false; try { thread.join(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } public void tick() { game.tock(input.key); } public void render() { BufferStrategy bs = getBufferStrategy(); if(bs == null){ createBufferStrategy(3); return; } screen.render(game); System.arraycopy(screen.pixels, 0, pixels, 0, Width*Height); Graphics g = bs.getDrawGraphics(); g.drawImage(img, 0, 0, Width, Height, null); g.dispose(); bs.show(); } }
UTF-8
Java
5,073
java
Display.java
Java
[]
null
[]
package learningrendering; import java.awt.Canvas; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Point; import java.awt.Toolkit; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import javax.swing.JFrame; import learningrendering.graphics.Screen; import learningrendering.userinput.InputHandler; public class Display extends Canvas implements Runnable{ private boolean FPS = false; public static boolean PosDebug = true; public static boolean Collision = false; private Game game; private Screen screen; private BufferedImage img; private int[] pixels; public int time; public int Width; public int Height; private InputHandler input; private int newMouseX = 0; private int oldMouseX = 0; public static boolean Left = false; public static boolean Right = false; private Thread thread; private boolean running = false; public Screen getScreen(){ return screen; } public BufferedImage getImg(){ return img; } public int[] getPixels(){ return pixels; } public void setScreen(Screen screen){ this.screen = screen; } public void setImg(BufferedImage img){ this.img = img; } public void setPixels(int[] pixels){ this.pixels = pixels; } public void setPixelsE(int pixel, int indx){ pixels[indx] = pixel; } public static void main(String[] args) { JFrame frame = new JFrame(); Display disp = new Display(800, 600); frame.add(disp); frame.requestFocus(); frame.pack(); frame.setSize(disp.Width, disp.Height); BufferedImage cursor = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); Cursor blank = Toolkit.getDefaultToolkit().createCustomCursor(cursor,new Point(0,0), "blank"); frame.setCursor(blank); frame.setVisible(true); disp.start(); } Display(int width, int height){ time = 0; Width = width; Height = height; game = new Game(); screen = new Screen(Height, Width); img = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_RGB); pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData(); input = new InputHandler(); addKeyListener(input); addFocusListener(input); addMouseListener(input); addMouseMotionListener(input); } public void start(){ if(running) return; running = true; thread = new Thread(this); thread.start(); } @Override public synchronized void run(){ int frames = 0; double unProcessed = 0.0; long previousTime = System.nanoTime(); double secondsPerTick = 1/60.0; int tickCount = 0; boolean ticked = false; while (running){ long currentTime = System.nanoTime(); long passedTime = currentTime - previousTime; previousTime = currentTime; unProcessed += passedTime / 1000000000.0; while(unProcessed > secondsPerTick){ unProcessed -= secondsPerTick; ticked = true; tickCount++; if(tickCount % 60 == 0){ if(FPS)System.out.println(frames + " fps"); previousTime += 1000; frames = 0; } } if(ticked){ render(); frames++; } //render(); frames++; tick(); requestFocus(); newMouseX = InputHandler.MouseX; if(newMouseX > oldMouseX){ Right = true; } if(newMouseX < oldMouseX){ Left = true; } if(newMouseX == oldMouseX){ Right = false; Left = false; } oldMouseX = newMouseX; } } public synchronized void stop(){ if(!running) return; running = false; try { thread.join(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } public void tick() { game.tock(input.key); } public void render() { BufferStrategy bs = getBufferStrategy(); if(bs == null){ createBufferStrategy(3); return; } screen.render(game); System.arraycopy(screen.pixels, 0, pixels, 0, Width*Height); Graphics g = bs.getDrawGraphics(); g.drawImage(img, 0, 0, Width, Height, null); g.dispose(); bs.show(); } }
5,073
0.52809
0.518628
200
24.360001
17.006775
102
false
false
0
0
0
0
0
0
0.635
false
false
2
392c48e9b103294f6369eb33be85b5b7347b4c0c
6,897,717,478,967
9a4ada67fbc396755a60b4396870edf745efc06c
/src/main/java/cofh/core/block/entity/SignalAirTile.java
ad9f020bd1fac1d8eb112f555f641507d28c9b6f
[]
no_license
CoFH/CoFHCore
https://github.com/CoFH/CoFHCore
84557be8d694b7773f005f2115607fac46046ae0
93e059978078e9f7753af2b131d6aabac9ac1c66
refs/heads/1.19.x
2023-08-31T10:57:17.637000
2023-08-24T05:01:43
2023-08-24T05:01:43
25,320,478
148
159
null
null
null
null
null
null
null
null
null
null
null
null
null
package cofh.core.block.entity; import cofh.lib.api.block.entity.ITickableTile; import cofh.lib.util.helpers.MathHelper; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import static cofh.core.init.CoreTileEntities.SIGNAL_AIR_TILE; public class SignalAirTile extends BlockEntity implements ITickableTile { protected int duration = 200; protected int power = 15; public SignalAirTile(BlockPos pos, BlockState state) { super(SIGNAL_AIR_TILE.get(), pos, state); } @Override public void tick() { if (level == null) { return; } if (--duration <= 0) { this.level.setBlockAndUpdate(worldPosition, Blocks.AIR.defaultBlockState()); this.level.removeBlockEntity(this.worldPosition); this.setRemoved(); } } public int getDuration() { return duration; } public int getPower() { return power; } public void setDuration(int duration) { this.duration = duration; } public void setPower(int power) { this.power = MathHelper.clamp(power, 0, 15); } }
UTF-8
Java
1,281
java
SignalAirTile.java
Java
[]
null
[]
package cofh.core.block.entity; import cofh.lib.api.block.entity.ITickableTile; import cofh.lib.util.helpers.MathHelper; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import static cofh.core.init.CoreTileEntities.SIGNAL_AIR_TILE; public class SignalAirTile extends BlockEntity implements ITickableTile { protected int duration = 200; protected int power = 15; public SignalAirTile(BlockPos pos, BlockState state) { super(SIGNAL_AIR_TILE.get(), pos, state); } @Override public void tick() { if (level == null) { return; } if (--duration <= 0) { this.level.setBlockAndUpdate(worldPosition, Blocks.AIR.defaultBlockState()); this.level.removeBlockEntity(this.worldPosition); this.setRemoved(); } } public int getDuration() { return duration; } public int getPower() { return power; } public void setDuration(int duration) { this.duration = duration; } public void setPower(int power) { this.power = MathHelper.clamp(power, 0, 15); } }
1,281
0.659641
0.652615
55
22.290909
23.071173
88
false
false
0
0
0
0
0
0
0.454545
false
false
2
c3e22eb9b42597cf4def182ce47b3145264be3cd
8,229,157,370,099
4cfda4f1b4d7703e1b460359012082c158103476
/miliconvert/xsmt/trunk/plugins/org.miliconvert.xsmt.mpgt/src/mpia/schema/impl/TypeContenuTextuelImpl.java
0733864cc81ff35b1a6cda8c2766993c8aba9611
[]
no_license
opensourcejavadeveloper/military_xml_project_miliconvert
https://github.com/opensourcejavadeveloper/military_xml_project_miliconvert
e62dee54499fdb8abaa76a9d44ed97ace19dc887
bb0276970c243ec3acc07fd4b255673d6d7dd080
refs/heads/master
2022-01-10T18:11:39.021000
2018-08-20T12:45:02
2018-08-20T12:45:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * <copyright> * </copyright> * * $Id$ */ package mpia.schema.impl; import mpia.schema.SchemaPackage; import mpia.schema.TypeContenuTextuel; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Type Contenu Textuel</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link mpia.schema.impl.TypeContenuTextuelImpl#getTexte <em>Texte</em>}</li> * <li>{@link mpia.schema.impl.TypeContenuTextuelImpl#getCTE <em>CTE</em>}</li> * <li>{@link mpia.schema.impl.TypeContenuTextuelImpl#getCE <em>CE</em>}</li> * </ul> * </p> * * @generated */ public class TypeContenuTextuelImpl extends EObjectImpl implements TypeContenuTextuel { /** * The default value of the '{@link #getTexte() <em>Texte</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTexte() * @generated * @ordered */ protected static final String TEXTE_EDEFAULT = null; /** * The cached value of the '{@link #getTexte() <em>Texte</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTexte() * @generated * @ordered */ protected String texte = TEXTE_EDEFAULT; /** * The default value of the '{@link #getCTE() <em>CTE</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCTE() * @generated * @ordered */ protected static final String CTE_EDEFAULT = null; /** * The cached value of the '{@link #getCTE() <em>CTE</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCTE() * @generated * @ordered */ protected String cTE = CTE_EDEFAULT; /** * The default value of the '{@link #getCE() <em>CE</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCE() * @generated * @ordered */ protected static final String CE_EDEFAULT = null; /** * The cached value of the '{@link #getCE() <em>CE</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCE() * @generated * @ordered */ protected String cE = CE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TypeContenuTextuelImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return SchemaPackage.eINSTANCE.getTypeContenuTextuel(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getTexte() { return texte; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTexte(String newTexte) { String oldTexte = texte; texte = newTexte; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SchemaPackage.TYPE_CONTENU_TEXTUEL__TEXTE, oldTexte, texte)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getCTE() { return cTE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCTE(String newCTE) { String oldCTE = cTE; cTE = newCTE; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SchemaPackage.TYPE_CONTENU_TEXTUEL__CTE, oldCTE, cTE)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getCE() { return cE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCE(String newCE) { String oldCE = cE; cE = newCE; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SchemaPackage.TYPE_CONTENU_TEXTUEL__CE, oldCE, cE)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SchemaPackage.TYPE_CONTENU_TEXTUEL__TEXTE: return getTexte(); case SchemaPackage.TYPE_CONTENU_TEXTUEL__CTE: return getCTE(); case SchemaPackage.TYPE_CONTENU_TEXTUEL__CE: return getCE(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SchemaPackage.TYPE_CONTENU_TEXTUEL__TEXTE: setTexte((String)newValue); return; case SchemaPackage.TYPE_CONTENU_TEXTUEL__CTE: setCTE((String)newValue); return; case SchemaPackage.TYPE_CONTENU_TEXTUEL__CE: setCE((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SchemaPackage.TYPE_CONTENU_TEXTUEL__TEXTE: setTexte(TEXTE_EDEFAULT); return; case SchemaPackage.TYPE_CONTENU_TEXTUEL__CTE: setCTE(CTE_EDEFAULT); return; case SchemaPackage.TYPE_CONTENU_TEXTUEL__CE: setCE(CE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SchemaPackage.TYPE_CONTENU_TEXTUEL__TEXTE: return TEXTE_EDEFAULT == null ? texte != null : !TEXTE_EDEFAULT.equals(texte); case SchemaPackage.TYPE_CONTENU_TEXTUEL__CTE: return CTE_EDEFAULT == null ? cTE != null : !CTE_EDEFAULT.equals(cTE); case SchemaPackage.TYPE_CONTENU_TEXTUEL__CE: return CE_EDEFAULT == null ? cE != null : !CE_EDEFAULT.equals(cE); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (texte: "); result.append(texte); result.append(", cTE: "); result.append(cTE); result.append(", cE: "); result.append(cE); result.append(')'); return result.toString(); } } //TypeContenuTextuelImpl
UTF-8
Java
6,320
java
TypeContenuTextuelImpl.java
Java
[]
null
[]
/** * <copyright> * </copyright> * * $Id$ */ package mpia.schema.impl; import mpia.schema.SchemaPackage; import mpia.schema.TypeContenuTextuel; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Type Contenu Textuel</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link mpia.schema.impl.TypeContenuTextuelImpl#getTexte <em>Texte</em>}</li> * <li>{@link mpia.schema.impl.TypeContenuTextuelImpl#getCTE <em>CTE</em>}</li> * <li>{@link mpia.schema.impl.TypeContenuTextuelImpl#getCE <em>CE</em>}</li> * </ul> * </p> * * @generated */ public class TypeContenuTextuelImpl extends EObjectImpl implements TypeContenuTextuel { /** * The default value of the '{@link #getTexte() <em>Texte</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTexte() * @generated * @ordered */ protected static final String TEXTE_EDEFAULT = null; /** * The cached value of the '{@link #getTexte() <em>Texte</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTexte() * @generated * @ordered */ protected String texte = TEXTE_EDEFAULT; /** * The default value of the '{@link #getCTE() <em>CTE</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCTE() * @generated * @ordered */ protected static final String CTE_EDEFAULT = null; /** * The cached value of the '{@link #getCTE() <em>CTE</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCTE() * @generated * @ordered */ protected String cTE = CTE_EDEFAULT; /** * The default value of the '{@link #getCE() <em>CE</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCE() * @generated * @ordered */ protected static final String CE_EDEFAULT = null; /** * The cached value of the '{@link #getCE() <em>CE</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCE() * @generated * @ordered */ protected String cE = CE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TypeContenuTextuelImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return SchemaPackage.eINSTANCE.getTypeContenuTextuel(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getTexte() { return texte; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTexte(String newTexte) { String oldTexte = texte; texte = newTexte; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SchemaPackage.TYPE_CONTENU_TEXTUEL__TEXTE, oldTexte, texte)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getCTE() { return cTE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCTE(String newCTE) { String oldCTE = cTE; cTE = newCTE; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SchemaPackage.TYPE_CONTENU_TEXTUEL__CTE, oldCTE, cTE)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getCE() { return cE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCE(String newCE) { String oldCE = cE; cE = newCE; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SchemaPackage.TYPE_CONTENU_TEXTUEL__CE, oldCE, cE)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SchemaPackage.TYPE_CONTENU_TEXTUEL__TEXTE: return getTexte(); case SchemaPackage.TYPE_CONTENU_TEXTUEL__CTE: return getCTE(); case SchemaPackage.TYPE_CONTENU_TEXTUEL__CE: return getCE(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SchemaPackage.TYPE_CONTENU_TEXTUEL__TEXTE: setTexte((String)newValue); return; case SchemaPackage.TYPE_CONTENU_TEXTUEL__CTE: setCTE((String)newValue); return; case SchemaPackage.TYPE_CONTENU_TEXTUEL__CE: setCE((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SchemaPackage.TYPE_CONTENU_TEXTUEL__TEXTE: setTexte(TEXTE_EDEFAULT); return; case SchemaPackage.TYPE_CONTENU_TEXTUEL__CTE: setCTE(CTE_EDEFAULT); return; case SchemaPackage.TYPE_CONTENU_TEXTUEL__CE: setCE(CE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SchemaPackage.TYPE_CONTENU_TEXTUEL__TEXTE: return TEXTE_EDEFAULT == null ? texte != null : !TEXTE_EDEFAULT.equals(texte); case SchemaPackage.TYPE_CONTENU_TEXTUEL__CTE: return CTE_EDEFAULT == null ? cTE != null : !CTE_EDEFAULT.equals(cTE); case SchemaPackage.TYPE_CONTENU_TEXTUEL__CE: return CE_EDEFAULT == null ? cE != null : !CE_EDEFAULT.equals(cE); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (texte: "); result.append(texte); result.append(", cTE: "); result.append(cTE); result.append(", cE: "); result.append(cE); result.append(')'); return result.toString(); } } //TypeContenuTextuelImpl
6,320
0.620886
0.620886
275
21.981817
21.793152
118
false
false
0
0
0
0
0
0
1.523636
false
false
2
37788047bc672984e516c4fb5d855f755591911a
27,195,732,985,696
d58b100a55f681b8b26fabb47ffc440d212161e7
/app/src/main/java/a315i/youcai/Activity/MoreInfoActivity.java
52262b926680f6baa5693735519c563c43b81e81
[]
no_license
lanyuzx/android-app
https://github.com/lanyuzx/android-app
48fc72f4af3304c14b3015aebe24f7a239167430
a94bcebf4746153b2adc8a2ffd78121fc9ab7d4e
refs/heads/master
2020-12-02T22:47:49.612000
2017-07-18T03:20:26
2017-07-18T03:20:26
96,183,555
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package a315i.youcai.Activity; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import a315i.youcai.R; public class MoreInfoActivity extends AppCompatActivity implements View.OnClickListener { private LinearLayout mLinearLayout; private String[] item_titles = { "设置密码", "客服电话", "使用帮助", "拼团流程", "问题反馈", "关于有菜" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_moreinfo); findViewById(R.id.moreInfo_backIv).setOnClickListener(this); mLinearLayout = (LinearLayout) findViewById(R.id.moreInfo_itemLayout); for (int i = 0;i<item_titles.length;i++){ View moreInfoItem = View.inflate(getApplicationContext(),R.layout.moreinfo_item,null ); moreInfoItem.setId(i + 100); moreInfoItem.setOnClickListener(this); TextView item_title = (TextView) moreInfoItem.findViewById(R.id.moreinfo_item_title); item_title.setText(item_titles[i]); mLinearLayout.addView(moreInfoItem); } } @Override public void onClick(View v) { switch (v.getId()){ case R.id.moreInfo_backIv: finish(); break; case 0+ 100: break; case 1+ 100: break; case 2+ 100: setupWebViewActivity("帮助","https://m.youcai.xin/help"); break; case 3+ 100: setupWebViewActivity("拼团流程","https://m.youcai.xin/static/help/group_rule.html"); break; case 4+ 100: Intent intent = new Intent(getApplicationContext(),FeedbackActivity.class); startActivity(intent); break; case 5+ 100: setupWebViewActivity("关于有菜","https://m.youcai.xin/about"); break; } } private void setupWebViewActivity(String title,String url){ Intent intent = new Intent(getApplicationContext(),WebViewActivity.class); intent.putExtra("title",title); intent.putExtra("webViewUrl",url); startActivity(intent); } }
UTF-8
Java
2,538
java
MoreInfoActivity.java
Java
[]
null
[]
package a315i.youcai.Activity; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import a315i.youcai.R; public class MoreInfoActivity extends AppCompatActivity implements View.OnClickListener { private LinearLayout mLinearLayout; private String[] item_titles = { "设置密码", "客服电话", "使用帮助", "拼团流程", "问题反馈", "关于有菜" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_moreinfo); findViewById(R.id.moreInfo_backIv).setOnClickListener(this); mLinearLayout = (LinearLayout) findViewById(R.id.moreInfo_itemLayout); for (int i = 0;i<item_titles.length;i++){ View moreInfoItem = View.inflate(getApplicationContext(),R.layout.moreinfo_item,null ); moreInfoItem.setId(i + 100); moreInfoItem.setOnClickListener(this); TextView item_title = (TextView) moreInfoItem.findViewById(R.id.moreinfo_item_title); item_title.setText(item_titles[i]); mLinearLayout.addView(moreInfoItem); } } @Override public void onClick(View v) { switch (v.getId()){ case R.id.moreInfo_backIv: finish(); break; case 0+ 100: break; case 1+ 100: break; case 2+ 100: setupWebViewActivity("帮助","https://m.youcai.xin/help"); break; case 3+ 100: setupWebViewActivity("拼团流程","https://m.youcai.xin/static/help/group_rule.html"); break; case 4+ 100: Intent intent = new Intent(getApplicationContext(),FeedbackActivity.class); startActivity(intent); break; case 5+ 100: setupWebViewActivity("关于有菜","https://m.youcai.xin/about"); break; } } private void setupWebViewActivity(String title,String url){ Intent intent = new Intent(getApplicationContext(),WebViewActivity.class); intent.putExtra("title",title); intent.putExtra("webViewUrl",url); startActivity(intent); } }
2,538
0.595547
0.581376
77
31.077923
25.940374
99
false
false
0
0
0
0
0
0
0.714286
false
false
2
cdb1be4c29b4b6fbfedeeb5177aa114f3f20564c
592,705,501,703
93a8f3211922363f5ba48ae1ce021947671e2c73
/src/com/htssoft/sploosh/affectors/GravitationalAffector.java
6a282a969e521123b6639f497371f5840d58497c
[ "BSD-2-Clause" ]
permissive
simonHeinen1/Sploosh
https://github.com/simonHeinen1/Sploosh
34892ece70991a40101453acac60cb72c0edde49
34904abc2fa68cc901309cf93c0d3b690ea0350c
refs/heads/master
2021-01-23T22:31:58.325000
2012-08-13T13:58:53
2012-08-13T13:58:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.htssoft.sploosh.affectors; import java.util.ArrayList; import com.htssoft.sploosh.presentation.FluidTracer; import com.htssoft.sploosh.presentation.FluidTracerAffector; import com.jme3.math.Vector3f; import com.jme3.util.TempVars; public class GravitationalAffector implements FluidTracerAffector { protected Vector3f mainCenter = new Vector3f(); protected ArrayList<Vector3f> centers; protected float strength; public GravitationalAffector(Vector3f center, float strength){ mainCenter.set(center); this.strength = strength; } public void addCenter(Vector3f newC){ if (centers == null){ centers = new ArrayList<Vector3f>(); } centers.add(new Vector3f(newC)); } @Override public void affectTracer(FluidTracer tracer, float tpf) { contrib(tracer, tpf, mainCenter); if (centers != null){ for (Vector3f c : centers){ contrib(tracer, tpf, c); } } } protected void contrib(FluidTracer tracer, float tpf, Vector3f center){ TempVars vars = TempVars.get(); Vector3f force = vars.vect1; force.set(center).subtractLocal(tracer.position); force.normalizeLocal(); force.multLocal(strength).multLocal(tpf); tracer.inertia.addLocal(force); vars.release(); } }
UTF-8
Java
1,239
java
GravitationalAffector.java
Java
[]
null
[]
package com.htssoft.sploosh.affectors; import java.util.ArrayList; import com.htssoft.sploosh.presentation.FluidTracer; import com.htssoft.sploosh.presentation.FluidTracerAffector; import com.jme3.math.Vector3f; import com.jme3.util.TempVars; public class GravitationalAffector implements FluidTracerAffector { protected Vector3f mainCenter = new Vector3f(); protected ArrayList<Vector3f> centers; protected float strength; public GravitationalAffector(Vector3f center, float strength){ mainCenter.set(center); this.strength = strength; } public void addCenter(Vector3f newC){ if (centers == null){ centers = new ArrayList<Vector3f>(); } centers.add(new Vector3f(newC)); } @Override public void affectTracer(FluidTracer tracer, float tpf) { contrib(tracer, tpf, mainCenter); if (centers != null){ for (Vector3f c : centers){ contrib(tracer, tpf, c); } } } protected void contrib(FluidTracer tracer, float tpf, Vector3f center){ TempVars vars = TempVars.get(); Vector3f force = vars.vect1; force.set(center).subtractLocal(tracer.position); force.normalizeLocal(); force.multLocal(strength).multLocal(tpf); tracer.inertia.addLocal(force); vars.release(); } }
1,239
0.737692
0.726392
52
22.826923
20.915325
72
false
false
0
0
0
0
0
0
1.903846
false
false
2
21df1364980f0bd184aa488d97ed1a0653f62f4c
14,491,219,690,055
0dc75dbe0f1eddac40e91568c758c1f27c9c54e7
/src/test/java/com/tomasjadzevicius/ch/demo/product/domain/CreateProductInteractorTest.java
1bb79c1a3d64cff9fa84a9cfe78b27704fa3b3fe
[]
no_license
tomasjad/products-microservice
https://github.com/tomasjad/products-microservice
3aa9e4902f488b849435b1efd1427f038dffbbb4
4e95063c72c4c5369a8f852d2b219366aa585e8a
refs/heads/main
2022-12-24T06:19:20.763000
2020-10-08T23:51:40
2020-10-08T23:51:40
302,486,980
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tomasjadzevicius.ch.demo.product.domain; import com.tomasjadzevicius.ch.demo.product.domain.exceptions.ValidationException; import com.tomasjadzevicius.ch.demo.product.domain.model.CreateProductCommand; import com.tomasjadzevicius.ch.demo.product.domain.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.math.BigDecimal; import java.time.Clock; import java.time.Instant; import java.time.LocalDate; import static java.time.ZoneOffset.UTC; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; class CreateProductInteractorTest { private ProductRepository repository; private CreateProductInteractor underTest; private ArgumentCaptor<Product> productArgumentCaptor; @BeforeEach void setUp() { Clock clock = Clock.fixed(Instant.parse("2020-10-01T10:00:00Z"), UTC); repository = mock(ProductRepository.class); underTest = new CreateProductInteractor(repository, clock); productArgumentCaptor = ArgumentCaptor.forClass(Product.class); } @Test void shouldNotAllowBlankName() { CreateProductCommand command = CreateProductCommand.builder() .name(" ") .price(BigDecimal.TEN) .build(); ValidationException exception = assertThrows(ValidationException.class, () -> underTest.createProduct(command)); assertEquals("name can not be blank", exception.getMessage()); } @Test void shouldNotAllowNullPrice() { CreateProductCommand command = CreateProductCommand.builder() .name("productA") .build(); ValidationException exception = assertThrows(ValidationException.class, () -> underTest.createProduct(command)); assertEquals("price can not be null", exception.getMessage()); } @Test void shouldNotAllowNegativePrice() { CreateProductCommand command = CreateProductCommand.builder() .name("productA") .price(BigDecimal.valueOf(-25.65D)) .build(); ValidationException exception = assertThrows(ValidationException.class, () -> underTest.createProduct(command)); assertEquals("price can not be negative", exception.getMessage()); } @Test void shouldCreateNewProduct() { CreateProductCommand command = CreateProductCommand.builder() .name("productA") .price(BigDecimal.valueOf(25.65D)) .build(); underTest.createProduct(command); verify(repository).save(productArgumentCaptor.capture()); Product savedProduct = productArgumentCaptor.getValue(); assertEquals("productA", savedProduct.getName()); assertEquals(BigDecimal.valueOf(25.65D), savedProduct.getPrice()); assertTrue(savedProduct.isActive()); assertNotNull(savedProduct.getId()); assertEquals(LocalDate.of(2020, 10, 1), savedProduct.getCreated()); } }
UTF-8
Java
3,109
java
CreateProductInteractorTest.java
Java
[]
null
[]
package com.tomasjadzevicius.ch.demo.product.domain; import com.tomasjadzevicius.ch.demo.product.domain.exceptions.ValidationException; import com.tomasjadzevicius.ch.demo.product.domain.model.CreateProductCommand; import com.tomasjadzevicius.ch.demo.product.domain.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.math.BigDecimal; import java.time.Clock; import java.time.Instant; import java.time.LocalDate; import static java.time.ZoneOffset.UTC; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; class CreateProductInteractorTest { private ProductRepository repository; private CreateProductInteractor underTest; private ArgumentCaptor<Product> productArgumentCaptor; @BeforeEach void setUp() { Clock clock = Clock.fixed(Instant.parse("2020-10-01T10:00:00Z"), UTC); repository = mock(ProductRepository.class); underTest = new CreateProductInteractor(repository, clock); productArgumentCaptor = ArgumentCaptor.forClass(Product.class); } @Test void shouldNotAllowBlankName() { CreateProductCommand command = CreateProductCommand.builder() .name(" ") .price(BigDecimal.TEN) .build(); ValidationException exception = assertThrows(ValidationException.class, () -> underTest.createProduct(command)); assertEquals("name can not be blank", exception.getMessage()); } @Test void shouldNotAllowNullPrice() { CreateProductCommand command = CreateProductCommand.builder() .name("productA") .build(); ValidationException exception = assertThrows(ValidationException.class, () -> underTest.createProduct(command)); assertEquals("price can not be null", exception.getMessage()); } @Test void shouldNotAllowNegativePrice() { CreateProductCommand command = CreateProductCommand.builder() .name("productA") .price(BigDecimal.valueOf(-25.65D)) .build(); ValidationException exception = assertThrows(ValidationException.class, () -> underTest.createProduct(command)); assertEquals("price can not be negative", exception.getMessage()); } @Test void shouldCreateNewProduct() { CreateProductCommand command = CreateProductCommand.builder() .name("productA") .price(BigDecimal.valueOf(25.65D)) .build(); underTest.createProduct(command); verify(repository).save(productArgumentCaptor.capture()); Product savedProduct = productArgumentCaptor.getValue(); assertEquals("productA", savedProduct.getName()); assertEquals(BigDecimal.valueOf(25.65D), savedProduct.getPrice()); assertTrue(savedProduct.isActive()); assertNotNull(savedProduct.getId()); assertEquals(LocalDate.of(2020, 10, 1), savedProduct.getCreated()); } }
3,109
0.694757
0.684143
86
35.151161
30.294491
120
false
false
0
0
0
0
0
0
0.616279
false
false
2
e05edc274e5660abd32743569c5da7bc43afde93
18,665,927,892,689
852f5c8dafd4443c25a574a8389bf89cc1047ec0
/src/abcd/Test30.java
598500de149df73d31cb1e307bd166c1be639417
[]
no_license
SathishNangedda/GitDemo
https://github.com/SathishNangedda/GitDemo
4a66b5c929247c6f9fb12b3d3c5f1886ea52f70a
0150cf16efe095f4f3529d38a5013bd5895128dc
refs/heads/master
2023-02-07T14:45:40.767000
2020-12-21T10:09:51
2020-12-21T10:09:51
323,267,742
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package abcd; import java.util.Scanner; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Test30 { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub for(int i=1; i<3; i++) { Scanner s = new Scanner(System.in); System.out.println("Enter Mobile No"); String m = s.nextLine(); System.out.println("Enter Password"); String p = s.next(); WebDriver driver = new ChromeDriver(); driver.get("https://www.way2sms.com"); driver.manage().window().maximize(); driver.findElement(By.name("mobileNo")).sendKeys(m); driver.findElement(By.name("password")).sendKeys(p); driver.findElement(By.xpath("//*[@id=\"loginform\"]/div[2]/div[2]/button[1]")).click(); Thread.sleep(5000); driver.close(); } } }
UTF-8
Java
867
java
Test30.java
Java
[ { "context": "\tdriver.findElement(By.name(\"password\")).sendKeys(p);\n\t\n\tdriver.findElement(By.xpath(\"//*[@id=\\\"login", "end": 723, "score": 0.9764551520347595, "start": 722, "tag": "PASSWORD", "value": "p" } ]
null
[]
package abcd; import java.util.Scanner; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Test30 { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub for(int i=1; i<3; i++) { Scanner s = new Scanner(System.in); System.out.println("Enter Mobile No"); String m = s.nextLine(); System.out.println("Enter Password"); String p = s.next(); WebDriver driver = new ChromeDriver(); driver.get("https://www.way2sms.com"); driver.manage().window().maximize(); driver.findElement(By.name("mobileNo")).sendKeys(m); driver.findElement(By.name("password")).sendKeys(p); driver.findElement(By.xpath("//*[@id=\"loginform\"]/div[2]/div[2]/button[1]")).click(); Thread.sleep(5000); driver.close(); } } }
867
0.688581
0.67474
43
19.16279
21.745815
88
false
false
0
0
0
0
0
0
1.186046
false
false
2
97b104e16e45217500481de6b36ee68a5b4e2e16
18,975,165,545,067
1730788cde571d3afe8e19c65da0b731e1840516
/updates-comments-scrape/src/main/java/main/GetUpdatesAction.java
8a0a500b05df00f581cc3b1ef0f1b2d10f1730b5
[]
no_license
fitecBD/crowdfunding-parent
https://github.com/fitecBD/crowdfunding-parent
755840e12c178a333fc1ec7a6f01c28968be2b04
e06a282f971bdf25ec872377f98a14ef0addd7ec
refs/heads/master
2021-01-22T12:24:48.126000
2017-06-13T06:13:11
2017-06-13T06:13:11
92,722,679
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main; public class GetUpdatesAction extends Action<TArg, TReturn> { }
UTF-8
Java
80
java
GetUpdatesAction.java
Java
[]
null
[]
package main; public class GetUpdatesAction extends Action<TArg, TReturn> { }
80
0.775
0.775
5
15
23.520205
61
false
false
0
0
0
0
0
0
0.4
false
false
2
60f64010977cddfeec24d7ff603ef4760a1dfb21
9,259,949,544,037
3963854d684a2ad5b873a71049d0687b45d929d4
/src/revision/MinimumSubsetSumDifference.java
29c54f1175d06acf808ba409ba9feb0241320be1
[]
no_license
sambaranhazra/Practice
https://github.com/sambaranhazra/Practice
42059553bd74afa6d7a5ad2ec206063c039daf5e
08ce4465076f3dcf32adbfc709bb8d46a11b135a
refs/heads/master
2023-03-22T06:41:43.679000
2021-03-16T04:16:01
2021-03-16T04:16:01
348,208,467
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package revision; import java.util.Arrays; public class MinimumSubsetSumDifference { static Boolean[][] cache; static boolean subsetSum(int sum, int[] arr, int n) { if (sum == 0) return true; if (n == 0) return false; if (cache[n][sum] != null) return cache[n][sum]; if (sum < arr[n - 1]) return cache[n][sum] = subsetSum(sum, arr, n - 1); else return cache[n][sum] = subsetSum(sum, arr, n - 1) || subsetSum(sum - arr[n - 1], arr, n - 1); } static int minSubsetSumDifference(int[] arr) { int sum = Arrays.stream(arr).sum(); int d = 0; for (int i = sum / 2; i > 0; i--) { cache = new Boolean[arr.length + 1][i + 1]; if (subsetSum(i, arr, arr.length)) { d = i; break; } } return sum - 2 * d; } public static void main(String[] args) { int[] arr = new int[]{31,26,33,21,40}; System.out.println(minSubsetSumDifference(arr)); } }
UTF-8
Java
1,071
java
MinimumSubsetSumDifference.java
Java
[]
null
[]
package revision; import java.util.Arrays; public class MinimumSubsetSumDifference { static Boolean[][] cache; static boolean subsetSum(int sum, int[] arr, int n) { if (sum == 0) return true; if (n == 0) return false; if (cache[n][sum] != null) return cache[n][sum]; if (sum < arr[n - 1]) return cache[n][sum] = subsetSum(sum, arr, n - 1); else return cache[n][sum] = subsetSum(sum, arr, n - 1) || subsetSum(sum - arr[n - 1], arr, n - 1); } static int minSubsetSumDifference(int[] arr) { int sum = Arrays.stream(arr).sum(); int d = 0; for (int i = sum / 2; i > 0; i--) { cache = new Boolean[arr.length + 1][i + 1]; if (subsetSum(i, arr, arr.length)) { d = i; break; } } return sum - 2 * d; } public static void main(String[] args) { int[] arr = new int[]{31,26,33,21,40}; System.out.println(minSubsetSumDifference(arr)); } }
1,071
0.495798
0.474323
38
27.18421
23.288641
105
false
false
0
0
0
0
0
0
0.894737
false
false
2
b62856f9b1f5c3891e0b8b17e0dab48a117ad5ea
7,009,386,650,502
f632deb8852eaeae896a00816125ac6b3dfa6877
/src/CellSociety/CellShapes/TriangleCell.java
1a132fea813ba22934e9fd56f69bed06e05aaf2a
[ "MIT" ]
permissive
ireneqiao/cs308_cellsociety
https://github.com/ireneqiao/cs308_cellsociety
d0f85c7f14da4d06f6c82505631919f3b0817aa8
0db17f8873387c6a717fefdd6d2f183a44174005
refs/heads/master
2020-05-07T10:24:22.535000
2019-04-09T17:48:30
2019-04-09T17:48:30
179,179,610
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package CellSociety.CellShapes; import CellSociety.UI; import javafx.scene.shape.Polygon; /** * TriangleCell class extends CellShape so that it contains the basic features of a CellShape but assigns x and y * coordinates that form a triangle shape by overriding methods from CellShape superclass. * * This is well-designed because it simply overrides superclass methods to create a distinct triangle shape. All other * methods are handled by the superclass. All triangle-specific information is encapsulated in this subclass. */ public class TriangleCell extends CellShape{ private final static int TRIANGLE_NUM_COORDINATES = 6; private final double[] STARTING_COORDINATES_UP_EVEN = new double[]{CELL_WIDTH/2, 0, 0, CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT}; private final double[] STARTING_COORDINATES_UP_ODD = new double[]{ CELL_WIDTH, 0, CELL_WIDTH/2, CELL_HEIGHT, CELL_WIDTH + CELL_WIDTH/2, CELL_HEIGHT}; private final double[] STARTING_COORDINATES_DOWN_EVEN = new double[]{ CELL_WIDTH/2, 0, CELL_WIDTH, CELL_HEIGHT, CELL_WIDTH + CELL_WIDTH/2, 0}; private final double[] STARTING_COORDINATES_DOWN_ODD = new double[]{ 0, 0, CELL_WIDTH/2, CELL_HEIGHT, CELL_WIDTH, 0}; private double[] myCoordinates; public TriangleCell (UI ui, int row, int col){ super(ui, row, col); myCoordinates = new double[TRIANGLE_NUM_COORDINATES]; super.assignCoordinates(myCoordinates, TRIANGLE_NUM_COORDINATES); super.myShape = new Polygon(myCoordinates); } @Override protected double calcXCoordinate(int i){ double x; if (ROW % 2 == 0){ if (COL % 2 == 0){ x = STARTING_COORDINATES_UP_EVEN[i] + COL * CELL_WIDTH/2; } else { x = STARTING_COORDINATES_DOWN_EVEN[i] + COL * CELL_WIDTH/2 - CELL_WIDTH/2; } } else { if (COL % 2 == 0){ x = STARTING_COORDINATES_DOWN_ODD[i] + COL * CELL_WIDTH/2; } else { x = STARTING_COORDINATES_UP_ODD[i] + COL * CELL_WIDTH/2 + CELL_WIDTH/2 - CELL_WIDTH; } } return x; } @Override protected double calcYCoordinate(int i){ double y; if (ROW % 2 == 0){ if (COL % 2 == 0){ y = STARTING_COORDINATES_UP_EVEN[i] + ROW * CELL_HEIGHT; } else { y = STARTING_COORDINATES_DOWN_EVEN[i] + ROW * CELL_HEIGHT; } } else { if (COL % 2 == 0){ y = STARTING_COORDINATES_DOWN_ODD[i] + ROW * CELL_HEIGHT; } else { y = STARTING_COORDINATES_UP_ODD[i] + ROW * CELL_HEIGHT; } } return y; } }
UTF-8
Java
2,916
java
TriangleCell.java
Java
[]
null
[]
package CellSociety.CellShapes; import CellSociety.UI; import javafx.scene.shape.Polygon; /** * TriangleCell class extends CellShape so that it contains the basic features of a CellShape but assigns x and y * coordinates that form a triangle shape by overriding methods from CellShape superclass. * * This is well-designed because it simply overrides superclass methods to create a distinct triangle shape. All other * methods are handled by the superclass. All triangle-specific information is encapsulated in this subclass. */ public class TriangleCell extends CellShape{ private final static int TRIANGLE_NUM_COORDINATES = 6; private final double[] STARTING_COORDINATES_UP_EVEN = new double[]{CELL_WIDTH/2, 0, 0, CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT}; private final double[] STARTING_COORDINATES_UP_ODD = new double[]{ CELL_WIDTH, 0, CELL_WIDTH/2, CELL_HEIGHT, CELL_WIDTH + CELL_WIDTH/2, CELL_HEIGHT}; private final double[] STARTING_COORDINATES_DOWN_EVEN = new double[]{ CELL_WIDTH/2, 0, CELL_WIDTH, CELL_HEIGHT, CELL_WIDTH + CELL_WIDTH/2, 0}; private final double[] STARTING_COORDINATES_DOWN_ODD = new double[]{ 0, 0, CELL_WIDTH/2, CELL_HEIGHT, CELL_WIDTH, 0}; private double[] myCoordinates; public TriangleCell (UI ui, int row, int col){ super(ui, row, col); myCoordinates = new double[TRIANGLE_NUM_COORDINATES]; super.assignCoordinates(myCoordinates, TRIANGLE_NUM_COORDINATES); super.myShape = new Polygon(myCoordinates); } @Override protected double calcXCoordinate(int i){ double x; if (ROW % 2 == 0){ if (COL % 2 == 0){ x = STARTING_COORDINATES_UP_EVEN[i] + COL * CELL_WIDTH/2; } else { x = STARTING_COORDINATES_DOWN_EVEN[i] + COL * CELL_WIDTH/2 - CELL_WIDTH/2; } } else { if (COL % 2 == 0){ x = STARTING_COORDINATES_DOWN_ODD[i] + COL * CELL_WIDTH/2; } else { x = STARTING_COORDINATES_UP_ODD[i] + COL * CELL_WIDTH/2 + CELL_WIDTH/2 - CELL_WIDTH; } } return x; } @Override protected double calcYCoordinate(int i){ double y; if (ROW % 2 == 0){ if (COL % 2 == 0){ y = STARTING_COORDINATES_UP_EVEN[i] + ROW * CELL_HEIGHT; } else { y = STARTING_COORDINATES_DOWN_EVEN[i] + ROW * CELL_HEIGHT; } } else { if (COL % 2 == 0){ y = STARTING_COORDINATES_DOWN_ODD[i] + ROW * CELL_HEIGHT; } else { y = STARTING_COORDINATES_UP_ODD[i] + ROW * CELL_HEIGHT; } } return y; } }
2,916
0.564129
0.552812
84
33.714287
29.916779
118
false
false
0
0
0
0
0
0
0.595238
false
false
2
fab651bc31368a0c7931f72fd3e3c95f60ed097c
27,393,301,479,000
29cb40266a20b6bc33248ccae4cccf02b8167a35
/Examples/carrental/src/main/java/com/gb/rental/model/account/LicenseType.java
1f229f181be14a2e87a2202c84ea02de7ef2b07b
[ "Apache-2.0" ]
permissive
chdharm/LearningPython
https://github.com/chdharm/LearningPython
397c0a829a960bd885b635ecb07c02870bcf1026
fad3a50e0dfb02c9caa8d745d81ec105696f1309
refs/heads/master
2022-06-17T16:31:56.064000
2022-06-02T06:18:59
2022-06-02T06:18:59
100,912,022
1
3
null
false
2022-06-02T06:19:24
2017-08-21T04:21:01
2022-06-02T06:19:03
2022-06-02T06:19:24
1,142
1
4
1
Python
false
false
package com.gb.rental.model.account; public enum LicenseType { MCWG, MC, LMW, HMW, INTERNATIONALMC, INTERNATIONALMCWG, INTERNATIONALLMW, INTERNATIONALHMW }
UTF-8
Java
189
java
LicenseType.java
Java
[]
null
[]
package com.gb.rental.model.account; public enum LicenseType { MCWG, MC, LMW, HMW, INTERNATIONALMC, INTERNATIONALMCWG, INTERNATIONALLMW, INTERNATIONALHMW }
189
0.671958
0.671958
12
14.75
10.385286
36
false
false
0
0
0
0
0
0
0.666667
false
false
2
43c3d5fdbffd2a1509f5756fb813e993d9209b76
22,239,340,696,108
923f8e5b027e36ca45341070b3cdd2e25333b99d
/任务3/第四题/Connect.java
f8cbfa2954617f6d533dfbcc90f31272625bc433
[ "ISC" ]
permissive
black-cat-head/Tasks
https://github.com/black-cat-head/Tasks
907aa1778108934de32da87ed2a03c178de40f83
7674e337c55a074d3aaaee51f6dd007960d86f40
refs/heads/master
2020-07-22T16:02:44.103000
2019-11-14T01:28:21
2019-11-14T01:28:21
207,090,960
0
0
null
true
2019-09-08T09:39:25
2019-09-08T09:39:25
2019-09-06T09:39:14
2019-09-06T09:39:13
0
0
0
0
null
false
false
package demo2; import java.sql.*; import java.util.ArrayList; import java.util.List; public class Connect{ static Connection connection = null; static ResultSet rs = null; static String userMySql="root"; static String passwordMySql="123"; static String urlMySql = "jdbc:mysql://localhost:3306/gz?user=" +userMySql+"&password="+passwordMySql + "&useUnicode=true&characterEncoding=utf-8"; //sqlserver数据库url //String urlSqlServer = "jdbc:sqlserver://localhost:1433;integratedSecurity=true;DatabaseName=InfoDb"; public Connect() { try { //mysql数据库设置驱动程序类型 Class.forName("com.mysql.jdbc.Driver"); System.out.println("mysql数据库驱动加载成功"); //DriverManager.getConnection(DriverManager.getConnection();); //sqlserver数据库设置驱动程序类型 //Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //System.out.println("sqlserver数据库驱动加载成功"); } catch(java.lang.ClassNotFoundException e) { e.printStackTrace(); } } public static void connect(){ try{ //mysql数据库 connection = DriverManager.getConnection(urlMySql); //sqlserver数据库 //connection = DriverManager.getConnection(urlSqlServer); if(connection!=null){ System.out.println("数据库连接成功"); } } catch(Exception e){ e.printStackTrace(); } } public static void disconnect(){ try{ if(connection != null){ connection.close(); connection = null; } } catch(Exception e){ e.printStackTrace(); } } public static ResultSet executeQuery(String sql) { try { System.out.println("executeQuery(). sql = " + sql); PreparedStatement pstm = connection.prepareStatement(sql); // 执行查询 rs = pstm.executeQuery(); } catch(SQLException ex) { ex.printStackTrace(); } return rs; } //插入 //executeUpdate 的返回值是一个整数,指示受影响的行数(即更新计数)。 //executeUpdate用于执行 INSERT、UPDATE 或 DELETE 语句 //以及 SQL DDL(数据定义语言)语句,例如 CREATE TABLE 和 DROP TABLE。 //执行增、删、改语句的方法 public static int executeUpdate(String sql) { int count = 0; connect(); try { Statement stmt = connection.createStatement(); count = stmt.executeUpdate(sql); } catch(SQLException ex) { System.err.println(ex.getMessage()); } disconnect(); return count; } public static void main(String agrs[]){ Connect m=new Connect(); m.connect(); } }
GB18030
Java
2,687
java
Connect.java
Java
[ { "context": "userMySql=\"root\"; \r\n\tstatic String passwordMySql=\"123\";\r\n\tstatic String urlMySql = \"jdbc:mysql://localh", "end": 264, "score": 0.9994215965270996, "start": 261, "tag": "PASSWORD", "value": "123" }, { "context": "alhost:3306/gz?user=\"\r\n\t\t\t+userMySql+\"&p...
null
[]
package demo2; import java.sql.*; import java.util.ArrayList; import java.util.List; public class Connect{ static Connection connection = null; static ResultSet rs = null; static String userMySql="root"; static String passwordMySql="123"; static String urlMySql = "jdbc:mysql://localhost:3306/gz?user=" +userMySql+"&password="+<PASSWORD>MySql + "&useUnicode=true&characterEncoding=utf-8"; //sqlserver数据库url //String urlSqlServer = "jdbc:sqlserver://localhost:1433;integratedSecurity=true;DatabaseName=InfoDb"; public Connect() { try { //mysql数据库设置驱动程序类型 Class.forName("com.mysql.jdbc.Driver"); System.out.println("mysql数据库驱动加载成功"); //DriverManager.getConnection(DriverManager.getConnection();); //sqlserver数据库设置驱动程序类型 //Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //System.out.println("sqlserver数据库驱动加载成功"); } catch(java.lang.ClassNotFoundException e) { e.printStackTrace(); } } public static void connect(){ try{ //mysql数据库 connection = DriverManager.getConnection(urlMySql); //sqlserver数据库 //connection = DriverManager.getConnection(urlSqlServer); if(connection!=null){ System.out.println("数据库连接成功"); } } catch(Exception e){ e.printStackTrace(); } } public static void disconnect(){ try{ if(connection != null){ connection.close(); connection = null; } } catch(Exception e){ e.printStackTrace(); } } public static ResultSet executeQuery(String sql) { try { System.out.println("executeQuery(). sql = " + sql); PreparedStatement pstm = connection.prepareStatement(sql); // 执行查询 rs = pstm.executeQuery(); } catch(SQLException ex) { ex.printStackTrace(); } return rs; } //插入 //executeUpdate 的返回值是一个整数,指示受影响的行数(即更新计数)。 //executeUpdate用于执行 INSERT、UPDATE 或 DELETE 语句 //以及 SQL DDL(数据定义语言)语句,例如 CREATE TABLE 和 DROP TABLE。 //执行增、删、改语句的方法 public static int executeUpdate(String sql) { int count = 0; connect(); try { Statement stmt = connection.createStatement(); count = stmt.executeUpdate(sql); } catch(SQLException ex) { System.err.println(ex.getMessage()); } disconnect(); return count; } public static void main(String agrs[]){ Connect m=new Connect(); m.connect(); } }
2,689
0.647107
0.641362
107
20.794392
21.285219
103
false
false
0
0
0
0
0
0
2.065421
false
false
2
714ee04ab82f3460ab3b30746e746c647fc6e6cf
4,552,665,368,125
c12585c44bf57b6ccaffecb379137d9ac05ddf4e
/app/src/main/java/com/pastelpunk/audiofic/app/AudioFic.java
7ecb5927826196d3b2b17ac8511832fef19962c6
[]
no_license
gedison/audioFic
https://github.com/gedison/audioFic
9c84da0a40609abf13c35b9e0917ef2437483798
7649b3ddcc65c65cc5ac05d812ad5ed448076cfb
refs/heads/master
2021-06-19T01:44:51.462000
2021-03-18T14:33:56
2021-03-18T14:33:56
179,880,982
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pastelpunk.audiofic.app; import android.app.Activity; import android.app.Application; import android.app.Fragment; import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DispatchingAndroidInjector; import dagger.android.HasActivityInjector; import dagger.android.HasFragmentInjector; public class AudioFic extends Application implements HasActivityInjector, HasFragmentInjector{ @Inject DispatchingAndroidInjector<Activity> dispatchingAndroidInjector; @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjectorFragment; @Override public void onCreate() { super.onCreate(); DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .build() .inject(this); } @Override public DispatchingAndroidInjector<Activity> activityInjector() { return dispatchingAndroidInjector; } @Override public AndroidInjector<Fragment> fragmentInjector() { return dispatchingAndroidInjectorFragment; } }
UTF-8
Java
1,107
java
AudioFic.java
Java
[ { "context": "package com.pastelpunk.audiofic.app;\n\nimport android.app.Activity;\nimpor", "end": 22, "score": 0.7525818347930908, "start": 16, "tag": "USERNAME", "value": "elpunk" } ]
null
[]
package com.pastelpunk.audiofic.app; import android.app.Activity; import android.app.Application; import android.app.Fragment; import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DispatchingAndroidInjector; import dagger.android.HasActivityInjector; import dagger.android.HasFragmentInjector; public class AudioFic extends Application implements HasActivityInjector, HasFragmentInjector{ @Inject DispatchingAndroidInjector<Activity> dispatchingAndroidInjector; @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjectorFragment; @Override public void onCreate() { super.onCreate(); DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .build() .inject(this); } @Override public DispatchingAndroidInjector<Activity> activityInjector() { return dispatchingAndroidInjector; } @Override public AndroidInjector<Fragment> fragmentInjector() { return dispatchingAndroidInjectorFragment; } }
1,107
0.746161
0.746161
40
26.674999
24.724874
94
false
false
0
0
0
0
0
0
0.4
false
false
2
cff0d83f4217f203495d5505673f3b3df6f415c6
29,308,856,851,014
cdba99ef71db2adf88e0870de547c1beda8fee45
/app/src/main/java/com/pro2on/lesson_1_1/MainActivity.java
dca95a589a048da35c1bc926f110d88dade0ccaf
[]
no_license
pro2on/android_device_info
https://github.com/pro2on/android_device_info
ef940b61fd8dcba87c951a34926b00ff2704286a
46b77fce4112fd9b488ee1bc4fb27641c1a14d07
refs/heads/master
2021-01-19T00:16:05.935000
2015-02-03T19:03:17
2015-02-03T19:03:17
30,259,241
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pro2on.lesson_1_1; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.view.ViewGroup.LayoutParams; import com.pro2on.lesson_1_1.model.DeviceInformationModel; import com.pro2on.lesson_1_1.model.ModelFactory; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TableLayout tableLayout = ModelFactory.getInstance().getDeviceInformationModel().getInformationAsTableLayout(this); LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout); linearLayout.addView(tableLayout); } }
UTF-8
Java
973
java
MainActivity.java
Java
[]
null
[]
package com.pro2on.lesson_1_1; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.view.ViewGroup.LayoutParams; import com.pro2on.lesson_1_1.model.DeviceInformationModel; import com.pro2on.lesson_1_1.model.ModelFactory; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TableLayout tableLayout = ModelFactory.getInstance().getDeviceInformationModel().getInformationAsTableLayout(this); LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout); linearLayout.addView(tableLayout); } }
973
0.786228
0.775951
35
26.799999
27.867851
123
false
false
0
0
0
0
0
0
0.514286
false
false
2
6f27ed3d70f9c890987eb016e1f83761985a8e85
18,245,021,120,533
095015530434d6f0882b964da7bd88a309be081e
/trial/RotateMatrix.java
cb649c6dbe9da866201d2bab80ad1c8843c3acc3
[]
no_license
dani97/javaDSPractise
https://github.com/dani97/javaDSPractise
5dd739b361f616b46e26f3d3b58ddebca632fbb8
5c3f2155bcab821561c49375f6e2662b3641eae3
refs/heads/master
2021-01-21T14:28:00.779000
2017-09-04T15:40:04
2017-09-04T15:40:04
95,283,912
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package trial; import java.util.Scanner; public class RotateMatrix { public static void print(int [][] matrix,int n){ int i,j; for(i=0;i<n;i++){ for(j=0;j<n;j++){ System.out.print(matrix[i][j]+" "); } System.out.println(); } } public static int [][] rotate(int [][] matrix,int n){ int [][] matrix1 = new int[n][n]; int i,j; for(i=0;i<n;i++){ for (j=0;j<n;j++){ matrix1[i][j] = matrix[n-j-1][i]; } } return matrix1; } public static int[][] rotate1(int [][] matrix,int n){ for(int layer=0;layer<n/2;layer++){ int first = layer; int last = n-1-layer; for(int i = first;i<last;i++){ int offset = i-first; System.out.println( "rotate" + matrix[first][i]+" "+matrix [last-offset][first]+" "+matrix[last][last-offset]+" "+matrix[i][last]); int top = matrix[first][i]; matrix[first][i] = matrix [last-offset][first]; matrix[last-offset][first] = matrix[last][last-offset]; matrix[last][last-offset] = matrix[i][last]; matrix[i][last] = top; } } return matrix; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int [][] matrix = new int [n][n]; int i,j; for(i=0;i<n;i++){ for(j=0;j<n;j++){ matrix[i][j] = sc.nextInt(); } sc.nextLine(); } sc.close(); print(matrix,n); System.out.println("After rotate"); print(rotate(matrix,n),n); System.out.println("After rotate1"); print(rotate1(matrix,n),n); } }
UTF-8
Java
1,592
java
RotateMatrix.java
Java
[]
null
[]
package trial; import java.util.Scanner; public class RotateMatrix { public static void print(int [][] matrix,int n){ int i,j; for(i=0;i<n;i++){ for(j=0;j<n;j++){ System.out.print(matrix[i][j]+" "); } System.out.println(); } } public static int [][] rotate(int [][] matrix,int n){ int [][] matrix1 = new int[n][n]; int i,j; for(i=0;i<n;i++){ for (j=0;j<n;j++){ matrix1[i][j] = matrix[n-j-1][i]; } } return matrix1; } public static int[][] rotate1(int [][] matrix,int n){ for(int layer=0;layer<n/2;layer++){ int first = layer; int last = n-1-layer; for(int i = first;i<last;i++){ int offset = i-first; System.out.println( "rotate" + matrix[first][i]+" "+matrix [last-offset][first]+" "+matrix[last][last-offset]+" "+matrix[i][last]); int top = matrix[first][i]; matrix[first][i] = matrix [last-offset][first]; matrix[last-offset][first] = matrix[last][last-offset]; matrix[last][last-offset] = matrix[i][last]; matrix[i][last] = top; } } return matrix; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int [][] matrix = new int [n][n]; int i,j; for(i=0;i<n;i++){ for(j=0;j<n;j++){ matrix[i][j] = sc.nextInt(); } sc.nextLine(); } sc.close(); print(matrix,n); System.out.println("After rotate"); print(rotate(matrix,n),n); System.out.println("After rotate1"); print(rotate1(matrix,n),n); } }
1,592
0.554648
0.544598
66
22.121212
21.42182
135
false
false
0
0
0
0
0
0
3.015152
false
false
2
e70a0647cb60fb1ea189f1220c3b8d2ff6b05be1
5,806,795,811,453
ebd4f145ab55faa18bf58fe55d5ecd22ea9fad60
/src/cliente/Cliente.java
1250beaa6ee6ee4632e4dd275cd461a80efdff99
[]
no_license
taller-avanzada/yet-another-chat
https://github.com/taller-avanzada/yet-another-chat
1d4d3a4a2e8f20404ab1a58d611a79265ec074e1
2a2ea9dd09510810526f85ac74de26410a30313a
refs/heads/main
2023-08-28T13:13:53.943000
2021-11-06T01:40:45
2021-11-06T01:40:45
424,740,056
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cliente; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; public class Cliente { private String name; private Socket socket; private DataInputStream in; private DataOutputStream out; private ClienteRecibe recibe; private int cantSalas; public Cliente(int puerto, String ip) { try { socket = new Socket(ip, puerto); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); cantSalas = 0; // falta la parte de leer } catch (IOException e) { e.printStackTrace(); } } public void escribir(String sala, String mensaje) { try { out.write(0); out.writeUTF(sala + ";" + name + ";" + mensaje); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void setName(String name) { this.name = name; } public DataOutputStream getDataOutputStream() { return out; } public DataInputStream getDataInputStream() { return in; } public void setRecibe(ClienteRecibe recibe) { this.recibe = recibe; } public ClienteRecibe getRecibe() { return recibe; } public void enviarNuevaSala(String nombreSala) { try { ++cantSalas; out.write(1); out.writeUTF(nombreSala); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public int getCantSalas() { return cantSalas; } public void conectarseASala(String nombreSala) { try { ++cantSalas; out.write(1); out.writeUTF(nombreSala); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void disconnect(String nombreSala) { try { --cantSalas; out.write(3); out.writeUTF(nombreSala); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
UTF-8
Java
1,806
java
Cliente.java
Java
[]
null
[]
package cliente; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; public class Cliente { private String name; private Socket socket; private DataInputStream in; private DataOutputStream out; private ClienteRecibe recibe; private int cantSalas; public Cliente(int puerto, String ip) { try { socket = new Socket(ip, puerto); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); cantSalas = 0; // falta la parte de leer } catch (IOException e) { e.printStackTrace(); } } public void escribir(String sala, String mensaje) { try { out.write(0); out.writeUTF(sala + ";" + name + ";" + mensaje); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void setName(String name) { this.name = name; } public DataOutputStream getDataOutputStream() { return out; } public DataInputStream getDataInputStream() { return in; } public void setRecibe(ClienteRecibe recibe) { this.recibe = recibe; } public ClienteRecibe getRecibe() { return recibe; } public void enviarNuevaSala(String nombreSala) { try { ++cantSalas; out.write(1); out.writeUTF(nombreSala); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public int getCantSalas() { return cantSalas; } public void conectarseASala(String nombreSala) { try { ++cantSalas; out.write(1); out.writeUTF(nombreSala); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void disconnect(String nombreSala) { try { --cantSalas; out.write(3); out.writeUTF(nombreSala); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
1,806
0.678295
0.673311
97
17.618557
15.533431
56
false
false
0
0
0
0
0
0
1.979381
false
false
2
25432b09441b57edc378ad59bfce0067768d4579
25,297,357,398,207
e6d0ba6cdb7ed9cc77eb9b1161e069338ce2ab64
/TaskHelper/src/tx/helper/module/TCallResult.java
39ea23a641412b79d5ce3a3b445353c96ec25700
[]
no_license
doug-william/WeiXin-HeSheng
https://github.com/doug-william/WeiXin-HeSheng
a2e5a65a2a02d967b4eba7afcdd7acecd0356f59
bfe408c43223d3f2b6a3c2ff9b63f5d380de405d
refs/heads/master
2021-01-01T17:57:12.399000
2014-09-28T07:58:27
2014-09-28T07:58:40
23,922,201
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package tx.helper.module; public class TCallResult extends CRMResult { public TCall call; public TCall getCall() { return call; } public void setCall(TCall call) { this.call = call; } }
UTF-8
Java
201
java
TCallResult.java
Java
[]
null
[]
package tx.helper.module; public class TCallResult extends CRMResult { public TCall call; public TCall getCall() { return call; } public void setCall(TCall call) { this.call = call; } }
201
0.696517
0.696517
15
12.4
14.056078
44
false
false
0
0
0
0
0
0
0.933333
false
false
2
ceced97448b9f03296e587cabdb5bdb5bbfb53c2
26,826,365,750,003
c0559d4132795e0c59882f0dfd3d78cb80b95350
/modules/application/src/main/java/edu/northeastern/truthtree/adapter/utilities/URLUtil.java
6bc9d0b91f0a8a3f2e3ca1bc453a995747eb1900
[ "MIT" ]
permissive
TruthTreeASD/backend
https://github.com/TruthTreeASD/backend
3bd41cbbc4dda649428d8f6adb7d1b10dc63d58d
71d2203754e5ecb54e125da92a18c7b14540e391
refs/heads/develop
2022-07-22T13:40:36.591000
2019-04-24T23:30:22
2019-04-24T23:30:22
166,601,031
1
0
MIT
false
2022-03-31T18:46:08
2019-01-19T22:39:27
2019-04-24T23:30:25
2022-03-31T18:46:08
12,149
1
0
1
Java
false
false
package edu.northeastern.truthtree.adapter.utilities; import org.json.simple.JSONArray; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; /** * Represents the methods needed to read JSON from a URL API. */ @Component public class URLUtil { private static RestTemplate restTemplate = null; @Autowired public URLUtil(RestTemplate restTemplate) { this.restTemplate = restTemplate; } /** * Reads the content form a web address and converts it into a JSONArray. * * @param url The web address of the web page to be read and converted. * @return JSONArray in the form of the text on the web page */ public static JSONArray readJSONFromURL(String url) { String jsonString = readURL(url); return JSONUtil.stringToJSONArray(jsonString); } public static String readJSONFromURLInString(String url) { return readURL(url); } /** * Reads a web page and turns its contents into a string. * * @param url The web address of the web page to be read and converted. * @return Web contents as a string */ private static String readURL(String url) { ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); return response.getBody(); } /** * Reads a web page and turns its contents into a string. * * @param url The web address of the web page to be read and converted. * @return Web contents as a string */ public static String postJSONFromURL(String url, String jsonString) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(jsonString, headers); ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class); return response.getBody(); } /** * Reads a web page and turns its contents into a string. * * @param url The web address of the web page to be read and converted. * @return Web contents as a string */ public static void putJSONFromURL(String url) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>("", headers); restTemplate.put(url, entity, String.class); } public static void deleteJSONFromURL(String url){ restTemplate.delete(url); } }
UTF-8
Java
2,650
java
URLUtil.java
Java
[]
null
[]
package edu.northeastern.truthtree.adapter.utilities; import org.json.simple.JSONArray; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; /** * Represents the methods needed to read JSON from a URL API. */ @Component public class URLUtil { private static RestTemplate restTemplate = null; @Autowired public URLUtil(RestTemplate restTemplate) { this.restTemplate = restTemplate; } /** * Reads the content form a web address and converts it into a JSONArray. * * @param url The web address of the web page to be read and converted. * @return JSONArray in the form of the text on the web page */ public static JSONArray readJSONFromURL(String url) { String jsonString = readURL(url); return JSONUtil.stringToJSONArray(jsonString); } public static String readJSONFromURLInString(String url) { return readURL(url); } /** * Reads a web page and turns its contents into a string. * * @param url The web address of the web page to be read and converted. * @return Web contents as a string */ private static String readURL(String url) { ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); return response.getBody(); } /** * Reads a web page and turns its contents into a string. * * @param url The web address of the web page to be read and converted. * @return Web contents as a string */ public static String postJSONFromURL(String url, String jsonString) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(jsonString, headers); ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class); return response.getBody(); } /** * Reads a web page and turns its contents into a string. * * @param url The web address of the web page to be read and converted. * @return Web contents as a string */ public static void putJSONFromURL(String url) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>("", headers); restTemplate.put(url, entity, String.class); } public static void deleteJSONFromURL(String url){ restTemplate.delete(url); } }
2,650
0.729434
0.729434
82
31.317074
26.499369
92
false
false
0
0
0
0
0
0
0.414634
false
false
2
4db582f1a5e2c2ac364c1c6e8979905d28b4d29a
31,129,923,026,207
7ad54455ccfdd0c2fa6c060b345488ec8ebb1cf4
/javax/mail/search/AddressStringTerm.java
e3e8c050f80a31d4a9d442cdd70a13db9c761b43
[]
no_license
chetanreddym/segmentation-correction-tool
https://github.com/chetanreddym/segmentation-correction-tool
afdbdaa4642fcb79a21969346420dd09eea72f8c
7ca3b116c3ecf0de3a689724e12477a187962876
refs/heads/master
2021-05-13T20:09:00.245000
2018-01-10T04:42:03
2018-01-10T04:42:03
116,817,741
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package javax.mail.search; import javax.mail.Address; import javax.mail.internet.InternetAddress; public abstract class AddressStringTerm extends StringTerm { protected AddressStringTerm(String paramString) { super(paramString, true); } protected boolean match(Address paramAddress) { if ((paramAddress instanceof InternetAddress)) { InternetAddress localInternetAddress = (InternetAddress)paramAddress; return super.match(localInternetAddress.toUnicodeString()); } return super.match(paramAddress.toString()); } public boolean equals(Object paramObject) { if (!(paramObject instanceof AddressStringTerm)) return false; return super.equals(paramObject); } }
UTF-8
Java
776
java
AddressStringTerm.java
Java
[]
null
[]
package javax.mail.search; import javax.mail.Address; import javax.mail.internet.InternetAddress; public abstract class AddressStringTerm extends StringTerm { protected AddressStringTerm(String paramString) { super(paramString, true); } protected boolean match(Address paramAddress) { if ((paramAddress instanceof InternetAddress)) { InternetAddress localInternetAddress = (InternetAddress)paramAddress; return super.match(localInternetAddress.toUnicodeString()); } return super.match(paramAddress.toString()); } public boolean equals(Object paramObject) { if (!(paramObject instanceof AddressStringTerm)) return false; return super.equals(paramObject); } }
776
0.697165
0.697165
71
9.929578
18.704014
75
false
false
0
0
0
0
0
0
0.140845
false
false
2
131dd3bb13f33183a42f611810704935c53a759c
34,479,997,506,282
95061f58ffb78f850984b433491aa00451e28cf9
/MeiFuGo/src/com/xyj/mefugou/app/Configer.java
1b031c9544211d0de169e8697b67028d30cd7a98
[ "MIT" ]
permissive
xiaohuizli/MeifuGO
https://github.com/xiaohuizli/MeifuGO
e3a0cc02b5c049565d58e07391bdc2a97565f56d
269dbf7b66286d379dd286c24d043d93db71d417
refs/heads/master
2020-06-11T14:44:24.209000
2016-05-10T15:42:53
2016-05-10T15:42:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xyj.mefugou.app; import android.os.Environment; import java.io.File; public final class Configer{ public static final String BUG_NAME = "mefugou"; public static final String HTTP_URL = "http://59.46.12.222/"; //public static final String HTTP_URL = "http://192.168.1.100:8080/"; public static final boolean BUG_STATIC = true; public static final String PERF_USER = "mefugou_user"; public static final String PERF_APP = "mefugou_app"; public static final int app_type = 2;//2为美肤GO }
UTF-8
Java
537
java
Configer.java
Java
[ { "context": " //public static final String HTTP_URL = \"http://192.168.1.100:8080/\";\n\n public static final boolean BUG_STAT", "end": 299, "score": 0.8876984715461731, "start": 286, "tag": "IP_ADDRESS", "value": "192.168.1.100" } ]
null
[]
package com.xyj.mefugou.app; import android.os.Environment; import java.io.File; public final class Configer{ public static final String BUG_NAME = "mefugou"; public static final String HTTP_URL = "http://59.46.12.222/"; //public static final String HTTP_URL = "http://192.168.1.100:8080/"; public static final boolean BUG_STATIC = true; public static final String PERF_USER = "mefugou_user"; public static final String PERF_APP = "mefugou_app"; public static final int app_type = 2;//2为美肤GO }
537
0.696799
0.649718
22
23.181818
25.853849
73
false
false
0
0
0
0
0
0
0.454545
false
false
2
185794d84c59de6a4943e6ac88883cec3b87e6a4
39,316,130,663,501
ad751aab21033ff028bc2c5aa1d5d4439217fe85
/FP-LA/gbstore/gbstore-db-translator/src/test/java/au/com/gbstore/dbtranslator/dao/EntryDaoTest.java
ea99b6e0f0903eabe610e00a472b75f85128ee28
[]
no_license
jlessa/marl
https://github.com/jlessa/marl
37a7f71ed58ec944d7bae295b27d7141b99e274f
dc6bfc480340c352575384fe7ebabbc5e13ea4c5
refs/heads/master
2020-04-17T05:36:07.382000
2016-10-28T16:08:17
2016-10-28T16:08:17
67,254,687
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package au.com.gbstore.dbtranslator.dao; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import au.com.gbstore.dbtranslator.model.Entry; import au.com.gbstore.dbtranslator.model.ItemStoreOrder; import au.com.gbstore.dbtranslator.model.Product; import au.com.gbstore.dbtranslator.model.Store; import au.com.gbstore.dbtranslator.model.StoreOrder; import au.com.gbstore.dbtranslator.model.Supplier; public class EntryDaoTest { //Declaring Daos private static EntryDao dao; private static SupplierDao sdao; private static ProductDao pdao; private static StoreDao stdao; private static StoreOrderDao sodao; /**Set up daos with the h2db settings. * Save supplier, store and product beforehand * @throws Exception */ @BeforeClass public static void setUp() throws Exception{ dao = new EntryDao(); sdao = new SupplierDao(); pdao = new ProductDao(); stdao = new StoreDao(); sodao = new StoreOrderDao(); Store boteco = new Store(); boteco.setName("Boteco"); try { stdao.persist(boteco); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Store devassa = new Store(); devassa.setName("Devassa"); stdao.persist(devassa); Store bar = new Store(); bar.setName("Bar"); stdao.persist(bar); Supplier suppliera = new Supplier(); suppliera.setName("SupplierA"); suppliera = sdao.persist(suppliera); Supplier supplierb = new Supplier(); supplierb.setName("SupplierB"); supplierb = sdao.persist(supplierb); Supplier supplierc = new Supplier(); supplierc.setName("SupplierC"); supplierc = sdao.persist(supplierc); Product budweiser = new Product(); budweiser.setName("Budweiser"); budweiser.setProductSupplierId(1L); budweiser.setSupplier(suppliera); budweiser = pdao.persist(budweiser); Product amstel = new Product(); amstel.setName("Amstel"); amstel.setProductSupplierId(2L); amstel.setSupplier(supplierb); amstel = pdao.persist(amstel); Product heineken = new Product(); heineken.setName("Heineken"); heineken.setProductSupplierId(3L); heineken.setSupplier(supplierc); heineken = pdao.persist(heineken); StoreOrder sorder = new StoreOrder(); sorder.setStore(boteco); ItemStoreOrder item1 = new ItemStoreOrder(); item1.setQuantity(BigInteger.valueOf(100)); Product product = budweiser; item1.setProduct(product); item1.setStoreOrder(sorder); ItemStoreOrder item2 = new ItemStoreOrder(); item2.setQuantity(BigInteger.valueOf(200)); product = amstel; item2.setProduct(product); item2.setStoreOrder(sorder); ItemStoreOrder item3 = new ItemStoreOrder(); item3.setQuantity(BigInteger.valueOf(300)); product = heineken; item3.setProduct(product); item3.setStoreOrder(sorder); sorder.getItemStoreOrderList().add(item1); sorder.getItemStoreOrderList().add(item2); sorder.getItemStoreOrderList().add(item3); sorder = sodao.persist(sorder); StoreOrder sorder2 = new StoreOrder(); sorder2.setStore(bar); item1.setStoreOrder(sorder2); item2.setStoreOrder(sorder2); sorder.getItemStoreOrderList().add(item1); sorder.getItemStoreOrderList().add(item2); sorder2 = sodao.persist(sorder2); } /**Save a new entry. * @return * @throws Exception */ public Long saveEntity() throws Exception{ Entry entry = new Entry(); List<StoreOrder> list = new ArrayList<StoreOrder>(); List<ItemStoreOrder> listItem = new ArrayList<ItemStoreOrder>(); ItemStoreOrder item = new ItemStoreOrder(); entry.setInsertDate(new Date()); StoreOrder order = new StoreOrder(); order.setInsertDate(new Date()); Store store = stdao.findById(1L); order.setStore(store); Product product = pdao.findById(1L); item.setProduct(product); listItem.add(item); order.setItemStoreOrderList(listItem); item.setStoreOrder(order); list.add(order); entry.setStoreOrderList(list); entry = dao.persist(entry); return entry.getEntryId(); } /**Verify persist method. * It must persist a new entity and generate a new id * It must has a StoreOrder * @throws Exception */ @Test public void testPersistEntry() throws Exception { Long id = saveEntity(); Long otherId = saveEntity(); assertNotEquals(id, otherId); Entry entry = dao.findById(id); assertNotNull(entry.getStoreOrderList().get(0).getItemStoreOrderList().get(0).getStoreOrder()); } /**Find the entry saved on saveEntry method. * @throws Exception */ @Test public void testFindById() throws Exception{ Long id = saveEntity(); Entry newEntry = dao.findById(id); assertNotNull(newEntry); } /**Try to find a * @throws Exception * */ @Test public void testFindANonEntity() throws Exception{ Long id = saveEntity(); dao.remove(id); assertNull(dao.findById(id)); } /**Try to remove an Entity * @throws Exception */ @Test public void testRemove() throws Exception{ Long id = saveEntity(); dao.remove(id); assertNull(dao.findById(id)); } }
UTF-8
Java
5,241
java
EntryDaoTest.java
Java
[ { "context": "t budweiser = new Product();\n\t\tbudweiser.setName(\"Budweiser\");\n\t\tbudweiser.setProductSupplierId(1L);\n\t\tbudwei", "end": 1938, "score": 0.8082106113433838, "start": 1929, "tag": "NAME", "value": "Budweiser" }, { "context": "Product amstel = new Product();\n\t\t...
null
[]
package au.com.gbstore.dbtranslator.dao; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import au.com.gbstore.dbtranslator.model.Entry; import au.com.gbstore.dbtranslator.model.ItemStoreOrder; import au.com.gbstore.dbtranslator.model.Product; import au.com.gbstore.dbtranslator.model.Store; import au.com.gbstore.dbtranslator.model.StoreOrder; import au.com.gbstore.dbtranslator.model.Supplier; public class EntryDaoTest { //Declaring Daos private static EntryDao dao; private static SupplierDao sdao; private static ProductDao pdao; private static StoreDao stdao; private static StoreOrderDao sodao; /**Set up daos with the h2db settings. * Save supplier, store and product beforehand * @throws Exception */ @BeforeClass public static void setUp() throws Exception{ dao = new EntryDao(); sdao = new SupplierDao(); pdao = new ProductDao(); stdao = new StoreDao(); sodao = new StoreOrderDao(); Store boteco = new Store(); boteco.setName("Boteco"); try { stdao.persist(boteco); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Store devassa = new Store(); devassa.setName("Devassa"); stdao.persist(devassa); Store bar = new Store(); bar.setName("Bar"); stdao.persist(bar); Supplier suppliera = new Supplier(); suppliera.setName("SupplierA"); suppliera = sdao.persist(suppliera); Supplier supplierb = new Supplier(); supplierb.setName("SupplierB"); supplierb = sdao.persist(supplierb); Supplier supplierc = new Supplier(); supplierc.setName("SupplierC"); supplierc = sdao.persist(supplierc); Product budweiser = new Product(); budweiser.setName("Budweiser"); budweiser.setProductSupplierId(1L); budweiser.setSupplier(suppliera); budweiser = pdao.persist(budweiser); Product amstel = new Product(); amstel.setName("Amstel"); amstel.setProductSupplierId(2L); amstel.setSupplier(supplierb); amstel = pdao.persist(amstel); Product heineken = new Product(); heineken.setName("Heineken"); heineken.setProductSupplierId(3L); heineken.setSupplier(supplierc); heineken = pdao.persist(heineken); StoreOrder sorder = new StoreOrder(); sorder.setStore(boteco); ItemStoreOrder item1 = new ItemStoreOrder(); item1.setQuantity(BigInteger.valueOf(100)); Product product = budweiser; item1.setProduct(product); item1.setStoreOrder(sorder); ItemStoreOrder item2 = new ItemStoreOrder(); item2.setQuantity(BigInteger.valueOf(200)); product = amstel; item2.setProduct(product); item2.setStoreOrder(sorder); ItemStoreOrder item3 = new ItemStoreOrder(); item3.setQuantity(BigInteger.valueOf(300)); product = heineken; item3.setProduct(product); item3.setStoreOrder(sorder); sorder.getItemStoreOrderList().add(item1); sorder.getItemStoreOrderList().add(item2); sorder.getItemStoreOrderList().add(item3); sorder = sodao.persist(sorder); StoreOrder sorder2 = new StoreOrder(); sorder2.setStore(bar); item1.setStoreOrder(sorder2); item2.setStoreOrder(sorder2); sorder.getItemStoreOrderList().add(item1); sorder.getItemStoreOrderList().add(item2); sorder2 = sodao.persist(sorder2); } /**Save a new entry. * @return * @throws Exception */ public Long saveEntity() throws Exception{ Entry entry = new Entry(); List<StoreOrder> list = new ArrayList<StoreOrder>(); List<ItemStoreOrder> listItem = new ArrayList<ItemStoreOrder>(); ItemStoreOrder item = new ItemStoreOrder(); entry.setInsertDate(new Date()); StoreOrder order = new StoreOrder(); order.setInsertDate(new Date()); Store store = stdao.findById(1L); order.setStore(store); Product product = pdao.findById(1L); item.setProduct(product); listItem.add(item); order.setItemStoreOrderList(listItem); item.setStoreOrder(order); list.add(order); entry.setStoreOrderList(list); entry = dao.persist(entry); return entry.getEntryId(); } /**Verify persist method. * It must persist a new entity and generate a new id * It must has a StoreOrder * @throws Exception */ @Test public void testPersistEntry() throws Exception { Long id = saveEntity(); Long otherId = saveEntity(); assertNotEquals(id, otherId); Entry entry = dao.findById(id); assertNotNull(entry.getStoreOrderList().get(0).getItemStoreOrderList().get(0).getStoreOrder()); } /**Find the entry saved on saveEntry method. * @throws Exception */ @Test public void testFindById() throws Exception{ Long id = saveEntity(); Entry newEntry = dao.findById(id); assertNotNull(newEntry); } /**Try to find a * @throws Exception * */ @Test public void testFindANonEntity() throws Exception{ Long id = saveEntity(); dao.remove(id); assertNull(dao.findById(id)); } /**Try to remove an Entity * @throws Exception */ @Test public void testRemove() throws Exception{ Long id = saveEntity(); dao.remove(id); assertNull(dao.findById(id)); } }
5,241
0.722763
0.714749
199
25.336683
16.63085
97
false
false
0
0
0
0
0
0
2.140703
false
false
2
1395bcdd6faa507ddf7165870dc50790d3951c96
38,783,554,726,407
ba7988caebb32430c26bff197ec8e9f6bef91c44
/src/main/java/com/gtis/portal/service/PfRoleService.java
55f0218170f4a5265bc276b5b1c386350b04b750
[]
no_license
huiyao351/portal-new
https://github.com/huiyao351/portal-new
f799d9f23477451ab1fc668e42103437090170fd
b8f387b43e7a745e2c3b13e64d450d224ba5e331
refs/heads/master
2021-01-20T05:53:28.268000
2017-04-30T01:21:14
2017-04-30T01:21:14
89,822,422
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gtis.portal.service; import com.gtis.portal.entity.PfRole; import com.gtis.portal.model.Ztree; import com.gtis.portal.model.ZtreeChanged; import java.util.LinkedHashMap; import java.util.List; public interface PfRoleService extends BaseService<PfRole, String> { /** * 获取按照行政区代码界别组织的角色树 * @param regionCode * @return */ public Ztree getRoleRegionTree(String regionCode); public void deleteById(String roleId); public List<PfRole> getListByXzqdm(String xzqdm); /** * 获取简单的角色树,没有根据行政区代码字段进行分组 * @param xzqdm * @return */ public List<Ztree> getTreeByXzqdm(String xzqdm); List<PfRole> getRoleByName(String roleName); /** * 查询那些角色拥有该主题的可见权限 * @param subId * @return */ public Ztree getRoleTreeBySubId(String subId,String regionCode); public List<PfRole> getRoleListBySubId(String subId); public List<ZtreeChanged> getRoleRelListBySubId(String subId); public LinkedHashMap<String,PfRole> roleList2RoleMap(List<PfRole> roleList); }
UTF-8
Java
1,169
java
PfRoleService.java
Java
[]
null
[]
package com.gtis.portal.service; import com.gtis.portal.entity.PfRole; import com.gtis.portal.model.Ztree; import com.gtis.portal.model.ZtreeChanged; import java.util.LinkedHashMap; import java.util.List; public interface PfRoleService extends BaseService<PfRole, String> { /** * 获取按照行政区代码界别组织的角色树 * @param regionCode * @return */ public Ztree getRoleRegionTree(String regionCode); public void deleteById(String roleId); public List<PfRole> getListByXzqdm(String xzqdm); /** * 获取简单的角色树,没有根据行政区代码字段进行分组 * @param xzqdm * @return */ public List<Ztree> getTreeByXzqdm(String xzqdm); List<PfRole> getRoleByName(String roleName); /** * 查询那些角色拥有该主题的可见权限 * @param subId * @return */ public Ztree getRoleTreeBySubId(String subId,String regionCode); public List<PfRole> getRoleListBySubId(String subId); public List<ZtreeChanged> getRoleRelListBySubId(String subId); public LinkedHashMap<String,PfRole> roleList2RoleMap(List<PfRole> roleList); }
1,169
0.709953
0.709005
43
23.534883
23.13092
80
false
false
0
0
0
0
0
0
0.418605
false
false
2
b9ea9d5661b2d12b24089f7dc5dc5e9a61b31430
36,593,121,402,364
4d0f0ae2b173480bf83ac742b95edff80350b09c
/app/src/main/java/com/yp/paparazzilive/model/HomePagerModel/LiveList.java
996105bbfdcccf50154519c3f8e2e1477547c6fd
[]
no_license
NBAGroup/Live
https://github.com/NBAGroup/Live
9e0a24676176ec8414096e3ff284a38d56c092aa
524b05bd3f9ea2d412b0880c38c3b850b2674155
refs/heads/master
2020-02-26T16:00:03.501000
2016-09-22T15:03:04
2016-09-22T15:03:04
68,674,457
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yp.paparazzilive.model.HomePagerModel; import java.util.List; /** * Created by hedianbo on 2016/9/20. */ public class LiveList { private List<Live1> data_list; public List<Live1> getData_list() { return data_list; } public void setData_list(List<Live1> data_list) { this.data_list = data_list; } }
UTF-8
Java
353
java
LiveList.java
Java
[ { "context": "rModel;\n\nimport java.util.List;\n\n/**\n * Created by hedianbo on 2016/9/20.\n */\npublic class LiveList {\n\n pr", "end": 102, "score": 0.9995704293251038, "start": 94, "tag": "USERNAME", "value": "hedianbo" } ]
null
[]
package com.yp.paparazzilive.model.HomePagerModel; import java.util.List; /** * Created by hedianbo on 2016/9/20. */ public class LiveList { private List<Live1> data_list; public List<Live1> getData_list() { return data_list; } public void setData_list(List<Live1> data_list) { this.data_list = data_list; } }
353
0.648725
0.620397
19
17.578947
18.270817
53
false
false
0
0
0
0
0
0
0.263158
false
false
2
e01342815afe0fecb191c0ba81e76f58ee2f1b30
36,189,394,486,373
2c37ba67896cb7ef6c012c149f7a7f62239b547d
/src/main/java/frc/robot/CanbusDistanceSensor.java
8114beb101c0db5f6b86fec360c4f83c5e193d38
[]
no_license
2202Programming/Basic_Mecanum2
https://github.com/2202Programming/Basic_Mecanum2
2ede28e0bbf41f2cbf756b9efff0903b69ce3fcd
6e778f97bf1988da910df637f2abe04f59e6cb6e
refs/heads/master
2020-09-14T06:45:43.803000
2019-12-05T02:45:37
2019-12-05T02:45:37
223,054,345
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot; import edu.wpi.first.wpilibj.command.Subsystem; /** * Add your docs here. */ /*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ import java.nio.ByteBuffer; import edu.wpi.first.wpilibj.Sendable; import edu.wpi.first.wpilibj.SendableBase; import edu.wpi.first.wpilibj.smartdashboard.SendableBuilder; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * */ public class CanbusDistanceSensor extends SendableBase implements Sendable { // Message IDs private static final int HEARTBEAT_MESSAGE = 0x18F0FF00; private static final int CALIBRATION_STATE_MESSAGE = 0x0CF91200; private static final int MEASURED_DISTANCE_MESSAGE = 0x0CF91000; private static final int MEASUREMENT_QUALITY_MESSAGE = 0x0CF91100; private static final int RANGING_CONFIGURATION_MESSAGE = 0x0CF91300; private static final int DEVICE_CONFIGURATION_MESSAGE = 0x0CAAFFF9; private static final int kSendMessagePeriod = 0; // LiveWindow color update MS maximum interval (milliseconds) protected final static int LIVE_WINDOW_UPDATE_INTERVAL = 50; private static double lastDistance = 0; public static byte[] hwdata = new byte[8]; private double serialNumber; private double partNumber; private double firmWare; public CanbusDistanceSensor() { // LiveWindow.add(this); } // Messages from device public static byte[] readHeartbeat(int id) { long read = CANSendReceive.readMessage(HEARTBEAT_MESSAGE, id); if (read != -1) hwdata = CANSendReceive.result; return hwdata; } public static int[] getSensorInfo(byte[] hwdata) { int[] temp = new int[3]; // SmartDashboard.putNumber("D5", (int) hwdata[5]); // SmartDashboard.putNumber("D4", (int) hwdata[4]); temp[0] = extractValue(hwdata, 3, 1); temp[1] = extractValue(hwdata, 5, 4); temp[2] = extractValue(hwdata, 7, 6); return temp; } public static int findSensor(int id) { hwdata = readHeartbeat(id); if (hwdata[4] != 0) { return id; } else { return 999; } } public static int[] getDistanceMM(int id) { int[] temp = { 0, 0 }; long read = CANSendReceive.readMessage(MEASURED_DISTANCE_MESSAGE, id); if (read == -1) { return temp; } else { int rangingStatus = Byte.toUnsignedInt(CANSendReceive.result[2]); if (rangingStatus != 0) { temp[0] = -rangingStatus; return temp; } else { // SmartDashboard.putNumber("D1",Byte.toUnsignedInt(CANSendReceive.result[1])); // SmartDashboard.putNumber("D0",Byte.toUnsignedInt(CANSendReceive.result[0])); temp[0] = extractValue(CANSendReceive.result, 1, 0); // temp[0 ]= CANSendReceive.result[1]<<8; // temp[1]= Byte.toUnsignedInt(CANSendReceive.result[0]); // temp[0]+=temp[1]; temp[1] = extractValue(CANSendReceive.result, 7, 4) / 65536; return temp; } } } public static int[] readQuality(int id) { int temp[] = { 0, 0 }; long read = CANSendReceive.readMessage(MEASUREMENT_QUALITY_MESSAGE, id); // SmartDashboard.putNumber("Q3",(int)CANSendReceive.result[3]); // SmartDashboard.putNumber("Q2",(int)CANSendReceive.result[2]); // SmartDashboard.putNumber("Q1",(int)CANSendReceive.result[1]); // SmartDashboard.putNumber("Q0",(int)CANSendReceive.result[0]); if (read != -1) { temp[0] = extractValue(CANSendReceive.result, 3, 0) / 65536; temp[1] = extractValue(CANSendReceive.result, 7, 4) / 65536; } return temp; } public static int[] readCalibrationState(int id) { int temp[] = { 0, 0, 0, 0, 0, 0, 0 }; long read = CANSendReceive.readMessage(CALIBRATION_STATE_MESSAGE, id); if (read != -1) { temp[2] = extractValue(CANSendReceive.result, 2, 1); temp[0] = CANSendReceive.result[0] & 0b00001111; temp[1] = CANSendReceive.result[0] >> 4; } return temp; } // // Messages to device public static void configureRange(int id, int mode) { byte[] data = new byte[3]; int interval = 100; data[0] = (byte) mode; switch (mode) { case 0: interval = 100; break; case 1:// 150ms in 2 byte format interval = 150; break; case 2:// 200ms in 2 byte format interval = 200; break; default: interval = 100; break; } ByteBuffer b = ByteBuffer.allocate(4); b.putInt(interval); byte[] result = b.array(); data[1] = result[1]; data[2] = result[2]; CANSendReceive.sendMessage(RANGING_CONFIGURATION_MESSAGE | id, data, 3, kSendMessagePeriod); } public static void identifyDevice(int id) { byte[] hwdata = new byte[8]; hwdata = readHeartbeat(id); hwdata[0] = 0x0D; CANSendReceive.sendMessage(DEVICE_CONFIGURATION_MESSAGE, hwdata, 6, kSendMessagePeriod); } public static void configureDevice(int oldID, int newID) { byte[] hwdata = new byte[8]; if (newID >= 0 && newID < 33) { hwdata = readHeartbeat(oldID); getSensorInfo(hwdata); hwdata[0] = 0x0C; hwdata[6] = (byte) newID; CANSendReceive.sendMessage(DEVICE_CONFIGURATION_MESSAGE, hwdata, 7, kSendMessagePeriod); } } public static int extractValue(byte[] src, int high, int low) { int temp = 0; int temp1 = 0; int i = 0; temp = (src[high]); for (i = high - 1; i >= low; i--) { temp1 = Byte.toUnsignedInt(src[i]); temp = (temp * 256) + temp1; } return temp; } // https://www.chiefdelphi.com/t/creating-custom-smartdashboard-types-like-pidcommand/162737/8 @Override public void initSendable(SendableBuilder builder) { builder.setSmartDashboardType("ColorProx"); // builder.addDoubleProperty("Range Offset", () -> readCalibrationState()[2], // null); // builder.addDoubleProperty("X Position", () -> readCalibrationState()[0], // null); // builder.addDoubleProperty("Y Position", () -> readCalibrationState()[1], // null); builder.addDoubleProperty("Serial Number", () -> serialNumber, null); builder.addDoubleProperty("Part Number", () -> (double) partNumber, null); builder.addDoubleProperty("Firmware", () -> (double) firmWare, null); // builder.addDoubleProperty("Distance MM", () -> getDistanceMM(), null); // builder.addDoubleProperty("Distance Inch", () -> getDistanceMM() / 25.4, // null); // builder.addDoubleProperty("Ambient Light", () -> readQuality()[0], null); // builder.addDoubleProperty("Std Dev", () -> readQuality()[1], null); } }
UTF-8
Java
7,448
java
CanbusDistanceSensor.java
Java
[]
null
[]
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot; import edu.wpi.first.wpilibj.command.Subsystem; /** * Add your docs here. */ /*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ import java.nio.ByteBuffer; import edu.wpi.first.wpilibj.Sendable; import edu.wpi.first.wpilibj.SendableBase; import edu.wpi.first.wpilibj.smartdashboard.SendableBuilder; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * */ public class CanbusDistanceSensor extends SendableBase implements Sendable { // Message IDs private static final int HEARTBEAT_MESSAGE = 0x18F0FF00; private static final int CALIBRATION_STATE_MESSAGE = 0x0CF91200; private static final int MEASURED_DISTANCE_MESSAGE = 0x0CF91000; private static final int MEASUREMENT_QUALITY_MESSAGE = 0x0CF91100; private static final int RANGING_CONFIGURATION_MESSAGE = 0x0CF91300; private static final int DEVICE_CONFIGURATION_MESSAGE = 0x0CAAFFF9; private static final int kSendMessagePeriod = 0; // LiveWindow color update MS maximum interval (milliseconds) protected final static int LIVE_WINDOW_UPDATE_INTERVAL = 50; private static double lastDistance = 0; public static byte[] hwdata = new byte[8]; private double serialNumber; private double partNumber; private double firmWare; public CanbusDistanceSensor() { // LiveWindow.add(this); } // Messages from device public static byte[] readHeartbeat(int id) { long read = CANSendReceive.readMessage(HEARTBEAT_MESSAGE, id); if (read != -1) hwdata = CANSendReceive.result; return hwdata; } public static int[] getSensorInfo(byte[] hwdata) { int[] temp = new int[3]; // SmartDashboard.putNumber("D5", (int) hwdata[5]); // SmartDashboard.putNumber("D4", (int) hwdata[4]); temp[0] = extractValue(hwdata, 3, 1); temp[1] = extractValue(hwdata, 5, 4); temp[2] = extractValue(hwdata, 7, 6); return temp; } public static int findSensor(int id) { hwdata = readHeartbeat(id); if (hwdata[4] != 0) { return id; } else { return 999; } } public static int[] getDistanceMM(int id) { int[] temp = { 0, 0 }; long read = CANSendReceive.readMessage(MEASURED_DISTANCE_MESSAGE, id); if (read == -1) { return temp; } else { int rangingStatus = Byte.toUnsignedInt(CANSendReceive.result[2]); if (rangingStatus != 0) { temp[0] = -rangingStatus; return temp; } else { // SmartDashboard.putNumber("D1",Byte.toUnsignedInt(CANSendReceive.result[1])); // SmartDashboard.putNumber("D0",Byte.toUnsignedInt(CANSendReceive.result[0])); temp[0] = extractValue(CANSendReceive.result, 1, 0); // temp[0 ]= CANSendReceive.result[1]<<8; // temp[1]= Byte.toUnsignedInt(CANSendReceive.result[0]); // temp[0]+=temp[1]; temp[1] = extractValue(CANSendReceive.result, 7, 4) / 65536; return temp; } } } public static int[] readQuality(int id) { int temp[] = { 0, 0 }; long read = CANSendReceive.readMessage(MEASUREMENT_QUALITY_MESSAGE, id); // SmartDashboard.putNumber("Q3",(int)CANSendReceive.result[3]); // SmartDashboard.putNumber("Q2",(int)CANSendReceive.result[2]); // SmartDashboard.putNumber("Q1",(int)CANSendReceive.result[1]); // SmartDashboard.putNumber("Q0",(int)CANSendReceive.result[0]); if (read != -1) { temp[0] = extractValue(CANSendReceive.result, 3, 0) / 65536; temp[1] = extractValue(CANSendReceive.result, 7, 4) / 65536; } return temp; } public static int[] readCalibrationState(int id) { int temp[] = { 0, 0, 0, 0, 0, 0, 0 }; long read = CANSendReceive.readMessage(CALIBRATION_STATE_MESSAGE, id); if (read != -1) { temp[2] = extractValue(CANSendReceive.result, 2, 1); temp[0] = CANSendReceive.result[0] & 0b00001111; temp[1] = CANSendReceive.result[0] >> 4; } return temp; } // // Messages to device public static void configureRange(int id, int mode) { byte[] data = new byte[3]; int interval = 100; data[0] = (byte) mode; switch (mode) { case 0: interval = 100; break; case 1:// 150ms in 2 byte format interval = 150; break; case 2:// 200ms in 2 byte format interval = 200; break; default: interval = 100; break; } ByteBuffer b = ByteBuffer.allocate(4); b.putInt(interval); byte[] result = b.array(); data[1] = result[1]; data[2] = result[2]; CANSendReceive.sendMessage(RANGING_CONFIGURATION_MESSAGE | id, data, 3, kSendMessagePeriod); } public static void identifyDevice(int id) { byte[] hwdata = new byte[8]; hwdata = readHeartbeat(id); hwdata[0] = 0x0D; CANSendReceive.sendMessage(DEVICE_CONFIGURATION_MESSAGE, hwdata, 6, kSendMessagePeriod); } public static void configureDevice(int oldID, int newID) { byte[] hwdata = new byte[8]; if (newID >= 0 && newID < 33) { hwdata = readHeartbeat(oldID); getSensorInfo(hwdata); hwdata[0] = 0x0C; hwdata[6] = (byte) newID; CANSendReceive.sendMessage(DEVICE_CONFIGURATION_MESSAGE, hwdata, 7, kSendMessagePeriod); } } public static int extractValue(byte[] src, int high, int low) { int temp = 0; int temp1 = 0; int i = 0; temp = (src[high]); for (i = high - 1; i >= low; i--) { temp1 = Byte.toUnsignedInt(src[i]); temp = (temp * 256) + temp1; } return temp; } // https://www.chiefdelphi.com/t/creating-custom-smartdashboard-types-like-pidcommand/162737/8 @Override public void initSendable(SendableBuilder builder) { builder.setSmartDashboardType("ColorProx"); // builder.addDoubleProperty("Range Offset", () -> readCalibrationState()[2], // null); // builder.addDoubleProperty("X Position", () -> readCalibrationState()[0], // null); // builder.addDoubleProperty("Y Position", () -> readCalibrationState()[1], // null); builder.addDoubleProperty("Serial Number", () -> serialNumber, null); builder.addDoubleProperty("Part Number", () -> (double) partNumber, null); builder.addDoubleProperty("Firmware", () -> (double) firmWare, null); // builder.addDoubleProperty("Distance MM", () -> getDistanceMM(), null); // builder.addDoubleProperty("Distance Inch", () -> getDistanceMM() / 25.4, // null); // builder.addDoubleProperty("Ambient Light", () -> readQuality()[0], null); // builder.addDoubleProperty("Std Dev", () -> readQuality()[1], null); } }
7,448
0.60862
0.578679
226
31.960176
28.457594
96
false
false
0
0
0
0
0
0
0.79646
false
false
2
11e643f2f25b6e05b55f56e4742d5250ff2ba030
34,136,400,125,952
4307c9e92ba65776da7ca89fb2dfdd7ce545e384
/src/test/java/com/hlytec/cloud/NetserviceApplicationTests.java
820f0e67a931ab03ae05c38fd479d6a7a828ce27
[ "MIT" ]
permissive
shanghaif/iot-service
https://github.com/shanghaif/iot-service
1822614854346841f6526f1f79f4422459d23172
b2b342ae14105cfdb8b7e32d3132a2a6ddb83a28
refs/heads/main
2023-07-28T15:29:56.821000
2021-08-26T09:27:18
2021-08-26T09:27:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hlytec.cloud; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import java.util.Date; @SpringBootTest class NetserviceApplicationTests { }
UTF-8
Java
201
java
NetserviceApplicationTests.java
Java
[]
null
[]
package com.hlytec.cloud; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import java.util.Date; @SpringBootTest class NetserviceApplicationTests { }
201
0.820895
0.820895
10
19.1
18.970766
60
false
false
0
0
0
0
0
0
0.4
false
false
2
6131db5a1f3fcbf0a53b1352f3503269c68d232b
6,004,364,309,364
2bd7643730a0048e0ba1e7bb663a97166c54dc54
/EBPSv2/src/main/java/com/service/utility/EmailSendingPandingServiceImp.java
72001feeadf10a934ee729e862c17ff116a07749
[]
no_license
bkings/BuildingPermitDynamic
https://github.com/bkings/BuildingPermitDynamic
3f8b4d7fa8aaff45b43f05fc16fcb1ea54da3ad7
bb7322f6e04b2017854a5ceebcf4b37d755d000b
refs/heads/master
2023-02-16T20:46:37.209000
2021-01-17T06:40:25
2021-01-17T06:40:25
299,945,567
1
0
null
false
2020-10-21T13:30:47
2020-09-30T14:25:30
2020-10-21T11:38:46
2020-10-21T13:30:13
56,631
1
0
0
Java
false
false
package com.service.utility; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.config.JWTToken; import com.dao.utility.DaoEmailSendingPanding; import com.model.utility.EmailSendingPanding; @Service public class EmailSendingPandingServiceImp implements EmailSendingPandingService { @Autowired DaoEmailSendingPanding da; @Override public Object getAll() { return da.getRecord("SELECT date_time \"dateTime\",email,body,subject,application_no \"applicationNo\",CONCAT(application_no,email,date_time) AS id FROM email_sending_panding WHERE status='Y'"); } @Override public Object save(EmailSendingPanding obj, String Authorization) { model.Message message = new model.Message(); String msg = ""; int row; JWTToken td = new JWTToken(Authorization); if (!td.isStatus()) { return message.respondWithError("invalid token"); } try { row = da.save(obj); msg = da.getMsg(); if (row > 0) { return message.respondWithMessage("Success"); } else if (msg.contains("Duplicate entry")) { msg = "This record already exist"; } return message.respondWithError(msg); } catch (Exception e) { return message.respondWithError(e.getMessage()); } } @Override public Object update(String id, String Authorization) { model.Message message = new model.Message(); try { String sql = "UPDATE email_sending_panding SET status='S' WHERE CONCAT(application_no,email,date_time)='" + id + "'"; int row = da.delete(sql); String msg = da.getMsg(); if (row > 0) { return message.respondWithMessage("Success"); } else if (msg.contains("Duplicate entry")) { msg = "This record already exist"; } return message.respondWithError(msg); } catch (Exception e) { return message.respondWithError(e.getMessage()); } } }
UTF-8
Java
2,164
java
EmailSendingPandingServiceImp.java
Java
[]
null
[]
package com.service.utility; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.config.JWTToken; import com.dao.utility.DaoEmailSendingPanding; import com.model.utility.EmailSendingPanding; @Service public class EmailSendingPandingServiceImp implements EmailSendingPandingService { @Autowired DaoEmailSendingPanding da; @Override public Object getAll() { return da.getRecord("SELECT date_time \"dateTime\",email,body,subject,application_no \"applicationNo\",CONCAT(application_no,email,date_time) AS id FROM email_sending_panding WHERE status='Y'"); } @Override public Object save(EmailSendingPanding obj, String Authorization) { model.Message message = new model.Message(); String msg = ""; int row; JWTToken td = new JWTToken(Authorization); if (!td.isStatus()) { return message.respondWithError("invalid token"); } try { row = da.save(obj); msg = da.getMsg(); if (row > 0) { return message.respondWithMessage("Success"); } else if (msg.contains("Duplicate entry")) { msg = "This record already exist"; } return message.respondWithError(msg); } catch (Exception e) { return message.respondWithError(e.getMessage()); } } @Override public Object update(String id, String Authorization) { model.Message message = new model.Message(); try { String sql = "UPDATE email_sending_panding SET status='S' WHERE CONCAT(application_no,email,date_time)='" + id + "'"; int row = da.delete(sql); String msg = da.getMsg(); if (row > 0) { return message.respondWithMessage("Success"); } else if (msg.contains("Duplicate entry")) { msg = "This record already exist"; } return message.respondWithError(msg); } catch (Exception e) { return message.respondWithError(e.getMessage()); } } }
2,164
0.612754
0.61183
66
31.787878
33.297791
202
false
false
0
0
0
0
0
0
0.575758
false
false
2
4caeec07362d336ffe53b32c53e12e493c07a4bc
26,852,135,558,756
e54bc53c7381551cbf0d3837705d30ed301c106e
/study-json-to-pojo/src/main/java/org/sagebionetworks/schema/generator/FileUtils.java
c449a93880df5ab276b0f7105922c8e0953a2ef2
[]
no_license
bage2014/study
https://github.com/bage2014/study
8e72f85a02d63f957bf0b6d83955a8e5abe50fc7
bb124ef5fc4f8f7a51dba08b5a5230bc870245d0
refs/heads/master
2023-08-25T18:36:31.609000
2023-08-25T10:41:15
2023-08-25T10:41:15
135,044,737
347
87
null
false
2022-12-17T06:21:05
2018-05-27T12:35:53
2022-12-14T22:50:31
2022-12-17T06:21:03
119,108
231
65
71
Java
false
false
package org.sagebionetworks.schema.generator; import java.io.BufferedInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Simple helper for basic file operations. * * @author John * */ public class FileUtils { /** * The recursive iterator can be used to walk all files in a directory tree. * Children will appear before parent directories so this can be used for * recursive deletes. * * @param root * @param filter * @return */ public static Iterator<File> getRecursiveIterator(File root, FileFilter filter) { // Start with a list List<File> list = new LinkedList<File>(); // Build up the list addAllChildren(root, filter, list); return list.iterator(); } /** * Helper recursive method to build up a list of file from. * * @param root * @param filter * @param list */ private static void addAllChildren(File root, FileFilter filter, List<File> list) { if (root.isDirectory()) { // List all files and directories without filtering. File[] array = root.listFiles(); for (File child : array) { addAllChildren(child, filter, list); } } // Add this to the list if accepted. if (filter == null || filter.accept(root)) { list.add(root); } } /** * Read a file into a string. * * @param toLoad * @return * @throws IOException */ public static String readToString(File toLoad) throws IOException { if (toLoad == null) throw new IllegalArgumentException("File cannot be null"); InputStream in = new FileInputStream(toLoad); return readToString(in); } /** * Read an input stream into a string. * * @param in * @return * @throws IOException */ public static String readToString(InputStream in) throws IOException { try { BufferedInputStream bufferd = new BufferedInputStream(in); byte[] buffer = new byte[1024]; StringBuilder builder = new StringBuilder(); int index = -1; while ((index = bufferd.read(buffer, 0, buffer.length)) > 0) { builder.append(new String(buffer, 0, index, "UTF-8")); } return builder.toString(); } finally { in.close(); } } /** * Recursively delete a directory and all sub-directories. * * @param directory */ public static void recursivelyDeleteDirectory(File directory) { // Get the recursive iterator Iterator<File> it = getRecursiveIterator(directory, null); while (it.hasNext()) { it.next().delete(); } } /** * Create a temporary directory using the given name * * @return * @throws IOException */ public static File createTempDirectory(String name) throws IOException { // Start will a temp file File temp = File.createTempFile(name, ""); // Delete the file temp.delete(); // Convert it a directory temp.mkdir(); return temp; } }
UTF-8
Java
2,952
java
FileUtils.java
Java
[ { "context": "e helper for basic file operations.\n * \n * @author John\n * \n */\npublic class FileUtils {\n\n\t/**\n\t * The re", "end": 366, "score": 0.9991557598114014, "start": 362, "tag": "NAME", "value": "John" } ]
null
[]
package org.sagebionetworks.schema.generator; import java.io.BufferedInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Simple helper for basic file operations. * * @author John * */ public class FileUtils { /** * The recursive iterator can be used to walk all files in a directory tree. * Children will appear before parent directories so this can be used for * recursive deletes. * * @param root * @param filter * @return */ public static Iterator<File> getRecursiveIterator(File root, FileFilter filter) { // Start with a list List<File> list = new LinkedList<File>(); // Build up the list addAllChildren(root, filter, list); return list.iterator(); } /** * Helper recursive method to build up a list of file from. * * @param root * @param filter * @param list */ private static void addAllChildren(File root, FileFilter filter, List<File> list) { if (root.isDirectory()) { // List all files and directories without filtering. File[] array = root.listFiles(); for (File child : array) { addAllChildren(child, filter, list); } } // Add this to the list if accepted. if (filter == null || filter.accept(root)) { list.add(root); } } /** * Read a file into a string. * * @param toLoad * @return * @throws IOException */ public static String readToString(File toLoad) throws IOException { if (toLoad == null) throw new IllegalArgumentException("File cannot be null"); InputStream in = new FileInputStream(toLoad); return readToString(in); } /** * Read an input stream into a string. * * @param in * @return * @throws IOException */ public static String readToString(InputStream in) throws IOException { try { BufferedInputStream bufferd = new BufferedInputStream(in); byte[] buffer = new byte[1024]; StringBuilder builder = new StringBuilder(); int index = -1; while ((index = bufferd.read(buffer, 0, buffer.length)) > 0) { builder.append(new String(buffer, 0, index, "UTF-8")); } return builder.toString(); } finally { in.close(); } } /** * Recursively delete a directory and all sub-directories. * * @param directory */ public static void recursivelyDeleteDirectory(File directory) { // Get the recursive iterator Iterator<File> it = getRecursiveIterator(directory, null); while (it.hasNext()) { it.next().delete(); } } /** * Create a temporary directory using the given name * * @return * @throws IOException */ public static File createTempDirectory(String name) throws IOException { // Start will a temp file File temp = File.createTempFile(name, ""); // Delete the file temp.delete(); // Convert it a directory temp.mkdir(); return temp; } }
2,952
0.677846
0.674797
126
22.428572
20.753439
77
false
false
0
0
0
0
0
0
1.698413
false
false
2
8e4a24837c915286b86469ef71e06ba1ae19736f
19,138,374,324,878
c6112fbf1614c39d68f773e90f0e3d4c43370c81
/app/src/main/java/com/example/leeandroid/bing/adapter/ListAdapter.java
adef5580fa1a8475bce12a64300f4643a24b9dde
[]
no_license
duanchaozhong/BIND
https://github.com/duanchaozhong/BIND
9f53b55cafe41b721e44276d2b13b58b93abcb22
528122771b283ea9e4641644eb5ef7cad0ddb1f0
refs/heads/master
2019-07-09T01:09:01.521000
2017-05-22T22:03:28
2017-05-22T22:03:28
88,456,718
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.leeandroid.bing.adapter; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.example.leeandroid.bing.R; import com.example.leeandroid.bing.activity.FreeActivity; import com.example.leeandroid.bing.activity.Info2Activity; import com.example.leeandroid.bing.activity.Info3Activity; import com.example.leeandroid.bing.activity.pay.PayActivity; import com.example.leeandroid.bing.activity.pdf.DownLoaderActivity; import com.example.leeandroid.bing.activity.pin.Yupin2Activity; import com.example.leeandroid.bing.activity.pin.Yupin3Activity; import com.example.leeandroid.bing.activity.pin.YupinActivity; import com.example.leeandroid.bing.activity.xun.XunJiaActivity; import com.example.leeandroid.bing.model.AllListBean; import com.example.leeandroid.bing.model.GetLpBean; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by Administrator on 2016/8/9. */ public class ListAdapter extends BaseAdapter { private int k1=0; private int k2=0; private static int index=-1; private Context context = null; private List<AllListBean.DataBean.ListBean> list = null; private LayoutInflater inflater = null; public ListAdapter(Context context, List<AllListBean.DataBean.ListBean> list) { this.context = context; this.list = list; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = inflater.inflate(R.layout.item_allfragment, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.itemDoneChange.setText(list.get(position).getStatusName()+""); //此处一堆判断,逻辑复杂 final int status = list.get(position).getStatus(); int a1=0; int a2=0; int b1=0; double pric=0.0; if (status != 1) { //显示3个按钮 // //先看颜色 holder.textView5.setVisibility(View.INVISIBLE); holder.textView3.setVisibility(View.INVISIBLE); holder.itemDonePay.setVisibility(View.INVISIBLE); holder.itemDonePaygragy.setVisibility(View.INVISIBLE); if (list.get(position).getXjBtn() == 0) { //灰色,失去焦点,询价 holder.itemDoneOne.setVisibility(View.INVISIBLE); holder.itemDoneGray.setVisibility(View.VISIBLE); holder.itemDoneBlue.setVisibility(View.INVISIBLE); } else if (list.get(position).getXjBtn() == 1) { //灰色,失去焦点 holder.itemDoneOne.setVisibility(View.INVISIBLE); holder.itemDoneGray.setVisibility(View.VISIBLE); holder.itemDoneBlue.setVisibility(View.INVISIBLE); } else { //黄色,点击结果页面 holder.itemDoneOne.setVisibility(View.VISIBLE); holder.itemDoneGray.setVisibility(View.INVISIBLE); holder.itemDoneBlue.setVisibility(View.INVISIBLE); holder.itemDoneOne.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, XunJiaActivity.class); intent.putExtra("xmId", list.get(position).getXmId()); context.startActivity(intent); // Intent intent=new Intent(context, FreeActivity.class); // context.startActivity(intent); // ((Activity)context).finish(); } }); } //**************** if (list.get(position).getYpBtn() == 0) { //灰色,失去焦点,预评 if ("1".equals(list.get(position).getNeedYpReport()+"")){ //**中 holder.itemDoneTwogray.setVisibility(View.INVISIBLE); holder.itemDoneTwo.setVisibility(View.VISIBLE); holder.itemDoneTwoorange.setVisibility(View.INVISIBLE); holder.itemDoneTwoblue.setVisibility(View.INVISIBLE); a1=0; }else { holder.itemDoneTwogray.setVisibility(View.VISIBLE); holder.itemDoneTwo.setVisibility(View.INVISIBLE); holder.itemDoneTwoorange.setVisibility(View.INVISIBLE); holder.itemDoneTwoblue.setVisibility(View.INVISIBLE); a1=1; } } else if (list.get(position).getYpBtn() == 1) { //蓝色 holder.itemDoneTwogray.setVisibility(View.INVISIBLE); holder.itemDoneTwo.setVisibility(View.INVISIBLE); holder.itemDoneTwoorange.setVisibility(View.INVISIBLE); holder.itemDoneTwoblue.setVisibility(View.VISIBLE); a1=2; holder.itemDoneTwoblue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (list.get(position).getBgBtn() == 1){ k1=1; index=1; }else { index=0; } Intent intent = new Intent(context, Yupin2Activity.class); intent.putExtra("xmId",list.get(position).getXmId()); intent.putExtra("index",index); intent.putExtra("k2",1); context.startActivity(intent); // ((Activity)context).finish(); } }); } else { //黄色,点击结果页面,pdf holder.itemDoneTwogray.setVisibility(View.INVISIBLE); holder.itemDoneTwoorange.setVisibility(View.VISIBLE); holder.itemDoneTwo.setVisibility(View.INVISIBLE); holder.itemDoneTwoblue.setVisibility(View.INVISIBLE); a1=3; holder.itemDoneTwoorange.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, DownLoaderActivity.class); intent.putExtra("url",list.get(position).getYpUrl()+""); context.startActivity(intent); } }); } //*********** if (list.get(position).getBgBtn() == 0) { //灰色,失去焦点,报告 if ("1".equals(list.get(position).getNeedBgReport()+"")){ holder.itemDoneThreegray.setVisibility(View.INVISIBLE); holder.itemDoneThree.setVisibility(View.VISIBLE); holder.itemDoneThreeorange.setVisibility(View.INVISIBLE); holder.itemDoneThreeblue.setVisibility(View.INVISIBLE); a2=0; }else { holder.itemDoneThreegray.setVisibility(View.VISIBLE); holder.itemDoneThree.setVisibility(View.INVISIBLE); holder.itemDoneThreeorange.setVisibility(View.INVISIBLE); holder.itemDoneThreeblue.setVisibility(View.INVISIBLE); a2=1; } } else if (list.get(position).getBgBtn() == 1) { //蓝色 holder.itemDoneThreegray.setVisibility(View.INVISIBLE); holder.itemDoneThree.setVisibility(View.INVISIBLE); holder.itemDoneThreeorange.setVisibility(View.INVISIBLE); holder.itemDoneThreeblue.setVisibility(View.VISIBLE); a2=2; holder.itemDoneThreeblue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (list.get(position).getYpBtn() == 1){ k2=1; index=1; }else { k2=0; index=2; } Intent intent = new Intent(context, Yupin3Activity.class); intent.putExtra("xmId",list.get(position).getXmId()); intent.putExtra("k2",k2); intent.putExtra("index",index); context.startActivity(intent); // ((Activity)context).finish(); } }); } else { //黄色,点击结果页面,pdf holder.itemDoneThreegray.setVisibility(View.INVISIBLE); holder.itemDoneThreeorange.setVisibility(View.VISIBLE); holder.itemDoneThree.setVisibility(View.INVISIBLE); holder.itemDoneThreeblue.setVisibility(View.INVISIBLE); a2=3; holder.itemDoneThreeorange.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, DownLoaderActivity.class); intent.putExtra("url",list.get(position).getBgUrl()+""); context.startActivity(intent); } }); } } else { //显示2个按钮 holder.itemDonePay.setVisibility(View.VISIBLE); holder.textView3.setVisibility(View.VISIBLE); holder.textView5.setVisibility(View.VISIBLE); holder.itemDoneOne.setVisibility(View.INVISIBLE); holder.itemDoneGray.setVisibility(View.INVISIBLE); holder.itemDoneBlue.setVisibility(View.INVISIBLE); holder.itemDoneTwo.setVisibility(View.INVISIBLE); holder.itemDoneTwoorange.setVisibility(View.INVISIBLE); holder.itemDoneTwoblue.setVisibility(View.INVISIBLE); holder.itemDoneThreeblue.setVisibility(View.INVISIBLE); holder.itemDoneThreeorange.setVisibility(View.INVISIBLE); holder.itemDoneThree.setVisibility(View.INVISIBLE); double price = 0.0; if (list.get(position).getPayBtn() == 0) { //显示灰色 holder.textView3.setVisibility(View.INVISIBLE); holder.textView5.setVisibility(View.INVISIBLE); holder.itemDonePay.setVisibility(View.INVISIBLE); holder.itemDonePaygragy.setVisibility(View.VISIBLE); b1=0; } else if (list.get(position).getPayBtn() == 1) { b1=1; // holder.itemDoneChange.setText("待付款"); holder.textView3.setVisibility(View.VISIBLE); holder.textView5.setVisibility(View.VISIBLE); holder.itemDonePay.setVisibility(View.VISIBLE); holder.itemDonePaygragy.setVisibility(View.INVISIBLE); holder.textView5.setText(list.get(position).getPayingXj() + ""); Log.i("jiage1", list.get(position).getPayingXj() + ""); price = list.get(position).getPayingXj(); //添加跳转付款 final double finalPrice = price; pric=price; holder.itemDonePay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PayActivity.class); intent.putExtra("payinxj", finalPrice); context.startActivity(intent); } }); } else if (list.get(position).getPayBtn() == 2) { b1=1; // holder.itemDoneChange.setText("待付款"); holder.textView3.setVisibility(View.VISIBLE); holder.textView5.setVisibility(View.VISIBLE); holder.itemDonePay.setVisibility(View.VISIBLE); holder.itemDonePaygragy.setVisibility(View.INVISIBLE); holder.textView5.setText(list.get(position).getPayingYp() + ""); Log.i("jiage2", list.get(position).getPayingYp() + ""); price = list.get(position).getPayingYp(); //添加跳转付款 final double finalPrice = price; pric=price; holder.itemDonePay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PayActivity.class); intent.putExtra("payinxj", finalPrice); context.startActivity(intent); } }); } else { holder.itemDoneChange.setText("待付款"); b1=1; holder.textView3.setVisibility(View.VISIBLE); holder.textView5.setVisibility(View.VISIBLE); holder.itemDonePay.setVisibility(View.VISIBLE); holder.itemDonePaygragy.setVisibility(View.INVISIBLE); holder.textView5.setText(list.get(position).getPayingBg() + ""); Log.i("jiage3", list.get(position).getPayingBg() + ""); price = list.get(position).getPayingBg(); //添加跳转付款 final double finalPrice = price; pric=price; holder.itemDonePay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PayActivity.class); intent.putExtra("payinxj", finalPrice); context.startActivity(intent); } }); } } //加载 holder.itemDoneName.setText(list.get(position).getLpmc() + ""); holder.itemDoneAddress.setText(list.get(position).getWydz() + ""); //new DecimalFormat("######0.00").format(resultGuBean.getData().getSumMoney()/10000)+"" if (list.get(position).getSumMoeny()==0){ //隐藏 holder.price.setVisibility(View.INVISIBLE); holder.textView6.setVisibility(View.INVISIBLE); holder.itemDonePrice.setVisibility(View.INVISIBLE); }else { holder.price.setVisibility(View.VISIBLE); holder.textView6.setVisibility(View.VISIBLE); holder.itemDonePrice.setVisibility(View.VISIBLE); // if ("东方知音苑".equals(list.get(position).getLpmc())){ // holder.price.setText("673.57"); // }else { // // holder.price.setText(new DecimalFormat("######0.00").format((double)list.get(position).getSumMoeny()/10000) + ""); // } // Log.i("price",totalMoney(list.get(position).getSumMoeny()/10000)+"nmnmnmnmnm"); holder.price.setText(totalMoney(list.get(position).getSumMoeny()/10000)+ ""); } //格式化时间,并进行赋值 Long updateTime = list.get(position).getCreateDate(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd "); // Long time = new Long(updateTime); // String datetime = format.format(updateTime * 1000); //时间值 String datetime = format.format(updateTime); holder.itemDoneTime.setText(datetime); // final String title = list.get(position).getTitle(); holder.itemTitle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ("null".equals(list.get(position).getLpxxId() + "")) { Toast.makeText(context, "暂无楼盘信息", Toast.LENGTH_SHORT).show(); } else { Intent intent = new Intent(context, Info3Activity.class); intent.putExtra("lpxxId", list.get(position).getLpxxId() + ""); intent.putExtra("lpmc",list.get(position).getLpmc() + ""); context.startActivity(intent); } } }); //单击跳转到详情页 final int finalA = a1; final int finalA1 = a2; final int finalB = b1; final double finalPric = pric; holder.test.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ("null".equals(list.get(position).getLpxxId() + "")) { Intent intent = new Intent(context, Info2Activity.class); intent.putExtra("xmId", list.get(position).getXmId() + ""); intent.putExtra("status",status); intent.putExtra("a1", finalA); intent.putExtra("a2", finalA1); intent.putExtra("b1", finalB); intent.putExtra("pric", finalPric); intent.putExtra("wydz",list.get(position).getWydz()+""); intent.putExtra("url1",list.get(position).getYpUrl()+""); intent.putExtra("url2",list.get(position).getBgUrl()+""); intent.putExtra("statusname",list.get(position).getStatusName()+""); intent.putExtra("lpmc",list.get(position).getLpmc() + ""); intent.putExtra("assignee",list.get(position).getAssignee()); Log.i("dczid",list.get(position).getAssignee()); context.startActivity(intent); // Toast.makeText(context, "暂无楼盘信息", Toast.LENGTH_SHORT).show(); } else { Intent intent = new Intent(context, Info2Activity.class); intent.putExtra("xmId", list.get(position).getXmId() + ""); intent.putExtra("status",status); intent.putExtra("a1", finalA); intent.putExtra("a2", finalA1); intent.putExtra("b1", finalB); intent.putExtra("pric", finalPric); intent.putExtra("wydz",list.get(position).getWydz()+""); intent.putExtra("url1",list.get(position).getYpUrl()+""); intent.putExtra("url2",list.get(position).getBgUrl()+""); intent.putExtra("statusname",list.get(position).getStatusName()+""); intent.putExtra("lpmc",list.get(position).getLpmc() + ""); intent.putExtra("assignee",list.get(position).getAssignee()); Log.i("dczid",list.get(position).getAssignee()); context.startActivity(intent); } } }); /** * 我新加的内容 * */ if(list.get(position).getB5().equals("1")){ //如果b5是1就是已读内容 holder.itemDoneName.setTextColor(Color.parseColor("#7e7e7e")); holder.itemDoneAddress.setTextColor(Color.parseColor("#c1c1c1")); holder.itemDoneTime.setTextColor(Color.parseColor("#c1c1c1")); holder.itemDoneChange.setTextColor(Color.parseColor("#7e7e7e")); holder.itemDonePrice.setTextColor(Color.parseColor("#c1c1c1")); holder.price.setTextColor(Color.parseColor("#c1c1c1")); holder.textView6.setTextColor(Color.parseColor("#c1c1c1")); }else { holder.itemDoneName.setTextColor(Color.parseColor("#2a2a2a")); holder.itemDoneAddress.setTextColor(Color.parseColor("#666666")); holder.itemDoneTime.setTextColor(Color.parseColor("#666666")); holder.itemDoneChange.setTextColor(Color.parseColor("#2a2a2a")); holder.itemDonePrice.setTextColor(Color.parseColor("#2a2a2a")); holder.price.setTextColor(Color.parseColor("#2a2a2a")); holder.textView6.setTextColor(Color.parseColor("#2a2a2a")); } return convertView; } public static String totalMoney(double money) { java.math.BigDecimal bigDec = new java.math.BigDecimal(money); double total = bigDec.setScale(2, java.math.BigDecimal.ROUND_HALF_UP) .doubleValue(); DecimalFormat df = new DecimalFormat("0.00"); return df.format(total); } //加载数据 public void reloadListView(List<AllListBean.DataBean.ListBean> _list, boolean isClear) { if (isClear) { list.clear(); } list.addAll(_list); notifyDataSetChanged(); } public GetLpBean parseJsonToGetLpBean(String jsonString) { Gson gson = new Gson(); GetLpBean bean = gson.fromJson(jsonString, new TypeToken<GetLpBean>() { }.getType()); return bean; } static class ViewHolder { @BindView(R.id.imageView_item_done_image) ImageView imageViewItemDoneImage; @BindView(R.id.item_done_name) //名字 TextView itemDoneName; @BindView(R.id.item_arrow_waitpay) ImageView itemArrowWaitpay; @BindView(R.id.item_done_address) //地址 TextView itemDoneAddress; @BindView(R.id.item_done_time) //时间 TextView itemDoneTime; @BindView(R.id.item_done_change) //状态 TextView itemDoneChange; @BindView(R.id.item_done_price) //价格单位 TextView itemDonePrice; @BindView(R.id.price) //价格 TextView price; @BindView(R.id.textView6) //¥ TextView textView6; @BindView(R.id.test) LinearLayout test; @BindView(R.id.item_done_three) TextView itemDoneThree; @BindView(R.id.item_done_two) TextView itemDoneTwo; @BindView(R.id.item_done_one) TextView itemDoneOne; @BindView(R.id.textView3) TextView textView3; @BindView(R.id.textView5) TextView textView5; @BindView(R.id.item_done_pay) TextView itemDonePay; @BindView(R.id.item_done_gray) TextView itemDoneGray; @BindView(R.id.item_done_blue) TextView itemDoneBlue; @BindView(R.id.item_title) LinearLayout itemTitle; @BindView(R.id.item_done_twoblue) TextView itemDoneTwoblue; @BindView(R.id.item_done_twoorange) TextView itemDoneTwoorange; @BindView(R.id.item_done_threeblue) TextView itemDoneThreeblue; @BindView(R.id.item_done_threeorange) TextView itemDoneThreeorange; @BindView(R.id.item_done_paygragy) TextView itemDonePaygragy; @BindView(R.id.item_done_threegray) TextView itemDoneThreegray; @BindView(R.id.item_done_twogray) TextView itemDoneTwogray; ViewHolder(View view) { ButterKnife.bind(this, view); } } }
UTF-8
Java
24,293
java
ListAdapter.java
Java
[ { "context": "import butterknife.ButterKnife;\n\n/**\n * Created by Administrator on 2016/8/9.\n */\npublic class ListAdapter extends", "end": 1413, "score": 0.7781963348388672, "start": 1400, "tag": "USERNAME", "value": "Administrator" }, { "context": "tion).getPayingXj() + \"\");\n...
null
[]
package com.example.leeandroid.bing.adapter; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.example.leeandroid.bing.R; import com.example.leeandroid.bing.activity.FreeActivity; import com.example.leeandroid.bing.activity.Info2Activity; import com.example.leeandroid.bing.activity.Info3Activity; import com.example.leeandroid.bing.activity.pay.PayActivity; import com.example.leeandroid.bing.activity.pdf.DownLoaderActivity; import com.example.leeandroid.bing.activity.pin.Yupin2Activity; import com.example.leeandroid.bing.activity.pin.Yupin3Activity; import com.example.leeandroid.bing.activity.pin.YupinActivity; import com.example.leeandroid.bing.activity.xun.XunJiaActivity; import com.example.leeandroid.bing.model.AllListBean; import com.example.leeandroid.bing.model.GetLpBean; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by Administrator on 2016/8/9. */ public class ListAdapter extends BaseAdapter { private int k1=0; private int k2=0; private static int index=-1; private Context context = null; private List<AllListBean.DataBean.ListBean> list = null; private LayoutInflater inflater = null; public ListAdapter(Context context, List<AllListBean.DataBean.ListBean> list) { this.context = context; this.list = list; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = inflater.inflate(R.layout.item_allfragment, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.itemDoneChange.setText(list.get(position).getStatusName()+""); //此处一堆判断,逻辑复杂 final int status = list.get(position).getStatus(); int a1=0; int a2=0; int b1=0; double pric=0.0; if (status != 1) { //显示3个按钮 // //先看颜色 holder.textView5.setVisibility(View.INVISIBLE); holder.textView3.setVisibility(View.INVISIBLE); holder.itemDonePay.setVisibility(View.INVISIBLE); holder.itemDonePaygragy.setVisibility(View.INVISIBLE); if (list.get(position).getXjBtn() == 0) { //灰色,失去焦点,询价 holder.itemDoneOne.setVisibility(View.INVISIBLE); holder.itemDoneGray.setVisibility(View.VISIBLE); holder.itemDoneBlue.setVisibility(View.INVISIBLE); } else if (list.get(position).getXjBtn() == 1) { //灰色,失去焦点 holder.itemDoneOne.setVisibility(View.INVISIBLE); holder.itemDoneGray.setVisibility(View.VISIBLE); holder.itemDoneBlue.setVisibility(View.INVISIBLE); } else { //黄色,点击结果页面 holder.itemDoneOne.setVisibility(View.VISIBLE); holder.itemDoneGray.setVisibility(View.INVISIBLE); holder.itemDoneBlue.setVisibility(View.INVISIBLE); holder.itemDoneOne.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, XunJiaActivity.class); intent.putExtra("xmId", list.get(position).getXmId()); context.startActivity(intent); // Intent intent=new Intent(context, FreeActivity.class); // context.startActivity(intent); // ((Activity)context).finish(); } }); } //**************** if (list.get(position).getYpBtn() == 0) { //灰色,失去焦点,预评 if ("1".equals(list.get(position).getNeedYpReport()+"")){ //**中 holder.itemDoneTwogray.setVisibility(View.INVISIBLE); holder.itemDoneTwo.setVisibility(View.VISIBLE); holder.itemDoneTwoorange.setVisibility(View.INVISIBLE); holder.itemDoneTwoblue.setVisibility(View.INVISIBLE); a1=0; }else { holder.itemDoneTwogray.setVisibility(View.VISIBLE); holder.itemDoneTwo.setVisibility(View.INVISIBLE); holder.itemDoneTwoorange.setVisibility(View.INVISIBLE); holder.itemDoneTwoblue.setVisibility(View.INVISIBLE); a1=1; } } else if (list.get(position).getYpBtn() == 1) { //蓝色 holder.itemDoneTwogray.setVisibility(View.INVISIBLE); holder.itemDoneTwo.setVisibility(View.INVISIBLE); holder.itemDoneTwoorange.setVisibility(View.INVISIBLE); holder.itemDoneTwoblue.setVisibility(View.VISIBLE); a1=2; holder.itemDoneTwoblue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (list.get(position).getBgBtn() == 1){ k1=1; index=1; }else { index=0; } Intent intent = new Intent(context, Yupin2Activity.class); intent.putExtra("xmId",list.get(position).getXmId()); intent.putExtra("index",index); intent.putExtra("k2",1); context.startActivity(intent); // ((Activity)context).finish(); } }); } else { //黄色,点击结果页面,pdf holder.itemDoneTwogray.setVisibility(View.INVISIBLE); holder.itemDoneTwoorange.setVisibility(View.VISIBLE); holder.itemDoneTwo.setVisibility(View.INVISIBLE); holder.itemDoneTwoblue.setVisibility(View.INVISIBLE); a1=3; holder.itemDoneTwoorange.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, DownLoaderActivity.class); intent.putExtra("url",list.get(position).getYpUrl()+""); context.startActivity(intent); } }); } //*********** if (list.get(position).getBgBtn() == 0) { //灰色,失去焦点,报告 if ("1".equals(list.get(position).getNeedBgReport()+"")){ holder.itemDoneThreegray.setVisibility(View.INVISIBLE); holder.itemDoneThree.setVisibility(View.VISIBLE); holder.itemDoneThreeorange.setVisibility(View.INVISIBLE); holder.itemDoneThreeblue.setVisibility(View.INVISIBLE); a2=0; }else { holder.itemDoneThreegray.setVisibility(View.VISIBLE); holder.itemDoneThree.setVisibility(View.INVISIBLE); holder.itemDoneThreeorange.setVisibility(View.INVISIBLE); holder.itemDoneThreeblue.setVisibility(View.INVISIBLE); a2=1; } } else if (list.get(position).getBgBtn() == 1) { //蓝色 holder.itemDoneThreegray.setVisibility(View.INVISIBLE); holder.itemDoneThree.setVisibility(View.INVISIBLE); holder.itemDoneThreeorange.setVisibility(View.INVISIBLE); holder.itemDoneThreeblue.setVisibility(View.VISIBLE); a2=2; holder.itemDoneThreeblue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (list.get(position).getYpBtn() == 1){ k2=1; index=1; }else { k2=0; index=2; } Intent intent = new Intent(context, Yupin3Activity.class); intent.putExtra("xmId",list.get(position).getXmId()); intent.putExtra("k2",k2); intent.putExtra("index",index); context.startActivity(intent); // ((Activity)context).finish(); } }); } else { //黄色,点击结果页面,pdf holder.itemDoneThreegray.setVisibility(View.INVISIBLE); holder.itemDoneThreeorange.setVisibility(View.VISIBLE); holder.itemDoneThree.setVisibility(View.INVISIBLE); holder.itemDoneThreeblue.setVisibility(View.INVISIBLE); a2=3; holder.itemDoneThreeorange.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, DownLoaderActivity.class); intent.putExtra("url",list.get(position).getBgUrl()+""); context.startActivity(intent); } }); } } else { //显示2个按钮 holder.itemDonePay.setVisibility(View.VISIBLE); holder.textView3.setVisibility(View.VISIBLE); holder.textView5.setVisibility(View.VISIBLE); holder.itemDoneOne.setVisibility(View.INVISIBLE); holder.itemDoneGray.setVisibility(View.INVISIBLE); holder.itemDoneBlue.setVisibility(View.INVISIBLE); holder.itemDoneTwo.setVisibility(View.INVISIBLE); holder.itemDoneTwoorange.setVisibility(View.INVISIBLE); holder.itemDoneTwoblue.setVisibility(View.INVISIBLE); holder.itemDoneThreeblue.setVisibility(View.INVISIBLE); holder.itemDoneThreeorange.setVisibility(View.INVISIBLE); holder.itemDoneThree.setVisibility(View.INVISIBLE); double price = 0.0; if (list.get(position).getPayBtn() == 0) { //显示灰色 holder.textView3.setVisibility(View.INVISIBLE); holder.textView5.setVisibility(View.INVISIBLE); holder.itemDonePay.setVisibility(View.INVISIBLE); holder.itemDonePaygragy.setVisibility(View.VISIBLE); b1=0; } else if (list.get(position).getPayBtn() == 1) { b1=1; // holder.itemDoneChange.setText("待付款"); holder.textView3.setVisibility(View.VISIBLE); holder.textView5.setVisibility(View.VISIBLE); holder.itemDonePay.setVisibility(View.VISIBLE); holder.itemDonePaygragy.setVisibility(View.INVISIBLE); holder.textView5.setText(list.get(position).getPayingXj() + ""); Log.i("jiage1", list.get(position).getPayingXj() + ""); price = list.get(position).getPayingXj(); //添加跳转付款 final double finalPrice = price; pric=price; holder.itemDonePay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PayActivity.class); intent.putExtra("payinxj", finalPrice); context.startActivity(intent); } }); } else if (list.get(position).getPayBtn() == 2) { b1=1; // holder.itemDoneChange.setText("待付款"); holder.textView3.setVisibility(View.VISIBLE); holder.textView5.setVisibility(View.VISIBLE); holder.itemDonePay.setVisibility(View.VISIBLE); holder.itemDonePaygragy.setVisibility(View.INVISIBLE); holder.textView5.setText(list.get(position).getPayingYp() + ""); Log.i("jiage2", list.get(position).getPayingYp() + ""); price = list.get(position).getPayingYp(); //添加跳转付款 final double finalPrice = price; pric=price; holder.itemDonePay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PayActivity.class); intent.putExtra("payinxj", finalPrice); context.startActivity(intent); } }); } else { holder.itemDoneChange.setText("待付款"); b1=1; holder.textView3.setVisibility(View.VISIBLE); holder.textView5.setVisibility(View.VISIBLE); holder.itemDonePay.setVisibility(View.VISIBLE); holder.itemDonePaygragy.setVisibility(View.INVISIBLE); holder.textView5.setText(list.get(position).getPayingBg() + ""); Log.i("jiage3", list.get(position).getPayingBg() + ""); price = list.get(position).getPayingBg(); //添加跳转付款 final double finalPrice = price; pric=price; holder.itemDonePay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PayActivity.class); intent.putExtra("payinxj", finalPrice); context.startActivity(intent); } }); } } //加载 holder.itemDoneName.setText(list.get(position).getLpmc() + ""); holder.itemDoneAddress.setText(list.get(position).getWydz() + ""); //new DecimalFormat("######0.00").format(resultGuBean.getData().getSumMoney()/10000)+"" if (list.get(position).getSumMoeny()==0){ //隐藏 holder.price.setVisibility(View.INVISIBLE); holder.textView6.setVisibility(View.INVISIBLE); holder.itemDonePrice.setVisibility(View.INVISIBLE); }else { holder.price.setVisibility(View.VISIBLE); holder.textView6.setVisibility(View.VISIBLE); holder.itemDonePrice.setVisibility(View.VISIBLE); // if ("东方知音苑".equals(list.get(position).getLpmc())){ // holder.price.setText("673.57"); // }else { // // holder.price.setText(new DecimalFormat("######0.00").format((double)list.get(position).getSumMoeny()/10000) + ""); // } // Log.i("price",totalMoney(list.get(position).getSumMoeny()/10000)+"nmnmnmnmnm"); holder.price.setText(totalMoney(list.get(position).getSumMoeny()/10000)+ ""); } //格式化时间,并进行赋值 Long updateTime = list.get(position).getCreateDate(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd "); // Long time = new Long(updateTime); // String datetime = format.format(updateTime * 1000); //时间值 String datetime = format.format(updateTime); holder.itemDoneTime.setText(datetime); // final String title = list.get(position).getTitle(); holder.itemTitle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ("null".equals(list.get(position).getLpxxId() + "")) { Toast.makeText(context, "暂无楼盘信息", Toast.LENGTH_SHORT).show(); } else { Intent intent = new Intent(context, Info3Activity.class); intent.putExtra("lpxxId", list.get(position).getLpxxId() + ""); intent.putExtra("lpmc",list.get(position).getLpmc() + ""); context.startActivity(intent); } } }); //单击跳转到详情页 final int finalA = a1; final int finalA1 = a2; final int finalB = b1; final double finalPric = pric; holder.test.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ("null".equals(list.get(position).getLpxxId() + "")) { Intent intent = new Intent(context, Info2Activity.class); intent.putExtra("xmId", list.get(position).getXmId() + ""); intent.putExtra("status",status); intent.putExtra("a1", finalA); intent.putExtra("a2", finalA1); intent.putExtra("b1", finalB); intent.putExtra("pric", finalPric); intent.putExtra("wydz",list.get(position).getWydz()+""); intent.putExtra("url1",list.get(position).getYpUrl()+""); intent.putExtra("url2",list.get(position).getBgUrl()+""); intent.putExtra("statusname",list.get(position).getStatusName()+""); intent.putExtra("lpmc",list.get(position).getLpmc() + ""); intent.putExtra("assignee",list.get(position).getAssignee()); Log.i("dczid",list.get(position).getAssignee()); context.startActivity(intent); // Toast.makeText(context, "暂无楼盘信息", Toast.LENGTH_SHORT).show(); } else { Intent intent = new Intent(context, Info2Activity.class); intent.putExtra("xmId", list.get(position).getXmId() + ""); intent.putExtra("status",status); intent.putExtra("a1", finalA); intent.putExtra("a2", finalA1); intent.putExtra("b1", finalB); intent.putExtra("pric", finalPric); intent.putExtra("wydz",list.get(position).getWydz()+""); intent.putExtra("url1",list.get(position).getYpUrl()+""); intent.putExtra("url2",list.get(position).getBgUrl()+""); intent.putExtra("statusname",list.get(position).getStatusName()+""); intent.putExtra("lpmc",list.get(position).getLpmc() + ""); intent.putExtra("assignee",list.get(position).getAssignee()); Log.i("dczid",list.get(position).getAssignee()); context.startActivity(intent); } } }); /** * 我新加的内容 * */ if(list.get(position).getB5().equals("1")){ //如果b5是1就是已读内容 holder.itemDoneName.setTextColor(Color.parseColor("#7e7e7e")); holder.itemDoneAddress.setTextColor(Color.parseColor("#c1c1c1")); holder.itemDoneTime.setTextColor(Color.parseColor("#c1c1c1")); holder.itemDoneChange.setTextColor(Color.parseColor("#7e7e7e")); holder.itemDonePrice.setTextColor(Color.parseColor("#c1c1c1")); holder.price.setTextColor(Color.parseColor("#c1c1c1")); holder.textView6.setTextColor(Color.parseColor("#c1c1c1")); }else { holder.itemDoneName.setTextColor(Color.parseColor("#2a2a2a")); holder.itemDoneAddress.setTextColor(Color.parseColor("#666666")); holder.itemDoneTime.setTextColor(Color.parseColor("#666666")); holder.itemDoneChange.setTextColor(Color.parseColor("#2a2a2a")); holder.itemDonePrice.setTextColor(Color.parseColor("#2a2a2a")); holder.price.setTextColor(Color.parseColor("#2a2a2a")); holder.textView6.setTextColor(Color.parseColor("#2a2a2a")); } return convertView; } public static String totalMoney(double money) { java.math.BigDecimal bigDec = new java.math.BigDecimal(money); double total = bigDec.setScale(2, java.math.BigDecimal.ROUND_HALF_UP) .doubleValue(); DecimalFormat df = new DecimalFormat("0.00"); return df.format(total); } //加载数据 public void reloadListView(List<AllListBean.DataBean.ListBean> _list, boolean isClear) { if (isClear) { list.clear(); } list.addAll(_list); notifyDataSetChanged(); } public GetLpBean parseJsonToGetLpBean(String jsonString) { Gson gson = new Gson(); GetLpBean bean = gson.fromJson(jsonString, new TypeToken<GetLpBean>() { }.getType()); return bean; } static class ViewHolder { @BindView(R.id.imageView_item_done_image) ImageView imageViewItemDoneImage; @BindView(R.id.item_done_name) //名字 TextView itemDoneName; @BindView(R.id.item_arrow_waitpay) ImageView itemArrowWaitpay; @BindView(R.id.item_done_address) //地址 TextView itemDoneAddress; @BindView(R.id.item_done_time) //时间 TextView itemDoneTime; @BindView(R.id.item_done_change) //状态 TextView itemDoneChange; @BindView(R.id.item_done_price) //价格单位 TextView itemDonePrice; @BindView(R.id.price) //价格 TextView price; @BindView(R.id.textView6) //¥ TextView textView6; @BindView(R.id.test) LinearLayout test; @BindView(R.id.item_done_three) TextView itemDoneThree; @BindView(R.id.item_done_two) TextView itemDoneTwo; @BindView(R.id.item_done_one) TextView itemDoneOne; @BindView(R.id.textView3) TextView textView3; @BindView(R.id.textView5) TextView textView5; @BindView(R.id.item_done_pay) TextView itemDonePay; @BindView(R.id.item_done_gray) TextView itemDoneGray; @BindView(R.id.item_done_blue) TextView itemDoneBlue; @BindView(R.id.item_title) LinearLayout itemTitle; @BindView(R.id.item_done_twoblue) TextView itemDoneTwoblue; @BindView(R.id.item_done_twoorange) TextView itemDoneTwoorange; @BindView(R.id.item_done_threeblue) TextView itemDoneThreeblue; @BindView(R.id.item_done_threeorange) TextView itemDoneThreeorange; @BindView(R.id.item_done_paygragy) TextView itemDonePaygragy; @BindView(R.id.item_done_threegray) TextView itemDoneThreegray; @BindView(R.id.item_done_twogray) TextView itemDoneTwogray; ViewHolder(View view) { ButterKnife.bind(this, view); } } }
24,293
0.562257
0.553055
536
43.606342
25.25733
132
false
false
0
0
0
0
0
0
0.75
false
false
2
72b13e7247b9383f8a6272e120bd272d68bde139
16,097,537,469,664
ba4948c4b6ad2b3e3376f43acbf4ed42ff43c6e0
/src/main/java/com/alipay/api/domain/AlipayFundJointaccountFundOrderQueryModel.java
cb3b5e84ea1d1870da10da2df18958fe9b9fc640
[ "Apache-2.0" ]
permissive
midoujia/alipay-sdk-java-all
https://github.com/midoujia/alipay-sdk-java-all
638a99943f1d05e4bdf0870dd40a62c5c6c6059b
fc41e3a0102f6c446dbf2a5b7a9f21ee6ca91884
refs/heads/master
2023-09-02T14:45:02.224000
2021-11-16T10:07:35
2021-11-16T10:07:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 查询资金单据 * * @author auto create * @since 1.0, 2021-09-07 10:07:11 */ public class AlipayFundJointaccountFundOrderQueryModel extends AlipayObject { private static final long serialVersionUID = 5175413133266617734L; /** * 合花群ID <br/> 补充说明: <br/> - 该字段可在签约接口调用后,由alipay.fund.jointaccount.account.completed中返回<br> - 该字段可在签约接口调用后,由alipay.fund.jointaccount.detail.query中返回 */ @ApiField("account_id") private String accountId; /** * 授权协议号 <br/> 补充说明: <br/> - 该字段可在签约接口调用后,由alipay.fund.jointaccount.account.completed中返回<br> - 该字段可在签约接口调用后, 由alipay.fund.jointaccount.detail.query中返回 */ @ApiField("agreement_no") private String agreementNo; /** * 业务场景码 */ @ApiField("biz_scene") private String bizScene; /** * 支付宝侧转账订单号(查询方式一:通过传入 biz_trans_id查询) <br/> 补充说明: <br/> - 该字段可在调用alipay.fund.jointaccount.fund.btoc.transfer中同步返回 <br/> - 该字段可在资金操作接口调用后,由alipay.fund.jointaccount.fund.completed中返回 */ @ApiField("biz_trans_id") private String bizTransId; /** * 资金操作类型:<br/> - FREEZE:提现申请 <br/> - UNFREEZE:提现审批拒绝 <br/> - WITHDRAW:提现审批同意 <br/> - DEPOSIT:手动转入 <br/> - SINGLE_TRANSFER:存量资金搬迁 */ @ApiField("operate_type") private String operateType; /** * 商户侧单号(查询方式二:通过传入 out_biz_no查询) <br/> 补充说明: <br/> - 该字段与各类资金操作接口的请求参数中传入值保持一致 */ @ApiField("out_biz_no") private String outBizNo; /** * 销售产品码 */ @ApiField("product_code") private String productCode; /** * (发起人)支付宝侧用户唯一标识 <br/> 补充说明: <br/> - 发起人可为C端用户<br/> - 发起人也可为B端商户 */ @ApiField("request_uid") private String requestUid; public String getAccountId() { return this.accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getAgreementNo() { return this.agreementNo; } public void setAgreementNo(String agreementNo) { this.agreementNo = agreementNo; } public String getBizScene() { return this.bizScene; } public void setBizScene(String bizScene) { this.bizScene = bizScene; } public String getBizTransId() { return this.bizTransId; } public void setBizTransId(String bizTransId) { this.bizTransId = bizTransId; } public String getOperateType() { return this.operateType; } public void setOperateType(String operateType) { this.operateType = operateType; } public String getOutBizNo() { return this.outBizNo; } public void setOutBizNo(String outBizNo) { this.outBizNo = outBizNo; } public String getProductCode() { return this.productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getRequestUid() { return this.requestUid; } public void setRequestUid(String requestUid) { this.requestUid = requestUid; } }
UTF-8
Java
3,496
java
AlipayFundJointaccountFundOrderQueryModel.java
Java
[ { "context": "apping.ApiField;\r\n\r\n/**\r\n * 查询资金单据\r\n *\r\n * @author auto create\r\n * @since 1.0, 2021-09-07 10:07:11\r\n */\r\npublic ", "end": 165, "score": 0.7238362431526184, "start": 154, "tag": "USERNAME", "value": "auto create" } ]
null
[]
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 查询资金单据 * * @author auto create * @since 1.0, 2021-09-07 10:07:11 */ public class AlipayFundJointaccountFundOrderQueryModel extends AlipayObject { private static final long serialVersionUID = 5175413133266617734L; /** * 合花群ID <br/> 补充说明: <br/> - 该字段可在签约接口调用后,由alipay.fund.jointaccount.account.completed中返回<br> - 该字段可在签约接口调用后,由alipay.fund.jointaccount.detail.query中返回 */ @ApiField("account_id") private String accountId; /** * 授权协议号 <br/> 补充说明: <br/> - 该字段可在签约接口调用后,由alipay.fund.jointaccount.account.completed中返回<br> - 该字段可在签约接口调用后, 由alipay.fund.jointaccount.detail.query中返回 */ @ApiField("agreement_no") private String agreementNo; /** * 业务场景码 */ @ApiField("biz_scene") private String bizScene; /** * 支付宝侧转账订单号(查询方式一:通过传入 biz_trans_id查询) <br/> 补充说明: <br/> - 该字段可在调用alipay.fund.jointaccount.fund.btoc.transfer中同步返回 <br/> - 该字段可在资金操作接口调用后,由alipay.fund.jointaccount.fund.completed中返回 */ @ApiField("biz_trans_id") private String bizTransId; /** * 资金操作类型:<br/> - FREEZE:提现申请 <br/> - UNFREEZE:提现审批拒绝 <br/> - WITHDRAW:提现审批同意 <br/> - DEPOSIT:手动转入 <br/> - SINGLE_TRANSFER:存量资金搬迁 */ @ApiField("operate_type") private String operateType; /** * 商户侧单号(查询方式二:通过传入 out_biz_no查询) <br/> 补充说明: <br/> - 该字段与各类资金操作接口的请求参数中传入值保持一致 */ @ApiField("out_biz_no") private String outBizNo; /** * 销售产品码 */ @ApiField("product_code") private String productCode; /** * (发起人)支付宝侧用户唯一标识 <br/> 补充说明: <br/> - 发起人可为C端用户<br/> - 发起人也可为B端商户 */ @ApiField("request_uid") private String requestUid; public String getAccountId() { return this.accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getAgreementNo() { return this.agreementNo; } public void setAgreementNo(String agreementNo) { this.agreementNo = agreementNo; } public String getBizScene() { return this.bizScene; } public void setBizScene(String bizScene) { this.bizScene = bizScene; } public String getBizTransId() { return this.bizTransId; } public void setBizTransId(String bizTransId) { this.bizTransId = bizTransId; } public String getOperateType() { return this.operateType; } public void setOperateType(String operateType) { this.operateType = operateType; } public String getOutBizNo() { return this.outBizNo; } public void setOutBizNo(String outBizNo) { this.outBizNo = outBizNo; } public String getProductCode() { return this.productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getRequestUid() { return this.requestUid; } public void setRequestUid(String requestUid) { this.requestUid = requestUid; } }
3,496
0.688866
0.676913
142
18.774649
17.579756
77
false
false
0
0
0
0
0
0
0.950704
false
false
2
37b42a958891e7c5a015a82f6be59a972e291068
12,953,621,393,859
ab8f1bd15c19c20bcaeacfdc73d108b9a62b5455
/src/main/java/com/lintcode/t201807/Pnum0015.java
30a9659a91f3ad70cdf4786c82b253cc1ae848a2
[]
no_license
haiswang1989/lintcode
https://github.com/haiswang1989/lintcode
afef9e143657b0ee5aa713d2aab364d8aa4eab46
5b944bc797250f0025b9c9bd4228f8dd883c85e2
refs/heads/master
2020-03-22T02:51:08.952000
2018-11-19T06:22:33
2018-11-19T06:22:33
139,397,195
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lintcode.t201807; import java.util.List; /** * 全排列 * * 给定一个数字列表,返回其所有可能的排列 * * 给出一个列表[1,2,3],其全排列为 * * [ * [1,2,3], * [1,3,2], * [2,1,3], * [2,3,1], * [3,1,2], * [3,2,1] * ] * * <p>Description:</p> * @author hansen.wang * @date 2018年7月5日 上午9:24:03 */ public class Pnum0015 { public static void main(String[] args) { } /** * * @param nums: A list of integers. * @return: A list of permutations. */ public List<List<Integer>> permute(int[] nums) { // write your code here return null; } public void recursion(int[] nums, int fromIndex, List<List<Integer>> result) { for(int i=fromIndex; i<nums.length; i++) { } } }
UTF-8
Java
848
java
Pnum0015.java
Java
[ { "context": "[3,2,1]\n * ]\n * \n * <p>Description:</p>\n * @author hansen.wang\n * @date 2018年7月5日 上午9:24:03\n */\npublic class Pnu", "end": 260, "score": 0.9987889528274536, "start": 249, "tag": "NAME", "value": "hansen.wang" } ]
null
[]
package com.lintcode.t201807; import java.util.List; /** * 全排列 * * 给定一个数字列表,返回其所有可能的排列 * * 给出一个列表[1,2,3],其全排列为 * * [ * [1,2,3], * [1,3,2], * [2,1,3], * [2,3,1], * [3,1,2], * [3,2,1] * ] * * <p>Description:</p> * @author hansen.wang * @date 2018年7月5日 上午9:24:03 */ public class Pnum0015 { public static void main(String[] args) { } /** * * @param nums: A list of integers. * @return: A list of permutations. */ public List<List<Integer>> permute(int[] nums) { // write your code here return null; } public void recursion(int[] nums, int fromIndex, List<List<Integer>> result) { for(int i=fromIndex; i<nums.length; i++) { } } }
848
0.509091
0.454545
46
15.73913
16.780468
82
false
false
0
0
0
0
0
0
0.565217
false
false
2
492bfa402c46a23fd95f4d4fb812a3277a98e407
33,363,306,004,622
76e0c7918310391cf36de336ed2001c1115b4e90
/LoginDemo/src/main/java/com/testgaap/logindemo/app/service/MyUserDetailService.java
520bddd922ab0afc7d578c4516bf5632cec10bd2
[]
no_license
gautambsg08/LoginDemo
https://github.com/gautambsg08/LoginDemo
46144f57cadca918215022a7e739ccf8f9cc7636
6005f0b03936051f7db0329ebca878359a2a9af2
refs/heads/master
2021-05-18T18:37:15.321000
2020-03-30T16:55:54
2020-03-30T16:55:54
251,362,603
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.testgaap.logindemo.app.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.testgaap.logindemo.app.entity.LoginEntity; import com.testgaap.logindemo.app.entity.MyUserDetails; import com.testgaap.logindemo.app.oao.LoginDao; @Service public class MyUserDetailService implements UserDetailsService { @Autowired private LoginDao loginDao; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { LoginEntity loginEntity = loginDao.findByusername(username); UserDetails userDetails = null; if (loginEntity != null) { userDetails= new MyUserDetails(loginEntity); } else { throw new UsernameNotFoundException("user not exist with : "+username); } return userDetails; } }
UTF-8
Java
1,091
java
MyUserDetailService.java
Java
[]
null
[]
package com.testgaap.logindemo.app.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.testgaap.logindemo.app.entity.LoginEntity; import com.testgaap.logindemo.app.entity.MyUserDetails; import com.testgaap.logindemo.app.oao.LoginDao; @Service public class MyUserDetailService implements UserDetailsService { @Autowired private LoginDao loginDao; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { LoginEntity loginEntity = loginDao.findByusername(username); UserDetails userDetails = null; if (loginEntity != null) { userDetails= new MyUserDetails(loginEntity); } else { throw new UsernameNotFoundException("user not exist with : "+username); } return userDetails; } }
1,091
0.786434
0.786434
35
29.171429
28.665047
90
false
false
0
0
0
0
0
0
1.371429
false
false
2
8de188af9d496bb96314d3005c5b0036dc41fa4c
25,434,796,370,568
c16ded0f3a758e8af54233616cb358386f9830b6
/Question_bank/src/main/java/com/yc/utils/PageUtil.java
cf97289d0058392cf045fdd232a899f2d4edbbc8
[]
no_license
SanJiankeBook/graduation
https://github.com/SanJiankeBook/graduation
57f356e39e6e3ca04668ddce8d88df978b6eda11
265873eea4e3fbc81b40740bbdd7aa18155f230b
refs/heads/master
2021-04-03T01:04:38.666000
2019-01-15T11:51:39
2019-01-15T11:51:39
124,863,917
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yc.utils; import java.io.Serializable; import java.util.List; public class PageUtil implements Serializable { private static final long serialVersionUID = 1L; private int pageNo=1; private int pageSize=15; private int totalSize; private int totalPages; private List<?> list; public int getPrePageNo(){ int prePageNo=1; if(pageNo>1){ prePageNo=pageNo-1; }else{ prePageNo=1; } this.pageNo=prePageNo; return prePageNo; } public int getNextPageNo(){ int nextPageNo=1; if(pageNo<getTotalPages()){ nextPageNo=pageNo+1; }else{ nextPageNo=getTotalPages(); } this.pageNo=nextPageNo; return nextPageNo; } public int getTotalPages() { totalPages=this.getTotalSize()%this.getPageSize()==0?this.getTotalSize()/this.getPageSize():this.getTotalSize()/this.getPageSize()+1; return totalPages; } public int getTotalSize() { return totalSize; } public void setTotalSize(int totalSize) { if(totalSize<0){ this.totalSize=0; }else{ this.totalSize = totalSize; } } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { if(pageSize<=0){ this.pageSize=5; }else{ this.pageSize = pageSize; } } public int getPageNo() { if(this.pageNo>this.getTotalPages()){ this.pageNo=this.getTotalPages(); } return pageNo; } public void setPageNo(int pageNo) { if(pageNo<=0){ this.pageNo=1; }else{ this.pageNo = pageNo; } } public List<?> getList() { return list; } public void setList(List<?> list) { this.list = list; } }
UTF-8
Java
1,672
java
PageUtil.java
Java
[]
null
[]
package com.yc.utils; import java.io.Serializable; import java.util.List; public class PageUtil implements Serializable { private static final long serialVersionUID = 1L; private int pageNo=1; private int pageSize=15; private int totalSize; private int totalPages; private List<?> list; public int getPrePageNo(){ int prePageNo=1; if(pageNo>1){ prePageNo=pageNo-1; }else{ prePageNo=1; } this.pageNo=prePageNo; return prePageNo; } public int getNextPageNo(){ int nextPageNo=1; if(pageNo<getTotalPages()){ nextPageNo=pageNo+1; }else{ nextPageNo=getTotalPages(); } this.pageNo=nextPageNo; return nextPageNo; } public int getTotalPages() { totalPages=this.getTotalSize()%this.getPageSize()==0?this.getTotalSize()/this.getPageSize():this.getTotalSize()/this.getPageSize()+1; return totalPages; } public int getTotalSize() { return totalSize; } public void setTotalSize(int totalSize) { if(totalSize<0){ this.totalSize=0; }else{ this.totalSize = totalSize; } } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { if(pageSize<=0){ this.pageSize=5; }else{ this.pageSize = pageSize; } } public int getPageNo() { if(this.pageNo>this.getTotalPages()){ this.pageNo=this.getTotalPages(); } return pageNo; } public void setPageNo(int pageNo) { if(pageNo<=0){ this.pageNo=1; }else{ this.pageNo = pageNo; } } public List<?> getList() { return list; } public void setList(List<?> list) { this.list = list; } }
1,672
0.641148
0.630383
90
16.577778
18.065914
135
false
false
0
0
0
0
0
0
1.911111
false
false
2
3a22e7608e8b7990a05f46a5aed2fc4c83bb5044
25,434,796,369,030
e740e2cb6a8b4edec220e3848a8b2cc5f1de0411
/src/main/java/io/sloyo/persistence/commons/api/IEntity.java
ed672e5f5f1a7c684751e97abc8ae99cf8c20ee7
[ "MIT" ]
permissive
sloyo/core-service
https://github.com/sloyo/core-service
a1453d7264331b5b758ce30fc37b529924a8c0e0
4d6bb308b5ec29636d22151bad26813f9c618f1c
refs/heads/master
2020-06-29T00:56:07.709000
2019-09-07T21:38:44
2019-09-07T21:38:44
200,391,853
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.sloyo.persistence.commons.api; public interface IEntity { public Long getId(); }
UTF-8
Java
99
java
IEntity.java
Java
[]
null
[]
package io.sloyo.persistence.commons.api; public interface IEntity { public Long getId(); }
99
0.727273
0.727273
7
13.142858
15.697393
41
false
false
0
0
0
0
0
0
0.285714
false
false
2
228c44d6d470cf0c0d3ae69e8b0a6d8a5563361e
14,096,082,731,961
326e9a7a7c5e4a78491cb86added1054347ce508
/src/dao/MovieScheduleDao.java
74a112e0d770c07c84771f210b32e3ade7574e42
[]
no_license
diarmuid451/javaproject
https://github.com/diarmuid451/javaproject
acd44751aa8e4a80fec407a8027c38f6ed23a492
7c0e2cb00ceed94f795bedd8a258d5cce60dc557
refs/heads/master
2020-11-28T16:47:08.944000
2019-12-30T15:19:16
2019-12-30T15:19:16
229,872,277
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao; public interface MovieScheduleDao { void getMoiveScheduleInfo(int movieNo); String getOneMovieInfo(int movieId, String screenMoiveId); int getMovieSchId(int movieId, String screenMoiveId); int getScreenId(int movieId, String screenMoiveId); }
UTF-8
Java
267
java
MovieScheduleDao.java
Java
[]
null
[]
package dao; public interface MovieScheduleDao { void getMoiveScheduleInfo(int movieNo); String getOneMovieInfo(int movieId, String screenMoiveId); int getMovieSchId(int movieId, String screenMoiveId); int getScreenId(int movieId, String screenMoiveId); }
267
0.797753
0.797753
13
19.538462
23.385122
59
false
false
0
0
0
0
0
0
1
false
false
2
abeaf30c594758eda7a46bc23b56e1ab01303de6
15,075,335,278,331
a53f266293e1fa3eaef5cea3c6d4c3195a2551cb
/src/java_20210503/SwitchDemo.java
d40193af6443187e080b1146fbf236aea18a7792
[]
no_license
CHOHEEJEONG/java_fundametal
https://github.com/CHOHEEJEONG/java_fundametal
201528c0861702e46cadf86d66098c1a57e220d4
372914050d8d4ace637338a94d56f14d6f90f34b
refs/heads/master
2023-05-26T21:22:44.582000
2021-06-10T10:56:45
2021-06-10T10:56:45
365,913,801
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package java_20210503; public class SwitchDemo { public static void main(String[] args) { // Run configurations => Arguments => Program arguments (에 숫자 집어넣으면 됨) int month = Integer.parseInt(args[0]); String season = ""; switch(month) { // case12,1,2 : 라고 표기해도 된다. (버전이 업데이트 되면서 가능해짐) // case는 중복되면 안된다. case 12 : case 1 : case 2 : season ="겨울";break; case 3 : case 4 : case 5 : season ="봄";break; case 6 : case 7 : case 8 : season ="여름";break; case 9 : case 10 : case 11 : season ="가을";break; default : season = "없는 계절"; } System.out.println(month + "월은 "+ season + "입니다."); } }
UTF-8
Java
787
java
SwitchDemo.java
Java
[]
null
[]
package java_20210503; public class SwitchDemo { public static void main(String[] args) { // Run configurations => Arguments => Program arguments (에 숫자 집어넣으면 됨) int month = Integer.parseInt(args[0]); String season = ""; switch(month) { // case12,1,2 : 라고 표기해도 된다. (버전이 업데이트 되면서 가능해짐) // case는 중복되면 안된다. case 12 : case 1 : case 2 : season ="겨울";break; case 3 : case 4 : case 5 : season ="봄";break; case 6 : case 7 : case 8 : season ="여름";break; case 9 : case 10 : case 11 : season ="가을";break; default : season = "없는 계절"; } System.out.println(month + "월은 "+ season + "입니다."); } }
787
0.556869
0.51551
30
21.566668
18.360617
72
false
false
0
0
0
0
0
0
3.366667
false
false
2
41264b0ef7c3959f024d50e48866273aac101bb8
6,038,724,030,056
7345f85781d2cc5d513eea77e8f75d1e3acf8e35
/app/src/main/java/com/example/metropoliaweatherapp/QuestionnaireActivity.java
02eed7578d9e5d175e080fdd86c2defa9b9b7378
[]
no_license
nippongun/MetropoliaWeatherApp
https://github.com/nippongun/MetropoliaWeatherApp
33d8f0f0d17c1fec82ab40929f7178374d1ea5f4
13575885da507fa93a5c1a1d152a974764917757
refs/heads/master
2021-03-13T04:33:56.826000
2020-03-11T13:53:49
2020-03-11T13:53:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.metropoliaweatherapp; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; public class QuestionnaireActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { public EditText editText4; public EditText editText; public Button saveButton; public EditText editText3; public Spinner editText2; public static final String SH_PR = "shPr"; public static final String TEXT = "text"; public static final String FIRST_VISIT = "first"; public String text; @SuppressLint("WrongViewCast") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_questionnaire); editText4 = findViewById(R.id.editText4); editText = findViewById(R.id.editText); saveButton = findViewById(R.id.saveButton); editText3 = findViewById(R.id.editText3); //editText2 = findViewById(R.id.editText2); saveButton = findViewById(R.id.saveButton); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { savePrefs(); } }); } public void savePrefs(){ SharedPreferences sharedPreferences = getSharedPreferences(SH_PR, MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(TEXT, text); editor.apply(); } public void loadPrefs(){ SharedPreferences sharedPreferences = getSharedPreferences(SH_PR, MODE_PRIVATE); } @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { text = adapterView.getItemAtPosition(i).toString(); Toast.makeText(adapterView.getContext(), text, Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }
UTF-8
Java
2,322
java
QuestionnaireActivity.java
Java
[]
null
[]
package com.example.metropoliaweatherapp; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; public class QuestionnaireActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { public EditText editText4; public EditText editText; public Button saveButton; public EditText editText3; public Spinner editText2; public static final String SH_PR = "shPr"; public static final String TEXT = "text"; public static final String FIRST_VISIT = "first"; public String text; @SuppressLint("WrongViewCast") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_questionnaire); editText4 = findViewById(R.id.editText4); editText = findViewById(R.id.editText); saveButton = findViewById(R.id.saveButton); editText3 = findViewById(R.id.editText3); //editText2 = findViewById(R.id.editText2); saveButton = findViewById(R.id.saveButton); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { savePrefs(); } }); } public void savePrefs(){ SharedPreferences sharedPreferences = getSharedPreferences(SH_PR, MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(TEXT, text); editor.apply(); } public void loadPrefs(){ SharedPreferences sharedPreferences = getSharedPreferences(SH_PR, MODE_PRIVATE); } @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { text = adapterView.getItemAtPosition(i).toString(); Toast.makeText(adapterView.getContext(), text, Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }
2,322
0.706288
0.702412
78
28.76923
25.782583
108
false
false
0
0
0
0
0
0
0.602564
false
false
2
2cf527aed0bdb02a28a2ab90ff1bab4050cfe427
10,350,871,250,331
77c690de12e4c7db4af29c4a10762fc6c86d36d5
/src/java/biblioteca/datos/hibernate/dao/IUsuarioDAO.java
b77fd2c829474cb46cd759a6b87420730bd03300
[]
no_license
Alemorar/FinalVillanueva3033
https://github.com/Alemorar/FinalVillanueva3033
3df2edd1ef0fcd84bb350d258663fd1a6ff7895a
58ecb9f3f8542289a9cc0b40b575ff1873afdc9b
refs/heads/master
2021-01-13T00:48:32.526000
2015-12-30T13:10:25
2015-12-30T13:10:25
46,362,762
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package biblioteca.datos.hibernate.dao; import biblioteca.modelo.dominio.Usuario; public interface IUsuarioDAO { /** * Valida la existencia de un usuario. * @param nombreUsuario * @param password * @return null si no existe. */ Usuario validarUsuario(String nombreUsuario, String password); void modificarUsuario(Usuario usuario); }
UTF-8
Java
392
java
IUsuarioDAO.java
Java
[ { "context": "Valida la existencia de un usuario.\r\n * @param nombreUsuario\r\n * @param password\r\n * @return null si n", "end": 200, "score": 0.9620007872581482, "start": 187, "tag": "USERNAME", "value": "nombreUsuario" } ]
null
[]
package biblioteca.datos.hibernate.dao; import biblioteca.modelo.dominio.Usuario; public interface IUsuarioDAO { /** * Valida la existencia de un usuario. * @param nombreUsuario * @param password * @return null si no existe. */ Usuario validarUsuario(String nombreUsuario, String password); void modificarUsuario(Usuario usuario); }
392
0.673469
0.673469
15
24.133333
19.581852
66
false
false
0
0
0
0
0
0
0.333333
false
false
2
95c102bacc59a60cb0707067e6d94e9284899b13
25,546,465,545,309
54c1830494fa86e76aabccb2c8fea4ad059003bd
/BinaryTree.java
e130e7947985fa995ad6ebc8d927784a4f556a68
[]
no_license
stein-sam-m/Sorting
https://github.com/stein-sam-m/Sorting
c08880ece5ef366e3eadc2eade91557f51159f78
78166fb16791874a098f404b4e19a45e61103082
refs/heads/master
2020-04-07T00:55:56.560000
2018-12-03T18:17:07
2018-12-03T18:17:07
157,924,461
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Sam Stein // Sorting and displaying by using a BST // Binary Search Tree public class BinaryTree { // Constructors BinaryTree(int key) { this.root = new Node(key); } BinaryTree() { this.root = null; } //Properties; Node root; // Methods // Insert a new node into the tree public void insert(int item) { if (this.root == null) { // Empty tree, set new item to root this.root = new Node (item); return; } Node thisNode = root; while(true) { if (item <= thisNode.key) { // Traversing left side if (thisNode.left == null) { thisNode.right = new Node(item); break; } else { thisNode = thisNode.left; continue; } } else { // Traversing right side if (thisNode.right == null) { thisNode.right = new Node(item); break; } else { thisNode = thisNode.right; continue; } } } } // Traverse and display the tree public void display() { if (this.root == null) { System.out.println("The tree is empty, ya dummy"); return; } System.out.print("Binary Tree results: "); displayNode(this.root); System.out.println(); } // Displays the value in the individual node private void displayNode(Node thisNode) { if (thisNode.left != null) { displayNode(thisNode.left); } else { System.out.print(thisNode.key + " "); if (thisNode.right != null) { displayNode(thisNode.right); } } } } // The nodes that make up the Binary Search Tree class Node { // Constructor Node (int item) { key = item; this.left = null; this.right = null; } // Properties int key; Node left; Node right; }
UTF-8
Java
1,675
java
BinaryTree.java
Java
[ { "context": "// Sam Stein\n// Sorting and displaying by using a BST\n\n\n// Bin", "end": 12, "score": 0.9996450543403625, "start": 3, "tag": "NAME", "value": "Sam Stein" } ]
null
[]
// <NAME> // Sorting and displaying by using a BST // Binary Search Tree public class BinaryTree { // Constructors BinaryTree(int key) { this.root = new Node(key); } BinaryTree() { this.root = null; } //Properties; Node root; // Methods // Insert a new node into the tree public void insert(int item) { if (this.root == null) { // Empty tree, set new item to root this.root = new Node (item); return; } Node thisNode = root; while(true) { if (item <= thisNode.key) { // Traversing left side if (thisNode.left == null) { thisNode.right = new Node(item); break; } else { thisNode = thisNode.left; continue; } } else { // Traversing right side if (thisNode.right == null) { thisNode.right = new Node(item); break; } else { thisNode = thisNode.right; continue; } } } } // Traverse and display the tree public void display() { if (this.root == null) { System.out.println("The tree is empty, ya dummy"); return; } System.out.print("Binary Tree results: "); displayNode(this.root); System.out.println(); } // Displays the value in the individual node private void displayNode(Node thisNode) { if (thisNode.left != null) { displayNode(thisNode.left); } else { System.out.print(thisNode.key + " "); if (thisNode.right != null) { displayNode(thisNode.right); } } } } // The nodes that make up the Binary Search Tree class Node { // Constructor Node (int item) { key = item; this.left = null; this.right = null; } // Properties int key; Node left; Node right; }
1,672
0.599403
0.599403
110
14.236363
13.911361
53
false
false
0
0
0
0
0
0
2.054545
false
false
2
4932ff0143a9d9f22a6f0f7934c40800d454ea05
14,534,169,339,953
7a773626651e3f67a878375254160cfe03a4482e
/app/src/main/java/uca/apps/isi/transinic/models/Articulo.java
eb2ec359f51e774843f9c6766fafc3e0acea8765
[]
no_license
uca-isti/android-0209-2-20171C
https://github.com/uca-isti/android-0209-2-20171C
e02110717054e9aa0a1afae64604b0faff0f4279
746e286661cdf84a2482414aa35abdcf914c71c0
refs/heads/master
2021-01-23T06:39:28.555000
2017-04-19T05:27:21
2017-04-19T05:27:21
86,385,153
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uca.apps.isi.transinic.models; /** * Created by isi3 on 4/4/2017. */ public class Articulo { private int numero; private String nombre; private String descripcion; public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public int getMulta_id() { return multa_id; } public void setMulta_id(int multa_id) { this.multa_id = multa_id; } private int multa_id; }
UTF-8
Java
815
java
Articulo.java
Java
[ { "context": " uca.apps.isi.transinic.models;\n\n/**\n * Created by isi3 on 4/4/2017.\n */\n\npublic class Articulo {\n priv", "end": 62, "score": 0.9994275569915771, "start": 58, "tag": "USERNAME", "value": "isi3" } ]
null
[]
package uca.apps.isi.transinic.models; /** * Created by isi3 on 4/4/2017. */ public class Articulo { private int numero; private String nombre; private String descripcion; public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public int getMulta_id() { return multa_id; } public void setMulta_id(int multa_id) { this.multa_id = multa_id; } private int multa_id; }
815
0.603681
0.595092
45
17.088888
15.706789
52
false
false
0
0
0
0
0
0
0.288889
false
false
2
681c1d24c29effd3ab55ac4847f7fe1e54132263
30,150,670,487,227
d681cc80c86a1a26f6d833d76d798872599428f3
/src/com/sunwah/baseapp/weixin/action/WeixinJSSDKAction.java
affe238d6cc309a23888b32fbdfee2c0e43e491c
[]
no_license
lwbmygithub/weixinDevelop
https://github.com/lwbmygithub/weixinDevelop
1237fc9ba52753ac2b3c11a29bd0cdf15a30c690
ea8c0ecdf7064752beb02711647ad22114e10ddd
refs/heads/master
2020-09-26T08:04:10.215000
2016-09-02T02:42:44
2016-09-02T02:42:44
67,183,808
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sunwah.baseapp.weixin.action; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import net.sf.json.JSONObject; import com.opensymphony.xwork2.ActionSupport; import com.sunwah.baseapp.weixin.service.WeixinAuthorizeService; import com.sunwah.baseapp.weixin.service.WeixinMediaService; import com.sunwah.baseapp.weixin.service.WeixinQrCodeService; import com.sunwah.baseapp.weixin.util.JSSDKUtil; public class WeixinJSSDKAction extends ActionSupport{ private static JSSDKUtil util = new JSSDKUtil(); private String url; private WeixinMediaService weixinMediaService; private String requestArea2; private String filePath1; private String code; private WeixinAuthorizeService weixinAuthorizeService; private File file; private String fileFileName; private WeixinQrCodeService weixinQrCodeService; /* * 这里定义的是文件的类型,如果不需要获取文件类型的话,可以不定义.   *  命名规则跟xxxFileName类似,这里一定要定义成xxxContentType形式.  */ private String fileContentType; /* * 这个变量是重名名后的文件名 */ private String newFileName; public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } public String getFileContentType() { return fileContentType; } public void setFileContentType(String fileContentType) { this.fileContentType = fileContentType; } public WeixinAuthorizeService getWeixinAuthorizeService() { return weixinAuthorizeService; } public void setWeixinAuthorizeService( WeixinAuthorizeService weixinAuthorizeService) { this.weixinAuthorizeService = weixinAuthorizeService; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getRequestArea2() { return requestArea2; } public void setRequestArea2(String requestArea2) { this.requestArea2 = requestArea2; } public String getFilePath1() { return filePath1; } public void setFilePath1(String filePath1) { this.filePath1 = filePath1; } public WeixinMediaService getWeixinMediaService() { return weixinMediaService; } public void setWeixinMediaService(WeixinMediaService weixinMediaService) { this.weixinMediaService = weixinMediaService; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public void getData(){ util.getSignatureAlgorithm(url); String noncestr = util.getNoncestr(); String ticket = util.getTicket(); String timestamp = util.getTimestamp(); String signature = util.getSignature(); JSONObject obj = new JSONObject(); obj.put("noncestr", noncestr); obj.put("ticket", ticket); obj.put("timestamp", timestamp); obj.put("signature", signature); String jsonString = obj.toString(); HttpServletResponse response = ServletActionContext.getResponse(); try { PrintWriter out = response.getWriter(); out.print(jsonString); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String testQrCode(){ JSONObject result = this.weixinQrCodeService.createQrScene(300, 123); String ticket = result.getString("ticket"); this.weixinQrCodeService.showQrCode("asdfas"); return "success"; } public String handleSubmit(){ System.out.println(this.getRequestArea2()); if(filePath1 != null) this.getWeixinMediaService().getMedia(filePath1); if(file != null) return upload(); return "success"; } public String handleAuthorize(){ JSONObject result = this.getWeixinAuthorizeService().codeToAccessToken(code); System.out.println(result.toString()); String accessToken = result.getString("access_token"); String openId = result.getString("openid"); JSONObject result1 = this.getWeixinAuthorizeService().getUserInfo(accessToken, openId); System.out.println(result1.toString()); return "success"; } public String upload(){ System.out.println("文件名:" + fileFileName); System.out.println("文件类型:" + fileContentType); if(file != null){ //文件保存目录是WebContent/file目录下 String realpath = ServletActionContext.getServletContext().getRealPath("/file"); System.out.println("文件的保存路径:" + realpath); //文件的后缀 String suffix = fileFileName.substring(fileFileName.lastIndexOf(".")); if(fileFileName.lastIndexOf(".") == -1){ return INPUT; } //上传以后,会重命名文件的名称,将其命名为全部是数字的文件名,防止可能出现的乱码. //当然,只是为了防止出现乱码,一般不会出现乱码 double randomDouble = Math.random() * 10000; int randomInt = (int)randomDouble; newFileName = "new" + randomInt + suffix; File savefile = new File(new File(realpath), newFileName); //如果保存的路径不存在,则新建 if(!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs(); try{ //复制文件 FileUtils.copyFile(file, savefile); System.out.println("文件上传成功"); }catch(IOException e){ e.printStackTrace(); System.out.println("文件上传失败"); return INPUT; } } return SUCCESS; } public WeixinQrCodeService getWeixinQrCodeService() { return weixinQrCodeService; } public void setWeixinQrCodeService(WeixinQrCodeService weixinQrCodeService) { this.weixinQrCodeService = weixinQrCodeService; } }
UTF-8
Java
6,057
java
WeixinJSSDKAction.java
Java
[]
null
[]
package com.sunwah.baseapp.weixin.action; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import net.sf.json.JSONObject; import com.opensymphony.xwork2.ActionSupport; import com.sunwah.baseapp.weixin.service.WeixinAuthorizeService; import com.sunwah.baseapp.weixin.service.WeixinMediaService; import com.sunwah.baseapp.weixin.service.WeixinQrCodeService; import com.sunwah.baseapp.weixin.util.JSSDKUtil; public class WeixinJSSDKAction extends ActionSupport{ private static JSSDKUtil util = new JSSDKUtil(); private String url; private WeixinMediaService weixinMediaService; private String requestArea2; private String filePath1; private String code; private WeixinAuthorizeService weixinAuthorizeService; private File file; private String fileFileName; private WeixinQrCodeService weixinQrCodeService; /* * 这里定义的是文件的类型,如果不需要获取文件类型的话,可以不定义.   *  命名规则跟xxxFileName类似,这里一定要定义成xxxContentType形式.  */ private String fileContentType; /* * 这个变量是重名名后的文件名 */ private String newFileName; public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } public String getFileContentType() { return fileContentType; } public void setFileContentType(String fileContentType) { this.fileContentType = fileContentType; } public WeixinAuthorizeService getWeixinAuthorizeService() { return weixinAuthorizeService; } public void setWeixinAuthorizeService( WeixinAuthorizeService weixinAuthorizeService) { this.weixinAuthorizeService = weixinAuthorizeService; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getRequestArea2() { return requestArea2; } public void setRequestArea2(String requestArea2) { this.requestArea2 = requestArea2; } public String getFilePath1() { return filePath1; } public void setFilePath1(String filePath1) { this.filePath1 = filePath1; } public WeixinMediaService getWeixinMediaService() { return weixinMediaService; } public void setWeixinMediaService(WeixinMediaService weixinMediaService) { this.weixinMediaService = weixinMediaService; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public void getData(){ util.getSignatureAlgorithm(url); String noncestr = util.getNoncestr(); String ticket = util.getTicket(); String timestamp = util.getTimestamp(); String signature = util.getSignature(); JSONObject obj = new JSONObject(); obj.put("noncestr", noncestr); obj.put("ticket", ticket); obj.put("timestamp", timestamp); obj.put("signature", signature); String jsonString = obj.toString(); HttpServletResponse response = ServletActionContext.getResponse(); try { PrintWriter out = response.getWriter(); out.print(jsonString); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String testQrCode(){ JSONObject result = this.weixinQrCodeService.createQrScene(300, 123); String ticket = result.getString("ticket"); this.weixinQrCodeService.showQrCode("asdfas"); return "success"; } public String handleSubmit(){ System.out.println(this.getRequestArea2()); if(filePath1 != null) this.getWeixinMediaService().getMedia(filePath1); if(file != null) return upload(); return "success"; } public String handleAuthorize(){ JSONObject result = this.getWeixinAuthorizeService().codeToAccessToken(code); System.out.println(result.toString()); String accessToken = result.getString("access_token"); String openId = result.getString("openid"); JSONObject result1 = this.getWeixinAuthorizeService().getUserInfo(accessToken, openId); System.out.println(result1.toString()); return "success"; } public String upload(){ System.out.println("文件名:" + fileFileName); System.out.println("文件类型:" + fileContentType); if(file != null){ //文件保存目录是WebContent/file目录下 String realpath = ServletActionContext.getServletContext().getRealPath("/file"); System.out.println("文件的保存路径:" + realpath); //文件的后缀 String suffix = fileFileName.substring(fileFileName.lastIndexOf(".")); if(fileFileName.lastIndexOf(".") == -1){ return INPUT; } //上传以后,会重命名文件的名称,将其命名为全部是数字的文件名,防止可能出现的乱码. //当然,只是为了防止出现乱码,一般不会出现乱码 double randomDouble = Math.random() * 10000; int randomInt = (int)randomDouble; newFileName = "new" + randomInt + suffix; File savefile = new File(new File(realpath), newFileName); //如果保存的路径不存在,则新建 if(!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs(); try{ //复制文件 FileUtils.copyFile(file, savefile); System.out.println("文件上传成功"); }catch(IOException e){ e.printStackTrace(); System.out.println("文件上传失败"); return INPUT; } } return SUCCESS; } public WeixinQrCodeService getWeixinQrCodeService() { return weixinQrCodeService; } public void setWeixinQrCodeService(WeixinQrCodeService weixinQrCodeService) { this.weixinQrCodeService = weixinQrCodeService; } }
6,057
0.703814
0.698014
218
25.096331
21.57991
90
false
false
0
0
0
0
0
0
2.600917
false
false
2
07c0e912c40daadbc08e2a7f2518d7f001e48480
36,292,473,662,389
4b25bd24201828d4ca18212a16a5a030ba1f5400
/hazelcast/src/main/java/com/hazelcast/client/impl/spi/impl/ClientClusterViewService.java
cc3c3e7443a2ef772ab98ddea5b17fe4fb0c1b88
[ "Apache-2.0" ]
permissive
ybs-tech/hazelcast
https://github.com/ybs-tech/hazelcast
0be3842d9688db09bddb272eaef74b360193e11e
af2778f9c76364e281efc8f7127bae233600f1a8
refs/heads/master
2022-03-22T18:20:52.657000
2019-12-03T14:10:12
2019-12-03T14:10:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * 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 com.hazelcast.client.impl.spi.impl; import com.hazelcast.client.Client; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.config.ClientConnectionStrategyConfig; import com.hazelcast.client.impl.ClientImpl; import com.hazelcast.client.impl.MemberImpl; import com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl; import com.hazelcast.client.impl.connection.ClientConnectionManager; import com.hazelcast.client.impl.connection.nio.ClientConnection; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.codec.ClientAddClusterViewListenerCodec; import com.hazelcast.client.impl.spi.ClientClusterService; import com.hazelcast.client.impl.spi.ClientListenerService; import com.hazelcast.client.impl.spi.ClientPartitionService; import com.hazelcast.client.impl.spi.EventHandler; import com.hazelcast.cluster.Address; import com.hazelcast.cluster.Cluster; import com.hazelcast.cluster.InitialMembershipEvent; import com.hazelcast.cluster.InitialMembershipListener; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.MemberAttributeEvent; import com.hazelcast.cluster.MemberAttributeOperationType; import com.hazelcast.cluster.MemberSelector; import com.hazelcast.cluster.MembershipEvent; import com.hazelcast.cluster.MembershipListener; import com.hazelcast.cluster.impl.AbstractMember; import com.hazelcast.cluster.memberselector.MemberSelectors; import com.hazelcast.config.ListenerConfig; import com.hazelcast.internal.cluster.MemberInfo; import com.hazelcast.internal.cluster.impl.MemberSelectingCollection; import com.hazelcast.internal.nio.ClassLoaderUtil; import com.hazelcast.internal.nio.Connection; import com.hazelcast.internal.util.Clock; import com.hazelcast.internal.util.ExceptionUtil; import com.hazelcast.internal.util.HashUtil; import com.hazelcast.internal.util.UuidUtil; import com.hazelcast.internal.util.collection.Int2ObjectHashMap; import com.hazelcast.logging.ILogger; import com.hazelcast.nio.serialization.Data; import com.hazelcast.partition.NoDataMemberInClusterException; import com.hazelcast.partition.Partition; import com.hazelcast.partition.PartitionLostListener; import com.hazelcast.spi.exception.TargetDisconnectedException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.net.InetSocketAddress; import java.util.Collection; import java.util.Collections; import java.util.EventListener; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static com.hazelcast.internal.util.Preconditions.checkNotNull; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableSet; /** * The {@link ClientClusterService} and {@link ClientPartitionService} implementation. */ public class ClientClusterViewService implements ClientClusterService, ClientPartitionService { private static final int INITIAL_MEMBERS_TIMEOUT_SECONDS = 120; private static final ListenerMessageCodec CLUSTER_VIEW_LISTENER_CODEC = new ListenerMessageCodec() { @Override public ClientMessage encodeAddRequest(boolean localOnly) { return ClientAddClusterViewListenerCodec.encodeRequest(localOnly); } @Override public UUID decodeAddResponse(ClientMessage clientMessage) { return UuidUtil.NIL_UUID; } @Override public ClientMessage encodeRemoveRequest(UUID realRegistrationId) { return null; } @Override public boolean decodeRemoveResponse(ClientMessage clientMessage) { return true; } }; private static final ClusterViewSnapshot EMPTY_SNAPSHOT = new ClusterViewSnapshot(-1, new LinkedHashMap<>(), Collections.emptySet(), -1, new Int2ObjectHashMap<>()); private static final long BLOCKING_GET_ONCE_SLEEP_MILLIS = 100; private final HazelcastClientInstanceImpl client; private final AtomicReference<ClusterViewSnapshot> clusterSnapshot = new AtomicReference<>(EMPTY_SNAPSHOT); private final ConcurrentMap<UUID, MembershipListener> listeners = new ConcurrentHashMap<>(); private final Object clusterViewLock = new Object(); private final Set<String> labels; private final ILogger logger; private final ClientConnectionManager connectionManager; private final ClientListenerService listenerService; private final CountDownLatch initialListFetchedLatch = new CountDownLatch(1); private volatile int partitionCount; private volatile UUID clusterViewListenerUUID; private static final class ClusterViewSnapshot { private final int version; private final LinkedHashMap<Address, Member> members; private final Set<Member> memberSet; private final int partitionSateVersion; private final Int2ObjectHashMap<Address> partitions; private ClusterViewSnapshot(int version, LinkedHashMap<Address, Member> members, Set<Member> memberSet, int partitionSateVersion, Int2ObjectHashMap<Address> partitions) { this.version = version; this.members = members; this.memberSet = memberSet; this.partitionSateVersion = partitionSateVersion; this.partitions = partitions; } } public ClientClusterViewService(HazelcastClientInstanceImpl client) { this.client = client; labels = unmodifiableSet(client.getClientConfig().getLabels()); logger = client.getLoggingService().getLogger(ClientClusterService.class); connectionManager = client.getConnectionManager(); listenerService = client.getListenerService(); } private void handleListenerConfigs() { ClientConfig clientConfig = client.getClientConfig(); List<ListenerConfig> listenerConfigs = clientConfig.getListenerConfigs(); for (ListenerConfig listenerConfig : listenerConfigs) { EventListener listener = listenerConfig.getImplementation(); if (listener == null) { try { listener = ClassLoaderUtil.newInstance(clientConfig.getClassLoader(), listenerConfig.getClassName()); } catch (Exception e) { logger.severe(e); } } if (listener instanceof MembershipListener) { addMembershipListenerWithoutInit((MembershipListener) listener); } if (listener instanceof PartitionLostListener) { client.getPartitionService().addPartitionLostListener((PartitionLostListener) listener); } } } @Override public Member getMember(Address address) { return clusterSnapshot.get().members.get(address); } @Override public Member getMember(@Nonnull UUID uuid) { checkNotNull(uuid, "UUID must not be null"); final Collection<Member> memberList = getMemberList(); for (Member member : memberList) { if (uuid.equals(member.getUuid())) { return member; } } return null; } @Override public Collection<Member> getMemberList() { return clusterSnapshot.get().members.values(); } @Override public Collection<Member> getMembers(@Nonnull MemberSelector selector) { checkNotNull(selector, "selector must not be null"); return new MemberSelectingCollection<>(getMemberList(), selector); } @Override public Address getMasterAddress() { final Collection<Member> memberList = getMemberList(); return !memberList.isEmpty() ? new Address(memberList.iterator().next().getSocketAddress()) : null; } @Override public int getSize() { return getMemberList().size(); } @Override public int getSize(@Nonnull MemberSelector selector) { checkNotNull(selector, "selector must not be null"); int size = 0; for (Member member : getMemberList()) { if (selector.select(member)) { size++; } } return size; } @Override public long getClusterTime() { return Clock.currentTimeMillis(); } @Override public Client getLocalClient() { final ClientConnectionManager cm = client.getConnectionManager(); final ClientConnection connection = (ClientConnection) cm.getRandomConnection(); InetSocketAddress inetSocketAddress = connection != null ? connection.getLocalSocketAddress() : null; UUID clientUuid = cm.getClientUuid(); return new ClientImpl(clientUuid, inetSocketAddress, client.getName(), labels); } @Nonnull @Override public UUID addMembershipListener(@Nonnull MembershipListener listener) { checkNotNull(listener, "Listener can't be null"); synchronized (clusterViewLock) { UUID id = addMembershipListenerWithoutInit(listener); if (listener instanceof InitialMembershipListener) { Cluster cluster = client.getCluster(); Set<Member> members = clusterSnapshot.get().memberSet; //if members are empty,it means initial event did not arrive yet //it will be redirected to listeners when it arrives see #handleInitialMembershipEvent if (!members.isEmpty()) { InitialMembershipEvent event = new InitialMembershipEvent(cluster, members); ((InitialMembershipListener) listener).init(event); } } return id; } } private UUID addMembershipListenerWithoutInit(@Nonnull MembershipListener listener) { UUID id = UuidUtil.newUnsecureUUID(); listeners.put(id, listener); return id; } @Override public boolean removeMembershipListener(@Nonnull UUID registrationId) { checkNotNull(registrationId, "registrationId can't be null"); return listeners.remove(registrationId) != null; } public void start() { handleListenerConfigs(); clusterViewListenerUUID = listenerService.registerListener(CLUSTER_VIEW_LISTENER_CODEC, new ClusterViewListenerHandler()); ClientConnectionStrategyConfig connectionStrategyConfig = client.getClientConfig().getConnectionStrategyConfig(); boolean asyncStart = connectionStrategyConfig.isAsyncStart(); if (!asyncStart) { waitInitialMemberListFetched(); } } public void shutdown() { UUID lastListenerUUID = this.clusterViewListenerUUID; if (lastListenerUUID != null) { listenerService.deregisterListener(lastListenerUUID); } } private void waitInitialMemberListFetched() { try { boolean success = initialListFetchedLatch.await(INITIAL_MEMBERS_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!success) { throw new IllegalStateException("Could not get initial member list from cluster!"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw ExceptionUtil.rethrow(e); } } public void reset() { List<MembershipEvent> events; synchronized (clusterViewLock) { if (logger.isFineEnabled()) { logger.fine("Resetting the cluster snapshot"); } ClusterViewSnapshot cleanSnapshot = new ClusterViewSnapshot(-1, new LinkedHashMap<>(), Collections.emptySet(), -1, new Int2ObjectHashMap<>()); events = detectMembershipEvents(clusterSnapshot.get().memberSet, Collections.emptySet()); clusterSnapshot.set(cleanSnapshot); } fireEvents(events); } private void applyInitialState(int version, Collection<MemberInfo> memberInfos, Collection<Map.Entry<Address, List<Integer>>> partitions, int partitionStateVersion) { Int2ObjectHashMap<Address> map = convertToPartitionToAddressMap(partitions); ClusterViewSnapshot snapshot = createSnapshot(version, memberInfos, map, partitionStateVersion); clusterSnapshot.set(snapshot); logger.info(membersString(snapshot)); Set<Member> members = snapshot.memberSet; InitialMembershipEvent event = new InitialMembershipEvent(client.getCluster(), members); for (MembershipListener listener : listeners.values()) { if (listener instanceof InitialMembershipListener) { ((InitialMembershipListener) listener).init(event); } } onPartitionTableUpdate(); } private void onPartitionTableUpdate() { // partition count is set once at the start. Even if we reset the partition table when switching cluster // we want to remember the partition count. That is why it is a different field. ClusterViewSnapshot clusterViewSnapshot = clusterSnapshot.get(); Int2ObjectHashMap<Address> newPartitions = clusterViewSnapshot.partitions; if (partitionCount == 0) { partitionCount = newPartitions.size(); } if (logger.isFineEnabled()) { logger.fine("Processed partition response. partitionStateVersion : " + clusterViewSnapshot.partitionSateVersion + ", partitionCount :" + newPartitions.size()); } } private void applyNewState(int memberListVersion, Collection<MemberInfo> memberInfos, Collection<Map.Entry<Address, List<Integer>>> partitions, int partitionStateVersion, ClusterViewSnapshot oldState) { ClusterViewSnapshot newState; if (fromSameMaster(oldState.members, memberInfos)) { //if masters are same, we can update member list and partition table separately if (partitionStateVersion > oldState.partitionSateVersion) { //incoming partition table is more up-to-date Int2ObjectHashMap<Address> map = convertToPartitionToAddressMap(partitions); newState = createSnapshot(memberListVersion, memberInfos, map, partitionStateVersion); } else { //re-use current partition table newState = createSnapshot(memberListVersion, memberInfos, oldState.partitions, oldState.partitionSateVersion); } } else { //masters are different switch with new state (both member list and partition table) atomically Int2ObjectHashMap<Address> map = convertToPartitionToAddressMap(partitions); newState = createSnapshot(memberListVersion, memberInfos, map, partitionStateVersion); } clusterSnapshot.set(newState); onPartitionTableUpdate(); } private boolean fromSameMaster(Map<Address, Member> currentMembers, Collection<MemberInfo> newMemberInfos) { Iterator<Member> iterator = currentMembers.values().iterator(); if (!iterator.hasNext()) { return false; } Member masterMember = iterator.next(); MemberInfo newMaster = newMemberInfos.iterator().next(); return masterMember.getUuid().equals(newMaster.getUuid()); } private ClusterViewSnapshot createSnapshot(int version, Collection<MemberInfo> memberInfos, Int2ObjectHashMap<Address> partitions, int partitionStateVersion) { LinkedHashMap<Address, Member> newMembers = new LinkedHashMap<>(); for (MemberInfo memberInfo : memberInfos) { Address address = memberInfo.getAddress(); newMembers.put(address, new MemberImpl(address, memberInfo.getVersion(), memberInfo.getUuid(), memberInfo.getAttributes(), memberInfo.isLiteMember())); } Set<Member> memberSet = unmodifiableSet(new HashSet<>(newMembers.values())); return new ClusterViewSnapshot(version, newMembers, memberSet, partitionStateVersion, partitions); } private List<MembershipEvent> detectMembershipEvents(Set<Member> prevMembers, Set<Member> currentMembers) { List<Member> newMembers = new LinkedList<>(); Set<Member> deadMembers = new HashSet<>(prevMembers); for (Member member : currentMembers) { if (!deadMembers.remove(member)) { newMembers.add(member); } } List<MembershipEvent> events = new LinkedList<>(); // removal events should be added before added events for (Member member : deadMembers) { events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_REMOVED, currentMembers)); Address address = member.getAddress(); if (getMember(address) == null) { Connection connection = connectionManager.getConnection(address); if (connection != null) { connection.close(null, new TargetDisconnectedException("The client has closed the connection to this member," + " after receiving a member left event from the cluster. " + connection)); } } } for (Member member : newMembers) { events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_ADDED, currentMembers)); } if (events.size() != 0) { logger.info(membersString(clusterSnapshot.get())); } return events; } private String membersString(ClusterViewSnapshot snapshot) { Collection<Member> members = snapshot.members.values(); StringBuilder sb = new StringBuilder("\n\nMembers ["); sb.append(members.size()); sb.append("] {"); for (Member member : members) { sb.append("\n\t").append(member); } sb.append("\n}\n"); return sb.toString(); } private class ClusterViewListenerHandler extends ClientAddClusterViewListenerCodec.AbstractEventHandler implements EventHandler<ClientMessage> { @Override public void beforeListenerRegister(Connection connection) { if (logger.isFinestEnabled()) { logger.finest("Register attempt of ClusterViewListenerHandler to " + connection); } } @Override public void onListenerRegister(Connection connection) { if (logger.isFinestEnabled()) { logger.finest("Registered ClusterViewListenerHandler to " + connection); } } @Override public void handleMembersViewEvent(int memberListVersion, Collection<MemberInfo> memberInfos, Collection<Map.Entry<Address, List<Integer>>> partitions, int partitionStateVersion) { if (logger.isFinestEnabled()) { Int2ObjectHashMap<Address> map = convertToPartitionToAddressMap(partitions); ClusterViewSnapshot snapshot = createSnapshot(memberListVersion, memberInfos, map, partitionStateVersion); logger.finest("Handling new snapshot with membership version: " + memberListVersion + ", partitionStateVersion: " + partitionStateVersion + ", membersString " + membersString(snapshot)); } ClusterViewSnapshot clusterViewSnapshot = clusterSnapshot.get(); if (clusterViewSnapshot == EMPTY_SNAPSHOT) { synchronized (clusterViewLock) { clusterViewSnapshot = clusterSnapshot.get(); if (clusterViewSnapshot == EMPTY_SNAPSHOT) { //this means this is the first time client connected to cluster applyInitialState(memberListVersion, memberInfos, partitions, partitionStateVersion); initialListFetchedLatch.countDown(); return; } } } List<MembershipEvent> events = emptyList(); if (memberListVersion >= clusterViewSnapshot.version) { synchronized (clusterViewLock) { clusterViewSnapshot = clusterSnapshot.get(); if (memberListVersion >= clusterViewSnapshot.version) { Set<Member> prevMembers = clusterSnapshot.get().memberSet; applyNewState(memberListVersion, memberInfos, partitions, partitionStateVersion, clusterViewSnapshot); Set<Member> currentMembers = clusterSnapshot.get().memberSet; events = detectMembershipEvents(prevMembers, currentMembers); } } } fireEvents(events); } @Override public void handleMemberAttributeChangeEvent(Member member, String key, int operationType, @Nullable String value) { Set<Member> currentMembers = clusterSnapshot.get().memberSet; Cluster cluster = client.getCluster(); UUID uuid = member.getUuid(); for (Member target : currentMembers) { if (target.getUuid().equals(uuid)) { MemberAttributeOperationType type = MemberAttributeOperationType.getValue(operationType); ((AbstractMember) target).updateAttribute(type, key, value); MemberAttributeEvent event = new MemberAttributeEvent(cluster, target, currentMembers, type, key, value); for (MembershipListener listener : listeners.values()) { listener.memberAttributeChanged(event); } break; } } } } private void fireEvents(List<MembershipEvent> events) { for (MembershipEvent event : events) { for (MembershipListener listener : listeners.values()) { if (event.getEventType() == MembershipEvent.MEMBER_ADDED) { listener.memberAdded(event); } else { listener.memberRemoved(event); } } } } private Int2ObjectHashMap<Address> convertToPartitionToAddressMap(Collection<Map.Entry<Address, List<Integer>>> partitions) { Int2ObjectHashMap<Address> newPartitions = new Int2ObjectHashMap<Address>(); for (Map.Entry<Address, List<Integer>> entry : partitions) { Address address = entry.getKey(); for (Integer partition : entry.getValue()) { newPartitions.put(partition, address); } } return newPartitions; } @Override public Address getPartitionOwner(int partitionId) { return clusterSnapshot.get().partitions.get(partitionId); } @Override public int getPartitionId(Data key) { final int pc = getPartitionCount(); if (pc <= 0) { return 0; } int hash = key.getPartitionHash(); return HashUtil.hashToIndex(hash, pc); } @Override public int getPartitionId(Object key) { final Data data = client.getSerializationService().toData(key); return getPartitionId(data); } @Override public int getPartitionCount() { while (partitionCount == 0 && connectionManager.isAlive()) { Set<Member> memberList = clusterSnapshot.get().memberSet; if (MemberSelectingCollection.count(memberList, MemberSelectors.DATA_MEMBER_SELECTOR) == 0) { throw new NoDataMemberInClusterException( "Partitions can't be assigned since all nodes in the cluster are lite members"); } try { Thread.sleep(BLOCKING_GET_ONCE_SLEEP_MILLIS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw ExceptionUtil.rethrow(e); } } return partitionCount; } @Override public Partition getPartition(int partitionId) { return new PartitionImpl(partitionId); } private final class PartitionImpl implements Partition { private final int partitionId; private PartitionImpl(int partitionId) { this.partitionId = partitionId; } @Override public int getPartitionId() { return partitionId; } @Override public Member getOwner() { Address owner = getPartitionOwner(partitionId); if (owner != null) { return getMember(owner); } return null; } @Override public String toString() { return "PartitionImpl{partitionId=" + partitionId + '}'; } } }
UTF-8
Java
26,018
java
ClientClusterViewService.java
Java
[ { "context": "/*\n * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.\n *\n * Licensed", "end": 32, "score": 0.8909170031547546, "start": 31, "tag": "NAME", "value": "H" } ]
null
[]
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * 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 com.hazelcast.client.impl.spi.impl; import com.hazelcast.client.Client; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.config.ClientConnectionStrategyConfig; import com.hazelcast.client.impl.ClientImpl; import com.hazelcast.client.impl.MemberImpl; import com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl; import com.hazelcast.client.impl.connection.ClientConnectionManager; import com.hazelcast.client.impl.connection.nio.ClientConnection; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.codec.ClientAddClusterViewListenerCodec; import com.hazelcast.client.impl.spi.ClientClusterService; import com.hazelcast.client.impl.spi.ClientListenerService; import com.hazelcast.client.impl.spi.ClientPartitionService; import com.hazelcast.client.impl.spi.EventHandler; import com.hazelcast.cluster.Address; import com.hazelcast.cluster.Cluster; import com.hazelcast.cluster.InitialMembershipEvent; import com.hazelcast.cluster.InitialMembershipListener; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.MemberAttributeEvent; import com.hazelcast.cluster.MemberAttributeOperationType; import com.hazelcast.cluster.MemberSelector; import com.hazelcast.cluster.MembershipEvent; import com.hazelcast.cluster.MembershipListener; import com.hazelcast.cluster.impl.AbstractMember; import com.hazelcast.cluster.memberselector.MemberSelectors; import com.hazelcast.config.ListenerConfig; import com.hazelcast.internal.cluster.MemberInfo; import com.hazelcast.internal.cluster.impl.MemberSelectingCollection; import com.hazelcast.internal.nio.ClassLoaderUtil; import com.hazelcast.internal.nio.Connection; import com.hazelcast.internal.util.Clock; import com.hazelcast.internal.util.ExceptionUtil; import com.hazelcast.internal.util.HashUtil; import com.hazelcast.internal.util.UuidUtil; import com.hazelcast.internal.util.collection.Int2ObjectHashMap; import com.hazelcast.logging.ILogger; import com.hazelcast.nio.serialization.Data; import com.hazelcast.partition.NoDataMemberInClusterException; import com.hazelcast.partition.Partition; import com.hazelcast.partition.PartitionLostListener; import com.hazelcast.spi.exception.TargetDisconnectedException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.net.InetSocketAddress; import java.util.Collection; import java.util.Collections; import java.util.EventListener; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static com.hazelcast.internal.util.Preconditions.checkNotNull; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableSet; /** * The {@link ClientClusterService} and {@link ClientPartitionService} implementation. */ public class ClientClusterViewService implements ClientClusterService, ClientPartitionService { private static final int INITIAL_MEMBERS_TIMEOUT_SECONDS = 120; private static final ListenerMessageCodec CLUSTER_VIEW_LISTENER_CODEC = new ListenerMessageCodec() { @Override public ClientMessage encodeAddRequest(boolean localOnly) { return ClientAddClusterViewListenerCodec.encodeRequest(localOnly); } @Override public UUID decodeAddResponse(ClientMessage clientMessage) { return UuidUtil.NIL_UUID; } @Override public ClientMessage encodeRemoveRequest(UUID realRegistrationId) { return null; } @Override public boolean decodeRemoveResponse(ClientMessage clientMessage) { return true; } }; private static final ClusterViewSnapshot EMPTY_SNAPSHOT = new ClusterViewSnapshot(-1, new LinkedHashMap<>(), Collections.emptySet(), -1, new Int2ObjectHashMap<>()); private static final long BLOCKING_GET_ONCE_SLEEP_MILLIS = 100; private final HazelcastClientInstanceImpl client; private final AtomicReference<ClusterViewSnapshot> clusterSnapshot = new AtomicReference<>(EMPTY_SNAPSHOT); private final ConcurrentMap<UUID, MembershipListener> listeners = new ConcurrentHashMap<>(); private final Object clusterViewLock = new Object(); private final Set<String> labels; private final ILogger logger; private final ClientConnectionManager connectionManager; private final ClientListenerService listenerService; private final CountDownLatch initialListFetchedLatch = new CountDownLatch(1); private volatile int partitionCount; private volatile UUID clusterViewListenerUUID; private static final class ClusterViewSnapshot { private final int version; private final LinkedHashMap<Address, Member> members; private final Set<Member> memberSet; private final int partitionSateVersion; private final Int2ObjectHashMap<Address> partitions; private ClusterViewSnapshot(int version, LinkedHashMap<Address, Member> members, Set<Member> memberSet, int partitionSateVersion, Int2ObjectHashMap<Address> partitions) { this.version = version; this.members = members; this.memberSet = memberSet; this.partitionSateVersion = partitionSateVersion; this.partitions = partitions; } } public ClientClusterViewService(HazelcastClientInstanceImpl client) { this.client = client; labels = unmodifiableSet(client.getClientConfig().getLabels()); logger = client.getLoggingService().getLogger(ClientClusterService.class); connectionManager = client.getConnectionManager(); listenerService = client.getListenerService(); } private void handleListenerConfigs() { ClientConfig clientConfig = client.getClientConfig(); List<ListenerConfig> listenerConfigs = clientConfig.getListenerConfigs(); for (ListenerConfig listenerConfig : listenerConfigs) { EventListener listener = listenerConfig.getImplementation(); if (listener == null) { try { listener = ClassLoaderUtil.newInstance(clientConfig.getClassLoader(), listenerConfig.getClassName()); } catch (Exception e) { logger.severe(e); } } if (listener instanceof MembershipListener) { addMembershipListenerWithoutInit((MembershipListener) listener); } if (listener instanceof PartitionLostListener) { client.getPartitionService().addPartitionLostListener((PartitionLostListener) listener); } } } @Override public Member getMember(Address address) { return clusterSnapshot.get().members.get(address); } @Override public Member getMember(@Nonnull UUID uuid) { checkNotNull(uuid, "UUID must not be null"); final Collection<Member> memberList = getMemberList(); for (Member member : memberList) { if (uuid.equals(member.getUuid())) { return member; } } return null; } @Override public Collection<Member> getMemberList() { return clusterSnapshot.get().members.values(); } @Override public Collection<Member> getMembers(@Nonnull MemberSelector selector) { checkNotNull(selector, "selector must not be null"); return new MemberSelectingCollection<>(getMemberList(), selector); } @Override public Address getMasterAddress() { final Collection<Member> memberList = getMemberList(); return !memberList.isEmpty() ? new Address(memberList.iterator().next().getSocketAddress()) : null; } @Override public int getSize() { return getMemberList().size(); } @Override public int getSize(@Nonnull MemberSelector selector) { checkNotNull(selector, "selector must not be null"); int size = 0; for (Member member : getMemberList()) { if (selector.select(member)) { size++; } } return size; } @Override public long getClusterTime() { return Clock.currentTimeMillis(); } @Override public Client getLocalClient() { final ClientConnectionManager cm = client.getConnectionManager(); final ClientConnection connection = (ClientConnection) cm.getRandomConnection(); InetSocketAddress inetSocketAddress = connection != null ? connection.getLocalSocketAddress() : null; UUID clientUuid = cm.getClientUuid(); return new ClientImpl(clientUuid, inetSocketAddress, client.getName(), labels); } @Nonnull @Override public UUID addMembershipListener(@Nonnull MembershipListener listener) { checkNotNull(listener, "Listener can't be null"); synchronized (clusterViewLock) { UUID id = addMembershipListenerWithoutInit(listener); if (listener instanceof InitialMembershipListener) { Cluster cluster = client.getCluster(); Set<Member> members = clusterSnapshot.get().memberSet; //if members are empty,it means initial event did not arrive yet //it will be redirected to listeners when it arrives see #handleInitialMembershipEvent if (!members.isEmpty()) { InitialMembershipEvent event = new InitialMembershipEvent(cluster, members); ((InitialMembershipListener) listener).init(event); } } return id; } } private UUID addMembershipListenerWithoutInit(@Nonnull MembershipListener listener) { UUID id = UuidUtil.newUnsecureUUID(); listeners.put(id, listener); return id; } @Override public boolean removeMembershipListener(@Nonnull UUID registrationId) { checkNotNull(registrationId, "registrationId can't be null"); return listeners.remove(registrationId) != null; } public void start() { handleListenerConfigs(); clusterViewListenerUUID = listenerService.registerListener(CLUSTER_VIEW_LISTENER_CODEC, new ClusterViewListenerHandler()); ClientConnectionStrategyConfig connectionStrategyConfig = client.getClientConfig().getConnectionStrategyConfig(); boolean asyncStart = connectionStrategyConfig.isAsyncStart(); if (!asyncStart) { waitInitialMemberListFetched(); } } public void shutdown() { UUID lastListenerUUID = this.clusterViewListenerUUID; if (lastListenerUUID != null) { listenerService.deregisterListener(lastListenerUUID); } } private void waitInitialMemberListFetched() { try { boolean success = initialListFetchedLatch.await(INITIAL_MEMBERS_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!success) { throw new IllegalStateException("Could not get initial member list from cluster!"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw ExceptionUtil.rethrow(e); } } public void reset() { List<MembershipEvent> events; synchronized (clusterViewLock) { if (logger.isFineEnabled()) { logger.fine("Resetting the cluster snapshot"); } ClusterViewSnapshot cleanSnapshot = new ClusterViewSnapshot(-1, new LinkedHashMap<>(), Collections.emptySet(), -1, new Int2ObjectHashMap<>()); events = detectMembershipEvents(clusterSnapshot.get().memberSet, Collections.emptySet()); clusterSnapshot.set(cleanSnapshot); } fireEvents(events); } private void applyInitialState(int version, Collection<MemberInfo> memberInfos, Collection<Map.Entry<Address, List<Integer>>> partitions, int partitionStateVersion) { Int2ObjectHashMap<Address> map = convertToPartitionToAddressMap(partitions); ClusterViewSnapshot snapshot = createSnapshot(version, memberInfos, map, partitionStateVersion); clusterSnapshot.set(snapshot); logger.info(membersString(snapshot)); Set<Member> members = snapshot.memberSet; InitialMembershipEvent event = new InitialMembershipEvent(client.getCluster(), members); for (MembershipListener listener : listeners.values()) { if (listener instanceof InitialMembershipListener) { ((InitialMembershipListener) listener).init(event); } } onPartitionTableUpdate(); } private void onPartitionTableUpdate() { // partition count is set once at the start. Even if we reset the partition table when switching cluster // we want to remember the partition count. That is why it is a different field. ClusterViewSnapshot clusterViewSnapshot = clusterSnapshot.get(); Int2ObjectHashMap<Address> newPartitions = clusterViewSnapshot.partitions; if (partitionCount == 0) { partitionCount = newPartitions.size(); } if (logger.isFineEnabled()) { logger.fine("Processed partition response. partitionStateVersion : " + clusterViewSnapshot.partitionSateVersion + ", partitionCount :" + newPartitions.size()); } } private void applyNewState(int memberListVersion, Collection<MemberInfo> memberInfos, Collection<Map.Entry<Address, List<Integer>>> partitions, int partitionStateVersion, ClusterViewSnapshot oldState) { ClusterViewSnapshot newState; if (fromSameMaster(oldState.members, memberInfos)) { //if masters are same, we can update member list and partition table separately if (partitionStateVersion > oldState.partitionSateVersion) { //incoming partition table is more up-to-date Int2ObjectHashMap<Address> map = convertToPartitionToAddressMap(partitions); newState = createSnapshot(memberListVersion, memberInfos, map, partitionStateVersion); } else { //re-use current partition table newState = createSnapshot(memberListVersion, memberInfos, oldState.partitions, oldState.partitionSateVersion); } } else { //masters are different switch with new state (both member list and partition table) atomically Int2ObjectHashMap<Address> map = convertToPartitionToAddressMap(partitions); newState = createSnapshot(memberListVersion, memberInfos, map, partitionStateVersion); } clusterSnapshot.set(newState); onPartitionTableUpdate(); } private boolean fromSameMaster(Map<Address, Member> currentMembers, Collection<MemberInfo> newMemberInfos) { Iterator<Member> iterator = currentMembers.values().iterator(); if (!iterator.hasNext()) { return false; } Member masterMember = iterator.next(); MemberInfo newMaster = newMemberInfos.iterator().next(); return masterMember.getUuid().equals(newMaster.getUuid()); } private ClusterViewSnapshot createSnapshot(int version, Collection<MemberInfo> memberInfos, Int2ObjectHashMap<Address> partitions, int partitionStateVersion) { LinkedHashMap<Address, Member> newMembers = new LinkedHashMap<>(); for (MemberInfo memberInfo : memberInfos) { Address address = memberInfo.getAddress(); newMembers.put(address, new MemberImpl(address, memberInfo.getVersion(), memberInfo.getUuid(), memberInfo.getAttributes(), memberInfo.isLiteMember())); } Set<Member> memberSet = unmodifiableSet(new HashSet<>(newMembers.values())); return new ClusterViewSnapshot(version, newMembers, memberSet, partitionStateVersion, partitions); } private List<MembershipEvent> detectMembershipEvents(Set<Member> prevMembers, Set<Member> currentMembers) { List<Member> newMembers = new LinkedList<>(); Set<Member> deadMembers = new HashSet<>(prevMembers); for (Member member : currentMembers) { if (!deadMembers.remove(member)) { newMembers.add(member); } } List<MembershipEvent> events = new LinkedList<>(); // removal events should be added before added events for (Member member : deadMembers) { events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_REMOVED, currentMembers)); Address address = member.getAddress(); if (getMember(address) == null) { Connection connection = connectionManager.getConnection(address); if (connection != null) { connection.close(null, new TargetDisconnectedException("The client has closed the connection to this member," + " after receiving a member left event from the cluster. " + connection)); } } } for (Member member : newMembers) { events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_ADDED, currentMembers)); } if (events.size() != 0) { logger.info(membersString(clusterSnapshot.get())); } return events; } private String membersString(ClusterViewSnapshot snapshot) { Collection<Member> members = snapshot.members.values(); StringBuilder sb = new StringBuilder("\n\nMembers ["); sb.append(members.size()); sb.append("] {"); for (Member member : members) { sb.append("\n\t").append(member); } sb.append("\n}\n"); return sb.toString(); } private class ClusterViewListenerHandler extends ClientAddClusterViewListenerCodec.AbstractEventHandler implements EventHandler<ClientMessage> { @Override public void beforeListenerRegister(Connection connection) { if (logger.isFinestEnabled()) { logger.finest("Register attempt of ClusterViewListenerHandler to " + connection); } } @Override public void onListenerRegister(Connection connection) { if (logger.isFinestEnabled()) { logger.finest("Registered ClusterViewListenerHandler to " + connection); } } @Override public void handleMembersViewEvent(int memberListVersion, Collection<MemberInfo> memberInfos, Collection<Map.Entry<Address, List<Integer>>> partitions, int partitionStateVersion) { if (logger.isFinestEnabled()) { Int2ObjectHashMap<Address> map = convertToPartitionToAddressMap(partitions); ClusterViewSnapshot snapshot = createSnapshot(memberListVersion, memberInfos, map, partitionStateVersion); logger.finest("Handling new snapshot with membership version: " + memberListVersion + ", partitionStateVersion: " + partitionStateVersion + ", membersString " + membersString(snapshot)); } ClusterViewSnapshot clusterViewSnapshot = clusterSnapshot.get(); if (clusterViewSnapshot == EMPTY_SNAPSHOT) { synchronized (clusterViewLock) { clusterViewSnapshot = clusterSnapshot.get(); if (clusterViewSnapshot == EMPTY_SNAPSHOT) { //this means this is the first time client connected to cluster applyInitialState(memberListVersion, memberInfos, partitions, partitionStateVersion); initialListFetchedLatch.countDown(); return; } } } List<MembershipEvent> events = emptyList(); if (memberListVersion >= clusterViewSnapshot.version) { synchronized (clusterViewLock) { clusterViewSnapshot = clusterSnapshot.get(); if (memberListVersion >= clusterViewSnapshot.version) { Set<Member> prevMembers = clusterSnapshot.get().memberSet; applyNewState(memberListVersion, memberInfos, partitions, partitionStateVersion, clusterViewSnapshot); Set<Member> currentMembers = clusterSnapshot.get().memberSet; events = detectMembershipEvents(prevMembers, currentMembers); } } } fireEvents(events); } @Override public void handleMemberAttributeChangeEvent(Member member, String key, int operationType, @Nullable String value) { Set<Member> currentMembers = clusterSnapshot.get().memberSet; Cluster cluster = client.getCluster(); UUID uuid = member.getUuid(); for (Member target : currentMembers) { if (target.getUuid().equals(uuid)) { MemberAttributeOperationType type = MemberAttributeOperationType.getValue(operationType); ((AbstractMember) target).updateAttribute(type, key, value); MemberAttributeEvent event = new MemberAttributeEvent(cluster, target, currentMembers, type, key, value); for (MembershipListener listener : listeners.values()) { listener.memberAttributeChanged(event); } break; } } } } private void fireEvents(List<MembershipEvent> events) { for (MembershipEvent event : events) { for (MembershipListener listener : listeners.values()) { if (event.getEventType() == MembershipEvent.MEMBER_ADDED) { listener.memberAdded(event); } else { listener.memberRemoved(event); } } } } private Int2ObjectHashMap<Address> convertToPartitionToAddressMap(Collection<Map.Entry<Address, List<Integer>>> partitions) { Int2ObjectHashMap<Address> newPartitions = new Int2ObjectHashMap<Address>(); for (Map.Entry<Address, List<Integer>> entry : partitions) { Address address = entry.getKey(); for (Integer partition : entry.getValue()) { newPartitions.put(partition, address); } } return newPartitions; } @Override public Address getPartitionOwner(int partitionId) { return clusterSnapshot.get().partitions.get(partitionId); } @Override public int getPartitionId(Data key) { final int pc = getPartitionCount(); if (pc <= 0) { return 0; } int hash = key.getPartitionHash(); return HashUtil.hashToIndex(hash, pc); } @Override public int getPartitionId(Object key) { final Data data = client.getSerializationService().toData(key); return getPartitionId(data); } @Override public int getPartitionCount() { while (partitionCount == 0 && connectionManager.isAlive()) { Set<Member> memberList = clusterSnapshot.get().memberSet; if (MemberSelectingCollection.count(memberList, MemberSelectors.DATA_MEMBER_SELECTOR) == 0) { throw new NoDataMemberInClusterException( "Partitions can't be assigned since all nodes in the cluster are lite members"); } try { Thread.sleep(BLOCKING_GET_ONCE_SLEEP_MILLIS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw ExceptionUtil.rethrow(e); } } return partitionCount; } @Override public Partition getPartition(int partitionId) { return new PartitionImpl(partitionId); } private final class PartitionImpl implements Partition { private final int partitionId; private PartitionImpl(int partitionId) { this.partitionId = partitionId; } @Override public int getPartitionId() { return partitionId; } @Override public Member getOwner() { Address owner = getPartitionOwner(partitionId); if (owner != null) { return getMember(owner); } return null; } @Override public String toString() { return "PartitionImpl{partitionId=" + partitionId + '}'; } } }
26,018
0.656968
0.655277
607
41.863262
32.620773
130
false
false
0
0
0
0
0
0
0.61944
false
false
2
298675001250685111b9231a26e11f20bf7519a1
23,261,542,913,544
5a3482885648c4aebcfed029ec552b311949551f
/electric-core/src/main/java/com/anton/electric/model/Switchboard.java
57150e4bca2bf0e246168ac18ba4e35dcaed4f66
[]
no_license
apechinsky/switchboard
https://github.com/apechinsky/switchboard
ad2e15c4390fde5559e422120bfdc2893d6d2394
1e52438e42e9bc2f977f2bc31be638b452de54da
refs/heads/master
2020-03-11T09:05:13.011000
2018-05-13T15:22:46
2018-05-13T15:22:46
129,901,582
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.anton.electric.model; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import com.google.common.base.MoreObjects; /** * Электрощиток. * * @author Q-APE */ public class Switchboard { private String name; private Map<String, Component> components; private Ground ground; private Consumers consumers; private Set<Group> groups; public Switchboard(String name, Map<String, Component> components, Ground ground, Consumers consumers, Set<Group> groups) { this.name = name; this.components = components; this.ground = ground; this.consumers = consumers; this.groups = groups; } public String getName() { return name; } public Collection<Component> getInputs() { return components.values().stream() .filter(Input380.class::isInstance) .collect(Collectors.toList()); } public Ground getGround() { return ground; } public List<Consumer> getConsumers() { return consumers.getConsumers(); } public Set<Component> getComponents() { Set<Component> components = new HashSet<>(); components.add(ground); components.addAll(this.components.values()); return components; } public Set<Group> getGroups() { return groups; } public double getPrice() { return getComponents().stream() .collect(Collectors.summingDouble(Component::price)); } public int getModules() { return getComponents().stream() .collect(Collectors.summingInt(Component::size)); } private void collectLinked(Component component, Map<String, Component> collector) { collector.put(component.id(), component); component.getOutputComponents().stream() .forEach(linkedComponent -> collectLinked(linkedComponent, collector)); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("components", getComponents().size()) .add("price", getPrice()) .add("modules", getModules()) .toString(); } }
UTF-8
Java
2,323
java
Switchboard.java
Java
[ { "context": "e.MoreObjects;\n\n/**\n * Электрощиток.\n *\n * @author Q-APE\n */\npublic class Switchboard {\n\n private Strin", "end": 278, "score": 0.9979196190834045, "start": 273, "tag": "USERNAME", "value": "Q-APE" } ]
null
[]
package com.anton.electric.model; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import com.google.common.base.MoreObjects; /** * Электрощиток. * * @author Q-APE */ public class Switchboard { private String name; private Map<String, Component> components; private Ground ground; private Consumers consumers; private Set<Group> groups; public Switchboard(String name, Map<String, Component> components, Ground ground, Consumers consumers, Set<Group> groups) { this.name = name; this.components = components; this.ground = ground; this.consumers = consumers; this.groups = groups; } public String getName() { return name; } public Collection<Component> getInputs() { return components.values().stream() .filter(Input380.class::isInstance) .collect(Collectors.toList()); } public Ground getGround() { return ground; } public List<Consumer> getConsumers() { return consumers.getConsumers(); } public Set<Component> getComponents() { Set<Component> components = new HashSet<>(); components.add(ground); components.addAll(this.components.values()); return components; } public Set<Group> getGroups() { return groups; } public double getPrice() { return getComponents().stream() .collect(Collectors.summingDouble(Component::price)); } public int getModules() { return getComponents().stream() .collect(Collectors.summingInt(Component::size)); } private void collectLinked(Component component, Map<String, Component> collector) { collector.put(component.id(), component); component.getOutputComponents().stream() .forEach(linkedComponent -> collectLinked(linkedComponent, collector)); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("components", getComponents().size()) .add("price", getPrice()) .add("modules", getModules()) .toString(); } }
2,323
0.630896
0.629598
93
23.849463
22.945913
127
false
false
0
0
0
0
0
0
0.494624
false
false
2
21bdabbfc60c752f8ed29abbc517f6652e2dc2ec
22,505,628,686,658
7b9f302f74faaa16eb803122c444b69bf01da45c
/src/edu/twister/malik/services/content/CommentDescription.java
411ca3bd67f39e86715af417b0e618f3df314cb3
[]
no_license
malikbenkirane/ip6.web3.twister
https://github.com/malikbenkirane/ip6.web3.twister
1816c23a2af35a30f97b5408735b4320a56653fa
07b5552ee02450b2d4225ef0b42af8e8941c354f
refs/heads/master
2021-01-19T18:47:28.256000
2017-04-19T13:59:12
2017-04-19T13:59:12
88,382,318
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.twister.malik.services.content; import edu.twister.malik.services.ServiceException; import edu.twister.malik.services.content.ContentException; import java.util.Date; import java.util.GregorianCalendar; import com.mongodb.DBObject; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.MongoException; import com.mongodb.DBCursor; public class CommentDescription { private String comment; private String userkey; private String username; private int useriid; private Date date; public CommentDescription (String comment, String userkey, String username, int useriid) { this.comment = comment; this.userkey = userkey; this.username = username; this.date = (new GregorianCalendar()).getTime(); } private static void validate (String comment) throws ServiceException { //ContentException._COMMENT_<...> return; } private static int update_sequence //incremental comment id (DBCollection messagesCollection, int mid) throws ServiceException { int iter, seq = 0; do { BasicDBObject query = new BasicDBObject(); query.append("mid", mid); BasicDBObject update = new BasicDBObject(); BasicDBObject _update = new BasicDBObject(); _update.append("ccnt", 1); update.put("$inc", _update); try { DBObject res = messagesCollection.findAndModify( query, null, null, false, update, true, false); seq = (Integer) res.get("ccnt"); //seq = _seq.intValue(); } catch (ClassCastException ce) { throw new ContentException(ContentException._CONTENT_NOT_CASTING); } catch (MongoException me) { throw new ServiceException(me); } catch (NullPointerException npe) { throw new ContentException(ContentException._NO_COUNTERS); } //resolve duplicates (concur) BasicDBObject dup = new BasicDBObject(); dup.append("mid", mid); dup.append("comments.id", seq); DBCursor c = messagesCollection.find(dup); iter = c.count(); } while (iter > 0); return seq; } public int insertIn(DBCollection messagesCollection, int mid) throws ServiceException { validate(comment); int cid = update_sequence(messagesCollection, mid); /* * document (commentDocument) * { id, comment, date, user : { iid, sid, name } } */ BasicDBObject commentDocument = new BasicDBObject(); BasicDBObject user = new BasicDBObject(); commentDocument.append("id", cid); commentDocument.append("date", date); commentDocument.append("comment", comment); user.append("iid", useriid); user.append("sid", userkey); user.append("name", username); commentDocument.append("user", user); //query BasicDBObject update = new BasicDBObject(); BasicDBObject _update = new BasicDBObject(); BasicDBObject query = new BasicDBObject(); _update.put("comments", commentDocument); update.put("$push", _update); query.put("mid", mid); try { messagesCollection.update(query, update); return cid; } catch (MongoException me) { throw new ServiceException(me); } } public Date getDate() { return date; } }
UTF-8
Java
4,055
java
CommentDescription.java
Java
[ { "context": "his.userkey = userkey;\n this.username = username;\n this.date = (new GregorianCalendar()", "end": 759, "score": 0.999147891998291, "start": 751, "tag": "USERNAME", "value": "username" }, { "context": "d(\"sid\", userkey);\n user.append(...
null
[]
package edu.twister.malik.services.content; import edu.twister.malik.services.ServiceException; import edu.twister.malik.services.content.ContentException; import java.util.Date; import java.util.GregorianCalendar; import com.mongodb.DBObject; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.MongoException; import com.mongodb.DBCursor; public class CommentDescription { private String comment; private String userkey; private String username; private int useriid; private Date date; public CommentDescription (String comment, String userkey, String username, int useriid) { this.comment = comment; this.userkey = userkey; this.username = username; this.date = (new GregorianCalendar()).getTime(); } private static void validate (String comment) throws ServiceException { //ContentException._COMMENT_<...> return; } private static int update_sequence //incremental comment id (DBCollection messagesCollection, int mid) throws ServiceException { int iter, seq = 0; do { BasicDBObject query = new BasicDBObject(); query.append("mid", mid); BasicDBObject update = new BasicDBObject(); BasicDBObject _update = new BasicDBObject(); _update.append("ccnt", 1); update.put("$inc", _update); try { DBObject res = messagesCollection.findAndModify( query, null, null, false, update, true, false); seq = (Integer) res.get("ccnt"); //seq = _seq.intValue(); } catch (ClassCastException ce) { throw new ContentException(ContentException._CONTENT_NOT_CASTING); } catch (MongoException me) { throw new ServiceException(me); } catch (NullPointerException npe) { throw new ContentException(ContentException._NO_COUNTERS); } //resolve duplicates (concur) BasicDBObject dup = new BasicDBObject(); dup.append("mid", mid); dup.append("comments.id", seq); DBCursor c = messagesCollection.find(dup); iter = c.count(); } while (iter > 0); return seq; } public int insertIn(DBCollection messagesCollection, int mid) throws ServiceException { validate(comment); int cid = update_sequence(messagesCollection, mid); /* * document (commentDocument) * { id, comment, date, user : { iid, sid, name } } */ BasicDBObject commentDocument = new BasicDBObject(); BasicDBObject user = new BasicDBObject(); commentDocument.append("id", cid); commentDocument.append("date", date); commentDocument.append("comment", comment); user.append("iid", useriid); user.append("sid", userkey); user.append("name", username); commentDocument.append("user", user); //query BasicDBObject update = new BasicDBObject(); BasicDBObject _update = new BasicDBObject(); BasicDBObject query = new BasicDBObject(); _update.put("comments", commentDocument); update.put("$push", _update); query.put("mid", mid); try { messagesCollection.update(query, update); return cid; } catch (MongoException me) { throw new ServiceException(me); } } public Date getDate() { return date; } }
4,055
0.537361
0.536621
116
33.956898
19.582888
80
false
false
0
0
0
0
0
0
0.818965
false
false
2
a3edaa88443d3c5ccd05ca1b0fb65a44eafd0228
22,505,628,689,062
8cb0aac92ca023d0ac1c795d02cf7d5734d33a71
/redisson-playground/src/test/java/com/young/redisson/test/Lec07MapCacheTest.java
eec7f2fc04917969a1839a62c0af36ff435eb17f
[]
no_license
Youngwook-Jeon/redis-with-spring-webflux
https://github.com/Youngwook-Jeon/redis-with-spring-webflux
cc3effa6b9eb24fff514dbdad42d28efb3880a69
736d2573283a634589b400fa2a587bce61c89777
refs/heads/main
2023-07-10T05:31:33.392000
2021-08-17T12:37:17
2021-08-17T12:37:17
387,826,308
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.young.redisson.test; import com.young.redisson.test.dto.Student; import org.junit.jupiter.api.Test; import org.redisson.api.RMapCacheReactive; import org.redisson.api.RMapReactive; import org.redisson.codec.TypedJsonJacksonCodec; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.util.List; import java.util.concurrent.TimeUnit; public class Lec07MapCacheTest extends BaseTest { @Test public void mapCacheTest() { TypedJsonJacksonCodec codec = new TypedJsonJacksonCodec(Integer.class, Student.class); RMapCacheReactive<Integer, Student> mapCache = this.client.getMapCache("users:cache", codec); Student student1 = new Student("sam", 20, "Incheon", List.of(1, 2, 3)); Student student2 = new Student("young", 30, "miami", List.of(10, 20, 30)); Mono<Student> st1 = mapCache.put(1, student1, 5L, TimeUnit.SECONDS); Mono<Student> st2 = mapCache.put(2, student2, 10L, TimeUnit.SECONDS); StepVerifier.create(st1.then(st2).then()) .verifyComplete(); sleep(3000); mapCache.get(1).doOnNext(System.out::println).subscribe(); mapCache.get(2).doOnNext(System.out::println).subscribe(); sleep(3000); mapCache.get(1).doOnNext(System.out::println).subscribe(); mapCache.get(2).doOnNext(System.out::println).subscribe(); } }
UTF-8
Java
1,394
java
Lec07MapCacheTest.java
Java
[ { "context": " codec);\n\n Student student1 = new Student(\"sam\", 20, \"Incheon\", List.of(1, 2, 3));\n Stude", "end": 711, "score": 0.972285807132721, "start": 708, "tag": "NAME", "value": "sam" }, { "context": " Student student2 = new Student(\"young\", 30, \"mia...
null
[]
package com.young.redisson.test; import com.young.redisson.test.dto.Student; import org.junit.jupiter.api.Test; import org.redisson.api.RMapCacheReactive; import org.redisson.api.RMapReactive; import org.redisson.codec.TypedJsonJacksonCodec; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.util.List; import java.util.concurrent.TimeUnit; public class Lec07MapCacheTest extends BaseTest { @Test public void mapCacheTest() { TypedJsonJacksonCodec codec = new TypedJsonJacksonCodec(Integer.class, Student.class); RMapCacheReactive<Integer, Student> mapCache = this.client.getMapCache("users:cache", codec); Student student1 = new Student("sam", 20, "Incheon", List.of(1, 2, 3)); Student student2 = new Student("young", 30, "miami", List.of(10, 20, 30)); Mono<Student> st1 = mapCache.put(1, student1, 5L, TimeUnit.SECONDS); Mono<Student> st2 = mapCache.put(2, student2, 10L, TimeUnit.SECONDS); StepVerifier.create(st1.then(st2).then()) .verifyComplete(); sleep(3000); mapCache.get(1).doOnNext(System.out::println).subscribe(); mapCache.get(2).doOnNext(System.out::println).subscribe(); sleep(3000); mapCache.get(1).doOnNext(System.out::println).subscribe(); mapCache.get(2).doOnNext(System.out::println).subscribe(); } }
1,394
0.697274
0.66858
39
34.743591
30.202494
101
false
false
0
0
0
0
0
0
1.076923
false
false
2
88db716275efd0772c71380cb3c635d1efefbf17
17,824,114,330,681
07593813271271dd226b127eb6abec07cb4862f5
/Circulemos2/CarteraEJB/src/main/java/co/com/datatools/c2/negocio/helpers/cartera/ActividadCarteraHelper.java
ca2017941a1fc8e05f00be5d49619a1bcfb453e3
[]
no_license
Divier/proyectojee
https://github.com/Divier/proyectojee
6f28cde44e7d721c86bfa6892b016a90169c65bc
f30892222fa9949dae2d9fc74a750e207d962736
refs/heads/master
2021-04-30T16:58:17.051000
2017-02-09T15:39:54
2017-02-09T15:39:54
80,161,866
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package co.com.datatools.c2.negocio.helpers.cartera; import java.util.ArrayList; import java.util.List; import co.com.datatools.c2.dto.cartera.ActividadCarteraDTO; import co.com.datatools.c2.entidades.ActividadCartera; /** * @author Generated * @version 3.0 - Wed Oct 21 09:26:15 COT 2015 */ public class ActividadCarteraHelper { // --- to DTO public static ActividadCarteraDTO toLevel0DTO(ActividadCartera entidad) { ActividadCarteraDTO dto = new ActividadCarteraDTO(); dto.setCodigo(entidad.getCodigo()); dto.setDescripcion(entidad.getDescripcion()); dto.setEstado(entidad.getEstado()); dto.setNombre(entidad.getNombre()); dto.setSigla(entidad.getSigla()); return dto; } public static ActividadCarteraDTO toLevel1DTO(ActividadCartera entidad) { ActividadCarteraDTO dto = toLevel0DTO(entidad); return dto; } public static List<ActividadCarteraDTO> toListLevel0DTO(List<ActividadCartera> listEntidad) { List<ActividadCarteraDTO> listDto = new ArrayList<ActividadCarteraDTO>(); for (ActividadCartera entidad : listEntidad) { listDto.add(toLevel0DTO(entidad)); } return listDto; } public static List<ActividadCarteraDTO> toListLevel1DTO(List<ActividadCartera> listEntidad) { List<ActividadCarteraDTO> listDto = new ArrayList<ActividadCarteraDTO>(); for (ActividadCartera entidad : listEntidad) { listDto.add(toLevel1DTO(entidad)); } return listDto; } // --- fin to DTO // --- to Entidad public static ActividadCartera toLevel0Entity(ActividadCarteraDTO dto, ActividadCartera entidad) { if (null == entidad) { entidad = new ActividadCartera(); } entidad.setCodigo(dto.getCodigo()); entidad.setDescripcion(dto.getDescripcion()); entidad.setEstado(dto.getEstado()); entidad.setNombre(dto.getNombre()); entidad.setSigla(dto.getSigla()); return entidad; } public static ActividadCartera toLevel1Entity(ActividadCarteraDTO dto, ActividadCartera entidad) { entidad = toLevel0Entity(dto, entidad); return entidad; } public static List<ActividadCartera> toListLevel0Entity(List<ActividadCarteraDTO> listDto) { List<ActividadCartera> listEntidad = new ArrayList<ActividadCartera>(); for (ActividadCarteraDTO dto : listDto) { listEntidad.add(toLevel0Entity(dto, null)); } return listEntidad; } public static List<ActividadCartera> toListLevel1Entity(List<ActividadCarteraDTO> listDto) { List<ActividadCartera> listEntidad = new ArrayList<ActividadCartera>(); for (ActividadCarteraDTO dto : listDto) { listEntidad.add(toLevel1Entity(dto, null)); } return listEntidad; } // --- fin to Entidad }
UTF-8
Java
2,917
java
ActividadCarteraHelper.java
Java
[ { "context": "ols.c2.entidades.ActividadCartera;\n\n/**\n * @author Generated\n * @version 3.0 - Wed Oct 21 09:26:15 COT 2015\n *", "end": 246, "score": 0.8791276216506958, "start": 237, "tag": "USERNAME", "value": "Generated" } ]
null
[]
package co.com.datatools.c2.negocio.helpers.cartera; import java.util.ArrayList; import java.util.List; import co.com.datatools.c2.dto.cartera.ActividadCarteraDTO; import co.com.datatools.c2.entidades.ActividadCartera; /** * @author Generated * @version 3.0 - Wed Oct 21 09:26:15 COT 2015 */ public class ActividadCarteraHelper { // --- to DTO public static ActividadCarteraDTO toLevel0DTO(ActividadCartera entidad) { ActividadCarteraDTO dto = new ActividadCarteraDTO(); dto.setCodigo(entidad.getCodigo()); dto.setDescripcion(entidad.getDescripcion()); dto.setEstado(entidad.getEstado()); dto.setNombre(entidad.getNombre()); dto.setSigla(entidad.getSigla()); return dto; } public static ActividadCarteraDTO toLevel1DTO(ActividadCartera entidad) { ActividadCarteraDTO dto = toLevel0DTO(entidad); return dto; } public static List<ActividadCarteraDTO> toListLevel0DTO(List<ActividadCartera> listEntidad) { List<ActividadCarteraDTO> listDto = new ArrayList<ActividadCarteraDTO>(); for (ActividadCartera entidad : listEntidad) { listDto.add(toLevel0DTO(entidad)); } return listDto; } public static List<ActividadCarteraDTO> toListLevel1DTO(List<ActividadCartera> listEntidad) { List<ActividadCarteraDTO> listDto = new ArrayList<ActividadCarteraDTO>(); for (ActividadCartera entidad : listEntidad) { listDto.add(toLevel1DTO(entidad)); } return listDto; } // --- fin to DTO // --- to Entidad public static ActividadCartera toLevel0Entity(ActividadCarteraDTO dto, ActividadCartera entidad) { if (null == entidad) { entidad = new ActividadCartera(); } entidad.setCodigo(dto.getCodigo()); entidad.setDescripcion(dto.getDescripcion()); entidad.setEstado(dto.getEstado()); entidad.setNombre(dto.getNombre()); entidad.setSigla(dto.getSigla()); return entidad; } public static ActividadCartera toLevel1Entity(ActividadCarteraDTO dto, ActividadCartera entidad) { entidad = toLevel0Entity(dto, entidad); return entidad; } public static List<ActividadCartera> toListLevel0Entity(List<ActividadCarteraDTO> listDto) { List<ActividadCartera> listEntidad = new ArrayList<ActividadCartera>(); for (ActividadCarteraDTO dto : listDto) { listEntidad.add(toLevel0Entity(dto, null)); } return listEntidad; } public static List<ActividadCartera> toListLevel1Entity(List<ActividadCarteraDTO> listDto) { List<ActividadCartera> listEntidad = new ArrayList<ActividadCartera>(); for (ActividadCarteraDTO dto : listDto) { listEntidad.add(toLevel1Entity(dto, null)); } return listEntidad; } // --- fin to Entidad }
2,917
0.678437
0.667809
85
33.317646
29.670429
102
false
false
0
0
0
0
0
0
0.470588
false
false
2
88d7578942523a9bed00e864ed68967a36a496d7
4,269,197,531,906
3eda4c514782445bccd7dcaa857127a267bf62b8
/DesignPattern/src/desginpattern/facade/HomeTheaterFacade.java
d42cee16b5571be12e707cca427a12cae57c8817
[]
no_license
raven-books-source-codes/DesginPatternNotes
https://github.com/raven-books-source-codes/DesginPatternNotes
e04a23ac9f8ab8d6d2d41a0a49631567bcce8fc3
588927a725dd448b53cf83063bf25e066bcdcfc0
refs/heads/master
2021-05-18T06:47:31.966000
2020-04-17T07:50:29
2020-04-17T07:50:29
251,164,936
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package desginpattern.facade; /** * @author Raven * @version 1.0 * @date 2020/4/4 19:55 */ public class HomeTheaterFacade { private DVDPlayer dvdPlayer; private Popcorn popcorn; private Projector projector; private Screen screen; private Stereo stereo; private TheaterLights theaterLights; public HomeTheaterFacade() { dvdPlayer = new DVDPlayer(); popcorn = new Popcorn(); projector = new Projector(); screen = new Screen(); stereo = new Stereo(); theaterLights = new TheaterLights(); } public void ready(){ dvdPlayer.on(); popcorn.on(); projector.on(); screen.down(); stereo.on(); theaterLights.off(); } public void play(){ dvdPlayer.play(); } public void pause(){ dvdPlayer.pause(); } public void end(){ dvdPlayer.off(); popcorn.off(); screen.up(); stereo.off(); theaterLights.off(); } }
UTF-8
Java
1,017
java
HomeTheaterFacade.java
Java
[ { "context": "package desginpattern.facade;\n\n/**\n * @author Raven\n * @version 1.0\n * @date 2020/4/4 19:55\n */\npubli", "end": 51, "score": 0.9924522638320923, "start": 46, "tag": "NAME", "value": "Raven" } ]
null
[]
package desginpattern.facade; /** * @author Raven * @version 1.0 * @date 2020/4/4 19:55 */ public class HomeTheaterFacade { private DVDPlayer dvdPlayer; private Popcorn popcorn; private Projector projector; private Screen screen; private Stereo stereo; private TheaterLights theaterLights; public HomeTheaterFacade() { dvdPlayer = new DVDPlayer(); popcorn = new Popcorn(); projector = new Projector(); screen = new Screen(); stereo = new Stereo(); theaterLights = new TheaterLights(); } public void ready(){ dvdPlayer.on(); popcorn.on(); projector.on(); screen.down(); stereo.on(); theaterLights.off(); } public void play(){ dvdPlayer.play(); } public void pause(){ dvdPlayer.pause(); } public void end(){ dvdPlayer.off(); popcorn.off(); screen.up(); stereo.off(); theaterLights.off(); } }
1,017
0.565388
0.553589
50
19.34
12.486168
44
false
false
0
0
0
0
0
0
0.52
false
false
2
b1f3a402c7bc25a041af834dec80478fa94c1dc2
35,450,660,086,725
55c11143ba71627514755e171f64a3c77ff728bd
/src/main/java/com/hugo/service/ITaskService.java
3659a606a3905b13b6bb41ff0e47072ad9bb60ea
[]
no_license
cold11/hugo
https://github.com/cold11/hugo
c05c225d5a8e28f7248087e0eef297df7e409df6
98a648e26b385273e365019ba78f556e33641a44
refs/heads/master
2023-08-31T14:16:43.597000
2023-08-28T01:53:34
2023-08-28T01:53:34
71,546,848
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hugo.service; import com.hugo.common.page.Pager; import com.hugo.entity.TBTask; import com.hugo.model.vo.TaskVO; import com.hugo.service.base.IBaseService; /** * Created by ohj on 2016/10/26. */ public interface ITaskService extends IBaseService { Pager getTaskPager(Pager<TaskVO> pager); void saveEditorHistory(TaskVO taskVO); TBTask findByBookName(String bookname); }
UTF-8
Java
400
java
ITaskService.java
Java
[ { "context": "hugo.service.base.IBaseService;\n\n/**\n * Created by ohj on 2016/10/26.\n */\npublic interface ITaskService ", "end": 191, "score": 0.9994805455207825, "start": 188, "tag": "USERNAME", "value": "ohj" } ]
null
[]
package com.hugo.service; import com.hugo.common.page.Pager; import com.hugo.entity.TBTask; import com.hugo.model.vo.TaskVO; import com.hugo.service.base.IBaseService; /** * Created by ohj on 2016/10/26. */ public interface ITaskService extends IBaseService { Pager getTaskPager(Pager<TaskVO> pager); void saveEditorHistory(TaskVO taskVO); TBTask findByBookName(String bookname); }
400
0.76
0.74
17
22.529411
18.998816
52
false
false
0
0
0
0
0
0
0.470588
false
false
2
6b4121b3d55bfdebd40735725c5d8ab43ea26a4d
19,576,460,970,451
ce9f200ad1ce8f9853b1ff398c8e55e8f90b4256
/Artskjid.java
e0e148aa8af01959b37b310d1a6f8449547423dd
[]
no_license
HannahZhu2001/Competitive-Programming
https://github.com/HannahZhu2001/Competitive-Programming
548497ce86b71fbc0d3640ed92819f5ca86ac5c7
d3a3807dfc51de4f3de9a3206f56fa5a58566717
refs/heads/master
2020-12-14T20:27:27.410000
2020-01-19T07:36:23
2020-01-19T07:36:23
234,858,212
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.*; import java.util.*; public class Artskjid { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String [] temp = in.readLine().split(" "); int nodes = Integer.parseInt(temp[0]); int roads = Integer.parseInt(temp[1]); int [] distance = new int [nodes]; Arrays.fill (distance, -1); List<Edge> [] list = new ArrayList[nodes]; for(int x=0; x< nodes; x++) { list[x] = new ArrayList<Edge>(); } for (int x =0; x < roads; x++) { String [] temp1 = in.readLine().split(" "); int start = Integer.parseInt(temp1[0]); int fin = Integer.parseInt(temp1[1]); int dist = Integer.parseInt(temp1[2]); list[start].add(new Edge(fin, dist, 0)); //list[fin].add(new Edge(start, dist)); } Queue<Edge> queue = new LinkedList<Edge>(); // Queue<Integer> visited = new LinkedList<Integer>(); queue.add(new Edge(0, 0, 1)); int [][] furthest = new int [1<<18][nodes]; furthest[1][0] = -1; // visited.add(1); int max=0; while(queue.isEmpty() == false) { Edge current = queue.poll(); //current.visited = current.visited|1<<current.node; //visit = visit|1<<current.node; if (furthest[current.visited][current.node]<=current.distance ) { //furthest[visit][current.node] = Math.max(furthest[visit][current.node], current.distance); //current.distance = furthest[visit][current.node]; if (current.node == nodes-1&& current.distance > max) max = current.distance; for (Edge adj: list[current.node]) { //System.out.println(visit); //System.out.println(furthest[visit]); if(((1<<adj.node)&current.visited) ==0 && furthest[(1<<adj.node)|current.visited][adj.node] < current.distance+adj.distance) { //System.out.println("+"); furthest[(1<<adj.node)|current.visited][adj.node] = current.distance+adj.distance; queue.add(new Edge(adj.node,current.distance+adj.distance, current.visited|(1<<adj.node))); //visited.add(current.visited|(1<<adj.node)); } } } } System.out.print(max); } } class Edge implements Comparable<Edge> { public int node; public int distance; public int visited; public Edge (int n, int d, int v) { node = n; distance = d; visited = v; } public int compareTo (Edge other) { return distance - other.distance; } }
UTF-8
Java
2,946
java
Artskjid.java
Java
[]
null
[]
import java.io.*; import java.util.*; public class Artskjid { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String [] temp = in.readLine().split(" "); int nodes = Integer.parseInt(temp[0]); int roads = Integer.parseInt(temp[1]); int [] distance = new int [nodes]; Arrays.fill (distance, -1); List<Edge> [] list = new ArrayList[nodes]; for(int x=0; x< nodes; x++) { list[x] = new ArrayList<Edge>(); } for (int x =0; x < roads; x++) { String [] temp1 = in.readLine().split(" "); int start = Integer.parseInt(temp1[0]); int fin = Integer.parseInt(temp1[1]); int dist = Integer.parseInt(temp1[2]); list[start].add(new Edge(fin, dist, 0)); //list[fin].add(new Edge(start, dist)); } Queue<Edge> queue = new LinkedList<Edge>(); // Queue<Integer> visited = new LinkedList<Integer>(); queue.add(new Edge(0, 0, 1)); int [][] furthest = new int [1<<18][nodes]; furthest[1][0] = -1; // visited.add(1); int max=0; while(queue.isEmpty() == false) { Edge current = queue.poll(); //current.visited = current.visited|1<<current.node; //visit = visit|1<<current.node; if (furthest[current.visited][current.node]<=current.distance ) { //furthest[visit][current.node] = Math.max(furthest[visit][current.node], current.distance); //current.distance = furthest[visit][current.node]; if (current.node == nodes-1&& current.distance > max) max = current.distance; for (Edge adj: list[current.node]) { //System.out.println(visit); //System.out.println(furthest[visit]); if(((1<<adj.node)&current.visited) ==0 && furthest[(1<<adj.node)|current.visited][adj.node] < current.distance+adj.distance) { //System.out.println("+"); furthest[(1<<adj.node)|current.visited][adj.node] = current.distance+adj.distance; queue.add(new Edge(adj.node,current.distance+adj.distance, current.visited|(1<<adj.node))); //visited.add(current.visited|(1<<adj.node)); } } } } System.out.print(max); } } class Edge implements Comparable<Edge> { public int node; public int distance; public int visited; public Edge (int n, int d, int v) { node = n; distance = d; visited = v; } public int compareTo (Edge other) { return distance - other.distance; } }
2,946
0.514596
0.503394
77
36.285713
27.076542
140
false
false
0
0
0
0
0
0
0.831169
false
false
2
923564e4308eaffdc1d0c453dbf3dbb628e9c9ee
19,576,460,971,193
207e99f76adb34a55be379cc4a164b9b3dd54a6c
/src/main/java/Main.java
d0bafbdfcbc4db07e60115450b0133074a217d65
[]
no_license
Kage37/Riemann
https://github.com/Kage37/Riemann
c5d0f8c6a650d911314cebde55ba9daed731075d
2751705e1eddd6fa32dd4ee0812a177ce11dd1d7
refs/heads/master
2021-05-06T12:22:40.985000
2018-03-12T00:46:01
2018-03-12T00:46:01
113,112,121
0
0
null
false
2018-03-12T00:46:02
2017-12-05T00:44:37
2017-12-05T01:46:31
2018-03-12T00:46:02
396
0
0
0
Java
false
null
import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @EnableAutoConfiguration @ComponentScan(basePackages = {"web", "riemann"}) public class Main { public static void main(String[] args) throws Exception { SpringApplication.run(Main.class, args); } }
UTF-8
Java
383
java
Main.java
Java
[]
null
[]
import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @EnableAutoConfiguration @ComponentScan(basePackages = {"web", "riemann"}) public class Main { public static void main(String[] args) throws Exception { SpringApplication.run(Main.class, args); } }
383
0.770235
0.770235
14
26.357143
22.121763
60
false
false
0
0
0
0
0
0
0.571429
false
false
2
3d5c4e9d8fa2d026637d37b08e12d2534e248599
19,576,460,969,572
318ba16c9cae173d7737019785d0658dbcba51af
/app/src/main/java/com/copywrite/com/android_agent/AndroidAgent.java
d62de66e23b7a855f94e15f4823b514fe08f1ee8
[]
no_license
copywrite/AccessibilityService
https://github.com/copywrite/AccessibilityService
54b55efbb8f518bb50490a088927ff2ea201b887
379ddc1ab149a07204fd205e80c5f2aa7dab6db8
refs/heads/master
2020-12-30T14:44:19.674000
2017-05-12T09:50:02
2017-05-12T09:50:02
91,076,590
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.copywrite.com.android_agent; import android.app.Application; /** * Created by di on 2017/5/8. */ public class AndroidAgent extends Application {}
UTF-8
Java
163
java
AndroidAgent.java
Java
[]
null
[]
package com.copywrite.com.android_agent; import android.app.Application; /** * Created by di on 2017/5/8. */ public class AndroidAgent extends Application {}
163
0.742331
0.705521
9
17.111111
18.525925
48
false
false
0
0
0
0
0
0
0.222222
false
false
2
d1397c6b4a75348beffcb4626e2b1304a9168f0f
21,440,476,797,654
7b77dab731f1ac59feb2a17a7cd2a01ccfab3993
/editeurV3/src/caretaker/EnregistreurV2Impl.java
a33381935e517f799c3b69ebb7065f69ddd1f0ee
[]
no_license
frochard/editeurV3
https://github.com/frochard/editeurV3
c724c153665ec04e2391f753af94595edb92764c
5bad308653700d2cb573955fb3f2414a54d5e4a6
refs/heads/master
2021-01-10T11:11:50.670000
2015-12-03T19:35:10
2015-12-03T19:35:10
47,195,644
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package caretaker; import java.util.ArrayList; import commandV2.CommandEnregistrableV2; import memento.*; /** *Enregistreur de la version 2 *L’enregistreur a le rôle de Caretaker dans le design pattern Memento. *@author Sanaa Mairouch / Frédéric Rochard *@version V2 - 30/11/2015 */ public class EnregistreurV2Impl implements EnregistreurV2 { private ArrayList<Memento> listeCommandes = new ArrayList<Memento>(); /** * Renvoie la liste des mementos du Caretaker * @return listeCommandes liste des mementos du Caretaker */ public ArrayList<Memento> getListeCommandes() { return listeCommandes; } /** * méthode démarrant l'enregistrement d'une suite de commandes */ public void demarrer(){ //Suppression de tous les mementos précédent enregistrés this.listeCommandes.clear(); } /** * méthode arrêtant l'enregistrement d'une suite de commandes */ public void arreter(){ } /** * méthode rejouant la suite de commandes enregistrée */ public void rejouer(){ //Variable contnant la classe du memento stocké String mementoClasse; //Récupération de la commande dans la liste de memento for (Memento savedCmd : listeCommandes){ //Récupération du type de commande mementoClasse=savedCmd.getClass().getName(); switch (mementoClasse){ case "memento.MementoCopier": /*Appel de la commande Copier*/ MementoCopier mementoCopier=(MementoCopier) savedCmd; mementoCopier.getSavedCommand().restaurerDepuisMemento(mementoCopier); break; case "memento.MementoCouper": /*Appel de la commande Couper*/ MementoCouper mementoCouper=(MementoCouper) savedCmd; mementoCouper.getSavedCommand().restaurerDepuisMemento(mementoCouper); break; case "memento.MementoColler": /*Appel de la commande Coller*/ MementoColler mementoColler=(MementoColler) savedCmd; mementoColler.getSavedCommand().restaurerDepuisMemento(mementoColler); break; case "memento.MementoSaisir": /*Appel de la commande Saisir*/ MementoSaisir mementoSaisir=(MementoSaisir) savedCmd; mementoSaisir.getSavedCommand().restaurerDepuisMemento(mementoSaisir); break; case "memento.MementoSelectionner": /*Appel de la commande Selectionner*/ MementoSelectionner mementoSelectionner=(MementoSelectionner) savedCmd; mementoSelectionner.getSavedCommand().restaurerDepuisMemento(mementoSelectionner); break; default: /*Affichage d'un message indiquant une commande inconnue*/ } } } /** * Ajoute un memento à la liste des mementos du caretaker * @param m memento à ajouter */ public void addMemento(Memento m) { listeCommandes.add(m); } /** * Retourne un memento du Caretaker * @param index index du memento dans la liste de l'enregistreur * @return memento de la liste de mementos du caretaker correspondant à l'index placé en paramètre */ public Memento getMemento(int index){ return listeCommandes.get(index); } /** * enregistre la commande dans un memento * @param cmdASauver commande à sauvegarder dans le memento */ @Override public void enregistrer(CommandEnregistrableV2 cmdASauver) { this.addMemento(cmdASauver.sauverDansMemento()); } }
WINDOWS-1252
Java
3,252
java
EnregistreurV2Impl.java
Java
[ { "context": "retaker dans le design pattern Memento. \n *@author Sanaa Mairouch / Frédéric Rochard\n *@version V2 - 30/11/2015\n */", "end": 240, "score": 0.9998914003372192, "start": 226, "tag": "NAME", "value": "Sanaa Mairouch" }, { "context": "esign pattern Memento. \n *@author S...
null
[]
package caretaker; import java.util.ArrayList; import commandV2.CommandEnregistrableV2; import memento.*; /** *Enregistreur de la version 2 *L’enregistreur a le rôle de Caretaker dans le design pattern Memento. *@author <NAME> / <NAME> *@version V2 - 30/11/2015 */ public class EnregistreurV2Impl implements EnregistreurV2 { private ArrayList<Memento> listeCommandes = new ArrayList<Memento>(); /** * Renvoie la liste des mementos du Caretaker * @return listeCommandes liste des mementos du Caretaker */ public ArrayList<Memento> getListeCommandes() { return listeCommandes; } /** * méthode démarrant l'enregistrement d'une suite de commandes */ public void demarrer(){ //Suppression de tous les mementos précédent enregistrés this.listeCommandes.clear(); } /** * méthode arrêtant l'enregistrement d'une suite de commandes */ public void arreter(){ } /** * méthode rejouant la suite de commandes enregistrée */ public void rejouer(){ //Variable contnant la classe du memento stocké String mementoClasse; //Récupération de la commande dans la liste de memento for (Memento savedCmd : listeCommandes){ //Récupération du type de commande mementoClasse=savedCmd.getClass().getName(); switch (mementoClasse){ case "memento.MementoCopier": /*Appel de la commande Copier*/ MementoCopier mementoCopier=(MementoCopier) savedCmd; mementoCopier.getSavedCommand().restaurerDepuisMemento(mementoCopier); break; case "memento.MementoCouper": /*Appel de la commande Couper*/ MementoCouper mementoCouper=(MementoCouper) savedCmd; mementoCouper.getSavedCommand().restaurerDepuisMemento(mementoCouper); break; case "memento.MementoColler": /*Appel de la commande Coller*/ MementoColler mementoColler=(MementoColler) savedCmd; mementoColler.getSavedCommand().restaurerDepuisMemento(mementoColler); break; case "memento.MementoSaisir": /*Appel de la commande Saisir*/ MementoSaisir mementoSaisir=(MementoSaisir) savedCmd; mementoSaisir.getSavedCommand().restaurerDepuisMemento(mementoSaisir); break; case "memento.MementoSelectionner": /*Appel de la commande Selectionner*/ MementoSelectionner mementoSelectionner=(MementoSelectionner) savedCmd; mementoSelectionner.getSavedCommand().restaurerDepuisMemento(mementoSelectionner); break; default: /*Affichage d'un message indiquant une commande inconnue*/ } } } /** * Ajoute un memento à la liste des mementos du caretaker * @param m memento à ajouter */ public void addMemento(Memento m) { listeCommandes.add(m); } /** * Retourne un memento du Caretaker * @param index index du memento dans la liste de l'enregistreur * @return memento de la liste de mementos du caretaker correspondant à l'index placé en paramètre */ public Memento getMemento(int index){ return listeCommandes.get(index); } /** * enregistre la commande dans un memento * @param cmdASauver commande à sauvegarder dans le memento */ @Override public void enregistrer(CommandEnregistrableV2 cmdASauver) { this.addMemento(cmdASauver.sauverDansMemento()); } }
3,232
0.735668
0.731019
107
29.158878
25.202414
99
false
false
0
0
0
0
0
0
1.915888
false
false
2
d6c2d5fcdbe9abb3ee6260f76ad2facec5894494
13,297,218,813,491
74cb09179f819a1b5cf7df9ed539b293e8d29e95
/src/main/java/de/cas_ual_ty/visibilis/test/VCodePrintItem.java
f31c4088a136112e8977eb2bd6a8d83a90e581d8
[ "MIT" ]
permissive
CAS-ual-TY/Visibilis
https://github.com/CAS-ual-TY/Visibilis
ec20510b16ebb0a6799476a8dcc027b873b1af32
bf17c3484856ce72d0a627d13e27de1e91538fe7
refs/heads/master
2021-07-07T13:04:18.295000
2020-07-04T10:12:46
2020-07-04T10:12:46
199,338,614
2
1
MIT
false
2020-07-02T12:54:30
2019-07-28T21:24:03
2020-07-02T12:00:57
2020-07-02T12:54:29
31,737
1
1
0
Java
false
false
package de.cas_ual_ty.visibilis.test; import de.cas_ual_ty.visibilis.print.item.ClickablePrintItem; import net.minecraft.command.CommandSource; import net.minecraft.item.ItemStack; public class VCodePrintItem extends ClickablePrintItem { public VCodePrintItem(Properties properties) { super(properties); } @Override public boolean isEditable(ItemStack itemStack, CommandSource source) { return true; } }
UTF-8
Java
455
java
VCodePrintItem.java
Java
[]
null
[]
package de.cas_ual_ty.visibilis.test; import de.cas_ual_ty.visibilis.print.item.ClickablePrintItem; import net.minecraft.command.CommandSource; import net.minecraft.item.ItemStack; public class VCodePrintItem extends ClickablePrintItem { public VCodePrintItem(Properties properties) { super(properties); } @Override public boolean isEditable(ItemStack itemStack, CommandSource source) { return true; } }
455
0.734066
0.734066
19
22.947369
22.938072
72
false
false
0
0
0
0
0
0
0.368421
false
false
13
c45b83eb71e03ca81d03ed6e398ea2afb6b17cf1
5,806,795,829,592
32c1c3fc967b384be5d9e156ace2775ebc2c9547
/server2-sb2/src/main/java/com/spring/sleuth/demo/server2_sb2/config/kafka/ExecutorChannelBindingTargetFactory.java
97a9f9bf8dd9da48119c76b12ec9837c3bdd5191
[ "Apache-2.0" ]
permissive
rbaul/spring-sleuth-demo
https://github.com/rbaul/spring-sleuth-demo
a3e40a6e8ddf89a4f3b18f57119a235bb85a31d8
de8e7a370134666776a6e3a61ff008f917889f46
refs/heads/master
2020-11-27T12:59:08.896000
2020-01-17T13:18:09
2020-01-17T13:18:09
229,451,868
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.spring.sleuth.demo.server2_sb2.config.kafka; import org.springframework.cloud.stream.binding.AbstractBindingTargetFactory; import org.springframework.cloud.stream.binding.CompositeMessageChannelConfigurer; import org.springframework.context.annotation.Primary; import org.springframework.integration.channel.ExecutorChannel; import org.springframework.stereotype.Service; /** * Support ExecutorChannel */ @Primary @Service public class ExecutorChannelBindingTargetFactory extends AbstractBindingTargetFactory<ExecutorChannel> { private final CompositeMessageChannelConfigurer compositeMessageChannelConfigurer; public ExecutorChannelBindingTargetFactory(CompositeMessageChannelConfigurer compositeMessageChannelConfigurer) { super(ExecutorChannel.class); this.compositeMessageChannelConfigurer = compositeMessageChannelConfigurer; } @Override public ExecutorChannel createInput(String name) { ExecutorChannel executorChannel = new ExecutorChannel(Runnable::run); this.compositeMessageChannelConfigurer.configureInputChannel(executorChannel, name); return executorChannel; } @Override public ExecutorChannel createOutput(String name) { ExecutorChannel executorChannel = new ExecutorChannel(Runnable::run); this.compositeMessageChannelConfigurer.configureOutputChannel(executorChannel, name); return executorChannel; } }
UTF-8
Java
1,438
java
ExecutorChannelBindingTargetFactory.java
Java
[]
null
[]
package com.spring.sleuth.demo.server2_sb2.config.kafka; import org.springframework.cloud.stream.binding.AbstractBindingTargetFactory; import org.springframework.cloud.stream.binding.CompositeMessageChannelConfigurer; import org.springframework.context.annotation.Primary; import org.springframework.integration.channel.ExecutorChannel; import org.springframework.stereotype.Service; /** * Support ExecutorChannel */ @Primary @Service public class ExecutorChannelBindingTargetFactory extends AbstractBindingTargetFactory<ExecutorChannel> { private final CompositeMessageChannelConfigurer compositeMessageChannelConfigurer; public ExecutorChannelBindingTargetFactory(CompositeMessageChannelConfigurer compositeMessageChannelConfigurer) { super(ExecutorChannel.class); this.compositeMessageChannelConfigurer = compositeMessageChannelConfigurer; } @Override public ExecutorChannel createInput(String name) { ExecutorChannel executorChannel = new ExecutorChannel(Runnable::run); this.compositeMessageChannelConfigurer.configureInputChannel(executorChannel, name); return executorChannel; } @Override public ExecutorChannel createOutput(String name) { ExecutorChannel executorChannel = new ExecutorChannel(Runnable::run); this.compositeMessageChannelConfigurer.configureOutputChannel(executorChannel, name); return executorChannel; } }
1,438
0.810848
0.809458
36
38.972221
36.56234
117
false
false
0
0
0
0
0
0
0.472222
false
false
13
5da2cb959d833b7346c3056f49785bb325a8c960
506,806,148,702
04a6825a6aaef2b3217523f1527e837186f6eb48
/core/src/main/java/io/windmill/core/tasks/VoidTask1.java
4d19809ed9ab728ec1938b55f60a37a43ab91cd6
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
bestwpw/windmill
https://github.com/bestwpw/windmill
11c5693b81a0197415df245935c4fc620f564473
784bb266d6b54bdac90890bbb526b73e683e2b2b
refs/heads/master
2018-03-14T00:36:00.763000
2016-02-19T03:45:14
2016-02-19T04:21:01
52,240,032
10
2
null
true
2016-02-22T02:06:49
2016-02-22T02:06:49
2016-02-22T02:06:48
2016-02-21T07:50:37
169
0
0
0
null
null
null
package io.windmill.core.tasks; @FunctionalInterface public interface VoidTask1<I> { void compute(I input); }
UTF-8
Java
115
java
VoidTask1.java
Java
[]
null
[]
package io.windmill.core.tasks; @FunctionalInterface public interface VoidTask1<I> { void compute(I input); }
115
0.756522
0.747826
7
15.428572
13.167679
31
false
false
0
0
0
0
0
0
0.285714
false
false
13
db3951ed1c0dcd378811d1838958e82533b312b4
506,806,151,032
112376b0c120a3ece6b94f92a6fbfda4cda6ce97
/src/main/java/com/worksystem/exception/StudentRuntimeException.java
51d2f757fb249100255b0d420ddc5ad4061be74a
[]
no_license
wsw16886880/workSystem
https://github.com/wsw16886880/workSystem
2508b5e419cce65e376c94e0cd347c87c0b4fbd1
81c5c01eff5841891d53257b38f14311dbad81e3
refs/heads/master
2023-02-26T07:18:15.598000
2021-01-27T02:59:29
2021-01-27T02:59:29
333,287,770
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.worksystem.exception; /** * @author wsw16 */ public class StudentRuntimeException extends Exception { public StudentRuntimeException() { super(); } public StudentRuntimeException(String message, Throwable cause) { super(message, cause); } public StudentRuntimeException(String message) { super(message); } public StudentRuntimeException(Throwable cause) { super(cause); } }
UTF-8
Java
411
java
StudentRuntimeException.java
Java
[ { "context": "package com.worksystem.exception;\n\n/**\n * @author wsw16\n */\npublic class StudentRuntimeException extends ", "end": 55, "score": 0.9994658827781677, "start": 50, "tag": "USERNAME", "value": "wsw16" } ]
null
[]
package com.worksystem.exception; /** * @author wsw16 */ public class StudentRuntimeException extends Exception { public StudentRuntimeException() { super(); } public StudentRuntimeException(String message, Throwable cause) { super(message, cause); } public StudentRuntimeException(String message) { super(message); } public StudentRuntimeException(Throwable cause) { super(cause); } }
411
0.739659
0.734793
25
15.44
20.226873
66
false
false
0
0
0
0
0
0
0.92
false
false
13
56250884fd7b931d70b2ec2479bed7b7e39e2608
10,831,907,526,417
bcff6f5cef9523ff2571b40911d9c2072d70437c
/forumjava/src/main/java/forum/controller/ReplyController.java
bbc96a574bdfc5cb83217ddbba61f34199c48d14
[]
no_license
plamen33/Forum-Java
https://github.com/plamen33/Forum-Java
476e9d44b6c000d5c49a40905b3a4b0b854bc924
9e43d8cf84a259e4a478d8f65b0ab86b6de391ce
refs/heads/master
2021-01-20T13:12:22.630000
2017-05-06T13:12:32
2017-05-06T13:12:32
90,463,044
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package forum.controller; import forum.bindingModel.ReplyBindingModel; import forum.entity.Reply; import forum.entity.Topic; import forum.entity.User; import forum.repository.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.annotation.Transient; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; @Controller public class ReplyController { @Autowired private TopicRepository topicRepository; @Autowired private UserRepository userRepository; @Autowired private ReplyRepository replyRepository; @Autowired private CategoryRepository categoryRepository; @Autowired private ForumRepository forumRepository; @GetMapping("/reply/create/{id}") @PreAuthorize("isAuthenticated()") public String create(Model model, @PathVariable Integer id){ // public String create(@PathVariable Integer id, Model model){ Topic topic = this.topicRepository.findOne(id); UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User user = this.userRepository.findByEmail(principal.getUsername()); model.addAttribute("topic", topic); model.addAttribute("user", user); return "reply/create"; } @PostMapping("/reply/create/{id}") public String createProcess(ReplyBindingModel replyBindingModel, @PathVariable Integer id){ Topic topic = this.topicRepository.findOne(id); UserDetails principal = (UserDetails) SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); User user = this.userRepository.findByEmail(principal.getUsername()); LocalDateTime ldt = LocalDateTime.now(); Timestamp datePosted = Timestamp.valueOf(ldt); Timestamp dateUpdated = datePosted; Reply reply = new Reply( replyBindingModel.getMessage(), datePosted, dateUpdated, topic, user ); this.replyRepository.saveAndFlush(reply); return "redirect:/topic/"+id; } @GetMapping("/reply/edit/{id}") @PreAuthorize("isAuthenticated()") public String edit(@PathVariable Integer id, Model model){ if(!this.replyRepository.exists(id)){ return "redirect:/"; } System.out.println(id); Reply reply = this.replyRepository.findOne(id); Topic topic = this.topicRepository.findOne(reply.getTopic().getId()); if(!this.isAuthorOrAdmin(reply)){ // only admin or author can edit certain replies return "redirect:/topic/"+id; } UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User user = this.userRepository.findByEmail(principal.getUsername()); model.addAttribute("user", user); model.addAttribute("reply", reply); model.addAttribute("topic", topic); return "reply/edit"; } @PostMapping("/reply/edit/{id}") @PreAuthorize("isAuthenticated()") public String editProcess(@PathVariable Integer id, ReplyBindingModel replyBindingModel){ if(!this.replyRepository.exists(id)){ return "redirect:/"; } Reply reply = this.replyRepository.findOne(id); Integer topicId = reply.getTopic().getId(); if(!this.isAuthorOrAdmin(reply)){ // only admin or author can edit certain replies return "redirect:/topic/"+id; } LocalDateTime ldt = LocalDateTime.now(); Timestamp dateUpdated = Timestamp.valueOf(ldt); reply.setMessage(replyBindingModel.getMessage()); reply.setDateUpdated(dateUpdated); this.replyRepository.saveAndFlush(reply); return "redirect:/topic/"+topicId; } @GetMapping("/reply/delete/{id}") @PreAuthorize("isAuthenticated()") public String delete(@PathVariable Integer id, Model model){ if(!this.replyRepository.exists(id)){ return "redirect:/"; } Reply reply = this.replyRepository.findOne(id); Topic topic = this.topicRepository.findOne(reply.getTopic().getId()); if(!this.isAuthorOrAdmin(reply)){ // only admin or author can edit certain replies return "redirect:/topic/"+id; } UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User user = this.userRepository.findByEmail(principal.getUsername()); model.addAttribute("user", user); model.addAttribute("reply", reply); model.addAttribute("topic", topic); return "reply/delete"; } @PostMapping("/reply/delete/{id}") @PreAuthorize("isAuthenticated()") public String deleteProcess(@PathVariable Integer id, ReplyBindingModel replyBindingModel){ if(!this.replyRepository.exists(id)){ return "redirect:/"; } Reply reply = this.replyRepository.findOne(id); Integer topicId = reply.getTopic().getId(); if(!this.isAuthorOrAdmin(reply)){ // only admin or author can edit certain replies return "redirect:/topic/"+id; } this.replyRepository.delete(reply); return "redirect:/topic/"+topicId; } @Transient public boolean isAuthorOrAdmin(Reply reply) { UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User userEntity = this.userRepository.findByEmail(user.getUsername()); return userEntity.isAdmin() || userEntity.isReplyAuthor(reply); } }
UTF-8
Java
6,266
java
ReplyController.java
Java
[]
null
[]
package forum.controller; import forum.bindingModel.ReplyBindingModel; import forum.entity.Reply; import forum.entity.Topic; import forum.entity.User; import forum.repository.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.annotation.Transient; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; @Controller public class ReplyController { @Autowired private TopicRepository topicRepository; @Autowired private UserRepository userRepository; @Autowired private ReplyRepository replyRepository; @Autowired private CategoryRepository categoryRepository; @Autowired private ForumRepository forumRepository; @GetMapping("/reply/create/{id}") @PreAuthorize("isAuthenticated()") public String create(Model model, @PathVariable Integer id){ // public String create(@PathVariable Integer id, Model model){ Topic topic = this.topicRepository.findOne(id); UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User user = this.userRepository.findByEmail(principal.getUsername()); model.addAttribute("topic", topic); model.addAttribute("user", user); return "reply/create"; } @PostMapping("/reply/create/{id}") public String createProcess(ReplyBindingModel replyBindingModel, @PathVariable Integer id){ Topic topic = this.topicRepository.findOne(id); UserDetails principal = (UserDetails) SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); User user = this.userRepository.findByEmail(principal.getUsername()); LocalDateTime ldt = LocalDateTime.now(); Timestamp datePosted = Timestamp.valueOf(ldt); Timestamp dateUpdated = datePosted; Reply reply = new Reply( replyBindingModel.getMessage(), datePosted, dateUpdated, topic, user ); this.replyRepository.saveAndFlush(reply); return "redirect:/topic/"+id; } @GetMapping("/reply/edit/{id}") @PreAuthorize("isAuthenticated()") public String edit(@PathVariable Integer id, Model model){ if(!this.replyRepository.exists(id)){ return "redirect:/"; } System.out.println(id); Reply reply = this.replyRepository.findOne(id); Topic topic = this.topicRepository.findOne(reply.getTopic().getId()); if(!this.isAuthorOrAdmin(reply)){ // only admin or author can edit certain replies return "redirect:/topic/"+id; } UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User user = this.userRepository.findByEmail(principal.getUsername()); model.addAttribute("user", user); model.addAttribute("reply", reply); model.addAttribute("topic", topic); return "reply/edit"; } @PostMapping("/reply/edit/{id}") @PreAuthorize("isAuthenticated()") public String editProcess(@PathVariable Integer id, ReplyBindingModel replyBindingModel){ if(!this.replyRepository.exists(id)){ return "redirect:/"; } Reply reply = this.replyRepository.findOne(id); Integer topicId = reply.getTopic().getId(); if(!this.isAuthorOrAdmin(reply)){ // only admin or author can edit certain replies return "redirect:/topic/"+id; } LocalDateTime ldt = LocalDateTime.now(); Timestamp dateUpdated = Timestamp.valueOf(ldt); reply.setMessage(replyBindingModel.getMessage()); reply.setDateUpdated(dateUpdated); this.replyRepository.saveAndFlush(reply); return "redirect:/topic/"+topicId; } @GetMapping("/reply/delete/{id}") @PreAuthorize("isAuthenticated()") public String delete(@PathVariable Integer id, Model model){ if(!this.replyRepository.exists(id)){ return "redirect:/"; } Reply reply = this.replyRepository.findOne(id); Topic topic = this.topicRepository.findOne(reply.getTopic().getId()); if(!this.isAuthorOrAdmin(reply)){ // only admin or author can edit certain replies return "redirect:/topic/"+id; } UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User user = this.userRepository.findByEmail(principal.getUsername()); model.addAttribute("user", user); model.addAttribute("reply", reply); model.addAttribute("topic", topic); return "reply/delete"; } @PostMapping("/reply/delete/{id}") @PreAuthorize("isAuthenticated()") public String deleteProcess(@PathVariable Integer id, ReplyBindingModel replyBindingModel){ if(!this.replyRepository.exists(id)){ return "redirect:/"; } Reply reply = this.replyRepository.findOne(id); Integer topicId = reply.getTopic().getId(); if(!this.isAuthorOrAdmin(reply)){ // only admin or author can edit certain replies return "redirect:/topic/"+id; } this.replyRepository.delete(reply); return "redirect:/topic/"+topicId; } @Transient public boolean isAuthorOrAdmin(Reply reply) { UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User userEntity = this.userRepository.findByEmail(user.getUsername()); return userEntity.isAdmin() || userEntity.isReplyAuthor(reply); } }
6,266
0.685286
0.685286
172
35.430233
29.352327
131
false
false
0
0
0
0
0
0
0.593023
false
false
13
4a79c80d5f888784a59ad4a166fd199af4a3bf90
13,228,499,310,810
fbc670ca721c3a0f20aecec54809151348f59ce9
/Research/src/drafts/TriggerScriptIdea.java
b99fdec7d50062740ac0ed74f53a8b4251c2adfd
[]
no_license
DementedEarplug/DataStructuresPractice
https://github.com/DementedEarplug/DataStructuresPractice
f596a21573e120fd2ff273a2bab8de88265ed198
341e5b4506eeb22164ece01868ac8f49f4509587
refs/heads/master
2021-01-02T09:35:35.928000
2017-08-05T15:02:02
2017-08-05T15:02:02
99,255,100
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package drafts; import java.io.IOException; import java.util.ArrayList; public class TriggerScriptIdea { public static void main(String[] args) { ArrayList<String> waypoints = new ArrayList<>(); String currentLocation; String[] trigger = {"python","D:/Workspace/python.py"}; waypoints.add("pooto"); waypoints.add("polto"); waypoints.add("poloo"); waypoints.add("polot"); while(!waypoints.isEmpty()) //Maybe measure battery here aswell? { currentLocation = "pooto"; if(currentLocation.equals(waypoints.get(0))) { //hover drone //activate SDR script try { Process p =Runtime.getRuntime().exec(trigger); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } waypoints.remove(0); } } } }
UTF-8
Java
822
java
TriggerScriptIdea.java
Java
[]
null
[]
package drafts; import java.io.IOException; import java.util.ArrayList; public class TriggerScriptIdea { public static void main(String[] args) { ArrayList<String> waypoints = new ArrayList<>(); String currentLocation; String[] trigger = {"python","D:/Workspace/python.py"}; waypoints.add("pooto"); waypoints.add("polto"); waypoints.add("poloo"); waypoints.add("polot"); while(!waypoints.isEmpty()) //Maybe measure battery here aswell? { currentLocation = "pooto"; if(currentLocation.equals(waypoints.get(0))) { //hover drone //activate SDR script try { Process p =Runtime.getRuntime().exec(trigger); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } waypoints.remove(0); } } } }
822
0.641119
0.638686
42
18.571428
17.673147
66
false
false
0
0
0
0
0
0
2.714286
false
false
13
241248f5976521be366db6cf6561fb2e306bea9c
8,005,819,078,114
b5119fd67dc03930e79980a0149dfcafe86af2b2
/src/main/java/srdm/cloud/commonService/app/bean/account/CreateAccountReqBean.java
6153ec697893e3d5983329dc93b7d4db61b2dece
[]
no_license
devopssandeep-test/common-service
https://github.com/devopssandeep-test/common-service
9212eea4f957143e57877059b61f85d4a3fd4ae2
5db3417195e132ba4503cde59f072564014d12b7
refs/heads/master
2023-04-28T20:19:05.548000
2019-11-26T11:01:20
2019-11-26T11:01:20
224,170,206
0
0
null
false
2023-04-14T17:27:04
2019-11-26T10:58:48
2019-11-26T11:02:22
2023-04-14T17:27:04
248
0
0
1
Java
false
false
package srdm.cloud.commonService.app.bean.account; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotBlank; import org.springframework.beans.factory.annotation.Value; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AccessLevel; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import srdm.cloud.commonService.validation.DateTimeFormat; import srdm.cloud.commonService.validation.DomainId; import srdm.cloud.commonService.validation.Language; import srdm.cloud.commonService.validation.Password; import srdm.cloud.commonService.validation.RoleId; import srdm.cloud.commonService.validation.TimeZoneId; import srdm.cloud.commonService.validation.TimeZoneIdConfirm; import srdm.common.bean.JsonBaseReqBean; @Data @EqualsAndHashCode(callSuper = false) @TimeZoneIdConfirm public class CreateAccountReqBean extends JsonBaseReqBean { /** * */ private static final long serialVersionUID = -880798263028924667L; @NotBlank(message = "E0011") @Size(min = 1, max = 64, message = "E0014") @Pattern.List({ @Pattern(regexp = "^[\\p{ASCII}]+$", message = "E0014"), @Pattern(regexp = "[^\\\\/:*?\"<>|]*", message = "E0014") }) private String accountName; @NotNull(message = "E0011") //@Getter(AccessLevel.NONE) @JsonProperty("isPermanentAccount") private Boolean isPermanentAccount; @NotBlank(message = "E0011") @Password private String password; @NotBlank(message = "E0011") @RoleId private String roleId; //@Getter(AccessLevel.NONE) @JsonProperty("isPrivateRole") private Boolean isPrivateRole; @NotBlank(message = "E0011") @DomainId private String domainId; @NotBlank(message = "E0011") @Language private String language; @NotBlank(message = "E0011") @DateTimeFormat private String dateTimeFormat; @NotBlank(message = "E0011") @Pattern(regexp = "auto|manual", message = "E0014") private String timeZoneSpecifingType; @TimeZoneId private String timeZoneId; @NotNull(message = "E0011") @Pattern(regexp = "^[\\p{ASCII}]+$", message = "E0014") private String homeGroupId; }
UTF-8
Java
2,191
java
CreateAccountReqBean.java
Java
[]
null
[]
package srdm.cloud.commonService.app.bean.account; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotBlank; import org.springframework.beans.factory.annotation.Value; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AccessLevel; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import srdm.cloud.commonService.validation.DateTimeFormat; import srdm.cloud.commonService.validation.DomainId; import srdm.cloud.commonService.validation.Language; import srdm.cloud.commonService.validation.Password; import srdm.cloud.commonService.validation.RoleId; import srdm.cloud.commonService.validation.TimeZoneId; import srdm.cloud.commonService.validation.TimeZoneIdConfirm; import srdm.common.bean.JsonBaseReqBean; @Data @EqualsAndHashCode(callSuper = false) @TimeZoneIdConfirm public class CreateAccountReqBean extends JsonBaseReqBean { /** * */ private static final long serialVersionUID = -880798263028924667L; @NotBlank(message = "E0011") @Size(min = 1, max = 64, message = "E0014") @Pattern.List({ @Pattern(regexp = "^[\\p{ASCII}]+$", message = "E0014"), @Pattern(regexp = "[^\\\\/:*?\"<>|]*", message = "E0014") }) private String accountName; @NotNull(message = "E0011") //@Getter(AccessLevel.NONE) @JsonProperty("isPermanentAccount") private Boolean isPermanentAccount; @NotBlank(message = "E0011") @Password private String password; @NotBlank(message = "E0011") @RoleId private String roleId; //@Getter(AccessLevel.NONE) @JsonProperty("isPrivateRole") private Boolean isPrivateRole; @NotBlank(message = "E0011") @DomainId private String domainId; @NotBlank(message = "E0011") @Language private String language; @NotBlank(message = "E0011") @DateTimeFormat private String dateTimeFormat; @NotBlank(message = "E0011") @Pattern(regexp = "auto|manual", message = "E0014") private String timeZoneSpecifingType; @TimeZoneId private String timeZoneId; @NotNull(message = "E0011") @Pattern(regexp = "^[\\p{ASCII}]+$", message = "E0014") private String homeGroupId; }
2,191
0.76723
0.732086
81
26.049383
20.754831
73
false
false
0
0
0
0
0
0
1
false
false
13
5030e7fb72144437c4b27158b9f9196ddbfb05d2
9,423,158,300,643
1b66391f50a9fc96b34e1b865e6a60c10194ae7c
/com-haoran-common/src/main/java/com/haoran/common/u/U4Object.java
b65499e62eddabb80afa000c9cc517dde559af6d
[]
no_license
hanhaoran1996/com-haoran
https://github.com/hanhaoran1996/com-haoran
09f2672d7f65fbe125eb144930e1fd57f2b60a91
9aea4e3b1f9c2e067a923b7a5aa4016915bd256f
refs/heads/master
2020-07-02T18:33:41.538000
2019-11-01T12:25:08
2019-11-01T12:25:08
201,623,388
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.haoran.common.u; import com.google.common.base.Preconditions; import com.haoran.common.Constants; import java.util.Collection; import java.util.Map; /** * @author hr.han * @date 2019/5/12 18:50 */ public final class U4Object { private U4Object() {} public static void checkNotNull(Object ... objs) { for (Object obj : objs) { Preconditions.checkNotNull(obj); } } public static boolean isNull(Object obj) { return obj == null; } public static boolean areNulls(Object ... objs) { if (isNull(objs)) { return true; } for (Object obj : objs) { if (nonNull(obj)) { return false; } } return true; } public static boolean nonNull(Object obj) { return obj != null; } public static boolean nonNulls(Object ... objs) { if (isNull(objs)) { return false; } for (Object obj : objs) { if (isNull(obj)) { return false; } } return true; } public static boolean isNullOrEmpty(String str) { return isNull(str) || str.isEmpty(); } public static boolean nonNullOrEmpty(String str) { return nonNull(str) && !str.isEmpty(); } public static boolean isNullOrEmpty(Collection<?> col) { return isNull(col) || col.isEmpty(); } public static boolean nonNullOrEmpty(Collection<?> col) { return nonNull(col) && !col.isEmpty(); } public static boolean isNullOrEmpty(Map<?, ?> map) { return isNull(map) || map.isEmpty(); } public static boolean nonNullOrEmpty(Map<?, ?> map) { return nonNull(map) && !map.isEmpty(); } @SafeVarargs public static <T> boolean isNullOrEmpty(T ... args) { return isNull(args) || args.length == Constants.ZERO; } @SafeVarargs public static <T> boolean nonNullOrEmpty(T ... args) { return nonNull(args) && args.length != Constants.ZERO; } }
UTF-8
Java
2,077
java
U4Object.java
Java
[ { "context": ".Collection;\nimport java.util.Map;\n\n/**\n * @author hr.han\n * @date 2019/5/12 18:50\n */\npublic final class U", "end": 185, "score": 0.9979040026664734, "start": 179, "tag": "USERNAME", "value": "hr.han" } ]
null
[]
package com.haoran.common.u; import com.google.common.base.Preconditions; import com.haoran.common.Constants; import java.util.Collection; import java.util.Map; /** * @author hr.han * @date 2019/5/12 18:50 */ public final class U4Object { private U4Object() {} public static void checkNotNull(Object ... objs) { for (Object obj : objs) { Preconditions.checkNotNull(obj); } } public static boolean isNull(Object obj) { return obj == null; } public static boolean areNulls(Object ... objs) { if (isNull(objs)) { return true; } for (Object obj : objs) { if (nonNull(obj)) { return false; } } return true; } public static boolean nonNull(Object obj) { return obj != null; } public static boolean nonNulls(Object ... objs) { if (isNull(objs)) { return false; } for (Object obj : objs) { if (isNull(obj)) { return false; } } return true; } public static boolean isNullOrEmpty(String str) { return isNull(str) || str.isEmpty(); } public static boolean nonNullOrEmpty(String str) { return nonNull(str) && !str.isEmpty(); } public static boolean isNullOrEmpty(Collection<?> col) { return isNull(col) || col.isEmpty(); } public static boolean nonNullOrEmpty(Collection<?> col) { return nonNull(col) && !col.isEmpty(); } public static boolean isNullOrEmpty(Map<?, ?> map) { return isNull(map) || map.isEmpty(); } public static boolean nonNullOrEmpty(Map<?, ?> map) { return nonNull(map) && !map.isEmpty(); } @SafeVarargs public static <T> boolean isNullOrEmpty(T ... args) { return isNull(args) || args.length == Constants.ZERO; } @SafeVarargs public static <T> boolean nonNullOrEmpty(T ... args) { return nonNull(args) && args.length != Constants.ZERO; } }
2,077
0.564275
0.558016
90
22.077778
20.417437
62
false
false
0
0
0
0
0
0
0.355556
false
false
13
c1acb3e33ff30245d5257cd59d009eaf592d009d
695,784,761,801
82663c6ac058a3fc436325378b1c1490d203013c
/spring-cloud-docker-in-action/e-book/e-book-consumer-order/src/main/java/net/will/ebook/consumer/service/UserService.java
d7f3a236884337d1aaec8587afbccd095842d71c
[]
no_license
pure-study/spring-study
https://github.com/pure-study/spring-study
b593ae94ff9b67bcbc1c8b8a6fd8a83a69000438
357d1e5c99e0fb80e6788d676c9eaea295f69081
refs/heads/master
2021-01-10T04:46:10.224000
2020-02-06T12:48:32
2020-02-06T12:48:32
45,535,911
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.will.ebook.consumer.service; import net.will.ebook.user.facade.UserFacade; import org.springframework.cloud.openfeign.FeignClient; @FeignClient(name = "e-book-user") public interface UserService extends UserFacade { }
UTF-8
Java
232
java
UserService.java
Java
[]
null
[]
package net.will.ebook.consumer.service; import net.will.ebook.user.facade.UserFacade; import org.springframework.cloud.openfeign.FeignClient; @FeignClient(name = "e-book-user") public interface UserService extends UserFacade { }
232
0.810345
0.810345
8
28
22.181072
55
false
false
0
0
0
0
0
0
0.375
false
false
13
08b0081ad1f48f11b96e669fe45c7fb6722a5e6b
695,784,758,398
9d59ab02dbee9ad87a34a026a9d9af10dd712661
/entities/src/main/java/helpers/entities/KartotecniList.java
eb24317a7e19dd19c30597784b714c827a50c944
[]
no_license
primozh/studis-server
https://github.com/primozh/studis-server
0ca93abd60e2a737366b3b415b458e455b9136cc
d406cef033e5ecf88e74b688984b11bdf34f9cc8
refs/heads/master
2021-09-15T16:54:25.089000
2018-06-07T10:28:12
2018-06-07T10:28:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package helpers.entities; import java.util.List; public class KartotecniList { private String ime; private String priimek; private Integer vpisnaStevilka; private List<Vrstica> vrstica; public String getIme() { return ime; } public void setIme(String ime) { this.ime = ime; } public String getPriimek() { return priimek; } public void setPriimek(String priimek) { this.priimek = priimek; } public Integer getVpisnaStevilka() { return vpisnaStevilka; } public void setVpisnaStevilka(Integer vpisnaStevilka) { this.vpisnaStevilka = vpisnaStevilka; } public List<Vrstica> getVrstica() { return vrstica; } public void setVrstica(List<Vrstica> vrstica) { this.vrstica = vrstica; } }
UTF-8
Java
833
java
KartotecniList.java
Java
[]
null
[]
package helpers.entities; import java.util.List; public class KartotecniList { private String ime; private String priimek; private Integer vpisnaStevilka; private List<Vrstica> vrstica; public String getIme() { return ime; } public void setIme(String ime) { this.ime = ime; } public String getPriimek() { return priimek; } public void setPriimek(String priimek) { this.priimek = priimek; } public Integer getVpisnaStevilka() { return vpisnaStevilka; } public void setVpisnaStevilka(Integer vpisnaStevilka) { this.vpisnaStevilka = vpisnaStevilka; } public List<Vrstica> getVrstica() { return vrstica; } public void setVrstica(List<Vrstica> vrstica) { this.vrstica = vrstica; } }
833
0.633854
0.633854
43
18.372093
16.922564
59
false
false
0
0
0
0
0
0
0.325581
false
false
13
547f3544850b578df64fa3f77d2dfda841553259
32,289,564,175,262
7b45708512247491ec0af3af2c9772b8c9ab6986
/src/komorebi/bean/engine/Draw.java
207c682a01ed910fa796471e0419b32f2c4f422f
[]
no_license
fberry26/bean
https://github.com/fberry26/bean
d7c160829bc322f9962fb6ec4e49dcce5badcffd
55e13d49f38b7ef0ca05e8357425f51fdebd5254
refs/heads/master
2021-01-12T01:25:03.628000
2017-01-09T01:40:28
2017-01-09T01:40:28
78,382,759
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package komorebi.bean.engine; import static org.lwjgl.opengl.GL11.GL_NEAREST; import static org.lwjgl.opengl.GL11.GL_QUADS; import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; import static org.lwjgl.opengl.GL11.GL_TEXTURE_MAG_FILTER; import static org.lwjgl.opengl.GL11.GL_TEXTURE_MIN_FILTER; import static org.lwjgl.opengl.GL11.glBegin; import static org.lwjgl.opengl.GL11.glEnd; import static org.lwjgl.opengl.GL11.glPopMatrix; import static org.lwjgl.opengl.GL11.glPushMatrix; import static org.lwjgl.opengl.GL11.glTexCoord2f; import static org.lwjgl.opengl.GL11.glTexParameteri; import static org.lwjgl.opengl.GL11.glTranslatef; import static org.lwjgl.opengl.GL11.glVertex2f; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; public class Draw { public static Texture[] textures = new Texture[5]; public static int[] imgX = new int[5]; public static int[] imgY = new int[5]; public static ArrayList<String> keys = new ArrayList<String>(); public Draw() { } /** * Draws a square or rectangular shape to be rendered on the display * @param type Type of tile to be drawn * @param x Bottom-left horizontal coordinate of the square * @param y Bottom-left vertical coordinate of the square * @param scalar Scale of the tile to be multiplied by (1 = 16 x 16 square) */ public static void drawSquare(TileType type, float x, float y, int scalar) { int texId, texX, texY, texSx, texSy, sx, sy; switch (type) { case BLANK: texX=0; texY=0; texSx=16; texSy=16; sx = 16*scalar; sy = 16*scalar; break; case TILE: texX = 0; texY = 16; texSx=16; texSy=32; sx = 16*scalar; sy = 16*scalar; break; case BEAN: texX = 0; texY = 0; texSx=12; texSy=16; sx = 12*scalar; sy = 16*scalar; break; case FLAG: texX = 96; texY = 0; texSx = 108; texSy = 16; sx = 12*scalar; sy = 16*scalar; break; case SPIKE_END_LEFT: texX = 112; texY = 16; texSx = 128; texSy = 32; sx = 16*scalar; sy = 16*scalar; break; case SPIKE_MIDDLE: texX = 64; texY = 16; texSx = 80; texSy = 32; sx = 16*scalar; sy = 16*scalar; break; case SPIKE_END_RIGHT: texX = 96; texY = 16; texSx = 112; texSy = 32; sx = 16*scalar; sy = 16*scalar; break; case SPIKE_SINGLE: texX = 80; texY = 16; texSx = 96; texSy=32; sx = 16*scalar; sy = 16*scalar; break; case GATE: texX = 128; texY = 16; texSx = 132; texSy=32; sx = 4*scalar; sy = 16*scalar; break; case SINGLE_BEAM: texX = 124; texY = 0; texSx = 132; texSy=16; sx = 8*scalar; sy = 16*scalar; break; case BUTTON: texX = 134; texY = 28; texSx = 142; texSy=32; sx = 8*scalar; sy = 4*scalar; break; case LADDER: texX = 128; texY = 128; texSx = 144; texSy=144; sx = 16*scalar; sy = 16*scalar; break; case TREADMILL_LEFT: texX = 0; texY = 160; texSx = 16; texSy= 176; sx = 16*scalar; sy = 16*scalar; break; case TREADMILL_CENTER: texX = 16; texY = 160; texSx = 32; texSy=176; sx = 16*scalar; sy = 16*scalar; break; case TREADMILL_RIGHT: texX = 32; texY = 160; texSx = 48; texSy=176; sx = 16*scalar; sy = 16*scalar; break; case DOUBLE_BEAM_TOP: texX = 144; texY = 32; texSx = 152; texSy = 48; sx = 8*scalar; sy = 16*scalar; break; case DOUBLE_BEAM_BOTTOM: texX = 144; texY = 48; texSx = 152; texSy=64; sx = 8*scalar; sy = 16*scalar; break; case TURRET: texX = 108; texY = 4; texSx = 124; texSy=16; sx = 12*scalar; sy = 16*scalar; break; default: texX = 0; texY = 0; texSx=0; texSy=0; sx = 16*scalar; sy = 16*scalar; break; } if (type==TileType.BLANK) texId = 1; else texId = 0; draw(x, y, (float) sx, (float) sy, texX, texY, texSx, texSy, texId); } /** * Loads the necessary textures to be used within the draw class. Must be called before the draw class is used */ public static void loadTextures() { try { Texture t1 = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + "Spreadsheet" + ".png"))); textures[0] = t1; Texture t2 = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + "Blank" + ".png"))); textures[1] = t2; Texture t3 = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + "Selector" + ".png"))); textures[2] = t3; Texture t4 = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + "Play" + ".png"))); textures[3] = t4; Texture t5 = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + "Stop" + ".png"))); textures[4] = t5; imgX[0] = t1.getImageWidth(); imgY[0] = t1.getImageHeight(); imgX[1] = t2.getImageWidth(); imgY[1] = t2.getImageHeight(); imgX[2] = t3.getImageWidth(); imgY[2] = t3.getImageHeight(); imgX[3] = t4.getImageWidth(); imgY[3] = t4.getImageHeight(); imgX[4] = t5.getImageWidth(); imgY[4] = t5.getImageHeight(); } catch (Exception e) { e.printStackTrace(); } } /** * Draws the green tile-selector on the palette * @param x The bottom-left horizontal coordinate * @param y The bottom-left vertical coordinate */ public static void drawMenuItem(MenuItem m, int x, int y, int scalar) { int texX = 0, texY = 0, texSx = 0, texSy = 0, sx = 0, sy = 0, texId = 0; switch (m) { case LABEL: break; case PLAY: texX=0; texY=0; texSx=32; texSy=32; sx =16*scalar; sy=16*scalar; texId = 3; break; case SELECTOR: texX=0; texY=0; texSx=32; texSy=32; sx =16*scalar; sy=16*scalar; texId = 2; break; case STOP: texX=0; texY=0; texSx=32; texSy=32; sx =16*scalar; sy=16*scalar; texId = 4; break; default: sx = 0; sy = 0; texX=0; texY=0; texSx=0; texSy=0; break; } draw(x, y, sx, sy, texX, texY, texSx, texSy, texId); } /** * An adaptation of the drawSquare method which can render the animations of certain tile types * @param type Tile type of the square to be rendered * @param x Bottom-left horizontal coordinate * @param y Bottom-left vertical coordinate * @param scalar Scale of the tile to be multiplied by (1 = 16 x 16 square) * @param frame Frame of the animation */ public static void drawAnimation(TileType type, float x, float y, int scalar, int frame) { int texId, texX, texY, texSx, texSy, sx, sy; switch (type) { case GATE: texX = 128; texY = 16; texSx = 132; texSy=32; sx = 4*scalar; sy = 16*scalar; break; case BUTTON: texX = 134; texY = 28; texSx = 142; texSy=32; sx = 8*scalar; sy = 4*scalar; break; case TREADMILL_LEFT: texX = 0; texY = 144 + (frame*16); texSx = 16; texSy= texY + 16; sx = 16*scalar; sy = 16*scalar; break; case TREADMILL_CENTER: texX = 16; texY = 144 + (frame*16); texSx = 32; texSy=texY + 16; sx = 16*scalar; sy = 16*scalar; break; case TREADMILL_RIGHT: texX = 32; texY = 144 + (frame*16); texSx = 48; texSy=texY + 16; sx = 16*scalar; sy = 16*scalar; break; default: texX = 0; texY = 0; texSx=0; texSy=0; sx = 16*scalar; sy = 16*scalar; break; } if (type==TileType.BLANK) texId = 1; else texId = 0; draw(x, y, sx, sy, texX, texY, texSx, texSy, texId); } /** * Draws the TileType.TILE square of a specific color * @param color Color of the tile to be drawn * @param x Bottom-left horizontal coordinate * @param y Bottom-left vertical coordinate * @param scalar Scale of the tile to be multiplied by (1 = 16 x 16 square) */ public static void drawColoredTile(TileColor color, float x, float y, int scalar) { int texId, texX, texY, texSx, texSy, sx, sy; texX = color.getTexX(); texY = color.getTexY(); texSx = color.getTexSx(); texSy = color.getTexSy(); texId=0; sx = 16*scalar; sy = 16*scalar; draw(x, y, sx, sy, texX, texY, texSx, texSy, texId); } public static void draw(float x, float y, float sx, float sy, int texX, int texY, int texSx, int texSy, int texId) { glPushMatrix(); { Texture tex = textures[texId]; glTranslatef((int) x, (int) y, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); tex.bind(); glBegin(GL_QUADS); { glTexCoord2f((float)texX/imgX[texId], (float) texSy/imgY[texId]); glVertex2f(0, 0); glTexCoord2f((float) texX/imgX[texId], (float) texY/imgY[texId]); glVertex2f(0, (int) sy); glTexCoord2f((float) texSx/imgX[texId], (float) texY/imgY[texId]); glVertex2f((int) sx, (int) sy); glTexCoord2f((float) texSx/imgX[texId], (float) texSy/imgY[texId]); glVertex2f((int) sx, 0); } glEnd(); } glPopMatrix(); } }
UTF-8
Java
9,975
java
Draw.java
Java
[]
null
[]
package komorebi.bean.engine; import static org.lwjgl.opengl.GL11.GL_NEAREST; import static org.lwjgl.opengl.GL11.GL_QUADS; import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; import static org.lwjgl.opengl.GL11.GL_TEXTURE_MAG_FILTER; import static org.lwjgl.opengl.GL11.GL_TEXTURE_MIN_FILTER; import static org.lwjgl.opengl.GL11.glBegin; import static org.lwjgl.opengl.GL11.glEnd; import static org.lwjgl.opengl.GL11.glPopMatrix; import static org.lwjgl.opengl.GL11.glPushMatrix; import static org.lwjgl.opengl.GL11.glTexCoord2f; import static org.lwjgl.opengl.GL11.glTexParameteri; import static org.lwjgl.opengl.GL11.glTranslatef; import static org.lwjgl.opengl.GL11.glVertex2f; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; public class Draw { public static Texture[] textures = new Texture[5]; public static int[] imgX = new int[5]; public static int[] imgY = new int[5]; public static ArrayList<String> keys = new ArrayList<String>(); public Draw() { } /** * Draws a square or rectangular shape to be rendered on the display * @param type Type of tile to be drawn * @param x Bottom-left horizontal coordinate of the square * @param y Bottom-left vertical coordinate of the square * @param scalar Scale of the tile to be multiplied by (1 = 16 x 16 square) */ public static void drawSquare(TileType type, float x, float y, int scalar) { int texId, texX, texY, texSx, texSy, sx, sy; switch (type) { case BLANK: texX=0; texY=0; texSx=16; texSy=16; sx = 16*scalar; sy = 16*scalar; break; case TILE: texX = 0; texY = 16; texSx=16; texSy=32; sx = 16*scalar; sy = 16*scalar; break; case BEAN: texX = 0; texY = 0; texSx=12; texSy=16; sx = 12*scalar; sy = 16*scalar; break; case FLAG: texX = 96; texY = 0; texSx = 108; texSy = 16; sx = 12*scalar; sy = 16*scalar; break; case SPIKE_END_LEFT: texX = 112; texY = 16; texSx = 128; texSy = 32; sx = 16*scalar; sy = 16*scalar; break; case SPIKE_MIDDLE: texX = 64; texY = 16; texSx = 80; texSy = 32; sx = 16*scalar; sy = 16*scalar; break; case SPIKE_END_RIGHT: texX = 96; texY = 16; texSx = 112; texSy = 32; sx = 16*scalar; sy = 16*scalar; break; case SPIKE_SINGLE: texX = 80; texY = 16; texSx = 96; texSy=32; sx = 16*scalar; sy = 16*scalar; break; case GATE: texX = 128; texY = 16; texSx = 132; texSy=32; sx = 4*scalar; sy = 16*scalar; break; case SINGLE_BEAM: texX = 124; texY = 0; texSx = 132; texSy=16; sx = 8*scalar; sy = 16*scalar; break; case BUTTON: texX = 134; texY = 28; texSx = 142; texSy=32; sx = 8*scalar; sy = 4*scalar; break; case LADDER: texX = 128; texY = 128; texSx = 144; texSy=144; sx = 16*scalar; sy = 16*scalar; break; case TREADMILL_LEFT: texX = 0; texY = 160; texSx = 16; texSy= 176; sx = 16*scalar; sy = 16*scalar; break; case TREADMILL_CENTER: texX = 16; texY = 160; texSx = 32; texSy=176; sx = 16*scalar; sy = 16*scalar; break; case TREADMILL_RIGHT: texX = 32; texY = 160; texSx = 48; texSy=176; sx = 16*scalar; sy = 16*scalar; break; case DOUBLE_BEAM_TOP: texX = 144; texY = 32; texSx = 152; texSy = 48; sx = 8*scalar; sy = 16*scalar; break; case DOUBLE_BEAM_BOTTOM: texX = 144; texY = 48; texSx = 152; texSy=64; sx = 8*scalar; sy = 16*scalar; break; case TURRET: texX = 108; texY = 4; texSx = 124; texSy=16; sx = 12*scalar; sy = 16*scalar; break; default: texX = 0; texY = 0; texSx=0; texSy=0; sx = 16*scalar; sy = 16*scalar; break; } if (type==TileType.BLANK) texId = 1; else texId = 0; draw(x, y, (float) sx, (float) sy, texX, texY, texSx, texSy, texId); } /** * Loads the necessary textures to be used within the draw class. Must be called before the draw class is used */ public static void loadTextures() { try { Texture t1 = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + "Spreadsheet" + ".png"))); textures[0] = t1; Texture t2 = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + "Blank" + ".png"))); textures[1] = t2; Texture t3 = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + "Selector" + ".png"))); textures[2] = t3; Texture t4 = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + "Play" + ".png"))); textures[3] = t4; Texture t5 = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + "Stop" + ".png"))); textures[4] = t5; imgX[0] = t1.getImageWidth(); imgY[0] = t1.getImageHeight(); imgX[1] = t2.getImageWidth(); imgY[1] = t2.getImageHeight(); imgX[2] = t3.getImageWidth(); imgY[2] = t3.getImageHeight(); imgX[3] = t4.getImageWidth(); imgY[3] = t4.getImageHeight(); imgX[4] = t5.getImageWidth(); imgY[4] = t5.getImageHeight(); } catch (Exception e) { e.printStackTrace(); } } /** * Draws the green tile-selector on the palette * @param x The bottom-left horizontal coordinate * @param y The bottom-left vertical coordinate */ public static void drawMenuItem(MenuItem m, int x, int y, int scalar) { int texX = 0, texY = 0, texSx = 0, texSy = 0, sx = 0, sy = 0, texId = 0; switch (m) { case LABEL: break; case PLAY: texX=0; texY=0; texSx=32; texSy=32; sx =16*scalar; sy=16*scalar; texId = 3; break; case SELECTOR: texX=0; texY=0; texSx=32; texSy=32; sx =16*scalar; sy=16*scalar; texId = 2; break; case STOP: texX=0; texY=0; texSx=32; texSy=32; sx =16*scalar; sy=16*scalar; texId = 4; break; default: sx = 0; sy = 0; texX=0; texY=0; texSx=0; texSy=0; break; } draw(x, y, sx, sy, texX, texY, texSx, texSy, texId); } /** * An adaptation of the drawSquare method which can render the animations of certain tile types * @param type Tile type of the square to be rendered * @param x Bottom-left horizontal coordinate * @param y Bottom-left vertical coordinate * @param scalar Scale of the tile to be multiplied by (1 = 16 x 16 square) * @param frame Frame of the animation */ public static void drawAnimation(TileType type, float x, float y, int scalar, int frame) { int texId, texX, texY, texSx, texSy, sx, sy; switch (type) { case GATE: texX = 128; texY = 16; texSx = 132; texSy=32; sx = 4*scalar; sy = 16*scalar; break; case BUTTON: texX = 134; texY = 28; texSx = 142; texSy=32; sx = 8*scalar; sy = 4*scalar; break; case TREADMILL_LEFT: texX = 0; texY = 144 + (frame*16); texSx = 16; texSy= texY + 16; sx = 16*scalar; sy = 16*scalar; break; case TREADMILL_CENTER: texX = 16; texY = 144 + (frame*16); texSx = 32; texSy=texY + 16; sx = 16*scalar; sy = 16*scalar; break; case TREADMILL_RIGHT: texX = 32; texY = 144 + (frame*16); texSx = 48; texSy=texY + 16; sx = 16*scalar; sy = 16*scalar; break; default: texX = 0; texY = 0; texSx=0; texSy=0; sx = 16*scalar; sy = 16*scalar; break; } if (type==TileType.BLANK) texId = 1; else texId = 0; draw(x, y, sx, sy, texX, texY, texSx, texSy, texId); } /** * Draws the TileType.TILE square of a specific color * @param color Color of the tile to be drawn * @param x Bottom-left horizontal coordinate * @param y Bottom-left vertical coordinate * @param scalar Scale of the tile to be multiplied by (1 = 16 x 16 square) */ public static void drawColoredTile(TileColor color, float x, float y, int scalar) { int texId, texX, texY, texSx, texSy, sx, sy; texX = color.getTexX(); texY = color.getTexY(); texSx = color.getTexSx(); texSy = color.getTexSy(); texId=0; sx = 16*scalar; sy = 16*scalar; draw(x, y, sx, sy, texX, texY, texSx, texSy, texId); } public static void draw(float x, float y, float sx, float sy, int texX, int texY, int texSx, int texSy, int texId) { glPushMatrix(); { Texture tex = textures[texId]; glTranslatef((int) x, (int) y, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); tex.bind(); glBegin(GL_QUADS); { glTexCoord2f((float)texX/imgX[texId], (float) texSy/imgY[texId]); glVertex2f(0, 0); glTexCoord2f((float) texX/imgX[texId], (float) texY/imgY[texId]); glVertex2f(0, (int) sy); glTexCoord2f((float) texSx/imgX[texId], (float) texY/imgY[texId]); glVertex2f((int) sx, (int) sy); glTexCoord2f((float) texSx/imgX[texId], (float) texSy/imgY[texId]); glVertex2f((int) sx, 0); } glEnd(); } glPopMatrix(); } }
9,975
0.559699
0.513183
465
19.451612
20.187889
115
false
false
0
0
0
0
0
0
3.726882
false
false
13
61b90f5eabbba1b39fdfe8ed3a8c567d6bed5cdd
9,294,309,277,358
3184009c08f2211a19f47ee137fa334a5f3d9511
/src/test/java/com/workoutTracker/controller/WorkoutControllerTest.java
a79b48646ad291000edc64dc05df37cec29c07f2
[]
no_license
jijilki/WorkoutTracker
https://github.com/jijilki/WorkoutTracker
c66da7f45d55fe846518d98ed7caffbf1db00578
a0b49d5a096237871e64dc4187409d89ce0e751f
refs/heads/master
2022-08-16T03:15:56.604000
2018-05-29T14:28:34
2018-05-29T14:28:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.workoutTracker.controller; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import com.workoutTracker.wt.controller.WorkoutController; import com.workoutTracker.wt.impl.WorkoutServiceImpl; import com.workoutTracker.wt.intf.WorkoutServiceInterface; import com.workoutTracker.wt.request.CategoryRequest; import org.junit.Assert; @RunWith(MockitoJUnitRunner.class) public class WorkoutControllerTest{ @InjectMocks WorkoutController workoutControllerMock; @Mock WorkoutServiceInterface workoutServMock; CategoryRequest categoryRequest = new CategoryRequest(); @Before public void mockData (){ // TODO Auto-generated constructor stub categoryRequest.setCategoryName("Yoga"); } @Test public void testCreateCategory(){ Mockito.when(workoutServMock.addCategory(Matchers.any(CategoryRequest.class))).thenReturn("success"); Assert.assertEquals("success", workoutControllerMock.addCategory(categoryRequest)); } }
UTF-8
Java
1,246
java
WorkoutControllerTest.java
Java
[]
null
[]
package com.workoutTracker.controller; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import com.workoutTracker.wt.controller.WorkoutController; import com.workoutTracker.wt.impl.WorkoutServiceImpl; import com.workoutTracker.wt.intf.WorkoutServiceInterface; import com.workoutTracker.wt.request.CategoryRequest; import org.junit.Assert; @RunWith(MockitoJUnitRunner.class) public class WorkoutControllerTest{ @InjectMocks WorkoutController workoutControllerMock; @Mock WorkoutServiceInterface workoutServMock; CategoryRequest categoryRequest = new CategoryRequest(); @Before public void mockData (){ // TODO Auto-generated constructor stub categoryRequest.setCategoryName("Yoga"); } @Test public void testCreateCategory(){ Mockito.when(workoutServMock.addCategory(Matchers.any(CategoryRequest.class))).thenReturn("success"); Assert.assertEquals("success", workoutControllerMock.addCategory(categoryRequest)); } }
1,246
0.803371
0.803371
55
21.672728
23.91048
103
false
false
0
0
0
0
0
0
1.072727
false
false
13
9625dca3aba96e2ae621eea0d322a0ab21d3424d
4,449,586,173,287
7312ff00a32daebcaae32caef6812005318b704a
/src/main/java/org/telegram/api/functions/account/TLRequestAccountConfirmPhone.java
528a740124d3f9da7b2de7df8e312e71d5c81e6c
[ "MIT" ]
permissive
onixred/TelegramApi
https://github.com/onixred/TelegramApi
fa194e83d42bfa4a321636c040bc7ca4fa0619ac
093483533db583eeafb07bfa20aeec897bb91e58
refs/heads/master
2021-04-15T04:38:41.773000
2018-08-12T14:08:03
2018-08-12T14:08:03
126,354,440
7
4
MIT
true
2018-07-31T01:14:24
2018-03-22T15:16:58
2018-06-22T12:22:20
2018-07-31T01:14:24
745
1
2
3
Java
false
null
package org.telegram.api.functions.account; import org.telegram.tl.StreamingUtils; import org.telegram.tl.TLBool; import org.telegram.tl.TLContext; import org.telegram.tl.TLMethod; import org.telegram.tl.TLObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @author Ruben Bermudez * @version 1.0 * @brief TODO * @date 08 of August of 2016 */ public class TLRequestAccountConfirmPhone extends TLMethod<TLBool> { public static final int CLASS_ID = 0x5f2178c3; private String phoneCodeHash; private String phoneCode; public TLRequestAccountConfirmPhone() { super(); } @Override public int getClassId() { return CLASS_ID; } public String getPhoneCodeHash() { return phoneCodeHash; } public void setPhoneCodeHash(String phoneCodeHash) { this.phoneCodeHash = phoneCodeHash; } public String getPhoneCode() { return phoneCode; } public void setPhoneCode(String phoneCode) { this.phoneCode = phoneCode; } @Override public TLBool deserializeResponse(InputStream stream, TLContext context) throws IOException { final TLObject res = StreamingUtils.readTLObject(stream, context); if (res == null) { throw new IOException("Unable to parse response"); } if ((res instanceof TLBool)) { return (TLBool) res; } throw new IOException("Incorrect response type. Expected " + TLBool.class.getCanonicalName() + ", got: " + res.getClass().getCanonicalName()); } @Override public void serializeBody(OutputStream stream) throws IOException { StreamingUtils.writeTLString(phoneCodeHash, stream); StreamingUtils.writeTLString(phoneCode, stream); } @Override public void deserializeBody(InputStream stream, TLContext context) throws IOException { phoneCodeHash = StreamingUtils.readTLString(stream); phoneCode = StreamingUtils.readTLString(stream); } @Override public String toString() { return "account.confirmPhone#5f2178c3"; } }
UTF-8
Java
2,141
java
TLRequestAccountConfirmPhone.java
Java
[ { "context": "ream;\nimport java.io.OutputStream;\n\n/**\n * @author Ruben Bermudez\n * @version 1.0\n * @brief TODO\n * @date 08 of Aug", "end": 331, "score": 0.9998814463615417, "start": 317, "tag": "NAME", "value": "Ruben Bermudez" } ]
null
[]
package org.telegram.api.functions.account; import org.telegram.tl.StreamingUtils; import org.telegram.tl.TLBool; import org.telegram.tl.TLContext; import org.telegram.tl.TLMethod; import org.telegram.tl.TLObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @author <NAME> * @version 1.0 * @brief TODO * @date 08 of August of 2016 */ public class TLRequestAccountConfirmPhone extends TLMethod<TLBool> { public static final int CLASS_ID = 0x5f2178c3; private String phoneCodeHash; private String phoneCode; public TLRequestAccountConfirmPhone() { super(); } @Override public int getClassId() { return CLASS_ID; } public String getPhoneCodeHash() { return phoneCodeHash; } public void setPhoneCodeHash(String phoneCodeHash) { this.phoneCodeHash = phoneCodeHash; } public String getPhoneCode() { return phoneCode; } public void setPhoneCode(String phoneCode) { this.phoneCode = phoneCode; } @Override public TLBool deserializeResponse(InputStream stream, TLContext context) throws IOException { final TLObject res = StreamingUtils.readTLObject(stream, context); if (res == null) { throw new IOException("Unable to parse response"); } if ((res instanceof TLBool)) { return (TLBool) res; } throw new IOException("Incorrect response type. Expected " + TLBool.class.getCanonicalName() + ", got: " + res.getClass().getCanonicalName()); } @Override public void serializeBody(OutputStream stream) throws IOException { StreamingUtils.writeTLString(phoneCodeHash, stream); StreamingUtils.writeTLString(phoneCode, stream); } @Override public void deserializeBody(InputStream stream, TLContext context) throws IOException { phoneCodeHash = StreamingUtils.readTLString(stream); phoneCode = StreamingUtils.readTLString(stream); } @Override public String toString() { return "account.confirmPhone#5f2178c3"; } }
2,133
0.684727
0.674918
78
26.448717
27.175426
150
false
false
0
0
0
0
0
0
0.423077
false
false
13
4b3c8cf2333885c5376a8e3ff60f731d14857b4d
21,646,635,220,371
4dda2b528aa7d7e56a85b612e930531f57e810b3
/app/src/main/java/com/HyKj/UKeBao/view/activity/MarketingManage/CardDetailActivity.java
423e91489a9b7a8dfdbccc8ca721c9195cbca706
[]
no_license
qianggezaicunjin/UKeBao
https://github.com/qianggezaicunjin/UKeBao
d80cc5fcdfc872ea19326afda34409468a4da37a
cd8f4d4c60d1a844f685202e4f80e5a33f5c4e97
refs/heads/master
2021-01-10T23:06:05.066000
2016-12-21T03:21:18
2016-12-21T03:21:20
70,440,135
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.HyKj.UKeBao.view.activity.marketingManage; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.view.View; import android.widget.ListView; import com.HyKj.UKeBao.R; import com.HyKj.UKeBao.databinding.ActivityCardDetailBinding; import com.HyKj.UKeBao.model.marketingManage.LanFragmentModel; import com.HyKj.UKeBao.model.marketingManage.bean.MemberCardInfo; import com.HyKj.UKeBao.util.LogUtil; import com.HyKj.UKeBao.util.SystemBarUtil; import com.HyKj.UKeBao.view.activity.BaseActiviy; import com.HyKj.UKeBao.view.adapter.MarketingManage.CardDetailAdapter; import com.HyKj.UKeBao.viewModel.marketingManage.LanFragmentViewModel; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import java.util.ArrayList; import java.util.List; /** * 卡劵详情 * Created by Administrator on 2016/10/19. */ public class CardDetailActivity extends BaseActiviy { private ActivityCardDetailBinding mBinding; private LanFragmentViewModel viewModel; private ListView listView; private PullToRefreshListView mListView; private int id; private CardDetailAdapter adapter; private int rows = 10;//条目显示数 private int position = 0; private List<MemberCardInfo> datalist = new ArrayList<MemberCardInfo>(); private List<MemberCardInfo> temporary_list = new ArrayList<>(); public static Intent getStartIntent(Context context) { Intent intent = new Intent(context, CardDetailActivity.class); return intent; } @Override public void onCreateBinding() { SystemBarUtil.changeColor(R.color.blue); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_card_detail); mBinding.lvCardDetail.setMode(PullToRefreshBase.Mode.BOTH); listView = mBinding.lvCardDetail.getRefreshableView(); id = getIntent().getIntExtra("id", 0); viewModel = new LanFragmentViewModel(new LanFragmentModel(), this); mBinding.setViewModel(viewModel); viewModel.getSingCardDetail(id, false); } @Override public void setUpView() { } @Override public void setListeners() { //设置退出监听 mBinding.imbTitleBarBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); //下拉刷新 mBinding.lvCardDetail.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { if (refreshView.isHeaderShown()) { //重新加载数据 temporary_list.clear(); viewModel.getSingCardDetail(id, false); position=0; } else if (refreshView.isFooterShown()) { if (datalist.size() <= position) { mBinding.lvCardDetail.postDelayed(new Runnable() { @Override public void run() { mBinding.lvCardDetail.onRefreshComplete(); } },1000); toast("没有更多数据啦~", CardDetailActivity.this); } else { temporary_list.addAll(viewModel.getDisplayNum(position, rows)); position += rows; mBinding.lvCardDetail.postDelayed(new Runnable() { @Override public void run() { mBinding.lvCardDetail.onRefreshComplete(); adapter.notifyDataSetChanged(); } },1000); } } } }); } public void setDataList(List<MemberCardInfo> list) { datalist = list; temporary_list.addAll(viewModel.getDisplayNum(0, rows)); adapter = new CardDetailAdapter(this, temporary_list); position += rows; listView.setAdapter(adapter); mBinding.lvCardDetail.postDelayed(new Runnable() { @Override public void run() { mBinding.lvCardDetail.onRefreshComplete(); } },1000); adapter.notifyDataSetChanged(); } }
UTF-8
Java
4,590
java
CardDetailActivity.java
Java
[]
null
[]
package com.HyKj.UKeBao.view.activity.marketingManage; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.view.View; import android.widget.ListView; import com.HyKj.UKeBao.R; import com.HyKj.UKeBao.databinding.ActivityCardDetailBinding; import com.HyKj.UKeBao.model.marketingManage.LanFragmentModel; import com.HyKj.UKeBao.model.marketingManage.bean.MemberCardInfo; import com.HyKj.UKeBao.util.LogUtil; import com.HyKj.UKeBao.util.SystemBarUtil; import com.HyKj.UKeBao.view.activity.BaseActiviy; import com.HyKj.UKeBao.view.adapter.MarketingManage.CardDetailAdapter; import com.HyKj.UKeBao.viewModel.marketingManage.LanFragmentViewModel; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import java.util.ArrayList; import java.util.List; /** * 卡劵详情 * Created by Administrator on 2016/10/19. */ public class CardDetailActivity extends BaseActiviy { private ActivityCardDetailBinding mBinding; private LanFragmentViewModel viewModel; private ListView listView; private PullToRefreshListView mListView; private int id; private CardDetailAdapter adapter; private int rows = 10;//条目显示数 private int position = 0; private List<MemberCardInfo> datalist = new ArrayList<MemberCardInfo>(); private List<MemberCardInfo> temporary_list = new ArrayList<>(); public static Intent getStartIntent(Context context) { Intent intent = new Intent(context, CardDetailActivity.class); return intent; } @Override public void onCreateBinding() { SystemBarUtil.changeColor(R.color.blue); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_card_detail); mBinding.lvCardDetail.setMode(PullToRefreshBase.Mode.BOTH); listView = mBinding.lvCardDetail.getRefreshableView(); id = getIntent().getIntExtra("id", 0); viewModel = new LanFragmentViewModel(new LanFragmentModel(), this); mBinding.setViewModel(viewModel); viewModel.getSingCardDetail(id, false); } @Override public void setUpView() { } @Override public void setListeners() { //设置退出监听 mBinding.imbTitleBarBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); //下拉刷新 mBinding.lvCardDetail.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { if (refreshView.isHeaderShown()) { //重新加载数据 temporary_list.clear(); viewModel.getSingCardDetail(id, false); position=0; } else if (refreshView.isFooterShown()) { if (datalist.size() <= position) { mBinding.lvCardDetail.postDelayed(new Runnable() { @Override public void run() { mBinding.lvCardDetail.onRefreshComplete(); } },1000); toast("没有更多数据啦~", CardDetailActivity.this); } else { temporary_list.addAll(viewModel.getDisplayNum(position, rows)); position += rows; mBinding.lvCardDetail.postDelayed(new Runnable() { @Override public void run() { mBinding.lvCardDetail.onRefreshComplete(); adapter.notifyDataSetChanged(); } },1000); } } } }); } public void setDataList(List<MemberCardInfo> list) { datalist = list; temporary_list.addAll(viewModel.getDisplayNum(0, rows)); adapter = new CardDetailAdapter(this, temporary_list); position += rows; listView.setAdapter(adapter); mBinding.lvCardDetail.postDelayed(new Runnable() { @Override public void run() { mBinding.lvCardDetail.onRefreshComplete(); } },1000); adapter.notifyDataSetChanged(); } }
4,590
0.610252
0.604507
158
27.645569
26.469967
104
false
false
0
0
0
0
0
0
0.468354
false
false
13
b22e01203986e7caaf6862ad6360bfa52fcff8dc
16,441,134,839,643
c6e06ced7303d2082d60b8aa9244574a5d65345a
/src/main/java/com/iitu/wms/entities/TaskEntity.java
618cf279e38846c7fbdfd926f467c00808f0641d
[]
no_license
Karim0/wms
https://github.com/Karim0/wms
29fc873bc33131dd51feea536028b859d2291afd
379d004928385ebb4371be9078eca60118e76494
refs/heads/master
2023-03-07T02:06:40.296000
2021-12-08T09:46:09
2021-12-08T09:46:09
188,390,924
0
0
null
false
2023-02-22T07:29:14
2019-05-24T09:11:59
2021-12-08T09:46:31
2023-02-22T07:29:13
991
0
0
1
JavaScript
false
false
package com.iitu.wms.entities; import com.iitu.wms.base.BaseType; import javax.persistence.*; import java.util.Date; @Entity public class TaskEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; @Column(name = "task") private String task; @Column(name = "priority") @Enumerated(EnumType.STRING) private BaseType.PriorityOfExecution priority; @Column(name = "created") private Date created; @Column(name = "done") private Date done; @JoinColumn(name = "usr_id") @ManyToOne(fetch = FetchType.EAGER) private User user; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTask() { return task; } public void setTask(String task) { this.task = task; } public BaseType.PriorityOfExecution getPriority() { return priority; } public void setPriority(BaseType.PriorityOfExecution priority) { this.priority = priority; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getDone() { return done; } public void setDone(Date done) { this.done = done; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
UTF-8
Java
1,449
java
TaskEntity.java
Java
[]
null
[]
package com.iitu.wms.entities; import com.iitu.wms.base.BaseType; import javax.persistence.*; import java.util.Date; @Entity public class TaskEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; @Column(name = "task") private String task; @Column(name = "priority") @Enumerated(EnumType.STRING) private BaseType.PriorityOfExecution priority; @Column(name = "created") private Date created; @Column(name = "done") private Date done; @JoinColumn(name = "usr_id") @ManyToOne(fetch = FetchType.EAGER) private User user; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTask() { return task; } public void setTask(String task) { this.task = task; } public BaseType.PriorityOfExecution getPriority() { return priority; } public void setPriority(BaseType.PriorityOfExecution priority) { this.priority = priority; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getDone() { return done; } public void setDone(Date done) { this.done = done; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
1,449
0.602484
0.602484
80
17.112499
15.580431
68
false
false
0
0
0
0
0
0
0.275
false
false
13
5c8cbeea883243306f484c30f5ededbeba283293
9,311,489,148,395
b83e3507a87edd32a114f3ad5d0659b69a817702
/src/main/java/com/david/equisign/FileUploadResource.java
f9987f0bcbcc15de3e6b45dd8d11b28e4fbba8c7
[]
no_license
dhassoun2021/fileupload
https://github.com/dhassoun2021/fileupload
fe851d48d24636c5df1b66159e77bc4027a70849
68c7391fb7f4094f6246903773f9c60d59dc95e9
refs/heads/main
2023-04-20T11:16:14.573000
2021-05-09T20:57:41
2021-05-09T20:57:41
364,840,486
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.david.equisign; import org.glassfish.jersey.media.multipart.*; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Expose endpoint for upload and download file */ @Path("/equisign") public class FileUploadResource { private BasicConfiguration configuration; private IDataStorage dataStorage; private static final Logger LOG = Logger.getGlobal(); public FileUploadResource (BasicConfiguration configuration, IDataStorage dataStorage) { this.configuration = configuration; this.dataStorage = dataStorage; } @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) @Path("/files") public Response upload ( @FormDataParam("fileData")FormDataContentDisposition contentDisposition, @FormDataParam("fileData")InputStream inputStream, @Context HttpServletRequest request) { try { if (isEmptyFile(inputStream,contentDisposition)) { return Response.status(Response.Status.BAD_REQUEST.getStatusCode(),"File is mandatory").build(); } if (isLimitRequestSizeReached(request)) { return Response.status(Response.Status.BAD_REQUEST.getStatusCode(),"Request size is limited to " + configuration.getMaxSizeRequest() + "octets").build(); } LOG.log(Level.INFO,"Receive file " + contentDisposition.getFileName()); FileInfo fileInfo = dataStorage.saveFile(inputStream,contentDisposition.getFileName()); return Response.ok(fileInfo).build(); } catch (FileUploadException ex) { LOG.log(Level.SEVERE,"Error with upload file " + ex.getMessage()); return Response.serverError().build(); } } private boolean isEmptyFile (InputStream inputStream, FormDataContentDisposition contentDisposition) { return (inputStream == null || contentDisposition.getFileName() == null || contentDisposition.getFileName().trim().length() == 0); } private boolean isLimitRequestSizeReached (HttpServletRequest request) { return (request.getContentLength() > configuration.getMaxSizeRequest()); } @GET @Produces(MediaType.APPLICATION_OCTET_STREAM) @Path("/files/{idFile}") public Response download (@PathParam("idFile") String idFile ) { try { FileInfo fileInfo = dataStorage.readFile(idFile); return Response.ok(fileInfo.getStreamData()).header("content-disposition", "attachment; filename = " + fileInfo.getName()).build(); } catch (DataNotFoundException ex) { LOG.log(Level.SEVERE, "File with id " + idFile + "was not found" + ex.getMessage()); return Response.status(Response.Status.NOT_FOUND).build(); } catch (FileUploadException ex) { LOG.log(Level.SEVERE, "Error with download file " + idFile + " " + ex.getMessage()); ex.printStackTrace(); return Response.serverError().build(); } } }
UTF-8
Java
3,262
java
FileUploadResource.java
Java
[]
null
[]
package com.david.equisign; import org.glassfish.jersey.media.multipart.*; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Expose endpoint for upload and download file */ @Path("/equisign") public class FileUploadResource { private BasicConfiguration configuration; private IDataStorage dataStorage; private static final Logger LOG = Logger.getGlobal(); public FileUploadResource (BasicConfiguration configuration, IDataStorage dataStorage) { this.configuration = configuration; this.dataStorage = dataStorage; } @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) @Path("/files") public Response upload ( @FormDataParam("fileData")FormDataContentDisposition contentDisposition, @FormDataParam("fileData")InputStream inputStream, @Context HttpServletRequest request) { try { if (isEmptyFile(inputStream,contentDisposition)) { return Response.status(Response.Status.BAD_REQUEST.getStatusCode(),"File is mandatory").build(); } if (isLimitRequestSizeReached(request)) { return Response.status(Response.Status.BAD_REQUEST.getStatusCode(),"Request size is limited to " + configuration.getMaxSizeRequest() + "octets").build(); } LOG.log(Level.INFO,"Receive file " + contentDisposition.getFileName()); FileInfo fileInfo = dataStorage.saveFile(inputStream,contentDisposition.getFileName()); return Response.ok(fileInfo).build(); } catch (FileUploadException ex) { LOG.log(Level.SEVERE,"Error with upload file " + ex.getMessage()); return Response.serverError().build(); } } private boolean isEmptyFile (InputStream inputStream, FormDataContentDisposition contentDisposition) { return (inputStream == null || contentDisposition.getFileName() == null || contentDisposition.getFileName().trim().length() == 0); } private boolean isLimitRequestSizeReached (HttpServletRequest request) { return (request.getContentLength() > configuration.getMaxSizeRequest()); } @GET @Produces(MediaType.APPLICATION_OCTET_STREAM) @Path("/files/{idFile}") public Response download (@PathParam("idFile") String idFile ) { try { FileInfo fileInfo = dataStorage.readFile(idFile); return Response.ok(fileInfo.getStreamData()).header("content-disposition", "attachment; filename = " + fileInfo.getName()).build(); } catch (DataNotFoundException ex) { LOG.log(Level.SEVERE, "File with id " + idFile + "was not found" + ex.getMessage()); return Response.status(Response.Status.NOT_FOUND).build(); } catch (FileUploadException ex) { LOG.log(Level.SEVERE, "Error with download file " + idFile + " " + ex.getMessage()); ex.printStackTrace(); return Response.serverError().build(); } } }
3,262
0.678725
0.678418
86
36.930233
38.481281
168
false
false
0
0
0
0
0
0
0.581395
false
false
13
e19bb7dce049f8799c43e0cda3172f136e820900
16,655,883,178,068
a693f32e752f26f20df4711ffc499174c8a92d08
/src/main/java/com/ane/inf/weigh/dao/impl/WeighMapperImpl.java
a5c379afe98b6da3154e6c2ff5aae0dbcafc567a
[]
no_license
ydch10086/ane-inf
https://github.com/ydch10086/ane-inf
de3ac9517deb52ca43bcc27355421de03b67978e
7f3afb2c1d8917172771d3fb892b806447818bac
refs/heads/master
2018-03-20T05:11:19.268000
2016-09-03T08:36:28
2016-09-03T08:36:30
67,277,442
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @Title: WeighMapperImpl.java * @Package com.ane.inf.weigh.dao.impl * @Description: TODO * Copyright: Copyright (c) 2011 * Company:*****信息技术有限责任公司 * * @author Comsys-xuanning * @date 2016年6月12日 下午6:37:02 * @version V1.0 */ package com.ane.inf.weigh.dao.impl; import java.util.List; import org.springframework.stereotype.Repository; import com.ane.dao.impl.BaseMapperImpl; import com.ane.entity.WeighEntityVO; import com.ane.inf.weigh.dao.IWeighMapper; import com.ane.inf.weigh.entity.EwbInfo4Weigh; /** * @ClassName: WeighMapperImpl * @Description: TODO * @author Comsys-xuanning * @date 2016年6月12日 下午6:37:02 */ @Repository("weighRepo") public class WeighMapperImpl extends BaseMapperImpl<WeighEntityVO, Integer> implements IWeighMapper{ private final static Class<IWeighMapper> weigh = IWeighMapper.class; /** * <p>Title: getClass4NameSpace</p> * <p>Description: </p> * @return * @see com.ane.dao.IBaseMapper#getClass4NameSpace() */ @Override public Class<?> getClass4NameSpace() { return weigh; } /** * <p>Title: batchUpdateEwbInfo</p> * <p>Description: </p> * @param ewbInfoLst * @return * @see com.ane.inf.weigh.dao.IWeighMapper#batchUpdateEwbInfo(java.util.List) */ @Override public boolean batchUpdateEwbInfo(List<EwbInfo4Weigh> ewbInfoLst) { return this.getSqlSession().getMapper(weigh).batchUpdateEwbInfo(ewbInfoLst); } }
UTF-8
Java
1,454
java
WeighMapperImpl.java
Java
[ { "context": "c) 2011 \n * Company:*****信息技术有限责任公司\n * \n * @author Comsys-xuanning\n * @date 2016年6月12日 下午6:37:02\n * @version V1.0\n *", "end": 188, "score": 0.7707504034042358, "start": 173, "tag": "USERNAME", "value": "Comsys-xuanning" }, { "context": ": WeighMapperImpl\n * @Desc...
null
[]
/** * @Title: WeighMapperImpl.java * @Package com.ane.inf.weigh.dao.impl * @Description: TODO * Copyright: Copyright (c) 2011 * Company:*****信息技术有限责任公司 * * @author Comsys-xuanning * @date 2016年6月12日 下午6:37:02 * @version V1.0 */ package com.ane.inf.weigh.dao.impl; import java.util.List; import org.springframework.stereotype.Repository; import com.ane.dao.impl.BaseMapperImpl; import com.ane.entity.WeighEntityVO; import com.ane.inf.weigh.dao.IWeighMapper; import com.ane.inf.weigh.entity.EwbInfo4Weigh; /** * @ClassName: WeighMapperImpl * @Description: TODO * @author Comsys-xuanning * @date 2016年6月12日 下午6:37:02 */ @Repository("weighRepo") public class WeighMapperImpl extends BaseMapperImpl<WeighEntityVO, Integer> implements IWeighMapper{ private final static Class<IWeighMapper> weigh = IWeighMapper.class; /** * <p>Title: getClass4NameSpace</p> * <p>Description: </p> * @return * @see com.ane.dao.IBaseMapper#getClass4NameSpace() */ @Override public Class<?> getClass4NameSpace() { return weigh; } /** * <p>Title: batchUpdateEwbInfo</p> * <p>Description: </p> * @param ewbInfoLst * @return * @see com.ane.inf.weigh.dao.IWeighMapper#batchUpdateEwbInfo(java.util.List) */ @Override public boolean batchUpdateEwbInfo(List<EwbInfo4Weigh> ewbInfoLst) { return this.getSqlSession().getMapper(weigh).batchUpdateEwbInfo(ewbInfoLst); } }
1,454
0.718529
0.693777
60
22.566668
22.929869
100
false
false
0
0
0
0
0
0
0.666667
false
false
13
8669df5e710fe49d030580e9cadc82aca9ea6cb7
28,338,194,223,215
a5c3c09f1580f27f359a7ae7bc03dc543844bc0b
/branches/testJudge/src/Main.java
880bd8486537887d070a2f412d32ab15a4f82639
[]
no_license
jackzhao-mj/CDOJ
https://github.com/jackzhao-mj/CDOJ
cd2d58fb91154c49335b787a17cb30ca4ff2c096
00929be72e0cc5b083a59a19243c817420104efe
refs/heads/master
2021-01-18T18:07:00.723000
2015-05-03T09:36:43
2015-05-03T09:36:43
35,310,175
2
0
null
true
2015-05-09T01:38:15
2015-05-09T01:38:14
2015-05-03T09:38:38
2015-05-03T09:38:37
76,747
0
0
0
null
null
null
import java.io.*; import java.util.*; /** * Test for <strong>modified</strong> old judge. * <p/> * <strong>BEFORE TESTING</strong> * <ul> * <li> * Set temp path in <strong>judge.properties</strong> file. * </li> * <li> * Copy data files into <strong>temp/data</strong> path, classify the data files by problem name. * </li> * <li> * Copy code files into <strong>temp/codes</strong> path, classify the codes by user name. * </li> * <li> * Copy <strong>judge core file</strong> into <strong>temp/bin</strong> path. * </li> * </ul> * <p/> * <strong>DATA SETTING</strong> * Data score = 100 / number of cases * If 100 <strong>Mod</strong> cases is not 0, divide the score down to nearest integer. * * @author <a href="mailto:lyhypacm@gmail.com">fish</a> */ public class Main { // store problem's test case list. private static Map<String, List<String>> problemMap = new HashMap<>(); // store user's codes by user name, and we identify the codes by name. private static Map<String, Map<String, String>> codeMap = new HashMap<>(); private static String judgeCoreLocation; @SuppressWarnings("UnusedDeclaration") private static String temporaryPath; private static String dataPath; private static final Result[] JUDGE_RESULT = new Result[]{ Result.CompilationError, Result.Accepted, Result.PresentationError, Result.TimeLimitExceeded, Result.MemoryLimitExceeded, Result.WrongAnswer, Result.OutputLimitExceeded, Result.CompilationError, Result.RuntimeError, Result.RuntimeError, Result.RuntimeError, Result.RuntimeError, Result.SystemError, Result.RuntimeError, Result.SystemError, Result.RuntimeError }; public static void main(String[] args) { try { init(); // System.out.println("=======List start======="); // listAllProblems(); // listAllCodes(); // System.out.println("========List end========"); } catch (Exception e) { e.printStackTrace(); return; } judge(); } /** * List all codes' information, including the users' name * and their codes' name and their codes' path. */ @SuppressWarnings("UnusedDeclaration") private static void listAllCodes() { for (String key : codeMap.keySet()) { Map<String, String> map = codeMap.get(key); System.out.println(key + ": " + map.size()); for (String name : map.keySet()) { System.out.println(" " + name + ": " + map.get(name)); } System.out.println(); } } /** * List all problems' information, including problems' name and their test cases' path. */ @SuppressWarnings("UnusedDeclaration") private static void listAllProblems() { for (String key : problemMap.keySet()) { List<String> list = problemMap.get(key); System.out.println(key + ": " + list.size()); for (String value : list) { System.out.println(" " + value); } System.out.println(); } } /** * Judge all the codes in the <strong>data</strong> folder. */ private static void judge() { System.out.println("==========judge begin=========="); for (String user : codeMap.keySet()) { System.out.println("current user: " + user); int userScore = 0; for (String problem : problemMap.keySet()) { List<String> testCases = problemMap.get(problem); int totalScore = 0, scorePerCase = testCases.size() == 0 ? 0 : 100 / testCases.size(); System.out.println(" problem: " + problem); System.out.print(" "); boolean first = true; boolean nullCode = false; boolean compileError = false; for (String testCase : testCases) { Result result; if (nullCode) result = Result.NullCode; else if (compileError) result = Result.CompilationError; else result = judgeTestCase(codeMap.get(user), problem, testCase, first); first = false; if (result == Result.NullCode) nullCode = true; if (result == Result.CompilationError) compileError = true; switch (result) { case Accepted: System.out.print('A'); totalScore += scorePerCase; break; case WrongAnswer: System.out.print('W'); break; case TimeLimitExceeded: System.out.print('T'); break; case RuntimeError: System.out.print('R'); break; case CompilationError: System.out.print('C'); break; case SystemError: System.out.print("S"); break; case PresentationError: System.out.print("P"); break; case MemoryLimitExceeded: System.out.print("M"); break; case OutputLimitExceeded: System.out.print("O"); break; case NullCode: default: System.out.print('.'); break; } // System.out.println(result); } userScore += totalScore; System.out.println(" " + totalScore); } System.out.println(" score: " + userScore); } System.out.println("===========judge end==========="); } /** * Judge a simple test case according to the coder's code information and problem's information. * * @param codes code list * @param problem problem name * @param testCase test case's <strong>absolute</strong> path * @return result of judge core returns */ @SuppressWarnings({"UnusedAssignment", "UnusedDeclaration"}) private static Result judgeTestCase(Map<String, String> codes, String problem, String testCase, boolean isFirstCase) { String sourceFile; if (codes.get(problem) == null) return Result.NullCode; else sourceFile = codes.get(problem); Runtime runtime = Runtime.getRuntime(); int userId = 1; int problemId = 1; int timeLimit = 2000; int memoryLimit = 65535; int outputLimit = 8192; boolean isSpj = false; int languageId = 2; // C++ String inputFile = testCase + ".in"; String outputFile = testCase + ".out"; try { Process process = runtime.exec(buildCommand(userId, sourceFile, problemId, dataPath, temporaryPath, timeLimit, memoryLimit, outputLimit, isSpj, languageId, inputFile, outputFile, isFirstCase)); InputStream inputStream = process.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } String[] result = stringBuilder.toString().split(" "); // System.out.print("result:"); // for (String s : result) // System.out.print(" " + s); // System.out.println(); if (result != null && result.length >= 3) { try { return JUDGE_RESULT[Integer.valueOf(result[0])]; } catch (Exception e) { return Result.SystemError; } } else return Result.SystemError; } catch (Exception e) { e.printStackTrace(); return Result.SystemError; } } /** * Build the pylon core judging command line content. * * @return command line content */ private static String buildCommand(int userId, String sourceFile, int problemId, String dataPath, String temporaryPath, int timeLimit, int memoryLimit, int outputLimit, boolean isSpj, int languageId, String inputFile, String outputFile, boolean firstCase) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(judgeCoreLocation); stringBuilder.append("/pyloncore "); stringBuilder.append("-u "); stringBuilder.append(userId); stringBuilder.append(" -s "); stringBuilder.append(sourceFile); stringBuilder.append(" -n "); stringBuilder.append(problemId); stringBuilder.append(" -D "); stringBuilder.append(dataPath); stringBuilder.append(" -d "); stringBuilder.append(temporaryPath); stringBuilder.append(" -t "); stringBuilder.append(timeLimit); stringBuilder.append(" -m "); stringBuilder.append(memoryLimit); stringBuilder.append(" -o "); stringBuilder.append(outputLimit); if (isSpj) stringBuilder.append(" -S"); stringBuilder.append(" -l "); stringBuilder.append(languageId); stringBuilder.append(" -I "); stringBuilder.append(inputFile); stringBuilder.append(" -O "); stringBuilder.append(outputFile); if (firstCase) stringBuilder.append(" -C"); // System.out.println(stringBuilder.toString()); return stringBuilder.toString(); } /** * Initialize properties setting. * * @throws IOException */ private static void init() throws Exception { Properties properties = new Properties(); properties.load(new FileInputStream("judge.properties")); String temporaryPath; // read the property file and find the path for data, codes and judgeCore. temporaryPath = properties.getProperty("path"); dataPath = temporaryPath + "/data"; String codePath = temporaryPath + "/codes"; judgeCoreLocation = temporaryPath + "/bin"; // judge core temporary path Main.temporaryPath = temporaryPath + "/temp"; System.out.println("temporary path: " + temporaryPath); System.out.println("data path: " + dataPath); System.out.println("code path: " + codePath); System.out.println("judge core location: " + judgeCoreLocation); System.out.println("temporary path: " + temporaryPath); // fetch problem data. File dataFile = new File(dataPath); File[] problems = dataFile.listFiles(); assert problems != null; for (File problem : problems) { if (problem.isDirectory()) { // in this case, we fetch a problem directory and the problem name is the directory name. List<String> list = new LinkedList<>(); File[] testCases = problem.listFiles(); assert testCases != null; for (File testCase : testCases) { // we should get the file's absolute path, not the name or relative path // WARN: we only get the input file String file = testCase.getAbsolutePath(); if (file.endsWith(".in")) { file = file.substring(0, file.lastIndexOf('.')); list.add(file); } } problemMap.put(problem.getName(), list); } } // fetch user codes. File codeFile = new File(codePath); File[] codes = codeFile.listFiles(); assert codes != null; for (File code : codes) { if (code.isDirectory()) { Map<String, String> map = new HashMap<>(); File[] sources = code.listFiles(); assert sources != null; for (File source : sources) { map.put(source.getName().substring(0, source.getName().lastIndexOf('.')), source.getAbsolutePath()); } codeMap.put(code.getName(), map); } } } /** * Judge core's return results. */ private static enum Result { Accepted, WrongAnswer, TimeLimitExceeded, MemoryLimitExceeded, RuntimeError, CompilationError, NullCode, SystemError, OutputLimitExceeded, PresentationError } }
UTF-8
Java
13,356
java
Main.java
Java
[ { "context": "to nearest integer.\n *\n * @author <a href=\"mailto:lyhypacm@gmail.com\">fish</a>\n */\npublic class Main {\n // store pr", "end": 763, "score": 0.9999197125434875, "start": 745, "tag": "EMAIL", "value": "lyhypacm@gmail.com" } ]
null
[]
import java.io.*; import java.util.*; /** * Test for <strong>modified</strong> old judge. * <p/> * <strong>BEFORE TESTING</strong> * <ul> * <li> * Set temp path in <strong>judge.properties</strong> file. * </li> * <li> * Copy data files into <strong>temp/data</strong> path, classify the data files by problem name. * </li> * <li> * Copy code files into <strong>temp/codes</strong> path, classify the codes by user name. * </li> * <li> * Copy <strong>judge core file</strong> into <strong>temp/bin</strong> path. * </li> * </ul> * <p/> * <strong>DATA SETTING</strong> * Data score = 100 / number of cases * If 100 <strong>Mod</strong> cases is not 0, divide the score down to nearest integer. * * @author <a href="mailto:<EMAIL>">fish</a> */ public class Main { // store problem's test case list. private static Map<String, List<String>> problemMap = new HashMap<>(); // store user's codes by user name, and we identify the codes by name. private static Map<String, Map<String, String>> codeMap = new HashMap<>(); private static String judgeCoreLocation; @SuppressWarnings("UnusedDeclaration") private static String temporaryPath; private static String dataPath; private static final Result[] JUDGE_RESULT = new Result[]{ Result.CompilationError, Result.Accepted, Result.PresentationError, Result.TimeLimitExceeded, Result.MemoryLimitExceeded, Result.WrongAnswer, Result.OutputLimitExceeded, Result.CompilationError, Result.RuntimeError, Result.RuntimeError, Result.RuntimeError, Result.RuntimeError, Result.SystemError, Result.RuntimeError, Result.SystemError, Result.RuntimeError }; public static void main(String[] args) { try { init(); // System.out.println("=======List start======="); // listAllProblems(); // listAllCodes(); // System.out.println("========List end========"); } catch (Exception e) { e.printStackTrace(); return; } judge(); } /** * List all codes' information, including the users' name * and their codes' name and their codes' path. */ @SuppressWarnings("UnusedDeclaration") private static void listAllCodes() { for (String key : codeMap.keySet()) { Map<String, String> map = codeMap.get(key); System.out.println(key + ": " + map.size()); for (String name : map.keySet()) { System.out.println(" " + name + ": " + map.get(name)); } System.out.println(); } } /** * List all problems' information, including problems' name and their test cases' path. */ @SuppressWarnings("UnusedDeclaration") private static void listAllProblems() { for (String key : problemMap.keySet()) { List<String> list = problemMap.get(key); System.out.println(key + ": " + list.size()); for (String value : list) { System.out.println(" " + value); } System.out.println(); } } /** * Judge all the codes in the <strong>data</strong> folder. */ private static void judge() { System.out.println("==========judge begin=========="); for (String user : codeMap.keySet()) { System.out.println("current user: " + user); int userScore = 0; for (String problem : problemMap.keySet()) { List<String> testCases = problemMap.get(problem); int totalScore = 0, scorePerCase = testCases.size() == 0 ? 0 : 100 / testCases.size(); System.out.println(" problem: " + problem); System.out.print(" "); boolean first = true; boolean nullCode = false; boolean compileError = false; for (String testCase : testCases) { Result result; if (nullCode) result = Result.NullCode; else if (compileError) result = Result.CompilationError; else result = judgeTestCase(codeMap.get(user), problem, testCase, first); first = false; if (result == Result.NullCode) nullCode = true; if (result == Result.CompilationError) compileError = true; switch (result) { case Accepted: System.out.print('A'); totalScore += scorePerCase; break; case WrongAnswer: System.out.print('W'); break; case TimeLimitExceeded: System.out.print('T'); break; case RuntimeError: System.out.print('R'); break; case CompilationError: System.out.print('C'); break; case SystemError: System.out.print("S"); break; case PresentationError: System.out.print("P"); break; case MemoryLimitExceeded: System.out.print("M"); break; case OutputLimitExceeded: System.out.print("O"); break; case NullCode: default: System.out.print('.'); break; } // System.out.println(result); } userScore += totalScore; System.out.println(" " + totalScore); } System.out.println(" score: " + userScore); } System.out.println("===========judge end==========="); } /** * Judge a simple test case according to the coder's code information and problem's information. * * @param codes code list * @param problem problem name * @param testCase test case's <strong>absolute</strong> path * @return result of judge core returns */ @SuppressWarnings({"UnusedAssignment", "UnusedDeclaration"}) private static Result judgeTestCase(Map<String, String> codes, String problem, String testCase, boolean isFirstCase) { String sourceFile; if (codes.get(problem) == null) return Result.NullCode; else sourceFile = codes.get(problem); Runtime runtime = Runtime.getRuntime(); int userId = 1; int problemId = 1; int timeLimit = 2000; int memoryLimit = 65535; int outputLimit = 8192; boolean isSpj = false; int languageId = 2; // C++ String inputFile = testCase + ".in"; String outputFile = testCase + ".out"; try { Process process = runtime.exec(buildCommand(userId, sourceFile, problemId, dataPath, temporaryPath, timeLimit, memoryLimit, outputLimit, isSpj, languageId, inputFile, outputFile, isFirstCase)); InputStream inputStream = process.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } String[] result = stringBuilder.toString().split(" "); // System.out.print("result:"); // for (String s : result) // System.out.print(" " + s); // System.out.println(); if (result != null && result.length >= 3) { try { return JUDGE_RESULT[Integer.valueOf(result[0])]; } catch (Exception e) { return Result.SystemError; } } else return Result.SystemError; } catch (Exception e) { e.printStackTrace(); return Result.SystemError; } } /** * Build the pylon core judging command line content. * * @return command line content */ private static String buildCommand(int userId, String sourceFile, int problemId, String dataPath, String temporaryPath, int timeLimit, int memoryLimit, int outputLimit, boolean isSpj, int languageId, String inputFile, String outputFile, boolean firstCase) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(judgeCoreLocation); stringBuilder.append("/pyloncore "); stringBuilder.append("-u "); stringBuilder.append(userId); stringBuilder.append(" -s "); stringBuilder.append(sourceFile); stringBuilder.append(" -n "); stringBuilder.append(problemId); stringBuilder.append(" -D "); stringBuilder.append(dataPath); stringBuilder.append(" -d "); stringBuilder.append(temporaryPath); stringBuilder.append(" -t "); stringBuilder.append(timeLimit); stringBuilder.append(" -m "); stringBuilder.append(memoryLimit); stringBuilder.append(" -o "); stringBuilder.append(outputLimit); if (isSpj) stringBuilder.append(" -S"); stringBuilder.append(" -l "); stringBuilder.append(languageId); stringBuilder.append(" -I "); stringBuilder.append(inputFile); stringBuilder.append(" -O "); stringBuilder.append(outputFile); if (firstCase) stringBuilder.append(" -C"); // System.out.println(stringBuilder.toString()); return stringBuilder.toString(); } /** * Initialize properties setting. * * @throws IOException */ private static void init() throws Exception { Properties properties = new Properties(); properties.load(new FileInputStream("judge.properties")); String temporaryPath; // read the property file and find the path for data, codes and judgeCore. temporaryPath = properties.getProperty("path"); dataPath = temporaryPath + "/data"; String codePath = temporaryPath + "/codes"; judgeCoreLocation = temporaryPath + "/bin"; // judge core temporary path Main.temporaryPath = temporaryPath + "/temp"; System.out.println("temporary path: " + temporaryPath); System.out.println("data path: " + dataPath); System.out.println("code path: " + codePath); System.out.println("judge core location: " + judgeCoreLocation); System.out.println("temporary path: " + temporaryPath); // fetch problem data. File dataFile = new File(dataPath); File[] problems = dataFile.listFiles(); assert problems != null; for (File problem : problems) { if (problem.isDirectory()) { // in this case, we fetch a problem directory and the problem name is the directory name. List<String> list = new LinkedList<>(); File[] testCases = problem.listFiles(); assert testCases != null; for (File testCase : testCases) { // we should get the file's absolute path, not the name or relative path // WARN: we only get the input file String file = testCase.getAbsolutePath(); if (file.endsWith(".in")) { file = file.substring(0, file.lastIndexOf('.')); list.add(file); } } problemMap.put(problem.getName(), list); } } // fetch user codes. File codeFile = new File(codePath); File[] codes = codeFile.listFiles(); assert codes != null; for (File code : codes) { if (code.isDirectory()) { Map<String, String> map = new HashMap<>(); File[] sources = code.listFiles(); assert sources != null; for (File source : sources) { map.put(source.getName().substring(0, source.getName().lastIndexOf('.')), source.getAbsolutePath()); } codeMap.put(code.getName(), map); } } } /** * Judge core's return results. */ private static enum Result { Accepted, WrongAnswer, TimeLimitExceeded, MemoryLimitExceeded, RuntimeError, CompilationError, NullCode, SystemError, OutputLimitExceeded, PresentationError } }
13,345
0.527254
0.524708
332
39.228916
24.795586
115
false
false
0
0
0
0
0
0
0.695783
false
false
13
1b120d72622b72404824049682cfd2251ce42ce1
2,362,232,015,473
13cc1464dce1ab93629dd78991776a371a5a779a
/core/src/br/com/wfstudio/jogatina/vo/Status.java
1c4cfc74fee5f5297aacd063a64e3f5ca4f64740
[]
no_license
pandabr/jogatina
https://github.com/pandabr/jogatina
7ec4d6739776ff9266ffef0f5680ae103f3f2113
41f8a85fcf0d127b4976d622f81149e63934a248
refs/heads/master
2016-09-12T09:04:56.129000
2016-04-29T21:03:39
2016-04-29T21:03:39
56,005,359
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.wfstudio.jogatina.vo; /** * Created by root on 13/04/16. */ public class Status { private int id; private String nome; public Status(String nome) { this.nome = nome; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } }
UTF-8
Java
455
java
Status.java
Java
[ { "context": "ge br.com.wfstudio.jogatina.vo;\n\n/**\n * Created by root on 13/04/16.\n */\npublic class Status {\n privat", "end": 60, "score": 0.9811950922012329, "start": 56, "tag": "USERNAME", "value": "root" } ]
null
[]
package br.com.wfstudio.jogatina.vo; /** * Created by root on 13/04/16. */ public class Status { private int id; private String nome; public Status(String nome) { this.nome = nome; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } }
455
0.547253
0.534066
29
14.689655
12.841483
38
false
false
0
0
0
0
0
0
0.275862
false
false
13
83d0135853a46566951852ea44534ce08bc432ff
2,920,577,771,266
0b1b89d4695e877c0193905340ce956239f7c5e1
/app/src/main/java/ph/codeia/archbooster/MainActivity.java
25bc4653f61c03e10a5d93740daa991391ae1215
[ "MIT" ]
permissive
monzee/archbooster
https://github.com/monzee/archbooster
f295929519a15c39338e5233e91020c14b814f15
13600efbe1455c004af58c8ce2175503e53946b1
refs/heads/master
2020-04-25T19:55:07.411000
2019-03-07T02:20:02
2019-03-07T02:20:02
173,037,308
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ph.codeia.archbooster; /* * This file is a part of the arch-booster project. */ import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
UTF-8
Java
395
java
MainActivity.java
Java
[]
null
[]
package ph.codeia.archbooster; /* * This file is a part of the arch-booster project. */ import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
395
0.739241
0.739241
18
20.944445
22.041557
56
false
false
0
0
0
0
0
0
0.277778
false
false
13
8e23db04ec51fdac1977ae3bb95a75fb22e1c1c0
24,395,414,254,028
dc6e555273beec95891a4111d1a43d4d557c28a7
/src/org/thothlab/devilsvault/dao/employee/InternalUserDaoImpl.java
c3b39e2c87b775bee8bbc10f146ace5308761520
[]
no_license
amankhatri2008/RussianRouletteWithBlockChainBTC
https://github.com/amankhatri2008/RussianRouletteWithBlockChainBTC
8945c1071a0534edf4ce3487079da9561dd1399d
a03423f4dc0057da1f4e7205fff8bc29c3842b81
refs/heads/master
2020-03-26T03:03:43.528000
2018-08-12T12:24:27
2018-08-12T12:24:27
144,437,869
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.thothlab.devilsvault.dao.employee; import java.math.BigInteger; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import org.thothlab.devilsvault.db.model.InternalUserRegister; @Repository ("EmployeeDAOForInternal") public class InternalUserDaoImpl implements InternalUserDao { private JdbcTemplate jdbcTemplate; @SuppressWarnings("unused") private DataSource dataSource; @Autowired public void setdataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplate = new JdbcTemplate(dataSource); } public Integer getUserId(String email) { String query = "SELECT id from internal_user where email= '" + email + "'"; Integer id = jdbcTemplate.queryForList(query, Integer.class).get(0); return id; } public InternalUserRegister getUserById(int user_id) { String query = "SELECT * from internal_user where id= '" + user_id + "'"; InternalUserRegister user = new InternalUserRegister(); List<InternalUserRegister> user_list = new ArrayList<InternalUserRegister>(); user_list = jdbcTemplate.query(query, new BeanPropertyRowMapper<InternalUserRegister>(InternalUserRegister.class)); if(user_list.size()>0){ user = user_list.get(0); } return user; } public String getEmailID(Integer userID) { String query = "SELECT email from internal_user where id= '" + userID + "'"; String email = jdbcTemplate.queryForList(query, String.class).get(0); return email; } public Boolean save(InternalUserRegister userdetails) { String query = "INSERT INTO internal_user ( name , phone , email , password,country ,created_date,referUser) VALUES (?,?,?,?,?,?,?)"; Connection con = null; PreparedStatement ps = null; try{ con = dataSource.getConnection(); ps = con.prepareStatement(query); ps.setString(1, userdetails.getName()); ps.setString(2, userdetails.getPhone()); ps.setString(3, userdetails.getEmail()); ps.setString(4, userdetails.getPassword()); ps.setString(5, userdetails.getCountry()); java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime()); ps.setTimestamp(6, date); ps.setString(7, userdetails.getReferUser()); int out = ps.executeUpdate(); if(out !=0){ return true; }else return false; }catch(SQLException e){ e.printStackTrace(); }finally{ try { ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } }
UTF-8
Java
3,242
java
InternalUserDaoImpl.java
Java
[]
null
[]
package org.thothlab.devilsvault.dao.employee; import java.math.BigInteger; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import org.thothlab.devilsvault.db.model.InternalUserRegister; @Repository ("EmployeeDAOForInternal") public class InternalUserDaoImpl implements InternalUserDao { private JdbcTemplate jdbcTemplate; @SuppressWarnings("unused") private DataSource dataSource; @Autowired public void setdataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplate = new JdbcTemplate(dataSource); } public Integer getUserId(String email) { String query = "SELECT id from internal_user where email= '" + email + "'"; Integer id = jdbcTemplate.queryForList(query, Integer.class).get(0); return id; } public InternalUserRegister getUserById(int user_id) { String query = "SELECT * from internal_user where id= '" + user_id + "'"; InternalUserRegister user = new InternalUserRegister(); List<InternalUserRegister> user_list = new ArrayList<InternalUserRegister>(); user_list = jdbcTemplate.query(query, new BeanPropertyRowMapper<InternalUserRegister>(InternalUserRegister.class)); if(user_list.size()>0){ user = user_list.get(0); } return user; } public String getEmailID(Integer userID) { String query = "SELECT email from internal_user where id= '" + userID + "'"; String email = jdbcTemplate.queryForList(query, String.class).get(0); return email; } public Boolean save(InternalUserRegister userdetails) { String query = "INSERT INTO internal_user ( name , phone , email , password,country ,created_date,referUser) VALUES (?,?,?,?,?,?,?)"; Connection con = null; PreparedStatement ps = null; try{ con = dataSource.getConnection(); ps = con.prepareStatement(query); ps.setString(1, userdetails.getName()); ps.setString(2, userdetails.getPhone()); ps.setString(3, userdetails.getEmail()); ps.setString(4, userdetails.getPassword()); ps.setString(5, userdetails.getCountry()); java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime()); ps.setTimestamp(6, date); ps.setString(7, userdetails.getReferUser()); int out = ps.executeUpdate(); if(out !=0){ return true; }else return false; }catch(SQLException e){ e.printStackTrace(); }finally{ try { ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } }
3,242
0.652992
0.649291
97
32.42268
27.885567
143
false
false
0
0
0
0
0
0
1.113402
false
false
13
8b67eeb4400d4442e827fa53cbec0bbc8c76e029
15,728,170,297,679
1da26831e5ec3a5de77959148cfacf30bcd2697c
/src/main/java/hw6/DataProperties.java
1aa3b029c22b0760fb9b0bb5354e02ef2512c099
[]
no_license
Olesya24/OlesyaSashko
https://github.com/Olesya24/OlesyaSashko
fcaa488579a6cfb50e9d31f3995268ab84ac4ea0
2b3ba243e408d53259d4f24040d9d1fd1d3132ff
refs/heads/master
2021-05-20T22:59:30.234000
2020-05-31T12:06:37
2020-05-31T12:06:37
252,445,596
0
0
null
false
2020-05-31T12:06:38
2020-04-02T12:13:21
2020-04-29T19:24:19
2020-05-31T12:06:37
72
0
0
0
Java
false
false
package hw6; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class DataProperties { private static Properties dataProperties; static { dataProperties = new Properties(); try{ InputStream input = new FileInputStream("src/test/resources/hw6/config.properties"); dataProperties.load(input); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static Properties getDataProperty(){ return dataProperties; } }
UTF-8
Java
702
java
DataProperties.java
Java
[]
null
[]
package hw6; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class DataProperties { private static Properties dataProperties; static { dataProperties = new Properties(); try{ InputStream input = new FileInputStream("src/test/resources/hw6/config.properties"); dataProperties.load(input); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static Properties getDataProperty(){ return dataProperties; } }
702
0.659544
0.656695
28
24.071428
21.021976
96
false
false
0
0
0
0
0
0
0.464286
false
false
13
35d1539f788995d151384232404704dc3d520adc
4,853,313,111,345
e85063ddac66956caf1346ae42f463280048001f
/source/eu.artist.migration.mut.cmm/eu.artist.premigration.tft.scc/src/eu/artist/premigration/tft/scc/util/CSExplorer.java
fa6f0d8ba705a67521aea3e302683b2599eef03c
[]
no_license
artist-project/ARTIST-MUT
https://github.com/artist-project/ARTIST-MUT
bac4743fb3b357cb3b8d1e15f448808edfec20bd
e02fe62c117baf536fe19e8ac5d4e6371b27d37f
refs/heads/master
2021-01-10T13:55:30.676000
2015-06-04T06:50:54
2015-06-04T06:50:54
36,853,504
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package eu.artist.premigration.tft.scc.util; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import eu.artist.premigration.tft.scc.structures.Method; import eu.artist.premigration.tft.scc.structures.SourceFile; public class CSExplorer implements ClassExplorer{ private List<String> noMethodList = Arrays.asList(new String[]{"namespace", "class", "while", "using", "if", "for", "else", "get", "set", "try", "catch", "finally", "switch", "foreach", "do"}); public SourceFile findMethodsParser(File file) throws Exception{ return findMethodsParser(file, null); } public SourceFile findMethodsParser(File file, ArrayList<Integer> lines) throws Exception{ SourceFile sf; sf =getMethods(file, lines); sf.setName(file.getName()); sf.setPath(file.getPath()); //TODO set package return sf; } private SourceFile getMethods (File file, ArrayList<Integer> lines) throws Exception{ Scanner scanner = new Scanner(file); String line=""; int linNumber=0; SourceFile retorno= new SourceFile(); retorno.setTotalyReusable("true"); boolean insideMethod=false; Method obj= new Method(); int keyNum=0; while(scanner.hasNext()) { linNumber++; line=scanner.nextLine(); int linePos=line.indexOf("{"); if(linePos>=0) { if (insideMethod){ keyNum++; } if (checkLine(line)){ String name=getMethodName(line); if (!name.equals("")){ insideMethod=true; obj.setName(name); System.out.println("Method Name: "+name); obj.setBline(""+linNumber); System.out.println("Beginline: "+linNumber); keyNum++; } } } if (insideMethod){ linePos=line.indexOf("}"); if(linePos>=0){ keyNum--; if (keyNum==0){ insideMethod=false; obj.setEline(""+linNumber); System.out.println("Endline: "+linNumber); String reusable= "true"; if (lines!=null){ for (Integer lin: lines){ if (lin>Integer.parseInt(obj.getBline())&&lin<linNumber){ reusable="false"; System.out.println("Not reusable!!"); retorno.setTotalyReusable("false"); } } } obj.setReusable(reusable); retorno.addLinea(obj); obj= new Method(); } } } linePos=line.indexOf("namespace"); if(linePos>=0){ retorno.setPackageName(line.substring(linePos+10,line.length()-2)); } } return retorno; } private boolean checkLine(String line){ boolean retorno=true; if (line.indexOf("\"")>=0){ return false; } for (String str :noMethodList){ if (line.indexOf(str+" ")>=0){ return false; } if (line.indexOf(str+"(")>=0){ return false; } if (line.indexOf(str+"{")>=0){ return false; } } return retorno; } private String getMethodName(String line){ String retorno=""; int end= line.indexOf("("); if (end>=0){ line=line.substring(0, end); int begin=line.lastIndexOf(" "); retorno=line.substring(begin+1); } return retorno; } }
UTF-8
Java
3,289
java
CSExplorer.java
Java
[]
null
[]
package eu.artist.premigration.tft.scc.util; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import eu.artist.premigration.tft.scc.structures.Method; import eu.artist.premigration.tft.scc.structures.SourceFile; public class CSExplorer implements ClassExplorer{ private List<String> noMethodList = Arrays.asList(new String[]{"namespace", "class", "while", "using", "if", "for", "else", "get", "set", "try", "catch", "finally", "switch", "foreach", "do"}); public SourceFile findMethodsParser(File file) throws Exception{ return findMethodsParser(file, null); } public SourceFile findMethodsParser(File file, ArrayList<Integer> lines) throws Exception{ SourceFile sf; sf =getMethods(file, lines); sf.setName(file.getName()); sf.setPath(file.getPath()); //TODO set package return sf; } private SourceFile getMethods (File file, ArrayList<Integer> lines) throws Exception{ Scanner scanner = new Scanner(file); String line=""; int linNumber=0; SourceFile retorno= new SourceFile(); retorno.setTotalyReusable("true"); boolean insideMethod=false; Method obj= new Method(); int keyNum=0; while(scanner.hasNext()) { linNumber++; line=scanner.nextLine(); int linePos=line.indexOf("{"); if(linePos>=0) { if (insideMethod){ keyNum++; } if (checkLine(line)){ String name=getMethodName(line); if (!name.equals("")){ insideMethod=true; obj.setName(name); System.out.println("Method Name: "+name); obj.setBline(""+linNumber); System.out.println("Beginline: "+linNumber); keyNum++; } } } if (insideMethod){ linePos=line.indexOf("}"); if(linePos>=0){ keyNum--; if (keyNum==0){ insideMethod=false; obj.setEline(""+linNumber); System.out.println("Endline: "+linNumber); String reusable= "true"; if (lines!=null){ for (Integer lin: lines){ if (lin>Integer.parseInt(obj.getBline())&&lin<linNumber){ reusable="false"; System.out.println("Not reusable!!"); retorno.setTotalyReusable("false"); } } } obj.setReusable(reusable); retorno.addLinea(obj); obj= new Method(); } } } linePos=line.indexOf("namespace"); if(linePos>=0){ retorno.setPackageName(line.substring(linePos+10,line.length()-2)); } } return retorno; } private boolean checkLine(String line){ boolean retorno=true; if (line.indexOf("\"")>=0){ return false; } for (String str :noMethodList){ if (line.indexOf(str+" ")>=0){ return false; } if (line.indexOf(str+"(")>=0){ return false; } if (line.indexOf(str+"{")>=0){ return false; } } return retorno; } private String getMethodName(String line){ String retorno=""; int end= line.indexOf("("); if (end>=0){ line=line.substring(0, end); int begin=line.lastIndexOf(" "); retorno=line.substring(begin+1); } return retorno; } }
3,289
0.594102
0.589237
135
23.362963
24.327276
194
false
false
0
0
0
0
0
0
3.02963
false
false
13
df54c95e9052b49eb810bb0532ad9b7071b1003e
12,541,304,518,753
ec40410d3b8983073a42566d83a32471bd1864d0
/clientapp/src/main/java/module-info.java
c0fcf3ccb3e9b38c26de680e8c64acd4d7c9443a
[]
no_license
kmprograms/httpclientexample
https://github.com/kmprograms/httpclientexample
6dc3cd574ef35929a194cfc882ae21b1555e8220
8fffd87df9dead956020b7ccfcfa8910dee7f141
refs/heads/master
2020-05-03T01:10:15.280000
2019-03-29T04:04:16
2019-03-29T04:04:16
178,329,999
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
module clientapp { requires java.net.http; requires java.sql; requires gson; opens pl.kmprograms.model; }
UTF-8
Java
123
java
module-info.java
Java
[]
null
[]
module clientapp { requires java.net.http; requires java.sql; requires gson; opens pl.kmprograms.model; }
123
0.674797
0.674797
8
14.5
11.61895
30
false
false
0
0
0
0
0
0
0.5
false
false
13
f5047f947e79ee65b6247788b91d92891831af78
17,300,128,333,985
e42ddb71e522abff17906490e2e74960a7372e0a
/workspace/上交实验代码/实验2-RMI/src/com/acj/rmi/server/Student.java
72230a56b1e79761663da822b9dbf0cdabbeb0a9
[]
no_license
IACJ/java-DistributedComputing
https://github.com/IACJ/java-DistributedComputing
8b60da5fb6297beb745c740f5546553a99749fa2
15015707b82be5543436a964461ec042f4e64776
refs/heads/master
2021-05-16T10:01:56.232000
2017-12-09T17:05:17
2017-12-09T17:05:17
104,639,235
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.acj.rmi.server; public class Student implements java.io.Serializable{ /** * */ private static final long serialVersionUID = 1L; private Long id; private String name; private int grade; public Student() { super(); } public Student(Long i, String name, int grade) { super(); this.id = i; this.name = name; this.grade = grade; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", grade=" + grade + "]"; } }
UTF-8
Java
803
java
Student.java
Java
[]
null
[]
package com.acj.rmi.server; public class Student implements java.io.Serializable{ /** * */ private static final long serialVersionUID = 1L; private Long id; private String name; private int grade; public Student() { super(); } public Student(Long i, String name, int grade) { super(); this.id = i; this.name = name; this.grade = grade; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", grade=" + grade + "]"; } }
803
0.617684
0.616438
46
16.456522
16.329098
75
false
false
0
0
0
0
0
0
1.5
false
false
13
53e122066d141393289fec8f53b0e9fcf03644ad
8,005,819,107,732
2622ac0a7542d14a4e36661868293d3c62c0d8d5
/Computer.java
1a83de6cf9b3cc96918900c042c22ee2b53610cd
[]
no_license
yaswaantr/week3.day1
https://github.com/yaswaantr/week3.day1
cb65462ff81ef456942f4b9bcff47c6d72a0f1f7
cac7587aa0eb923d88da3d09f6935abe8916c6dd
refs/heads/main
2023-08-18T21:42:17.557000
2021-09-20T14:31:41
2021-09-20T14:31:41
408,475,872
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.system; public class Computer { public void computerModel() { System.out.println("Below are the Computer Models available with us: " + '\n' + "Brand : HP Pavillion 1505" + '\n' + "Brand : Lenovo NoteBook15" + '\n' + "Brand : Dell 1545" + '\n' + "Brand : Sony Vaio 800"); } /* * public static void main(String[] args) { // TODO Auto-generated method stub * * } */ }
UTF-8
Java
415
java
Computer.java
Java
[]
null
[]
package org.system; public class Computer { public void computerModel() { System.out.println("Below are the Computer Models available with us: " + '\n' + "Brand : HP Pavillion 1505" + '\n' + "Brand : Lenovo NoteBook15" + '\n' + "Brand : Dell 1545" + '\n' + "Brand : Sony Vaio 800"); } /* * public static void main(String[] args) { // TODO Auto-generated method stub * * } */ }
415
0.590361
0.559036
17
22.529411
36.112762
109
false
false
0
0
0
0
0
0
0.882353
false
false
13
bafc3ca29666886550af3836b9b9b005980b56f3
26,379,689,201,610
926509a8e9bca10c29d92e89e7ae9d45b5514c52
/src/main/java/com/hrg/pyh/common/utils/Page.java
c84c19c8ae50a9d96c68cdab0ded08d139db883c
[]
no_license
zt422680855/pyh
https://github.com/zt422680855/pyh
477f10be945ec8655ee59e33eef7d2b2e6c8cdb3
319740f68f3fc987bad6d0e78598e15f7a5df221
refs/heads/master
2020-05-27T19:22:48.276000
2019-05-27T02:48:40
2019-05-27T02:48:40
188,760,184
0
0
null
false
2020-07-01T23:13:42
2019-05-27T02:48:22
2019-05-27T02:48:51
2020-07-01T23:13:41
153
0
0
2
Java
false
false
package com.hrg.pyh.common.utils; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.List; /** * 分页数据封装 * * @author zhengtao * @version 2018年1月30日 * @see Page * @since */ @Getter @Setter public class Page<T> implements Serializable { private static final long serialVersionUID = 1L; /** 总记录数 */ private long totalCount; /** 每页记录数 */ private int pageSize; /** 总页数 */ private int totalPage; /** 当前页数 */ private int currPage; /** 列表数据 */ private List<T> list; /** * 分页查询结果返回封装 * * @param list 列表数据 * @param totalCount 总记录数 * @param pageSize 每页记录数 * @param currPage 当前页数 */ public Page(List<T> list, long totalCount, int pageSize, int currPage) { this.list = list; this.totalCount = totalCount; this.pageSize = pageSize; this.currPage = currPage; this.totalPage = (int) Math.ceil((double) totalCount / pageSize); } }
UTF-8
Java
1,128
java
Page.java
Java
[ { "context": "port java.util.List;\n\n/**\n * 分页数据封装\n * \n * @author zhengtao\n * @version 2018年1月30日\n * @see Page\n * @since\n */", "end": 170, "score": 0.9722996950149536, "start": 162, "tag": "USERNAME", "value": "zhengtao" } ]
null
[]
package com.hrg.pyh.common.utils; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.List; /** * 分页数据封装 * * @author zhengtao * @version 2018年1月30日 * @see Page * @since */ @Getter @Setter public class Page<T> implements Serializable { private static final long serialVersionUID = 1L; /** 总记录数 */ private long totalCount; /** 每页记录数 */ private int pageSize; /** 总页数 */ private int totalPage; /** 当前页数 */ private int currPage; /** 列表数据 */ private List<T> list; /** * 分页查询结果返回封装 * * @param list 列表数据 * @param totalCount 总记录数 * @param pageSize 每页记录数 * @param currPage 当前页数 */ public Page(List<T> list, long totalCount, int pageSize, int currPage) { this.list = list; this.totalCount = totalCount; this.pageSize = pageSize; this.currPage = currPage; this.totalPage = (int) Math.ceil((double) totalCount / pageSize); } }
1,128
0.602362
0.594488
54
17.814816
17.238066
76
false
false
0
0
0
0
0
0
0.351852
false
false
13
f73400945bac2586019497c0d774ba4c3dbeaaa9
19,980,187,870,284
0cedd8386a93ae17042d5b4fbc85f7cba35f4197
/TestProject/src/com/wear/testproject/impl/IWatchListener.java
7806811d2c6b5479429eb1db644f6d6a02be17de
[]
no_license
ljwshigood/Xiaogoududu
https://github.com/ljwshigood/Xiaogoududu
2ae0c78e10af1f2cff7bc6d9aca673fe28980d43
0d36c5af93a738fdc1b6972880907e13205a5047
refs/heads/master
2021-01-10T08:11:49.696000
2016-04-03T06:37:10
2016-04-03T06:37:10
55,113,118
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wear.testproject.impl; import com.wear.testproject.bean.ListenerBean; public interface IWatchListener { public void searchListen(ListenerBean bean); }
UTF-8
Java
168
java
IWatchListener.java
Java
[]
null
[]
package com.wear.testproject.impl; import com.wear.testproject.bean.ListenerBean; public interface IWatchListener { public void searchListen(ListenerBean bean); }
168
0.809524
0.809524
8
20
19.962465
46
false
false
0
0
0
0
0
0
0.625
false
false
13
9bfb85ba67f266b9b65862d2dd094bbc42fd6fcb
27,908,697,498,761
3aedbc595d1fe9e4e5ec5f1ec16478fcd5304232
/Registro_Usuarios/src/registro_usuarios/Ventana.java
4c735a00de7c617a16d3b27385394720afc51958
[]
no_license
RafaelUrena/EntornoGrafico
https://github.com/RafaelUrena/EntornoGrafico
17f783104910623300559f8037a047099a3e88c5
a04a43bb745733c052105053d08e86ab4f4383bd
refs/heads/master
2020-03-16T11:45:44.516000
2018-05-08T19:35:24
2018-05-08T19:35:24
132,654,277
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 registro_usuarios; import java.util.LinkedList; import javax.swing.table.DefaultTableModel; /** * * @author the_d */ public class Ventana extends javax.swing.JFrame { /** * Creates new form Ventana */ public Ventana() { initComponents(); this.lista = new LinkedList<>(); this.cBcargo.addItem("Analista"); this.cBcargo.addItem("Programador"); this.cBcargo.addItem("Diseñador"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); cTdni = new javax.swing.JTextField(); cTnombre = new javax.swing.JTextField(); eDni = new javax.swing.JLabel(); eNombre = new javax.swing.JLabel(); cBcargo = new javax.swing.JComboBox<>(); cSedad = new javax.swing.JSpinner(); eEdad = new javax.swing.JLabel(); eCargo = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); rBsoltero = new javax.swing.JRadioButton(); rBcasado = new javax.swing.JRadioButton(); bAnadir = new javax.swing.JButton(); bVerdni = new javax.swing.JButton(); bBorrarperson = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); eDni.setText("DNI"); eNombre.setText("Nombre"); eEdad.setText("Edad"); eCargo.setText("Cargo"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Estado civil")); buttonGroup1.add(rBsoltero); rBsoltero.setText("Soltero"); buttonGroup1.add(rBcasado); rBcasado.setText("Casado"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(rBsoltero) .addComponent(rBcasado)) .addContainerGap(66, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(rBsoltero) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(rBcasado) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); bAnadir.setText("Añadir"); bAnadir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bAnadirActionPerformed(evt); } }); bVerdni.setText("Ver DNI seleccionado"); bVerdni.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bVerdniActionPerformed(evt); } }); bBorrarperson.setText("Borrar persona"); bBorrarperson.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bBorrarpersonActionPerformed(evt); } }); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "DNI", "Nombre", "Estado", "Edad", "Cargo" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane2.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(34, 34, 34) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(eEdad) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cSedad, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(eDni) .addComponent(eNombre)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cTnombre) .addComponent(cTdni, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(eCargo) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(bAnadir)) .addGroup(layout.createSequentialGroup() .addGap(7, 7, 7) .addComponent(cBcargo, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(11, 11, 11)))))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(bVerdni) .addGap(56, 56, 56) .addComponent(bBorrarperson, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(35, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(51, 51, 51) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cTdni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(eDni)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cTnombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(eNombre)) .addGap(26, 26, 26) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(17, 17, 17) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bVerdni) .addComponent(bBorrarperson) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(eEdad) .addComponent(cSedad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(9, 9, 9) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cBcargo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(eCargo)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(bAnadir) .addContainerGap(17, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void bVerdniActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bVerdniActionPerformed Persona p = this.lista.get(this.jTable1.getSelectedRow()); Ventana1 v1 = new Ventana1(p); v1.setVisible(true); System.out.println(p); }//GEN-LAST:event_bVerdniActionPerformed private void bAnadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAnadirActionPerformed Persona p = new Persona(); Object filan[] = new Object[5]; if(this.comprobarCampos()){ if(this.estaDni()){ javax.swing.JOptionPane.showMessageDialog(null, "El DNI ya se encuentra en la lista", "DNI Duplicado", javax.swing.JOptionPane.ERROR_MESSAGE); } else { p.setCargo((String) this.cBcargo.getSelectedItem()); p.setDni(this.cTdni.getText()); p.setEdad((int) this.cSedad.getValue()); if(this.rBcasado.isSelected()){ p.setEstado("Casado"); } else { p.setEstado("Soltero"); } p.setNombre(this.cTnombre.getText()); DefaultTableModel m = (DefaultTableModel) jTable1.getModel(); filan[0] = p.getDni(); filan[1] = p.getNombre(); filan[2] = p.getEstado(); filan[3] = p.getEdad(); filan[4] = p.getCargo(); m.addRow(filan); this.jTable1.setModel(m); this.lista.add(p); } } else { javax.swing.JOptionPane.showMessageDialog(null, "Debe rellenar todos los datos", "ERROR", javax.swing.JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_bAnadirActionPerformed private void bBorrarpersonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBorrarpersonActionPerformed int index = this.jTable1.getSelectedRow(); this.lista.remove(index); DefaultTableModel m = (DefaultTableModel) jTable1.getModel(); m.removeRow(index); this.jTable1.setModel(m); }//GEN-LAST:event_bBorrarpersonActionPerformed private boolean comprobarCampos(){ boolean estanDatos = true; if(this.eDni.getText().trim().length() <= 0){ estanDatos = false; } if(this.cTnombre.getText().trim().length() <= 0){ estanDatos = false; } if(!this.rBcasado.isSelected() && !this.rBsoltero.isSelected()){ estanDatos = false; } return estanDatos; } private boolean estaDni(){ boolean esta = false; for(Persona p : this.lista){ if(p.getDni().equals(this.cTdni.getText())){ esta = true; } } return esta; } /** * @param args the command line arguments */ LinkedList<Persona> lista; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bAnadir; private javax.swing.JButton bBorrarperson; private javax.swing.JButton bVerdni; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JComboBox<String> cBcargo; private javax.swing.JSpinner cSedad; private javax.swing.JTextField cTdni; private javax.swing.JTextField cTnombre; private javax.swing.JLabel eCargo; private javax.swing.JLabel eDni; private javax.swing.JLabel eEdad; private javax.swing.JLabel eNombre; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JRadioButton rBcasado; private javax.swing.JRadioButton rBsoltero; // End of variables declaration//GEN-END:variables }
UTF-8
Java
14,976
java
Ventana.java
Java
[ { "context": ".swing.table.DefaultTableModel;\n\n/**\n *\n * @author the_d\n */\npublic class Ventana extends javax.swing.JFra", "end": 310, "score": 0.9994945526123047, "start": 305, "tag": "USERNAME", "value": "the_d" } ]
null
[]
/* * 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 registro_usuarios; import java.util.LinkedList; import javax.swing.table.DefaultTableModel; /** * * @author the_d */ public class Ventana extends javax.swing.JFrame { /** * Creates new form Ventana */ public Ventana() { initComponents(); this.lista = new LinkedList<>(); this.cBcargo.addItem("Analista"); this.cBcargo.addItem("Programador"); this.cBcargo.addItem("Diseñador"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); cTdni = new javax.swing.JTextField(); cTnombre = new javax.swing.JTextField(); eDni = new javax.swing.JLabel(); eNombre = new javax.swing.JLabel(); cBcargo = new javax.swing.JComboBox<>(); cSedad = new javax.swing.JSpinner(); eEdad = new javax.swing.JLabel(); eCargo = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); rBsoltero = new javax.swing.JRadioButton(); rBcasado = new javax.swing.JRadioButton(); bAnadir = new javax.swing.JButton(); bVerdni = new javax.swing.JButton(); bBorrarperson = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); eDni.setText("DNI"); eNombre.setText("Nombre"); eEdad.setText("Edad"); eCargo.setText("Cargo"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Estado civil")); buttonGroup1.add(rBsoltero); rBsoltero.setText("Soltero"); buttonGroup1.add(rBcasado); rBcasado.setText("Casado"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(rBsoltero) .addComponent(rBcasado)) .addContainerGap(66, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(rBsoltero) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(rBcasado) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); bAnadir.setText("Añadir"); bAnadir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bAnadirActionPerformed(evt); } }); bVerdni.setText("Ver DNI seleccionado"); bVerdni.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bVerdniActionPerformed(evt); } }); bBorrarperson.setText("Borrar persona"); bBorrarperson.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bBorrarpersonActionPerformed(evt); } }); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "DNI", "Nombre", "Estado", "Edad", "Cargo" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane2.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(34, 34, 34) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(eEdad) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cSedad, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(eDni) .addComponent(eNombre)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cTnombre) .addComponent(cTdni, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(eCargo) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(bAnadir)) .addGroup(layout.createSequentialGroup() .addGap(7, 7, 7) .addComponent(cBcargo, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(11, 11, 11)))))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(bVerdni) .addGap(56, 56, 56) .addComponent(bBorrarperson, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(35, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(51, 51, 51) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cTdni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(eDni)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cTnombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(eNombre)) .addGap(26, 26, 26) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(17, 17, 17) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bVerdni) .addComponent(bBorrarperson) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(eEdad) .addComponent(cSedad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(9, 9, 9) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cBcargo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(eCargo)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(bAnadir) .addContainerGap(17, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void bVerdniActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bVerdniActionPerformed Persona p = this.lista.get(this.jTable1.getSelectedRow()); Ventana1 v1 = new Ventana1(p); v1.setVisible(true); System.out.println(p); }//GEN-LAST:event_bVerdniActionPerformed private void bAnadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAnadirActionPerformed Persona p = new Persona(); Object filan[] = new Object[5]; if(this.comprobarCampos()){ if(this.estaDni()){ javax.swing.JOptionPane.showMessageDialog(null, "El DNI ya se encuentra en la lista", "DNI Duplicado", javax.swing.JOptionPane.ERROR_MESSAGE); } else { p.setCargo((String) this.cBcargo.getSelectedItem()); p.setDni(this.cTdni.getText()); p.setEdad((int) this.cSedad.getValue()); if(this.rBcasado.isSelected()){ p.setEstado("Casado"); } else { p.setEstado("Soltero"); } p.setNombre(this.cTnombre.getText()); DefaultTableModel m = (DefaultTableModel) jTable1.getModel(); filan[0] = p.getDni(); filan[1] = p.getNombre(); filan[2] = p.getEstado(); filan[3] = p.getEdad(); filan[4] = p.getCargo(); m.addRow(filan); this.jTable1.setModel(m); this.lista.add(p); } } else { javax.swing.JOptionPane.showMessageDialog(null, "Debe rellenar todos los datos", "ERROR", javax.swing.JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_bAnadirActionPerformed private void bBorrarpersonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBorrarpersonActionPerformed int index = this.jTable1.getSelectedRow(); this.lista.remove(index); DefaultTableModel m = (DefaultTableModel) jTable1.getModel(); m.removeRow(index); this.jTable1.setModel(m); }//GEN-LAST:event_bBorrarpersonActionPerformed private boolean comprobarCampos(){ boolean estanDatos = true; if(this.eDni.getText().trim().length() <= 0){ estanDatos = false; } if(this.cTnombre.getText().trim().length() <= 0){ estanDatos = false; } if(!this.rBcasado.isSelected() && !this.rBsoltero.isSelected()){ estanDatos = false; } return estanDatos; } private boolean estaDni(){ boolean esta = false; for(Persona p : this.lista){ if(p.getDni().equals(this.cTdni.getText())){ esta = true; } } return esta; } /** * @param args the command line arguments */ LinkedList<Persona> lista; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bAnadir; private javax.swing.JButton bBorrarperson; private javax.swing.JButton bVerdni; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JComboBox<String> cBcargo; private javax.swing.JSpinner cSedad; private javax.swing.JTextField cTdni; private javax.swing.JTextField cTnombre; private javax.swing.JLabel eCargo; private javax.swing.JLabel eDni; private javax.swing.JLabel eEdad; private javax.swing.JLabel eNombre; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JRadioButton rBcasado; private javax.swing.JRadioButton rBsoltero; // End of variables declaration//GEN-END:variables }
14,976
0.600374
0.591626
310
47.303226
36.972855
175
false
false
0
0
0
0
0
0
0.629032
false
false
13
9f15ce86aabf97e8f10b97c5dff5e3ed463c728e
6,717,328,864,047
01684203045b41b00ca063217dba4041eacee83a
/gouge-model/src/main/java/com/gouge/dao/mapper/SwingNotepadMapper.java
72171ca3dc1951a757cb819685bfc06383555eae
[]
no_license
heganfeng/project-gouge
https://github.com/heganfeng/project-gouge
487259c07846d3445bd1e27b9d43b6c7ba8d12ab
d9c2d1e19402e0ad2108ed5d0dd75c60944da67d
refs/heads/master
2020-03-27T07:03:11.331000
2018-08-26T07:15:41
2018-08-26T07:15:41
146,159,054
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gouge.dao.mapper; import com.gouge.dao.entity.SwingNotepad; public interface SwingNotepadMapper { int deleteByPrimaryKey(String id); int insert(SwingNotepad record); int insertSelective(SwingNotepad record); SwingNotepad selectByPrimaryKey(String id); int updateByPrimaryKeySelective(SwingNotepad record); int updateByPrimaryKeyWithBLOBs(SwingNotepad record); int updateByPrimaryKey(SwingNotepad record); }
UTF-8
Java
454
java
SwingNotepadMapper.java
Java
[]
null
[]
package com.gouge.dao.mapper; import com.gouge.dao.entity.SwingNotepad; public interface SwingNotepadMapper { int deleteByPrimaryKey(String id); int insert(SwingNotepad record); int insertSelective(SwingNotepad record); SwingNotepad selectByPrimaryKey(String id); int updateByPrimaryKeySelective(SwingNotepad record); int updateByPrimaryKeyWithBLOBs(SwingNotepad record); int updateByPrimaryKey(SwingNotepad record); }
454
0.786344
0.786344
19
22.947369
22.551634
57
false
false
0
0
0
0
0
0
0.473684
false
false
13
86b6ca118a4b05b7423daab56cd768da80cf9ab7
12,386,685,691,636
32f764519351db4ba041a71f47e95efc7d5ca6ec
/fastDFSConsumer/src/main/java/com/yuw/consumer/controller/FastDFSController.java
7057cf9ec51f8215dad80295291bf8602c8f0aec
[]
no_license
XiFYuW/fastDFS-examples
https://github.com/XiFYuW/fastDFS-examples
1a8ac0ced326f03bc8d3936b251ca2b76dca2065
1a3fcfc73c4733a95819422884706e891a3fbda4
refs/heads/master
2022-08-19T05:16:09.769000
2019-10-18T02:02:35
2019-10-18T02:02:35
209,946,819
0
0
null
false
2022-06-17T02:32:54
2019-09-21T07:57:40
2019-10-18T02:01:20
2022-06-17T02:32:54
28
0
0
2
Java
false
false
package com.yuw.consumer.controller; import com.yuw.consumer.service.FastDFSService; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @author https://github.com/XiFYuW * @date 2019/9/21 10:07 */ @RestController public class FastDFSController { @Resource FastDFSService fastDFSService; @RequestMapping("/common/hello/{name}") public String index(@PathVariable("name") String name) { return fastDFSService.hello(name); } @RequestMapping(value = "/common/upload") public String index() { return fastDFSService.upload(); } }
UTF-8
Java
756
java
FastDFSController.java
Java
[ { "context": "tion.Resource;\n\n/**\n * @author https://github.com/XiFYuW\n * @date 2019/9/21 10:07\n */\n@RestController\npubl", "end": 349, "score": 0.9994952082633972, "start": 343, "tag": "USERNAME", "value": "XiFYuW" } ]
null
[]
package com.yuw.consumer.controller; import com.yuw.consumer.service.FastDFSService; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @author https://github.com/XiFYuW * @date 2019/9/21 10:07 */ @RestController public class FastDFSController { @Resource FastDFSService fastDFSService; @RequestMapping("/common/hello/{name}") public String index(@PathVariable("name") String name) { return fastDFSService.hello(name); } @RequestMapping(value = "/common/upload") public String index() { return fastDFSService.upload(); } }
756
0.738095
0.723545
29
25.068966
21.703218
62
false
false
0
0
0
0
0
0
0.310345
false
false
13
01ae8d48975a4758c0f6a3cb938e8b0042c1770b
18,605,798,355,047
149007c623a3e8925b700573f0d7b5bb3e637985
/src/ManejadorJugadores/JugManager.java
e3db36cd078f918d07d8d99bd8ac2bfe7eef2e09
[]
no_license
GR-Ramirez/ProyectosRecuperados
https://github.com/GR-Ramirez/ProyectosRecuperados
9b4d7adda36bf670a406848502cef5e8493cb8ba
e161a5fd5b4533caf5b144395155315d4edffb4d
refs/heads/master
2021-01-16T18:29:49.586000
2011-06-21T06:21:14
2011-06-21T06:21:14
1,927,681
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ManejadorJugadores; import java.io.*; import java.util.ArrayList; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author Owner */ public class JugManager { RandomAccessFile raf; public JugManager(){ try{ raf= new RandomAccessFile("Jugadores.uno","rw"); } catch(IOException io){ } } public void addJugador(String nom,char genero, byte edad){ try{ if(buscarJugador(nom)==-1){ raf.seek(raf.length()); raf.writeBoolean(true); raf.writeUTF(nom); raf.writeByte(edad); raf.writeChar(genero); raf.writeInt(0);//ganes raf.writeInt(0);//perdidas raf.writeInt(0);//record punto raf.writeInt(0);//puntostotal } else JOptionPane.showMessageDialog(null, "Los nombres de los jugadores deben ser únicos", "Nombre ya tomado", JOptionPane.ERROR_MESSAGE); } catch(IOException io){ System.err.println(io.getMessage()); } } public void desactivarJugador(String nom){ try{ long aBorrar= buscarJugador(nom); if(aBorrar!=-1){ raf.seek(aBorrar); raf.writeBoolean(false); } } catch(IOException io){ System.err.println(io.getMessage()); } } public long buscarJugador(String nombre){ long pos= 0; try{ raf.seek(0); while(raf.length()>raf.getFilePointer()){ pos= raf.getFilePointer(); boolean valido= raf.readBoolean(); if(nombre.equals(raf.readUTF())&&valido) return pos; raf.seek(raf.getFilePointer()+19); } return -1; } catch(IOException io){ System.err.println(); return -1; } } public JugInfo[] getJugadores(){ ArrayList<JugInfo> info= new ArrayList(0); try{ raf.seek(0); while(raf.getFilePointer()<raf.length()){ if(raf.readBoolean()) info.add(getJI(raf.readUTF())); else{ raf.readUTF(); raf.seek(raf.getFilePointer()+19); } } info.trimToSize(); JugInfo[] estaraElErrorAqui= info.toArray(new JugInfo[0]); return estaraElErrorAqui; } catch(IOException io){ System.err.println(io.getMessage()); return null; } } public JugInfo getJI(String nombre){ JugInfo j= new JugInfo(); long aqui= buscarJugador(nombre); if(aqui!=-1){ try{ raf.seek(aqui); raf.readBoolean(); j.nombre=raf.readUTF(); j.edad= raf.readByte(); j.genero= raf.readChar(); j.ganes= raf.readInt(); j.perdidas= raf.readInt(); j.record= raf.readInt(); j.puntosHistoria= raf.readInt(); return j; } catch(IOException io){ System.err.println(io.getMessage()); return null; } } else{ JOptionPane.showMessageDialog(null, "No existe este jugador.", "No existe", JOptionPane.ERROR_MESSAGE); return null; } } public void cerrarStream(){ if(raf!=null) try { raf.close(); } catch (IOException ex) { Logger.getLogger(JugManager.class.getName()).log(Level.SEVERE, null, ex); } } public String[] getSoloNombres(JugInfo[] fuente){ String[] copia= new String[fuente.length]; for(int o=0; o<copia.length; o++) copia[o]= fuente[o].nombre; return copia; } public String[] getSoloNombres(){ JugInfo[] fuente= getJugadores(); String[] copia= new String[fuente.length]; for(int o=0; o<copia.length; o++) copia[o]= fuente[o].nombre; return copia; } }
UTF-8
Java
4,566
java
JugManager.java
Java
[ { "context": "mport javax.swing.JOptionPane;\n\n\n/**\n *\n * @author Owner\n */\npublic class JugManager {\n RandomAccessFil", "end": 324, "score": 0.5049141049385071, "start": 319, "tag": "USERNAME", "value": "Owner" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ManejadorJugadores; import java.io.*; import java.util.ArrayList; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author Owner */ public class JugManager { RandomAccessFile raf; public JugManager(){ try{ raf= new RandomAccessFile("Jugadores.uno","rw"); } catch(IOException io){ } } public void addJugador(String nom,char genero, byte edad){ try{ if(buscarJugador(nom)==-1){ raf.seek(raf.length()); raf.writeBoolean(true); raf.writeUTF(nom); raf.writeByte(edad); raf.writeChar(genero); raf.writeInt(0);//ganes raf.writeInt(0);//perdidas raf.writeInt(0);//record punto raf.writeInt(0);//puntostotal } else JOptionPane.showMessageDialog(null, "Los nombres de los jugadores deben ser únicos", "Nombre ya tomado", JOptionPane.ERROR_MESSAGE); } catch(IOException io){ System.err.println(io.getMessage()); } } public void desactivarJugador(String nom){ try{ long aBorrar= buscarJugador(nom); if(aBorrar!=-1){ raf.seek(aBorrar); raf.writeBoolean(false); } } catch(IOException io){ System.err.println(io.getMessage()); } } public long buscarJugador(String nombre){ long pos= 0; try{ raf.seek(0); while(raf.length()>raf.getFilePointer()){ pos= raf.getFilePointer(); boolean valido= raf.readBoolean(); if(nombre.equals(raf.readUTF())&&valido) return pos; raf.seek(raf.getFilePointer()+19); } return -1; } catch(IOException io){ System.err.println(); return -1; } } public JugInfo[] getJugadores(){ ArrayList<JugInfo> info= new ArrayList(0); try{ raf.seek(0); while(raf.getFilePointer()<raf.length()){ if(raf.readBoolean()) info.add(getJI(raf.readUTF())); else{ raf.readUTF(); raf.seek(raf.getFilePointer()+19); } } info.trimToSize(); JugInfo[] estaraElErrorAqui= info.toArray(new JugInfo[0]); return estaraElErrorAqui; } catch(IOException io){ System.err.println(io.getMessage()); return null; } } public JugInfo getJI(String nombre){ JugInfo j= new JugInfo(); long aqui= buscarJugador(nombre); if(aqui!=-1){ try{ raf.seek(aqui); raf.readBoolean(); j.nombre=raf.readUTF(); j.edad= raf.readByte(); j.genero= raf.readChar(); j.ganes= raf.readInt(); j.perdidas= raf.readInt(); j.record= raf.readInt(); j.puntosHistoria= raf.readInt(); return j; } catch(IOException io){ System.err.println(io.getMessage()); return null; } } else{ JOptionPane.showMessageDialog(null, "No existe este jugador.", "No existe", JOptionPane.ERROR_MESSAGE); return null; } } public void cerrarStream(){ if(raf!=null) try { raf.close(); } catch (IOException ex) { Logger.getLogger(JugManager.class.getName()).log(Level.SEVERE, null, ex); } } public String[] getSoloNombres(JugInfo[] fuente){ String[] copia= new String[fuente.length]; for(int o=0; o<copia.length; o++) copia[o]= fuente[o].nombre; return copia; } public String[] getSoloNombres(){ JugInfo[] fuente= getJugadores(); String[] copia= new String[fuente.length]; for(int o=0; o<copia.length; o++) copia[o]= fuente[o].nombre; return copia; } }
4,566
0.489157
0.484775
167
26.335329
18.174013
85
false
false
0
0
0
0
0
0
0.508982
false
false
13
9ae4912f077180bba324216f1d4dd062a88c2a73
9,397,388,456,562
c2cd7285461cfb2a7456bfb1a54d9e2c06b39bd3
/HastaTakipSistemi/src/hastatakipsist/sekreter_idrar_tahlil.java
76af63d4a7b1a8b4a02ff76c58a9a1037c34f687
[]
no_license
DilNi/HastaTakipSistemi
https://github.com/DilNi/HastaTakipSistemi
5852e21a3cb7f1a3fa0562812b62c654e1f13320
2250853af810097154da68e85d998ae22a7aa56f
refs/heads/main
2023-06-04T12:45:27.964000
2021-06-22T19:55:49
2021-06-22T19:55:49
379,381,130
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hastatakipsist; import Helper.*; import java.awt.Dimension; import java.awt.Toolkit; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; public class sekreter_idrar_tahlil extends javax.swing.JFrame { Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; int columnsNumber = 0; public sekreter_idrar_tahlil() { initComponents(); retrievetableIdrar2(); setSize(1500,700); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2); } private void retrievetableIdrar(String TC) { try { DefaultTableModel tbl = (DefaultTableModel) tbl_idrar.getModel(); while (tbl.getRowCount() > 0) { tbl.removeRow(0); } conn = Helper.db.connection_db(); String sql = "SELECT * FROM IdrarTahlil WHERE TC='" + TC + "'"; pst = conn.prepareStatement(sql); rs = pst.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); columnsNumber = rsmd.getColumnCount(); String[] data = new String[columnsNumber]; while (rs.next()) { for (int i = 0; i < data.length; i++) { data[i] = rs.getString(i + 1); } DefaultTableModel tblModel = (DefaultTableModel) tbl_idrar.getModel(); tblModel.addRow(data); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex); } finally { try { conn.close(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex); } } } private void retrievetableIdrar2() { try { DefaultTableModel tbl = (DefaultTableModel) tbl_idrar.getModel(); while (tbl.getRowCount() > 0) { tbl.removeRow(0); } conn = Helper.db.connection_db(); String sql = "SELECT * FROM IdrarTahlil"; pst = conn.prepareStatement(sql); rs = pst.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); columnsNumber = rsmd.getColumnCount(); String[] data = new String[columnsNumber]; while (rs.next()) { for (int i = 0; i < data.length; i++) { data[i] = rs.getString(i + 1); } DefaultTableModel tblModel = (DefaultTableModel) tbl_idrar.getModel(); tblModel.addRow(data); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex); } finally { try { conn.close(); } catch (Exception ex) { } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane4 = new javax.swing.JScrollPane(); tbl_idrar = new javax.swing.JTable(); jPanel4 = new javax.swing.JPanel(); jLabel20 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); hasta_tc = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); txt_renk = new javax.swing.JTextField(); txt_tarih = new javax.swing.JTextField(); txt_glukoz = new javax.swing.JTextField(); txt_protein = new javax.swing.JTextField(); txt_ph = new javax.swing.JTextField(); txt_dansite = new javax.swing.JTextField(); txt_bilirubin = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); txt_keton = new javax.swing.JTextField(); btn_kayit = new javax.swing.JButton(); btn_sil = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); txt_urobili = new javax.swing.JTextField(); txt_gorunum = new javax.swing.JTextField(); btn_resetle = new javax.swing.JButton(); txt_nitrit = new javax.swing.JTextField(); btn_güncelle = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jLabel28 = new javax.swing.JLabel(); tc_arama = new javax.swing.JTextField(); btn_tcbul = new javax.swing.JButton(); btn_onceki_sayfa = new javax.swing.JButton(); btn_onceki_sayfa1 = new javax.swing.JButton(); jLabel21 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); jPanel1.setBackground(new java.awt.Color(0, 204, 204)); jPanel1.setOpaque(false); jScrollPane4.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION); jScrollPane4.setEnabled(false); tbl_idrar.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null, null, null} }, new String [] { "TC", "Tarih", "Renk", "Görünüm", "Dansite", "pH", "Protein", "Glukoz", "Bilirubin", "Ürobilinojen", "Keton", "Nitrit" } )); tbl_idrar.setAutoscrolls(false); tbl_idrar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); tbl_idrar.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION); tbl_idrar.setIntercellSpacing(new java.awt.Dimension(1, 4)); tbl_idrar.setOpaque(false); tbl_idrar.setRequestFocusEnabled(false); tbl_idrar.getTableHeader().setReorderingAllowed(false); tbl_idrar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbl_idrarMouseClicked(evt); } }); tbl_idrar.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { tbl_idrarPropertyChange(evt); } }); jScrollPane4.setViewportView(tbl_idrar); jPanel4.setOpaque(false); jLabel20.setFont(new java.awt.Font("Sitka Text", 1, 24)); // NOI18N jLabel20.setText("LABORATUVAR İDRAR TAHLİL SONUCU EKLEME"); jPanel5.setOpaque(false); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel10.setText("pH:"); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel11.setText("Tarih:"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel5.setText("Protein:"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel3.setText("TC:"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel6.setText("Dansite:"); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel7.setText("Renk:"); hasta_tc.setToolTipText(""); hasta_tc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hasta_tcActionPerformed(evt); } }); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel8.setText("Görünüm:"); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel12.setText("Glukoz:"); txt_renk.setToolTipText(""); txt_tarih.setToolTipText(""); txt_glukoz.setToolTipText(""); txt_protein.setToolTipText(""); txt_ph.setToolTipText(""); txt_dansite.setToolTipText(""); txt_bilirubin.setToolTipText(""); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel13.setText("Ürobilinojen:"); jLabel15.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel15.setText("Nitrit:"); jLabel16.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel16.setText("Bilirubin:"); txt_keton.setToolTipText(""); btn_kayit.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_kayit.setText("KAYIT "); btn_kayit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_kayitActionPerformed(evt); } }); btn_sil.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_sil.setText("SİL"); btn_sil.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_silActionPerformed(evt); } }); jLabel1.setText("Keton:"); txt_urobili.setToolTipText(""); txt_gorunum.setToolTipText(""); btn_resetle.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_resetle.setText("RESETLE"); btn_resetle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_resetleActionPerformed(evt); } }); txt_nitrit.setToolTipText(""); btn_güncelle.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_güncelle.setText("GÜNCELLE"); btn_güncelle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_güncelleActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(hasta_tc, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_ph, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_keton, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel11) .addComponent(jLabel5) .addComponent(jLabel15)) .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_nitrit, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(btn_güncelle, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43) .addComponent(btn_resetle, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39) .addComponent(btn_sil)) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_tarih, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_protein, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel7) .addComponent(jLabel12)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addComponent(txt_renk, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel8)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(txt_glukoz, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel16))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_bilirubin, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_gorunum, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(14, 14, 14) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txt_dansite, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txt_urobili, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addComponent(btn_kayit, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(13, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(hasta_tc, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(txt_tarih, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11) .addComponent(jLabel7) .addComponent(jLabel8) .addComponent(txt_renk, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(txt_dansite, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_gorunum, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_ph, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(txt_protein, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5) .addComponent(txt_glukoz, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12) .addComponent(txt_bilirubin, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel16) .addComponent(jLabel13) .addComponent(txt_urobili, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_keton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15) .addComponent(jLabel1) .addComponent(txt_nitrit, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_kayit, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_sil, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_resetle, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_güncelle, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(379, 379, 379)) ); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(279, 279, 279) .addComponent(jLabel20)) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(44, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(7, 7, 7) .addComponent(jLabel20) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(50, 50, 50)) ); jPanel3.setOpaque(false); jLabel28.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N jLabel28.setText("TC :"); btn_tcbul.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_tcbul.setText("BUL"); btn_tcbul.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_tcbulActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel28) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(tc_arama, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btn_tcbul) .addContainerGap(48, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel28) .addComponent(tc_arama) .addComponent(btn_tcbul)) .addContainerGap()) ); btn_onceki_sayfa.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_onceki_sayfa.setText("Önceki sayfa"); btn_onceki_sayfa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_onceki_sayfaActionPerformed(evt); } }); btn_onceki_sayfa1.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_onceki_sayfa1.setText("OTURUMU KAPAT"); btn_onceki_sayfa1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_onceki_sayfa1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 1090, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btn_onceki_sayfa, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btn_onceki_sayfa1) .addGap(48, 48, 48))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_onceki_sayfa, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btn_onceki_sayfa1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(45, 45, 45)) ); getContentPane().add(jPanel1); jPanel1.setBounds(170, 30, 1159, 611); jLabel21.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ıcon/Medical+Banner.jpg"))); // NOI18N getContentPane().add(jLabel21); jLabel21.setBounds(0, 0, 1500, 690); pack(); }// </editor-fold>//GEN-END:initComponents private void tbl_idrarPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_tbl_idrarPropertyChange // TODO add your handling code here: }//GEN-LAST:event_tbl_idrarPropertyChange private void hasta_tcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hasta_tcActionPerformed // TODO add your handling code here: }//GEN-LAST:event_hasta_tcActionPerformed private void btn_kayitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_kayitActionPerformed if (hasta_tc.getText().length() == 0 || txt_tarih.getText().length() == 0 || txt_renk.getText().length() == 0 || txt_dansite.getText().length() == 0 || txt_ph.getText().length() == 0 || txt_protein.getText().length() == 0 || txt_glukoz.getText().length() == 0 || txt_bilirubin.getText().length() == 0 || txt_urobili.getText().length() == 0 || txt_keton.getText().length() == 0 || txt_nitrit.getText().length() == 0) { helper.bosluk("fill"); } else { try { String sql = "INSERT INTO IdrarTahlil " + "values(?,?,?,?,?,?,?,?,?,?,?,?)"; conn = db.connection_db(); pst = conn.prepareStatement(sql); pst.setString(1, hasta_tc.getText()); pst.setString(2, txt_tarih.getText()); pst.setString(3, txt_renk.getText()); pst.setString(4, txt_gorunum.getText()); pst.setString(5, txt_dansite.getText()); pst.setString(6, txt_ph.getText()); pst.setString(7, txt_protein.getText()); pst.setString(8, txt_glukoz.getText()); pst.setString(9, txt_bilirubin.getText()); pst.setString(10, txt_urobili.getText()); pst.setString(11, txt_keton.getText()); pst.setString(12, txt_nitrit.getText()); pst.executeUpdate(); retrievetableIdrar2(); JOptionPane.showMessageDialog(null, "KAYIT BAŞARIYLA EKLENDİ."); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } finally { try { resetle(); pst.close(); conn.close(); } catch (Exception e) { } } } }//GEN-LAST:event_btn_kayitActionPerformed private void btn_silActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_silActionPerformed if (!(hasta_tc.getText()).equals("")) { try { conn = db.connection_db(); String sql = "DELETE FROM IdrarTahlil WHERE TC=?"; pst = conn.prepareStatement(sql); pst.setString(1, hasta_tc.getText()); pst.execute(); retrievetableIdrar2(); resetle(); JOptionPane.showMessageDialog(null, "KAYIT SİLİNMİŞTİR !"); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } finally { try { conn.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } } } else { JOptionPane.showMessageDialog(null, "SİLMEK İSTEDİĞİNİZ KAYDI SEÇİNİZ !"); } }//GEN-LAST:event_btn_silActionPerformed private void btn_tcbulActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_tcbulActionPerformed String HastaTC = ""; String data = ""; try { conn = Helper.db.connection_db(); String sql = "SELECT * FROM IdrarTahlil WHERE TC=?"; pst = conn.prepareStatement(sql); pst.setString(1, tc_arama.getText()); rs = pst.executeQuery(); if (rs.next()) { HastaTC = rs.getString("TC"); JOptionPane.showMessageDialog(null, "TC BULUNDU."); } else { JOptionPane.showMessageDialog(null, "TC BULUNAMADI !"); } } catch (Exception ex) { } try { conn.close(); retrievetableIdrar(HastaTC); } catch (Exception ex) { } try { conn = Helper.db.connection_db(); String sql = "SELECT * FROM IdrarTahlil WHERE TC=?"; pst = conn.prepareStatement(sql); pst.setString(1, tc_arama.getText()); rs = pst.executeQuery(); while (rs.next()) { data = rs.getString("TC"); hasta_tc.setText(data); data = rs.getString("Tarih"); txt_tarih.setText(data); data = rs.getString("Renk"); txt_renk.setText(data); data = rs.getString("Görünüm"); txt_gorunum.setText(data); data = rs.getString("Dansite"); txt_dansite.setText(data); data = rs.getString("pH"); txt_ph.setText(data); data = rs.getString("Protein"); txt_protein.setText(data); data = rs.getString("Glukoz"); txt_glukoz.setText(data); data = rs.getString("Bilirubin"); txt_bilirubin.setText(data); data = rs.getString("Ürobilinojen"); txt_urobili.setText(data); data = rs.getString("Keton"); txt_keton.setText(data); data = rs.getString("Nitrit"); txt_nitrit.setText(data); } } catch (Exception ex) { } }//GEN-LAST:event_btn_tcbulActionPerformed public void resetle() { tc_arama.setText(""); hasta_tc.setText(""); txt_tarih.setText(""); txt_renk.setText(""); txt_dansite.setText(""); txt_gorunum.setText(""); txt_ph.setText(""); txt_protein.setText(""); txt_glukoz.setText(""); txt_bilirubin.setText(""); txt_urobili.setText(""); txt_keton.setText(""); txt_nitrit.setText(""); } private void btn_resetleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_resetleActionPerformed resetle(); retrievetableIdrar2(); }//GEN-LAST:event_btn_resetleActionPerformed private void btn_onceki_sayfaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_onceki_sayfaActionPerformed this.dispose(); sekreter_islem_secme s = new sekreter_islem_secme(); s.setVisible(true); }//GEN-LAST:event_btn_onceki_sayfaActionPerformed private void btn_onceki_sayfa1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_onceki_sayfa1ActionPerformed this.dispose(); login l = new login(); l.setVisible(true); }//GEN-LAST:event_btn_onceki_sayfa1ActionPerformed private void tbl_idrarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_idrarMouseClicked int i = tbl_idrar.getSelectedRow(); TableModel model = tbl_idrar.getModel(); hasta_tc.setText(model.getValueAt(i, 0).toString()); txt_tarih.setText(model.getValueAt(i, 1).toString()); txt_renk.setText(model.getValueAt(i, 2).toString()); txt_gorunum.setText(model.getValueAt(i, 3).toString()); txt_dansite.setText(model.getValueAt(i, 4).toString()); txt_ph.setText(model.getValueAt(i, 5).toString()); txt_protein.setText(model.getValueAt(i, 6).toString()); txt_glukoz.setText(model.getValueAt(i, 7).toString()); txt_bilirubin.setText(model.getValueAt(i, 8).toString()); txt_urobili.setText(model.getValueAt(i, 9).toString()); txt_keton.setText(model.getValueAt(i, 10).toString()); txt_nitrit.setText(model.getValueAt(i, 11).toString()); }//GEN-LAST:event_tbl_idrarMouseClicked private void btn_güncelleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_güncelleActionPerformed try { conn = db.connection_db(); String TC = hasta_tc.getText(); String tarih = txt_tarih.getText(); String renk = txt_renk.getText(); String gorunum = txt_gorunum.getText(); String dansite = txt_dansite.getText(); String ph = txt_ph.getText(); String protein = txt_protein.getText(); String glukoz = txt_glukoz.getText(); String bilirubin = txt_bilirubin.getText(); String urobili = txt_urobili.getText(); String keton = txt_keton.getText(); String nitrit = txt_nitrit.getText(); String sql = "UPDATE IdrarTahlil SET TC='" + TC + "',Tarih='" + tarih + "',Renk='" + renk + "'," + "Görünüm='" + gorunum + "',Dansite='" + dansite + "',pH='" + ph + "'," + "Protein='" + protein + "',Glukoz='" + glukoz + "'," + "Bilirubin='" + bilirubin + "',Ürobilinojen='" + urobili + "'," + "Keton='" + keton + "',Nitrit='" + nitrit + "' WHERE TC='" + TC + "'"; pst = conn.prepareStatement(sql); pst.execute(); retrievetableIdrar2(); JOptionPane.showMessageDialog(null, "KAYIT GÜNCELLENMİŞTİR."); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } finally { try { conn.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } } }//GEN-LAST:event_btn_güncelleActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(sekreter_idrar_tahlil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(sekreter_idrar_tahlil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(sekreter_idrar_tahlil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(sekreter_idrar_tahlil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new sekreter_idrar_tahlil().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_güncelle; private javax.swing.JButton btn_kayit; private javax.swing.JButton btn_onceki_sayfa; private javax.swing.JButton btn_onceki_sayfa1; private javax.swing.JButton btn_resetle; private javax.swing.JButton btn_sil; private javax.swing.JButton btn_tcbul; private javax.swing.JTextField hasta_tc; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTable tbl_idrar; private javax.swing.JTextField tc_arama; private javax.swing.JTextField txt_bilirubin; private javax.swing.JTextField txt_dansite; private javax.swing.JTextField txt_glukoz; private javax.swing.JTextField txt_gorunum; private javax.swing.JTextField txt_keton; private javax.swing.JTextField txt_nitrit; private javax.swing.JTextField txt_ph; private javax.swing.JTextField txt_protein; private javax.swing.JTextField txt_renk; private javax.swing.JTextField txt_tarih; private javax.swing.JTextField txt_urobili; // End of variables declaration//GEN-END:variables }
UTF-8
Java
42,518
java
sekreter_idrar_tahlil.java
Java
[ { "context": " // NOI18N\n jLabel20.setText(\"LABORATUVAR İDRAR TAHLİL SONUCU EKLEME\");\n\n jPanel5.setOpaque(fals", "end": 7543, "score": 0.6006916761398315, "start": 7533, "tag": "NAME", "value": "DRAR TAHLİ" }, { "context": "8)); // NOI18N\n btn_onceki_sayfa1...
null
[]
package hastatakipsist; import Helper.*; import java.awt.Dimension; import java.awt.Toolkit; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; public class sekreter_idrar_tahlil extends javax.swing.JFrame { Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; int columnsNumber = 0; public sekreter_idrar_tahlil() { initComponents(); retrievetableIdrar2(); setSize(1500,700); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2); } private void retrievetableIdrar(String TC) { try { DefaultTableModel tbl = (DefaultTableModel) tbl_idrar.getModel(); while (tbl.getRowCount() > 0) { tbl.removeRow(0); } conn = Helper.db.connection_db(); String sql = "SELECT * FROM IdrarTahlil WHERE TC='" + TC + "'"; pst = conn.prepareStatement(sql); rs = pst.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); columnsNumber = rsmd.getColumnCount(); String[] data = new String[columnsNumber]; while (rs.next()) { for (int i = 0; i < data.length; i++) { data[i] = rs.getString(i + 1); } DefaultTableModel tblModel = (DefaultTableModel) tbl_idrar.getModel(); tblModel.addRow(data); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex); } finally { try { conn.close(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex); } } } private void retrievetableIdrar2() { try { DefaultTableModel tbl = (DefaultTableModel) tbl_idrar.getModel(); while (tbl.getRowCount() > 0) { tbl.removeRow(0); } conn = Helper.db.connection_db(); String sql = "SELECT * FROM IdrarTahlil"; pst = conn.prepareStatement(sql); rs = pst.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); columnsNumber = rsmd.getColumnCount(); String[] data = new String[columnsNumber]; while (rs.next()) { for (int i = 0; i < data.length; i++) { data[i] = rs.getString(i + 1); } DefaultTableModel tblModel = (DefaultTableModel) tbl_idrar.getModel(); tblModel.addRow(data); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex); } finally { try { conn.close(); } catch (Exception ex) { } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane4 = new javax.swing.JScrollPane(); tbl_idrar = new javax.swing.JTable(); jPanel4 = new javax.swing.JPanel(); jLabel20 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); hasta_tc = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); txt_renk = new javax.swing.JTextField(); txt_tarih = new javax.swing.JTextField(); txt_glukoz = new javax.swing.JTextField(); txt_protein = new javax.swing.JTextField(); txt_ph = new javax.swing.JTextField(); txt_dansite = new javax.swing.JTextField(); txt_bilirubin = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); txt_keton = new javax.swing.JTextField(); btn_kayit = new javax.swing.JButton(); btn_sil = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); txt_urobili = new javax.swing.JTextField(); txt_gorunum = new javax.swing.JTextField(); btn_resetle = new javax.swing.JButton(); txt_nitrit = new javax.swing.JTextField(); btn_güncelle = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jLabel28 = new javax.swing.JLabel(); tc_arama = new javax.swing.JTextField(); btn_tcbul = new javax.swing.JButton(); btn_onceki_sayfa = new javax.swing.JButton(); btn_onceki_sayfa1 = new javax.swing.JButton(); jLabel21 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); jPanel1.setBackground(new java.awt.Color(0, 204, 204)); jPanel1.setOpaque(false); jScrollPane4.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION); jScrollPane4.setEnabled(false); tbl_idrar.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null, null, null} }, new String [] { "TC", "Tarih", "Renk", "Görünüm", "Dansite", "pH", "Protein", "Glukoz", "Bilirubin", "Ürobilinojen", "Keton", "Nitrit" } )); tbl_idrar.setAutoscrolls(false); tbl_idrar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); tbl_idrar.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION); tbl_idrar.setIntercellSpacing(new java.awt.Dimension(1, 4)); tbl_idrar.setOpaque(false); tbl_idrar.setRequestFocusEnabled(false); tbl_idrar.getTableHeader().setReorderingAllowed(false); tbl_idrar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbl_idrarMouseClicked(evt); } }); tbl_idrar.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { tbl_idrarPropertyChange(evt); } }); jScrollPane4.setViewportView(tbl_idrar); jPanel4.setOpaque(false); jLabel20.setFont(new java.awt.Font("Sitka Text", 1, 24)); // NOI18N jLabel20.setText("LABORATUVAR İ<NAME>L SONUCU EKLEME"); jPanel5.setOpaque(false); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel10.setText("pH:"); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel11.setText("Tarih:"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel5.setText("Protein:"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel3.setText("TC:"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel6.setText("Dansite:"); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel7.setText("Renk:"); hasta_tc.setToolTipText(""); hasta_tc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hasta_tcActionPerformed(evt); } }); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel8.setText("Görünüm:"); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel12.setText("Glukoz:"); txt_renk.setToolTipText(""); txt_tarih.setToolTipText(""); txt_glukoz.setToolTipText(""); txt_protein.setToolTipText(""); txt_ph.setToolTipText(""); txt_dansite.setToolTipText(""); txt_bilirubin.setToolTipText(""); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel13.setText("Ürobilinojen:"); jLabel15.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel15.setText("Nitrit:"); jLabel16.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel16.setText("Bilirubin:"); txt_keton.setToolTipText(""); btn_kayit.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_kayit.setText("KAYIT "); btn_kayit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_kayitActionPerformed(evt); } }); btn_sil.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_sil.setText("SİL"); btn_sil.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_silActionPerformed(evt); } }); jLabel1.setText("Keton:"); txt_urobili.setToolTipText(""); txt_gorunum.setToolTipText(""); btn_resetle.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_resetle.setText("RESETLE"); btn_resetle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_resetleActionPerformed(evt); } }); txt_nitrit.setToolTipText(""); btn_güncelle.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_güncelle.setText("GÜNCELLE"); btn_güncelle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_güncelleActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(hasta_tc, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_ph, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_keton, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel11) .addComponent(jLabel5) .addComponent(jLabel15)) .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_nitrit, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(btn_güncelle, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43) .addComponent(btn_resetle, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39) .addComponent(btn_sil)) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_tarih, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_protein, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel7) .addComponent(jLabel12)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addComponent(txt_renk, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel8)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(txt_glukoz, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel16))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_bilirubin, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_gorunum, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(14, 14, 14) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txt_dansite, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txt_urobili, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addComponent(btn_kayit, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(13, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(hasta_tc, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(txt_tarih, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11) .addComponent(jLabel7) .addComponent(jLabel8) .addComponent(txt_renk, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(txt_dansite, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_gorunum, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_ph, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(txt_protein, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5) .addComponent(txt_glukoz, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12) .addComponent(txt_bilirubin, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel16) .addComponent(jLabel13) .addComponent(txt_urobili, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_keton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15) .addComponent(jLabel1) .addComponent(txt_nitrit, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_kayit, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_sil, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_resetle, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_güncelle, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(379, 379, 379)) ); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(279, 279, 279) .addComponent(jLabel20)) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(44, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(7, 7, 7) .addComponent(jLabel20) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(50, 50, 50)) ); jPanel3.setOpaque(false); jLabel28.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N jLabel28.setText("TC :"); btn_tcbul.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_tcbul.setText("BUL"); btn_tcbul.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_tcbulActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel28) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(tc_arama, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btn_tcbul) .addContainerGap(48, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel28) .addComponent(tc_arama) .addComponent(btn_tcbul)) .addContainerGap()) ); btn_onceki_sayfa.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_onceki_sayfa.setText("Önceki sayfa"); btn_onceki_sayfa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_onceki_sayfaActionPerformed(evt); } }); btn_onceki_sayfa1.setFont(new java.awt.Font("Sitka Text", 0, 18)); // NOI18N btn_onceki_sayfa1.setText("OTURUMU KAPAT"); btn_onceki_sayfa1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_onceki_sayfa1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 1090, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btn_onceki_sayfa, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btn_onceki_sayfa1) .addGap(48, 48, 48))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_onceki_sayfa, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btn_onceki_sayfa1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(45, 45, 45)) ); getContentPane().add(jPanel1); jPanel1.setBounds(170, 30, 1159, 611); jLabel21.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ıcon/Medical+Banner.jpg"))); // NOI18N getContentPane().add(jLabel21); jLabel21.setBounds(0, 0, 1500, 690); pack(); }// </editor-fold>//GEN-END:initComponents private void tbl_idrarPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_tbl_idrarPropertyChange // TODO add your handling code here: }//GEN-LAST:event_tbl_idrarPropertyChange private void hasta_tcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hasta_tcActionPerformed // TODO add your handling code here: }//GEN-LAST:event_hasta_tcActionPerformed private void btn_kayitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_kayitActionPerformed if (hasta_tc.getText().length() == 0 || txt_tarih.getText().length() == 0 || txt_renk.getText().length() == 0 || txt_dansite.getText().length() == 0 || txt_ph.getText().length() == 0 || txt_protein.getText().length() == 0 || txt_glukoz.getText().length() == 0 || txt_bilirubin.getText().length() == 0 || txt_urobili.getText().length() == 0 || txt_keton.getText().length() == 0 || txt_nitrit.getText().length() == 0) { helper.bosluk("fill"); } else { try { String sql = "INSERT INTO IdrarTahlil " + "values(?,?,?,?,?,?,?,?,?,?,?,?)"; conn = db.connection_db(); pst = conn.prepareStatement(sql); pst.setString(1, hasta_tc.getText()); pst.setString(2, txt_tarih.getText()); pst.setString(3, txt_renk.getText()); pst.setString(4, txt_gorunum.getText()); pst.setString(5, txt_dansite.getText()); pst.setString(6, txt_ph.getText()); pst.setString(7, txt_protein.getText()); pst.setString(8, txt_glukoz.getText()); pst.setString(9, txt_bilirubin.getText()); pst.setString(10, txt_urobili.getText()); pst.setString(11, txt_keton.getText()); pst.setString(12, txt_nitrit.getText()); pst.executeUpdate(); retrievetableIdrar2(); JOptionPane.showMessageDialog(null, "KAYIT BAŞARIYLA EKLENDİ."); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } finally { try { resetle(); pst.close(); conn.close(); } catch (Exception e) { } } } }//GEN-LAST:event_btn_kayitActionPerformed private void btn_silActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_silActionPerformed if (!(hasta_tc.getText()).equals("")) { try { conn = db.connection_db(); String sql = "DELETE FROM IdrarTahlil WHERE TC=?"; pst = conn.prepareStatement(sql); pst.setString(1, hasta_tc.getText()); pst.execute(); retrievetableIdrar2(); resetle(); JOptionPane.showMessageDialog(null, "KAYIT SİLİNMİŞTİR !"); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } finally { try { conn.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } } } else { JOptionPane.showMessageDialog(null, "SİLMEK İSTEDİĞİNİZ KAYDI SEÇİNİZ !"); } }//GEN-LAST:event_btn_silActionPerformed private void btn_tcbulActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_tcbulActionPerformed String HastaTC = ""; String data = ""; try { conn = Helper.db.connection_db(); String sql = "SELECT * FROM IdrarTahlil WHERE TC=?"; pst = conn.prepareStatement(sql); pst.setString(1, tc_arama.getText()); rs = pst.executeQuery(); if (rs.next()) { HastaTC = rs.getString("TC"); JOptionPane.showMessageDialog(null, "TC BULUNDU."); } else { JOptionPane.showMessageDialog(null, "TC BULUNAMADI !"); } } catch (Exception ex) { } try { conn.close(); retrievetableIdrar(HastaTC); } catch (Exception ex) { } try { conn = Helper.db.connection_db(); String sql = "SELECT * FROM IdrarTahlil WHERE TC=?"; pst = conn.prepareStatement(sql); pst.setString(1, tc_arama.getText()); rs = pst.executeQuery(); while (rs.next()) { data = rs.getString("TC"); hasta_tc.setText(data); data = rs.getString("Tarih"); txt_tarih.setText(data); data = rs.getString("Renk"); txt_renk.setText(data); data = rs.getString("Görünüm"); txt_gorunum.setText(data); data = rs.getString("Dansite"); txt_dansite.setText(data); data = rs.getString("pH"); txt_ph.setText(data); data = rs.getString("Protein"); txt_protein.setText(data); data = rs.getString("Glukoz"); txt_glukoz.setText(data); data = rs.getString("Bilirubin"); txt_bilirubin.setText(data); data = rs.getString("Ürobilinojen"); txt_urobili.setText(data); data = rs.getString("Keton"); txt_keton.setText(data); data = rs.getString("Nitrit"); txt_nitrit.setText(data); } } catch (Exception ex) { } }//GEN-LAST:event_btn_tcbulActionPerformed public void resetle() { tc_arama.setText(""); hasta_tc.setText(""); txt_tarih.setText(""); txt_renk.setText(""); txt_dansite.setText(""); txt_gorunum.setText(""); txt_ph.setText(""); txt_protein.setText(""); txt_glukoz.setText(""); txt_bilirubin.setText(""); txt_urobili.setText(""); txt_keton.setText(""); txt_nitrit.setText(""); } private void btn_resetleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_resetleActionPerformed resetle(); retrievetableIdrar2(); }//GEN-LAST:event_btn_resetleActionPerformed private void btn_onceki_sayfaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_onceki_sayfaActionPerformed this.dispose(); sekreter_islem_secme s = new sekreter_islem_secme(); s.setVisible(true); }//GEN-LAST:event_btn_onceki_sayfaActionPerformed private void btn_onceki_sayfa1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_onceki_sayfa1ActionPerformed this.dispose(); login l = new login(); l.setVisible(true); }//GEN-LAST:event_btn_onceki_sayfa1ActionPerformed private void tbl_idrarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_idrarMouseClicked int i = tbl_idrar.getSelectedRow(); TableModel model = tbl_idrar.getModel(); hasta_tc.setText(model.getValueAt(i, 0).toString()); txt_tarih.setText(model.getValueAt(i, 1).toString()); txt_renk.setText(model.getValueAt(i, 2).toString()); txt_gorunum.setText(model.getValueAt(i, 3).toString()); txt_dansite.setText(model.getValueAt(i, 4).toString()); txt_ph.setText(model.getValueAt(i, 5).toString()); txt_protein.setText(model.getValueAt(i, 6).toString()); txt_glukoz.setText(model.getValueAt(i, 7).toString()); txt_bilirubin.setText(model.getValueAt(i, 8).toString()); txt_urobili.setText(model.getValueAt(i, 9).toString()); txt_keton.setText(model.getValueAt(i, 10).toString()); txt_nitrit.setText(model.getValueAt(i, 11).toString()); }//GEN-LAST:event_tbl_idrarMouseClicked private void btn_güncelleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_güncelleActionPerformed try { conn = db.connection_db(); String TC = hasta_tc.getText(); String tarih = txt_tarih.getText(); String renk = txt_renk.getText(); String gorunum = txt_gorunum.getText(); String dansite = txt_dansite.getText(); String ph = txt_ph.getText(); String protein = txt_protein.getText(); String glukoz = txt_glukoz.getText(); String bilirubin = txt_bilirubin.getText(); String urobili = txt_urobili.getText(); String keton = txt_keton.getText(); String nitrit = txt_nitrit.getText(); String sql = "UPDATE IdrarTahlil SET TC='" + TC + "',Tarih='" + tarih + "',Renk='" + renk + "'," + "Görünüm='" + gorunum + "',Dansite='" + dansite + "',pH='" + ph + "'," + "Protein='" + protein + "',Glukoz='" + glukoz + "'," + "Bilirubin='" + bilirubin + "',Ürobilinojen='" + urobili + "'," + "Keton='" + keton + "',Nitrit='" + nitrit + "' WHERE TC='" + TC + "'"; pst = conn.prepareStatement(sql); pst.execute(); retrievetableIdrar2(); JOptionPane.showMessageDialog(null, "KAYIT GÜNCELLENMİŞTİR."); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } finally { try { conn.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } } }//GEN-LAST:event_btn_güncelleActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(sekreter_idrar_tahlil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(sekreter_idrar_tahlil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(sekreter_idrar_tahlil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(sekreter_idrar_tahlil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new sekreter_idrar_tahlil().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_güncelle; private javax.swing.JButton btn_kayit; private javax.swing.JButton btn_onceki_sayfa; private javax.swing.JButton btn_onceki_sayfa1; private javax.swing.JButton btn_resetle; private javax.swing.JButton btn_sil; private javax.swing.JButton btn_tcbul; private javax.swing.JTextField hasta_tc; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTable tbl_idrar; private javax.swing.JTextField tc_arama; private javax.swing.JTextField txt_bilirubin; private javax.swing.JTextField txt_dansite; private javax.swing.JTextField txt_glukoz; private javax.swing.JTextField txt_gorunum; private javax.swing.JTextField txt_keton; private javax.swing.JTextField txt_nitrit; private javax.swing.JTextField txt_ph; private javax.swing.JTextField txt_protein; private javax.swing.JTextField txt_renk; private javax.swing.JTextField txt_tarih; private javax.swing.JTextField txt_urobili; // End of variables declaration//GEN-END:variables }
42,513
0.597951
0.582433
863
48.206257
37.052517
179
false
false
0
0
0
0
0
0
0.895713
false
false
13
7907c54f1461089bcaac7e264bf3e5dfca654987
5,935,644,820,538
72a89c88fffad8e758451f1245e9688906274404
/proj/corejava/src/main/java/basics/ThreadTest.java
fb61aa5f29ba81b2e6d88613c8b46a752a438847
[]
no_license
RavikrianGoru/dev-repo
https://github.com/RavikrianGoru/dev-repo
15c8f46d9154d3b7be413643751ce122586e50cf
897a379235a93875e512eacd37139f62454de5ff
refs/heads/master
2021-06-07T19:24:09.772000
2021-04-02T18:12:20
2021-04-02T18:12:20
102,496,972
0
3
null
false
2021-01-20T23:53:38
2017-09-05T15:14:29
2020-05-08T03:13:25
2021-01-20T23:53:36
26,143
0
1
2
Java
false
false
package basics; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; public class ThreadTest { @SuppressWarnings("finally") public static int tTest() { try { System.out.println("Hi----Try"); return 1; // System.out.println("Hi----Try");//C.T Error: Unreachable code } catch (Exception e) { System.out.println("Hi----Catch"); return 2; // System.out.println("Hi----Catch");//C.T Error: Unreachable code } finally { System.out.println("Hi----finally"); return 3; // System.out.println("Hi----finally");//C.T Error: Unreachable code } // return 4; //C.T Error: Unreachable } public static void main(String[] args) { AtomicInteger atomicInt = new AtomicInteger(0); ExecutorService executor = Executors.newFixedThreadPool(2); IntStream.range(0, 1000).forEach(i -> executor.submit(atomicInt::incrementAndGet)); System.out.println(atomicInt.get()); System.out.println("-------------------------"); System.out.println("Returned value:" + tTest()); System.out.println("-------------------------"); } }
UTF-8
Java
1,170
java
ThreadTest.java
Java
[]
null
[]
package basics; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; public class ThreadTest { @SuppressWarnings("finally") public static int tTest() { try { System.out.println("Hi----Try"); return 1; // System.out.println("Hi----Try");//C.T Error: Unreachable code } catch (Exception e) { System.out.println("Hi----Catch"); return 2; // System.out.println("Hi----Catch");//C.T Error: Unreachable code } finally { System.out.println("Hi----finally"); return 3; // System.out.println("Hi----finally");//C.T Error: Unreachable code } // return 4; //C.T Error: Unreachable } public static void main(String[] args) { AtomicInteger atomicInt = new AtomicInteger(0); ExecutorService executor = Executors.newFixedThreadPool(2); IntStream.range(0, 1000).forEach(i -> executor.submit(atomicInt::incrementAndGet)); System.out.println(atomicInt.get()); System.out.println("-------------------------"); System.out.println("Returned value:" + tTest()); System.out.println("-------------------------"); } }
1,170
0.662393
0.652991
38
29.789474
23.442156
85
false
false
0
0
0
0
0
0
2.078947
false
false
13
d7c5991e3d734851c4583d6d0c40e7d17d19f17b
15,032,385,540,900
4fd585a3642b0b7954abd7322b58351ee453ab1a
/WebMD_BDD/src/test/java/bdd/webMD/actionPage/WebMDConnectActions.java
d7acb9f2a10f109ff7b47207993947a990f67939
[]
no_license
MightySamurai/WebMD
https://github.com/MightySamurai/WebMD
ee023e8b84359a4cbc01520c95eb2dc5b23c21a7
f06430856d38d183073cf7cef02d8c92778c0df4
refs/heads/master
2023-05-13T11:47:27.041000
2020-06-04T21:52:01
2020-06-04T21:52:01
266,231,272
0
0
null
false
2023-05-09T18:25:25
2020-05-23T00:07:16
2020-06-04T21:51:26
2023-05-09T18:25:25
10,481
0
0
2
HTML
false
false
package bdd.webMD.actionPage; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.support.PageFactory; import bdd.webMD.elementPage.WebMDConnectElementPage; import bdd.webMD.utilities.SetupDrivers; public class WebMDConnectActions { JavascriptExecutor js = (JavascriptExecutor) SetupDrivers.chromeDriver; WebMDConnectElementPage connectPageElements; public WebMDConnectActions () { this.connectPageElements = new WebMDConnectElementPage(); PageFactory.initElements(SetupDrivers.chromeDriver, connectPageElements); } public void getWebMDLoginPage() { SetupDrivers.chromeDriver.get("https://member.webmd.com/signin?appid=1&returl=https://www.webmd.com/"); SetupDrivers.chromeDriver.manage().window().maximize(); SetupDrivers.chromeDriver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); SetupDrivers.chromeDriver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); } public void popUP () { connectPageElements.popup.click(); } public void scrollDown () { js.executeScript("window.scrollBy(0,1900)"); } public void faceBookBtn () { connectPageElements.faceBook.click(); } }
UTF-8
Java
1,200
java
WebMDConnectActions.java
Java
[]
null
[]
package bdd.webMD.actionPage; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.support.PageFactory; import bdd.webMD.elementPage.WebMDConnectElementPage; import bdd.webMD.utilities.SetupDrivers; public class WebMDConnectActions { JavascriptExecutor js = (JavascriptExecutor) SetupDrivers.chromeDriver; WebMDConnectElementPage connectPageElements; public WebMDConnectActions () { this.connectPageElements = new WebMDConnectElementPage(); PageFactory.initElements(SetupDrivers.chromeDriver, connectPageElements); } public void getWebMDLoginPage() { SetupDrivers.chromeDriver.get("https://member.webmd.com/signin?appid=1&returl=https://www.webmd.com/"); SetupDrivers.chromeDriver.manage().window().maximize(); SetupDrivers.chromeDriver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); SetupDrivers.chromeDriver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); } public void popUP () { connectPageElements.popup.click(); } public void scrollDown () { js.executeScript("window.scrollBy(0,1900)"); } public void faceBookBtn () { connectPageElements.faceBook.click(); } }
1,200
0.780833
0.7725
44
26.272728
28.721518
105
false
false
0
0
0
0
0
0
1.318182
false
false
13
07bd3de2cafbbc666045a06869f019c0ef02e44d
33,174,327,403,047
21a17144bfe4e705e7217438b09d44dad67a19da
/NF8-Conjunts/src/nf8Conjunts/Exercici86.java
550e1f2bd0c136d75bfe57c092f837712de4dfc5
[]
no_license
gabri231/m03uf5
https://github.com/gabri231/m03uf5
f29f89d85bc55891cd651a7e63f24eb7b0d465b1
c1d08ac738d6cb5e7f649a70d63a3d9f2d626c2f
refs/heads/master
2020-12-26T03:01:31.633000
2015-11-27T00:43:09
2015-11-27T00:43:09
43,116,578
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nf8Conjunts; import java.util.LinkedHashSet; import java.util.Set; /** Un programa Java simple - Colas * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @author Gabriel Calle Torrez * @version 1 * @since 06.10.2015 * * Crea un programa Java que faci el següent: 1. Creï una LinkedHashSet que suporti 5 objectes de tipus cotxe com hem creat abans. 2. Afegeix-hi dos objectes tipus cotxe: a.Hyundai Atos 1500, 3 b.Ford Focus 2000,4 3. Pots afegir-hi duplicats? 4. Obté les dades de tots els objectes amb qualsevol mètode 5. Quin ordre hi tenim? Quin tipus de “cuaâ€� és? * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ public class Exercici86 { public static void main(String[] args) { ////////////////////////////////////////////////////////////////////////////////////////////// // 1. Creï una LinkedHashSet que suporti 5 objectes de tipus cotxe com hem creat abans. //ok // Se crea la lista. LinkedHashSet<Coche> linkedHashDeCoches=new LinkedHashSet<Coche>(); linkedHashDeCoches.add(new Coche("Alfa Romero", "Giulia", 2900, 6)); linkedHashDeCoches.add(new Coche("Dacia", "Sandero", 1200, 4)); linkedHashDeCoches.add(new Coche("Ford", "Focus", 2000, 4)); linkedHashDeCoches.add(new Coche("Opel", "Insignia", 2200, 4)); linkedHashDeCoches.add(new Coche("Seat", "Ibiza", 1600, 4)); ////////////////////////////////////////////////////////////////////////////////////////////// // 2. Afegeix-hi dos objectes tipus cotxe: // a. Hyundai Atos 1500, 3 // b. Ford Focus 2000,4 // linea(); System.out.println("Se añaden dos objetos coche. "); Boolean intento; intento = linkedHashDeCoches.add(new Coche("Hyundai", "Atos", 1500, 3)); if (intento){ System.out.println("Ok: Éxito al insertar el Hyundai "); } else{ System.out.println("ERROR: Fracaso al insertar el Hyundai, porque ya existe."); } intento = linkedHashDeCoches.add(new Coche("Ford", "Focus", 2000, 4)); if (intento){ System.out.println("Ok: Éxito al insertar el Ford Focus "); } else{ System.out.println("ERROR: Fracaso al insertar el Ford Focus, porque ya existe"); } ////////////////////////////////////////////////////////////////////////////////////////////// // 3. Pots afegir-hi duplicats? linea(); System.out.println("No se pueden añadir elementos duplicados."); // 4. Obté les dades de tots els objectes amb qualsevol mètode for (Coche car : linkedHashDeCoches){ System.out.println("|" + String.format("%1$-13s",car.getMarca()) + "| " +String.format("%1$-10s",car.getModelo()) +"| " +car.getCilindrada() +"\t| " +car.getCilindres() +"\t| " + String.format("%.2f", car.potenciaFiscal())+"\t|"); } // 5. Quin ordre hi tenim? Quin tipus de cúa és? linea(); System.out.println("Estan por orden de llegada. El tipo de cola es: FIFO."); } //Fin de main static void linea(){ System.out.println("#########################################################################"); } }
UTF-8
Java
3,141
java
Exercici86.java
Java
[ { "context": " * * * * * * * * * * * * * * * * * * * \n * @author Gabriel Calle Torrez\n * @version 1\n * @since 06.10.2015\n * \n * Crea un", "end": 222, "score": 0.9998834133148193, "start": 202, "tag": "NAME", "value": "Gabriel Calle Torrez" }, { "context": "<Coche>();\n\t\t\n\t\t...
null
[]
package nf8Conjunts; import java.util.LinkedHashSet; import java.util.Set; /** Un programa Java simple - Colas * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @author <NAME> * @version 1 * @since 06.10.2015 * * Crea un programa Java que faci el següent: 1. Creï una LinkedHashSet que suporti 5 objectes de tipus cotxe com hem creat abans. 2. Afegeix-hi dos objectes tipus cotxe: a.Hyundai Atos 1500, 3 b.Ford Focus 2000,4 3. Pots afegir-hi duplicats? 4. Obté les dades de tots els objectes amb qualsevol mètode 5. Quin ordre hi tenim? Quin tipus de “cuaâ€� és? * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ public class Exercici86 { public static void main(String[] args) { ////////////////////////////////////////////////////////////////////////////////////////////// // 1. Creï una LinkedHashSet que suporti 5 objectes de tipus cotxe com hem creat abans. //ok // Se crea la lista. LinkedHashSet<Coche> linkedHashDeCoches=new LinkedHashSet<Coche>(); linkedHashDeCoches.add(new Coche("<NAME>", "Giulia", 2900, 6)); linkedHashDeCoches.add(new Coche("Dacia", "Sandero", 1200, 4)); linkedHashDeCoches.add(new Coche("Ford", "Focus", 2000, 4)); linkedHashDeCoches.add(new Coche("Opel", "Insignia", 2200, 4)); linkedHashDeCoches.add(new Coche("Seat", "Ibiza", 1600, 4)); ////////////////////////////////////////////////////////////////////////////////////////////// // 2. Afegeix-hi dos objectes tipus cotxe: // a. Hyundai Atos 1500, 3 // b. Ford Focus 2000,4 // linea(); System.out.println("Se añaden dos objetos coche. "); Boolean intento; intento = linkedHashDeCoches.add(new Coche("Hyundai", "Atos", 1500, 3)); if (intento){ System.out.println("Ok: Éxito al insertar el Hyundai "); } else{ System.out.println("ERROR: Fracaso al insertar el Hyundai, porque ya existe."); } intento = linkedHashDeCoches.add(new Coche("Ford", "Focus", 2000, 4)); if (intento){ System.out.println("Ok: Éxito al insertar el Ford Focus "); } else{ System.out.println("ERROR: Fracaso al insertar el Ford Focus, porque ya existe"); } ////////////////////////////////////////////////////////////////////////////////////////////// // 3. Pots afegir-hi duplicats? linea(); System.out.println("No se pueden añadir elementos duplicados."); // 4. Obté les dades de tots els objectes amb qualsevol mètode for (Coche car : linkedHashDeCoches){ System.out.println("|" + String.format("%1$-13s",car.getMarca()) + "| " +String.format("%1$-10s",car.getModelo()) +"| " +car.getCilindrada() +"\t| " +car.getCilindres() +"\t| " + String.format("%.2f", car.potenciaFiscal())+"\t|"); } // 5. Quin ordre hi tenim? Quin tipus de cúa és? linea(); System.out.println("Estan por orden de llegada. El tipo de cola es: FIFO."); } //Fin de main static void linea(){ System.out.println("#########################################################################"); } }
3,122
0.548346
0.520398
93
32.483871
29.736698
98
false
false
0
0
0
0
95
0.091552
2.537634
false
false
13
7d9366b78a8de9bdcee0ff0479b173c65acd2251
16,638,703,316,503
0b460ef0e07693e278af5d6431f8a40993c72a93
/FPR360/FPR360-alert-server/FPR360-alert-services/src/main/java/com/cbg/fpr360/alertservices/common/service/MasterDataService.java
e95d44c0e6e0bbc8782c359dfd31cecefef1ac99
[ "Apache-2.0" ]
permissive
kumardeepakbca/spring
https://github.com/kumardeepakbca/spring
12cf305629ee328f1415b90999d620fa1ccab586
f0117a26950cdb3089cb5a63f5c0178b6e49e90e
refs/heads/master
2017-12-07T05:30:40.073000
2017-09-22T12:10:38
2017-09-22T12:10:38
79,661,866
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cbg.fpr360.alertservices.common.service; import java.util.Map; import com.cbg.fpr360.alertutil.helper.FPR360ServiceException; public interface MasterDataService { public Map<String, Long> getAllAlertVendor() throws FPR360ServiceException; public Map<String, Map<String, Long>> getAllStatusMaster() throws FPR360ServiceException; }
UTF-8
Java
351
java
MasterDataService.java
Java
[]
null
[]
package com.cbg.fpr360.alertservices.common.service; import java.util.Map; import com.cbg.fpr360.alertutil.helper.FPR360ServiceException; public interface MasterDataService { public Map<String, Long> getAllAlertVendor() throws FPR360ServiceException; public Map<String, Map<String, Long>> getAllStatusMaster() throws FPR360ServiceException; }
351
0.817664
0.774929
13
26
32.074432
90
false
false
0
0
0
0
0
0
0.769231
false
false
13
5304282272eb5de68915987662057690cdcee84b
26,671,746,943,893
56468ad83bd0efde4881f0ef3590308bc0af0c9b
/src/PollsterModel.java
e68921d2b819f7b115e14d8f3ef8a8e9be184d90
[]
no_license
chrislemelin/Pollster
https://github.com/chrislemelin/Pollster
a2a2d93352ce84b12e851020f285169bdf47b870
ff6be66a6c7177197c7dbc30e9de6d53d3b3e643
refs/heads/master
2020-06-14T11:09:24.544000
2016-11-30T13:49:30
2016-11-30T13:49:30
75,191,141
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.SocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.swing.Timer; public class PollsterModel implements ViewListener { private HashMap<SocketAddress,ResponderModel> responders; private ArrayList<ModelListener> listeners; private String currentQuestion = "this is the example question master"; private class ResponderModel { private int state; private ViewProxy viewProxy; private int lastUpdate; private long lastTimeStamp; private boolean active; private ResponderModel() { state = 0; Timer timer = new Timer (1000, new ActionListener() { public void actionPerformed (ActionEvent e) { updateResponders(); } }); timer.start(); } private void updateResponders() { //lemaSystem.out.println("lemango "+ responders.size()); for (Map.Entry<SocketAddress, ResponderModel> entry : responders.entrySet()) { try { entry.getValue().viewProxy.getNewQuestion(currentQuestion, System.currentTimeMillis()); } catch(IOException e) { } } } private void report(String question, long timeStamp, int yes) { if(question.equals(currentQuestion) && timeStamp > lastTimeStamp) { lastTimeStamp = timeStamp; if(yes == 1 && state!= 1) { state = 1; //recalc() } else if(yes == -1 && state != -1) { state = -1; //recalc() } } } } public PollsterModel() { responders = new HashMap<SocketAddress, ResponderModel>(); listeners = new ArrayList<ModelListener>(); } private void notifyListeners() { } @Override public void answer(ViewProxy listener,SocketAddress address,long timeStamp, String question, int yes) throws IOException { if(responders.containsKey(address)) { responders.get(address).report(question,timeStamp, yes); } else { System.out.println("new message"); ResponderModel mod = new ResponderModel(); mod.viewProxy = listener; mod.state = 0; responders.put(address, mod); } } public void newQuestion(ViewProxy listener, String Question) { /* System.out.println("new Question:" +Question); Iterator it = responders.entrySet().iterator(); for (Map.Entry<SocketAddress, ResponderModel> entry : responders.entrySet()) { try { entry.getValue().viewProxy.getNewQuestion(Question, System.currentTimeMillis()); } catch(IOException e) { } } */ currentQuestion = Question; } }
UTF-8
Java
2,733
java
PollsterModel.java
Java
[]
null
[]
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.SocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.swing.Timer; public class PollsterModel implements ViewListener { private HashMap<SocketAddress,ResponderModel> responders; private ArrayList<ModelListener> listeners; private String currentQuestion = "this is the example question master"; private class ResponderModel { private int state; private ViewProxy viewProxy; private int lastUpdate; private long lastTimeStamp; private boolean active; private ResponderModel() { state = 0; Timer timer = new Timer (1000, new ActionListener() { public void actionPerformed (ActionEvent e) { updateResponders(); } }); timer.start(); } private void updateResponders() { //lemaSystem.out.println("lemango "+ responders.size()); for (Map.Entry<SocketAddress, ResponderModel> entry : responders.entrySet()) { try { entry.getValue().viewProxy.getNewQuestion(currentQuestion, System.currentTimeMillis()); } catch(IOException e) { } } } private void report(String question, long timeStamp, int yes) { if(question.equals(currentQuestion) && timeStamp > lastTimeStamp) { lastTimeStamp = timeStamp; if(yes == 1 && state!= 1) { state = 1; //recalc() } else if(yes == -1 && state != -1) { state = -1; //recalc() } } } } public PollsterModel() { responders = new HashMap<SocketAddress, ResponderModel>(); listeners = new ArrayList<ModelListener>(); } private void notifyListeners() { } @Override public void answer(ViewProxy listener,SocketAddress address,long timeStamp, String question, int yes) throws IOException { if(responders.containsKey(address)) { responders.get(address).report(question,timeStamp, yes); } else { System.out.println("new message"); ResponderModel mod = new ResponderModel(); mod.viewProxy = listener; mod.state = 0; responders.put(address, mod); } } public void newQuestion(ViewProxy listener, String Question) { /* System.out.println("new Question:" +Question); Iterator it = responders.entrySet().iterator(); for (Map.Entry<SocketAddress, ResponderModel> entry : responders.entrySet()) { try { entry.getValue().viewProxy.getNewQuestion(Question, System.currentTimeMillis()); } catch(IOException e) { } } */ currentQuestion = Question; } }
2,733
0.654592
0.650201
129
20.186047
23.399055
121
false
false
0
0
0
0
0
0
2.418605
false
false
13
1c743eddc14dafe8d66378814cbf6e2b44fda12d
3,496,103,441,335
c4cf78e57244c0b3df30aa67dc3dfa59a7f83a5a
/java/src/main/java/FIIT/VI/YAGO/domain/Article.java
f58c3b2318a6896e571d2cdee88740c3f36438d4
[ "Apache-2.0" ]
permissive
jonny999/yago
https://github.com/jonny999/yago
9ff3c4c98ebd1146a506f8599985edb38642c7ae
0175ad260aaba021d46ce37531fb4897012ab245
refs/heads/master
2020-05-01T04:31:31.039000
2014-12-15T16:22:34
2014-12-15T16:22:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package FIIT.VI.YAGO.domain; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; /** * Domain entity represent wiki article * @author mm * */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) public class Article { private static final ObjectMapper mapper = new ObjectMapper(); /** YAGO identifier name for article, is unique*/ private String name; /** Information about size of article, count o chars*/ private String size; /** Wikipedia name of article*/ private String wikiName; /** Wikipedia URl*/ private String ulrWikipedia; /** DPpedia URl*/ private String urlAlternative; /** Wikipedia references to other articles*/ private List<String> linksTo; /** Wikipedia alternative names*/ private List<Names> names; /** Tags of wikipedia*/ private List<String> categories; public String getName() { return name; } /** * Parse unique name for json file * @return classic YAGO name without special codes, like /_ */ public String parseFilesName(){ return name.replaceAll("_", "").replaceAll("/", ""); } /** * Set classical unique name and parse wikipedia name * @param name unique YAGO name */ public void parseName(String name) { this.setName(name); this.setWikiName(name.replaceAll("_", " ")); } public void setName(String name) { this.name = name; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getUlrWikipedia() { return ulrWikipedia; } public void setUlrWikipedia(String ulrWikipedia) { this.ulrWikipedia = ulrWikipedia; } public List<String> getLinksTo() { if (linksTo == null) { linksTo = new ArrayList<String>(); } return linksTo; } public void setLinksTo(List<String> linksTo) { this.linksTo = linksTo; } /** * Map article entity to JSON format * @return * @throws JsonGenerationException * @throws JsonMappingException * @throws IOException */ public String toJson() throws JsonGenerationException, JsonMappingException, IOException { return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this); } /** * Parse lucene document from variables * @return Lucene document */ public Document document() { Document doc = new Document(); doc.add(new TextField("name", name, Field.Store.YES)); doc.add(new TextField("ulrWikipedia", ulrWikipedia, Field.Store.YES)); for (String category : this.getCategories()) { doc.add(new TextField("category", category, Field.Store.YES)); } for (String link : this.getLinksTo()) { doc.add(new TextField("link", link, Field.Store.YES)); } for (Names name : this.getNames()) { doc.add(new TextField("name", name.getName(), Field.Store.YES)); } return doc; } /** * Parse alternative names of wikipedia article * @return String list of alternatives names */ public String toAlternativesNames() { StringBuilder builder = new StringBuilder(); builder.append(this.getName()); for (Names n : this.getNames()) { builder.append("\t" + n.getName()); } builder.append("\n"); return builder.toString(); } /** * Select tags of article * @return String list of tags */ public String toCategoriesNames() { StringBuilder builder = new StringBuilder(); builder.append(this.getName()); for (String n : this.getCategories()) { builder.append("\t" + n); } builder.append("\n"); return builder.toString(); } public List<Names> getNames() { if (names == null) { names = new ArrayList<Names>(); } return names; } public void setNames(List<Names> names) { this.names = names; } public List<String> getCategories() { if (categories == null) { this.categories = new ArrayList<String>(); } return categories; } public void processCategory(String category) { String parseCategory = category.replaceAll("_", " "); this.getCategories().add(parseCategory); } public void setCategories(List<String> categories) { this.categories = categories; } public String getUrlAlternative() { return urlAlternative; } public void setUrlAlternative(String urlAlternative) { this.urlAlternative = urlAlternative; } public String getWikiName() { return wikiName; } public void setWikiName(String wikiName) { this.wikiName = wikiName; } }
UTF-8
Java
4,893
java
Article.java
Java
[ { "context": "* Domain entity represent wiki article\r\n * @author mm\r\n *\r\n */\r\n@JsonSerialize(include = JsonSerialize.", "end": 523, "score": 0.9975274205207825, "start": 521, "tag": "USERNAME", "value": "mm" } ]
null
[]
package FIIT.VI.YAGO.domain; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; /** * Domain entity represent wiki article * @author mm * */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) public class Article { private static final ObjectMapper mapper = new ObjectMapper(); /** YAGO identifier name for article, is unique*/ private String name; /** Information about size of article, count o chars*/ private String size; /** Wikipedia name of article*/ private String wikiName; /** Wikipedia URl*/ private String ulrWikipedia; /** DPpedia URl*/ private String urlAlternative; /** Wikipedia references to other articles*/ private List<String> linksTo; /** Wikipedia alternative names*/ private List<Names> names; /** Tags of wikipedia*/ private List<String> categories; public String getName() { return name; } /** * Parse unique name for json file * @return classic YAGO name without special codes, like /_ */ public String parseFilesName(){ return name.replaceAll("_", "").replaceAll("/", ""); } /** * Set classical unique name and parse wikipedia name * @param name unique YAGO name */ public void parseName(String name) { this.setName(name); this.setWikiName(name.replaceAll("_", " ")); } public void setName(String name) { this.name = name; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getUlrWikipedia() { return ulrWikipedia; } public void setUlrWikipedia(String ulrWikipedia) { this.ulrWikipedia = ulrWikipedia; } public List<String> getLinksTo() { if (linksTo == null) { linksTo = new ArrayList<String>(); } return linksTo; } public void setLinksTo(List<String> linksTo) { this.linksTo = linksTo; } /** * Map article entity to JSON format * @return * @throws JsonGenerationException * @throws JsonMappingException * @throws IOException */ public String toJson() throws JsonGenerationException, JsonMappingException, IOException { return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this); } /** * Parse lucene document from variables * @return Lucene document */ public Document document() { Document doc = new Document(); doc.add(new TextField("name", name, Field.Store.YES)); doc.add(new TextField("ulrWikipedia", ulrWikipedia, Field.Store.YES)); for (String category : this.getCategories()) { doc.add(new TextField("category", category, Field.Store.YES)); } for (String link : this.getLinksTo()) { doc.add(new TextField("link", link, Field.Store.YES)); } for (Names name : this.getNames()) { doc.add(new TextField("name", name.getName(), Field.Store.YES)); } return doc; } /** * Parse alternative names of wikipedia article * @return String list of alternatives names */ public String toAlternativesNames() { StringBuilder builder = new StringBuilder(); builder.append(this.getName()); for (Names n : this.getNames()) { builder.append("\t" + n.getName()); } builder.append("\n"); return builder.toString(); } /** * Select tags of article * @return String list of tags */ public String toCategoriesNames() { StringBuilder builder = new StringBuilder(); builder.append(this.getName()); for (String n : this.getCategories()) { builder.append("\t" + n); } builder.append("\n"); return builder.toString(); } public List<Names> getNames() { if (names == null) { names = new ArrayList<Names>(); } return names; } public void setNames(List<Names> names) { this.names = names; } public List<String> getCategories() { if (categories == null) { this.categories = new ArrayList<String>(); } return categories; } public void processCategory(String category) { String parseCategory = category.replaceAll("_", " "); this.getCategories().add(parseCategory); } public void setCategories(List<String> categories) { this.categories = categories; } public String getUrlAlternative() { return urlAlternative; } public void setUrlAlternative(String urlAlternative) { this.urlAlternative = urlAlternative; } public String getWikiName() { return wikiName; } public void setWikiName(String wikiName) { this.wikiName = wikiName; } }
4,893
0.669119
0.669119
215
20.758139
19.811369
74
false
false
0
0
0
0
0
0
1.427907
false
false
13
5f0becde777f872e5b54b4dd1cad82f3d72742f2
26,319,559,658,862
b3e16344574faca4139ac08bd2160b35fb8e8b41
/Prog0/src/ScoresList.java
4637f844fda935e396047940d2b97d6a76ad7096
[]
no_license
thlambert/Object-Oriented-Programming
https://github.com/thlambert/Object-Oriented-Programming
6e643a4b89cd4b3307890377bf96e6e59e1029fc
7a2797d974c6f968de0b62b272fed238bd6b2431
refs/heads/master
2020-09-10T18:58:19.542000
2019-11-14T23:47:50
2019-11-14T23:47:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** Java class to manipulate a list of scores. This program allows manipulation of a list of scores: Adding, Deleting, Finding, Printing, Average @author Thomas Lambert */ public class ScoresList { public final int MAX_SIZE = 10; private int scores[] = new int[MAX_SIZE]; private int numScores = 0; /** Adds a score to the end of the list if the list is not full. Time needed: O(1) @param score to add to the end of the scores list @return true if score is successfully added, false otherwise */ public boolean appendScore ( int score ) { // Write the function body if (numScores < MAX_SIZE) { scores[numScores++] = score; return true; } return false; } /** Calculates the float average of the scores stored in the list. Time needed: O(N) @return average of scores in the list, 0.0 if no scores in the list. */ public float average() { float ave = 0.0F; // Floating point constants are doubles without the F int sum = 0; // Complete the function if (numScores > 0) { for(int i = 0; i < numScores; i++) { sum += scores[i]; } return ave = (float)sum/(numScores); } else { return 0.0f; } } /** Deletes the LAST occurrence of score from the scores list, if it exists. Moves all scores up, maintaining relative positions, if it is deleted. Time needed: O(N) @param score to delete @return true if the score is successfully deleted, false otherwise */ public boolean delete ( int score ) { // Write the function body // You must use one and only one for loop inside the function. int num1 = find(score); if(num1 > -1) { numScores--; for(int i = num1; i < numScores; i++) scores[i] = scores[i + 1]; return true; } else { return false; } } /** Tries to find the LAST occurrence of score in the list of scores. Time needed: O(N) @param score to find @return 0-based position of the LAST occurrence of score, -1 if not found */ private int find ( int score ) { // Write the function body // You must use one and only one for loop inside the function. for(int i = numScores - 1; i > -1; i--) { if (scores[i] == score) { return i; } } return -1; } /** Prints the list of scores to System.out, one score per line. Time needed: O(N) */ public void print() { // Complete the function body System.out.println( "The list of scores is:" ); for(int i = 0; i < numScores; i++) { System.out.println(scores[i]); } } } // class ScoresList
UTF-8
Java
3,010
java
ScoresList.java
Java
[ { "context": "ing, Deleting, Finding, Printing, Average\r\n@author Thomas Lambert\r\n*/\r\n\r\npublic class ScoresList\r\n{\r\n public fina", "end": 176, "score": 0.9997323751449585, "start": 162, "tag": "NAME", "value": "Thomas Lambert" } ]
null
[]
/** Java class to manipulate a list of scores. This program allows manipulation of a list of scores: Adding, Deleting, Finding, Printing, Average @author <NAME> */ public class ScoresList { public final int MAX_SIZE = 10; private int scores[] = new int[MAX_SIZE]; private int numScores = 0; /** Adds a score to the end of the list if the list is not full. Time needed: O(1) @param score to add to the end of the scores list @return true if score is successfully added, false otherwise */ public boolean appendScore ( int score ) { // Write the function body if (numScores < MAX_SIZE) { scores[numScores++] = score; return true; } return false; } /** Calculates the float average of the scores stored in the list. Time needed: O(N) @return average of scores in the list, 0.0 if no scores in the list. */ public float average() { float ave = 0.0F; // Floating point constants are doubles without the F int sum = 0; // Complete the function if (numScores > 0) { for(int i = 0; i < numScores; i++) { sum += scores[i]; } return ave = (float)sum/(numScores); } else { return 0.0f; } } /** Deletes the LAST occurrence of score from the scores list, if it exists. Moves all scores up, maintaining relative positions, if it is deleted. Time needed: O(N) @param score to delete @return true if the score is successfully deleted, false otherwise */ public boolean delete ( int score ) { // Write the function body // You must use one and only one for loop inside the function. int num1 = find(score); if(num1 > -1) { numScores--; for(int i = num1; i < numScores; i++) scores[i] = scores[i + 1]; return true; } else { return false; } } /** Tries to find the LAST occurrence of score in the list of scores. Time needed: O(N) @param score to find @return 0-based position of the LAST occurrence of score, -1 if not found */ private int find ( int score ) { // Write the function body // You must use one and only one for loop inside the function. for(int i = numScores - 1; i > -1; i--) { if (scores[i] == score) { return i; } } return -1; } /** Prints the list of scores to System.out, one score per line. Time needed: O(N) */ public void print() { // Complete the function body System.out.println( "The list of scores is:" ); for(int i = 0; i < numScores; i++) { System.out.println(scores[i]); } } } // class ScoresList
3,002
0.539203
0.531229
117
23.743589
21.480722
77
false
false
0
0
0
0
0
0
0.34188
false
false
13
7c275bebecd80516c942f2b96a1396e4a4c68811
17,377,437,739,214
2b92302fc02f8034961beb841f13d7d96c1d21d7
/tops-car/tops-front-otms-car/src/main/java/com/car/service/IWinningRecordService.java
dc1c0367697e3ff01857b6dbf446c45ef4f726c3
[]
no_license
fangleu/tops-hotel
https://github.com/fangleu/tops-hotel
6761fbbaa4984d6e8ea7c9df9a992bf90fd25e3f
6dae9939ab672d920dad7a7f33adbb3ab2fa20ef
refs/heads/master
2021-01-21T04:39:52.045000
2016-07-15T05:24:30
2016-07-15T05:25:38
34,242,862
1
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.car.service; import java.io.Serializable; import com.car.bean.WinningRecord; import com.car.common.dao.IBaseService; public interface IWinningRecordService extends IBaseService<WinningRecord , Serializable>{ }
UTF-8
Java
228
java
IWinningRecordService.java
Java
[]
null
[]
package com.car.service; import java.io.Serializable; import com.car.bean.WinningRecord; import com.car.common.dao.IBaseService; public interface IWinningRecordService extends IBaseService<WinningRecord , Serializable>{ }
228
0.815789
0.815789
11
19.727272
26.727892
90
false
false
0
0
0
0
0
0
0.545455
false
false
13
813dec72f758bc2a4919fb1cd5776b05a7c9a00b
18,949,395,745,227
6bd833872c5b6983b2ebdf5491783c530d3be99d
/src/main/java/com/w5kickPDF/W5SearchCountry.java
7c3627c30030849386f912893e14ed3f3b345ffa
[]
no_license
Wudnkidner/W5PdfCreator3
https://github.com/Wudnkidner/W5PdfCreator3
cdd1fb8b9f885a7256a76a019503df1dc2fdb5ad
21f6455382483bb56d61ffbab3066719800c59b3
refs/heads/master
2021-06-13T00:19:10.439000
2017-02-12T17:27:56
2017-02-12T17:27:56
69,160,516
0
0
null
false
2017-02-12T17:27:57
2016-09-25T11:32:17
2016-09-25T11:32:26
2017-02-12T17:27:57
63
0
0
0
Java
null
null
package com.w5kickPDF; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Created by albert on 11.09.16. */ public class W5SearchCountry { public ListView createListView(final TextField txt) throws SQLException { final ObservableList<String> entries = FXCollections.observableArrayList(); final ListView list = new ListView(); txt.setPromptText("Search"); txt.textProperty().addListener( new ChangeListener() { public void changed(ObservableValue observable, Object oldVal, Object newVal) { handleSearchByKey(txt, list, entries, (String)oldVal, (String)newVal); } }); // Set up the ListView list.setPrefHeight(0); list.setVisible(false); // Populate the list's entries entries.addAll(W5MySQLRequests.getFightersList()); list.setItems( entries ); return list; } private void handleSearchByKey(final TextField txt, final ListView list, final ObservableList<String> entries, String oldVal, String newVal) { // If the number of characters in the text box is less than last time // it must be because the user pressed delete if ( oldVal != null && (newVal.length() < oldVal.length()) ) { // Restore the lists original set of entries // and start from the beginning list.setItems( entries ); } //Clone newVal String newVAlClone = newVal; // Change to upper case so that case is not an issue newVal = newVal.toUpperCase(); // Filter out the entries that don't contain the entered text ObservableList<String> subentries = FXCollections.observableArrayList(); for ( Object entry: list.getItems() ) { String entryText = (String)entry; if ( entryText.toUpperCase().contains(newVal) ) { subentries.add(entryText); } } list.setItems(subentries); newVal = newVAlClone; if (newVal.length() > 0) { list.setPrefHeight(180); list.setVisible(true); if (newVal.length() > 6 && subentries.size() == 0) { ObservableList<String> fighter = FXCollections.observableArrayList(); fighter.add("Click to add a "+ newVal +" to the database."); list.setItems(fighter); final String finalNewVal = newVal; list.setOnMouseClicked(new EventHandler<MouseEvent>() { public void handle(MouseEvent mouseEvent) { if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ try { newFighterQuery(list,finalNewVal,entries); } catch (SQLException e) { e.printStackTrace(); } System.out.println("Сработала 2 команда"); list.setPrefHeight(0); list.setVisible(false); } } } }); } else { list.setOnMouseClicked(new EventHandler<MouseEvent>() { public void handle(MouseEvent mouseEvent) { if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ txt.setText((String)list.getSelectionModel() .getSelectedItem()); System.out.println("Сработала 1 команда"); list.setPrefHeight(0); list.setVisible(false); } } } }); } } else { list.setPrefHeight(0); list.setVisible(false); } } public String getFighterText (TextField txt) { String fighterText = txt.getText(); return fighterText; } public static void newFighterQuery (ListView list, String finalNewVal, final ObservableList<String> entries) throws SQLException { Connection connection = W5MySQLConnection.getConnection(); String insertString = "INSERT INTO Fighters"+ "(firstname, lastname,country,weight)" + "VALUES" + "(?,?,?,?)"; if ( connection != null) { PreparedStatement preparedStmt = null; preparedStmt = connection.prepareStatement(insertString); String[] nameFilter = finalNewVal.split(" "); preparedStmt.setString(1, nameFilter[0]); preparedStmt.setString(2, nameFilter[1]); preparedStmt.setString(3, ""); preparedStmt.setString(4, ""); preparedStmt.execute(); connection.close(); entries.clear(); entries.addAll(W5MySQLRequests.getFightersList()); list.setItems( entries ); W5CreateFightStage.setStatus("Complete"); } else { W5CreateFightStage.setStatus("Error"); } } }
UTF-8
Java
6,412
java
W5SearchCountry.java
Java
[ { "context": "\nimport java.sql.SQLException;\n\n\n/**\n * Created by albert on 11.09.16.\n */\npublic class W5SearchCountry {\n\n", "end": 501, "score": 0.9632551670074463, "start": 495, "tag": "USERNAME", "value": "albert" } ]
null
[]
package com.w5kickPDF; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Created by albert on 11.09.16. */ public class W5SearchCountry { public ListView createListView(final TextField txt) throws SQLException { final ObservableList<String> entries = FXCollections.observableArrayList(); final ListView list = new ListView(); txt.setPromptText("Search"); txt.textProperty().addListener( new ChangeListener() { public void changed(ObservableValue observable, Object oldVal, Object newVal) { handleSearchByKey(txt, list, entries, (String)oldVal, (String)newVal); } }); // Set up the ListView list.setPrefHeight(0); list.setVisible(false); // Populate the list's entries entries.addAll(W5MySQLRequests.getFightersList()); list.setItems( entries ); return list; } private void handleSearchByKey(final TextField txt, final ListView list, final ObservableList<String> entries, String oldVal, String newVal) { // If the number of characters in the text box is less than last time // it must be because the user pressed delete if ( oldVal != null && (newVal.length() < oldVal.length()) ) { // Restore the lists original set of entries // and start from the beginning list.setItems( entries ); } //Clone newVal String newVAlClone = newVal; // Change to upper case so that case is not an issue newVal = newVal.toUpperCase(); // Filter out the entries that don't contain the entered text ObservableList<String> subentries = FXCollections.observableArrayList(); for ( Object entry: list.getItems() ) { String entryText = (String)entry; if ( entryText.toUpperCase().contains(newVal) ) { subentries.add(entryText); } } list.setItems(subentries); newVal = newVAlClone; if (newVal.length() > 0) { list.setPrefHeight(180); list.setVisible(true); if (newVal.length() > 6 && subentries.size() == 0) { ObservableList<String> fighter = FXCollections.observableArrayList(); fighter.add("Click to add a "+ newVal +" to the database."); list.setItems(fighter); final String finalNewVal = newVal; list.setOnMouseClicked(new EventHandler<MouseEvent>() { public void handle(MouseEvent mouseEvent) { if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ try { newFighterQuery(list,finalNewVal,entries); } catch (SQLException e) { e.printStackTrace(); } System.out.println("Сработала 2 команда"); list.setPrefHeight(0); list.setVisible(false); } } } }); } else { list.setOnMouseClicked(new EventHandler<MouseEvent>() { public void handle(MouseEvent mouseEvent) { if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ txt.setText((String)list.getSelectionModel() .getSelectedItem()); System.out.println("Сработала 1 команда"); list.setPrefHeight(0); list.setVisible(false); } } } }); } } else { list.setPrefHeight(0); list.setVisible(false); } } public String getFighterText (TextField txt) { String fighterText = txt.getText(); return fighterText; } public static void newFighterQuery (ListView list, String finalNewVal, final ObservableList<String> entries) throws SQLException { Connection connection = W5MySQLConnection.getConnection(); String insertString = "INSERT INTO Fighters"+ "(firstname, lastname,country,weight)" + "VALUES" + "(?,?,?,?)"; if ( connection != null) { PreparedStatement preparedStmt = null; preparedStmt = connection.prepareStatement(insertString); String[] nameFilter = finalNewVal.split(" "); preparedStmt.setString(1, nameFilter[0]); preparedStmt.setString(2, nameFilter[1]); preparedStmt.setString(3, ""); preparedStmt.setString(4, ""); preparedStmt.execute(); connection.close(); entries.clear(); entries.addAll(W5MySQLRequests.getFightersList()); list.setItems( entries ); W5CreateFightStage.setStatus("Complete"); } else { W5CreateFightStage.setStatus("Error"); } } }
6,412
0.500784
0.495611
166
37.427711
28.942677
150
false
false
0
0
0
0
0
0
0.554217
false
false
13
d12ce040d490f5af925eb403274917a3a7e3b106
29,343,216,575,050
2b32a59fe1f860cdb2c70d6f287d5ef9cf54779c
/HttpUtils/app/src/main/java/com/example/administrator/http/MainComponent.java
cb3bdc68c27dbddc4f0f7f471acc8d9dc4e627d9
[ "Apache-2.0" ]
permissive
yang-jianzheng/HttpUtil_ForOKHttp
https://github.com/yang-jianzheng/HttpUtil_ForOKHttp
c79037150f78838f9b66c71589ee1409a6b1b86b
4292b66ad235aff1ba7349d206b6ec886b92bcee
refs/heads/master
2017-12-06T10:25:02.542000
2017-01-26T02:53:54
2017-01-26T02:53:54
80,021,060
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.administrator.http; import java.util.List; /** * MVP的解耦接口,定义到了一个接口中 * 最外层接口,只是为了统一 Presenter 和 View 的访问入口 */ public interface MainComponent { /** * 同一个 Activity/Fragment 只能展示一种界面,但是可以用不同的 Presenter 实现类来加载不同来源的数据 */ interface Presenter{ void loadData(int offset, int size); } /** * 方便处理数据测试 */ interface View{ void setData(List<VideoBean> data); void onError(int code, Exception e); void showLoadingDialog(); void dismissLoadingDialog(); } }
UTF-8
Java
698
java
MainComponent.java
Java
[]
null
[]
package com.example.administrator.http; import java.util.List; /** * MVP的解耦接口,定义到了一个接口中 * 最外层接口,只是为了统一 Presenter 和 View 的访问入口 */ public interface MainComponent { /** * 同一个 Activity/Fragment 只能展示一种界面,但是可以用不同的 Presenter 实现类来加载不同来源的数据 */ interface Presenter{ void loadData(int offset, int size); } /** * 方便处理数据测试 */ interface View{ void setData(List<VideoBean> data); void onError(int code, Exception e); void showLoadingDialog(); void dismissLoadingDialog(); } }
698
0.635379
0.635379
29
18.103449
18.422895
70
false
false
0
0
0
0
0
0
0.37931
false
false
13
84776968ed439bf652e55802b81dc461408c75f7
14,147,622,290,467
9d36dc5f9f4a80fdd79bc0795dcebc55b6c1bb87
/core/src/ru/geekbrains/storage/Game.java
6b0b11df6273d3fb9cc69bfaa868c1cd24bac5b5
[]
no_license
duchien85/StarGame
https://github.com/duchien85/StarGame
c92f2187eae0f32607cef02610ed02c02f4751ed
53c634fac2b750dcd6b6c74d0d38fc5cbc488a8b
refs/heads/master
2022-04-19T21:46:31.631000
2020-04-19T21:47:07
2020-04-19T21:47:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.geekbrains.storage; public enum Game { INSTANCE; }
UTF-8
Java
72
java
Game.java
Java
[]
null
[]
package ru.geekbrains.storage; public enum Game { INSTANCE; }
72
0.666667
0.666667
10
6.2
10.047885
30
false
false
0
0
0
0
0
0
0.2
false
false
13
7dbfc747db9ed7729ff9b326e490c1dba7ec7419
13,846,974,594,512
d0beb9327bba6faf37ba4facbcec34bbcdae9ca7
/project_part1/src/drawit/tests/DoublePointTest.java
e52a4e0518560fa9c9e3f7af243ff1e88c265964
[]
no_license
ahmedshimi/Project_part1
https://github.com/ahmedshimi/Project_part1
afdb495cb203adec52301612776ab15f014667a4
66395033254d9504a6d21c77a0eab8bcb0f65171
refs/heads/master
2022-04-10T23:35:28.237000
2020-04-01T02:29:34
2020-04-01T02:29:34
245,265,538
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package drawit.tests; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import drawit.DoublePoint; class DoublePointTest { @Test void test() { DoublePoint myDoublePoint = new DoublePoint(-1,1); assertEquals(-1,myDoublePoint.getX()); assertEquals(1,myDoublePoint.getY()); DoublePoint myDoublePoint2 = new DoublePoint(2,2); assertEquals(-3,myDoublePoint.minus(myDoublePoint2).getX()); assertEquals(-1,myDoublePoint.minus(myDoublePoint2).getY()); DoublePoint myDoublePoint3 = new DoublePoint(-1.4,1.6); assertEquals(-1,myDoublePoint3.round().getX()); assertEquals(2,myDoublePoint3.round().getY()); assertEquals(-4,myDoublePoint.plus(myDoublePoint.minus(myDoublePoint2)).getX()); assertEquals(0,myDoublePoint.plus(myDoublePoint.minus(myDoublePoint2)).getY()); } }
UTF-8
Java
835
java
DoublePointTest.java
Java
[]
null
[]
package drawit.tests; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import drawit.DoublePoint; class DoublePointTest { @Test void test() { DoublePoint myDoublePoint = new DoublePoint(-1,1); assertEquals(-1,myDoublePoint.getX()); assertEquals(1,myDoublePoint.getY()); DoublePoint myDoublePoint2 = new DoublePoint(2,2); assertEquals(-3,myDoublePoint.minus(myDoublePoint2).getX()); assertEquals(-1,myDoublePoint.minus(myDoublePoint2).getY()); DoublePoint myDoublePoint3 = new DoublePoint(-1.4,1.6); assertEquals(-1,myDoublePoint3.round().getX()); assertEquals(2,myDoublePoint3.round().getY()); assertEquals(-4,myDoublePoint.plus(myDoublePoint.minus(myDoublePoint2)).getX()); assertEquals(0,myDoublePoint.plus(myDoublePoint.minus(myDoublePoint2)).getY()); } }
835
0.750898
0.722156
32
25.125
26.636148
82
false
false
0
0
0
0
0
0
1.71875
false
false
13
7635c5edf58970e88894a7211f68ff7e1ad11d41
24,421,184,086,415
1ecb4a91ce970ee75582adb67af78f49c9f7c925
/app/src/main/java/ir/hosseinrasti/app/jobjo/ui/user/signup/SignupPresenter.java
1128c231346bb7fdcdf1c81768712b5fd7648218
[ "Apache-2.0" ]
permissive
husseinrasti/Jobjo-RxJava-MVP-Dagger2
https://github.com/husseinrasti/Jobjo-RxJava-MVP-Dagger2
4563160c76cfcca4b1fef97dcf217b4cea4ee42b
0bb7cd9f49e6873327ac04b2f7ae3e3bb6e0dced
refs/heads/master
2020-06-22T18:09:42.320000
2019-07-21T11:57:33
2019-07-21T11:57:33
197,765,791
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ir.hosseinrasti.app.jobjo.ui.user.signup; import com.jakewharton.rxbinding2.widget.RxTextView; import com.jakewharton.rxbinding2.widget.TextViewTextChangeEvent; import java.util.concurrent.TimeUnit; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.observers.DisposableObserver; import io.reactivex.observers.DisposableSingleObserver; import io.reactivex.schedulers.Schedulers; import ir.hosseinrasti.app.jobjo.data.DataSource; import ir.hosseinrasti.app.jobjo.data.entity.UserModel; import ir.hosseinrasti.app.jobjo.data.repository.SignupRepository; /** * Created by Hossein on 5/24/2018. */ public class SignupPresenter implements SignupContract.Presenter { private DataSource.Signup repository; private SignupContract.View view; private CompositeDisposable subscription = new CompositeDisposable(); private boolean isUserAvailable = false; public SignupPresenter( DataSource.Signup repository ) { this.repository = repository; } @Override public void takeView( SignupContract.View view ) { this.view = view; } @Override public void dropView() { view = null; } @Override public void rxUnsubscribe() { subscription.clear(); subscription.dispose(); } @Override public void checkUsername() { subscription.add( RxTextView.textChangeEvents( view.getEdtUserName() ) .skipInitialValue() .debounce( 500, TimeUnit.MILLISECONDS ) .distinctUntilChanged() .subscribeOn( Schedulers.io() ) .observeOn( AndroidSchedulers.mainThread() ) .subscribeWith( search() ) ); } private DisposableObserver<TextViewTextChangeEvent> search() { return new DisposableObserver<TextViewTextChangeEvent>() { @Override public void onNext( TextViewTextChangeEvent textViewTextChangeEvent ) { repository.isUsernameAvailable( textViewTextChangeEvent.text().toString() ) .subscribeOn( Schedulers.newThread() ) .observeOn( AndroidSchedulers.mainThread() ) .subscribeWith( new DisposableSingleObserver<UserModel>() { @Override public void onSuccess( UserModel userModel ) { if ( userModel.isError() ) { view.showErrorInputUsername( userModel.getErrorMessage() ); isUserAvailable = true; } else { view.showErrorInputUsername( userModel.getErrorMessage() ); isUserAvailable = false; } } @Override public void onError( Throwable e ) { e.printStackTrace(); view.showErrorRegister( "خطا! اتصال اینترنت را بررسی کنید." ); } } ); } @Override public void onError( Throwable e ) { } @Override public void onComplete() { } }; } @Override public void clickedRegister() { if ( view != null ) { if ( isUserAvailable ) { return; } String username = view.getUsername(); String email = view.getEmail(); String fullname = view.getFullname(); String password = view.getPassword(); String passwordConfirm = view.getPasswordConfirm(); if ( email.isEmpty() ) { view.showErrorRegister( "لطفا ایمیل را وارد کنید." ); return; } if ( fullname.isEmpty() ) { view.showErrorRegister( "لطفا نام کامل خودتان را وارد کنید." ); return; } if ( password.isEmpty() ) { view.showErrorInputPassword( "لطفا رمز را وارد کنید." ); return; } if ( password.length() <= 5 ) { view.showErrorInputPassword( "لطفا برای رمز حداقل 6 حرف استفاده کنید." ); return; } if ( !password.equals( passwordConfirm ) ) { view.showErrorInputPassword( "رمز ها با هم مطابقت ندارند!" ); return; } if ( username.isEmpty() ) { view.showErrorInputUsername( "لطفا نام کاربری را وارد کنید." ); return; } UserModel userModel = new UserModel(); userModel.setUsername( username ); userModel.setEmail( email ); userModel.setFullname( fullname ); userModel.setPassword( password ); view.showProgress(); subscription.add( repository.registerUser( userModel ) .subscribeOn( Schedulers.io() ) .observeOn( AndroidSchedulers.mainThread() ) .subscribeWith( new DisposableSingleObserver<UserModel>() { @Override public void onSuccess( UserModel userModel ) { if ( !userModel.isError() ) { view.showSuccessRegister( userModel.getErrorMessage() ); } else { view.showErrorRegister( userModel.getErrorMessage() ); } view.hideProgress(); } @Override public void onError( Throwable e ) { view.hideProgress(); view.showErrorRegister( "خطا! اتصال اینترنت را بررسی کنید." ); } } ) ); } } }
UTF-8
Java
6,302
java
SignupPresenter.java
Java
[ { "context": "ta.repository.SignupRepository;\n\n/**\n * Created by Hossein on 5/24/2018.\n */\n\npublic class SignupPresenter i", "end": 669, "score": 0.7258877754211426, "start": 662, "tag": "NAME", "value": "Hossein" }, { "context": "\n }\n String username = ...
null
[]
package ir.hosseinrasti.app.jobjo.ui.user.signup; import com.jakewharton.rxbinding2.widget.RxTextView; import com.jakewharton.rxbinding2.widget.TextViewTextChangeEvent; import java.util.concurrent.TimeUnit; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.observers.DisposableObserver; import io.reactivex.observers.DisposableSingleObserver; import io.reactivex.schedulers.Schedulers; import ir.hosseinrasti.app.jobjo.data.DataSource; import ir.hosseinrasti.app.jobjo.data.entity.UserModel; import ir.hosseinrasti.app.jobjo.data.repository.SignupRepository; /** * Created by Hossein on 5/24/2018. */ public class SignupPresenter implements SignupContract.Presenter { private DataSource.Signup repository; private SignupContract.View view; private CompositeDisposable subscription = new CompositeDisposable(); private boolean isUserAvailable = false; public SignupPresenter( DataSource.Signup repository ) { this.repository = repository; } @Override public void takeView( SignupContract.View view ) { this.view = view; } @Override public void dropView() { view = null; } @Override public void rxUnsubscribe() { subscription.clear(); subscription.dispose(); } @Override public void checkUsername() { subscription.add( RxTextView.textChangeEvents( view.getEdtUserName() ) .skipInitialValue() .debounce( 500, TimeUnit.MILLISECONDS ) .distinctUntilChanged() .subscribeOn( Schedulers.io() ) .observeOn( AndroidSchedulers.mainThread() ) .subscribeWith( search() ) ); } private DisposableObserver<TextViewTextChangeEvent> search() { return new DisposableObserver<TextViewTextChangeEvent>() { @Override public void onNext( TextViewTextChangeEvent textViewTextChangeEvent ) { repository.isUsernameAvailable( textViewTextChangeEvent.text().toString() ) .subscribeOn( Schedulers.newThread() ) .observeOn( AndroidSchedulers.mainThread() ) .subscribeWith( new DisposableSingleObserver<UserModel>() { @Override public void onSuccess( UserModel userModel ) { if ( userModel.isError() ) { view.showErrorInputUsername( userModel.getErrorMessage() ); isUserAvailable = true; } else { view.showErrorInputUsername( userModel.getErrorMessage() ); isUserAvailable = false; } } @Override public void onError( Throwable e ) { e.printStackTrace(); view.showErrorRegister( "خطا! اتصال اینترنت را بررسی کنید." ); } } ); } @Override public void onError( Throwable e ) { } @Override public void onComplete() { } }; } @Override public void clickedRegister() { if ( view != null ) { if ( isUserAvailable ) { return; } String username = view.getUsername(); String email = view.getEmail(); String fullname = view.getFullname(); String password = view.getPassword(); String passwordConfirm = view.getPasswordConfirm(); if ( email.isEmpty() ) { view.showErrorRegister( "لطفا ایمیل را وارد کنید." ); return; } if ( fullname.isEmpty() ) { view.showErrorRegister( "لطفا نام کامل خودتان را وارد کنید." ); return; } if ( password.isEmpty() ) { view.showErrorInputPassword( "لطفا رمز را وارد کنید." ); return; } if ( password.length() <= 5 ) { view.showErrorInputPassword( "لطفا برای رمز حداقل 6 حرف استفاده کنید." ); return; } if ( !password.equals( passwordConfirm ) ) { view.showErrorInputPassword( "رمز ها با هم مطابقت ندارند!" ); return; } if ( username.isEmpty() ) { view.showErrorInputUsername( "لطفا نام کاربری را وارد کنید." ); return; } UserModel userModel = new UserModel(); userModel.setUsername( username ); userModel.setEmail( email ); userModel.setFullname( fullname ); userModel.setPassword( <PASSWORD> ); view.showProgress(); subscription.add( repository.registerUser( userModel ) .subscribeOn( Schedulers.io() ) .observeOn( AndroidSchedulers.mainThread() ) .subscribeWith( new DisposableSingleObserver<UserModel>() { @Override public void onSuccess( UserModel userModel ) { if ( !userModel.isError() ) { view.showSuccessRegister( userModel.getErrorMessage() ); } else { view.showErrorRegister( userModel.getErrorMessage() ); } view.hideProgress(); } @Override public void onError( Throwable e ) { view.hideProgress(); view.showErrorRegister( "خطا! اتصال اینترنت را بررسی کنید." ); } } ) ); } } }
6,304
0.525438
0.523147
165
36.048485
26.426985
95
false
false
0
0
0
0
0
0
0.369697
false
false
13
e89aff7f5885780ef8bea013f54a2b6f963eb5ef
2,508,260,925,512
9d30d4358fd3c012bf3ae09c4ae475ef9626ce7f
/FirstExample.java
26aabaffcbb5032fc04e8eeae0a57d03c94be693
[]
no_license
Lebedok/DoWhileLoop_java
https://github.com/Lebedok/DoWhileLoop_java
760a27211f1030f030f4d04532879426a8ae680b
86188b9bfffad1003d4ec9fe15189cf7b93fb3fc
refs/heads/main
2023-02-01T16:55:30.377000
2020-12-17T18:36:01
2020-12-17T18:36:01
321,541,179
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DoWhileLoop; public class FirstExample { public static void main(String[] args) { //Want to print "Chicago" 5 times using do while loop int count = 1; do { System.out.println("Chicago"); count++; }while (count<=5); System.out.println(count); // 7 int num = 6; while (num<5){ System.out.println("Illinois"); num++; } System.out.println(num); // num will be 6 bc while condition is false } }
UTF-8
Java
539
java
FirstExample.java
Java
[]
null
[]
package DoWhileLoop; public class FirstExample { public static void main(String[] args) { //Want to print "Chicago" 5 times using do while loop int count = 1; do { System.out.println("Chicago"); count++; }while (count<=5); System.out.println(count); // 7 int num = 6; while (num<5){ System.out.println("Illinois"); num++; } System.out.println(num); // num will be 6 bc while condition is false } }
539
0.51577
0.502783
31
16.387096
20.115276
77
false
false
0
0
0
0
0
0
0.322581
false
false
13
18a8dfd9748a9b448a0dce37a68fa52bddda140b
32,091,995,702,059
364ae56a8da9fdb17218415d1117a029226825dc
/src/test/java/com/maya/postcode/PostcodeSearchApplicationTest.java
4dc739f72acdc1307b5c685d84727febb02d84c3
[]
no_license
mayamalakova/PostcodeSearch
https://github.com/mayamalakova/PostcodeSearch
82a2ab439b489a1efd4c8ab42090d8c9891eeb63
f1b69ba49c8f6c2277add896cfd557770a35f71e
refs/heads/master
2021-01-25T11:34:43.345000
2017-06-11T15:16:14
2017-06-11T15:16:14
93,936,255
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.maya.postcode; import com.maya.postcode.client.PostcodeSearchClient; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Created by maja on 09/06/17. */ public class PostcodeSearchApplicationTest { }
UTF-8
Java
253
java
PostcodeSearchApplicationTest.java
Java
[ { "context": "port static org.junit.Assert.*;\n\n/**\n * Created by maja on 09/06/17.\n */\npublic class PostcodeSearchAppli", "end": 188, "score": 0.9947969913482666, "start": 184, "tag": "USERNAME", "value": "maja" } ]
null
[]
package com.maya.postcode; import com.maya.postcode.client.PostcodeSearchClient; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Created by maja on 09/06/17. */ public class PostcodeSearchApplicationTest { }
253
0.766798
0.743083
14
17.142857
17.799908
53
false
false
0
0
0
0
0
0
0.357143
false
false
13
7dc6bb4047edfebedb0779fd7ea889bd7d7ac590
31,963,146,619,584
11e91d4eb8d8a9cc18718182aab5b3d6df619248
/src/main/java/erebus/entity/ai/EntityAIAntsBlock.java
6608da3b5c3ba68b87a666f317d576bfbd2ba5c1
[]
no_license
vadis365/TheErebus
https://github.com/vadis365/TheErebus
3f71eb8344aaaf3226253a2c854cbba7bf4301eb
e0cbec6c69b864b0ffde3b52232e1416a95b6109
refs/heads/mc1.12
2021-06-03T07:25:53.959000
2021-02-21T19:26:09
2021-02-21T19:26:09
16,282,196
20
24
null
false
2023-02-20T21:58:27
2014-01-27T15:02:45
2022-07-26T10:20:14
2021-02-21T19:26:14
54,000
35
34
77
Java
false
false
package erebus.entity.ai; import java.awt.Point; import java.util.List; import erebus.core.helper.Spiral; import erebus.core.helper.Utils; import erebus.entity.EntityBlackAnt; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; public abstract class EntityAIAntsBlock extends EntityAIBase { /** * The bigger you make this value the faster the AI will be. But performance will also decrease so be sensible */ private static final int CHECKS_PER_TICK = 3; private final int EAT_SPEED; protected final EntityLiving entity; private final int maxGrowthMetadata; private final IBlockState blockState; private final ItemStack seed; private boolean hasTarget; public int cropX; public int cropY; public int cropZ; private int spiralIndex; private int eatTicks; private static final List<Point> spiral = new Spiral(8, 8).spiral(); public EntityAIAntsBlock(EntityLiving entity, IBlockState state, int maxGrowthMetadata, ItemStack seed, double moveSpeed, int eatSpeed) { this.entity = entity; this.maxGrowthMetadata = maxGrowthMetadata; blockState = state; this.seed = seed; hasTarget = false; spiralIndex = 0; EAT_SPEED = eatSpeed * 20; } public EntityAIAntsBlock(EntityAnimal entity, IBlockState state, int maxGrowthMetadata, float moveSpeed, int eatSpeed) { this(entity, state, maxGrowthMetadata, null, moveSpeed, eatSpeed); } @Override public boolean shouldExecute() { return true; } @Override public boolean shouldContinueExecuting() { return !entity.isChild(); } @Override public void updateTask() { EntityBlackAnt blackAnt = (EntityBlackAnt) entity; if (!shouldContinueExecuting()) return; int xCoord = blackAnt.getDropPointX(); int yCoord = blackAnt.getDropPointY(); int zCoord = blackAnt.getDropPointZ(); for (int i = 0; i < CHECKS_PER_TICK; i++) if (!hasTarget) { increment(); Point p = getNextPoint(); for (int y = -2; y < 1; y++) if (canEatBlock(entity.getEntityWorld().getBlockState(new BlockPos(xCoord + p.x, yCoord + y, zCoord + p.y)))) { cropX = xCoord + p.x; cropY = yCoord + y; cropZ = zCoord + p.y; hasTarget = true; } } else if (isEntityReady()) { moveToLocation(); entity.getLookHelper().setLookPosition(cropX + 0.5D, cropY + 0.5D, cropZ + 0.5D, 30.0F, 8.0F); AxisAlignedBB blockbounds = getBlockAABB(cropX, cropY, cropZ); boolean flag = entity.getEntityBoundingBox().maxY >= blockbounds.minY && entity.getEntityBoundingBox().minY <= blockbounds.maxY && entity.getEntityBoundingBox().maxX >= blockbounds.minX && entity.getEntityBoundingBox().minX <= blockbounds.maxX && entity.getEntityBoundingBox().maxZ >= blockbounds.minZ && entity.getEntityBoundingBox().minZ <= blockbounds.maxZ; if (flag && canEatBlock(getTargetBlock())) { prepareToEat(); eatTicks++; if (!canEatBlock(getTargetBlock())) { eatingInterupted(); hasTarget = false; eatTicks = 0; return; } else if (EAT_SPEED <= eatTicks) { if (seed != null) Utils.dropStack(entity.getEntityWorld(), new BlockPos(cropX, cropY, cropZ), seed.copy()); hasTarget = false; eatTicks = 0; afterEaten(); return; } } if (!flag && eatTicks > 0 || entity.getEntityWorld().isAirBlock(new BlockPos(cropX, cropY, cropZ))) { eatingInterupted(); hasTarget = false; eatTicks = 0; return; } } } private void increment() { spiralIndex++; if (spiralIndex >= spiral.size()) spiralIndex = 0; } private Point getNextPoint() { return spiral.get(spiralIndex); } public IBlockState getTargetBlock() { IBlockState state = entity.getEntityWorld().getBlockState(new BlockPos(cropX, cropY, cropZ)); return state; } /** * Override this if you wish to do a more advanced checking on which blocks should be eaten * * @param state * @yeah - it uses meta atm :( * @return true is should eat block, false is it shouldn't */ protected boolean canEatBlock(IBlockState state) { return state == blockState && state.getBlock().getMetaFromState(state) == maxGrowthMetadata && state.getBlock() != Blocks.AIR; } /** * Test if entity is ready to eat block * * @return true to allow block to be eaten. false to deny it. */ protected abstract boolean isEntityReady(); /** * Allows you to set mob specific move tasks. */ protected abstract void moveToLocation(); /** * Allows any other tasks to be cancelled just before block has been eaten. */ protected abstract void prepareToEat(); /** * Allows any other tasks to be cancelled if the block cannot be eaten. */ protected abstract void eatingInterupted(); /** * Gets called just after block has been eaten. */ protected abstract void afterEaten(); protected AxisAlignedBB getBlockAABB(int x, int y, int z) { return new AxisAlignedBB(cropX, cropY, cropZ, cropX + 1D, cropY + 1D, cropZ + 1D); } }
UTF-8
Java
5,212
java
EntityAIAntsBlock.java
Java
[]
null
[]
package erebus.entity.ai; import java.awt.Point; import java.util.List; import erebus.core.helper.Spiral; import erebus.core.helper.Utils; import erebus.entity.EntityBlackAnt; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; public abstract class EntityAIAntsBlock extends EntityAIBase { /** * The bigger you make this value the faster the AI will be. But performance will also decrease so be sensible */ private static final int CHECKS_PER_TICK = 3; private final int EAT_SPEED; protected final EntityLiving entity; private final int maxGrowthMetadata; private final IBlockState blockState; private final ItemStack seed; private boolean hasTarget; public int cropX; public int cropY; public int cropZ; private int spiralIndex; private int eatTicks; private static final List<Point> spiral = new Spiral(8, 8).spiral(); public EntityAIAntsBlock(EntityLiving entity, IBlockState state, int maxGrowthMetadata, ItemStack seed, double moveSpeed, int eatSpeed) { this.entity = entity; this.maxGrowthMetadata = maxGrowthMetadata; blockState = state; this.seed = seed; hasTarget = false; spiralIndex = 0; EAT_SPEED = eatSpeed * 20; } public EntityAIAntsBlock(EntityAnimal entity, IBlockState state, int maxGrowthMetadata, float moveSpeed, int eatSpeed) { this(entity, state, maxGrowthMetadata, null, moveSpeed, eatSpeed); } @Override public boolean shouldExecute() { return true; } @Override public boolean shouldContinueExecuting() { return !entity.isChild(); } @Override public void updateTask() { EntityBlackAnt blackAnt = (EntityBlackAnt) entity; if (!shouldContinueExecuting()) return; int xCoord = blackAnt.getDropPointX(); int yCoord = blackAnt.getDropPointY(); int zCoord = blackAnt.getDropPointZ(); for (int i = 0; i < CHECKS_PER_TICK; i++) if (!hasTarget) { increment(); Point p = getNextPoint(); for (int y = -2; y < 1; y++) if (canEatBlock(entity.getEntityWorld().getBlockState(new BlockPos(xCoord + p.x, yCoord + y, zCoord + p.y)))) { cropX = xCoord + p.x; cropY = yCoord + y; cropZ = zCoord + p.y; hasTarget = true; } } else if (isEntityReady()) { moveToLocation(); entity.getLookHelper().setLookPosition(cropX + 0.5D, cropY + 0.5D, cropZ + 0.5D, 30.0F, 8.0F); AxisAlignedBB blockbounds = getBlockAABB(cropX, cropY, cropZ); boolean flag = entity.getEntityBoundingBox().maxY >= blockbounds.minY && entity.getEntityBoundingBox().minY <= blockbounds.maxY && entity.getEntityBoundingBox().maxX >= blockbounds.minX && entity.getEntityBoundingBox().minX <= blockbounds.maxX && entity.getEntityBoundingBox().maxZ >= blockbounds.minZ && entity.getEntityBoundingBox().minZ <= blockbounds.maxZ; if (flag && canEatBlock(getTargetBlock())) { prepareToEat(); eatTicks++; if (!canEatBlock(getTargetBlock())) { eatingInterupted(); hasTarget = false; eatTicks = 0; return; } else if (EAT_SPEED <= eatTicks) { if (seed != null) Utils.dropStack(entity.getEntityWorld(), new BlockPos(cropX, cropY, cropZ), seed.copy()); hasTarget = false; eatTicks = 0; afterEaten(); return; } } if (!flag && eatTicks > 0 || entity.getEntityWorld().isAirBlock(new BlockPos(cropX, cropY, cropZ))) { eatingInterupted(); hasTarget = false; eatTicks = 0; return; } } } private void increment() { spiralIndex++; if (spiralIndex >= spiral.size()) spiralIndex = 0; } private Point getNextPoint() { return spiral.get(spiralIndex); } public IBlockState getTargetBlock() { IBlockState state = entity.getEntityWorld().getBlockState(new BlockPos(cropX, cropY, cropZ)); return state; } /** * Override this if you wish to do a more advanced checking on which blocks should be eaten * * @param state * @yeah - it uses meta atm :( * @return true is should eat block, false is it shouldn't */ protected boolean canEatBlock(IBlockState state) { return state == blockState && state.getBlock().getMetaFromState(state) == maxGrowthMetadata && state.getBlock() != Blocks.AIR; } /** * Test if entity is ready to eat block * * @return true to allow block to be eaten. false to deny it. */ protected abstract boolean isEntityReady(); /** * Allows you to set mob specific move tasks. */ protected abstract void moveToLocation(); /** * Allows any other tasks to be cancelled just before block has been eaten. */ protected abstract void prepareToEat(); /** * Allows any other tasks to be cancelled if the block cannot be eaten. */ protected abstract void eatingInterupted(); /** * Gets called just after block has been eaten. */ protected abstract void afterEaten(); protected AxisAlignedBB getBlockAABB(int x, int y, int z) { return new AxisAlignedBB(cropX, cropY, cropZ, cropX + 1D, cropY + 1D, cropZ + 1D); } }
5,212
0.702034
0.696662
175
28.788572
37.858925
364
false
false
0
0
0
0
0
0
2.525714
false
false
13