blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
8cbf7a9dfe743cb100a880d04ed9500c42544681 | Java | sp0gg/GildedRose_java | /src/com/sp0gg/gildedrose/Inventory.java | UTF-8 | 234 | 2.640625 | 3 | [] | no_license | package com.sp0gg.gildedrose;
public class Inventory {
private Item[] items;
public Inventory(Item[] items) {
this.items = items;
}
public void updateQuality() {
for (Item item : items) {
item.updateQuality();
}
}
}
| true |
44e7890cd3d8713b1348d46ea7f4b52f82f7cf8b | Java | cy-default/learning | /learning-springcloud/src/main/java/com/rm13/cloud/exception/CustomException.java | UTF-8 | 1,369 | 3.015625 | 3 | [] | no_license | package com.rm13.cloud.exception;
import lombok.Data;
/**
* 业务类异常,不记录带有栈追踪信息的Exception;(fillInStackTrace性能慢50倍)/ 可以重写fillInStackTrace
*
* @author yuan.chen
* @email chen.yuan135@chinaredstar.com
* @Date 2019-06-25
*/
@Data
public class CustomException extends RuntimeException {
private Integer code;
private String message;
/**
* 仅包含message, 没有cause, 也不记录栈异常, 性能最高
*
* @param message
*/
public CustomException(Integer code, String message) {
this(code, message, false);
}
/**
* 包含message, 可指定是否记录异常
*
* @param msg
* @param recordStackTrace
*/
public CustomException(Integer code, String msg, boolean recordStackTrace) {
super(msg, null, false, recordStackTrace);
this.code = code;
this.message = msg;
}
/**
* 包含message和cause, 会记录栈异常
*
* @param msg
* @param cause
*/
public CustomException(Integer code, String msg, Throwable cause) {
super(msg, cause, false, true);
}
/**
* 重写fillInStackTrace
* 避免对异常进行昂贵且无用的堆栈跟踪
*
* @return
*/
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
}
| true |
44279fde0db50052cecccde4bc7da9b93ddde3cb | Java | neetavarkala/miui_framework_clover | /android/util/SparseArray.java | UTF-8 | 7,051 | 2.21875 | 2 | [] | no_license | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
package android.util;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.GrowingArrayUtils;
import libcore.util.EmptyArray;
// Referenced classes of package android.util:
// ContainerHelpers
public class SparseArray
implements Cloneable
{
public SparseArray()
{
this(10);
}
public SparseArray(int i)
{
mGarbage = false;
if(i == 0)
{
mKeys = EmptyArray.INT;
mValues = EmptyArray.OBJECT;
} else
{
mValues = ArrayUtils.newUnpaddedObjectArray(i);
mKeys = new int[mValues.length];
}
mSize = 0;
}
private void gc()
{
int i = mSize;
int j = 0;
int ai[] = mKeys;
Object aobj[] = mValues;
for(int k = 0; k < i;)
{
Object obj = aobj[k];
int l = j;
if(obj != DELETED)
{
if(k != j)
{
ai[j] = ai[k];
aobj[j] = obj;
aobj[k] = null;
}
l = j + 1;
}
k++;
j = l;
}
mGarbage = false;
mSize = j;
}
public void append(int i, Object obj)
{
if(mSize != 0 && i <= mKeys[mSize - 1])
{
put(i, obj);
return;
}
if(mGarbage && mSize >= mKeys.length)
gc();
mKeys = GrowingArrayUtils.append(mKeys, mSize, i);
mValues = GrowingArrayUtils.append(mValues, mSize, obj);
mSize = mSize + 1;
}
public void clear()
{
int i = mSize;
Object aobj[] = mValues;
for(int j = 0; j < i; j++)
aobj[j] = null;
mSize = 0;
mGarbage = false;
}
public SparseArray clone()
{
SparseArray sparsearray = null;
SparseArray sparsearray1 = (SparseArray)super.clone();
sparsearray = sparsearray1;
sparsearray1.mKeys = (int[])mKeys.clone();
sparsearray = sparsearray1;
sparsearray1.mValues = (Object[])mValues.clone();
sparsearray = sparsearray1;
_L2:
return sparsearray;
CloneNotSupportedException clonenotsupportedexception;
clonenotsupportedexception;
if(true) goto _L2; else goto _L1
_L1:
}
public volatile Object clone()
throws CloneNotSupportedException
{
return clone();
}
public void delete(int i)
{
i = ContainerHelpers.binarySearch(mKeys, mSize, i);
if(i >= 0 && mValues[i] != DELETED)
{
mValues[i] = DELETED;
mGarbage = true;
}
}
public Object get(int i)
{
return get(i, null);
}
public Object get(int i, Object obj)
{
i = ContainerHelpers.binarySearch(mKeys, mSize, i);
if(i < 0 || mValues[i] == DELETED)
return obj;
else
return mValues[i];
}
public int indexOfKey(int i)
{
if(mGarbage)
gc();
return ContainerHelpers.binarySearch(mKeys, mSize, i);
}
public int indexOfValue(Object obj)
{
if(mGarbage)
gc();
for(int i = 0; i < mSize; i++)
if(mValues[i] == obj)
return i;
return -1;
}
public int indexOfValueByValue(Object obj)
{
if(mGarbage)
gc();
for(int i = 0; i < mSize; i++)
{
if(obj == null)
{
if(mValues[i] == null)
return i;
continue;
}
if(obj.equals(mValues[i]))
return i;
}
return -1;
}
public int keyAt(int i)
{
if(mGarbage)
gc();
return mKeys[i];
}
public void put(int i, Object obj)
{
int j = ContainerHelpers.binarySearch(mKeys, mSize, i);
if(j >= 0)
{
mValues[j] = obj;
} else
{
int k = j;
if(k < mSize && mValues[k] == DELETED)
{
mKeys[k] = i;
mValues[k] = obj;
return;
}
j = k;
if(mGarbage)
{
j = k;
if(mSize >= mKeys.length)
{
gc();
j = ContainerHelpers.binarySearch(mKeys, mSize, i);
}
}
mKeys = GrowingArrayUtils.insert(mKeys, mSize, j, i);
mValues = GrowingArrayUtils.insert(mValues, mSize, j, obj);
mSize = mSize + 1;
}
}
public void remove(int i)
{
delete(i);
}
public void removeAt(int i)
{
if(mValues[i] != DELETED)
{
mValues[i] = DELETED;
mGarbage = true;
}
}
public void removeAtRange(int i, int j)
{
for(j = Math.min(mSize, i + j); i < j; i++)
removeAt(i);
}
public Object removeReturnOld(int i)
{
i = ContainerHelpers.binarySearch(mKeys, mSize, i);
if(i >= 0 && mValues[i] != DELETED)
{
Object obj = mValues[i];
mValues[i] = DELETED;
mGarbage = true;
return obj;
} else
{
return null;
}
}
public void setValueAt(int i, Object obj)
{
if(mGarbage)
gc();
mValues[i] = obj;
}
public int size()
{
if(mGarbage)
gc();
return mSize;
}
public String toString()
{
if(size() <= 0)
return "{}";
StringBuilder stringbuilder = new StringBuilder(mSize * 28);
stringbuilder.append('{');
int i = 0;
while(i < mSize)
{
if(i > 0)
stringbuilder.append(", ");
stringbuilder.append(keyAt(i));
stringbuilder.append('=');
Object obj = valueAt(i);
if(obj != this)
stringbuilder.append(obj);
else
stringbuilder.append("(this Map)");
i++;
}
stringbuilder.append('}');
return stringbuilder.toString();
}
public Object valueAt(int i)
{
if(mGarbage)
gc();
return mValues[i];
}
private static final Object DELETED = new Object();
private boolean mGarbage;
private int mKeys[];
private int mSize;
private Object mValues[];
}
| true |
b977b169727539ce0a78ccbabb1ebbcabb817ece | Java | szyna/AvalonStatTracker | /app/src/main/java/az/avalonstattracker/MainActivity.java | UTF-8 | 3,904 | 2.15625 | 2 | [] | no_license | package az.avalonstattracker;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
public String TAG = "MainActivity";
Utilities utils;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
utils = new Utilities(this);
}
public void addGame(View view){
AddGameActivity.utils = utils;
Intent intent = new Intent(this, AddGameActivity.class);
startActivity(intent);
}
public void addPlayer(View view){
Context context = this;
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.add_player_alert, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, R.style.DialogTheme);
alertDialogBuilder.setView(promptsView);
final EditText userInput = promptsView.findViewById(R.id.add_player_alert_btn);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Add player",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String player_name = userInput.getText().toString();
String text;
boolean success;
switch (utils.dbHelper.addPlayer(player_name)) {
case 1: text = "Player name cannot be empty!";
success = false;
break;
case 2: text = "Player name already exists!";
success = false;
break;
default: text = "Player added successfully";
success = true;
}
Animations.addFadeOutTextAnimation(
getApplicationContext(),
(RelativeLayout) findViewById(R.id.const_layout),
text,
success
);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
public void showGameHistory(View view){
GameHistoryActivity.utils = utils;
Intent intent = new Intent(this, GameHistoryActivity.class);
startActivity(intent);
}
public void showStatistics(View view){
StatisticsActivity.utils = utils;
Intent intent = new Intent(this, StatisticsActivity.class);
startActivity(intent);
}
public void showRankings(View view){
RankingsActivity.utils = utils;
Intent intent = new Intent(this, RankingsActivity.class);
startActivity(intent);
}
}
| true |
b531eef2d87a991f245e1abfb5f7e03a8380d1a5 | Java | fzx-wsss/study | /study/src/main/java/com/wsss/algorithm/hot/spot/model/TotalLimitFlow.java | UTF-8 | 1,728 | 2.125 | 2 | [] | no_license | package com.wsss.algorithm.hot.spot.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public class TotalLimitFlow implements Serializable {
private static final long serialVersionUID = -3720479033004210338L;
/** 主键CODE */
private String code;
/** 版本号 */
private Integer optimistic;
/** 创建日期 */
private Date createDate;
/** 日使用流量 */
private BigDecimal dayFlow;
/** 月使用流量 */
private BigDecimal monthFlow;
/**
* 总限额CODE
* 参照表:TOTAL_LIMIT主键
*/
private String limitCode;
/** 备注 */
private String remark;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code == null ? null : code.trim();
}
public Integer getOptimistic() {
return optimistic;
}
public void setOptimistic(Integer optimistic) {
this.optimistic = optimistic;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public BigDecimal getDayFlow() {
return dayFlow;
}
public void setDayFlow(BigDecimal dayFlow) {
this.dayFlow = dayFlow;
}
public BigDecimal getMonthFlow() {
return monthFlow;
}
public void setMonthFlow(BigDecimal monthFlow) {
this.monthFlow = monthFlow;
}
public String getLimitCode() {
return limitCode;
}
public void setLimitCode(String limitCode) {
this.limitCode = limitCode == null ? null : limitCode.trim();
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
} | true |
04c0fa93814b7d86c86ff52877c378fa246c45ec | Java | ctripcorp/x-pipe | /redis/redis-core/src/main/java/com/ctrip/xpipe/redis/core/redis/rdb/encoding/StreamListpackIterator.java | UTF-8 | 3,013 | 2.421875 | 2 | [
"Apache-2.0"
] | permissive | package com.ctrip.xpipe.redis.core.redis.rdb.encoding;
import com.ctrip.xpipe.redis.core.redis.exception.RdbStreamParseFailException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author lishanglin
* date 2022/6/23
*/
public class StreamListpackIterator {
private StreamID masterId;
private Listpack listpack;
private AtomicInteger cursor;
private long size;
private long deletedSize;
private long masterFieldsSize;
private List<byte[]> masterFields;
private static final byte STREAM_ITEM_FLAG_NONE = 0;
private static final byte STREAM_ITEM_FLAG_DELETED = 0b01;
private static final byte STREAM_ITEM_FLAG_SAMEFIELDS = 0b10;
public StreamListpackIterator(StreamID masterId, Listpack listpack) {
this.masterId = masterId;
this.listpack = listpack;
this.cursor = new AtomicInteger(0);
this.decodeHeader();
}
private void decodeHeader() {
this.size = listpack.getElement(0).getInt();
this.deletedSize = listpack.getElement(1).getInt();
this.masterFieldsSize = listpack.getElement(2).getInt();
this.cursor.set(3);
this.masterFields = new LinkedList<>();
while (cursor.get() < masterFieldsSize + 3) {
this.masterFields.add(listpack.getElement(cursor.getAndIncrement()).getBytes());
}
this.cursor.incrementAndGet(); // skip master term
}
public boolean hasNext() {
return this.cursor.get() < this.listpack.size();
}
public StreamEntry next() {
if (!hasNext()) throw new RdbStreamParseFailException("no more data");
long flag = listpack.getElement(cursor.getAndIncrement()).getInt();
long relatedMs = listpack.getElement(cursor.getAndIncrement()).getInt();
long relatedSeq = listpack.getElement(cursor.getAndIncrement()).getInt();
StreamEntry streamEntry = new StreamEntry(
new StreamID(masterId.getMs() + relatedMs, masterId.getSeq() + relatedSeq),
0 != (flag & STREAM_ITEM_FLAG_DELETED));
boolean sameFields = 0 != (flag & STREAM_ITEM_FLAG_SAMEFIELDS);
long fieldsSize;
if (sameFields) {
fieldsSize = masterFieldsSize;
} else {
fieldsSize = listpack.getElement(cursor.getAndIncrement()).getInt();
}
for (int i = 0; i < fieldsSize; i++) {
if (sameFields) {
byte[] value = listpack.getElement(cursor.getAndIncrement()).getBytes();
streamEntry.addField(masterFields.get(i), value);
} else {
byte[] field = listpack.getElement(cursor.getAndIncrement()).getBytes();
byte[] value = listpack.getElement(cursor.getAndIncrement()).getBytes();
streamEntry.addField(field, value);
}
}
this.cursor.incrementAndGet(); // skip prev entry lp-count
return streamEntry;
}
}
| true |
6fa68963cd67cf6e3c1c8bee6a65ec865b4dd375 | Java | MeteorProject/CharGer | /util/CGUtil.java | UTF-8 | 18,551 | 3.1875 | 3 | [] | no_license | package charger.util;
import charger.*;
import charger.obj.*;
import java.util.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.Color.*;
import javax.swing.*;
/**
* Utility classes (all static!) that should be of fairly general use
*/
public class CGUtil {
/**
* Displays the text string centered about the point x,y in the given color.
* taken from p 586, Naughton and Schildt, 1996
*
* @param g the current Graphics context
* @param s the string to be displayed
* @param x horizontal position of the centerpoint (in pixels)
* @param y vertical position of the centerpoint (in pixels)
* @param c the color to be displayed
*/
static public void drawCenteredString( Graphics2D g, String s, double x, double y, Color c ) {
FontMetrics fm = g.getFontMetrics();
double startx = x - ( ( fm.stringWidth( s ) ) / 2 );
// float starty = y + ( fm.getAscent() + fm.getDescent() + fm.getLeading() ) / 2;
double starty = y - 1 + ( fm.getDescent() + fm.getAscent() ) / 2;
Color oldcolor = g.getColor();
g.setColor( c );
g.drawString( s, (float)startx, (float)starty );
g.setColor( oldcolor );
}
/**
* Displays a centered text string in black
*
* @see CGUtil#drawCenteredString
*/
static public void drawCenteredString( Graphics2D g, String s, double x, double y ) {
drawCenteredString( g, s, x, y, Color.black );
}
static public void drawCenteredString( Graphics2D g, String s, Point2D.Double p, Color c ) {
drawCenteredString( g, s, p.x, p.y, c );
}
/**
* Returns the short (un-qualified) name string of the given object
*
* @param obj Any Java object
* @return unqualified name of the object's class
*/
static public String shortClassName( Object obj ) {
String full = obj.getClass().getName();
int index = full.lastIndexOf( '.' );
if ( index == 0 ) {
return full;
} else {
return full.substring( index + 1 );
}
}
/**
* Find the lower left point for displaying a string whose center point is
* known. adapted from p 586, Naughton and Schildt, 1996
*
* @param fm any font metrics
* @param s the string to be displayed
* @param center position of the centerpoint (in pixels)
*/
static public Point2D.Double getStringLowerLeftFromCenter( FontMetrics fm, String s, Point2D.Double center ) {
if ( fm == null || s == null ) {
return center;
}
double startx = center.x - ( ( fm.stringWidth( s ) ) / 2 );
//int starty = center.y - 1 + ( fm.getDescent() + fm.getAscent() )/2;
double starty = center.y - 1 + ( fm.getAscent() ) / 2;
return new Point2D.Double( startx, starty );
}
// /**
// *
// * @param objects
// * @param how either "vertical" or "horizontal"
// */
// public static void alignObjects( ArrayList<GraphObject> objects, String how ) {
//
// }
/**
* Gather together all the selected nodes, edges and graphs into a list. The
* list is sorted: graphs first, then nodes then edges. Responsible for making sure that no object
* is included more than once (e.g., if it is enclosed in a graph that's in
* the list as well as appearing by itself.) If an edge is in the list, but
* either of its linked nodes is NOT in the list, then the edge is not
* included. If any two selected nodes are linked by an edge, then that edge
* should be included whether it was originally selected or not.
*
* @return collection of selected objects
*/
public static ArrayList<GraphObject> sortObjects( ArrayList<GraphObject> list ) {
Iterator iter = list.iterator();
GraphObject go = null;
ArrayList<Graph> graphs = new ArrayList<>();
ArrayList<GNode> nodes = new ArrayList<>();
ArrayList<GEdge> edges = new ArrayList<>();
while ( iter.hasNext() ) { // looking at all selected elements in the graph, ignoring edges
go = (GraphObject)iter.next();
// if the object is in a graph that's selected, then skip it
if ( list.contains( go.getOwnerGraph() )) continue;
//if (go.isSelected) {
if ( go.myKind == GraphObject.Kind.GRAPH ) {
graphs.add( (Graph)go );
} else if ( go.myKind == GraphObject.Kind.GNODE ) {
nodes.add( (GNode)go );
} else if ( go.myKind == GraphObject.Kind.GEDGE ) {
edges.add( (GEdge)go );
}
}
//}
ArrayList<GraphObject> sortedOnes = new ArrayList<>();
sortedOnes.addAll( graphs );
sortedOnes.addAll( nodes );
sortedOnes.addAll( edges );
return sortedOnes;
}
/**
* returns the AWT rectangle given any two opposite corners, correcting for
* signs. Corners may either be a combination of upper left and lower right
* or else upper right and lower left.
*
* @param x1 are the x,y's for points 1 and 2 representing opposite corners
* of a rectangle
* @param y1
* @param x2
* @param y2
*/
static public Rectangle2D.Double adjustForCartesian( double x1, double y1, double x2, double y2 ) {
Rectangle2D.Double r = new Rectangle2D.Double( x1, y1, Math.abs( x1 - x2 ), Math.abs( y1 - y2 ) );
if ( x1 > x2 ) {
r.x = x2;
}
if ( y1 > y2 ) {
r.y = y2;
}
return r;
}
/**
* returns the AWT rectangle given its two opposite corners
*
* @param p1 and p2 are the two points representing opposite corners of a
* rectangle
* @param p2
*/
static public Rectangle2D.Double adjustForCartesian( Point2D.Double p1, Point2D.Double p2 ) {
Rectangle2D.Double r = new Rectangle2D.Double( p1.x, p1.y, Math.abs( p1.x - p2.x ), Math.abs( p1.y - p2.y ) );
if ( p1.x > p2.x ) {
r.x = p2.x;
}
if ( p1.y > p2.y ) {
r.y = p2.y;
}
return r;
}
/**
* Calculate height and width on a string using a given font metrics.
*
* @param s String whose dimensions are desired.
* @param fm Font metrics under which the string is to be rendered.
* @return Dimensions of the string.
*/
static public Dimension stringDimensions( String s, FontMetrics fm ) {
//Global.info( "stringDimensions -- \"" + s ;
if ( s == null ) {
s = "";
}
Dimension returnOne = new Dimension();
if ( fm == null ) {
fm = Global.defaultFontMetrics;
}
if ( fm != null ) {
returnOne.height = fm.getHeight();
returnOne.width = fm.stringWidth( s );
}
return returnOne;
}
/**
* Loads choice list from the enumeration given. Makes no assumptions about
* whether choice is visible, listened-to, etc.
*
* @param c The (already allocated) Choice to be loaded
* @param choices The list of choice strings to be put into the list.
* @param fm The currently applicable font metrics, used for determining
* size of box
*/
public static int fillChoiceList( JComboBox c, String[] choices, FontMetrics fm ) {
float width = 0;
float height = fm.getHeight();
if ( c.getItemCount() > 0 ) {
c.removeAllItems();
}
for ( int choicenum = 0; choicenum < choices.length; choicenum++ ) {
String s = choices[ choicenum];
c.addItem( s );
Dimension dim = CGUtil.stringDimensions( s, fm );
float w = (float)dim.getWidth();
//Global.info( "width of string " + s + " is " + w );
if ( w > width ) {
width = w;
}
}
return (int)width;
//Global.info( "width of choice box is " + width );
// c.setSize( new Dimension( (int)width * 2, (int)( height * 2 ) ) );
}
/**
* Loads given text field with given string, resizing the field if
* necessary. Makes no assumptions about whether field is visible,
* listened-to, etc.
*
* @param tf The (already allocated) TextField to be loaded
* @param textLabel The string to load into tf
* @param fm font metrics from the context for which the combo box will be
* sized
*/
public static void loadSizedTextField( JTextField tf, String textLabel, FontMetrics fm ) {
tf.setText( textLabel );
int width = fm.stringWidth( textLabel ) * 2;
if ( width < fm.stringWidth( "MMMM" ) ) {
width = fm.stringWidth( "MMMM" );
}
// tf.setSize( width, fm.getHeight() * 4 / 3 );
// tf.setFont( fm.getFont() );
}
/**
* Loads combo box, setting given string as the default, resizing the field
* if necessary. Assumes combo box is initialized and if popup is used,
* popup is already filled.
*
* @param cb The (already allocated) JComboBox to be loaded
* @param textLabel The string to load into tf
* @param fm font metrics from the context for which the combo box will be
* sized
*/
public static void loadSizedComboBox( JComboBox cb, String textLabel, FontMetrics fm ) {
//Global.info( "load combo box to match " + textLabel );
cb.setFont( fm.getFont() );
int count = cb.getItemCount();
int k = 0;
while ( k < count && !( (String)cb.getItemAt( k ) ).equalsIgnoreCase( textLabel ) ) {
k++;
}
if ( k < count ) {
cb.setSelectedIndex( k );
}
int width = 0;
for ( k = 0; k < count; k++ ) {
int w = fm.stringWidth( (String)cb.getItemAt( k ) );
if ( width < w ) {
width = w;
}
}
// cb.setSize( width + 40, fm.getHeight() * 5 / 2 );
// cb.setPreferredSize( cb.getSize() );
ComboBoxEditor editor = cb.getEditor();
Component editorComp = editor.getEditorComponent();
//Global.info( "selected index is " + k + " out of " + count );
cb.getEditor().getEditorComponent().setFont( fm.getFont() );
// cb.getEditor().getEditorComponent().setSize( cb.getSize() );
// cb.getEditor().getEditorComponent().setMinimumSize( cb.getSize() );
}
/**
* Determines the union of a set of nodes' display rectangles. For a context
* node, treats its entire extent as its rectangle.
*
* @param nodeList Set of Graph objects.
* @return union of nodeList's display rectangles
*/
public static Rectangle2D.Double unionDisplayRects( ArrayList nodeList ) {
Iterator iter = nodeList.iterator();
GraphObject go = null;
Rectangle2D.Double r = null;
while ( iter.hasNext() ) {
go = (GraphObject)iter.next();
if ( r == null ) {
r = Util.make2DDouble( go.displayRect );
} else {
r.add( Util.make2DDouble( go.displayRect ));
}
}
return r;
}
/**
* Displays a point's coordinates in text at its location.
*
* @param g context in which to draw
* @param p point being displayed.
*/
public static void showPoint( Graphics2D g, Point2D.Double p ) {
g.drawString( "(" + Math.round(p.x) + "," + Math.round(p.y) + ")", (float)p.x, (float)p.y );
}
// /**
// * Creates a color-complement version of an ImageIcon.
// *
// * @param normal the image icon to be reversed.
// * @param c some component to which the image icon belongs
// * @return inverted icon
// */
// public static ImageIcon invertImageIcon( ImageIcon normal, Component c ) {
// Image src = normal.getImage();
// ImageFilter colorfilter = new InvertFilter();
// Image img = c.createImage( new FilteredImageSource( src.getSource(), colorfilter ) );
// return new ImageIcon( img );
// }
/**
* Returns the darker of the two colors, using a very crude algorithm.
*/
public static Color getDarkest( Color c1, Color c2 ) {
int sum1 = c1.getRed() + c1.getBlue() + c1.getGreen();
int sum2 = c2.getRed() + c2.getBlue() + c2.getGreen();
if ( sum1 < sum2 ) {
return c1;
} else {
return c2;
}
}
// /**
// * Mimics behavior of jawa.awt.Rectangle.grow which was oddly omitted from
// * Rectangle2D
// */
// public static void grow( Rectangle2D.Float r, float xinc, float yinc ) {
// float newx = r.x - xinc;
// float newy = r.y - yinc;
// float newwidth = r.width + 2 * xinc;
// float newheight = r.height + 2 * yinc;
// r.setFrame( newx, newy, newwidth, newheight );
// }
/**
* Mimics behavior of jawa.awt.Rectangle.grow which was oddly omitted from
* Rectangle2D
*/
public static void grow( Rectangle2D.Double r, double xinc, double yinc ) {
double newx = r.x - xinc;
double newy = r.y - yinc;
double newwidth = r.width + 2 * xinc;
double newheight = r.height + 2 * yinc;
r.setFrame( newx, newy, newwidth, newheight );
}
/**
* Returns the center of the rectangle as a Point2D.Double
*/
public static Point2D.Double getCenter( Rectangle2D.Double r ) {
return new Point2D.Double( r.getCenterX(), r.getCenterY() );
}
/** Used in determining connected components. */
public static ArrayList< ArrayList<GNode> > getConnectedComponents( Graph g ) {
HashMap<GNode, Integer> componentLabels = new HashMap<>();
ArrayList< ArrayList<GNode> > nodeLists = new ArrayList< ArrayList<GNode>>();
/* Initialize the hashmap so that all nodes have zero (meaning not visited yet).
* Traverse the graph, starting at 1, and label each node in the hashmap with
* that integer until you can't reach any more.
* Increment counter, look for unvisited nodes and repeat until all nodes are accounted for.
*/
ShallowIterator iterForInit = new ShallowIterator( g, GraphObject.Kind.GNODE );
while ( iterForInit.hasNext() ) {
GNode go = (GNode)iterForInit.next();
componentLabels.put( go, Integer.valueOf( -1) );
}
int componentNum = -1;
// while there are still unlabeled nodes
while ( componentLabels.containsValue( Integer.valueOf( -1 )) ) {
componentNum++;
// find an unlabeled node, and label everything connected to it.
Object[] nodes = componentLabels.keySet().toArray();
int nodenum = 0;
while ( ! componentLabels.get( (GNode)nodes[nodenum] ).equals( Integer.valueOf(-1)) )
nodenum++;
//
GNode startNode = (GNode)nodes[nodenum] ;
labelConnectedNodes( componentLabels, startNode, componentNum );
}
// set up all the empty component label lists
for ( int cnum = 0; cnum <= componentNum; cnum++ ) {
ArrayList<GNode> labelsForOneComponent = new ArrayList<GNode>();
nodeLists.add( labelsForOneComponent );
}
// display the results
for ( int cnum = 0; cnum <= componentNum; cnum++ ) {
for ( GNode node : componentLabels.keySet() ) {
if ( componentLabels.get( node).equals( Integer.valueOf( cnum) ) ) {
// Global.info( " node " + node.getTextLabel() );
nodeLists.get( cnum ).add( node );
}
}
// Global.info( "Component number " + cnum + " has " + nodeLists.get( cnum ).size() + " nodes.");
}
return nodeLists;
}
/**
* Start by labeling the start node and then recursively find all the others
*
* @param startNode
*/
private static void labelConnectedNodes( HashMap<GNode, Integer> componentLabels, GNode startNode, int componentNum ) {
Integer label = Integer.valueOf( componentNum );
componentLabels.put( startNode, label );
ArrayList<GEdge> edges = startNode.getEdges();
for ( GEdge edge : edges ) { // for all edges, label their other nodes
GNode oneToLabel = null;
if ( edge.howLinked( startNode ) == GEdge.Direction.FROM ) {
oneToLabel = (GNode)edge.toObj;
} else { // startNode is the "to" node
oneToLabel = (GNode)edge.fromObj;
}
// Don't have to worry here about contexts in the spring algorithm at least,
// because we've already installed custom edges for contexts
if ( componentLabels.get( oneToLabel ) == Integer.valueOf( -1 ) ) {
labelConnectedNodes( componentLabels, oneToLabel, componentNum );
}
}
}
/**
* Finds the center of the bounding rectangle that enclosed all the nodes
* @param nodes
* @return the center point of the rectangle that bounds all of the nodes in the list.
*/
static public Point2D.Double getCenterPoint( ArrayList<GNode> nodes ) {
if ( nodes.size() == 0 ) return null;
Rectangle2D.Double rect = Util.make2DDouble( nodes.get( 0 ).getDisplayRect() );
for ( GNode node : nodes ) {
rect.add( node.getDisplayRect());
}
return new Point2D.Double( rect.x + rect.width/2, rect.y + rect.height / 2 );
}
/**
* Finds the object in the list that is closest to the point given
*/
static public GNode closestObject( ArrayList<GNode> nodes, Point2D.Double point ) {
if ( nodes.size() == 0 ) return null;
double shortest = Double.MAX_VALUE;
GNode closest = null;
for ( GNode node : nodes ) {
// if ( node instanceof Graph ) continue;
double distance = node.getCenter().distance( point );
if ( distance < shortest ) {
shortest = distance;
closest = node;
}
}
return closest;
}
}
| true |
5ae8efa381656cde594ce1e9f3bf7bb501af9cca | Java | cha63506/CompSecurity | /Spotify_source/src/fju.java | UTF-8 | 1,762 | 1.78125 | 2 | [] | no_license | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.spotify.android.paste.widget.SpotifyIconView;
public final class fju extends fjr
{
private int a;
private int b;
private View c;
private TextView d;
private TextView e;
public fju()
{
a = -1;
b = -1;
cvp.a(true, "You must specify a title string resource ID");
cvp.a(true, "You must specify a body string resource ID");
a = 0x7f08037f;
b = 0x7f08037e;
}
public final void a(LayoutInflater layoutinflater, ViewGroup viewgroup)
{
c = layoutinflater.inflate(0x7f03013d, viewgroup, false);
d = (TextView)c.findViewById(0x7f1104d0);
e = (TextView)c.findViewById(0x7f1104d1);
((SpotifyIconView)c.findViewById(0x7f1102b9)).setOnClickListener(new android.view.View.OnClickListener() {
private fju a;
public final void onClick(View view)
{
a.c();
}
{
a = fju.this;
super();
}
});
viewgroup.addView(c);
if (a > 0)
{
d.setText(a);
} else
{
d.setText(null);
}
d.setVisibility(0);
if (b > 0)
{
e.setText(b);
} else
{
e.setText(null);
}
e.setVisibility(0);
}
public final void a(ViewGroup viewgroup)
{
viewgroup.removeView(c);
}
}
| true |
4f32a038274aac2e91c90e953bc0a0c24d99915b | Java | kinny94/data-stucture-and-algo | /Patterns/Two Pointer/ComparingStringContainingBackspaces.java | UTF-8 | 1,537 | 3.609375 | 4 | [] | no_license | class ComparingStringContainingBackspaces {
public boolean compare(String str1, String str2) {
int index1 = str1.length() - 1;
int index2 = str2.length() - 1;
while (index1 >=0 || index2 >= 0) {
int i1 = getNextValidCharacter(str1, index1);
int i2 = getNextValidCharacter(str2, index2);
System.out.println(i1 + " : " + i2);
if (i1 < 0 && i2 < 0) {
return true;
}
if (i1 < 0 || i2 < 0) {
return false;
}
if (str1.charAt(i1) != str2.charAt(i2)) {
return false;
}
index1 = i1 - 1;
index2 = i2 - 1;
}
return true;
}
private int getNextValidCharacter(String str, int index) {
int backspaceCount = 0;
while (index >= 0) {
if (str.charAt(index) == '#') {
backspaceCount++;
} else if (backspaceCount > 0) {
backspaceCount--;
} else {
break;
}
index--;
}
return index;
}
public static void main(String[] args) {
ComparingStringContainingBackspaces obj = new ComparingStringContainingBackspaces();
System.out.println(obj.compare("xy#z", "xzz#"));
System.out.println(obj.compare("xy#z", "xyz#"));
System.out.println(obj.compare("xp#", "xyz##"));
System.out.println(obj.compare("xywrrmp", "xywrrmu#p"));
}
} | true |
a7fee137b58fe49cc35bce69dd7f714958ea794d | Java | PacktPublishing/Spring-MVC-Blueprints | /Chapter 04/Ch04/src/main/java/org/packt/human/resource/portal/controller/GoogleChartClient.java | UTF-8 | 1,702 | 2.1875 | 2 | [
"MIT"
] | permissive | package org.packt.human.resource.portal.controller;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.JsonObject;
@Controller
public class GoogleChartClient {
@RequestMapping(value = "/getReportData", method = RequestMethod.GET)
public @ResponseBody
String loadData(HttpServletResponse response) {
JsonObject piedata1 = new JsonObject();
piedata1.addProperty("value", Integer.parseInt("30"));
piedata1.addProperty("color", "#F38630");
piedata1.addProperty("title", "INDIA");
JsonObject piedata2 = new JsonObject();
piedata2.addProperty("value", Integer.parseInt("50"));
piedata2.addProperty("color", "#E0E4CC");
piedata2.addProperty("title", "US");
JsonObject piedata3 = new JsonObject();
piedata3.addProperty("value", Integer.parseInt("100"));
piedata3.addProperty("color", "#E0E4FF");
piedata3.addProperty("title", "CHINA");
ArrayList<Object> pieDataSet = new ArrayList<Object>();
pieDataSet.add(piedata1);
pieDataSet.add(piedata2);
pieDataSet.add(piedata3);
return pieDataSet.toString();
}
}
| true |
2234ed59139877a5fc46e30c136fd774c24ace8a | Java | AniketBinekar/Expense-Manager | /app/src/main/java/com/applycreditcard/expense_manager/ui/home/HomeFragment.java | UTF-8 | 25,184 | 1.679688 | 2 | [] | no_license | package com.applycreditcard.expense_manager.ui.home;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.applycreditcard.expense_manager.R;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.annotations.NotNull;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import Adapter.CategoryListAdapter;
import Adapter.HomeScreenListAdapter;
import Model.CategoryModel;
import Model.Data;
public class HomeFragment extends Fragment implements CategoryListAdapter.OnclickInterface, HomeScreenListAdapter.OnclickInterface {
// final Context context = this;
// Button button;
RecyclerView simpleList;
private CategoryListAdapter categoryListAdapter;
private ArrayList<CategoryModel> categoryModels;
private LinearLayout bottomSheetLL;
private FirebaseFirestore db;
private ImageView categoryIV;
private HomeScreenListAdapter homeScreenListAdapter;
private ArrayList<Data> homeScreenListData;
private String date, amount, category;
private ProgressBar loadingPB;
private CardView balanceCV, incomeCV, expenseCV;
private TextView incomeTv, expenseTv, balanceTv, categoryTV, messageTV, setBalanceTv, balanceTV;
int income = 0, expense = 0, balance = 0;
Dialog dialog;
public static final String SHARED_PREFS = "shared_prefs";
public static final String AMOUNT_KEY = "amt";
private FirebaseAuth mAuth;
SharedPreferences sharedpreferences;
int setAmount;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
loadingPB = root.findViewById(R.id.idPBLoading);
db = FirebaseFirestore.getInstance();
sharedpreferences = getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
setAmount = sharedpreferences.getInt(AMOUNT_KEY, 0);
mAuth = FirebaseAuth.getInstance();
categoryModels = new ArrayList<>();
messageTV = root.findViewById(R.id.idTVMessage);
balanceCV = root.findViewById(R.id.idCVBalance);
expenseCV = root.findViewById(R.id.idCVExpense);
incomeCV = root.findViewById(R.id.idCVIncome);
setBalanceTv = root.findViewById(R.id.setBalance);
balanceTV = root.findViewById(R.id.idTVBalance);
incomeTv = root.findViewById(R.id.incomeAmount);
balanceTv = root.findViewById(R.id.balanceAmount);
expenseTv = root.findViewById(R.id.expenseAmount);
homeScreenListData = new ArrayList<>();
if (setAmount != 0) {
balanceTV.setText("₹ " + setAmount);
}
Button button = root.findViewById(R.id.addTransaction);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayBottomSheet();
}
});
RecyclerView recyclerView = root.findViewById(R.id.recyclerView);
homeScreenListAdapter = new HomeScreenListAdapter(homeScreenListData, this::onExpenseClick);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(homeScreenListAdapter);
readData();
incomeCV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
homeScreenListData.clear();
readFilteredData("Income");
}
});
expenseCV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
homeScreenListData.clear();
readFilteredData("Expense");
}
});
balanceCV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
income = 0;
balance = 0;
expense = 0;
homeScreenListData.clear();
readData();
}
});
setBalanceTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog = new Dialog(getContext());
View layout = LayoutInflater.from(getContext()).inflate(R.layout.setbalance_alert_dialogbox, null);
dialog.setContentView(layout);
EditText setLimitEditText = layout.findViewById(R.id.setLimitET);
Button setLimitBtn = layout.findViewById(R.id.idBtnSetLimit);
setLimitBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (TextUtils.isEmpty(setLimitEditText.getText().toString())) {
Toast.makeText(getContext(), "Please Enter Amount", Toast.LENGTH_SHORT).show();
} else {
SharedPreferences.Editor editor = sharedpreferences.edit();
int amt = Integer.parseInt(setLimitEditText.getText().toString());
editor.putInt(AMOUNT_KEY, amt);
editor.apply();
dialog.dismiss();
balanceTV.setText("₹ " + sharedpreferences.getInt(AMOUNT_KEY, 0));
}
}
});
dialog.show();
}
});
return root;
}
private void readData() {
loadingPB.setVisibility(View.VISIBLE);
db.collection("ExpenseManager").document(mAuth.getCurrentUser().getUid()).collection("userTranscation").orderBy("timestamp").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
loadingPB.setVisibility(View.GONE);
if (!queryDocumentSnapshots.isEmpty()) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
Data c = d.toObject(Data.class);
c.setDocId(d.getId());
// created for recycler view
homeScreenListData.add(c);
homeScreenListAdapter.notifyDataSetChanged();
}
}
if (homeScreenListData.size() == 0) {
messageTV.setText("Please enter transcations");
messageTV.setVisibility(View.VISIBLE);
}
for (int i = 0; i < homeScreenListData.size(); i++) {
Data c = homeScreenListData.get(i);
if (c.getCategory().toLowerCase().equals("clothing")) {
c.setImgid(R.drawable.ic_clothing);
} else if (c.getCategory().toLowerCase().equals("food")) {
c.setImgid(R.drawable.ic_food);
} else if (c.getCategory().toLowerCase().equals("fuel")) {
c.setImgid(R.drawable.ic_gas_pump);
} else if (c.getCategory().toLowerCase().equals("health")) {
c.setImgid(R.drawable.ic_health);
} else if (c.getCategory().toLowerCase().equals("recharge")) {
c.setImgid(R.drawable.ic_mobile_recharge);
} else if (c.getCategory().toLowerCase().equals("electricity")) {
c.setImgid(R.drawable.ic_lightning);
} else {
c.setImgid(R.drawable.ic_wallet);
}
if (homeScreenListData.get(i).getParentCategory().equals("Income")) {
income = income + Integer.parseInt(c.getAmount());
} else {
expense = expense + Integer.parseInt(c.getAmount());
}
// double prevBal = balance;
balance = income - expense;
//if (prevBal == 0) {
balanceTv.setText("₹ " + balance);
incomeTv.setText("₹ " + income);
expenseTv.setText("₹ " + expense);
//}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
loadingPB.setVisibility(View.GONE);
Toast.makeText(getContext(), "Fail to get data..", Toast.LENGTH_SHORT).show();
}
});
}
private void readFilteredData(String filter) {
loadingPB.setVisibility(View.VISIBLE);
db.collection("ExpenseManager").document(mAuth.getCurrentUser().getUid()).collection("userTranscation").whereEqualTo("parentCategory", filter).orderBy("timestamp").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
loadingPB.setVisibility(View.GONE);
if (!queryDocumentSnapshots.isEmpty()) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
Data c = d.toObject(Data.class);
if (c.getCategory().toLowerCase().equals("clothing")) {
c.setImgid(R.drawable.ic_clothing);
} else if (c.getCategory().toLowerCase().equals("food")) {
c.setImgid(R.drawable.ic_food);
} else if (c.getCategory().toLowerCase().equals("fuel")) {
c.setImgid(R.drawable.ic_gas_pump);
} else if (c.getCategory().toLowerCase().equals("health")) {
c.setImgid(R.drawable.ic_health);
} else if (c.getCategory().toLowerCase().equals("recharge")) {
c.setImgid(R.drawable.ic_mobile_recharge);
} else if (c.getCategory().toLowerCase().equals("electricity")) {
c.setImgid(R.drawable.ic_lightning);
} else {
c.setImgid(R.drawable.ic_wallet);
}
// created for recycler view.
homeScreenListData.add(c);
homeScreenListAdapter.notifyDataSetChanged();
}
if (homeScreenListData.size() == 0) {
messageTV.setText("Please enter transcations");
messageTV.setVisibility(View.VISIBLE);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
loadingPB.setVisibility(View.GONE);
Toast.makeText(getContext(), "Fail to get data..", Toast.LENGTH_SHORT).show();
}
});
}
private void addData(String amount, String date, String category, BottomSheetDialog bottomSheetDialog) {
CollectionReference collectionReference = db.collection("ExpenseManager").document(mAuth.getCurrentUser().getUid()).collection("userTranscation");
String parentCat = "";
if (category == "Salary") {
parentCat = "Income";
} else {
parentCat = "Expense";
}
Date currentDate = Calendar.getInstance().getTime();
Map map = new HashMap();
map.put("amount", amount);
map.put("category", category);
map.put("date", date);
map.put("parentCategory", parentCat);
map.put("timestamp", currentDate);
collectionReference.add(map).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
homeScreenListData.clear();
readData();
bottomSheetDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
bottomSheetDialog.dismiss();
Toast.makeText(getContext(), "Fail to add Data \n" + e, Toast.LENGTH_SHORT).show();
}
});
}
private void displayBottomSheet() {
final BottomSheetDialog bottomSheetTeachersDialog = new BottomSheetDialog(getContext(), R.style.BottomSheetDialogTheme);
View layout = LayoutInflater.from(getContext()).inflate(R.layout.fragment_bottom_sheet, bottomSheetLL);
bottomSheetTeachersDialog.setContentView(layout);
bottomSheetTeachersDialog.setCancelable(false);
bottomSheetTeachersDialog.setCanceledOnTouchOutside(true);
bottomSheetTeachersDialog.show();
TextView dateTV = layout.findViewById(R.id.idTVDate);
categoryIV = layout.findViewById(R.id.idIVCategory);
EditText amountEdt = layout.findViewById(R.id.idEdtAmount);
categoryTV = layout.findViewById(R.id.idTVCategory);
Button cancelBtn = layout.findViewById(R.id.idBtnCancel);
Button addBtn = layout.findViewById(R.id.idBtnAdd);
categoryTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
categoryModels.clear();
dialog = new Dialog(getContext());
View layout = LayoutInflater.from(getContext()).inflate(R.layout.category_alert_dialogbox, null);
dialog.setContentView(layout);
simpleList = layout.findViewById(R.id.simpleListView);
categoryModels.add(new CategoryModel(R.drawable.ic_clothing, "Clothing"));
categoryModels.add(new CategoryModel(R.drawable.ic_food, "Food"));
categoryModels.add(new CategoryModel(R.drawable.ic_gas_pump, "Fuel"));
categoryModels.add(new CategoryModel(R.drawable.ic_mobile_recharge, "Recharge"));
categoryModels.add(new CategoryModel(R.drawable.ic_lightning, "Electricity"));
categoryModels.add(new CategoryModel(R.drawable.ic_health, "Health"));
categoryModels.add(new CategoryModel(R.drawable.ic_wallet, "Salary"));
categoryListAdapter = new CategoryListAdapter(categoryModels, getContext(), HomeFragment.this::onClick);
simpleList.setLayoutManager(new LinearLayoutManager(getContext()));
simpleList.setAdapter(categoryListAdapter);
dialog.show();
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetTeachersDialog.dismiss();
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (balance == setAmount) {
AlertDialog dialog = new AlertDialog.Builder(getActivity()).setTitle("Message").setMessage("Your are spending more than your set Limit !!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create();
dialog.show();
} else {
amount = amountEdt.getText().toString();
date = dateTV.getText().toString();
category = categoryTV.getText().toString();
addData(amount, date, category, bottomSheetTeachersDialog);
}
}
});
dateTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCalender = Calendar.getInstance();
int year = mCalender.get(Calendar.YEAR);
int month = mCalender.get(Calendar.MONTH);
int dayOfMonth = mCalender.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
dateTV.setText(dayOfMonth + "-" + (month + 1) + "-" + year);
}
}, year, month, dayOfMonth);
datePickerDialog.show();
}
});
}
//Delete and Update Bottom Sheet
private void displayUpdateBottomSheet(int position) {
String date = homeScreenListData.get(position).getDate();
String amount = homeScreenListData.get(position).getAmount();
String parentCategory = homeScreenListData.get(position).getParentCategory();
String category = homeScreenListData.get(position).getCategory();
int imgId = homeScreenListData.get(position).getImgid();
String docId = homeScreenListData.get(position).getDocId();
final BottomSheetDialog bottomSheetTeachersDialog = new BottomSheetDialog(getContext(), R.style.BottomSheetDialogTheme);
View layout = LayoutInflater.from(getContext()).inflate(R.layout.bottom_sheet_update, bottomSheetLL);
bottomSheetTeachersDialog.setContentView(layout);
bottomSheetTeachersDialog.setCancelable(false);
bottomSheetTeachersDialog.setCanceledOnTouchOutside(true);
bottomSheetTeachersDialog.show();
TextView dateTV = layout.findViewById(R.id.idTVDate);
categoryIV = layout.findViewById(R.id.idIVCategory);
EditText amountEdt = layout.findViewById(R.id.idEdtAmount);
categoryTV = layout.findViewById(R.id.idTVCategory);
Button updateBtn = layout.findViewById(R.id.idBtnUpdate);
Button deleteBtn = layout.findViewById(R.id.idBtnDelete);
dateTV.setText(date);
amountEdt.setText(amount);
categoryTV.setText(category);
categoryIV.setImageResource(imgId);
categoryTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
categoryModels.clear();
dialog = new Dialog(getContext());
View layout = LayoutInflater.from(getContext()).inflate(R.layout.category_alert_dialogbox, null);
dialog.setContentView(layout);
simpleList = layout.findViewById(R.id.simpleListView);
categoryModels.add(new CategoryModel(R.drawable.ic_clothing, "Clothing"));
categoryModels.add(new CategoryModel(R.drawable.ic_food, "Food"));
categoryModels.add(new CategoryModel(R.drawable.ic_gas_pump, "Fuel"));
categoryModels.add(new CategoryModel(R.drawable.ic_mobile_recharge, "Recharge"));
categoryModels.add(new CategoryModel(R.drawable.ic_lightning, "Electricity"));
categoryModels.add(new CategoryModel(R.drawable.ic_health, "Health"));
categoryModels.add(new CategoryModel(R.drawable.ic_wallet, "Salary"));
categoryListAdapter = new CategoryListAdapter(categoryModels, getContext(), HomeFragment.this::onClick);
simpleList.setLayoutManager(new LinearLayoutManager(getContext()));
simpleList.setAdapter(categoryListAdapter);
dialog.show();
}
});
updateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//update data here
updatedata(amount, date, category, parentCategory, docId);
bottomSheetTeachersDialog.dismiss();
readData();
}
});
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//delete data here
// homeScreenListData.clear();
delete(docId);
// readData();
bottomSheetTeachersDialog.dismiss();
}
});
dateTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCalender = Calendar.getInstance();
int year = mCalender.get(Calendar.YEAR);
int month = mCalender.get(Calendar.MONTH);
int dayOfMonth = mCalender.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
dateTV.setText(dayOfMonth + "-" + (month + 1) + "-" + year);
}
}, year, month, dayOfMonth);
datePickerDialog.show();
}
});
}
private void delete(String docId) {
homeScreenListData.clear();
readData();
db.collection("ExpenseManager").document(mAuth.getCurrentUser().getUid()).collection("userTranscation").document(docId).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void unused) {
Toast.makeText(getContext(), "deleted", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull @NotNull Exception e) {
Toast.makeText(getContext(), "failure to deleted", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onClick(int position) {
String cate = categoryModels.get(position).getCategoryName();
categoryTV.setText(cate);
categoryIV.setImageResource(categoryModels.get(position).getImageUrl());
Drawable drawable = getResources().getDrawable(categoryModels.get(position).getImageUrl());
categoryTV.setCompoundDrawables(getResources().getDrawable(R.drawable.ic_clothing), null, null, null);
dialog.dismiss();
}
private void updatedata(String amount, String date, String category, String parentCategory, String docId) {
Data updateData = new Data(amount, date, category, parentCategory);
db.collection("ExpenseManager").document(mAuth.getCurrentUser().getUid()).collection("userTranscation").document(docId).set(updateData).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(getContext(), "Data has been updated..", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getContext(), "Fail to update the data..", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onExpenseClick(int position) {
displayUpdateBottomSheet(position);
}
} | true |
8af28af135d1e0b17ef9a00df9d59f990e8808ca | Java | AlexMitchell1294/Team-N-Project | /src/main/java/edu/wpi/cs3733/d21/teamN/services/database/Ndb.java | UTF-8 | 5,550 | 3.28125 | 3 | [] | no_license | package edu.wpi.cs3733.d21.teamN.services.database;
import java.sql.*;
import java.util.Scanner;
public class Ndb {
private static Connection connection;
private static Statement stmt;
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); // Apache Derby
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
connection =
DriverManager.getConnection(
"jdbc:derby:src/main/java/edu/wpi/teamname/services/database/DerbyDB;user=admin;password=admin;create=true");
stmt = connection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
return;
}
initTables();
if (args.length == 0) {
System.out.println(
"1 - Node Information\n2 - Update Node Information\n3 - Update Node Location Long Name");
System.out.println("4 - Edge Information\n5 - Exit Program");
} else {
switch (args[0]) {
case "1":
displayNodeInfo();
break;
case "2":
updateNode();
break;
case "3":
updateNodeLongName();
break;
case "4":
displayEdgeInfo();
break;
default:
System.exit(0);
}
}
}
// displays nodes (on command line)
private static void displayNodeInfo() {
try {
String str = "SELECT * FROM Nodes";
ResultSet r = stmt.executeQuery(str);
printResultSet(r);
} catch (SQLException e) {
e.printStackTrace();
}
}
// scanner in w/ id and then prompt for new x and y and change
private static void updateNode() {
try {
Scanner s = new Scanner(System.in);
System.out.print("Enter Node ID: ");
String id = s.nextLine();
System.out.print("Enter new X Y (ex. 100 200): ");
String[] xy = s.nextLine().split(" ");
String str =
"UPDATE Nodes SET xcoord = "
+ xy[0]
+ ", ycoord = "
+ xy[1]
+ " WHERE nodeID = '"
+ id
+ "'";
s.close();
stmt.execute(str);
} catch (SQLException e) {
e.printStackTrace();
}
}
// enter ID and then prompt w/ new long name
private static void updateNodeLongName() {
try {
Scanner s = new Scanner(System.in);
System.out.print("Enter Node ID: ");
String id = s.nextLine();
System.out.print("Enter new longName: ");
String ln = s.nextLine();
String str = "UPDATE Nodes SET longName = '" + ln + "' WHERE nodeID = '" + id + "'";
s.close();
stmt.execute(str);
} catch (SQLException e) {
e.printStackTrace();
}
}
// display list of edges w/ attributes
private static void displayEdgeInfo() {
try {
String str = "SELECT * FROM Edges";
ResultSet r = stmt.executeQuery(str);
printResultSet(r);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void printResultSet(ResultSet r) throws SQLException {
ResultSetMetaData rm = r.getMetaData();
int colNum = rm.getColumnCount();
for (int i = 1; i <= colNum; i++) {
System.out.printf("%-45s", rm.getColumnLabel(i));
}
System.out.println(); // newline
while (r.next()) {
for (int i = 1; i <= colNum; i++) System.out.printf("%-45s", r.getString(i));
System.out.println(); // newline
}
}
/** inits tables into database. */
private static void initTables() {
try {
String str =
"CREATE TABLE Nodes( "
+ "id varchar(25), "
+ "xcoord INT NOT NULL, "
+ "ycoord INT NOT NULL, "
+ "floor varchar(25), "
+ "building varchar(25), "
+ "nodeType varchar(25), "
+ "longName varchar(45), "
+ "shortName varchar(35), "
+ "PRIMARY KEY (id))";
stmt.execute(str);
str =
"CREATE TABLE Edges( "
+ "id varchar(25), "
+ "startNodeID varchar(25) REFERENCES Nodes (id), "
+ "endNodeID varchar(25) REFERENCES Nodes (id), "
+ "PRIMARY KEY (id))";
stmt.execute(str);
str =
"CREATE TABLE Users("
+ "id INT NOT NULL GENERATED ALWAYS AS IDENTITY,"
+ "Username varchar(40) NOT NULL UNIQUE, "
+ "Password varchar(40) NOT NULL,"
+ "UserType varchar(15),"
+ "CONSTRAINT chk_UserType CHECK (UserType IN ('Patient', 'Employee', 'Administrator')),"
+ "PRIMARY KEY (id))";
stmt.execute(str);
str =
"CREATE TABLE Requests("
+ "id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
+ "Type varchar(30), "
+ "SenderID INT NOT NULL REFERENCES Users (id), "
+ "ReceiverID INT REFERENCES Users (id), "
+ "Content varchar(700), "
+ "Notes varchar(200), "
+ "CONSTRAINT chk_Type CHECK (Type IN "
+ "('Food Delivery', 'Language Interpreter', 'Sanitation', 'Laundry', 'Gift Delivery', 'Floral Delivery', 'Medicine Delivery', "
+ "'Religious Request', 'Internal Patient Transportation', 'External Patient Transportation', 'Security', 'Facilities Maintenance', "
+ "'Computer Service', 'Audio/Visual')),"
+ "PRIMARY KEY (id))";
stmt.execute(str);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| true |
dd0e829e1b95e7e2caedcbbbd7dbab6af19bccf4 | Java | Kalcoder/ICS3U-2019-20 | /U2/A3/Remixing For Loop and Array Programs/src/me/Kaleb/Main.java | UTF-8 | 2,990 | 4.15625 | 4 | [] | no_license | package me.Kaleb;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
runProgramOne();
runProgramTwo();
runProgramThree();
}
/**
* Function to run the first program in Remixing For Loop and Array Programs
*/
private static void runProgramOne() {
// Creates Scanner for input
Scanner keyedInput = new Scanner(System.in);
// Declare and initialize the array to store inputted numbers and the total of all numbers
int[] numbers = new int[20];
int total = 0;
// Prompt user for twenty integers to be added
System.out.println("Enter twenty integers and they will be added together:");
for (int i = 0; i < numbers.length; i++)
{
// Add inputted number to numbers[]
numbers[i] = keyedInput.nextInt();
}
// Loop through all values in numbers[] and add them together
for (int i = 0; i < numbers.length; i++)
{
total = total + numbers[i];
}
// Print total of numbers in numbers[]
System.out.println("The sum of those numbers is:");
System.out.println(total);
}
/**
* Function to run the second program in Remixing For Loop and Array Programs
*/
private static void runProgramTwo() {
// Creates Scanner for input
Scanner keyedInput = new Scanner(System.in);
// Declare and initialize an array of 5 strings called friends
String[] friends = new String[5];
// Prompt user for 5 names of friends
System.out.println("Enter the names of five friends:");
for (int i = 0; i < friends.length; i++)
{
friends[i] = keyedInput.nextLine();
}
// Print 2nd, 3rd and 4th inputted names
System.out.println("The second, third and fourth names listed were:");
System.out.println("Second: " + friends[1]);
System.out.println("Third: " + friends[2]);
System.out.println("Fourth: " + friends[3]);
}
/**
* Function to run the third program in Remixing For Loop and Array Programs
*/
private static void runProgramThree() {
// Creates Scanner for input
Scanner keyedInput = new Scanner(System.in);
// Declare and initialize an array of doubles called marks, a double to hold the total of all values in marks[], and a double to hold average of all values in marks[]
double[] marks = {34.7, 54.1, 34.8, 99.6, 43.6, 43.2, 65.8, 44.8, 88.6};
double total=0;
double average;
// Print out all marks
System.out.println("These are the marks:");
for (int i = 0; i < marks.length; i++)
{
System.out.println(marks[i]);
}
// Add all marks together
for (int i = 0; i < marks.length; i++)
{
total = total + marks[i];
}
// Calculate average of all marks and store it in average variable
average = total / marks.length;
average = NumberUtils.round(average, 1);
// Print out average
System.out.println("The average mark is:");
System.out.println(average);
}
}
| true |
ccbb9350976f49c7ef85511bf89a5ee6d634bbbd | Java | TeamScrumUnipacifico/ProyectoFinal | /src/main/java/com/reservapp/entrega/modelo/dto/MesaDTO.java | UTF-8 | 1,649 | 1.992188 | 2 | [] | no_license | package com.reservapp.entrega.modelo.dto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.sql.*;
import java.util.Date;
/**
*
* @author Zathura Code Generator http://zathuracode.org
* www.zathuracode.org
*
*/
public class MesaDTO implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(MesaDTO.class);
private Integer codigoMesa;
private String estado;
private Integer puestos;
private String ubicacion;
private Integer codigoEstablecimiento_Establecimiento;
public Integer getCodigoMesa() {
return codigoMesa;
}
public void setCodigoMesa(Integer codigoMesa) {
this.codigoMesa = codigoMesa;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public Integer getPuestos() {
return puestos;
}
public void setPuestos(Integer puestos) {
this.puestos = puestos;
}
public String getUbicacion() {
return ubicacion;
}
public void setUbicacion(String ubicacion) {
this.ubicacion = ubicacion;
}
public Integer getCodigoEstablecimiento_Establecimiento() {
return codigoEstablecimiento_Establecimiento;
}
public void setCodigoEstablecimiento_Establecimiento(
Integer codigoEstablecimiento_Establecimiento) {
this.codigoEstablecimiento_Establecimiento = codigoEstablecimiento_Establecimiento;
}
}
| true |
199152d26329f2fc7c9d3618a3fbc39af3eaa98a | Java | kelum99/Mad-Project | /app/src/main/java/com/example/progym/user/payment/EditPayment.java | UTF-8 | 4,916 | 2.125 | 2 | [] | no_license | package com.example.progym.user.payment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.progym.R;
import com.example.progym.admin.exercises.UpdateDeleteExercise;
import com.example.progym.admin.member.DeleteMember;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class EditPayment extends AppCompatActivity {
DatabaseReference proGymFinance;
EditText et_method, et_cname, et_cno, et_expDate, et_cvv;
Button btn_edit, btn_dlt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_payment);
String key = getIntent().getStringExtra("CardNum");
proGymFinance = FirebaseDatabase.getInstance("https://progym-867fb-default-rtdb.asia-southeast1.firebasedatabase.app").getReference().child("Cards").child(key);
et_method = findViewById(R.id.et_method);
et_cname = findViewById(R.id.et_cname);
et_cno = findViewById(R.id.et_cno);
et_expDate = findViewById(R.id.et_expDate);
et_cvv = findViewById(R.id.et_cvv);
btn_edit = findViewById(R.id.btn_edit);
btn_dlt = findViewById(R.id.btn_dlt);
et_method.setText(getIntent().getStringExtra("PayMethod"));
et_cname.setText(getIntent().getStringExtra("CardHolderName"));
et_cno.setText(getIntent().getStringExtra("CardNum"));
et_expDate.setText(getIntent().getStringExtra("ExpDate"));
et_cvv.setText(getIntent().getStringExtra("CVV"));
btn_edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UpdateCard();
}
});
btn_dlt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(EditPayment.this);
alert.setTitle("Are you sure you want to delete this card?");
alert.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
DeleteCard();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertdialog = alert.create();
alertdialog.show();
}
});
}
public void UpdateCard() {
proGymFinance.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
snapshot.getRef().child("cardHolderName").setValue(et_cname.getText().toString());
snapshot.getRef().child("cardNumber").setValue(et_cno.getText().toString());
snapshot.getRef().child("cvv").setValue(et_cvv.getText().toString());
snapshot.getRef().child("expDate").setValue(et_expDate.getText().toString());
snapshot.getRef().child("paymentMethod").setValue(et_method.getText().toString());
Toast.makeText(getApplicationContext(), "Update Card Successfully!", Toast.LENGTH_SHORT).show();
EditPayment.this.finish();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
public void DeleteCard() {
proGymFinance.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Card Deleted Successfully!", Toast.LENGTH_SHORT).show();
EditPayment.this.finish();
} else {
Toast.makeText(getApplicationContext(), "Card Not Deleted!", Toast.LENGTH_SHORT).show();
}
}
});
}
} | true |
0961efae21ec3ad2122d0cd86dd54a7505f7086e | Java | git741852963/why | /dxz-backend/dxz-core/src/main/java/com/neusoft/features/db/DynamicDataSource.java | UTF-8 | 364 | 1.796875 | 2 | [] | no_license | package com.neusoft.features.db;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* DynamicDataSource.java
*
* @author andy.jiao@msn.com
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDataSouce();
}
}
| true |
650d2864ecae94607bd80cdafc83d1ef7169977c | Java | dw1258838824/TestSys | /src/main/java/com/ruoyi/project/system/computer/controller/BillContoller.java | UTF-8 | 7,729 | 1.90625 | 2 | [
"MIT"
] | permissive | package com.ruoyi.project.system.computer.controller;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.api.entity.ClassInErrorMsg;
import com.ruoyi.project.system.api.service.ClassInService;
import com.ruoyi.project.system.bill.domain.Bill;
import com.ruoyi.project.system.bill.service.IBillService;
import com.ruoyi.project.system.exam.domain.TExam;
import com.ruoyi.project.system.exam.service.ITExamService;
import com.ruoyi.project.system.register.domain.TExamRegister;
import com.ruoyi.project.system.register.service.ITExamRegisterService;
import com.ruoyi.project.system.student.domain.Student;
import com.ruoyi.project.system.student.service.IStudentService;
import com.testsys.common.UnionPayOfWXPay;
@RestController
@RequestMapping("/student/bill")
public class BillContoller {
private static final Logger log = LoggerFactory.getLogger(BillContoller.class);
@Autowired
private IBillService billService;
@Autowired
private ITExamService examService;
@Autowired
private ITExamRegisterService examRegisterService;
@Autowired
private IStudentService studentService;
@Autowired
private ClassInService classInService;
@Value("${wechat.notify_url}")
private String notifyUrl;
private String payIP = "47.93.241.224";
@GetMapping("/wechat/pay")
public AjaxResult wechatPay(Long examId, HttpServletRequest request){
TExam exam = examService.selectTExamById(examId);
String rignEndTime = DateUtils.parseDateToStr("yyyyMMddHHmmss", exam.getRignEndTime());
if(null != exam && !"1".equals(exam.getState())){
return new AjaxResult(AjaxResult.Type.ERROR,"失败,报名时间已截止");
}
Bill b = new Bill();
//b.setPayUserId(ShiroUtils.getSysUser().getStudent().getStudentId());
b.setPayUserId(ShiroUtils.getSysUser().getUserId());
b.setBillType("1");
b.setPayState("1");
b.setBillName("1");
b.setRefId(exam.getExamId());
List<Bill> billList = billService.selectBillList(b);
//判断当前考试是否已经报名
if(null != billList && billList.size() > 0){
return new AjaxResult(AjaxResult.Type.ERROR,"无法重复报名");
}
if(null != exam){
String billNo = UUID.randomUUID().toString().replaceAll("-","");
Bill bill = new Bill();
bill.setBillNo(billNo);//订单编号
bill.setBillType("1");//账单类型 1收入 2支出
bill.setBillName("1");//账单名称 1报名费 2补考费
//bill.setPayUserId(ShiroUtils.getSysUser().getStudent().getStudentId());//支付人
bill.setPayUserId(ShiroUtils.getSysUser().getUserId());//支付人
bill.setAmount(exam.getPrice());//价格
if(exam.getPrice() > 0.00){
bill.setPayState("0");//交易状态 0处理中 1成功 2异常
}else {
bill.setPayState("1");//交易状态 0处理中 1成功 2异常
}
bill.setRefId(examId);//关联编号
int count = billService.insertBill(bill);
if(count > 0){
if(bill.getAmount() > 0.00) {
Map<String,String> wechatPay = UnionPayOfWXPay.unifiedOrder(
"2",
"",
billNo,
examId.toString(),
exam.getExamTitle(),
String.valueOf(Double.valueOf(exam.getPrice() * 100).intValue()),
payIP,
notifyUrl,
rignEndTime);
Map<String,String> re = Maps.newHashMap();
re.put("url",wechatPay.get("code_url"));
re.put("billNo",billNo);
return new AjaxResult(AjaxResult.Type.SUCCESS,"成功",re);
}else {
Student stu = ShiroUtils.getSysUser().getStudent();
TExamRegister er = new TExamRegister();
er.setStudentId(stu.getStudentId());
er.setExamId(exam.getExamId());
er.setState("1");
er.setExamCode(DateUtils.dateTimeNow("yyyyMMdd")+(ShiroUtils.getSysUser().getDeptId()==null?"000":ShiroUtils.getSysUser().getDeptId())+""+stu.getStudentId());
er.setCtime(new Date());
try {
Map<String, String> params = Maps.newHashMap();
params.put("courseId", exam.getUid()+"");;
params.put("className", stu.getStudentName());
params.put("beginTime", (exam.getBeginTime().getTime()/1000)+"");
params.put("endTime", (exam.getArgueEndTime().getTime()/1000)+"");
params.put("teacherUid", stu.getUid()+"");
params.put("record","1");
params.put("live","1");
params.put("replay","1");
String json = classInService.classInHttp("addCourseClass", params);//调用classIn加课节
JSONObject obj = JSONObject.parseObject(json);
Integer errno = obj.getJSONObject("error_info").getInteger("errno");
if(null!=errno && errno==1) {
Long uid = obj.getLong("data");//获取课节ID
er.setUid(uid);
er.setLiveurl(obj.getJSONObject("more_data").getString("live_url"));
}else {
log.error("调用classIn添加课节失败",json);
return new AjaxResult(AjaxResult.Type.ERROR,ClassInErrorMsg.getErrorMsgByCode(errno, "addCourseClass"));
}
} catch (Exception e) {
log.error("调用classIn添加课节失败",e);
return new AjaxResult(AjaxResult.Type.ERROR,"失败");
}
//添加报名信息
examRegisterService.insertTExamRegister(er);
return new AjaxResult(AjaxResult.Type.SUCCESS,"成功",er.getExamCode());
}
}
}
return new AjaxResult(AjaxResult.Type.ERROR,"失败");
}
@GetMapping("isSuccess")
public AjaxResult billIsSuccess(HttpServletRequest request){
String billNo = request.getParameter("billNo");
String examId = request.getParameter("examId");
String studentId = request.getParameter("studentId");
Bill bill = billService.selectBillByBillNo(billNo);
if("0".equals(bill.getPayState())){
return new AjaxResult(AjaxResult.Type.SUCCESS,"订单待支付","WAIT");
}else if("1".equals(bill.getPayState())){
TExamRegister tExamRegister = new TExamRegister();
tExamRegister.setExamId(Long.parseLong(examId));
tExamRegister.setStudentId(Long.parseLong(studentId));
return new AjaxResult(AjaxResult.Type.SUCCESS,"SUCCESS",examRegisterService.selectTExamRegisterByStudentExam(tExamRegister).getExamCode());
}else{
return new AjaxResult(AjaxResult.Type.SUCCESS,"订单支付异常","ERROR");
}
}
}
| true |
6613ed293d9e40dec1e9309d5c73a050f17ffd24 | Java | petarchord/HealthyLifers | /app/src/main/java/com/healthyteam/android/healthylifers/Domain/LocationBuilder.java | UTF-8 | 2,038 | 2.3125 | 2 | [] | no_license | package com.healthyteam.android.healthylifers.Domain;
import android.graphics.Bitmap;
import java.util.List;
public class LocationBuilder implements Builder {
private Bitmap LocaitonPic;
private String Name;
private String Descripition;
private String DateAdded;
private List<String> TagList;
private UserLocation.Category Category;
private int likeCount;
private int dislikeCount;
private UserLocation.Rate UserRate;
private Double lan;
private Double lon;
// private List<Comments> Comments;
//ako je neophodno da se dovlace svi objekti komentara iz baze, onda atribut ispod nije potreban
private int commentCount;
private User Author;
@Override
public void setPicture(Bitmap locaitonPic){
this.LocaitonPic=locaitonPic;
}
@Override
public void setName(String Name) {
this.Name=Name;
}
@Override
public void setDescripition(String Desc) {
this.Descripition=Desc;
}
@Override
public void setDateAdded(String DateAdded) {
this.DateAdded=DateAdded;
}
@Override
public void setCategory(UserLocation.Category category) {
this.Category=category;
}
@Override
public void setLikeCount(int Count) {
this.likeCount=Count;
}
@Override
public void setDislikeCount(int Count) {
this.dislikeCount=Count;
}
@Override
public void setUserRate(UserLocation.Rate Rate) {
this.UserRate=Rate;
}
@Override
public void setLangitude(Double lan) {
this.lan=lan;
}
@Override
public void setLongitude(Double lon) {
this.lon=lon;
}
@Override
public void setCommentCount(int Count) {
this.commentCount=Count;
}
@Override
public void setAuthor(User Author){
this.Author=Author;
}
public UserLocation getResult(){
return new UserLocation();
}
@Override
public void setTags(List<String> tags) {
this.TagList=tags;
}
}
| true |
df9cf63fc95ee41a1855ae71e430ef1ffaec8c96 | Java | lsianturi/xyzatoz | /src/com/benclaus/koperasi/model/FormulaArgItem.java | UTF-8 | 867 | 2.390625 | 2 | [] | no_license | package com.benclaus.koperasi.model;
public class FormulaArgItem {
private FormulaArg formulaArg;
private BookItem bookItem;
private String formula;
private String formulaArgs;
private double value;
public FormulaArg getFormulaArg() {
return formulaArg;
}
public void setFormulaArg(FormulaArg formulaArg) {
this.formulaArg = formulaArg;
}
public BookItem getBookItem() {
return bookItem;
}
public void setBookItem(BookItem bookItem) {
this.bookItem = bookItem;
}
public String getFormula() {
return formula;
}
public void setFormula(String formula) {
this.formula = formula;
}
public String getFormulaArgs() {
return formulaArgs;
}
public void setFormulaArgs(String formulaArgs) {
this.formulaArgs = formulaArgs;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
| true |
1ecd9c767027bd573ac4d09aee9659f0a8283bf1 | Java | caiofellipe/calendario-academico-unifaesp | /app/src/main/java/com/br/calendario_academico/DadosModel.java | UTF-8 | 1,348 | 2.171875 | 2 | [
"MIT"
] | permissive | package com.br.calendario_academico;
public class DadosModel {
int idLegenda;
String Descricao;
String DataInicio;
String DataFim;
String Cor;
int Feriado;
public int getIdLegenda() {
return idLegenda;
}
public void setIdLegenda(int idLegenda) {
this.idLegenda = idLegenda;
}
public String getDescricao() {
return Descricao;
}
public void setDescricao(String descricao) {
Descricao = descricao;
}
public String getDataInicio() {
return DataInicio;
}
public void setDataInicio(String dataInicio) {
DataInicio = dataInicio;
}
public String getDataFim() {
return DataFim;
}
public void setDataFim(String dataFim) {
DataFim = dataFim;
}
public String getCor() {
return Cor;
}
public void setCor(String cor) {
Cor = cor;
}
public int isFeriado() {
return Feriado;
}
public void setFeriado(int feriado) {
Feriado = feriado;
}
public DadosModel(int idLegenda, String descricao, String dataInicio, String dataFim, String cor, int feriado) {
this.idLegenda = idLegenda;
Descricao = descricao;
DataInicio = dataInicio;
DataFim = dataFim;
Cor = cor;
Feriado = feriado;
}
}
| true |
4c208c27c0c3c3930940ec77208447d5b5569211 | Java | atanvir/Satvik | /app/src/main/java/com/satvick/model/SizeCheckedListModel.java | UTF-8 | 540 | 2.453125 | 2 | [] | no_license | package com.satvick.model;
public class SizeCheckedListModel {
private String sizeName;
boolean isSizeChecked;
public SizeCheckedListModel(String sizeName) {
this.sizeName = sizeName;
}
public String getSizeName() {
return sizeName;
}
public void setSizeName(String sizeName) {
this.sizeName = sizeName;
}
public boolean isSizeChecked() {
return isSizeChecked;
}
public void setSizeChecked(boolean sizeChecked) {
isSizeChecked = sizeChecked;
}
}
| true |
ed0505218c72ff41a5285641854f55d3842f10b9 | Java | MinecraftSources/MiningCrates | /src/es/minetsii/MiningCrates/chests/CrateEffect.java | UTF-8 | 246 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | package es.minetsii.MiningCrates.chests;
public enum CrateEffect {
EXPLODE("explode"), UP("up"), TELEPORT("teleport");
@SuppressWarnings("deprecation")
private String type;
CrateEffect(String type) {
this.type = type;
}
}
| true |
425e89b2de44c2e064b562e020f9a7965a434977 | Java | srinivasudadi9000/Bus_Tracking | /app/src/main/java/diet/bus_tracking/Timings.java | UTF-8 | 501 | 2.609375 | 3 | [] | no_license | package diet.bus_tracking;
public class Timings {
String busstop,timings;
public Timings(String busstop, String timings) {
this.busstop = busstop;
this.timings = timings;
}
public String getBusstop() {
return busstop;
}
public void setBusstop(String busstop) {
this.busstop = busstop;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
}
| true |
d79fb882067441592a32bc5e035115280fb411ee | Java | J-Jessica/algorithm | /src/笔试/T1.java | UTF-8 | 1,003 | 3.265625 | 3 | [] | no_license | package 笔试;
/**
* @ClassName T1
* @Description TODO
* @Author jingpeipei
* @Date 2018/9/9 10:04
*/
import java.util.*;
public class T1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(maxLengthNotRepeatSubstring(str));
}
public static int maxLengthNotRepeatSubstring(String str) {
if(str==null || str.isEmpty()){
return 0;
}
Map<Character, Integer> map = new HashMap<>();
int maxLength = 0;
int current = 0;
for(int index=0; index<str.length(); index++){
if(map.containsKey(str.charAt(index))){
current = map.get(str.charAt(index)) + 1;
}
else{
if((index-current+1)>maxLength){
maxLength=index-current+1;
}
}
map.put(str.charAt(index), index);
}
return maxLength;
}
}
| true |
919011a52ec5bcef8ac3652fd463f0b8260d5e2c | Java | King07/ProgrammingProjects | /AndroidDevelopmentGroup1/AndroidDevelopmentProject/src/com/example/androiddevelopmentproject/OpponentProfilePlayer.java | UTF-8 | 670 | 2.484375 | 2 | [] | no_license | package com.example.androiddevelopmentproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class OpponentProfilePlayer extends FragmentActivity {
Player player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.opponent_player_profile);
// 1. get passed intent
Intent intent = getIntent();
player = (Player) intent.getSerializableExtra("Player");
System.out.println(" The OpponentProfilePlayer Activity"+player.toString());
}
public Player getPlayer() {
return player;
}
}
| true |
a5383ca06c7a4af2f510ee09371813e94f1f974b | Java | lvaruzza/BAMFold | /BAMFolder/src/main/java/bfx/assembly/scaffold/edges/SuperEdgeBuilder.java | UTF-8 | 1,242 | 2.640625 | 3 | [] | no_license | package bfx.assembly.scaffold.edges;
import java.util.Map;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
public class SuperEdgeBuilder {
private int count;
private int sumMQ;
private String left;
private String right;
private boolean reverse;
private DescriptiveStatistics stats;
private Map<String, Integer> seqs;
public double calcDistance(AlignEdge edge) {
if (edge.isReverse()) {
return seqs.get(right)-edge.getRightStart()+edge.getLeftEnd();
} else {
return seqs.get(left)-edge.getLeftStart()+edge.getRightEnd();
}
}
public SuperEdgeBuilder(AlignEdge edge,Map<String, Integer> seqs) {
count=1;
left=edge.getLeftNode();
right=edge.getRightNode();
sumMQ=edge.getMQ();
reverse=edge.isReverse();
this.seqs = seqs;
stats = new DescriptiveStatistics();
stats.addValue(calcDistance(edge));
}
public void sumEdge(AlignEdge edge) {
count++;
sumMQ+=edge.getMQ();
stats.addValue(calcDistance(edge));
}
public SuperEdge build() {
double median = stats.getPercentile(50);
double q1 = stats.getPercentile(25);
double q3 = stats.getPercentile(75);
double iqd = q3-q1;
return new SuperEdge(left,right,reverse,
count,sumMQ,
median,iqd);
}
} | true |
6653810c772b31242cc959c7b7e397aeb0284782 | Java | liuchen0510/apptest | /yujunwei/youji/src/main/java/com/pages/AddcommentPage.java | UTF-8 | 1,216 | 1.921875 | 2 | [] | no_license | package com.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import io.appium.java_client.AppiumDriver;
public class AddcommentPage {
private AppiumDriver driver;
@FindBy(id="neet.com.youjidemo:id/tab_icon")
private WebElement txt_icon;
@FindBy(id="neet.com.youjidemo:id/et_share_passage")
private WebElement txt_passage;
@FindBy(xpath = "\"//*[@text='点击增加图片或视频']\"")
private WebElement txt_title;
@FindBy(className="android.widget.RelativeLayout")
private WebElement txt_layout;
@FindBy(id="com.google.android.apps.photos:id/image")
private WebElement txt_image;
@FindBy(xpath = "\"//*[@text='上传']\"")
private WebElement txt_shangchuan;
Actions action;
public AddcommentPage(AppiumDriver driver) {
this.driver = driver;
action = new Actions(driver);
}
public void addcomment(String text) {
action.click( txt_icon);
action.sendKeys(txt_passage,text);
action.click(txt_title);
action.click(txt_layout);
action.click(txt_image);
action.click(txt_shangchuan);
}
}
| true |
5ca8ec64d6f4f019625acbb694947d434de3342d | Java | guillaumeguy/AdventOfCode2020 | /src/main/java/day14/Instructions.java | UTF-8 | 526 | 2.78125 | 3 | [] | no_license | package day14;
import java.util.List;
public class Instructions {
String mask;
List<Integer> addresses;
List<Integer> values;
public Instructions(String a, List<Integer> b, List<Integer> c) {
this.mask = a;
this.addresses = b;
this.values = c;
}
@Override
public String toString() {
return "Instructions{" +
"mask='" + mask + '\'' +
", addresses=" + addresses +
", values=" + values +
'}';
}
}
| true |
08be73dde8a9a06bf6c90799793e7255bffbcbc9 | Java | bartosz-jazwa/Delegation | /src/main/java/com/jazwa/delegation/model/document/DelegationStatus.java | UTF-8 | 116 | 1.59375 | 2 | [] | no_license | package com.jazwa.delegation.model.document;
public enum DelegationStatus {
INIT,SUBMITTED,REJECTED,PAID;
}
| true |
3fcea18c8be8d9c889eab8dd154c33c52e80a4e9 | Java | zgreen3/RSOI-LAB_3 | /service_1/src/main/java/smirnov/bn/service_1/web/LingVarController.java | UTF-8 | 7,599 | 2.296875 | 2 | [] | no_license | package smirnov.bn.service_1.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import smirnov.bn.service_1.model.LingVarInfo;
import smirnov.bn.service_1.service.LingVarService;
@RestController
@RequestMapping("/ling_var_dict")
public class LingVarController {
@Autowired
private LingVarService lingVarService;
private static final Logger logger = LoggerFactory.getLogger(LingVarController.class);
//curl -X POST --data {\"lingVarName\":\"Tester\",\"lingVarTermLowVal\":\"2\",\"lingVarTermMedVal\":\"4\",\"lingVarTermHighVal\":\"6\"} http://localhost:8191/ling_var_dict/create-ling_var --header "Content-Type:application/json"
//curl -X POST --data {\"lingVarName\":\"Tester2\",\"lingVarTermLowVal\":\"3\",\"lingVarTermMedVal\":\"5\",\"lingVarTermHighVal\":\"8\"} http://localhost:8191/ling_var_dict/create-ling_var --header "Content-Type:application/json"
//curl -X POST --data {\"lingVarName\":\"Tester3\",\"lingVarTermLowVal\":\"1\",\"lingVarTermMedVal\":\"3\",\"lingVarTermHighVal\":\"7\"} http://localhost:8191/ling_var_dict/create-ling_var --header "Content-Type:application/json"
//curl -X POST --data {\"lingVarName\":\"Tester4\",\"lingVarTermLowVal\":\"0\",\"lingVarTermMedVal\":\"2\",\"lingVarTermHighVal\":\"5\"} http://localhost:8191/ling_var_dict/create-ling_var --header "Content-Type:application/json"
//curl -X POST --data {\"lingVarName\":\"Tester5\",\"lingVarTermLowVal\":\"0\",\"lingVarTermMedVal\":\"3\",\"lingVarTermHighVal\":\"6\"} http://localhost:8191/ling_var_dict/create-ling_var --header "Content-Type:application/json"
//curl -X POST --data {\"lingVarName\":\"Tester\",\"lingVarTermLowVal\":\"2\",\"lingVarTermMedVal\":\"4\",\"lingVarTermHighVal\":\"6\"} //...
//http://localhost:8191/ling_var_dict/create-ling_var //...
//--header "Content-Type:application/json"
@PostMapping("/create-ling_var")
public ResponseEntity<String> createLingVar(@RequestBody LingVarInfo lingVarInfo) {
try {
Integer newlingVarId = lingVarService.createLingVar(lingVarInfo);
logger.info("createLingVar() - CREATING" + "\n" + "id param: " + String.valueOf(newlingVarId));
return new ResponseEntity<>(newlingVarId.toString(), HttpStatus.CREATED);
}
catch (NullPointerException e) {
logger.error
("Null Pointer Exception Error in createLingVar(...)", e);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
catch (Exception e) {
logger.error
("Error in createLingVar(...)", e);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
@GetMapping("/read-{id}")
public ResponseEntity<LingVarInfo> findLingVarById(@PathVariable Integer id) {
try {
logger.info("findLingVarById() - START" + "\n" + "id param: " + String.valueOf(id));
return new ResponseEntity<>(lingVarService.findLingVarById(id), HttpStatus.OK);
} catch (Exception e) {
logger.error("Error in findLingVarById(...)", e);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
@GetMapping("/read-by-emp-uuid-{employeeUuid}")
public ResponseEntity<List<LingVarInfo>> findLingVarsByEmployeeUuid(@PathVariable String employeeUuid) {
try {
logger.info("findLingVarsByEmployeeUuid() - START" + "\n" + "employeeUuid param: " + employeeUuid);
return new ResponseEntity<>(lingVarService.findLingVarsByEmployeeUuid(employeeUuid), HttpStatus.OK);
} catch (Exception e) {
logger.error("Error in findLingVarsByEmployeeUuid(...)", e);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
@GetMapping("/read-all")
public ResponseEntity<List<LingVarInfo>> findAllLingVars() {
try {
logger.info("findAllLingVars() - START");
List<LingVarInfo> lingVarsInfo = lingVarService.findAllLingVars();
if (lingVarsInfo != null && lingVarsInfo.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} else {
return new ResponseEntity<>(lingVarsInfo, HttpStatus.OK);
}
} catch (Exception e) {
logger.error("Error in findAllLingVars(...)", e);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
//https://github.com/umeshawasthi/javadevjournal/tree/master/spring/rest-pagination/src/main/java/com/javadevjournal/rest
//https://www.javadevjournal.com/spring/rest-pagination-in-spring/
//http://www.appsdeveloperblog.com/rest-pagination-tutorial-with-spring-mvc/
//https://www.baeldung.com/rest-api-pagination-in-spring
// [ http://localhost:8083/ling_var_dict/all-paginated?page=1&sizeLimit=1 ] (:)
@RequestMapping(value = "/read-all-paginated", params = {"page", "sizeLimit"}, method = GET)
@ResponseBody
public ResponseEntity<List<LingVarInfo>> findAllLingVarPaginated(@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "sizeLimit", defaultValue = "100") int sizeLimit) {
try {
logger.info("findAllLingVarPaginated() - START" + "\n" + "page param: " + String.valueOf(page) + "\n" +
"sizeLimit param: " + String.valueOf(sizeLimit));
List<LingVarInfo> lingVarsInfo = lingVarService.findAllLingVarPaginated(page, sizeLimit);
if (lingVarsInfo != null && lingVarsInfo.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} else {
return new ResponseEntity<>(lingVarsInfo, HttpStatus.OK);
}
} catch (Exception e) {
logger.error("Error in findAllLingVarPaginated(...)", e);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
//curl -X PUT --data {\"lingVarName\":\"Tester2\",\"lingVarTermLowVal\":\"3\",\"lingVarTermMedVal\":\"5\",\"lingVarTermHighVal\":\"8\"} http://localhost:8191/ling_var_dict/update-ling_var
@PutMapping("/update-ling_var")
public ResponseEntity<String> updateLingVar(@RequestBody LingVarInfo lingVarInfo) {
try {
logger.info("updateLingVar() - START" + "\n" + "id param: " + String.valueOf(lingVarInfo.getLingVarId()));
lingVarService.updateLingVar(lingVarInfo);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
logger.error("Error in updateLingVar(...)", e);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
//curl -X DELETE http://localhost:8191/ling_var_dict/delete-{lingVarId}
@DeleteMapping("/delete-{lingVarId}")
public ResponseEntity<String> deleteLingVarById(@PathVariable Integer lingVarId) {
try {
logger.info("deleteLingVarById() - START" + "\n" + "id param: " + String.valueOf(lingVarId));
lingVarService.deleteLingVarById(lingVarId);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
logger.error("Error in deleteLingVarById(...)", e);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
}
| true |
3d8250457dba23afc9f6e29a5fd719d55bdb998a | Java | visit-dav/visit | /src/java/WindowInformation.java | UTF-8 | 23,273 | 1.851563 | 2 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
package llnl.visit;
import java.util.Vector;
import java.lang.Integer;
// ****************************************************************************
// Class: WindowInformation
//
// Purpose:
// This class contains the attributes that tell the state of a viewer window.
//
// Notes: Autogenerated by xml2java.
//
// Programmer: xml2java
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
public class WindowInformation extends AttributeSubject
{
private static int WindowInformation_numAdditionalAtts = 29;
public WindowInformation()
{
super(WindowInformation_numAdditionalAtts);
activeSource = new String("");
activeTimeSlider = -1;
timeSliders = new Vector();
timeSliderCurrentStates = new Vector();
animationMode = 2;
interactionMode = 0;
toolUpdateMode = 1;
boundingBoxNavigate = true;
spin = false;
fullFrame = false;
perspective = true;
maintainView = false;
lockView = false;
lockTools = false;
lockTime = false;
viewExtentsType = 0;
viewDimension = 2;
viewKeyframes = new Vector();
cameraViewMode = false;
usingScalableRendering = false;
lastRenderMin = 0f;
lastRenderAvg = 0f;
lastRenderMax = 0f;
numPrimitives = 0;
extents = new double[6];
extents[0] = 0;
extents[1] = 0;
extents[2] = 0;
extents[3] = 0;
extents[4] = 0;
extents[5] = 0;
windowSize = new int[2];
windowSize[0] = 0;
windowSize[1] = 0;
winMode = 0;
DDTSim = false;
DDTConnected = false;
}
public WindowInformation(int nMoreFields)
{
super(WindowInformation_numAdditionalAtts + nMoreFields);
activeSource = new String("");
activeTimeSlider = -1;
timeSliders = new Vector();
timeSliderCurrentStates = new Vector();
animationMode = 2;
interactionMode = 0;
toolUpdateMode = 1;
boundingBoxNavigate = true;
spin = false;
fullFrame = false;
perspective = true;
maintainView = false;
lockView = false;
lockTools = false;
lockTime = false;
viewExtentsType = 0;
viewDimension = 2;
viewKeyframes = new Vector();
cameraViewMode = false;
usingScalableRendering = false;
lastRenderMin = 0f;
lastRenderAvg = 0f;
lastRenderMax = 0f;
numPrimitives = 0;
extents = new double[6];
extents[0] = 0;
extents[1] = 0;
extents[2] = 0;
extents[3] = 0;
extents[4] = 0;
extents[5] = 0;
windowSize = new int[2];
windowSize[0] = 0;
windowSize[1] = 0;
winMode = 0;
DDTSim = false;
DDTConnected = false;
}
public WindowInformation(WindowInformation obj)
{
super(obj);
int i;
activeSource = new String(obj.activeSource);
activeTimeSlider = obj.activeTimeSlider;
timeSliders = new Vector(obj.timeSliders.size());
for(i = 0; i < obj.timeSliders.size(); ++i)
timeSliders.addElement(new String((String)obj.timeSliders.elementAt(i)));
timeSliderCurrentStates = new Vector();
for(i = 0; i < obj.timeSliderCurrentStates.size(); ++i)
{
Integer iv = (Integer)obj.timeSliderCurrentStates.elementAt(i);
timeSliderCurrentStates.addElement(new Integer(iv.intValue()));
}
animationMode = obj.animationMode;
interactionMode = obj.interactionMode;
toolUpdateMode = obj.toolUpdateMode;
boundingBoxNavigate = obj.boundingBoxNavigate;
spin = obj.spin;
fullFrame = obj.fullFrame;
perspective = obj.perspective;
maintainView = obj.maintainView;
lockView = obj.lockView;
lockTools = obj.lockTools;
lockTime = obj.lockTime;
viewExtentsType = obj.viewExtentsType;
viewDimension = obj.viewDimension;
viewKeyframes = new Vector();
for(i = 0; i < obj.viewKeyframes.size(); ++i)
{
Integer iv = (Integer)obj.viewKeyframes.elementAt(i);
viewKeyframes.addElement(new Integer(iv.intValue()));
}
cameraViewMode = obj.cameraViewMode;
usingScalableRendering = obj.usingScalableRendering;
lastRenderMin = obj.lastRenderMin;
lastRenderAvg = obj.lastRenderAvg;
lastRenderMax = obj.lastRenderMax;
numPrimitives = obj.numPrimitives;
extents = new double[6];
for(i = 0; i < obj.extents.length; ++i)
extents[i] = obj.extents[i];
windowSize = new int[2];
windowSize[0] = obj.windowSize[0];
windowSize[1] = obj.windowSize[1];
winMode = obj.winMode;
DDTSim = obj.DDTSim;
DDTConnected = obj.DDTConnected;
SelectAll();
}
public int Offset()
{
return super.Offset() + super.GetNumAdditionalAttributes();
}
public int GetNumAdditionalAttributes()
{
return WindowInformation_numAdditionalAtts;
}
public boolean equals(WindowInformation obj)
{
int i;
// Compare the elements in the timeSliders vector.
boolean timeSliders_equal = (obj.timeSliders.size() == timeSliders.size());
for(i = 0; (i < timeSliders.size()) && timeSliders_equal; ++i)
{
// Make references to String from Object.
String timeSliders1 = (String)timeSliders.elementAt(i);
String timeSliders2 = (String)obj.timeSliders.elementAt(i);
timeSliders_equal = timeSliders1.equals(timeSliders2);
}
// Compare the elements in the timeSliderCurrentStates vector.
boolean timeSliderCurrentStates_equal = (obj.timeSliderCurrentStates.size() == timeSliderCurrentStates.size());
for(i = 0; (i < timeSliderCurrentStates.size()) && timeSliderCurrentStates_equal; ++i)
{
// Make references to Integer from Object.
Integer timeSliderCurrentStates1 = (Integer)timeSliderCurrentStates.elementAt(i);
Integer timeSliderCurrentStates2 = (Integer)obj.timeSliderCurrentStates.elementAt(i);
timeSliderCurrentStates_equal = timeSliderCurrentStates1.equals(timeSliderCurrentStates2);
}
// Compare the elements in the viewKeyframes vector.
boolean viewKeyframes_equal = (obj.viewKeyframes.size() == viewKeyframes.size());
for(i = 0; (i < viewKeyframes.size()) && viewKeyframes_equal; ++i)
{
// Make references to Integer from Object.
Integer viewKeyframes1 = (Integer)viewKeyframes.elementAt(i);
Integer viewKeyframes2 = (Integer)obj.viewKeyframes.elementAt(i);
viewKeyframes_equal = viewKeyframes1.equals(viewKeyframes2);
}
// Compare the extents arrays.
boolean extents_equal = true;
for(i = 0; i < 6 && extents_equal; ++i)
extents_equal = (extents[i] == obj.extents[i]);
// Compare the windowSize arrays.
boolean windowSize_equal = true;
for(i = 0; i < 2 && windowSize_equal; ++i)
windowSize_equal = (windowSize[i] == obj.windowSize[i]);
// Create the return value
return ((activeSource.equals(obj.activeSource)) &&
(activeTimeSlider == obj.activeTimeSlider) &&
timeSliders_equal &&
timeSliderCurrentStates_equal &&
(animationMode == obj.animationMode) &&
(interactionMode == obj.interactionMode) &&
(toolUpdateMode == obj.toolUpdateMode) &&
(boundingBoxNavigate == obj.boundingBoxNavigate) &&
(spin == obj.spin) &&
(fullFrame == obj.fullFrame) &&
(perspective == obj.perspective) &&
(maintainView == obj.maintainView) &&
(lockView == obj.lockView) &&
(lockTools == obj.lockTools) &&
(lockTime == obj.lockTime) &&
(viewExtentsType == obj.viewExtentsType) &&
(viewDimension == obj.viewDimension) &&
viewKeyframes_equal &&
(cameraViewMode == obj.cameraViewMode) &&
(usingScalableRendering == obj.usingScalableRendering) &&
(lastRenderMin == obj.lastRenderMin) &&
(lastRenderAvg == obj.lastRenderAvg) &&
(lastRenderMax == obj.lastRenderMax) &&
(numPrimitives == obj.numPrimitives) &&
extents_equal &&
windowSize_equal &&
(winMode == obj.winMode) &&
(DDTSim == obj.DDTSim) &&
(DDTConnected == obj.DDTConnected));
}
// Property setting methods
public void SetActiveSource(String activeSource_)
{
activeSource = activeSource_;
Select(0);
}
public void SetActiveTimeSlider(int activeTimeSlider_)
{
activeTimeSlider = activeTimeSlider_;
Select(1);
}
public void SetTimeSliders(Vector timeSliders_)
{
timeSliders = timeSliders_;
Select(2);
}
public void SetTimeSliderCurrentStates(Vector timeSliderCurrentStates_)
{
timeSliderCurrentStates = timeSliderCurrentStates_;
Select(3);
}
public void SetAnimationMode(int animationMode_)
{
animationMode = animationMode_;
Select(4);
}
public void SetInteractionMode(int interactionMode_)
{
interactionMode = interactionMode_;
Select(5);
}
public void SetToolUpdateMode(int toolUpdateMode_)
{
toolUpdateMode = toolUpdateMode_;
Select(6);
}
public void SetBoundingBoxNavigate(boolean boundingBoxNavigate_)
{
boundingBoxNavigate = boundingBoxNavigate_;
Select(7);
}
public void SetSpin(boolean spin_)
{
spin = spin_;
Select(8);
}
public void SetFullFrame(boolean fullFrame_)
{
fullFrame = fullFrame_;
Select(9);
}
public void SetPerspective(boolean perspective_)
{
perspective = perspective_;
Select(10);
}
public void SetMaintainView(boolean maintainView_)
{
maintainView = maintainView_;
Select(11);
}
public void SetLockView(boolean lockView_)
{
lockView = lockView_;
Select(12);
}
public void SetLockTools(boolean lockTools_)
{
lockTools = lockTools_;
Select(13);
}
public void SetLockTime(boolean lockTime_)
{
lockTime = lockTime_;
Select(14);
}
public void SetViewExtentsType(int viewExtentsType_)
{
viewExtentsType = viewExtentsType_;
Select(15);
}
public void SetViewDimension(int viewDimension_)
{
viewDimension = viewDimension_;
Select(16);
}
public void SetViewKeyframes(Vector viewKeyframes_)
{
viewKeyframes = viewKeyframes_;
Select(17);
}
public void SetCameraViewMode(boolean cameraViewMode_)
{
cameraViewMode = cameraViewMode_;
Select(18);
}
public void SetUsingScalableRendering(boolean usingScalableRendering_)
{
usingScalableRendering = usingScalableRendering_;
Select(19);
}
public void SetLastRenderMin(float lastRenderMin_)
{
lastRenderMin = lastRenderMin_;
Select(20);
}
public void SetLastRenderAvg(float lastRenderAvg_)
{
lastRenderAvg = lastRenderAvg_;
Select(21);
}
public void SetLastRenderMax(float lastRenderMax_)
{
lastRenderMax = lastRenderMax_;
Select(22);
}
public void SetNumPrimitives(int numPrimitives_)
{
numPrimitives = numPrimitives_;
Select(23);
}
public void SetExtents(double[] extents_)
{
for(int i = 0; i < 6; ++i)
extents[i] = extents_[i];
Select(24);
}
public void SetWindowSize(int[] windowSize_)
{
windowSize[0] = windowSize_[0];
windowSize[1] = windowSize_[1];
Select(25);
}
public void SetWindowSize(int e0, int e1)
{
windowSize[0] = e0;
windowSize[1] = e1;
Select(25);
}
public void SetWinMode(int winMode_)
{
winMode = winMode_;
Select(26);
}
public void SetDDTSim(boolean DDTSim_)
{
DDTSim = DDTSim_;
Select(27);
}
public void SetDDTConnected(boolean DDTConnected_)
{
DDTConnected = DDTConnected_;
Select(28);
}
// Property getting methods
public String GetActiveSource() { return activeSource; }
public int GetActiveTimeSlider() { return activeTimeSlider; }
public Vector GetTimeSliders() { return timeSliders; }
public Vector GetTimeSliderCurrentStates() { return timeSliderCurrentStates; }
public int GetAnimationMode() { return animationMode; }
public int GetInteractionMode() { return interactionMode; }
public int GetToolUpdateMode() { return toolUpdateMode; }
public boolean GetBoundingBoxNavigate() { return boundingBoxNavigate; }
public boolean GetSpin() { return spin; }
public boolean GetFullFrame() { return fullFrame; }
public boolean GetPerspective() { return perspective; }
public boolean GetMaintainView() { return maintainView; }
public boolean GetLockView() { return lockView; }
public boolean GetLockTools() { return lockTools; }
public boolean GetLockTime() { return lockTime; }
public int GetViewExtentsType() { return viewExtentsType; }
public int GetViewDimension() { return viewDimension; }
public Vector GetViewKeyframes() { return viewKeyframes; }
public boolean GetCameraViewMode() { return cameraViewMode; }
public boolean GetUsingScalableRendering() { return usingScalableRendering; }
public float GetLastRenderMin() { return lastRenderMin; }
public float GetLastRenderAvg() { return lastRenderAvg; }
public float GetLastRenderMax() { return lastRenderMax; }
public int GetNumPrimitives() { return numPrimitives; }
public double[] GetExtents() { return extents; }
public int[] GetWindowSize() { return windowSize; }
public int GetWinMode() { return winMode; }
public boolean GetDDTSim() { return DDTSim; }
public boolean GetDDTConnected() { return DDTConnected; }
// Write and read methods.
public void WriteAtts(CommunicationBuffer buf)
{
if(WriteSelect(0, buf))
buf.WriteString(activeSource);
if(WriteSelect(1, buf))
buf.WriteInt(activeTimeSlider);
if(WriteSelect(2, buf))
buf.WriteStringVector(timeSliders);
if(WriteSelect(3, buf))
buf.WriteIntVector(timeSliderCurrentStates);
if(WriteSelect(4, buf))
buf.WriteInt(animationMode);
if(WriteSelect(5, buf))
buf.WriteInt(interactionMode);
if(WriteSelect(6, buf))
buf.WriteInt(toolUpdateMode);
if(WriteSelect(7, buf))
buf.WriteBool(boundingBoxNavigate);
if(WriteSelect(8, buf))
buf.WriteBool(spin);
if(WriteSelect(9, buf))
buf.WriteBool(fullFrame);
if(WriteSelect(10, buf))
buf.WriteBool(perspective);
if(WriteSelect(11, buf))
buf.WriteBool(maintainView);
if(WriteSelect(12, buf))
buf.WriteBool(lockView);
if(WriteSelect(13, buf))
buf.WriteBool(lockTools);
if(WriteSelect(14, buf))
buf.WriteBool(lockTime);
if(WriteSelect(15, buf))
buf.WriteInt(viewExtentsType);
if(WriteSelect(16, buf))
buf.WriteInt(viewDimension);
if(WriteSelect(17, buf))
buf.WriteIntVector(viewKeyframes);
if(WriteSelect(18, buf))
buf.WriteBool(cameraViewMode);
if(WriteSelect(19, buf))
buf.WriteBool(usingScalableRendering);
if(WriteSelect(20, buf))
buf.WriteFloat(lastRenderMin);
if(WriteSelect(21, buf))
buf.WriteFloat(lastRenderAvg);
if(WriteSelect(22, buf))
buf.WriteFloat(lastRenderMax);
if(WriteSelect(23, buf))
buf.WriteInt(numPrimitives);
if(WriteSelect(24, buf))
buf.WriteDoubleArray(extents);
if(WriteSelect(25, buf))
buf.WriteIntArray(windowSize);
if(WriteSelect(26, buf))
buf.WriteInt(winMode);
if(WriteSelect(27, buf))
buf.WriteBool(DDTSim);
if(WriteSelect(28, buf))
buf.WriteBool(DDTConnected);
}
public void ReadAtts(int index, CommunicationBuffer buf)
{
switch(index)
{
case 0:
SetActiveSource(buf.ReadString());
break;
case 1:
SetActiveTimeSlider(buf.ReadInt());
break;
case 2:
SetTimeSliders(buf.ReadStringVector());
break;
case 3:
SetTimeSliderCurrentStates(buf.ReadIntVector());
break;
case 4:
SetAnimationMode(buf.ReadInt());
break;
case 5:
SetInteractionMode(buf.ReadInt());
break;
case 6:
SetToolUpdateMode(buf.ReadInt());
break;
case 7:
SetBoundingBoxNavigate(buf.ReadBool());
break;
case 8:
SetSpin(buf.ReadBool());
break;
case 9:
SetFullFrame(buf.ReadBool());
break;
case 10:
SetPerspective(buf.ReadBool());
break;
case 11:
SetMaintainView(buf.ReadBool());
break;
case 12:
SetLockView(buf.ReadBool());
break;
case 13:
SetLockTools(buf.ReadBool());
break;
case 14:
SetLockTime(buf.ReadBool());
break;
case 15:
SetViewExtentsType(buf.ReadInt());
break;
case 16:
SetViewDimension(buf.ReadInt());
break;
case 17:
SetViewKeyframes(buf.ReadIntVector());
break;
case 18:
SetCameraViewMode(buf.ReadBool());
break;
case 19:
SetUsingScalableRendering(buf.ReadBool());
break;
case 20:
SetLastRenderMin(buf.ReadFloat());
break;
case 21:
SetLastRenderAvg(buf.ReadFloat());
break;
case 22:
SetLastRenderMax(buf.ReadFloat());
break;
case 23:
SetNumPrimitives(buf.ReadInt());
break;
case 24:
SetExtents(buf.ReadDoubleArray());
break;
case 25:
SetWindowSize(buf.ReadIntArray());
break;
case 26:
SetWinMode(buf.ReadInt());
break;
case 27:
SetDDTSim(buf.ReadBool());
break;
case 28:
SetDDTConnected(buf.ReadBool());
break;
}
}
public String toString(String indent)
{
String str = new String();
str = str + stringToString("activeSource", activeSource, indent) + "\n";
str = str + intToString("activeTimeSlider", activeTimeSlider, indent) + "\n";
str = str + stringVectorToString("timeSliders", timeSliders, indent) + "\n";
str = str + intVectorToString("timeSliderCurrentStates", timeSliderCurrentStates, indent) + "\n";
str = str + intToString("animationMode", animationMode, indent) + "\n";
str = str + intToString("interactionMode", interactionMode, indent) + "\n";
str = str + intToString("toolUpdateMode", toolUpdateMode, indent) + "\n";
str = str + boolToString("boundingBoxNavigate", boundingBoxNavigate, indent) + "\n";
str = str + boolToString("spin", spin, indent) + "\n";
str = str + boolToString("fullFrame", fullFrame, indent) + "\n";
str = str + boolToString("perspective", perspective, indent) + "\n";
str = str + boolToString("maintainView", maintainView, indent) + "\n";
str = str + boolToString("lockView", lockView, indent) + "\n";
str = str + boolToString("lockTools", lockTools, indent) + "\n";
str = str + boolToString("lockTime", lockTime, indent) + "\n";
str = str + intToString("viewExtentsType", viewExtentsType, indent) + "\n";
str = str + intToString("viewDimension", viewDimension, indent) + "\n";
str = str + intVectorToString("viewKeyframes", viewKeyframes, indent) + "\n";
str = str + boolToString("cameraViewMode", cameraViewMode, indent) + "\n";
str = str + boolToString("usingScalableRendering", usingScalableRendering, indent) + "\n";
str = str + floatToString("lastRenderMin", lastRenderMin, indent) + "\n";
str = str + floatToString("lastRenderAvg", lastRenderAvg, indent) + "\n";
str = str + floatToString("lastRenderMax", lastRenderMax, indent) + "\n";
str = str + intToString("numPrimitives", numPrimitives, indent) + "\n";
str = str + doubleArrayToString("extents", extents, indent) + "\n";
str = str + intArrayToString("windowSize", windowSize, indent) + "\n";
str = str + intToString("winMode", winMode, indent) + "\n";
str = str + boolToString("DDTSim", DDTSim, indent) + "\n";
str = str + boolToString("DDTConnected", DDTConnected, indent) + "\n";
return str;
}
// Attributes
private String activeSource;
private int activeTimeSlider;
private Vector timeSliders; // vector of String objects
private Vector timeSliderCurrentStates; // vector of Integer objects
private int animationMode;
private int interactionMode;
private int toolUpdateMode;
private boolean boundingBoxNavigate;
private boolean spin;
private boolean fullFrame;
private boolean perspective;
private boolean maintainView;
private boolean lockView;
private boolean lockTools;
private boolean lockTime;
private int viewExtentsType;
private int viewDimension;
private Vector viewKeyframes; // vector of Integer objects
private boolean cameraViewMode;
private boolean usingScalableRendering;
private float lastRenderMin;
private float lastRenderAvg;
private float lastRenderMax;
private int numPrimitives;
private double[] extents;
private int[] windowSize;
private int winMode;
private boolean DDTSim;
private boolean DDTConnected;
}
| true |
bbd05ab33b832dc2a468558f2f9321a25ad91a12 | Java | hybian/311 | /WiKi_Clawer_PA1/src/CrawlerTest.java | UTF-8 | 1,710 | 2.53125 | 3 | [] | no_license | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CrawlerTest {
static final String BASE_URL = "https://en.wikipedia.org";
private static ArrayList<String> links;
private static String document;
private static String test = "<dd><a href=\"/wiki/wtf\" title=\"WTF\">WTF</a></dd>\r\n" +
"<p>\r\n" +
"<dd><a href=\"/wiki/:wtf\" title=\"WTF\">WTF</a></dd>\\r\\n" +
"<dd><a href=\"/wiki/Iowa_State_Cyclones\" title=\"Iowa State Cyclones\">Iowa State Cyclones</a></dd>\r\n" +
"<dd><a href=\"/wiki/Iowa_State_University_College_of_Business\" title=\"Iowa State University College of Business\">Business</a></dd>\r\n" +
"<dd><a href=\"/wiki/Iowa_State_University_College_of_Engineering\" title=\"Iowa State University College of Engineering\">Engineering</a></dd>\r\n" +
"<dd><a href=\"/https/Iowa_State_University_College_of_Human_Sciences\" title=\"Iowa State University College of Human Sciences\">Human Sciences</a></dd>\r\n" +
"<dd><a href=\"/wiki/#Iowa_State_University_College_of_Liberal_Arts_%26_Sciences\" title=\"Iowa State University College of Liberal Arts & Sciences\">Liberal Arts & Sciences</a></dd>";
public static void main(String[] args)
{
String seed = "/wiki/Complexity_theory";
String[] topics = {};
WikiCrawler wc = new WikiCrawler(seed, 100, topics, "false-100-noTopic.txt");
WikiCrawler wc_test = new WikiCrawler("/wiki/A.html", 6, topics, "wtf.txt");
wc.crawl(false);
}
}
| true |
eb5985ea6a6586e90913d4104eccf5a527011f73 | Java | stanvanrooy/decompiled-instagram | /decompiled/instagram/sources/p000X/C09540ba.java | UTF-8 | 623 | 1.679688 | 2 | [] | no_license | package p000X;
import android.os.MessageQueue;
/* renamed from: X.0ba reason: invalid class name and case insensitive filesystem */
public final class C09540ba implements MessageQueue.IdleHandler {
public final /* synthetic */ AnonymousClass0SV A00;
public C09540ba(AnonymousClass0SV r1) {
this.A00 = r1;
}
public final boolean queueIdle() {
if (((Boolean) C05640Lj.A00(AnonymousClass0L7.SHORTCUTS_2019, "is_enabled", false)).booleanValue()) {
C42181rp.A01(this.A00.A00);
return false;
}
C42181rp.A00(this.A00.A00);
return false;
}
}
| true |
1e371ccc2d973e5faf542bbac85d715b2f5be5ec | Java | FourKups/Finden | /app/src/main/java/com/fourkups/finden/Search_Activity.java | UTF-8 | 10,577 | 1.890625 | 2 | [] | no_license | package com.fourkups.finden;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.airbnb.lottie.LottieAnimationView;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Search_Activity extends AppCompatActivity implements OnItemClickListener{
private RecyclerView courseRV;
AlertDialog.Builder builder,Loading_builder,image_builder;
AlertDialog loadinDialog,alertDialog,imageDialog;
// variable for our adapter
// class and array list
private CourseAdapter adapter;
private ArrayList<CourseModal> courseModalArrayList;
Button dialogyes,dialogno;
ImageView close;
//
private static Bundle mBundleRecyclerViewState;
InputImage image;
int time=5000;
ArrayList<Uri> mArrayUri;
ArrayList<String> dupUri;
LottieAnimationView loadinbar;
ImageView dimage;
//
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
overridePendingTransition(R.anim.fadein,R.anim.fadeout);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
LayoutInflater li = LayoutInflater.from(this);
LayoutInflater Lo=LayoutInflater.from(this);
LayoutInflater Im=LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.dialog_layout, null);
View Loadview=Lo.inflate(R.layout.loadingbar,null);
View imageview=Im.inflate(R.layout.activity_image,null);
dialogyes=promptsView.findViewById(R.id.dialogyes);
dialogno=promptsView.findViewById(R.id.dialogno);
close=imageview.findViewById(R.id.close);
dimage=imageview.findViewById(R.id.Image);
builder = new AlertDialog.Builder(this);
Loading_builder=new AlertDialog.Builder(this);
image_builder=new AlertDialog.Builder(this);
builder.setView(promptsView);
Loading_builder.setView(Loadview);
image_builder.setView(imageview);
alertDialog = builder.create();
loadinDialog=Loading_builder.create();
imageDialog=image_builder.create();
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
loadinDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
imageDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
loadinDialog.setCanceledOnTouchOutside(false);
loadinDialog.show();
dupUri=new ArrayList<>();
mArrayUri=new ArrayList<>();
dupUri= getIntent().getStringArrayListExtra("SELECTED_URI");
if(dupUri.size()>100 && dupUri.size()<200){
time=((dupUri.size()/5)*1000)+5000;
}
else if(dupUri.size()>=200){
time = ((dupUri.size() / 5) * 1000) + 10000;
}else{
time = ((dupUri.size() / 5) * 1000) + 2000;
}
loadingbar(time);
for (String i:dupUri) {
//Toast.makeText(this, i, Toast.LENGTH_SHORT).show();
try {
image = InputImage.fromFilePath(this, Uri.parse(i));
recognizeText(image,Uri.parse((i)));
} catch (IOException e) {
e.printStackTrace();
}
}
EditText search=findViewById(R.id.search);
ImageView cancel=findViewById(R.id.cancel);
courseRV=findViewById(R.id.Recyler);
ImageView back=findViewById(R.id.back);
loadinbar=findViewById(R.id.loadingbar);
cancel.setVisibility(View.INVISIBLE);
dialogyes.setOnClickListener(v -> {
Intent intent=new Intent(getBaseContext(), MainActivity.class);
startActivity(intent);
finish();
});
dialogno.setOnClickListener(v -> alertDialog.dismiss());
search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(search.length()==0){
cancel.setVisibility(View.INVISIBLE);
}else{
cancel.setVisibility(View.VISIBLE);
}
filter(String.valueOf(search.getText()));
}
@Override
public void afterTextChanged(Editable s) {
}
});
cancel.setOnClickListener(v -> search.setText(""));
back.setOnClickListener(v -> alertDialog.show());
close.setOnClickListener(v -> imageDialog.cancel());
}
private void loadingbar(int time) {
new Thread(() -> {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
//loadinbar=findViewById(R.id.loadingbar);
loadinDialog.cancel();
// loadinbar.setVisibility(View.INVISIBLE);
}).start();
}
private void filter(String text) {
// creating a new array list to filter our data.
ArrayList<CourseModal> filteredlist = new ArrayList<>();
// running a for loop to compare elements.
for (CourseModal item : courseModalArrayList) {
// checking if the entered string matched with any item of our recycler view.
if (item.getCourseContent().toLowerCase().contains(text.toLowerCase())) {
// if the item is matched we are
// adding it to our filtered list.
filteredlist.add(item);
}
}
if (filteredlist.isEmpty()) {
// if no item is added in filtered list we are
// displaying a toast message as no data found.
Toast.makeText(this, "No Data Found..", Toast.LENGTH_SHORT).show();
} else {
// at last we are passing that filtered
// list to our adapter class.
adapter.filterList(filteredlist);
}
}
private void buildRecyclerView() {
// initializing our adapter class.
adapter = new CourseAdapter(courseModalArrayList, Search_Activity.this);
// adding layout manager to our recycler view.
LinearLayoutManager manager = new LinearLayoutManager(this);
courseRV.setHasFixedSize(true);
// setting layout manager
// to our recycler view.
courseRV.setLayoutManager(manager);
// setting adapter to
// our recycler view.
courseRV.setAdapter(adapter);
adapter.setClickListener(this);
}
private void recognizeText(InputImage image, Uri uri) {
// below line we are creating a new array list
courseModalArrayList = new ArrayList<>();
//Toast.makeText(this,image.toString(), Toast.LENGTH_SHORT).show();
// [START get_detector_default]
TextRecognizer recognizer = TextRecognition.getClient();
// [END get_detector_default]
// [START run_detector]
Task<Text> result =
recognizer.process(image)
.addOnSuccessListener(new OnSuccessListener<Text>() {
@Override
public void onSuccess(Text visionText) {
String text="";
for (Text.TextBlock block : visionText.getTextBlocks()) {
Rect boundingBox = block.getBoundingBox();
Point[] cornerPoints = block.getCornerPoints();
text += block.getText();
for (Text.Line line : block.getLines()) {
// ...
for (Text.Element element : line.getElements()) {
// ...
}
}
}
courseModalArrayList.add(new CourseModal(uri,text));
//Toast.makeText(Search_Activity.this,courseModalArrayList.toString(), Toast.LENGTH_SHORT).show();
buildRecyclerView();
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
}
});
// [END run_detector]
}
@Override
public void onBackPressed() {
alertDialog.show();
}
@Override
public void onClick(View view, int position) {
Picasso.get().load(dupUri.get(position)).into(dimage);
imageDialog.show();
/* Intent intent = new Intent(getBaseContext(),ImageActivity.class);
//Toast.makeText(this, dupUri.get(position), Toast.LENGTH_SHORT).show();
intent.putExtra("SELECTED_Image", dupUri.get(position));
startActivity(intent);*/
}
}
| true |
38e74754b9c20e4667416423551b239cee698419 | Java | C0BBY/springy | /src/main/java/com/alpha/springy/springy/SpringyApplication.java | UTF-8 | 380 | 1.875 | 2 | [] | no_license | package com.alpha.springy.springy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringyApplication {
public static void main(String[] args) {
SpringApplication.run(SpringyApplication.class, args);
}
private static String hello() {
return "hello world";
}
}
| true |
25a895a862137b19ba2353b5d516ec1bda068f59 | Java | linux10000/goku-food | /src/main/java/com/akiratoriyama/gokufoodapi/enums/I18nEnum.java | UTF-8 | 106 | 1.570313 | 2 | [] | no_license | package com.akiratoriyama.gokufoodapi.enums;
public interface I18nEnum {
public String getI18nKey();
}
| true |
fc835a0d24d8998504e28b3f5c6c6f9e6da41087 | Java | antonnovash/PracticeEconomicCybernetics2019 | /Novash_Lab_2/Applett.java | UTF-8 | 3,409 | 2.796875 | 3 | [] | no_license | import java.applet.Applet;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
@SuppressWarnings("serial")
public class Applett extends Applet {
private Color backgroundColor;
private Color contourColor;
private Color fillColorGray;
private Color fillColorDarkGray;
private Shape triangle;
private int unitWidth = 400;
private int unitHeight = 300;
private int centerX = unitWidth / 2;
private int centerY = unitHeight / 2;
private int median = unitHeight / 3;
public Applett() {
}
@Override
public void init() {
backgroundColor = parseColor("bgr", Color.lightGray);
fillColorGray = parseColor("fillColorGray", Color.gray);
fillColorDarkGray = parseColor("fillColorDarkGray", Color.darkGray);
contourColor = parseColor("col", Color.blue);
triangle = new Triangle(centerX, centerY, median);
}
private Color parseColor(String paramName, Color defaultValue) {
try {
return Color.decode(getParameter(paramName));
} catch (Exception e) {
return defaultValue;
}
}
@Override
public void paint(Graphics g) {
g.setColor(backgroundColor);
g.fillRect(0, 0, getWidth(), getHeight());
Graphics2D g2d = (Graphics2D) g;
BufferedImage original = initOriginal();
g2d.drawImage(original, 0, 0, null);
ConvolveOp op = new ConvolveOp(new Kernel(3, 3, new float[]{0.0f, -0.75f, 0.0f, -0.75f, 4.0f, -0.75f, 0.0f, -0.75f, 0.0f}));
g2d.drawImage(op.filter(original, null), unitWidth, 0, null);
}
private BufferedImage initOriginal() {
BufferedImage biSrc = new BufferedImage(unitWidth, unitHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = biSrc.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setBackground(backgroundColor);
g2d.clearRect(0, 0, unitWidth, unitHeight);
Paint shadowPaint = new Color(80, 80, 80, 120);
AffineTransform shadowTransform = AffineTransform.getShearInstance(-2.450, 0.0);
shadowTransform.scale(1.0350, 0.52);
g2d.setPaint(shadowPaint);
g2d.translate(250, 100);
g2d.fill(shadowTransform.createTransformedShape(triangle));
g2d.translate(-250, -100);
g2d.setPaint(new GradientPaint(centerX, centerY + (median >> 1), fillColorGray, centerX, centerY - median, fillColorDarkGray));
g2d.fill(triangle);
g2d.setColor(contourColor);
g2d.setStroke(new BasicStroke(10));
g2d.draw(triangle);
Font font = new Font("Serif", Font.BOLD, 8);
Font bigfont = font.deriveFont(AffineTransform.getScaleInstance(18.0, 18.0));
GlyphVector gv = bigfont.createGlyphVector(g2d.getFontRenderContext(), "!");
Shape jshape = gv.getGlyphOutline(0);
g2d.setColor(contourColor);
g2d.translate(175, 185);
g2d.fill(jshape);
g2d.translate(-175, -185);
return biSrc;
}
} | true |
a32570226c64c621767fea9625902904238678fd | Java | mkirsche/SVGraph | /src/FastaObject.java | UTF-8 | 1,185 | 3.421875 | 3 | [] | no_license | import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/**
* A representation of a FASTA file as a map from name to sequence
*/
public class FastaObject {
HashMap<String, String> nameToSeq;
ArrayList<String> names;
FastaObject(String filename) throws Exception
{
nameToSeq = new HashMap<String, String>();
names = new ArrayList<String>();
Scanner input = new Scanner(new FileInputStream(new File(filename)));
StringBuilder seq = new StringBuilder("");
String lastName = "";
while(input.hasNext())
{
String line = input.nextLine();
if(line.startsWith(">"))
{
// Add the last contig to the map
if(lastName.length() != 0)
{
names.add(lastName);
nameToSeq.put(lastName, seq.toString());
}
// Start a new contig by resetting the sequence updating the name
seq = new StringBuilder("");
lastName = line.substring(1);
}
else
{
// Continue adding to the sequence
seq.append(line);
}
}
if(lastName.length() != 0)
{
names.add(lastName);
nameToSeq.put(lastName, seq.toString());
}
input.close();
}
}
| true |
1cfdac189c7164f29806d1a111e82f24b478e3c1 | Java | shaokuuipo/poi-tl | /poi-tl/src/main/java/com/deepoove/poi/policy/AbstractParagraphConverterRenderPolicy.java | UTF-8 | 1,632 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2014-2021 Sayi
*
* 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.deepoove.poi.policy;
import com.deepoove.poi.converter.ToRenderDataConverter;
import com.deepoove.poi.data.ParagraphRenderData;
import com.deepoove.poi.render.RenderContext;
/**
* Use paragraph renderer policy render type <T>
*
* @author Sayi
*
* @param <T>
*/
public abstract class AbstractParagraphConverterRenderPolicy<T> extends AbstractRenderPolicy<T> {
protected final ToRenderDataConverter<T, ParagraphRenderData> paragraphConverter;
public abstract ToRenderDataConverter<T, ParagraphRenderData> getParagraphRenderDataConverter();
public AbstractParagraphConverterRenderPolicy() {
this.paragraphConverter = getParagraphRenderDataConverter();
}
@Override
protected void afterRender(RenderContext<T> context) {
super.clearPlaceholder(context, true);
}
@Override
public void doRender(RenderContext<T> context) throws Exception {
ParagraphRenderPolicy.Helper.renderParagraph(context.getRun(), paragraphConverter.convert(context.getData()));
}
}
| true |
4a68f0b12ccb49244992c36b094f5ff0c02c36e6 | Java | nisegami/grand-order-companion | /app/src/main/java/world/arshad/grandordercompanion/model/Material.java | UTF-8 | 5,074 | 2.65625 | 3 | [] | no_license | package world.arshad.grandordercompanion.model;
/**
* This is an enum of all skill and ascension materials.
* Created by arshad on 19/03/2018.
*/
public enum Material {
DRAGON_FANG("Dragon Fang", "dragon_fang"),
EVIL_BONE("Evil Bone", "evil_bone"),
PROOF_OF_HERO("Proof of Hero", "proof_of_hero"),
VOIDS_DUST("Void's Dust", "voids_dust"),
ETERNAL_GEAR("Eternal Gear", "eternal_gear"),
FORBIDDEN_PAGE("Forbidden Page", "forbidden_page"),
GHOST_LANTERN("Ghost Lantern", "ghost_lantern"),
HOMUNCULUS_BABY("Homunculus Baby", "homunculus_baby"),
METEOR_HORSESHOE("Meteor Horseshoe", "meteor_horseshoe"),
OCTUPLET_TWIN_CRYSTALS("Octuplet Twin Crystals", "octuplet_twin_crystals"),
PHOENIX_FEATHER("Phoenix Feather", "phoenix_feather"),
SEED_OF_YGGDRASSIL("Seed of Yggdrassil", "seed_of_yggdrassil"),
SERPENT_JEWEL("Serpent Jewel", "serpent_jewel"),
BLACK_BEAST_GREASE("Black Beast Grease", "black_beast_grease"),
CLAW_OF_CHAOS("Claw of Chaos", "claw_of_chaos"),
CRYSTALLIZED_LORE("Crystallized Lore", "crystallized_lore"),
DRAGONS_REVERSE_SCALE("Dragons Reverse Scale", "dragons_reverse_scale"),
HEART_OF_THE_FOREIGN_GOD("Heart of the Foreign God", "heart_of_the_foreign_god"),
SPIRIT_ROOT("Spirit Root", "spirit_root"),
TEARSTONE_OF_BLOOD("Tearstone of Blood", "tearstone_of_blood"),
WARHORSES_YOUNG_HORN("Warhorse's Young Horn", "warhorses_young_horn"),
BIZARRE_GOD_WINE("Bizarre God Wine", "bizarre_god_wine"),
CHAIN_OF_FOOLS("Chain of Fools", "chain_of_fools"),
CURSED_BEAST_CHOLECYST("Cursed Beast Cholecyst", "cursed_beast_cholecyst"),
GREAT_KNIGHT_MEDAL("Great Knight Medal", "great_knight_medal"),
LAMP_OF_SEALED_EVIL("Lamp of Sealed Evil", "lamp_of_sealed_evil"),
MAGICAL_CEREBROSPINAL_FLUID("Magical Cerebrospinal Fluid", "magical_cerebrospinal_fluid"),
SCARAB_OF_WISDOM("Scarab of Wisdom", "scarab_of_wisdom"),
SHELL_OF_REMINISCENCE("Shell of Reminiscence", "shell_of_reminiscence"),
STINGER_OF_CERTAIN_DEATH("Stinger of Certain Death", "stinger_of_certain_death"),
ARCHER_PIECE("Archer Piece", "archer_piece"),
ASSASSIN_PIECE("Assassin Piece", "assassin_piece"),
BERSERKER_PIECE("Berserker Piece", "berserker_piece"),
CASTER_PIECE("Caster Piece", "caster_piece"),
LANCER_PIECE("Lancer Piece", "lancer_piece"),
RIDER_PIECE("Rider Piece", "rider_piece"),
SABER_PIECE("Saber Piece", "saber_piece"),
ARCHER_MONUMENT("Archer Monument", "archer_monument"),
ASSASSIN_MONUMENT("Assassin Monument", "assassin_monument"),
BERSERKER_MONUMENT("Berserker Monument", "berserker_monument"),
CASTER_MONUMENT("Caster Monument", "caster_monument"),
LANCER_MONUMENT("Lancer Monument", "lancer_monument"),
RIDER_MONUMENT("Rider Monument", "rider_monument"),
SABER_MONUMENT("Saber Monument", "saber_monument"),
GEM_OF_ARCHER("Gem of Archer", "gem_of_archer"),
GEM_OF_ASSASSIN("Gem of Assassin", "gem_of_assassin"),
GEM_OF_BERSERKER("Gem of Berserker", "gem_of_berserker"),
GEM_OF_CASTER("Gem of Caster", "gem_of_caster"),
GEM_OF_LANCER("Gem of Lancer", "gem_of_lancer"),
GEM_OF_RIDER("Gem of Rider", "gem_of_rider"),
GEM_OF_SABER("Gem of Saber", "gem_of_saber"),
MAGIC_GEM_OF_ARCHER("Magic Gem of Archer", "magic_gem_of_archer"),
MAGIC_GEM_OF_ASSASSIN("Magic Gem of Assassin", "magic_gem_of_assassin"),
MAGIC_GEM_OF_BERSERKER("Magic Gem of Berserker", "magic_gem_of_berserker"),
MAGIC_GEM_OF_CASTER("Magic Gem of Caster", "magic_gem_of_caster"),
MAGIC_GEM_OF_LANCER("Magic Gem of Lancer", "magic_gem_of_lancer"),
MAGIC_GEM_OF_RIDER("Magic Gem of Rider", "magic_gem_of_rider"),
MAGIC_GEM_OF_SABER("Magic Gem of Saber", "magic_gem_of_saber"),
SECRET_GEM_OF_ARCHER("Secret Gem of Archer", "secret_gem_of_archer"),
SECRET_GEM_OF_ASSASSIN("Secret Gem of Assassin", "secret_gem_of_assassin"),
SECRET_GEM_OF_BERSERKER("Secret Gem of Berserker", "secret_gem_of_berserker"),
SECRET_GEM_OF_CASTER("Secret Gem of Caster", "secret_gem_of_caster"),
SECRET_GEM_OF_LANCER("Secret Gem of Lancer", "secret_gem_of_lancer"),
SECRET_GEM_OF_RIDER("Secret Gem of Rider", "secret_gem_of_rider"),
SECRET_GEM_OF_SABER("Secret Gem of Saber", "secret_gem_of_saber"),
TWINKLE_CANDY("Twinkle Candy", "twinkle_candy"),
SHARP_KNIFE("Sharp Knife", "sharp_knife"),
BUCKET_OF_CHICKEN("Bucket of Chicken", "bucket_of_chicken"),
GOLDEN_SKULL("Golden Skull", "golden_skull"),
CRYSTAL_BALL("Crystal Ball", "crystal_ball"),
GOLDEN_BEAR_LIGHTER("Golden Bear Lighter", "golden_bear_lighter"),
BELL_RINGING_BRANCH("Bell-Ringing Branch", "bell_ringing_branch");
private String humanName;
private String cleanName;
Material(String humanName, String cleanName) {
this.humanName = humanName;
this.cleanName = cleanName;
}
@Override
public String toString() {
return this.humanName;
}
public String getIconPath() {
return String.format("img/mats/%s.png", cleanName);
}
}
| true |
55396b0652722ea2f8cfa0bda4743f5499bdeb8b | Java | nhatday/vohoangnhat-ocwiki | /src/org/ocwiki/controller/rest/bean/ResourceSearchReportMapper.java | UTF-8 | 1,050 | 2.34375 | 2 | [] | no_license | package org.ocwiki.controller.rest.bean;
import org.ocwiki.data.Article;
import org.ocwiki.data.ResourceSearchReport;
public class ResourceSearchReportMapper implements
Mapper<ResourceSearchReportBean, ResourceSearchReport<? extends Article>> {
@Override
public ResourceSearchReportBean toBean(ResourceSearchReport<? extends Article> value) {
ResourceSearchReportBean bean = new ResourceSearchReportBean();
bean.setResource(ResourceReferenceMapper.get().toBean(
value.getResource()));
bean.setScore(value.getScore());
return bean;
}
@Override
public ResourceSearchReport<Article> toEntity(ResourceSearchReportBean value) {
ResourceSearchReport<Article> entity = new ResourceSearchReport<Article>();
entity.setResource(ResourceReferenceMapper.get().toEntity(
value.getResource()));
entity.setScore(value.getScore());
return entity;
}
private static ResourceSearchReportMapper DEFAULT_INSTANCE = new ResourceSearchReportMapper();
public static ResourceSearchReportMapper get() {
return DEFAULT_INSTANCE;
}
}
| true |
6fc1995649889d7191ae24aec5e500c1754b9390 | Java | ehasalud/openmrs-module-restrictbyrole | /omod/src/main/java/org/openmrs/module/restrictbyrole/web/controller/RestrictionFormController.java | UTF-8 | 3,498 | 1.953125 | 2 | [] | no_license | package org.openmrs.module.restrictbyrole.web.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.api.context.Context;
import org.openmrs.api.db.SerializedObject;
import org.openmrs.module.restrictbyrole.RoleRestriction;
import org.openmrs.module.restrictbyrole.RoleRestrictionValidator;
import org.openmrs.module.restrictbyrole.SerializedObjectEditor;
import org.openmrs.module.restrictbyrole.api.RestrictByRoleService;
import org.openmrs.propertyeditor.RoleEditor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/module/restrictbyrole/restrictionForm")
public class RestrictionFormController {
protected final Log log = LogFactory.getLog(getClass());
@Autowired
private RoleRestrictionValidator roleRestrictionValidator;
@RequestMapping(method = RequestMethod.GET)
public void initForm(){
}
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(java.lang.Integer.class,
new CustomNumberEditor(java.lang.Integer.class, true));
binder.registerCustomEditor(org.openmrs.Role.class, new RoleEditor());
binder.registerCustomEditor(org.openmrs.api.db.SerializedObject.class, new SerializedObjectEditor());
}
@ModelAttribute("restriction")
protected RoleRestriction formBackingObject(HttpServletRequest request) throws ServletException {
if (!Context.isAuthenticated())
return new RoleRestriction();
RoleRestriction restriction = null;
String idStr = request.getParameter("restrictionId");
if (idStr != null) {
RestrictByRoleService service = (RestrictByRoleService) Context.getService(RestrictByRoleService.class);
restriction = service.getRoleRestriction(Integer.valueOf(idStr));
}
if (restriction == null)
restriction = new RoleRestriction();
return restriction;
}
@ModelAttribute("serializedObjects")
protected List<SerializedObject> initSerializedObjects() {
if (!Context.isAuthenticated())
return new ArrayList<SerializedObject>();
RestrictByRoleService service = (RestrictByRoleService) Context.getService(RestrictByRoleService.class);
List<SerializedObject> serializedObjects = service.getAllSerializedObjects();
return serializedObjects;
}
@RequestMapping(method = RequestMethod.POST)
protected String processSubmit(@ModelAttribute("restriction")RoleRestriction rr) {
if (Context.isAuthenticated()) {
RestrictByRoleService service = (RestrictByRoleService) Context.getService(RestrictByRoleService.class);
if (rr.getId() == null) {
log.info("Creating new RoleRestriction");
service.createRoleRestriction(rr);
} else {
log.info("Updating RoleRestriction");
service.updateRoleRestriction(rr);
}
}
return "redirect:restrictionList.form";
}
}
| true |
8f23a5165e8c7fe3e94cabaf0f58a8ecc5a02b76 | Java | everoad/jpa-study-shop | /src/main/java/com/kbj/shop/repository/ItemRepository.java | UTF-8 | 712 | 2.390625 | 2 | [] | no_license | package com.kbj.shop.repository;
import com.kbj.shop.domain.item.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.Optional;
@Repository
@RequiredArgsConstructor
public class ItemRepository {
private final EntityManager em;
public Long save(Item item) {
em.persist(item);
return item.getId();
}
public Optional<Item> findById(Long id) {
return Optional.ofNullable(em.find(Item.class, id));
}
public List<Item> findAll() {
return em.createQuery("select i from Item i", Item.class)
.getResultList();
}
}
| true |
0e8f38d277e72c99c12a70d984020b9ccb0bc662 | Java | SyselMitY/Laboruebungen_Java_4 | /Labor_15_backend/src/main/java/com/example/gutegadsen_backend/util/UpvoteRequestBody.java | UTF-8 | 268 | 1.648438 | 2 | [] | no_license | package com.example.gutegadsen_backend.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public class UpvoteRequestBody {
public final String username;
public final Long postId;
public final Boolean upvoteState;
}
| true |
8d2b9c47f04b58362e44b5ae624fd54efbfb7dce | Java | RamesesDev/osiris2 | /web/commonweb/src/com/rameses/web/component/captcha/UICaptcha.java | UTF-8 | 1,925 | 1.882813 | 2 | [] | no_license |
package com.rameses.web.component.captcha;
import java.io.IOException;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.servlet.http.HttpServletRequest;
public class UICaptcha extends UIComponentBase{
public UICaptcha() {
}
public String getFamily() {
return null;
}
public void encodeBegin(FacesContext context) throws IOException {
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
ResponseWriter writer = context.getResponseWriter();
String id = getClientId(context);
String height = (String) getAttributes().get("height");
String width = (String) getAttributes().get("width");
String style = (String) getAttributes().get("style");
String styleClass = (String) getAttributes().get("styleClass");
StringBuffer url = new StringBuffer();
url.append(req.getRequestURI());
url.append("?" + CaptchaPhaseListener.CAPTCHA_PARAM + "=true");
writer.startElement("div", this);
writer.writeAttribute("id", id, null);
writer.startElement("img", this);
writer.writeAttribute("src", url.toString(), null);
writer.writeAttribute("alt", "jcaptcha image", null);
if(height != null)
writer.writeAttribute("height", height, null);
if(width != null)
writer.writeAttribute("width", width, null);
if(style != null)
writer.writeAttribute("style", style, null);
if(styleClass != null)
writer.writeAttribute("styleClass", styleClass, null);
writer.endElement("img");
}
public void encodeEnd(FacesContext context) throws IOException {
context.getResponseWriter().endElement("div");
}
}
| true |
39a68260d10d4a48b0ffa44880efead0da02bf6b | Java | huangdaiyi/guanggou | /src/main/java/com/hlhj/guanggou/mapper/UserFavoriteMapper.java | UTF-8 | 590 | 1.734375 | 2 | [] | no_license | package com.hlhj.guanggou.mapper;
import java.util.List;
import com.hlhj.guanggou.param.BasePagingParam;
import com.hlhj.guanggou.po.UserFavorite;
import com.hlhj.guanggou.result.FavoriteProduct;
public interface UserFavoriteMapper {
int deleteByPrimaryKey(Integer id);
int insert(UserFavorite record);
int insertSelective(UserFavorite record);
UserFavorite selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(UserFavorite record);
int updateByPrimaryKey(UserFavorite record);
List<FavoriteProduct> selectPaging(BasePagingParam param);
} | true |
17c5a7435657458189e78758f1b46f1f8d879d42 | Java | JohnNuha/SisTerQ | /prak6/Periksa.java | UTF-8 | 845 | 2.609375 | 3 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package prak6;
/**
*
* @author NuH
*/
public class Periksa extends Thread {
Dokter d = new Dokter("johan");
String namaDok = d.getNama();
Pasien p = new Pasien(1);
String p0 = p.getNama(0);
String p1 = p.getNama(1);
String p2 = p.getNama(2);
String p3 = p.getNama(3);
String p4 = p.getNama(4);
String p5 = p.getNama(5);
String p6 = p.getNama(6);
String p7 = p.getNama(7);
String p8 = p.getNama(8);
String p9 = p.getNama(9);
String pasall[] = {p0, p1, p2, p3, p4, p5, p6, p7, p8,p9};
int urut;
public Periksa(int i) {
urut = i;
}
@Override
public void run() {
System.out.println("pasien " + pasall[urut] + " telah diperiksa " + namaDok);
}
}
| true |
6f8708b5ff517cd8736d4600f2eec7eaabf96577 | Java | QingchenD/LeetCode | /src/ljava/FindFriendCircle.java | UTF-8 | 1,951 | 3.65625 | 4 | [] | no_license | package ljava;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
/**
* https://leetcode-cn.com/explore/featured/card/bytedance/243/array-and-sorting/1036/
* 班上有 N 名学生。其中有些人是朋友,有些则不是。他们的友谊具有是传递性。如果已知 A 是 B 的朋友,B 是 C 的朋友,那么我们可以认为 A 也是 C 的朋友。所谓的朋友圈,是指所有朋友的集合。
* 给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系。如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道。你必须输出所有学生中的已知的朋友圈总数。
*
* 输入:
* [[1,1,0],
* [1,1,0],
* [0,0,1]]
* 输出: 2
* 说明:已知学生0和学生1互为朋友,他们在一个朋友圈。
* 第2个学生自己在一个朋友圈。所以返回2。
*
* 注意:
* N 在[1,200]的范围内。
* 对于所有学生,有M[i][i] = 1。
* 如果有M[i][j] = 1,则有M[j][i] = 1。
*/
public class FindFriendCircle {
public int findCircleNum(int[][] M) {
boolean[] restGroup = new boolean[M.length];
for (int i = 0; i < M.length; i++) {
restGroup[i] = true;
}
int groups = 0;
for (int i = 0; i < M.length; i++) {
if (restGroup[i]) {
groups++;
DFS(M, i, restGroup);
}
}
return groups;
}
private void DFS(int[][]M, int line, boolean[] restGroup) {
boolean notDone = restGroup[line];
if (notDone) {
restGroup[line] = false;
for (int i = 0; i < M.length; i++) {
if (M[line][i] == 1) {
M[i][line] = M[line][i] = 0;
if (line != i) {
DFS(M, i, restGroup);
}
}
}
}
}
}
| true |
7cd658a25d667e5e1fc28cd31d58dc6d887ba07a | Java | dibog/net.bogdoll.wizards | /net.bogdoll.wizards/src/net/bogdoll/property/Property.java | UTF-8 | 924 | 2.71875 | 3 | [] | no_license | package net.bogdoll.property;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class Property<T>
{
private PropertyChangeSupport mPCS = new PropertyChangeSupport(this);
private T mValue;
public Property() {}
public Property(T aInitValue) {
mValue = aInitValue;
}
public void addPropertyChangeListener(PropertyChangeListener aListener) {
mPCS.addPropertyChangeListener(aListener);
}
public void removePropertyChangeListener(PropertyChangeListener aListener) {
mPCS.removePropertyChangeListener(aListener);
}
public T get() {
return mValue;
}
public void set(T aNewValue) {
T old = mValue;
mValue = aNewValue;
mPCS.firePropertyChange("value", old, mValue);
}
@Override
public String toString() {
return ""+mValue;
}
public void pulse() {
mPCS.firePropertyChange("value", null, mValue);
}
}
| true |
27fc0d3b0e038e36ab6722d887efc6b6564f8812 | Java | isilacar/restaurant-api | /src/main/java/com/finartz/restaurantApi/exception/CustomExceptionHandler.java | UTF-8 | 5,775 | 2.46875 | 2 | [] | no_license | package com.finartz.restaurantApi.exception;
import com.finartz.restaurantApi.error.BadCredentialError;
import com.finartz.restaurantApi.error.ErrorMessage;
import com.finartz.restaurantApi.error.InternalServerError;
import com.finartz.restaurantApi.error.NotAllowedError;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import java.time.LocalDateTime;
import java.util.Locale;
@ControllerAdvice
public class CustomExceptionHandler {
private final MessageSource messageSource;
public CustomExceptionHandler(MessageSource messageSource) {
this.messageSource = messageSource;
}
/*
exception tüm exceptionların atası olduğu için,en tepede o olduğu için onu alıyorum,ResourceNotFound sınıfımda RuntimeExceptiondan extend olduğu için,
aslında burada exception değişkenim,resourceNotFound değişkenim oluyor. Oradaki değerleri,ErrorMessage ın propertielerine setliyorum
*/
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorMessage> resourceNotFoundExceptionHandler(Exception exception, WebRequest request) {
ErrorMessage errors = new ErrorMessage();
errors.setTimestamp(LocalDateTime.now());
/*aşağıda da ,exception.getMessage() dan gelen symbol_name.code ile gelen hata kodunu,
message.properties dosyamdaki hata koduyla eşleştir ve karşılığındaki değeri döndür diyoruz.
*/
errors.setError(messageSource.getMessage(exception.getMessage(), null, Locale.getDefault()));
errors.setStatus(HttpStatus.NOT_FOUND.value());
errors.setCode(exception.getMessage()); //symbol.code
return new ResponseEntity<>(errors, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorMessage> generalException(Exception exception, WebRequest request) {
ErrorMessage errors = new ErrorMessage();
errors.setTimestamp(LocalDateTime.now());
errors.setError(messageSource.getMessage(InternalServerError.INTERNAL_SERVER_ERROR.getMessage(), null, Locale.getDefault()));
errors.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
errors.setCode(InternalServerError.INTERNAL_SERVER_ERROR.getMessage());
return new ResponseEntity<>(errors, HttpStatus.INTERNAL_SERVER_ERROR);
}
/*
@ExceptionHandler(MyJwtException.class)
public ResponseEntity<ErrorMessage> tokenException(Exception exception, WebRequest request) {
ErrorMessage errors = new ErrorMessage();
errors.setTimestamp(LocalDateTime.now());
errors.setError(messageSource.getMessage(exception.getMessage(), null, Locale.getDefault()));
errors.setStatus(HttpStatus.FORBIDDEN.value());
errors.setCode(exception.getMessage());
return new ResponseEntity<>(errors, HttpStatus.FORBIDDEN);
}
//400 Bad Request
@ExceptionHandler(MalformedJwtException.class)
public ResponseEntity<ErrorMessage> tokenNotValid(Exception exception, WebRequest request) {
ErrorMessage errors = new ErrorMessage();
errors.setTimestamp(LocalDateTime.now());
errors.setError(messageSource.getMessage(JwtError.MALFORMED_EXCEPTION.getMessage(), null, Locale.getDefault()));
errors.setStatus(HttpStatus.BAD_REQUEST.value());
errors.setCode(JwtError.MALFORMED_EXCEPTION.getMessage());
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
//401 Unauthorized HTTP" response
@ExceptionHandler(TokenExpiredException.class)
public ResponseEntity<ErrorMessage> tokenIsExpired(Exception exception, WebRequest request) {
ErrorMessage errors = new ErrorMessage();
errors.setTimestamp(LocalDateTime.now());
errors.setError(messageSource.getMessage(JwtError.EXPIRED_JWT_EXCEPTION.getMessage(), null, Locale.getDefault()));
errors.setStatus(HttpStatus.UNAUTHORIZED.value());
errors.setCode(JwtError.EXPIRED_JWT_EXCEPTION.getMessage());
return new ResponseEntity<>(errors, HttpStatus.UNAUTHORIZED);
}
*/
//BadCredentials hatası,loginde password hatalı girilince,401 unauthorized
@ExceptionHandler(BadCredentialsException.class)
public ResponseEntity<ErrorMessage> badCredentialsException(Exception exception, WebRequest request) {
ErrorMessage errors = new ErrorMessage();
errors.setTimestamp(LocalDateTime.now());
errors.setError(messageSource.getMessage(BadCredentialError.BAD_CREDENTIAL_ERROR.getMessage(), null, Locale.getDefault()));
errors.setStatus(HttpStatus.UNAUTHORIZED.value());
errors.setCode(BadCredentialError.BAD_CREDENTIAL_ERROR.getMessage());
return new ResponseEntity<>(errors, HttpStatus.UNAUTHORIZED);
}
//403 forbidden-Rolelere göre restaurantları göstermede fırlatılıyor.
@ExceptionHandler(ForbiddenException.class)
public ResponseEntity<ErrorMessage> notPermission(Exception exception, WebRequest request) {
ErrorMessage errors = new ErrorMessage();
errors.setTimestamp(LocalDateTime.now());
errors.setError(messageSource.getMessage(NotAllowedError.DO_NOT_HAVE_PERMISSION.getMessage(), null, Locale.getDefault()));
errors.setStatus(HttpStatus.FORBIDDEN.value());
errors.setCode(NotAllowedError.DO_NOT_HAVE_PERMISSION.getMessage());
return new ResponseEntity<>(errors, HttpStatus.FORBIDDEN);
}
}
| true |
865231ace52fc4656577aaab7bebe8dcb1d1fdc9 | Java | StijnStaring/Battleship | /src/startSituation/RandomStart.java | UTF-8 | 3,936 | 3.5 | 4 | [] | no_license | package startSituation;
import ships.*;
import java.util.Arrays;
import java.util.List;
import java.util.*;
public class RandomStart {
int amountRows;
int amountColumns;
public ArrayList<Ship> shipsOnBoard = new ArrayList<>();
public RandomStart(int amountRows, int amountColumns){
this.amountRows = amountRows;
this.amountColumns = amountColumns;
List<String> possibleShips = Arrays.asList("Carrier", "Battleship", "Submarine", "Destroyer");
Collections.shuffle(possibleShips);
for(String ship: possibleShips){
int[] randomStartIndex = {new Random().nextInt(amountRows), new Random().nextInt(amountColumns)}; // Get a random start position
int randomDirection = new Random().nextInt(4); // Get a random direction of the ship
switch (ship) {
case "Carrier" -> {
List<Object> checkedPlaceBoard = generateLegitimatePlace(new Carrier(randomStartIndex, randomDirection), shipsOnBoard);
shipsOnBoard.add(new Carrier((int[]) checkedPlaceBoard.get(0), (int) checkedPlaceBoard.get(1)));
}
case "Battleship" -> {
List<Object> checkedPlaceBoard = generateLegitimatePlace(new Battleship(randomStartIndex, randomDirection), shipsOnBoard);
shipsOnBoard.add(new Battleship((int[]) checkedPlaceBoard.get(0), (int) checkedPlaceBoard.get(1)));
}
case "Submarine" -> {
List<Object> checkedPlaceBoard = generateLegitimatePlace(new Submarine(randomStartIndex, randomDirection), shipsOnBoard);
shipsOnBoard.add(new Submarine((int[]) checkedPlaceBoard.get(0), (int) checkedPlaceBoard.get(1)));
}
case "Destroyer" -> {
List<Object> checkedPlaceBoard = generateLegitimatePlace(new Destroyer(randomStartIndex, randomDirection), shipsOnBoard);
shipsOnBoard.add(new Destroyer((int[]) checkedPlaceBoard.get(0), (int) checkedPlaceBoard.get(1)));
}
}
}
}
public static boolean noOverlap(Ship newShip,ArrayList<Ship> shipsOnBoard){
for(Ship testShip: shipsOnBoard) {
for(int[] indices: newShip.allUsedIndices()) {
for(int[] indicesTestShip: testShip.allUsedIndices()) {
if (Arrays.equals(indices, indicesTestShip)) {
return false;
}
}
}
}
return true;
}
public static boolean inBoard(Ship newShip,int amountRows, int amountColumns){
for(int[] indices: newShip.allUsedIndices()){
if(indices[0] >= amountRows || indices[0] >= amountColumns || indices[1] >= amountRows || indices[1] >= amountColumns || indices[0] < 0 || indices[1] < 0){
return false;
}
}
return true;
}
// A start position and direction that are legitimate, are sought for a ship on the current board
public List<Object> generateLegitimatePlace(Ship newShip, ArrayList<Ship> shipsOnBoard) {
if (inBoard(newShip,this.amountRows,this.amountColumns) && noOverlap(newShip, shipsOnBoard)) {
return Arrays.asList(newShip.startIndex, newShip.direction);
} else {
while (true) {
int[] randomStartIndex = {new Random().nextInt(amountRows), new Random().nextInt(amountColumns)};
int randomDirection = new Random().nextInt(4);
newShip.setStartIndex(randomStartIndex);
newShip.setDirection(randomDirection);
if (inBoard(newShip,this.amountRows,this.amountColumns) && noOverlap(newShip, shipsOnBoard)) {
return Arrays.asList(newShip.startIndex, newShip.direction);
}
}
}
}
}
| true |
a52bbd061c4d3c3ee6eaede7865c84834a990297 | Java | qdsncaq/jrest4guice | /JRest4Guice/src/persistence/src/main/java/org/jrest4guice/transaction/HibernateLocalTransactionInterceptor.java | UTF-8 | 2,430 | 2.265625 | 2 | [] | no_license | package org.jrest4guice.transaction;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Transaction;
import org.jrest4guice.guice.GuiceContext;
import org.jrest4guice.persistence.hibernate.SessionFactoryHolder;
import org.jrest4guice.persistence.hibernate.SessionInfo;
import org.jrest4guice.transaction.annotations.Transactional;
import org.jrest4guice.transaction.annotations.TransactionalType;
/**
*
* @author <a href="mailto:zhangyouqun@gmail.com">cnoss (QQ:86895156)</a>
*
*/
public class HibernateLocalTransactionInterceptor implements MethodInterceptor {
private static Log log = LogFactory.getLog(HibernateLocalTransactionInterceptor.class);
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
log.debug("[HibernateLocalTransactionInterceptor]进入=》"+methodInvocation.getMethod().getName());
SessionFactoryHolder sessionFH = GuiceContext.getInstance().getBean(SessionFactoryHolder.class);
SessionInfo session = sessionFH.getSessionInfo();
Method method = methodInvocation.getMethod();
Transactional transactional = method.getAnnotation(Transactional.class);
if(transactional == null){
transactional = method.getDeclaringClass().getAnnotation(Transactional.class);
}
TransactionalType type = transactional.type();
final Transaction transaction = session.getSession().getTransaction();
if(type != TransactionalType.READOLNY){
session.setNeed2ProcessTransaction(true);
}
if(transaction.isActive()){
return methodInvocation.proceed();
}
//开始一个新的事务
if(type != TransactionalType.READOLNY){
transaction.begin();
}
Object result = null;
try {
//执行被拦截的业务方法
result = methodInvocation.proceed();
//提交事务
if(type != TransactionalType.READOLNY){
transaction.commit();
}
} catch (Exception e) {
//回滚当前事务
if(type != TransactionalType.READOLNY && transaction.isActive()){
transaction.rollback();
}
throw e;
}
log.debug("[HibernateLocalTransactionInterceptor]离开=》"+methodInvocation.getMethod().getName());
//返回业务方法的执行结果
return result;
}
}
| true |
0c5a53dc8e817c6c07fc901dfbfb6fb97b0d80be | Java | cuongnd273/alertdrowsiness | /app/src/main/java/university/project/cuong/alertdrowsiness/activity/InfomationActivity.java | UTF-8 | 4,752 | 2.1875 | 2 | [] | no_license | package university.project.cuong.alertdrowsiness.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import university.project.cuong.alertdrowsiness.R;
import university.project.cuong.alertdrowsiness.adapter.UserAdapter;
import university.project.cuong.alertdrowsiness.contants.APIConstants;
import university.project.cuong.alertdrowsiness.dao.SessionManager;
import university.project.cuong.alertdrowsiness.model.User;
public class InfomationActivity extends AppCompatActivity {
private TextView tvname;
private TextView tvemail;
private TextView tvaddress;
private TextView tvtelephone;
private TextView tvidentityCard;
private TextView tvsex;
UserAdapter userAdapter;
SessionManager session;
ListView lvUser;
ArrayList<User> arrayUsers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_user);
getControls();
getInfomationUser();
}
public void getControls()
{
tvname= (TextView)findViewById(R.id.tvname2);
tvemail=(TextView) findViewById(R.id.tvemail2);
tvaddress=(TextView) findViewById(R.id.tvaddress2);
tvtelephone=(TextView)findViewById(R.id.tvtelephone2);
tvidentityCard=(TextView)findViewById(R.id.tvidentityCard2);
tvsex=(TextView)findViewById(R.id.tvsex2);
lvUser = (ListView) findViewById(R.id.lvUser);
arrayUsers = new ArrayList<>();
userAdapter = new UserAdapter(this, R.layout.activity_updat_version, arrayUsers);
lvUser.setAdapter(userAdapter);
session=new SessionManager(this);
}
private void getInfomationUser(){
RequestQueue requestQueue = Volley.newRequestQueue(this);
String response = null;
StringRequest stringRequest = new StringRequest(Request.Method.POST, APIConstants.URL_INFO, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if(response != null){
//save shared preference
try {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject object = arr.getJSONObject(i);
System.out.println("ObjectValue" + i + "" + object.toString());
User user = new User();
user.setUserName(object.getString("username"));
user.setAddress(object.getString("address"));
user.setEmail(object.getString("email"));
user.setIdentityCard(object.getString("identitycard"));
user.setSex(object.getString("sex"));
user.setTelephone(object.getString("telephone"));
arrayUsers.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
userAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Toast.makeText(getBaseContext(), "Error System", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(InfomationActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}
){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
String name= session.getInformation("username");
params.put("username",name);
return params;
}
};
requestQueue.add(stringRequest);
}
}
| true |
09501d1a7eef98d03c1eaf35af160c1b00d579ad | Java | ugandharreddy/myrepo1 | /attrahealthcare/src/main/java/com/attra/DaoClassImpl/PatientListInterface.java | UTF-8 | 203 | 1.796875 | 2 | [] | no_license | package com.attra.DaoClassImpl;
import java.util.List;
import com.attra.Model.Appointmentdetail;
public interface PatientListInterface {
public List<Appointmentdetail> getPatientList(String email);
}
| true |
3825048f24a6ff789363689c4a825bddd1f375a1 | Java | kimonic/springbootdemo | /src/main/java/StudyRecord.java | UTF-8 | 11,053 | 2.5625 | 3 | [] | no_license | /**
* spring boot 问题记录
*/
public class StudyRecord {
/**
* https://www.zhihu.com/question/19716589
* 程序员客栈 https://www.proginn.com/
* 猿急送 http://www.yuanjisong.com/
* 码市 https://mart.coding.net/
* 大鲲 https://pro.lagou.com/
* 自客 http://www.zike.com/
* 极牛 http://geekniu.com/
* 人人开发 http://rrkf.com/
* 实现网 https://shixian.com/
* 猪八戒网 http://www.zbj.com/
* 威客 http://www.epwk.com/
*/
public void catalog() {
//001 教程地址
aaa();
//002 404 错误
aaa();
//003 springboot中访问静态资源界面 html, css等
aaa();
//004 springboot中访问jsp页面
aaa();
//005 springboot 访问数据库
aaa();
//006 spring boot 整合mybatics 纯java
aaa();
//007 解决mybatics接口类 @Mapper注入失败的问题
aaa();
//008 解决 @mapper接口类添加 @autowired注解时提示
aaa();
//009 解决mysql数据库密码错误问题
aaa();
//010 解决springboot jsp文件需要重启服务器的问题
aab();
//011 jquery mobile学习教程
aac();
// 012 IDEA配置MySQL数据库报以下错误:
aad();
// 013 Failed to start component [Connector[HTTP/1.1-8080]],导致springboot内置tomcat无法启动
aae();
//014 解决自动生成get set方法时为private的问题
aaf();
//015 main--java文件夹下的类无法直接引用
aag();
//016 mysql 启动错误 code 2003
aah();
}
private void aah() {
/**
* 016 mysql 启动错误 code 2003
* 在命令行中输入 net start mysql启动成功后即可
*/
}
private void aag() {
/**
* 015 main--java文件夹下的类无法直接引用
* 需要在java文件夹下新建包内的类才可以引用
*/
}
private void aaf() {
/**
* 014 解决自动生成get set方法时为private的问题
*
* file--settings--editor--code style --javaa--code generation--default visibility
* 中修改
*/
}
public void aaa() {
/**
*
* 主页本地访问地址
* http://localhost:8080/index
* 手机真机云测试网站
* http://wetest.qq.com/cloud/help/AndroidP?from=adsout_WTbanner_androidP
*
*
* <!--maven仓库查找网站-->
* <!--http://maven.outofmemory.cn/javax.inject/javax.inject/1/-->
* <!--http://mvnrepository.com-->
*
* * 001 教程地址
* * 002 404错误
* * 003 springboot中访问静态资源界面 html,css等
* * 004 springboot中访问jsp页面
* * 005 springboot 访问数据库
* * 006 spring boot 整合mybatics 纯java
* * 007 解决mybatics接口类@Mapper注入失败的问题
* * 008 解决@mapper接口类添加@autowired注解时提示
* * 009 解决mysql数据库密码错误问题
* * 010 解决springboot jsp文件需要重启服务器的问题
* * 011 jquery mobile学习教程
*
*
* 001 教程地址
* https://www.zhihu.com/question/53729800
*
* 002 404错误
* @RestController 注释的类需要与@SpringBootApplication注释的类处于同意文件夹下
* 或者在该类上添加注解@ComponentScan(basePackages = {"controller"}),java目录下的包名路径,\]
* 不需要包含java文件夹路径,
* 一 spring boot的启动类不能直接放在main(src.main.java)这个包下面,把它放在有包的里面就可以了。
* 二 正常启动了,但是我写了一个controller ,用的@RestController 注解去配置的controller,然后路径也搭好了,
* 但是浏览器一直报404.最后原因是,spring boot只会扫描启动类当前包和以下的包 。
* 如果将 spring boot 放在 包 com.dai.controller 里面的话 ,它会扫描 com.dai.controller 和
* com.dai.controller.* 里面的所有的 ; 还有一种解决方案是 在启动类的上面添加
* @ComponentScan(basePackages = {"com.dai.*"})
*
* 003 springboot中访问静态资源界面 html,css等
* 将静态页面文件放到src-->main-->resources-->static-->html文件夹下
* 访问的路径即为http://localhost:8080/html/hello.html
*
*
* 004 springboot中访问jsp页面
* 首先在pom.xml中添加
* <!--添加访问jsp支持*************-->
* <dependency>
* <groupId>org.springframework.boot</groupId>
* <artifactId>spring-boot-starter-tomcat</artifactId>
* <scope>provided</scope>
* </dependency>
*
* <!-- JSTL -->
* <dependency>
* <groupId>javax.servlet</groupId>
* <artifactId>jstl</artifactId>
* </dependency>
*
* <!-- Need this to compile JSP -->
* <dependency>
* <groupId>org.apache.tomcat.embed</groupId>
* <artifactId>tomcat-embed-jasper</artifactId>
* <scope>provided</scope>
* </dependency>
*
* <dependency>
* <groupId>org.eclipse.jdt.core.compiler</groupId>
* <artifactId>ecj</artifactId>
* <version>4.6.1</version>
* <scope>provided</scope>
* </dependency>
* <!--添加访问jsp支持*******************-->
*
* 创建目录webapp--WEB-INF--jsp
* 在resources文件夹下的application.properties文件中添加
*
* spring.mvc.view.prefix=/WEB-INF/jsp/
* spring.mvc.view.suffix=.jsp
*
* 005 springboot 访问数据库
* 在pom.xml文件中添加
* <!--添加MySQL数据库驱动-->
* <dependency>
* <groupId>mysql</groupId>
* <artifactId>mysql-connector-java</artifactId>
* <version>8.0.11</version>
* </dependency>
* <dependency>
* <groupId>org.springframework.boot</groupId>
* <artifactId>spring-boot-starter-jdbc</artifactId>
* </dependency>
* <!--添加MySQL数据库驱动-->
* 在resources文件夹下的application.properties文件中添加
*
* spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT
* spring.datasource.username=root
* spring.datasource.password=dingzhixin
* spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
*
* 连接并访问数据库参见DataController.java文件
*
* 006 spring boot 整合mybatics 纯java
* 在pom.xml文件中添加
* <!--集成mybatics-->
* <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
* <dependency>
* <groupId>org.mybatis.spring.boot</groupId>
* <artifactId>mybatis-spring-boot-starter</artifactId>
* <version>1.3.2</version>
* </dependency>
* <!--集成mybatics-->
* 在resources文件夹下的application.properties文件中配置数据库链接
*
* 007 解决mybatics接口类@Mapper注入失败的问题
* 在启动类SpringbootdemoApplication下添加@MapperScan("@Mapper所在的包名")注解
* http://www.cnblogs.com/zqr99/p/8677642.html
*
*
* 008 解决@mapper接口类添加@autowired注解时提示
* Could not autowire. No beans of 'UserDao' type found
* 在@Mapper接口类上添加注解@Component即可
*
*
* 009 解决mysql数据库密码错误问题
* 重置mysql数据库密码
* my.ini文件将文件加设置为显示所有文件后在文件夹programdata文件夹内查看
* https://dev.mysql.com/doc/refman/8.0/en/resetting-permissions.html
* 原链接数据库需要先断开链接后重新链接
* C:\Program Files\MySQL\MySQL Server 8.0\bin目录下启动命令行执行
* mysqld -install 可能会导致数据库文件全部被删除--不确定!!!
* 添加mybatics后导致数据库链接异常并致使数据库数据全部被删除,不确定!!!
*
*
*/
}
public void aab() {
/**
* 010 解决springboot jsp文件需要重启服务器的问题
* https://blog.csdn.net/u013042707/article/details/78648259
*
* Setting--->Compiler--->勾选Build project automatically
*
* pom.xml中添加
* <dependency>
* <groupId>org.springframework.boot</groupId>
* <artifactId>spring-boot-devtools</artifactId>
* <optional>true</optional> <!-- 表示依赖不会传递 -->
* </dependency>
*
* <plugin>
* <groupId>org.springframework.boot</groupId>
* <artifactId>spring-boot-maven-plugin</artifactId>
* <configuration>
* <fork>true</fork> <!-- 如果没有该配置,devtools不会生效 -->
* </configuration>
* </plugin>
*/
}
public void aac() {
/**
* * 011 jquery mobile学习教程
* http://www.runoob.com/jquerymobile/jquerymobile-pages.html
*/
}
public void aad(){
/**
* 012 IDEA配置MySQL数据库报以下错误:
*
* https://blog.csdn.net/sjmz30071360/article/details/80108758
*
* 问题原因:
*
* 本地安装的MySQL版本为5.7版本,IDEA默认选用的Driver files为最新版本
*该原因描述与我的实际情况不符,但是将mysql驱动程序由idea自动选择后,问题确实解决
* 问题解决:
*
* 将Driver files设置为低版本即可连接成功!!!
*/
}
public void aae() {
/**
* 013 Failed to start component [Connector[HTTP/1.1-8080]],导致springboot内置tomcat无法启动
*
* 查看任务管理器内是否有多个正在运行的java.exe进程,或者tomcat的进程,有则结束掉,重新启动即可
*/
}
}
| true |
3ff98d4d819f3f15b6cb462d9200a1b86de3f902 | Java | pooyanjamshidi/spark-suite | /spark-monitor/src/main/java/uk/ac/ic/spark/monitor/services/ClusterMonitorService.java | UTF-8 | 639 | 2.28125 | 2 | [] | no_license | package uk.ac.ic.spark.monitor.services;
import com.google.common.util.concurrent.AbstractExecutionThreadService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ClusterMonitorService extends AbstractExecutionThreadService {
private static final Logger log = LogManager.getLogger(ClusterMonitorService.class);
@Override
protected void run() throws Exception {
while (true) {
log.info("I'm ClusterMonitorService and I'm running");
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
}
| true |
20505df71ac255c55504107f1f9d1d4e2fed0684 | Java | Ellengou/jingdun-blockchain | /qhdconsole/src/main/java/com/yuyoukj/service/impl/ConfprovinceServiceImpl.java | UTF-8 | 1,705 | 1.742188 | 2 | [] | no_license | package com.yuyoukj.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yuyoukj.ao.model.Page;
import com.yuyoukj.mapper.qhd.ConfprovinceMapper;
import com.yuyoukj.model.qhd.Confprovince;
import com.yuyoukj.service.ConfprovinceService;
@Service
public class ConfprovinceServiceImpl implements ConfprovinceService {
@Autowired
private ConfprovinceMapper confprovinceMapper;
@Override
public Page<Confprovince> getConfprovinceList(Page<Confprovince> page, Map<String, Object> pmap) {
pmap.put("page", page);
getConfprovinceList(pmap);
return page;
}
@Override
public List<Confprovince> getConfprovinceList(Map<String, Object> pmap) {
return confprovinceMapper.getConfprovinceList(pmap);
}
@Override
public Confprovince getConfprovince(Map<String, Object> pmap) {
return confprovinceMapper.getConfprovince(pmap);
}
@Override
public void delConfprovince(Map<String, Object> pmap) {
confprovinceMapper.delConfprovince(pmap);
}
@Override
public void saveConfprovince(Confprovince confprovince) {
if (confprovince.getId() == null) {
confprovinceMapper.saveConfprovince(confprovince);
} else {
confprovinceMapper.updateConfprovince(confprovince);
}
}
@Override
public void updateConfprovince_map(Map<String, Object> pmap) {
confprovinceMapper.updateConfprovince_map(pmap);
}
@Override
public void updateConfprovince(Confprovince confprovince) {
confprovinceMapper.updateConfprovince(confprovince);
}
@Override
public Integer checkSname(Map<String, Object> pmap) {
return confprovinceMapper.checkSname(pmap);
}
}
| true |
3f7bd55f09f484692ea53851465a081b41e6902d | Java | vikashhrs/carpooltest | /app/src/main/java/com/example/vikash/carpooltest/RideSetupActivity.java | UTF-8 | 2,233 | 2.46875 | 2 | [] | no_license | package com.example.vikash.carpooltest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class RideSetupActivity extends AppCompatActivity implements ListView.OnItemClickListener {
private ListView listView;
ArrayList<Location> locations;
CustomLocationListViewAdapter customLocationListViewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup_ride_share);
listView = (ListView)findViewById(R.id.locationListView);
listView.setOnItemClickListener(this);
locations = getLocations();
customLocationListViewAdapter = new CustomLocationListViewAdapter(getApplicationContext(),R.layout.custom_listview_item,locations);
listView.setAdapter(customLocationListViewAdapter);
}
private ArrayList<Location> getLocations(){
ArrayList<Location> locations = new ArrayList<>();
locations.add(new Location("Karachi Bakery"));
locations.add(new Location("Cyber Towers"));
locations.add(new Location("Golconda Ford"));
locations.add(new Location("Cream Stone"));
locations.add(new Location("Snow World"));
locations.add(new Location("Punjabi Rasoi"));
locations.add(new Location("Kolkata House"));
return locations;
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Location location = (Location)adapterView.getItemAtPosition(i);
if(location.isStatusChecked()){
location.setStatusChecked(false);
}else {
location.setStatusChecked(true);
}
updateLocationList(location);
}
private void updateLocationList(Location location){
for(Location lc : locations){
if(location.getLocationName().matches(lc.getLocationName())){
locations.remove(lc);
break;
}
}
locations.add(location);
customLocationListViewAdapter.notifyDataSetChanged();
}
}
| true |
b181b0c5f311ad2b564376d730aeacd353b5e495 | Java | NishBarman/GitDemo | /Academy/src/main/java/pageObject/forgetPassword.java | UTF-8 | 565 | 2.265625 | 2 | [] | no_license | package pageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class forgetPassword {
public WebDriver driver;
By Email=By.id("user_email");
By instruction=By.xpath("//input[@value='Send Me Instruction']");
public forgetPassword(WebDriver driver) {
// TODO Auto-generated constructor stub
this.driver=driver;
}
public WebElement getEmail()
{
return driver.findElement(Email);
}
public WebElement sendInstructions()
{
return driver.findElement(instruction);
}
}
| true |
ce47cb9884130e9878d88fab7d91f51bff05dca2 | Java | soeunsocheat/SportClub | /app/src/main/java/com/example/msi/sportclub/Menu_Screen.java | UTF-8 | 1,102 | 1.84375 | 2 | [] | no_license | package com.example.msi.sportclub;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class Menu_Screen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu__screen);
}
public void doHome(View view) {
Intent intent = new Intent(this, Home_Screen.class);
startActivity(intent);
}
public void doLoginAccount(View view) {
Intent intent = new Intent(this, LogIn_Screen.class);
startActivity(intent);
}
public void doProfile(View view) {
Intent intent = new Intent(this, Profile_Screen.class);
startActivity(intent);
}
public void doAboutUs(View view) {
Intent intent = new Intent(this, About_Us.class);
startActivity(intent);
}
public void doFillFeedback(View view) {
Intent intent = new Intent(this, Fill_Feedback.class);
startActivity(intent);
}
}
| true |
1724d91d321ab4841c1758b6e95789d480c2989b | Java | wmh200/miniRpc | /rpc-mini-rpc/src/main/java/hust/wang/netty/rpc/manage/RpcServiceManager.java | UTF-8 | 6,218 | 2.203125 | 2 | [] | no_license | package hust.wang.netty.rpc.manage;
/**
* @Author wangmh
* @Date 2021/6/25 下午5:07
**/
import hust.wang.netty.rpc.annotation.RpcServer;
import hust.wang.netty.rpc.annotation.RpcServerScan;
import hust.wang.netty.rpc.factory.ServiceFactory;
import hust.wang.netty.rpc.handler.HeartBeatServerHandler;
import hust.wang.netty.rpc.handler.PingMessageHandler;
import hust.wang.netty.rpc.handler.RpcRequestMessageHandler;
import hust.wang.netty.rpc.protocol.MessageCodecSharable;
import hust.wang.netty.rpc.protocol.ProtocolFrameDecoder;
import hust.wang.netty.rpc.register.NacosServerRegistry;
import hust.wang.netty.rpc.register.ServerRegistry;
import hust.wang.netty.rpc.util.PackageScanUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import java.net.InetSocketAddress;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Rpc服务端管理器
*
* @author chenlei
*/
public class RpcServiceManager {
protected String host;
protected int port;
protected ServerRegistry serverRegistry;
protected ServiceFactory serviceFactory;
NioEventLoopGroup worker = new NioEventLoopGroup();
NioEventLoopGroup boss = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
public RpcServiceManager(String host, int port) {
this.host = host;
this.port = port;
serverRegistry = new NacosServerRegistry();
serviceFactory = new ServiceFactory();
// 完成注册 扫描启动类上层的包 遍历所有target下的项目路径 找到加了注解的类注册到nacos里
autoRegistry();
}
/**
* 开启服务
*/
public void start() {
//日志
LoggingHandler LOGGING = new LoggingHandler(LogLevel.DEBUG);
//消息节码器
MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
//RPC请求处理器
RpcRequestMessageHandler RPC_HANDLER = new RpcRequestMessageHandler();
//心跳处理器
HeartBeatServerHandler HEATBEAT_SERVER = new HeartBeatServerHandler();
//心跳请求的处理器
PingMessageHandler PINGMESSAGE = new PingMessageHandler();
try {
bootstrap.group(boss, worker)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 256)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.TCP_NODELAY, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
pipeline.addLast(new ProtocolFrameDecoder());//定长解码器
pipeline.addLast(MESSAGE_CODEC);
pipeline.addLast(LOGGING);
pipeline.addLast(RPC_HANDLER);
}
});
//绑定端口
Channel channel = bootstrap.bind(port).sync().channel();
channel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
System.err.println("启动服务出错");
}finally {
worker.shutdownGracefully();
boss.shutdownGracefully();
}
}
/**
* 自动扫描@RpcServer注解 注册服务
*/
public void autoRegistry() {
String mainClassPath = PackageScanUtils.getStackTrace();
Class<?> mainClass;
try {
mainClass = Class.forName(mainClassPath);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("启动类为找到");
}
if (mainClass.isAnnotationPresent(RpcServer.class)) {
throw new RuntimeException("启动类缺少@RpcServer 注解");
}
String annotationValue = mainClass.getAnnotation(RpcServerScan.class).value();
//如果注解路径的值是空,则等于main父路径包下 获取父路径
if ("".equals(annotationValue)) {
annotationValue = mainClassPath.substring(0, mainClassPath.lastIndexOf("."));
}
//获取所有类的set集合
Set<Class<?>> set = PackageScanUtils.getClasses(annotationValue);
System.out.println(set.size());
for (Class<?> c : set) {
//只有有@RpcServer注解的才注册
if (c.isAnnotationPresent(RpcServer.class)) {
String ServerNameValue = c.getAnnotation(RpcServer.class).name();
Object object;
try {
object = c.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
System.err.println("创建对象" + c + "发生错误");
continue;
}
//注解的值如果为空,使用类名
if ("".equals(ServerNameValue)) {
addServer(object,c.getCanonicalName());
} else {
addServer(object, ServerNameValue);
}
}
}
}
/**
* 添加对象到工厂和注册到注册中心
*
* @param server
* @param serverName
* @param <T>
*/
public <T> void addServer(T server, String serverName) {
serviceFactory.addServiceProvider(server, serverName);
serverRegistry.register(serverName, new InetSocketAddress(host, port));
}
}
| true |
41a79f3f8aee166f094e1ecfeb11e99aeed58be1 | Java | pramodwus/SpringBoot-Security | /Spring-Mvc-Boot/src/main/java/com/sathya/controller/WelcomeController.java | UTF-8 | 355 | 1.78125 | 2 | [] | no_license | package com.sathya.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class WelcomeController {
@GetMapping("/show")
public ModelAndView showWelcome()
{
return new ModelAndView("welcome");
}
}
| true |
0fab12abbdea67463397f39b65aa4cac93ec036c | Java | nmwael/EyeOfTheWatcher | /EyeOfTheWatcherTornadoFX/src/main/java/org/eyeofthewatcher/dungeonmaster/DungeonMasterJSON.java | UTF-8 | 1,238 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | package org.eyeofthewatcher.dungeonmaster;
import org.eyeofthewatcher.dungeonmaster.entities.Prop;
import org.eyeofthewatcher.dungeonmaster.entities.Tile;
import org.eyeofthewatcher.dungeonmaster.entities.Weapon;
import java.util.Random;
/**
* Created by nmw on 12-06-2017.
*/
public class DungeonMasterJSON implements DungeonMaster {
private Random random;
private JSONRepository<Weapon> weaponJSONRepository;
private JSONRepository<Tile> tileJSONRepository;
private JSONRepository<Prop> propJSONRepository;
public DungeonMasterJSON() {
random = new Random();
weaponJSONRepository = new JSONRepository<>(Weapon.class);
tileJSONRepository = new JSONRepository<>(Tile.class);
propJSONRepository = new JSONRepository<>(Prop.class);
}
@Override
public JSONRepository<Weapon> getWeaponRepository() {
return weaponJSONRepository;
}
@Override
public JSONRepository<Tile> getTileRepository() {
return tileJSONRepository;
}
@Override
public JSONRepository<Prop> getPropRepository() {
return propJSONRepository;
}
@Override
public Integer rollDice(Short sides) {
return random.nextInt(sides);
}
}
| true |
ed22d4d4badde6a0c72b01b57808feb3a336cc34 | Java | rubenspessoa/wsn-simulation | /JSensor/src/projects/Flooding/DistributionModels/RandomDistribution.java | UTF-8 | 484 | 2.171875 | 2 | [] | no_license | package projects.Flooding.DistributionModels;
import jsensor.nodes.Node;
import jsensor.nodes.models.DistributionModelNode;
import jsensor.utils.Configuration;
import jsensor.utils.Position;
/**
*
* @authorMatheus
*/
public class RandomDistribution extends DistributionModelNode
{
@Override
public Position getPosition(Node s) {
return new Position(s.getRandom().nextInt(Configuration.dimX), s.getRandom().nextInt(Configuration.dimY));
}
}
| true |
2b1280c048c773262d6534eea29081835db4f0aa | Java | AZhen2333/erp01 | /src/main/java/com/dg/entity/ResponseResult.java | UTF-8 | 1,538 | 2.4375 | 2 | [] | no_license | package com.dg.entity;
import com.dg.utils.IStatusMessage;
import java.io.Serializable;
/**
* 前端请求响应结果,code:编码,message:描述,obj对象,可以是单个数据对象,数据列表或者PageInfo
*/
public class ResponseResult implements Serializable {
private static final long serialVersionUID = 7285065610386199394L;
private String code;
private String message;
private Object obj;
/**
* 成功
*/
public ResponseResult() {
this.code = IStatusMessage.SystemStatus.SUCCESS.getCode();
this.message = IStatusMessage.SystemStatus.SUCCESS.getMessage();
}
public ResponseResult(Object obj) {
this.code = IStatusMessage.SystemStatus.SUCCESS.getCode();
this.message = IStatusMessage.SystemStatus.SUCCESS.getMessage();
this.obj = obj;
}
/**
* 失败
*
* @param statusMessage
*/
public ResponseResult(IStatusMessage statusMessage) {
this.code = statusMessage.getCode();
this.message = statusMessage.getMessage();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
}
| true |
68a99f1e0d8fea08d23ec6e42ed12b4037d26126 | Java | sdcote/coyote | /CoyoteDX/src/test/java/coyote/dx/writer/FlatFileTest.java | UTF-8 | 1,181 | 1.90625 | 2 | [] | no_license | /*
* Copyright (c) 2015 Stephan D. Cote' - All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the MIT License which accompanies this distribution, and is
* available at http://creativecommons.org/licenses/MIT/
*/
package coyote.dx.writer;
//import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import coyote.dx.AbstractTest;
import coyote.dx.TransformEngine;
import coyote.loader.log.Log;
/**
* This tests the ability to simply run a bunch of tasks in order within a
* context to perform some generic function.
*/
public class FlatFileTest extends AbstractTest {
// @Test
public void test() {
// load the configuration from the class path
TransformEngine engine = loadEngine("ffwritertest");
assertNotNull(engine);
try {
engine.run();
} catch (Exception e) {
e.printStackTrace();
Log.error(e.getMessage());
fail(e.getMessage());
}
try {
engine.close();
} catch (IOException e) {
e.printStackTrace();
Log.error(e.getMessage());
}
}
}
| true |
2e90fccf5d422086fba91172a5de76c0a56adcee | Java | zjsywcc/cyborg-cloud | /src/main/java/com/ese/cloud/client/service/impl/AppInfoServiceImpl.java | UTF-8 | 2,894 | 2.140625 | 2 | [] | no_license | package com.ese.cloud.client.service.impl;
import com.ese.cloud.client.dao.AppInfoDao;
import com.ese.cloud.client.entity.AppInfo;
import com.ese.cloud.client.service.AppInfoService;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by rencong on 17/2/15.
*/
@Service
public class AppInfoServiceImpl implements AppInfoService {
Logger logger = LoggerFactory.getLogger(AppInfoServiceImpl.class);
@Autowired
AppInfoDao appInfoDao;
@Override
public boolean add(AppInfo appInfo) {
return appInfoDao.add(appInfo);
}
@Override
public AppInfo findById(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(new ObjectId(id)));
return appInfoDao.findOneByQuery(query);
}
@Override
public List<AppInfo> pageFind(int pageIndex, int pageSize) {
Query query = new Query();
query.skip(pageIndex);// skip相当于从那条记录开始
query.limit(pageSize);// 从skip开始,取多少条记录
return appInfoDao.findListByQuery(query);
}
@Override
public List<AppInfo> all() {
Query query = new Query();
return appInfoDao.findListByQuery(query);
}
@Override
public Long count() {
Query query = new Query();
return appInfoDao.count(query);
}
@Override
public boolean delete(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(new ObjectId(id)));
return appInfoDao.delete(query);
}
@Override
public boolean update(AppInfo appInfo) {
return appInfoDao.update(appInfo);
}
@Override
public boolean validateAppInfo(String id,String type,String value) {
Query query = new Query();
if(StringUtils.isNotEmpty(id)) {
query.addCriteria(Criteria.where("_id").ne(new ObjectId(id)));
}
if(StringUtils.equals("0",type)){
query.addCriteria(Criteria.where("name").is(value));
}
if(StringUtils.equals("1",type)){
query.addCriteria(Criteria.where("code").is(value));
}
if(StringUtils.equals("2",type)){
query.addCriteria(Criteria.where("owner").is(value));
}
if(StringUtils.equals("3",type)){
query.addCriteria(Criteria.where("mob").is(value));
}
if(StringUtils.equals("4",type)){
query.addCriteria(Criteria.where("email").is(value));
}
return appInfoDao.findByQuery(query);
}
}
| true |
eb21c90d4d8da779f30fc3b239d29568b5be1691 | Java | lenik/stack | /plover/modeling/plover-orm/src/main/java/com/bee32/plover/orm/context/PloverHibernateInterceptor.java | UTF-8 | 831 | 2.09375 | 2 | [] | no_license | package com.bee32.plover.orm.context;
import javax.inject.Inject;
import javax.inject.Named;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.orm.hibernate3.HibernateInterceptor;
import org.springframework.stereotype.Component;
@Component
@Named("hibernateInterceptor")
@Lazy
public class PloverHibernateInterceptor
extends HibernateInterceptor {
static Logger logger = LoggerFactory.getLogger(PloverHibernateInterceptor.class);
public PloverHibernateInterceptor() {
logger.info("Create default hibernate interceptor");
}
@Inject
@Override
public void setSessionFactory(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
}
| true |
701015e1be8252c3b9339edab002fed54667a8f8 | Java | Mohibulislam12/assignment | /capitalize.java | UTF-8 | 484 | 3.453125 | 3 | [] | no_license | import java.io.*;
class capitalize
{
public static void main(String args[])
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string");
String s = br.readLine();
int len = s.length();
String word="";
for(int i=0;i<len;i++)
{
char ch=s.charAt(i);
if(i%2==0)
ch=Character.toUpperCase(ch);
word=word+ch;
}
System.out.println("Required string is " + word);
}
catch(Exception e) {}
}
}
| true |
463729fd75ed05649ae9564a953e1cf4226ae726 | Java | miuramo/AnchorGarden | /src/jaist/css/covis/fm/AbstractFlowMenu.java | SHIFT_JIS | 3,545 | 2.171875 | 2 | [
"MIT"
] | permissive | package jaist.css.covis.fm;
import java.awt.Cursor;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import edu.umd.cs.piccolo.PCamera;
import edu.umd.cs.piccolo.PCanvas;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.event.PDragSequenceEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
/**
* t[j[̋ʕ
* @author miuramo
*
*/
public class AbstractFlowMenu extends PDragSequenceEventHandler {
public static Cursor handcursor = new Cursor(Cursor.HAND_CURSOR);
public static Cursor defaultcursor = new Cursor(Cursor.DEFAULT_CURSOR);
// public V geopanel;
// public PPath squiggle;
public int strokecount;
public long stime;
public PNode target;
public JFrame frame;
// public StudentPanel sptarget;
public Point2D tp;
public State fmenu, fmenu_orig;
public PCanvas canvas;
public PCamera camera;
public Point2D basep;
public Point2D camerap;
// public PBounds sptargetbb;
// private State now_state;
public java.util.Timer daemon;
public boolean outofbounds = false;
// Category log;
// public Vector redpenv;
// double[2] z̃xNg邾Bespanelɂ܂BStringBuffer͂ł͕svBƂŊOB
public PNode getTarget() {
return target;
}
// public StudentPanel getSpTarget(){
// return sptarget;
// }
public int getX() {
return (int) camerap.getX();
}
public int getY() {
return (int) camerap.getY();
}
// j[\C܂͔\ɂ
public void showMenu(boolean f) {
if (f) {
fmenu = fmenu_orig;
fmenu.paint();
if (fmenu != null)
camera.addChild(fmenu);
if (frame != null)
frame.setCursor(handcursor);
} else {
if (daemon != null) {
daemon.cancel();
daemon = null;
}
if (fmenu != null) {
camera.addChild(fmenu);
camera.removeChild(fmenu);
}
fmenu = null;
target = null;
strokecount = 0;
}
}
// j[\ǂiځCJ̎qm[hƂđ݂邩ǂׂj
public boolean isMenuShown() {
if (fmenu == null)
return false;
return fmenu.isDescendentOf(camera);
}
public void changeState(State newstate) {
if (fmenu != null) {
camera.addChild(fmenu);
camera.removeChild(fmenu);
}
fmenu = newstate;
fmenu.paint();
camera.addChild(fmenu);
}
public AbstractFlowMenu(JFrame f, PCanvas can, PCamera cam) {
frame = f;
canvas = can;
camera = cam;
// log = Logger.getLogger(AbstractFlowMenu.class.getName());
}
public void startDrag_pre(PInputEvent e) {
target = e.getPickedNode();
tp = target.getOffset();
basep = e.getPosition();
// log.debug(basep);
camerap = e.getPositionRelativeTo(camera);
}
public void startDrag_post(PInputEvent e) {
// TuNXŁCKvMyTimerTask_forYourClass NCXPW[
}
public void startDrag(PInputEvent e) {
super.startDrag(e);
// canvas.setCursor(handcursor);
}
public void drag(PInputEvent e) {
super.drag(e);
}
public void endDrag(PInputEvent e) {
super.endDrag(e);
endDrag_first(e);
endDrag_mid(e);
endDrag_end(e);
}
public void endDrag_first(PInputEvent e) {
if (fmenu != null)
fmenu.endDrag(e);
if (daemon != null) {
daemon.cancel();
daemon = null;
}
}
public void endDrag_mid(PInputEvent e) {
}
public void endDrag_end(PInputEvent e) {
showMenu(false);
outofbounds = false;
if (frame != null)
frame.setCursor(defaultcursor);
}
}
| true |
75fa17557ba5ae688fa9da5b4f44c56d7bd115bd | Java | baptistecolin/tp_jflex_cup | /Parser.java | UTF-8 | 56,912 | 2.1875 | 2 | [] | no_license |
//----------------------------------------------------
// The following code was generated by CUP v0.11a beta 20060608
// Wed Sep 27 11:11:14 CEST 2017
//----------------------------------------------------
import java_cup.runtime.*;
import java.util.*;
import java.io.*;
import java.lang.Math;
/** CUP v0.11a beta 20060608 generated parser.
* @version Wed Sep 27 11:11:14 CEST 2017
*/
public class Parser extends java_cup.runtime.lr_parser {
/** Default constructor. */
public Parser() {super();}
/** Constructor which sets the default scanner. */
public Parser(java_cup.runtime.Scanner s) {super(s);}
/** Constructor which sets the default scanner. */
public Parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);}
/** Production table. */
protected static final short _production_table[][] =
unpackFromStrings(new String[] {
"\000\055\000\002\002\004\000\002\002\003\000\002\002" +
"\004\000\002\006\002\000\002\002\005\000\002\007\002" +
"\000\002\003\005\000\002\010\002\000\002\003\005\000" +
"\002\011\002\000\002\003\005\000\002\012\002\000\002" +
"\003\005\000\002\004\005\000\002\004\005\000\002\004" +
"\005\000\002\004\005\000\002\004\004\000\002\004\006" +
"\000\002\004\006\000\002\004\006\000\002\004\006\000" +
"\002\004\006\000\002\004\006\000\002\004\005\000\002" +
"\004\005\000\002\004\003\000\002\004\003\000\002\004" +
"\003\000\002\004\003\000\002\004\005\000\002\004\005" +
"\000\002\004\004\000\002\004\005\000\002\004\005\000" +
"\002\004\005\000\002\004\005\000\002\004\005\000\002" +
"\004\007\000\002\004\003\000\002\004\003\000\002\005" +
"\005\000\002\005\005\000\002\005\005\000\002\005\005" +
"" });
/** Access to production table. */
public short[][] production_table() {return _production_table;}
/** Parse-action table. */
protected static final short[][] _action_table =
unpackFromStrings(new String[] {
"\000\136\000\046\003\021\010\022\012\030\014\020\015" +
"\024\016\012\017\013\020\023\021\004\027\016\032\026" +
"\040\011\043\005\044\007\045\017\046\010\047\027\050" +
"\031\001\002\000\004\012\136\001\002\000\042\004\uffd9" +
"\005\uffd9\006\uffd9\007\uffd9\011\uffd9\013\uffd9\022\uffd9\030" +
"\uffd9\031\uffd9\033\uffd9\034\uffd9\035\uffd9\036\uffd9\037\uffd9" +
"\041\uffd9\042\uffd9\001\002\000\004\011\ufffa\001\002\000" +
"\042\004\uffda\005\uffda\006\uffda\007\uffda\011\uffda\013\uffda" +
"\022\uffda\030\uffda\031\uffda\033\uffda\034\uffda\035\uffda\036" +
"\uffda\037\uffda\041\uffda\042\uffda\001\002\000\042\004\uffe5" +
"\005\uffe5\006\uffe5\007\uffe5\011\uffe5\013\uffe5\022\uffe5\030" +
"\uffe5\031\uffe5\033\uffe5\034\uffe5\035\uffe5\036\uffe5\037\uffe5" +
"\041\uffe5\042\uffe5\001\002\000\004\011\ufff6\001\002\000" +
"\004\012\127\001\002\000\004\012\124\001\002\000\036" +
"\004\050\005\053\006\044\007\041\011\ufffc\022\047\030" +
"\046\031\051\033\045\034\042\035\052\036\054\037\040" +
"\041\043\001\002\000\046\002\000\010\000\012\000\014" +
"\000\015\000\016\000\017\000\020\000\021\000\027\000" +
"\032\000\040\000\043\000\044\000\045\000\046\000\047" +
"\000\050\000\001\002\000\004\011\ufff8\001\002\000\042" +
"\004\uffe7\005\uffe7\006\uffe7\007\uffe7\011\uffe7\013\uffe7\022" +
"\uffe7\030\uffe7\031\uffe7\033\uffe7\034\uffe7\035\uffe7\036\uffe7" +
"\037\uffe7\041\uffe7\042\uffe7\001\002\000\004\012\115\001" +
"\002\000\004\011\ufffe\001\002\000\040\010\022\012\030" +
"\014\020\015\024\016\012\017\013\020\023\021\004\032" +
"\026\043\005\044\007\045\017\046\010\047\027\050\036" +
"\001\002\000\004\012\107\001\002\000\004\012\104\001" +
"\002\000\046\002\102\010\022\012\030\014\020\015\024" +
"\016\012\017\013\020\023\021\004\027\016\032\026\040" +
"\011\043\005\044\007\045\017\046\010\047\027\050\031" +
"\001\002\000\040\010\022\012\030\014\020\015\024\016" +
"\012\017\013\020\023\021\004\032\026\043\005\044\007" +
"\045\017\046\010\047\027\050\036\001\002\000\042\004" +
"\uffe4\005\uffe4\006\uffe4\007\uffe4\011\uffe4\013\uffe4\022\uffe4" +
"\030\uffe4\031\uffe4\033\uffe4\034\uffe4\035\uffe4\036\uffe4\037" +
"\uffe4\041\uffe4\042\uffe4\001\002\000\040\010\022\012\030" +
"\014\020\015\024\016\012\017\013\020\023\021\004\032" +
"\026\043\005\044\007\045\017\046\010\047\027\050\036" +
"\001\002\000\046\004\uffe6\005\uffe6\006\uffe6\007\uffe6\011" +
"\uffe6\022\uffe6\023\034\024\033\025\035\026\032\030\uffe6" +
"\031\uffe6\033\uffe6\034\uffe6\035\uffe6\036\uffe6\037\uffe6\041" +
"\uffe6\001\002\000\040\010\022\012\030\014\020\015\024" +
"\016\012\017\013\020\023\021\004\032\026\043\005\044" +
"\007\045\017\046\010\047\027\050\036\001\002\000\040" +
"\010\022\012\030\014\020\015\024\016\012\017\013\020" +
"\023\021\004\032\026\043\005\044\007\045\017\046\010" +
"\047\027\050\036\001\002\000\040\010\022\012\030\014" +
"\020\015\024\016\012\017\013\020\023\021\004\032\026" +
"\043\005\044\007\045\017\046\010\047\027\050\036\001" +
"\002\000\040\010\022\012\030\014\020\015\024\016\012" +
"\017\013\020\023\021\004\032\026\043\005\044\007\045" +
"\017\046\010\047\027\050\036\001\002\000\042\004\uffe6" +
"\005\uffe6\006\uffe6\007\uffe6\011\uffe6\013\uffe6\022\uffe6\030" +
"\uffe6\031\uffe6\033\uffe6\034\uffe6\035\uffe6\036\uffe6\037\uffe6" +
"\041\uffe6\042\uffe6\001\002\000\036\004\050\005\053\006" +
"\044\007\041\011\uffd6\022\047\030\046\031\051\033\045" +
"\034\042\035\052\036\054\037\040\041\043\001\002\000" +
"\040\010\022\012\030\014\020\015\024\016\012\017\013" +
"\020\023\021\004\032\026\043\005\044\007\045\017\046" +
"\010\047\027\050\036\001\002\000\040\010\022\012\030" +
"\014\020\015\024\016\012\017\013\020\023\021\004\032" +
"\026\043\005\044\007\045\017\046\010\047\027\050\036" +
"\001\002\000\040\010\022\012\030\014\020\015\024\016" +
"\012\017\013\020\023\021\004\032\026\043\005\044\007" +
"\045\017\046\010\047\027\050\036\001\002\000\040\010" +
"\022\012\030\014\020\015\024\016\012\017\013\020\023" +
"\021\004\032\026\043\005\044\007\045\017\046\010\047" +
"\027\050\036\001\002\000\040\010\022\012\030\014\020" +
"\015\024\016\012\017\013\020\023\021\004\032\026\043" +
"\005\044\007\045\017\046\010\047\027\050\036\001\002" +
"\000\040\010\022\012\030\014\020\015\024\016\012\017" +
"\013\020\023\021\004\032\026\043\005\044\007\045\017" +
"\046\010\047\027\050\036\001\002\000\040\010\022\012" +
"\030\014\020\015\024\016\012\017\013\020\023\021\004" +
"\032\026\043\005\044\007\045\017\046\010\047\027\050" +
"\036\001\002\000\040\010\022\012\030\014\020\015\024" +
"\016\012\017\013\020\023\021\004\032\026\043\005\044" +
"\007\045\017\046\010\047\027\050\036\001\002\000\040" +
"\010\022\012\030\014\020\015\024\016\012\017\013\020" +
"\023\021\004\032\026\043\005\044\007\045\017\046\010" +
"\047\027\050\036\001\002\000\040\010\022\012\030\014" +
"\020\015\024\016\012\017\013\020\023\021\004\032\026" +
"\043\005\044\007\045\017\046\010\047\027\050\036\001" +
"\002\000\040\010\022\012\030\014\020\015\024\016\012" +
"\017\013\020\023\021\004\032\026\043\005\044\007\045" +
"\017\046\010\047\027\050\036\001\002\000\040\010\022" +
"\012\030\014\020\015\024\016\012\017\013\020\023\021" +
"\004\032\026\043\005\044\007\045\017\046\010\047\027" +
"\050\036\001\002\000\040\010\022\012\030\014\020\015" +
"\024\016\012\017\013\020\023\021\004\032\026\043\005" +
"\044\007\045\017\046\010\047\027\050\036\001\002\000" +
"\042\004\uffdd\005\uffdd\006\uffdd\007\uffdd\011\uffdd\013\uffdd" +
"\022\047\030\uffdd\031\uffdd\033\uffdd\034\uffdd\035\uffdd\036" +
"\uffdd\037\uffdd\041\043\042\uffdd\001\002\000\042\004\ufff3" +
"\005\ufff3\006\044\007\041\011\ufff3\013\ufff3\022\047\030" +
"\ufff3\031\ufff3\033\045\034\042\035\052\036\054\037\040" +
"\041\043\042\ufff3\001\002\000\042\004\uffde\005\uffde\006" +
"\uffde\007\uffde\011\uffde\013\uffde\022\047\030\uffde\031\uffde" +
"\033\uffde\034\uffde\035\uffde\036\uffde\037\uffde\041\043\042" +
"\uffde\001\002\000\042\004\uffe2\005\uffe2\006\044\007\041" +
"\011\uffe2\013\uffe2\022\047\030\uffe2\031\uffe2\033\045\034" +
"\042\035\052\036\054\037\040\041\043\042\uffe2\001\002" +
"\000\042\004\ufff4\005\ufff4\006\044\007\041\011\ufff4\013" +
"\ufff4\022\047\030\ufff4\031\ufff4\033\045\034\042\035\052" +
"\036\054\037\040\041\043\042\ufff4\001\002\000\042\004" +
"\uffe9\005\uffe9\006\uffe9\007\uffe9\011\uffe9\013\uffe9\022\uffe9" +
"\030\uffe9\031\uffe9\033\uffe9\034\uffe9\035\uffe9\036\uffe9\037" +
"\uffe9\041\uffe9\042\uffe9\001\002\000\042\004\uffe3\005\uffe3" +
"\006\044\007\041\011\uffe3\013\uffe3\022\047\030\uffe3\031" +
"\uffe3\033\045\034\042\035\052\036\054\037\040\041\043" +
"\042\uffe3\001\002\000\042\004\uffe0\005\uffe0\006\uffe0\007" +
"\uffe0\011\uffe0\013\uffe0\022\047\030\uffe0\031\uffe0\033\uffe0" +
"\034\uffe0\035\uffe0\036\uffe0\037\uffe0\041\043\042\uffe0\001" +
"\002\000\042\004\ufff2\005\ufff2\006\ufff2\007\ufff2\011\ufff2" +
"\013\ufff2\022\047\030\ufff2\031\ufff2\033\ufff2\034\ufff2\035" +
"\ufff2\036\ufff2\037\ufff2\041\043\042\ufff2\001\002\000\036" +
"\004\050\005\053\006\044\007\041\022\047\030\046\031" +
"\051\033\045\034\042\035\052\036\054\037\040\041\043" +
"\042\067\001\002\000\040\010\022\012\030\014\020\015" +
"\024\016\012\017\013\020\023\021\004\032\026\043\005" +
"\044\007\045\017\046\010\047\027\050\036\001\002\000" +
"\042\004\050\005\053\006\044\007\041\011\uffdb\013\uffdb" +
"\022\047\030\046\031\051\033\045\034\042\035\052\036" +
"\054\037\040\041\043\042\uffdb\001\002\000\042\004\uffdf" +
"\005\uffdf\006\uffdf\007\uffdf\011\uffdf\013\uffdf\022\047\030" +
"\uffdf\031\uffdf\033\uffdf\034\uffdf\035\uffdf\036\uffdf\037\uffdf" +
"\041\043\042\uffdf\001\002\000\042\004\ufff1\005\ufff1\006" +
"\ufff1\007\ufff1\011\ufff1\013\ufff1\022\047\030\ufff1\031\ufff1" +
"\033\ufff1\034\ufff1\035\ufff1\036\ufff1\037\ufff1\041\043\042" +
"\ufff1\001\002\000\042\004\uffdc\005\uffdc\006\uffdc\007\uffdc" +
"\011\uffdc\013\uffdc\022\047\030\uffdc\031\uffdc\033\uffdc\034" +
"\uffdc\035\uffdc\036\uffdc\037\uffdc\041\043\042\uffdc\001\002" +
"\000\036\004\050\005\053\006\044\007\041\011\uffd8\022" +
"\047\030\046\031\051\033\045\034\042\035\052\036\054" +
"\037\040\041\043\001\002\000\036\004\050\005\053\006" +
"\044\007\041\011\uffd7\022\047\030\046\031\051\033\045" +
"\034\042\035\052\036\054\037\040\041\043\001\002\000" +
"\036\004\050\005\053\006\044\007\041\011\uffd5\022\047" +
"\030\046\031\051\033\045\034\042\035\052\036\054\037" +
"\040\041\043\001\002\000\036\004\050\005\053\006\044" +
"\007\041\013\100\022\047\030\046\031\051\033\045\034" +
"\042\035\052\036\054\037\040\041\043\001\002\000\042" +
"\004\uffe8\005\uffe8\006\uffe8\007\uffe8\011\uffe8\013\uffe8\022" +
"\uffe8\030\uffe8\031\uffe8\033\uffe8\034\uffe8\035\uffe8\036\uffe8" +
"\037\uffe8\041\uffe8\042\uffe8\001\002\000\042\004\uffe1\005" +
"\uffe1\006\uffe1\007\uffe1\011\uffe1\013\uffe1\022\047\030\uffe1" +
"\031\uffe1\033\uffe1\034\uffe1\035\uffe1\036\uffe1\037\uffe1\041" +
"\043\042\uffe1\001\002\000\004\002\001\001\002\000\046" +
"\002\uffff\010\uffff\012\uffff\014\uffff\015\uffff\016\uffff\017" +
"\uffff\020\uffff\021\uffff\027\uffff\032\uffff\040\uffff\043\uffff" +
"\044\uffff\045\uffff\046\uffff\047\uffff\050\uffff\001\002\000" +
"\040\010\022\012\030\014\020\015\024\016\012\017\013" +
"\020\023\021\004\032\026\043\005\044\007\045\017\046" +
"\010\047\027\050\036\001\002\000\036\004\050\005\053" +
"\006\044\007\041\013\106\022\047\030\046\031\051\033" +
"\045\034\042\035\052\036\054\037\040\041\043\001\002" +
"\000\042\004\uffee\005\uffee\006\uffee\007\uffee\011\uffee\013" +
"\uffee\022\uffee\030\uffee\031\uffee\033\uffee\034\uffee\035\uffee" +
"\036\uffee\037\uffee\041\uffee\042\uffee\001\002\000\040\010" +
"\022\012\030\014\020\015\024\016\012\017\013\020\023" +
"\021\004\032\026\043\005\044\007\045\017\046\010\047" +
"\027\050\036\001\002\000\036\004\050\005\053\006\044" +
"\007\041\013\111\022\047\030\046\031\051\033\045\034" +
"\042\035\052\036\054\037\040\041\043\001\002\000\042" +
"\004\uffeb\005\uffeb\006\uffeb\007\uffeb\011\uffeb\013\uffeb\022" +
"\uffeb\030\uffeb\031\uffeb\033\uffeb\034\uffeb\035\uffeb\036\uffeb" +
"\037\uffeb\041\uffeb\042\uffeb\001\002\000\042\004\ufff0\005" +
"\ufff0\006\ufff0\007\ufff0\011\ufff0\013\ufff0\022\047\030\ufff0" +
"\031\ufff0\033\ufff0\034\ufff0\035\ufff0\036\ufff0\037\ufff0\041" +
"\043\042\ufff0\001\002\000\004\011\114\001\002\000\046" +
"\002\ufffd\010\ufffd\012\ufffd\014\ufffd\015\ufffd\016\ufffd\017" +
"\ufffd\020\ufffd\021\ufffd\027\ufffd\032\ufffd\040\ufffd\043\ufffd" +
"\044\ufffd\045\ufffd\046\ufffd\047\ufffd\050\ufffd\001\002\000" +
"\040\010\022\012\030\014\020\015\024\016\012\017\013" +
"\020\023\021\004\032\026\043\005\044\007\045\017\046" +
"\010\047\027\050\036\001\002\000\036\004\050\005\053" +
"\006\044\007\041\013\117\022\047\030\046\031\051\033" +
"\045\034\042\035\052\036\054\037\040\041\043\001\002" +
"\000\042\004\uffef\005\uffef\006\uffef\007\uffef\011\uffef\013" +
"\uffef\022\uffef\030\uffef\031\uffef\033\uffef\034\uffef\035\uffef" +
"\036\uffef\037\uffef\041\uffef\042\uffef\001\002\000\004\011" +
"\121\001\002\000\046\002\ufff7\010\ufff7\012\ufff7\014\ufff7" +
"\015\ufff7\016\ufff7\017\ufff7\020\ufff7\021\ufff7\027\ufff7\032" +
"\ufff7\040\ufff7\043\ufff7\044\ufff7\045\ufff7\046\ufff7\047\ufff7" +
"\050\ufff7\001\002\000\004\011\123\001\002\000\046\002" +
"\ufffb\010\ufffb\012\ufffb\014\ufffb\015\ufffb\016\ufffb\017\ufffb" +
"\020\ufffb\021\ufffb\027\ufffb\032\ufffb\040\ufffb\043\ufffb\044" +
"\ufffb\045\ufffb\046\ufffb\047\ufffb\050\ufffb\001\002\000\040" +
"\010\022\012\030\014\020\015\024\016\012\017\013\020" +
"\023\021\004\032\026\043\005\044\007\045\017\046\010" +
"\047\027\050\036\001\002\000\036\004\050\005\053\006" +
"\044\007\041\013\126\022\047\030\046\031\051\033\045" +
"\034\042\035\052\036\054\037\040\041\043\001\002\000" +
"\042\004\uffec\005\uffec\006\uffec\007\uffec\011\uffec\013\uffec" +
"\022\uffec\030\uffec\031\uffec\033\uffec\034\uffec\035\uffec\036" +
"\uffec\037\uffec\041\uffec\042\uffec\001\002\000\040\010\022" +
"\012\030\014\020\015\024\016\012\017\013\020\023\021" +
"\004\032\026\043\005\044\007\045\017\046\010\047\027" +
"\050\036\001\002\000\036\004\050\005\053\006\044\007" +
"\041\013\131\022\047\030\046\031\051\033\045\034\042" +
"\035\052\036\054\037\040\041\043\001\002\000\042\004" +
"\uffed\005\uffed\006\uffed\007\uffed\011\uffed\013\uffed\022\uffed" +
"\030\uffed\031\uffed\033\uffed\034\uffed\035\uffed\036\uffed\037" +
"\uffed\041\uffed\042\uffed\001\002\000\004\011\133\001\002" +
"\000\046\002\ufff5\010\ufff5\012\ufff5\014\ufff5\015\ufff5\016" +
"\ufff5\017\ufff5\020\ufff5\021\ufff5\027\ufff5\032\ufff5\040\ufff5" +
"\043\ufff5\044\ufff5\045\ufff5\046\ufff5\047\ufff5\050\ufff5\001" +
"\002\000\004\011\135\001\002\000\046\002\ufff9\010\ufff9" +
"\012\ufff9\014\ufff9\015\ufff9\016\ufff9\017\ufff9\020\ufff9\021" +
"\ufff9\027\ufff9\032\ufff9\040\ufff9\043\ufff9\044\ufff9\045\ufff9" +
"\046\ufff9\047\ufff9\050\ufff9\001\002\000\040\010\022\012" +
"\030\014\020\015\024\016\012\017\013\020\023\021\004" +
"\032\026\043\005\044\007\045\017\046\010\047\027\050" +
"\036\001\002\000\036\004\050\005\053\006\044\007\041" +
"\013\140\022\047\030\046\031\051\033\045\034\042\035" +
"\052\036\054\037\040\041\043\001\002\000\042\004\uffea" +
"\005\uffea\006\uffea\007\uffea\011\uffea\013\uffea\022\uffea\030" +
"\uffea\031\uffea\033\uffea\034\uffea\035\uffea\036\uffea\037\uffea" +
"\041\uffea\042\uffea\001\002" });
/** Access to parse-action table. */
public short[][] action_table() {return _action_table;}
/** <code>reduce_goto</code> table. */
protected static final short[][] _reduce_table =
unpackFromStrings(new String[] {
"\000\136\000\012\002\024\003\014\004\013\005\005\001" +
"\001\000\002\001\001\000\002\001\001\000\004\010\133" +
"\001\001\000\002\001\001\000\002\001\001\000\004\012" +
"\131\001\001\000\002\001\001\000\002\001\001\000\004" +
"\007\121\001\001\000\002\001\001\000\004\011\117\001" +
"\001\000\002\001\001\000\002\001\001\000\004\006\112" +
"\001\001\000\004\004\111\001\001\000\002\001\001\000" +
"\002\001\001\000\010\003\102\004\013\005\005\001\001" +
"\000\004\004\100\001\001\000\002\001\001\000\004\004" +
"\076\001\001\000\002\001\001\000\004\004\075\001\001" +
"\000\004\004\074\001\001\000\004\004\073\001\001\000" +
"\004\004\036\001\001\000\002\001\001\000\002\001\001" +
"\000\004\004\072\001\001\000\004\004\071\001\001\000" +
"\004\004\070\001\001\000\004\004\065\001\001\000\004" +
"\004\064\001\001\000\004\004\063\001\001\000\004\004" +
"\062\001\001\000\004\004\061\001\001\000\004\004\060" +
"\001\001\000\004\004\057\001\001\000\004\004\056\001" +
"\001\000\004\004\055\001\001\000\004\004\054\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\002" +
"\001\001\000\002\001\001\000\002\001\001\000\002\001" +
"\001\000\004\004\067\001\001\000\002\001\001\000\002" +
"\001\001\000\002\001\001\000\002\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\004\004\104\001\001\000\002\001\001" +
"\000\002\001\001\000\004\004\107\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\004\004\115\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\004\004\124\001" +
"\001\000\002\001\001\000\002\001\001\000\004\004\127" +
"\001\001\000\002\001\001\000\002\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\004\004\136\001\001\000\002\001\001\000\002\001" +
"\001" });
/** Access to <code>reduce_goto</code> table. */
public short[][] reduce_table() {return _reduce_table;}
/** Instance of action encapsulation class. */
protected CUP$Parser$actions action_obj;
/** Action encapsulation object initializer. */
protected void init_actions()
{
action_obj = new CUP$Parser$actions(this);
}
/** Invoke a user supplied parse action. */
public java_cup.runtime.Symbol do_action(
int act_num,
java_cup.runtime.lr_parser parser,
java.util.Stack stack,
int top)
throws java.lang.Exception
{
/* call code in generated class */
return action_obj.CUP$Parser$do_action(act_num, parser, stack, top);
}
/** Indicates start state. */
public int start_state() {return 0;}
/** Indicates start production. */
public int start_production() {return 0;}
/** <code>EOF</code> Symbol index. */
public int EOF_sym() {return 0;}
/** <code>error</code> Symbol index. */
public int error_sym() {return 1;}
/** User initialization code. */
public void user_init() throws java.lang.Exception
{
//varMap.put("true", 1.0d);
//varMap.put("false", 0.0d);
}
public static void main(String args[]) throws Exception {
new Parser(new Lexer(new InputStreamReader(System.in))).parse();
}
}
/** Cup generated class to encapsulate user supplied action code.*/
class CUP$Parser$actions {
Map<String,Double> varMap = new HashMap<String,Double>();
static String TRUE = new String("true");
static String FALSE = new String("false");
static double ONE = 1.0d;
static double ZERO = 0.0d;
private final Parser parser;
/** Constructor */
CUP$Parser$actions(Parser parser) {
this.parser = parser;
}
/** Method with the actual generated action code. */
public final java_cup.runtime.Symbol CUP$Parser$do_action(
int CUP$Parser$act_num,
java_cup.runtime.lr_parser CUP$Parser$parser,
java.util.Stack CUP$Parser$stack,
int CUP$Parser$top)
throws java.lang.Exception
{
/* Symbol object for return from actions */
java_cup.runtime.Symbol CUP$Parser$result;
/* select the action based on the action number */
switch (CUP$Parser$act_num)
{
/*. . . . . . . . . . . . . . . . . . . .*/
case 44: // assignation ::= TK_ID TK_ASSIGNMULT expression
{
String RESULT =null;
int xleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int xright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
String x = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
double initialValue = varMap.get(x);
varMap.put(x, initialValue * e1);
RESULT = x + " = " + (initialValue * e1);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("assignation",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 43: // assignation ::= TK_ID TK_ASSIGNMINUS expression
{
String RESULT =null;
int xleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int xright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
String x = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
double initialValue = varMap.get(x);
varMap.put(x, initialValue - e1);
RESULT = x + " = " + (initialValue - e1);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("assignation",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 42: // assignation ::= TK_ID TK_ASSIGNPLUS expression
{
String RESULT =null;
int xleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int xright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
String x = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
double initialValue = varMap.get(x);
varMap.put(x, initialValue + e1);
RESULT = x + " = " + (initialValue + e1);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("assignation",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 41: // assignation ::= TK_ID TK_ASSIGN expression
{
String RESULT =null;
int xleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int xright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
String x = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
varMap.put(x, e1);
RESULT = x + " = " + e1 ;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("assignation",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 40: // expression ::= TK_INF
{
Double RESULT =null;
RESULT = Double.POSITIVE_INFINITY;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 39: // expression ::= TK_NAN
{
Double RESULT =null;
RESULT = Double.NaN;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 38: // expression ::= expression TK_CONDI expression TK_CONDI2 expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-4)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e3left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e3right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e3 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if(e1.equals(1.0)) {
RESULT = e2;
} else {
RESULT = e3;
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 37: // expression ::= expression TK_EQUAL expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if(e1.equals(e2)) {
RESULT = 1.0;
} else {
RESULT = 0.0;
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 36: // expression ::= expression TK_LOWEQ expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if(e1 <= e2) {
RESULT = 1.0;
} else {
RESULT = 0.0;
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 35: // expression ::= expression TK_LOW expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if(e1 < e2) {
RESULT = 1.0;
} else {
RESULT = 0.0;
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 34: // expression ::= expression TK_SUPEQ expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if(e1 >= e2) {
RESULT = 1.0;
} else {
RESULT = 0.0;
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 33: // expression ::= expression TK_SUP expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if(e1 > e2) {
RESULT = 1.0;
} else {
RESULT = 0.0;
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 32: // expression ::= TK_NOT expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if(e1==1){
RESULT = 0.0;
} else {
RESULT = 1.0;
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 31: // expression ::= expression TK_OR expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if(e1==1 || e2==1){
RESULT = 1.0;
} else {
RESULT = 0.0;
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 30: // expression ::= expression TK_AND expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if(e1==1.0 && e2==1.0){
RESULT = 1.0;
} else {
RESULT = 0.0;
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 29: // expression ::= TK_E
{
Double RESULT =null;
RESULT = Math.E;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 28: // expression ::= TK_PI
{
Double RESULT =null;
RESULT = Math.PI;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 27: // expression ::= TK_ID
{
Double RESULT =null;
int xleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int xright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
String x = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if(varMap.containsKey(x)){
RESULT = varMap.get(x) ;
} else {
System.out.println("# " + x + " n'est pas défini");
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 26: // expression ::= TK_VAL
{
Double RESULT =null;
int vleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int vright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double v = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = v;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 25: // expression ::= TK_OPBRA expression TK_CLBRA
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = e1 ;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 24: // expression ::= expression TK_POW expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Math.pow(e1,e2);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 23: // expression ::= TK_EXP TK_OPBRA expression TK_CLBRA
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = Math.exp(e1);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 22: // expression ::= TK_LN TK_OPBRA expression TK_CLBRA
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = Math.log(e1);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 21: // expression ::= TK_SQRT TK_OPBRA expression TK_CLBRA
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = Math.sqrt(e1);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 20: // expression ::= TK_TAN TK_OPBRA expression TK_CLBRA
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = Math.tan(e1);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 19: // expression ::= TK_COS TK_OPBRA expression TK_CLBRA
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = Math.cos(e1);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 18: // expression ::= TK_SIN TK_OPBRA expression TK_CLBRA
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = Math.sin(e1);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 17: // expression ::= TK_UMINUS expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = -e1 ;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 16: // expression ::= expression TK_DIV expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = e1 / e2 ;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 15: // expression ::= expression TK_MULT expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = e1 * e2 ;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 14: // expression ::= expression TK_MINUS expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = e1 - e2 ;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 13: // expression ::= expression TK_PLUS expression
{
Double RESULT =null;
int e1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int e1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e1 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
int e2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int e2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e2 = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = e1 + e2 ;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expression",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 12: // commande ::= TK_EXIT NT$4 TK_DONE
{
Object RESULT =null;
// propagate RESULT from NT$4
RESULT = (Object) ((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("commande",1, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 11: // NT$4 ::=
{
Object RESULT =null;
System.exit(0);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("NT$4",8, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 10: // commande ::= TK_ALLVAR NT$3 TK_DONE
{
Object RESULT =null;
// propagate RESULT from NT$3
RESULT = (Object) ((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("commande",1, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 9: // NT$3 ::=
{
Object RESULT =null;
long i=0;
Iterator<Map.Entry<String,Double>> it = varMap.entrySet().iterator();
if(!it.hasNext()){
System.out.println("Aucune variable définie");
}
while(it.hasNext()){
Map.Entry<String,Double> pair = it.next();
System.out.println("# " + pair.getKey() + " = " + pair.getValue());
}
CUP$Parser$result = parser.getSymbolFactory().newSymbol("NT$3",7, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 8: // commande ::= assignation NT$2 TK_DONE
{
Object RESULT =null;
// propagate RESULT from NT$2
RESULT = (Object) ((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
int aleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int aright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
String a = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("commande",1, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 7: // NT$2 ::=
{
Object RESULT =null;
int aleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int aright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
String a = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
System.out.println("# " + a);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("NT$2",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 6: // commande ::= expression NT$1 TK_DONE
{
Object RESULT =null;
// propagate RESULT from NT$1
RESULT = (Object) ((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
int eleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left;
int eright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right;
Double e = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("commande",1, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 5: // NT$1 ::=
{
Object RESULT =null;
int eleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left;
int eright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right;
Double e = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
System.out.println("# " + e);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("NT$1",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 4: // commandes ::= error NT$0 TK_DONE
{
Object RESULT =null;
// propagate RESULT from NT$0
RESULT = (Object) ((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("commandes",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 3: // NT$0 ::=
{
Object RESULT =null;
System.out.println("Expression incorrecte");
CUP$Parser$result = parser.getSymbolFactory().newSymbol("NT$0",4, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 2: // commandes ::= commandes commande
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("commandes",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 1: // commandes ::= commande
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("commandes",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 0: // $START ::= commandes EOF
{
Object RESULT =null;
int start_valleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left;
int start_valright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right;
Object start_val = (Object)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = start_val;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
/* ACCEPT */
CUP$Parser$parser.done_parsing();
return CUP$Parser$result;
/* . . . . . .*/
default:
throw new Exception(
"Invalid action number found in internal parse table");
}
}
}
| true |
c22aa8f4e662da312398f896ebb6e0855abb7c35 | Java | Eire0101/jxc | /src/main/java/com/i/service/SlmService.java | UTF-8 | 318 | 1.65625 | 2 | [] | no_license | package com.i.service;
import com.github.pagehelper.PageInfo;
import com.i.entity.Slm;
public interface SlmService {
public Integer getSlmCount();
public PageInfo selAllSlm(PageInfo pageInfo);
public void addSlm(Slm slm);
public void delSlm(Integer slmid);
public void updateSlm(Slm slm);
}
| true |
b6cdc04795370d721b2adadcad5e1e84cedb2510 | Java | AAbdel92/Projet-Final | /src/main/java/fr/laposte/simplon/controllers/DiaryController.java | UTF-8 | 2,212 | 2.171875 | 2 | [] | no_license | package fr.laposte.simplon.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import fr.laposte.simplon.models.Diary;
import fr.laposte.simplon.models.User;
import fr.laposte.simplon.services.DiaryService;
//@CrossOrigin("http://localhost:3000")
@RestController
@RequestMapping("api/diaries")
public class DiaryController {
@Autowired
private DiaryService service;
//@Formateur
@PostMapping
public Diary saveOne(@RequestBody Diary diary) {
return service.saveOne(diary);
}
//@Formateur, @Tuteur, @Apprenant
@GetMapping
public List<Diary> getAll(@RequestParam Optional<Boolean> consulter,
@RequestParam String userRole,
@RequestParam int promoId,
@RequestParam Optional<Integer> studentId,
@RequestParam Optional<Boolean> questions){
List<Diary> result = new ArrayList<>();
if (consulter.isPresent()) {
if ("formateur".equals(userRole)) {
result = service.getForReading(promoId);
} else if (studentId.isPresent()){
result = service.getForReading(promoId, studentId.get());
}
} else if ("formateur".equals(userRole) && questions.isPresent()){
result = service.getDiariesWithQuestionsByPromo(promoId);
} else if ("formateur".equals(userRole)) {
result = service.getNewDiariesByPromo(promoId);
} else if (studentId.isPresent()){
result = service.getDiariesToEditByStudentId(userRole, promoId, studentId.get());
}
return result;
}
//@Formateur, @Tuteur, @Apprenant
// @GetMapping
// public List<Diary> getAll(@RequestParam String userRole, @RequestParam int userId) {
// return service.getAll(userRole, userId);
// }
}
| true |
34a2c2b855d8cd7e4bca89e9610f2d56c24dd4da | Java | chiragjog/CloudStack | /utils/src/com/cloud/utils/db/ConnectionConcierge.java | UTF-8 | 7,917 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.utils.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.management.StandardMBean;
import org.apache.log4j.Logger;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.mgmt.JmxUtil;
/**
* ConnectionConcierge keeps stand alone database connections alive. This is
* useful when the code needs to keep a database connection for itself and
* needs someone to keep that database connection from being garbage collected
* because the connection has been idled for a long time.
*
* ConnectionConierge also has JMX hooks to allow for connections to be reset
* and validated on a live system so using it means you don't need to implement
* your own.
*/
public class ConnectionConcierge {
static final Logger s_logger = Logger.getLogger(ConnectionConcierge.class);
static final ConnectionConciergeManager s_mgr = new ConnectionConciergeManager();
Connection _conn;
String _name;
boolean _keepAlive;
boolean _autoCommit;
int _isolationLevel;
int _holdability;
public ConnectionConcierge(String name, Connection conn, boolean keepAlive) {
_name = name + s_mgr.getNextId();
_keepAlive = keepAlive;
try {
_autoCommit = conn.getAutoCommit();
_isolationLevel = conn.getTransactionIsolation();
_holdability = conn.getHoldability();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to get information from the connection object", e);
}
reset(conn);
}
public void reset(Connection conn) {
try {
release();
} catch (Throwable th) {
s_logger.error("Unable to release a connection", th);
}
_conn = conn;
try {
_conn.setAutoCommit(_autoCommit);
_conn.setHoldability(_holdability);
_conn.setTransactionIsolation(_isolationLevel);
} catch (SQLException e) {
s_logger.error("Unable to release a connection", e);
}
s_mgr.register(_name, this);
s_logger.debug("Registering a database connection for " + _name);
}
public final Connection conn() {
return _conn;
}
public void release() {
s_mgr.unregister(_name);
try {
if (_conn != null) {
_conn.close();
}
_conn = null;
} catch (SQLException e) {
throw new CloudRuntimeException("Problem in closing a connection", e);
}
}
@Override
protected void finalize() throws Exception {
if (_conn != null) {
release();
}
}
public boolean keepAlive() {
return _keepAlive;
}
protected static class ConnectionConciergeManager extends StandardMBean implements ConnectionConciergeMBean {
ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ConnectionKeeper"));
final ConcurrentHashMap<String, ConnectionConcierge> _conns = new ConcurrentHashMap<String, ConnectionConcierge>();
final AtomicInteger _idGenerator = new AtomicInteger();
ConnectionConciergeManager() {
super(ConnectionConciergeMBean.class, false);
resetKeepAliveTask(20);
try {
JmxUtil.registerMBean("DB Connections", "DB Connections", this);
} catch (Exception e) {
s_logger.error("Unable to register mbean", e);
}
}
public Integer getNextId() {
return _idGenerator.incrementAndGet();
}
public void register(String name, ConnectionConcierge concierge) {
_conns.put(name, concierge);
}
public void unregister(String name) {
_conns.remove(name);
}
protected String testValidity(String name, Connection conn) {
PreparedStatement pstmt = null;
try {
if (conn != null) {
pstmt = conn.prepareStatement("SELECT 1");
pstmt.executeQuery();
}
return null;
} catch (Throwable th) {
s_logger.error("Unable to keep the db connection for " + name, th);
return th.toString();
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
}
}
}
}
@Override
public List<String> testValidityOfConnections() {
ArrayList<String> results = new ArrayList<String>(_conns.size());
for (Map.Entry<String, ConnectionConcierge> entry : _conns.entrySet()) {
String result = testValidity(entry.getKey(), entry.getValue().conn());
results.add(entry.getKey() + "=" + (result == null ? "OK" : result));
}
return results;
}
@Override
public String resetConnection(String name) {
ConnectionConcierge concierge = _conns.get(name);
if (concierge == null) {
return "Not Found";
}
Connection conn = Transaction.getStandaloneConnection();
if (conn == null) {
return "Unable to get anotehr db connection";
}
concierge.reset(conn);
return "Done";
}
@Override
public String resetKeepAliveTask(int seconds) {
if (_executor != null) {
try {
_executor.shutdown();
} catch(Exception e) {
s_logger.error("Unable to shutdown executor", e);
}
}
_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ConnectionConcierge"));
_executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
s_logger.trace("connection concierge keep alive task");
for (Map.Entry<String, ConnectionConcierge> entry : _conns.entrySet()) {
ConnectionConcierge concierge = entry.getValue();
if (concierge.keepAlive()) {
testValidity(entry.getKey(), entry.getValue().conn());
}
}
}
}, 0, seconds, TimeUnit.SECONDS);
return "As you wish.";
}
@Override
public List<String> getConnectionsNotPooled() {
return new ArrayList<String>(_conns.keySet());
}
}
}
| true |
47cc1d3510e46bec48bdedb723d41673e22bbab8 | Java | jhayfelix/Bunny-Hop-Developers-Procurement-System | /src/main/java/procurementsys/controller/AddProductController.java | UTF-8 | 1,684 | 3.046875 | 3 | [] | no_license | package procurementsys.controller;
import java.util.Optional;
import procurementsys.model.Product;
import procurementsys.model.database.MySQLProductDAO;
import procurementsys.model.database.ProductDAO;
import procurementsys.view.SoftwareNotification;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextInputDialog;
/**
* @author Jan Tristan Milan
*/
public class AddProductController extends Controller {
public static void run() {
TextInputDialog dialog = new TextInputDialog();
dialog.setTitle("Add Product");
dialog.setHeaderText("Enter Product Details");
dialog.setContentText("Product name:");
dialog.setGraphic(null);
final Button btOk = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK);
btOk.addEventFilter(ActionEvent.ACTION, event -> {
if (!isValidName(dialog.getEditor().getText())) {
String errorMsg = "Product name cannot be empty."
+ " Please enter a product name.";
SoftwareNotification.notifyError(errorMsg);
event.consume();
}
});
Optional<String> name = dialog.showAndWait();
if (name.isPresent()){
ProductDAO productDAO = new MySQLProductDAO();
productDAO.add(new Product(name.get()));
String successMsg = "The product \'" + name.get()
+ "\' has been successfully added to the system.";
SoftwareNotification.notifySuccess(successMsg);
}
}
private static boolean isValidName(String name) {
if (name == null || name.length() == 0) {
return false;
}
return true;
}
}
| true |
4a41bfbd64af20e4286c52f65f4bfb8df7d58e94 | Java | DylanWang2020/PolymPic | /ActivityLauncher/src/main/java/com/knziha/polymer/browser/webkit/XWalkMainActivity.java | UTF-8 | 1,387 | 2.140625 | 2 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | package com.knziha.polymer.browser.webkit;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.ViewGroup;
import com.knziha.polymer.R;
import org.xwalk.core.XWalkActivityDelegate;
import org.xwalk.core.XWalkView;
/** Deprecated. Use XWalkActivityDelegate in your Activity directly. */
@Deprecated
public class XWalkMainActivity extends Activity {
private XWalkView mXWalkView;
private ViewGroup root;
private XWalkActivityDelegate mActivityDelegate;
protected void onXWalkReady() {
mXWalkView = new XWalkView(this);
root.addView(mXWalkView);
mXWalkView.load("http://www.baidu.com/", null);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root = findViewById(R.id.root);
Runnable cancelCommand = new Runnable() {
public void run() {
finish();
}
};
Runnable completeCommand = new Runnable() {
public void run() {
onXWalkReady();
}
};
this.mActivityDelegate = new XWalkActivityDelegate(this, cancelCommand, completeCommand);
}
protected void onResume() {
super.onResume();
this.mActivityDelegate.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
}
| true |
89e2c11e0e80914ed71cb4a27263f91169726eb5 | Java | apache/lenya | /org.apache.lenya.core.administration/src/main/java/org/apache/lenya/cms/ac/usecases/AddGroup.java | UTF-8 | 2,443 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.lenya.cms.ac.usecases;
import org.apache.lenya.ac.Group;
import org.apache.lenya.ac.ItemUtil;
import org.apache.lenya.cms.usecase.UsecaseException;
/**
* Usecase to add a group.
*
* @version $Id: AddGroup.java 407305 2006-05-17 16:21:49Z andreas $
*/
public class AddGroup extends AccessControlUsecase {
/**
* @see org.apache.lenya.cms.usecase.AbstractUsecase#doCheckExecutionConditions()
*/
protected void doCheckExecutionConditions() throws Exception {
validate();
}
/**
* Validates the request parameters.
* @throws UsecaseException if an error occurs.
*/
void validate() throws UsecaseException {
String groupId = getParameterAsString(GroupProfile.ID);
Group existingGroup = getGroupManager().getGroup(groupId);
if (existingGroup != null) {
addErrorMessage("This group already exists.");
}
if (!ItemUtil.isValidId(groupId)) {
addErrorMessage("This is not a valid group ID.");
}
}
/**
* @see org.apache.lenya.cms.usecase.AbstractUsecase#doExecute()
*/
protected void doExecute() throws Exception {
super.doExecute();
String id = getParameterAsString(GroupProfile.ID);
String name = getParameterAsString(GroupProfile.NAME);
String description = getParameterAsString(GroupProfile.DESCRIPTION);
Group group = getGroupManager().add(id);
group.setName(name);
group.setDescription(description);
group.save();
setExitParameter(GroupProfile.ID, id);
}
} | true |
272c42302f4e030090b3f2e76746edc6a5a2f7db | Java | sonhoang1809/Hana-Shop | /Lab2-HanaShop-SE130448/src/java/com/sample/hanashop/controllers/LoadUserDetailsController.java | UTF-8 | 3,753 | 2.125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sample.hanashop.controllers;
import com.sample.hanashop.daos.RoleDAO;
import com.sample.hanashop.daos.UserDAO;
import com.sample.hanashop.dtos.RoleDTO;
import com.sample.hanashop.dtos.UserDTO;
import com.sample.hanashop.mails.SendMailSSL;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
/**
*
* @author sonho
*/
public class LoadUserDetailsController extends HttpServlet {
private final String SUCCESS = "user-details.jsp";
private final String ERROR = "SearchController";
private static final Logger log = Logger.getLogger(LoadUserDetailsController.class.getName());
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String url = ERROR;
try {
HttpSession session = request.getSession();
String userID = request.getParameter("userID");
UserDTO userDTO = UserDAO.getFullUserDetail(userID);
UserDTO userCurr = (UserDTO) session.getAttribute("USERDTO");
if (userCurr.getRoleID().equalsIgnoreCase("AD")) {
List<RoleDTO> listRole = RoleDAO.getAllRole();
request.setAttribute("ListRole", listRole);
}
request.setAttribute("UserDetails", userDTO);
url = SUCCESS;
} catch (Exception ex) {
log.error("Error at LoadUserDetailsController: " + ex.toString());
SendMailSSL.sendToAdmin("Error at LoadUserDetailsController: " + ex.toString(), "Error!!");
} finally {
request.getRequestDispatcher(url).forward(request, response);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| true |
07e84acf41e1d17c3ed3b64da93c7f3106d2f0e0 | Java | leeedanny1/java_Study | /workspace/abstract_ex/src/ch04/Zergling.java | UHC | 186 | 2.703125 | 3 | [] | no_license | package ch04;
public class Zergling extends Unit {
//
// ݷ5, ü100
public Zergling(String name) {
this.name = name;
this.power = 5;
this.hp = 100;
}
}
| true |
d405cbb330fa33643c3667134893a4125efaf049 | Java | boggdan95/HojaDeTrabajo-1 | /HojaDeTrabajo-1/src/radioBBP.java | UTF-8 | 3,413 | 3.140625 | 3 | [] | no_license |
/**
* @author Boggdan Barrientos, Bryan Chan, Pablo Arriola
*
*/
public class radioBBP implements radio {
private int volumenActual = 0;
private double emisoraActual = 87.9;
private String frecuenciaActual = "FM";
private boolean estadoActual = false;
private double[] ams = new double[12];
private double[] fms = new double[12];
/*
* @see radio#encenderApagar()
* este va a ser el metodo que se va a utlizar para encender la radio si esta prendida se apaga si esta apagada se enciende
*/
@Override
public boolean encenderApagar() {
// TODO Auto-generated method stub
if(estadoActual==true){
estadoActual = false;
} else {
estadoActual = true;
}
return estadoActual;
}
/*
* @see radio#cambiarFrecuencia()
* va a ser mi metodo para cambiar de frecuencia si es esta en am va a pasar a fm. Cada una tiene su frecuencia inicial que se acordo en clase
*/
@Override
public String cambiarFrecuencia() {
// TODO Auto-generated method stub
if(frecuenciaActual=="FM"){
frecuenciaActual = "AM";
emisoraActual = 530;
} else {
frecuenciaActual = "FM";
emisoraActual = 87.9;
}
return frecuenciaActual;
}
/*
* @see radio#cambiarEmisora()
* este me va a servir para cambiar de emisora, seleccionando un boton
*/
@Override
public double cargarEmisora(int posicion) {
// TODO Auto-generated method stub
if(frecuenciaActual=="FM"){
return fms[posicion-1];
} else {
return ams[posicion-1];
}
}
/*
* @see radio#adelantarEmisora()
* este es mi metodo para adelantar de la emisora se le va a sumar a la emisora actual una constante dependiendo de si es am o fm
*/
@Override
public double adelantarEmisora() {
// TODO Auto-generated method stub
if(frecuenciaActual=="FM"){
if(emisoraActual<107.9){
emisoraActual = emisoraActual + 0.2;
}
} else {
if(emisoraActual<1610){
emisoraActual = emisoraActual + 10;
}
}
return (double)Math.round(emisoraActual * 10) / 10;
}
/*
* @see radio#retrocederEmisora()
* es el mismo que para adelantar la emisora pero ahora se resta en vez de sumar
*/
@Override
public double retrocederEmisora() {
// TODO Auto-generated method stub
if(frecuenciaActual=="FM"){
if(emisoraActual>87.9){
emisoraActual = emisoraActual - 0.2;
}
} else {
if(emisoraActual>530){
emisoraActual = emisoraActual - 10;
}
}
return (double)Math.round(emisoraActual * 10) / 10;
}
/*
* @see radio#guardarEmisora()
* sirve para guardar la estacion actual en una emisora
*/
@Override
public double guardarEmisora(double emisora, int posicion) {
// TODO Auto-generated method stub
if(frecuenciaActual=="FM"){
fms[posicion] = emisora;
} else {
ams[posicion] = emisora;
}
return emisora;
}
/*
* @see radio#subirVolumen()
* sirve para subir de volumen no puede pasar de 100
*/
@Override
public int subirVolumen() {
// TODO Auto-generated method stub
if(volumenActual!=100){
volumenActual++;
}
return volumenActual;
}
/*
* @see radio#bajarVolumen()
* sirve para bajar de volumen y el minimo es 0
*/
@Override
public int bajarVolumen() {
// TODO Auto-generated method stub
if(volumenActual!=0){
volumenActual--;
}
return volumenActual;
}
}
| true |
75a09b0b351a6b189797ae77255a3694d45a3691 | Java | BernardoGrigiastro/IBE-Editor | /ibeeditor/base/src/main/java/com/github/franckyi/ibeeditor/base/client/mvc/model/entry/StringEntryModel.java | UTF-8 | 544 | 2.390625 | 2 | [
"MIT"
] | permissive | package com.github.franckyi.ibeeditor.base.client.mvc.model.entry;
import com.github.franckyi.gameadapter.api.common.text.IText;
import com.github.franckyi.ibeeditor.base.client.mvc.model.CategoryModel;
import java.util.function.Consumer;
public class StringEntryModel extends ValueEntryModel<String> {
public StringEntryModel(CategoryModel category, IText label, String value, Consumer<String> action) {
super(category, label, value, action);
}
@Override
public Type getType() {
return Type.STRING;
}
}
| true |
c04c081846773e3e505341037073a042743cb6e4 | Java | luisfilipels/Interview-Preparation | /LeetCode/TargetSum.java | UTF-8 | 1,472 | 3.546875 | 4 | [] | no_license | package Extras.LeetCode;
import java.util.Arrays;
public class TargetSum {
private static int findTargetSumWays (int [] nums, int S) {
int [][] dp = new int[nums.length][2001]; // 0 a 1000 -> somas negativas. 1001 a 2001 -> somas positivas
for (int [] row : dp) {
Arrays.fill(row, Integer.MIN_VALUE);
}
return helper(nums, S, 0, 0, dp);
}
private static int helper (int [] nums, int S, int currentIndex, int currentSum, int[][] dp) {
if (currentIndex == nums.length-1 && (currentSum + nums[currentIndex] == S || currentSum - nums[currentIndex] == S)) {
if (nums[currentIndex] == 0) {
return 2;
}
return 1;
} else if (currentIndex == nums.length-1 && (currentSum + nums[currentIndex] != S || currentSum - nums[currentIndex] != S)) {
return 0;
} else {
if (dp[currentIndex][currentSum + 1000] != Integer.MIN_VALUE) {
return dp[currentIndex][currentSum + 1000];
}
dp[currentIndex][currentSum + 1000] = helper(nums, S, currentIndex+1, currentSum + nums[currentIndex], dp) + helper(nums, S, currentIndex+1, currentSum - nums[currentIndex], dp);
return dp[currentIndex][currentSum+1000];
}
}
public static void main(String[] args) {
int [] input = new int[] {1, 1, 1, 1, 1};
System.out.println(findTargetSumWays(input, 3));
}
}
| true |
c065c3b24ffec32dea1d8190782e588e937acda7 | Java | gwtproject/gwt | /dev/core/src/com/google/gwt/dev/javac/CompilationUnitImpl.java | UTF-8 | 3,715 | 1.734375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.dev.javac;
import com.google.gwt.dev.jjs.ast.JDeclaredType;
import com.google.gwt.dev.jjs.ast.JProgram;
import com.google.gwt.dev.util.collect.Lists;
import com.google.gwt.thirdparty.guava.common.base.Predicate;
import com.google.gwt.thirdparty.guava.common.collect.Iterables;
import org.eclipse.jdt.core.compiler.CategorizedProblem;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.List;
abstract class CompilationUnitImpl extends CompilationUnit {
/**
* Handle to serialized GWT AST.
*/
protected transient long astToken;
private final Dependencies dependencies;
private final List<CompiledClass> exposedCompiledClasses;
private final boolean hasErrors;
private final boolean hasJsInteropRootType;
private final List<JsniMethod> jsniMethods;
private final MethodArgNamesLookup methodArgs;
private final CategorizedProblem[] problems;
public CompilationUnitImpl(List<CompiledClass> compiledClasses,
List<JDeclaredType> types, Dependencies dependencies,
Collection<? extends JsniMethod> jsniMethods,
MethodArgNamesLookup methodArgs, CategorizedProblem[] problems) {
this.exposedCompiledClasses = Lists.normalizeUnmodifiable(compiledClasses);
this.dependencies = dependencies;
this.jsniMethods = Lists.create(jsniMethods.toArray(new JsniMethod[jsniMethods.size()]));
this.methodArgs = methodArgs;
this.problems = problems;
boolean hasAnyErrors = false;
if (problems != null) {
for (CategorizedProblem problem : problems) {
if (problem.isError()) {
hasAnyErrors = true;
}
}
}
this.hasErrors = hasAnyErrors;
this.hasJsInteropRootType = Iterables.any(types, new Predicate<JDeclaredType>() {
@Override public boolean apply(JDeclaredType type) {
return type.hasJsInteropEntryPoints();
}
});
for (CompiledClass cc : compiledClasses) {
cc.initUnit(this);
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
JProgram.serializeTypes(types, out);
out.close();
astToken = diskCache.writeByteArray(baos.toByteArray());
} catch (IOException e) {
throw new RuntimeException("Unexpected IOException on in-memory stream",
e);
}
}
@Override
public Collection<CompiledClass> getCompiledClasses() {
return exposedCompiledClasses;
}
@Override
public List<JsniMethod> getJsniMethods() {
return jsniMethods;
}
@Override
public MethodArgNamesLookup getMethodArgs() {
return methodArgs;
}
@Override
public byte[] getTypesSerialized() {
return diskCache.readByteArray(astToken);
}
@Override
public boolean isError() {
return hasErrors;
}
@Override
boolean hasJsInteropRootType() {
return hasJsInteropRootType;
}
@Override
Dependencies getDependencies() {
return dependencies;
}
@Override
CategorizedProblem[] getProblems() {
return problems;
}
} | true |
d0f5c46e49e7333dd7ced525b711146937b8168f | Java | nodwengu/schoolApp | /src/main/java/net/school/schoolApp/service/LessonService.java | UTF-8 | 2,798 | 2.421875 | 2 | [] | no_license | package net.school.schoolApp.service;
import lombok.RequiredArgsConstructor;
import net.school.schoolApp.entity.Day;
import net.school.schoolApp.entity.Grade;
import net.school.schoolApp.entity.Lesson;
import net.school.schoolApp.entity.Subject;
import net.school.schoolApp.repository.DayRepository;
import net.school.schoolApp.repository.GradeRepository;
import net.school.schoolApp.repository.LessonRepository;
import net.school.schoolApp.repository.SubjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class LessonService {
@Autowired
private LessonRepository lessonRepository;
@Autowired
private SubjectRepository subjectRepository;
@Autowired
private GradeRepository gradeRepository;
@Autowired
private DayRepository dayRepository;
public Lesson addLesson(Long subjectId, Long gradeId, Long dayId, Lesson lesson) {
Optional<Subject> optionalSubject = subjectRepository.findById(subjectId);
Optional<Grade> optionalGrade = gradeRepository.findById(gradeId);
Optional<Day> optionalDay = dayRepository.findById(dayId);
lesson.setSubject(optionalSubject.get());
lesson.setGrade(optionalGrade.get());
lesson.setDay(optionalDay.get());
return lessonRepository.save(lesson);
}
public List<Lesson> getAllLessons() {
return lessonRepository.findAll();
}
public Lesson getLessonById(Long id) {
return lessonRepository.findById(id).orElse(null);
}
public Lesson updateLesson(Lesson lesson) {
Lesson existingLesson = lessonRepository.findById(lesson.getId()).orElse(null);
existingLesson.setLessonName(lesson.getLessonName());
existingLesson.setTime(lesson.getTime());
return lessonRepository.save(existingLesson);
}
public String deleteLesson(Long id) {
lessonRepository.deleteById(id);
return "removed lesson with ID: " + id;
}
// public Lesson addLessonSubject(Long subjectId, Lesson lesson) {
// Optional<Subject> optionalSubject = subjectRepository.findById(subjectId);
// lesson.setSubject(optionalSubject.get());
//
// return lessonRepository.save(lesson);
// }
// public Lesson addLessonGrade(Long gradeId, Lesson lesson) {
// Optional<Grade> optionalGrade = gradeRepository.findById(gradeId);
// lesson.setGrade(optionalGrade.get());
// return lessonRepository.save(lesson);
// }
// public Lesson addLessonDay(Long dayId, Lesson lesson) {
// Optional<Day> optionalDay = dayRepository.findById(dayId);
// lesson.setDay(optionalDay.get());
// return lessonRepository.save(lesson);
// }
}
| true |
8545794ca4a3f9838786a533b286f6205ba48cac | Java | nkrusch/SpaceLaunchOne | /SpaceLaunchOne/datasrc/src/main/java/api/ILaunchLibrary.java | UTF-8 | 1,888 | 2.734375 | 3 | [
"MIT"
] | permissive | package api;
import models.LaunchDetailed;
import models.LaunchListDetailed;
import models.data.BuildConfig;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Define the Launch Library API methods callable from the app.
* <p>
* See <a href="https://thespacedevs.com/llapi">Launch Library 2 API</a> for documentation.
* </p>
*/
interface ILaunchLibrary {
/**
* Get list of launches whose launch date is greater than history start date.
* This enables fetching future and past launches, independent of current datetime.
*
* @param offset The initial index from which to return the results.
* @return List of launches.
*/
@GET("launch?format=json&mode=list&ordering=-net&mode=detailed&" +
"limit=" + BuildConfig.PageSize + "&net__gt=" + BuildConfig.HistoryStartDate)
Call<LaunchListDetailed> all_launches(@Query("offset") int offset);
/**
* Get a list of future launches, occurring after current datetime.
*
* @param limit Number of results to return per page.
* @return List of launches.
*/
@GET("launch/upcoming/?format=json&offset=0&ordering=net&mode=detailed")
Call<LaunchListDetailed> upcoming_launches(@Query("limit") int limit);
/**
* Get a list of past launches that occurred before current datetime.
*
* @param limit Number of results to return per page.
* @return List of launches.
*/
@GET("launch/previous/?format=json&offset=0&ordering=-net&mode=detailed")
Call<LaunchListDetailed> past_launches(@Query("limit") int limit);
/**
* Get details of a specified single launch.
*
* @param id Launch id.
* @return Details of launch event.
*/
@GET("launch/{id}?format=json&mode=detailed")
Call<LaunchDetailed> launch(@Path("id") String id);
}
| true |
86f5d4a3847853e5af1bc959e5c998ce5a3c8788 | Java | pepinpin/microMorse | /app/src/main/java/net/biospherecorp/umorse/FlashLight_Pre_Marshmallow.java | UTF-8 | 1,424 | 2.640625 | 3 | [] | no_license | package net.biospherecorp.umorse;
import android.hardware.Camera;
// To deal with devices before API 23 (Marshmallow)
class FlashLight_Pre_Marshmallow implements MorseLight.FlashLight {
// deprecated but used
// on devices before API 23 (Marshmallow)
private Camera _camera;
private Camera.Parameters _parameters;
@Override
public void open() {
L.i("FlashLight_Pre_Marshmallow", ">>>> open()");
// if the camera is not already opened
if (_camera == null){
try {
// open it
_camera = Camera.open();
}catch (RuntimeException e){
e.printStackTrace();
}
}
}
// releases the camera and resets the
// camera & parameters fields to null
@Override
public void release(){
if (_camera != null){
_camera.release();
_camera = null;
_parameters = null;
}
}
// turn the light ON
@Override
public void on(){
// if light is off and there is a camera object
if(_camera != null){
_parameters = _camera.getParameters();
_parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
_camera.setParameters(_parameters);
_camera.startPreview();
}
}
// turn the light OFF
@Override
public void off(){
// if light is on and there is a camera object
if (_camera != null){
_parameters = _camera.getParameters();
_parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
_camera.setParameters(_parameters);
_camera.stopPreview();
}
}
}
| true |
34962412a31bd9e376095309d3515641c263b1f5 | Java | leeleekaen/GankPro | /app/src/main/java/com/freedom/lauzy/gankpro/ui/fragment/OpenLibsFragment.java | UTF-8 | 3,529 | 1.992188 | 2 | [] | no_license | package com.freedom.lauzy.gankpro.ui.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.freedom.lauzy.gankpro.R;
import com.freedom.lauzy.gankpro.common.base.BaseFragment;
import com.freedom.lauzy.gankpro.function.MineTitleListener;
import com.freedom.lauzy.gankpro.function.entity.LibEntity;
import com.freedom.lauzy.gankpro.function.view.AndroidItemDecoration;
import com.freedom.lauzy.gankpro.model.LibsModel;
import com.freedom.lauzy.gankpro.ui.activity.LibsGithubActivity;
import com.freedom.lauzy.gankpro.ui.adapter.OpenLibsAdapter;
import butterknife.BindView;
public class OpenLibsFragment extends BaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
@BindView(R.id.rv_open_libs)
RecyclerView mRvOpenLibs;
private String mParam1;
private String mParam2;
private MineTitleListener mMineTitleListener;
private OpenLibsAdapter mAdapter;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MineTitleListener) {
mMineTitleListener = (MineTitleListener) context;
}
}
public OpenLibsFragment() {
}
public static OpenLibsFragment newInstance(String param1, String param2) {
OpenLibsFragment fragment = new OpenLibsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
protected int getLayoutResId() {
return R.layout.fragment_open_libs;
}
@Override
protected void initViews() {
initRecyclerView();
}
private void initRecyclerView() {
LinearLayoutManager manager = new LinearLayoutManager(mActivity);
manager.setOrientation(LinearLayoutManager.VERTICAL);
mRvOpenLibs.setLayoutManager(manager);
LibsModel libsModel = new LibsModel();
mAdapter = new OpenLibsAdapter(R.layout.layout_libs_item, libsModel.getLibsData(mActivity));
mRvOpenLibs.setAdapter(mAdapter);
mRvOpenLibs.addItemDecoration(new AndroidItemDecoration(mActivity));
mRvOpenLibs.setNestedScrollingEnabled(false);
}
@Override
protected void loadData() {
if (mMineTitleListener != null) {
mMineTitleListener.setTitle("开源库");
}
View headView = View.inflate(mActivity, R.layout.layout_head_lib_view, null);
mAdapter.addHeaderView(headView);
mRvOpenLibs.addOnItemTouchListener(new OnItemClickListener() {
@Override
public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
LibEntity libEntity = (LibEntity) adapter.getData().get(position);
mActivity.startActivity(LibsGithubActivity.newInstance(mActivity, libEntity.getLink()));
}
});
}
}
| true |
ca164add6c7f1d477aba842de9296003ff7d7d6c | Java | heyuanxiao123/tulexing2 | /Tulexing/src/com/xtkj/tlx/entity/LineType.java | UTF-8 | 960 | 2.328125 | 2 | [] | no_license | package com.xtkj.tlx.entity;
import java.io.Serializable;
import java.util.Date;
/*
* 声明线路类型实体类
*/
public class LineType implements Serializable {
private String lineTypeID;//线路类型编号
private String typeName; //线路类型名字
private Date time; //线路类型添加时间
private String icon; //线路类型图标名
private int state;
public String getLineTypeID() {
return lineTypeID;
}
public void setLineTypeID(String lineTypeID) {
this.lineTypeID = lineTypeID;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
| true |
19818aee77d24ac23ba4adf252411a75ac8a37c6 | Java | SoCool1345/DataStructures | /DataStructure/src/main/java/com/tree/ThreadedBinaryTree.java | UTF-8 | 2,960 | 3.5625 | 4 | [] | no_license | package com.tree;
public class ThreadedBinaryTree {
ThreadedBinaryTreeNode root;
ThreadedBinaryTreeNode pre;//前驱结点
public ThreadedBinaryTree(ThreadedBinaryTreeNode root) {
this.root = root;
}
public ThreadedBinaryTreeNode getRoot() {
return root;
}
public void setRoot(ThreadedBinaryTreeNode root) {
this.root = root;
}
public ThreadedBinaryTreeNode getPre() {
return pre;
}
public void setPre(ThreadedBinaryTreeNode pre) {
this.pre = pre;
}
public void preThreaded(){
this.preThreaded(root);
}
public void infixThreaded(){
this.infixThreaded(root);
}
//前序线索化
public void preThreaded(ThreadedBinaryTreeNode node){
if(node==null){
return;
}
//当前节点线索化
//左指针
if(node.getLeft()==null){
node.setLeft(pre);
node.setLeftType(1);
}
//右指针
if(pre!=null&&pre.getRight()==null){
pre.setRight(node);
pre.setRightType(1);
}
pre=node;
//左子树线索化
if(node.getLeftType()!=1) {
preThreaded(node.getLeft());
}
//右子树线索化
if(node.getRightType()!=1) {
preThreaded(node.getRight());
}
}
//中序线索化
public void infixThreaded(ThreadedBinaryTreeNode node){
if(node==null){
return;
}
//左子树线索化
infixThreaded(node.getLeft());
//当前节点线索化
//左指针
if(node.getLeft()==null){
node.setLeft(pre);
node.setLeftType(1);
}
//右指针
if(pre!=null&&pre.getRight()==null){
pre.setRight(node);
pre.setRightType(1);
}
pre=node;
//右子树线索化
infixThreaded(node.getRight());
}
//前序遍历
public void preThreadedList(){
ThreadedBinaryTreeNode node=root;
while (true) {
if (node == null) {
break;
}
while (node.getLeftType() == 0) {//一直向左遍历直到没有子树
System.out.println(node);
node = node.getLeft();
}
System.out.println(node);
node = node.getRight();
}
}
//中序遍历
public void infixThreadedList(){
ThreadedBinaryTreeNode node=root;
while (true) {
if (node == null) {
break;
}
while (node.getLeftType() == 0) {
node = node.getLeft();
}
System.out.println(node);
while (node.getRightType() == 1) {
node = node.getRight();
System.out.println(node);
}
node = node.getRight();
}
}
}
| true |
634c13c1812a56561b263a3ee1d133cc0d280690 | Java | wangjianing-2020/guli | /guli_parent/service/service_edu/src/main/java/com/atguigu/eduservice/controller/EduVideoController.java | UTF-8 | 2,551 | 2.015625 | 2 | [
"Artistic-2.0"
] | permissive | package com.atguigu.eduservice.controller;
import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 课程视频 前端控制器
* </p>
*
* @author testjava
* @since 2021-03-10
*/
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {
@Autowired
EduVideoService videoService;
// 注入vodClient
@Autowired
VodClient vodClient;
// 添加小节
@PostMapping("addVideo")
public R addVideo(@RequestBody EduVideo eduVideo){
videoService.save(eduVideo);
return R.ok();
}
// 删除小节
@DeleteMapping("{id}")
public R deleteVideo(@PathVariable String id){
// 根据小节ID获得视频id,调用方法实现视频删除
EduVideo eduVideo = videoService.getById(id);
String videoSourceId = eduVideo.getVideoSourceId();
// 判断小节里面是否有视频
if (!StringUtils.isEmpty(videoSourceId)){
//根据视频id,远程调用实现视频删除
R result = vodClient.removeAlyVideo(videoSourceId);
if (result.getCode() == 20001){
throw new GuliException(20001,"删除视频失败,熔断器");
}
}
// 删除小节
videoService.removeById(id);
return R.ok();
}
// 修改小节 TODO
@PostMapping("updateVideo")
public R updateVideo(@RequestBody EduVideo eduVideo){
videoService.updateById(eduVideo);
return R.ok();
}
// 根据小节Id查询
@GetMapping("getVideoInfo/{videoId}")
public R getVideoInfo(@PathVariable String videoId){
EduVideo eduVideo = videoService.getById(videoId);
return R.ok().data("video",eduVideo);
}
}
| true |
40835307595bd86f69573cf49e2c4e6fe35453df | Java | samwalls/particle-command | /src/main/java/engine/common/event/CollisionEnterEvent.java | UTF-8 | 238 | 1.9375 | 2 | [] | no_license | package engine.common.event;
import engine.common.physics.Contact;
public class CollisionEnterEvent extends Event {
public Contact contact;
public CollisionEnterEvent(Contact contact) {
this.contact = contact;
}
}
| true |
0bdbd1e02db118952cdf6e4550cfdfa8aed02a14 | Java | spachecogomez/fizzbuzz | /src/main/java/com/test/rest/FizzBuzzController.java | UTF-8 | 836 | 2.21875 | 2 | [] | no_license | package com.test.rest;
import com.test.components.FizzBuzzCalculator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Created by sebastianpacheco on 1/03/18.
*/
@RestController
public class FizzBuzzController {
@Autowired
private FizzBuzzCalculator fizzBuzzCalculator;
@RequestMapping(method = RequestMethod.POST, value = "/fizzbuzz", consumes = "application/json", produces = "application/json")
public List calculateFizzBuzz(@RequestBody List<Integer> nums){
return fizzBuzzCalculator.calculate(nums);
}
}
| true |
0e58fff17309e142170adc1d0a7666c421d269b4 | Java | VinitBhavsar/Stack-Overflow-Clone-Backend | /src/main/java/com/github/QueNAns/service/UserService.java | UTF-8 | 974 | 2.015625 | 2 | [] | no_license | package com.github.QueNAns.service;
import java.util.List;
import com.github.QueNAns.model.Answer;
import com.github.QueNAns.model.Question;
import com.github.QueNAns.model.SecurityQuestion;
import com.github.QueNAns.model.User;
public interface UserService {
List<User> login(String emilAddress, String password);
int signUp(User user);
//ForgetPassword Service
List<SecurityQuestion> getAllSecQuestions();
int checkEmailAddress(User user);
int resetPassword(User user);
//Common Service
List<User> getAllUsers();
List<User> getProfileDetails(long profileId);
List<Question> getProfileQuestions(long profileId);
List<Answer> getProfileAnswers(long profileId);
//User Details Updating Service
int updateUserPersonalDetails(User user);
int updateUserEmailAddress(User user);
int getPassword(User user);
int updateUserPassword(User user);
int updateUserProfilePicture(User user);
int deleteUser(long userid);
}
| true |
69fd9f0916edfcb61e7dc05e9527fc8327856d3d | Java | Qc031x/towin_pcpt | /src/com/sgfm/datacenter/util/LogIntercept.java | UTF-8 | 3,890 | 2.296875 | 2 | [] | no_license | package com.sgfm.datacenter.util;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.opensymphony.xwork2.ActionContext;
import com.sgfm.base.util.DateUtil;
/*import com.sgfm.datacenter.entity.Adminlog;
import com.sgfm.datacenter.service.stockmanager.AdminlogService;*/
@Component
public class LogIntercept {
/*@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(LogIntercept.class);
private Adminlog adminLog = new Adminlog();
@Autowired
private AdminlogService logservice;
private Long time;
public void before() throws Throwable {
time = System.currentTimeMillis();
}
*//**
* 正常返回后
*
* @throws Throwable
*//*
public void afterReturning() throws Throwable {
adminLog.setStatus(1);
adminLog.setTotaltime(System.currentTimeMillis() - time);
if (this.adminLog.isIsok()) { // 是否入库
this.logservice.addLog(adminLog);
}
}
*//**
* 异常情况
*
* @throws Exception
*//*
public void afterThrowing(Throwable throwable) throws Exception {
String msg = throwable.getMessage();
if (msg != null && msg.length() > 100) {
msg = msg.substring(0, 100);
adminLog.setOperation(msg);
}
adminLog.setStatus(0);
adminLog.setTotaltime(System.currentTimeMillis() - time);
if (this.adminLog.isIsok()) {// 是否入库
this.logservice.addLog(adminLog);
}
}
*//**
* 拦截演方法前后
*
* @throws Throwable
*//*
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
LogAnnotation an = method.getAnnotation(LogAnnotation.class);
if (method.isAnnotationPresent(NoLogAnnotation.class)) {
this.adminLog.setIsok(false);
return point.proceed();
}
if (an != null) {
this.adminLog.setDiscrible(an.describe());
this.adminLog.setOperatetype(an.type());
if (an.saveparam()) {
StringBuffer sb = new StringBuffer(method.getName() + "@");
Object[] param = point.getArgs();
for (int i = 0; i < param.length; i++) {
if (param[i] != null) {
if (param[i].getClass().isPrimitive()) {
sb.append(param[i]).append("@");
} else if(param[i] instanceof Date){
Date date=(Date)param[i];
sb.append(DateUtil.format(date,"yyyy/MM/dd HH:mm:ss")).append("@");
}else{
if (param[i] instanceof String[]) {
String[] pm = (String[]) param[i];
for (int j = 0; j < pm.length; j++) {
sb.append(pm[j]).append(",");
}
} else {
sb.append(param[i].toString()).append("@");
}
}
}
}
if (sb .length() > 100) {
this.adminLog.setOperation(sb.substring(0, 100));
}else{
this.adminLog.setOperation(sb.toString());
}
}
}else{
this.adminLog.setOperation(method.getName());
}
this.adminLog.setOperator(AppCache.getCurrentUser().getLoginName());
HttpServletRequest request = null;
final ActionContext context = ActionContext.getContext();
if (context != null) {
request = (HttpServletRequest) context
.get(ServletActionContext.HTTP_REQUEST);
this.adminLog.setIp(getClientAddress(request));
}
this.adminLog.setOperatedate(new Date());
return point.proceed();
}
*//**
* 获取客户端调用的IP
*//*
private final String getClientAddress(HttpServletRequest request) {
String address = request.getHeader("X-Forwarded-For");
if (address != null) {
return address;
}
return request.getRemoteAddr();
}*/
}
| true |
775b0612467fb3308ac1cdccfd8b6a2163abc370 | Java | eonezhang/wechat-pay | /wechat-pay-core/src/main/java/org/develop/wechatpay/utils/Util.java | UTF-8 | 2,514 | 2.671875 | 3 | [] | no_license | package org.develop.wechatpay.utils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.develop.wechatpay.annotation.SignElement;
import org.develop.wechatpay.annotation.XmlElement;
import org.develop.wechatpay.exception.WechatPayException;
/**
* 工具类
*
* @author qiuzhenhao
*
*/
public final class Util {
/**
* 捕获异常转为微信支付异常
*
* @param e
*/
public static void catchException(Throwable e) {
e.printStackTrace();
throw new WechatPayException(e);
}
/**
* 生成签名
*
* @param entity
* @param APIKey
* @return
*/
public static String generateSign(Object entity, String APIKey) {
Assert.nonNull(entity);
Assert.nonBlank(APIKey, "APIKey is not null");
List<String> list = new ArrayList<>();
for (Iterator<Field> iterator = dealSinpleEntity(entity.getClass()); iterator.hasNext();) {
Field field = iterator.next();
field.setAccessible(true);
try {
Object value = field.get(entity);
if (value == null)
continue;
String one = String.format("%s=%s", field.getAnnotation(XmlElement.class).value(), value.toString());
list.add(one);
} catch (IllegalArgumentException | IllegalAccessException e) {
Util.catchException(e);
}
}
list.add("key=" + APIKey);
// 未加密字符串
String unEncrypt = String.join("&", list);
System.out.println(unEncrypt);
return DigestUtils.md5Hex(unEncrypt).toUpperCase();
}
/**
* 处理单个实体类的字段筛选排序
*
* @param clazz
* @return
*/
private static Iterator<Field> dealSinpleEntity(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
// 字典排序器
final ASCIIComparator<Field> asciiComparator = new ASCIIComparator<>(field -> field.getAnnotation(XmlElement.class).value());
// 过滤并按字典排序
return Arrays.asList(fields).stream().filter(field -> Objects.nonNull(field.getAnnotation(XmlElement.class)) && Objects.isNull(field.getAnnotation(SignElement.class))).sorted(asciiComparator).iterator();
}
/**
* 生成随机字符串
*
* @param count
* @return
*/
public static String randomNonceStr(int count) {
return RandomStringUtils.randomAlphanumeric(count);
}
}
| true |
10583cab86b4f86bf129750cb8c8032595998c85 | Java | artem-torbeev/project | /src/main/java/servlets/LoginServlet.java | UTF-8 | 1,974 | 2.5625 | 3 | [] | no_license | package servlets;
import model.User;
import service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String password = req.getParameter("password");
User user = UserService.getInstance().verifyUser(name, password);
if (user != null) {
// создаем сессию
HttpSession session = req.getSession();
// кладем в атрибуты сессии атрибут user с ролью пользователя
if (user.getRole().equals("admin")) {
session.setAttribute("user", user);
// TODO исправить пути
resp.sendRedirect(req.getContextPath() + "/admin");
} else {
session.setAttribute("user", user);
resp.sendRedirect(req.getContextPath() + "/user");
}
} else {
resp.getWriter().println("Ups");
} // нужна регистрация если нет пользователя в базе
}
}
// String url = "http://" + request.getServerName() + ":"
// + request.getServerPort() + request.getContextPath()
// + "/login.jsp";
// response.sendRedirect(url); | true |
99a03f63c6ad87b186f9e4d05cc9870925cf499e | Java | markoromandic/Gerudok | /src/model/ModelElement.java | UTF-8 | 4,145 | 2.984375 | 3 | [
"MIT"
] | permissive | package model;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import work.CreateID;
import work.CreateName;
import work.TypeShape;
/**
* Element
* @author Nemanja
*/
public class ModelElement implements GeRuDocument{
private String name = "";
private ArrayList<ModelElement> listElements;
private ModelObject object;
private int type, id;
/**
* Ovde ide opis metode
* @author Nemanja
*/
public ModelElement(String name, int type){
this.name=name;
this.type=type;
id = CreateID.getNewID();
listElements = new ArrayList<>();
object = new ModelObject(getType());
}
/**
* Ovde ide opis metode
* @author Nemanja
*/
public ModelElement(int type){
this.name=CreateName.getElementName();
this.type=type;
System.out.println("NAPRAVLJEN SAM! Evo moj tip: "+getType());
id = CreateID.getNewID();
listElements = new ArrayList<>();
object = new ModelObject(getType());
}
public ModelObject getObject() {
return object;
}
/**
* Ovde ide opis
* @author Nemanja
* @return
*/
public String getName() {
return name;
}
/**
* Ovde ide opis
* @author Nemanja
* @return
*/
@Override
public int getID(){
return id;
}
/**
* Ovde ide opis
* @author Nemanja
*/
private void addElementToList(ModelElement element){
if(element.getType()==type){
System.out.println("Na element "+name+" dodajem: "+ element);
listElements.add(element);
} else System.out.println("GRESKA PRI DODAVANJU: Tip elementa "+name+" se ne podudara sa tipom elementa "+element.toString()+ " koji dodajemo");
}
/**
* Ovde ide opis
* @author Nemanja
*/
public void printAllElements(){
System.out.println("Na elementu "+name+" se nalaze elementi:");
for (int i = 0; i < listElements.size(); i++) {
System.out.println(listElements.get(i));
}
}
/**
* Ovde ide opis
* @author Nemanja
*/
private void removeElementByIndex(int index){
if(index>=0 && index<listElements.size()){
System.out.println("U elementu "+name+" brisem:"+ listElements.get(index));
listElements.remove(index);
}
else System.out.println("GRESKA PRI BRISANJU: U elementu "+ name + " ne postoji element na indeksu "+ index);
}
/**
* Ovde ide opis
* @author Nemanja
*/
private void removeElementByElement (ModelElement element){
if(listElements.contains(element)){
System.out.println("U elementu "+name+" brisem:"+ element);
listElements.remove(element);
} else System.out.println("GRESKA PRI BRISANJU: U elementu "+name+" ne postoji objekat:"+ element);
}
/**
* Ovde ide opis
* @author Nemanja
*/
private void changeName(String name) {
System.out.println("Promena naziva iz "+this.name+" u "+ name);
this.name=name;
}
/**
* Ovde ide opis
* @author Nemanja
* @return
*/
public ArrayList<ModelElement> getChildren(){
return listElements;
}
/**
* Ovde ide opis
* @author Nemanja
* @return
*/
public int getType(){
return type;
}
/**
* Ovde ide opis
* @author Nemanja
* @return
*/
@Override
public String toString()
{
return name;
}
@Override
public NameAndID add(Object o) {
// TODO Auto-generated method stub
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) o;
ModelElement parent = (ModelElement) parentNode.getUserObject();
if(parent.getType()==2){
return new NameAndID(-1, "nema");
}
ModelElement child = new ModelElement(parent.getType());
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
parentNode.add(childNode);
addElementToList(child);
return new NameAndID(child.getID(), child.getName());
}
@Override
public void remove(Object o) {
// TODO Auto-generated method stub
ModelElement element = (ModelElement) o;
removeElementByElement(element);
}
@Override
public void rename(String name) {
// TODO Auto-generated method stub
changeName(name);
}
@Override
public ArrayList<Object> getChildrenOwn(){
ArrayList<Object> listObj = new ArrayList<>();
for(ModelElement part : getChildren()){
listObj.add(part);
}
return listObj;
}
}
| true |
e60a974f5a9dd9733b5db08be69a18a7eefa51ce | Java | tsuzcx/qq_apk | /com.tencent.mm/classes.jar/com/tencent/kinda/framework/widget/base/MMKButton$BackgroundColorDrawable.java | UTF-8 | 1,228 | 1.765625 | 2 | [] | no_license | package com.tencent.kinda.framework.widget.base;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import com.tencent.matrix.trace.core.AppMethodBeat;
class MMKButton$BackgroundColorDrawable
extends Drawable
{
private int color;
MMKButton$BackgroundColorDrawable(int paramInt)
{
this.color = paramInt;
}
public void draw(Canvas paramCanvas)
{
AppMethodBeat.i(18993);
paramCanvas.drawColor(this.color);
AppMethodBeat.o(18993);
}
public int getOpacity()
{
AppMethodBeat.i(18994);
if (this.color == 0)
{
AppMethodBeat.o(18994);
return -2;
}
if (Color.alpha(this.color) > 0)
{
AppMethodBeat.o(18994);
return -3;
}
AppMethodBeat.o(18994);
return -1;
}
public void setAlpha(int paramInt) {}
public void setColorFilter(ColorFilter paramColorFilter) {}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes3.jar
* Qualified Name: com.tencent.kinda.framework.widget.base.MMKButton.BackgroundColorDrawable
* JD-Core Version: 0.7.0.1
*/ | true |
bac2af087fde531d83ae93c2e44124af9f4e58fb | Java | wanfengsky/IPv6--Network-teaching-platform | /src/main/java/com/yi/project/course/chapter/controller/CourseChapterController.java | UTF-8 | 5,904 | 1.929688 | 2 | [] | no_license | package com.yi.project.course.chapter.controller;
import java.util.List;
import com.yi.common.utils.security.ShiroUtils;
import com.yi.framework.web.domain.Ztree;
import com.yi.project.system.dept.domain.Dept;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yi.framework.aspectj.lang.annotation.Log;
import com.yi.framework.aspectj.lang.enums.BusinessType;
import com.yi.project.course.chapter.domain.CourseChapter;
import com.yi.project.course.chapter.service.ICourseChapterService;
import com.yi.framework.web.controller.BaseController;
import com.yi.framework.web.domain.AjaxResult;
import com.yi.common.utils.poi.ExcelUtil;
import com.yi.framework.web.page.TableDataInfo;
/**
* 课程章节Controller
*
* @author yi
* @date 2020-12-03
*/
@Api("课程章节管理")
@Controller
@RequestMapping("/course/chapter")
public class CourseChapterController extends BaseController {
private String prefix = "course/chapter";
@Autowired
private ICourseChapterService courseChapterService;
@ApiOperation("课程章节管理页")
@RequiresPermissions("course:chapter:view")
@GetMapping()
public String chapter() {
return prefix + "/chapter";
}
/**
* 查询课程章节列表
*/
@ApiOperation("课程章节列表查询")
@RequiresPermissions("course:chapter:list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(CourseChapter courseChapter) {
startPage();
List<CourseChapter> list = courseChapterService.selectCourseChapterList(courseChapter);
return getDataTable(list);
}
/**
* 查询课程章节列表
*/
@ApiOperation("课程章节列表查询")
@RequiresPermissions("course:chapter:list")
@GetMapping("/chapterList")
public String chapterList(Long courseId, ModelMap mmap) {
mmap.put("courseId", courseId);
return prefix + "/chapterList";
}
/**
* 查询课程章节列表
*/
@ApiOperation("课程章节列表查询")
@RequiresPermissions("course:chapter:list")
@GetMapping("/chapterCenter")
public String chapterCenter(Long courseId,Long chapterId, ModelMap mmap) {
mmap.put("chapterId", chapterId);
mmap.put("courseId", courseId);
return prefix + "/chapterCenter";
}
/**
* 导出课程章节列表
*/
@ApiOperation("课程章节列表导出")
@RequiresPermissions("course:chapter:export")
@Log(title = "课程章节", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ResponseBody
public AjaxResult export(CourseChapter courseChapter) {
List<CourseChapter> list = courseChapterService.selectCourseChapterList(courseChapter);
ExcelUtil<CourseChapter> util = new ExcelUtil<CourseChapter>(CourseChapter.class);
return util.exportExcel(list, "chapter");
}
/**
* 新增课程章节
*/
@ApiOperation("课程章节新增界面")
@GetMapping("/add")
public String add(Long courseId, ModelMap mmap) {
mmap.put("courseId", courseId);
return prefix + "/add";
}
/**
* 新增保存课程章节
*/
@ApiOperation("新增保存课程章节")
@RequiresPermissions("course:chapter:add")
@Log(title = "课程章节", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(CourseChapter courseChapter) {
return toAjax(courseChapterService.insertCourseChapter(courseChapter));
}
/**
* 修改课程章节
*/
@ApiOperation("课程章节编辑界面")
@GetMapping("/edit/{chapterId}")
public String edit(@PathVariable("chapterId") Long chapterId, ModelMap mmap) {
CourseChapter courseChapter = courseChapterService.selectCourseChapterById(chapterId);
mmap.put("courseChapter", courseChapter);
return prefix + "/edit";
}
/**
* 修改保存课程章节
*/
@ApiOperation("修改保存课程章节")
@RequiresPermissions("course:chapter:edit")
@Log(title = "课程章节", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(CourseChapter courseChapter) {
return toAjax(courseChapterService.updateCourseChapter(courseChapter));
}
/**
* 删除课程章节
*/
@ApiOperation("删除课程章节数据")
@RequiresPermissions("course:chapter:remove")
@Log(title = "课程章节", businessType = BusinessType.DELETE)
@PostMapping( "/remove")
@ResponseBody
public AjaxResult remove(String ids) {
return toAjax(courseChapterService.deleteCourseChapterByIds(ids));
}
/**
* 课程章节字典
*/
@ApiOperation("课程章节字典")
@RequiresPermissions("course:chapter:view")
@GetMapping("/dict/{courseId}")
@ResponseBody
public AjaxResult chapterDict(@PathVariable Long courseId) {
AjaxResult ajax = new AjaxResult();
ajax.put("code", 200);
ajax.put("value", courseChapterService.chapterDict(courseId));
return ajax;
}
/**
* 加载部门列表树
*/
@GetMapping("/treeData")
@ResponseBody
public List<Ztree> treeData(Long courseId)
{
List<Ztree> ztrees = courseChapterService.selectCourseTree(courseId);
return ztrees;
}
}
| true |
3b6f239b4e74e7c7cbedf6f81cb2d34a37b7c1cd | Java | OOSD-Devs/Aplikasi-Belajar | /src/com/data/Mahasiswa.java | UTF-8 | 10,661 | 2.828125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.data;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
*
* @author ares
*/
public class Mahasiswa extends User implements Auth{
private String kelas;
private String nim;
private JenisProdi jurusan;
/**
*
* @param kelas
* @param nim
* @param jurusan
*/
public Mahasiswa(String kelas, String nim, JenisProdi jurusan) {
this.kelas = kelas;
this.nim = nim;
this.jurusan = jurusan;
}
public Mahasiswa() {
}
public String getKelas() {
return kelas;
}
public void setKelas(String kelas) {
this.kelas = kelas;
}
public String getNim() {
return nim;
}
public void setNim(String nim) {
this.nim = nim;
}
public JenisProdi getJurusan() {
return jurusan;
}
public void setJurusan(JenisProdi jurusan) {
this.jurusan = jurusan;
}
public ArrayList<Mahasiswa> loginMahasiswa() throws IOException{
try{
File file = new File("Mahasiswa.txt");
}catch(Exception e){
System.out.println("Database tidak ditemukan");
System.out.println("Silahkan register terlebih dahulu!");
System.out.println(e);
}
Scanner userInput = new Scanner(System.in);
String username;
String password;
System.out.print("Masukkan Username: ");
username = userInput.next();
System.out.print("Masukkan Password: ");
password = userInput.next();
ArrayList<Mahasiswa> isExist = cari(username, password);
return isExist;
}
public ArrayList<Mahasiswa> cari(String username, String password) throws IOException{
FileReader fileInput = new FileReader("Mahasiswa.txt");
BufferedReader bufferInput = new BufferedReader(fileInput);
String data = bufferInput.readLine();
boolean isExist = false;
ArrayList<Mahasiswa> bio = new ArrayList<Mahasiswa>();
while(data != null){
StringTokenizer stringToken = new StringTokenizer(data, ",");
if(stringToken.nextToken().equalsIgnoreCase(username) && stringToken.nextToken().equalsIgnoreCase(password)){
Mahasiswa mhs = new Mahasiswa();
JenisKelamin jk;
JenisProdi jp;
mhs.setNama(stringToken.nextToken());
mhs.setNim(stringToken.nextToken());
jp = JenisProdi.valueOf(stringToken.nextToken());
mhs.setJurusan(jp);
jk = JenisKelamin.valueOf(stringToken.nextToken());
mhs.setJenisKelamin(jk);
bio.add(mhs);
}
data = bufferInput.readLine();
}
return bio;
}
// public boolean login() throws IOException{
//
// try{
// File file = new File("Mahasiswa.txt");
// }catch(Exception e){
// System.out.println("Database tidak ditemukan");
// System.out.println("Silahkan register terlebih dahulu!");
// System.out.println(e);
// return false;
// }
//
// Scanner userInput = new Scanner(System.in);
//
// String username;
// String password;
//
// System.out.print("Masukkan Username: ");
// username = userInput.next();
// System.out.print("Masukkan Password: ");
// password = userInput.next();
//
// boolean isExist = cariDiDatabase(username, password);
//
// return isExist;
// }
//
// public static boolean cariDiDatabase(String username, String password) throws IOException{
//
// FileReader fileInput = new FileReader("Mahasiswa.txt");
// BufferedReader bufferInput = new BufferedReader(fileInput);
//
// String data = bufferInput.readLine();
// boolean isExist = false;
//
// while(data != null){
//
// StringTokenizer stringToken = new StringTokenizer(data, ",");
//
// stringToken.nextToken();
// stringToken.nextToken();
// stringToken.nextToken();
// stringToken.nextToken();
//
// if(stringToken.nextToken().equalsIgnoreCase(username) && stringToken.nextToken().equalsIgnoreCase(password)){
// isExist = true;
// }
//
// data = bufferInput.readLine();
// }
//
// return isExist;
// }
@Override
public boolean logout(){
return false;
}
/**
*
* @throws IOException
*/
@Override
public void register() throws IOException{
FileWriter fileOutput = new FileWriter("Mahasiswa.txt", true);
try (BufferedWriter bufferOutput = new BufferedWriter(fileOutput)) {
Mahasiswa mhs = new Mahasiswa();
Scanner userInput = new Scanner(System.in);
int pilihan;
System.out.print("Masukkan Nama: ");
mhs.setNama(userInput.nextLine());
System.out.print("Masukkan NIM: ");
mhs.setNim(userInput.nextLine());
System.out.println("Jenis Kelamin: ");
System.out.println("1. " + JenisKelamin.LAKILAKI);
System.out.println("2. " + JenisKelamin.PEREMPUAN);
System.out.print("Masukkan kode Jenis Kelamin: ");
pilihan = userInput.nextInt();
while(pilihan != 1 && pilihan != 2){
System.out.println("Kode jenis kelamin salah!");
System.out.println("1. " + JenisKelamin.LAKILAKI);
System.out.println("2. " + JenisKelamin.PEREMPUAN);
System.out.print("Masukkan kode Jenis Kelamin: ");
pilihan = userInput.nextInt();
}
switch(pilihan){
case 1:
mhs.setJenisKelamin(JenisKelamin.LAKILAKI);
break;
case 2:
mhs.setJenisKelamin(JenisKelamin.PEREMPUAN);
break;
}
System.out.println("Jurusan: ");
System.out.println("1. " + JenisProdi.D3TI);
System.out.println("2. " + JenisProdi.D3TK);
System.out.println("3. " + JenisProdi.D4TRPL);
System.out.println("4. " + JenisProdi.S1IF);
System.out.println("5. " + JenisProdi.S1SI);
System.out.println("6. " + JenisProdi.S1TE);
System.out.println("7. " + JenisProdi.S1MR);
System.out.println("8. " + JenisProdi.S1BP);
System.out.print("Masukkan Kode Jurusan: ");
pilihan = userInput.nextInt();
while(pilihan != 1 && pilihan != 2 && pilihan != 3 && pilihan != 4 && pilihan != 5 && pilihan != 6 && pilihan != 7 && pilihan != 8){
System.out.println("Jurusan: ");
System.out.println("1. " + JenisProdi.D3TI);
System.out.println("2. " + JenisProdi.D3TK);
System.out.println("3. " + JenisProdi.D4TRPL);
System.out.println("4. " + JenisProdi.S1IF);
System.out.println("5. " + JenisProdi.S1SI);
System.out.println("6. " + JenisProdi.S1TE);
System.out.println("7. " + JenisProdi.S1MR);
System.out.println("8. " + JenisProdi.S1BP);
System.out.print("Masukkan Kode Jurusan: ");
pilihan = userInput.nextInt();
}
switch(pilihan){
case 1:
mhs.setJurusan(JenisProdi.D3TI);
break;
case 2:
mhs.setJurusan(JenisProdi.D3TK);
break;
case 3:
mhs.setJurusan(JenisProdi.D4TRPL);
break;
case 4:
mhs.setJurusan(JenisProdi.S1IF);
break;
case 5:
mhs.setJurusan(JenisProdi.S1SI);
break;
case 6:
mhs.setJurusan(JenisProdi.S1TE);
break;
case 7:
mhs.setJurusan(JenisProdi.S1MR);
break;
case 8:
mhs.setJurusan(JenisProdi.S1BP);
break;
}
System.out.print("Masukkan Username: ");
mhs.setUsername(userInput.next());
System.out.print("Masukkan Password: ");
mhs.setPassword(userInput.next());
System.out.println("Nama: " + mhs.getNama());
System.out.println("NIM: " + mhs.getNim());
System.out.println("Jurusan: " + mhs.getJurusan());
System.out.println("Jenis Kelamin " + mhs.getJenisKelamin());
System.out.println("Username: " + mhs.getUsername());
System.out.println("Password: " + mhs.getPassword());
boolean isRegister = yaAtauTidak("Apakah anda yakin ingin menambah data tersebut");
if(isRegister){
bufferOutput.write(mhs.getUsername() + "," + mhs.getPassword() + "," + mhs.getJurusan() + "," + mhs.getJenisKelamin() + "," + mhs.getNama() + "," + mhs.getNim());
bufferOutput.newLine();
bufferOutput.flush();
}
}
}
public static boolean yaAtauTidak(String messages){
Scanner userInput = new Scanner(System.in);
System.out.print("\n" + messages + " (y/n)? ");
String pilihanUser = userInput.next();
while(!pilihanUser.equalsIgnoreCase("y") && !pilihanUser.equalsIgnoreCase("n")){
System.out.println("Pilihan anda bukan y atau n");
System.out.println("\n" + messages + " y/n? ");
pilihanUser = userInput.next();
}
return pilihanUser.equalsIgnoreCase("y");
}
}
| true |