hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
8435485b1fc42b5ae4a98ac9e186704ff4d50b9e | 726 | package engine.sprites.properties;
/**
* Speed property implemented by launcher. Determines how fast projectiles move after
* being launched by Launcher object.
*
* @author Katherine Van Dyk
* @date 4/7/18
*
*/
public class SpeedProperty extends UpgradeProperty {
/**
* Constructor that takes in cost of range property, upgrade value, and
* initial range value.
*
* @param cost
* @param value
* @param speed
*/
public SpeedProperty(double cost, double value, double speed) {
super(cost, value, speed);
}
public SpeedProperty(UpgradeProperty p) {
super(p);
}
public void setProperty(double newSpeed) {
this.setProperty(newSpeed);
}
}
| 21.352941 | 85 | 0.655647 |
db79ca65af6add2e3b7b09887507c061b798da9d | 4,965 | package pro;
import static java.lang.System.exit;
import java.util.Scanner;
public class Pro {
public static void main(String[] args) {
int amt=0,unit=0;
Scanner scan =new Scanner(System.in);
for(;;){
System.out.println(" 1: INDUSTRIAL USER 2:COMMERCIAL USER 3:PUBLIC USER 4:EXIT" );/* display the choices */
System.out.println("ENTER YOUR CHOICE");
int var = scan.nextInt (); /* Input of choice */
switch(var){
case 1: System.out.println("Enter the units used");
unit=scan.nextInt(); /* input of units used */
if(unit<=1500)
{
amt=1000+(8*unit);/*calculate amount*/
}
else if(unit>1499 && unit<3500)
{
amt=1000+(9*unit); /*calculate amount*/
}
else if(unit>3499 && unit<5000)
{
amt=1000+(10*unit);/*calculate amount*/
}
else if(unit>=5000)
{
amt=1000+(12*unit);/*calculate amount*/
}
break;
case 2: System.out.println("Enter the units used");
unit=scan.nextInt();
if(unit<=1000)
{
amt=500+(6*unit);/*calculate amount*/
}
else if(unit>999 && unit<1500)
{
amt=500+(7*unit); /*calculate amount*/
}
else if(unit>1499 && unit<2500)
{
amt=500+(8*unit); /*calculate amount*/
}
else if(unit>=2500)
{
amt=500+(10*unit);/*calculate amount*/
}
break;
case 3: System.out.println("Enter the units used");
unit=scan.nextInt();
if(unit<=100)
{
amt=300+(3*unit);/*calculate amount*/
}
else if(unit>99 && unit<350)
{
amt=300+(4* unit);
}
else if( unit>350 && unit<500)
{
amt=300+(5* unit);/*calculate amount*/
}
else if( unit>=500)
{
amt=300+(8* unit);/*calculate amount*/
}
break;
case 4:System.out.println("");
System.out.println("THANK YOU");
exit(0); /*Terminating the program*/
default:System.out.println("INVALID CHOICE");
}
System.out.println("-----------------------------------------------------------------");
System.out.println("*****************************************************************");
System.out.println("-----------------------------------------------------------------");
System.out.println(" H E S C O M ");
System.out.println(" ELECTRICITY BILL ");
System.out.println();
System.out.println("NUMBER OF UNIT(S) USED = "+unit+" units" );
System.out.println("THE AMOUNT TO BE PAID IS = Rs."+amt );
System.out.println();
System.out.println(" THANK YOU ");
System.out.println("-----------------------------------------------------------------");
System.out.println("*****************************************************************");
System.out.println("-----------------------------------------------------------------");
System.out.println();
}
}
}
| 49.65 | 123 | 0.281571 |
8b25d6afe885c29f2d2e294a6bb2aaf95e9090d5 | 11,598 | package com.zolve;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.DefaultRetryPolicy;
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.JSONException;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
TextView currAmt;
Button credit;
Button debit;
Button refresh;
Button logout;
Button listAll;
private RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currAmt = findViewById(R.id.currAmt);
refresh = findViewById(R.id.getCurrAmt);
credit = findViewById(R.id.creditAmt);
debit = findViewById(R.id.debitAmt);
logout = findViewById(R.id.logout);
listAll = findViewById(R.id.listAll);
requestQueue = Volley.newRequestQueue(this);
refresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getBalance();
}
});
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPrefManager.getInstance(MainActivity.this).logout();
finish();
}
});
listAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,TransactionActivity.class));
}
});
credit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alert.setMessage("Credit");
alert.setTitle("Enter balance to credit");
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String val = input.getText().toString();
double amt = 0.0;
try {
amt = Double.parseDouble(val);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Must be a real number", Toast.LENGTH_SHORT).show();
}
creditBalance(amt);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
});
alert.show();
}
});
debit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alert.setMessage("Debit");
alert.setTitle("Enter balance to debit");
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String val = input.getText().toString();
double amt = 0.0;
try {
amt = Double.parseDouble(val);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Must be a real number", Toast.LENGTH_SHORT).show();
}
debitBalance(amt);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
});
alert.show();
}
});
}
private void debitBalance(double amt) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, ServerURL.DEBIT_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Token", response);
try {
JSONObject userObj = new JSONObject(response);
int status = userObj.optInt("data", -1);
if (status == 1)
Toast.makeText(MainActivity.this, "Balance debited successfully", Toast.LENGTH_SHORT).show();
else if (status == 0)
Toast.makeText(MainActivity.this, "Balance cannot be debited below minimum balance", Toast.LENGTH_SHORT).show();
} catch (JSONException | NullPointerException e) {
Toast.makeText(MainActivity.this, "Error debiting balance", Toast.LENGTH_SHORT).show();
}
getBalance();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error == null || error.networkResponse == null)
return;
String statusCode = String.valueOf(error.networkResponse.statusCode), body;
body = new String(error.networkResponse.data, StandardCharsets.UTF_8);
if (statusCode.equals("500"))
Toast.makeText(MainActivity.this, "Server could not be reached\nError code " + statusCode, Toast.LENGTH_SHORT).show();
Log.e("PhoneError", body);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("amount", String.valueOf(amt));
params.put("mobile", SharedPrefManager.getInstance(MainActivity.this).getLogin());
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(4000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
private void creditBalance(double amt) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, ServerURL.CREDIT_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Token", response);
try {
JSONObject userObj = new JSONObject(response);
if (userObj.optInt("data", 0) == 1)
Toast.makeText(MainActivity.this, "Balance credited successfully", Toast.LENGTH_SHORT).show();
} catch (JSONException | NullPointerException e) {
Toast.makeText(MainActivity.this, "Error crediting balance", Toast.LENGTH_SHORT).show();
}
getBalance();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error == null || error.networkResponse == null)
return;
String statusCode = String.valueOf(error.networkResponse.statusCode), body;
body = new String(error.networkResponse.data, StandardCharsets.UTF_8);
if (statusCode.equals("500"))
Toast.makeText(MainActivity.this, "Server could not be reached\nError code " + statusCode, Toast.LENGTH_SHORT).show();
Log.e("PhoneError", body);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("amount", String.valueOf(amt));
params.put("mobile", SharedPrefManager.getInstance(MainActivity.this).getLogin());
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(4000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
@Override
protected void onResume() {
super.onResume();
getBalance();
}
private void getBalance() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, ServerURL.BALANCE_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Token", response);
try {
JSONObject userObj = new JSONObject(response);
currAmt.setText(String.valueOf(userObj.optDouble("data", 0.0)));
} catch (JSONException | NullPointerException e) {
Toast.makeText(MainActivity.this, "Error acquiring balance", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error == null || error.networkResponse == null)
return;
String statusCode = String.valueOf(error.networkResponse.statusCode), body;
body = new String(error.networkResponse.data, StandardCharsets.UTF_8);
if (statusCode.equals("500"))
Toast.makeText(MainActivity.this, "Server could not be reached\nError code " + statusCode, Toast.LENGTH_SHORT).show();
Log.e("PhoneError", body);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("mobile", SharedPrefManager.getInstance(MainActivity.this).getLogin());
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(4000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
} | 43.931818 | 138 | 0.57234 |
26a6dff98a273f4b5f773f4b669c2daedbab84df | 67 | package android.pkg;
public class AClassWithoutAndroidAssert {
}
| 11.166667 | 41 | 0.80597 |
e1574e18441b5e23af923aab5ff25417f7c36a84 | 3,977 | package net.minecraft.block;
import java.util.List;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
public class BlockSand extends BlockFalling {
public static final PropertyEnum field_176504_a = PropertyEnum.func_177709_a("variant", BlockSand.EnumType.class);
private static final String __OBFID = "CL_00000303";
public BlockSand() {
this.func_180632_j(this.field_176227_L.func_177621_b().func_177226_a(field_176504_a, BlockSand.EnumType.SAND));
}
public int func_180651_a(IBlockState p_180651_1_) {
return ((BlockSand.EnumType)p_180651_1_.func_177229_b(field_176504_a)).func_176688_a();
}
public void func_149666_a(Item p_149666_1_, CreativeTabs p_149666_2_, List p_149666_3_) {
BlockSand.EnumType[] var4 = BlockSand.EnumType.values();
int var5 = var4.length;
for(int var6 = 0; var6 < var5; ++var6) {
BlockSand.EnumType var7 = var4[var6];
p_149666_3_.add(new ItemStack(p_149666_1_, 1, var7.func_176688_a()));
}
}
public MapColor func_180659_g(IBlockState p_180659_1_) {
return ((BlockSand.EnumType)p_180659_1_.func_177229_b(field_176504_a)).func_176687_c();
}
public IBlockState func_176203_a(int p_176203_1_) {
return this.func_176223_P().func_177226_a(field_176504_a, BlockSand.EnumType.func_176686_a(p_176203_1_));
}
public int func_176201_c(IBlockState p_176201_1_) {
return ((BlockSand.EnumType)p_176201_1_.func_177229_b(field_176504_a)).func_176688_a();
}
protected BlockState func_180661_e() {
return new BlockState(this, new IProperty[]{field_176504_a});
}
public static enum EnumType implements IStringSerializable {
SAND("SAND", 0, 0, "sand", "default", MapColor.field_151658_d),
RED_SAND("RED_SAND", 1, 1, "red_sand", "red", MapColor.field_151664_l);
private static final BlockSand.EnumType[] field_176695_c = new BlockSand.EnumType[values().length];
private final int field_176692_d;
private final String field_176693_e;
private final MapColor field_176690_f;
private final String field_176691_g;
// $FF: synthetic field
private static final BlockSand.EnumType[] $VALUES = new BlockSand.EnumType[]{SAND, RED_SAND};
private static final String __OBFID = "CL_00002069";
private EnumType(String p_i45687_1_, int p_i45687_2_, int p_i45687_3_, String p_i45687_4_, String p_i45687_5_, MapColor p_i45687_6_) {
this.field_176692_d = p_i45687_3_;
this.field_176693_e = p_i45687_4_;
this.field_176690_f = p_i45687_6_;
this.field_176691_g = p_i45687_5_;
}
public int func_176688_a() {
return this.field_176692_d;
}
public String toString() {
return this.field_176693_e;
}
public MapColor func_176687_c() {
return this.field_176690_f;
}
public static BlockSand.EnumType func_176686_a(int p_176686_0_) {
if(p_176686_0_ < 0 || p_176686_0_ >= field_176695_c.length) {
p_176686_0_ = 0;
}
return field_176695_c[p_176686_0_];
}
public String func_176610_l() {
return this.field_176693_e;
}
public String func_176685_d() {
return this.field_176691_g;
}
static {
BlockSand.EnumType[] var0 = values();
int var1 = var0.length;
for(int var2 = 0; var2 < var1; ++var2) {
BlockSand.EnumType var3 = var0[var2];
field_176695_c[var3.func_176688_a()] = var3;
}
}
}
}
| 33.70339 | 140 | 0.694493 |
e0852c65d6b117ffc5f7467a0c7913822c56393e | 550 | package de.unisiegen.gtitool.core.entities.listener;
import java.util.EventListener;
/**
* The listener interface for receiving modify status changes.
*
* @author Christian Fehler
* @version $Id: ModifyStatusChangedListener.java 1372 2008-10-30 08:36:20Z
* fehler $
*/
public interface ModifyStatusChangedListener extends EventListener
{
/**
* Invoked when the modify status changed.
*
* @param modified True if the status is modified, otherwise false.
*/
public void modifyStatusChanged ( boolean modified );
}
| 22.916667 | 75 | 0.727273 |
72407581982604c89e95074cfe1f56453611a81c | 919 | package com.example.mert.stoktakip.models;
/**
* {@code KarCiroBilgisi} sınıfı bir zaman aralığı içinde yapılan ciro ve kar miktarını tutuyor.
* Örneğin:
* Zaman - Kar(TL) - Ciro(TL)
* 15 Haz - 728.30 - 140.95
* Aralık - 12573.15 - 1128.00
* 2019 - 95833.45 - 7985.20
*/
public class KarCiroBilgisi {
private float ciro;
private float kar;
private String zaman;
public KarCiroBilgisi(float ciro, float kar, String zaman) {
this.ciro = ciro;
this.kar = kar;
this.zaman = zaman;
}
public float getKar() {
return kar;
}
public void setKar(float kar) {
this.kar = kar;
}
public float getCiro() {
return ciro;
}
public void setCiro(float ciro) {
this.ciro = ciro;
}
public String getZaman() {
return zaman;
}
public void setZaman(String zaman) {
this.zaman = zaman;
}
} | 20.422222 | 96 | 0.593036 |
95127c686a0be5e9442c4d9587e2d92890f6166a | 865 | package quanta.types;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import quanta.config.ServiceBase;
import quanta.model.NodeInfo;
import quanta.mongo.MongoSession;
import quanta.mongo.model.SubNode;
import quanta.request.CreateSubNodeRequest;
import quanta.util.Val;
@Component
public abstract class TypeBase extends ServiceBase {
private static final Logger log = LoggerFactory.getLogger(TypeBase.class);
public void postContruct() {
TypePluginMgr.addType(this);
}
/* Must match the actual type name of the nodes */
public abstract String getName();
public void convert(MongoSession ms, NodeInfo nodeInfo, SubNode node, boolean getFollowers) {}
public void createSubNode(MongoSession ms, Val<SubNode> node, CreateSubNodeRequest req, boolean linkBookmark) {}
}
| 30.892857 | 116 | 0.778035 |
4eaad9b1c61b8392b74b353a515381ef10023a2a | 13,595 | /*
* TACDocumentSet.java
*
* Created on May 5, 2008, 10:18 AM
*
*/
package gr.demokritos.iit.tacTools;
import gr.demokritos.iit.jinsect.storage.IFileLoader;
import gr.demokritos.iit.jinsect.structs.CategorizedFileEntry;
import gr.demokritos.iit.jinsect.structs.IDocumentSet;
import gr.demokritos.iit.jinsect.utils;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/** This class implements the {@link IDocumentSet} interface, also implementing
* a number of methods to make the retrieval of TAC document sets (also called
* DOCSTREAMs) easier.
*
* @author ggianna
*/
public class ACQUAINT2DocumentSet implements IDocumentSet, IFileLoader<String> {
/** Constant indicating tirage from the training set.
*/
public static final int FROM_TRAINING_SET = 1;
/** Constant indicating tirage from the test set.
*/
public static final int FROM_TEST_SET = 2;
/** Constant indicating tirage from the whole (training plus test) set.
*/
public static final int FROM_WHOLE_SET = 3;
/** The tag name of the Dateline tag. */
public static final String DATELINE_TAG = "DATELINE";
/** The tag name of the Text tag. */
public static final String TEXT_TAG = "TEXT";
/** The XMLDocument holding the DOCSTREAM. */
Document XMLDoc;
/** The categories of documents, derived from the <i>type</i> attribute of
* the <i>DOC</i> tag. */
ArrayList Categories;
/** The set of document identifiers.
*/
HashSet<String> hsDocs;
/** The mapping of files to categories. */
HashMap<String, String> hmDocsToCategories;
/** Creates a new instance of TACDocumentSet, given a corresponding TAC08
* formatted file.
*@param sTACXMLFile The XML file containing the DOCSTREAM.
*/
public ACQUAINT2DocumentSet(String sTACXMLFile) {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
XMLDoc = null;
Categories = null;
hsDocs = null;
hmDocsToCategories = null;
try {
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
XMLDoc = docBuilder.parse(new File(sTACXMLFile));
} catch (ParserConfigurationException ex) {
System.err.println("Invalid XML file. Details:");
ex.printStackTrace(System.err);
} catch (SAXException ex) {
System.err.println("Invalid XML file. Details:");
ex.printStackTrace(System.err);
} catch (IOException ex) {
System.err.println("Could not read XML file. Cause:");
ex.printStackTrace(System.err);
}
if (XMLDoc == null)
return;
// Init mapping to categories
hmDocsToCategories = new HashMap<String, String>();
// normalize text representation
XMLDoc.getDocumentElement().normalize();
}
public List getCategories() {
// Check for already calculated categories
if (Categories != null)
// and return, if found.
return Categories;
HashMap<String,Integer> hmCategories = new HashMap();
// Init categories.
// Get all docs
NodeList docList = XMLDoc.getElementsByTagName("DOC");
// and extract type as category.
for (int iNodeCnt = 0; iNodeCnt < docList.getLength(); iNodeCnt++) {
// Update Categories
hmCategories.put(docList.item(iNodeCnt).getAttributes().getNamedItem("type").getNodeValue(), 1);
}
Categories = new ArrayList(hmCategories.keySet());
return Categories;
}
public void createSets() {
// Clear existing set of files
hsDocs = new HashSet<String>();
// Get all docs
NodeList docList = XMLDoc.getElementsByTagName("DOC");
for (int iNodeCnt = 0; iNodeCnt < docList.getLength(); iNodeCnt++) {
// Add file ID to set
hsDocs.add(docList.item(iNodeCnt).getAttributes().getNamedItem("id").getNodeValue());
// Update category for file
hmDocsToCategories.put(docList.item(iNodeCnt).getAttributes().getNamedItem("id").getNodeValue(),
docList.item(iNodeCnt).getAttributes().getNamedItem("type").getNodeValue());
}
}
public ArrayList getFilesFromCategory(String sCategoryName) {
ArrayList sRes = new ArrayList();
for (String sFile : hmDocsToCategories.keySet()) {
if (hmDocsToCategories.get(sFile).equals(sCategoryName))
sRes.add(sFile);
}
return sRes;
}
/** Returns whole set. TODO: Implement as should be. */
public ArrayList getTrainingSet() {
ArrayList<CategorizedFileEntry> alRes = new ArrayList<CategorizedFileEntry>();
for (String sFile : hmDocsToCategories.keySet()) {
alRes.add(new CategorizedFileEntry(sFile, hmDocsToCategories.get(sFile)));
}
return alRes;
}
/** Returns whole set. TODO: Implement as should be. */
public ArrayList getTestSet() {
ArrayList<CategorizedFileEntry> alRes = new ArrayList<CategorizedFileEntry>();
for (String sFile : hmDocsToCategories.keySet()) {
alRes.add(new CategorizedFileEntry(sFile, hmDocsToCategories.get(sFile)));
}
return alRes;
}
public String loadFile(String sID) {
return loadDocumentTextToString(sID);
}
/** Returns the text portion of a given document as a String.
*@param sDocID The document ID.
*@return Null if document is not found, otherwise its text portion (all
* text found within <i>TEXT</i> tags.
*/
public String loadDocumentTextToString(String sDocID) {
return loadDocumentElement(sDocID, TEXT_TAG);
}
/** Returns the full text of a given document, including dateline and other
* elements as a String. Tags are removed.
*@param sDocID The document ID.
*@return Null if document is not found, otherwise its full text.
*/
public String loadFullDocumentTextToString(String sDocID) {
Node nDoc = XMLDoc.getElementById(sDocID);
if (nDoc == null)
return null;
Element eDoc = (Element)nDoc;
String sRes = eDoc.getTextContent();
return sRes;
}
/** Returns the dateline portion of a given document as a String, if the
* dateline exists.
*@param sDocID The document ID.
*@return Null if document is not found, a zero length String if no dateline
* was found, otherwise the document's dateline field (all
* text found within <i>DATELINE</i> tags.
*/
public String loadDocumentDatelineToString(String sDocID) {
return loadDocumentElement(sDocID, DATELINE_TAG);
}
/** Returns a given element of a given document as a String, if the
* element exists.
*@param sDocID The document ID.
*@param sElement The element name (e.g. TEXT or DATELINE).
*@return Null if document is not found, a zero length String if the specified
* element was not found, otherwise the document's element text.
*/
public final String loadDocumentElement(String sDocID, String sElement) {
Node nDoc = XMLDoc.getElementById(sDocID);
if (nDoc == null)
return null;
Element eDoc = (Element)nDoc;
NodeList nDocElements = nDoc.getChildNodes();
Node n = null;
// Find text elements
for (int iCnt = 0; iCnt < nDocElements.getLength(); iCnt++) {
if (nDocElements.item(iCnt).getNodeName().equalsIgnoreCase(sElement)) {
n = nDocElements.item(iCnt);
break;
}
}
String sRes;
if (n != null)
sRes = n.getTextContent();
else
sRes = ""; // Not found
return sRes;
}
public Date getDocDate(String sDocID) {
// Get dateline
String sDate = loadDocumentDatelineToString(sDocID);
// Init date based on ID.
// DocID Format: XXX_XXX_YYYYMMdd.####
// Get year by backtracking 8 digits from the dot.
int iDateStart = sDocID.indexOf(".");
String sYear = sDocID.substring(iDateStart - 8, iDateStart - 4);
String sMonthNum = sDocID.substring(sDocID.indexOf(".") - 4,
sDocID.indexOf(".") - 2);
String sMonth = null;
String sMonthDay = sDocID.substring(sDocID.indexOf(".") - 4,
sDocID.indexOf(".") - 2);
String sFinalDate = "";
// Use dateline
Pattern pDate = Pattern.compile(
"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)");
// If a month match has been found
Matcher m = pDate.matcher(sDate);
if (m.find()) {
// Get month substring
sMonth = sDate.substring(m.start(), m.end());
pDate = Pattern.compile("\\d+");
// If monthdate has been found
m = pDate.matcher(sDate);
if (m.find()) {
// read it
sMonthDay = sDate.substring(m.start(), m.end());
}
}
// Compose date in medium form
sFinalDate = sYear + " " + ((sMonth == null) ? sMonthNum : sMonth) +
" " + sMonthDay;
try {
String sFormat = (sMonth == null) ? "YYYY MM dd" : "YYYY MMM dd";
return new SimpleDateFormat(sFormat, new Locale("eng")
).parse(sFinalDate);
} catch (ParseException ex) {
Logger.getLogger(ACQUAINT2DocumentSet.class.getName()).log(Level.WARNING, null, ex);
}
return null;
}
/** Testing main function. */
public static void main(String[] sArgs) {
System.err.print("Parsing XML file...");
ACQUAINT2DocumentSet tds = new ACQUAINT2DocumentSet(
"/home/pckid/Documents/JApplications/JInsect/TAC2008/data/cna_eng/cna_eng_200410");
System.err.println("Done.");
System.err.print("Creating sets.");
tds.createSets();
System.err.println("Done.");
System.err.println("Determining categories...");
System.out.println(utils.printList(tds.getCategories(), " | "));
System.err.println("Determining categories...Done.");
System.err.println("File count per category...");
for (String sCategory : (List<String>)tds.getCategories())
System.out.println(String.format("%s : #%d", sCategory, tds.getFilesFromCategory(sCategory).size()));
System.err.println("File count per category...Done.");
System.out.println("First text per category...");
for (String sCategory : (List<String>)tds.getCategories()) {
System.out.println("\n===" + sCategory + "===");
System.out.println(tds.loadDocumentTextToString((String)tds.getFilesFromCategory(sCategory).get(0)));
String sDateline = tds.loadDocumentDatelineToString(
(String)tds.getFilesFromCategory(sCategory).get(0));
System.out.println(sDateline.length() == 0 ? "No dateline..." : "Dateline:\t" + sDateline);
}
System.out.println("File count per category...Done.");
System.err.println("Extracting dates...");
for (String sDocID : tds.toFilenameSet(ACQUAINT2DocumentSet.FROM_WHOLE_SET)) {
Date d = tds.getDocDate(sDocID);
System.out.println(String.format("%s : %s", sDocID, d != null ? d.toString() :
"No date found"));
}
System.err.println("Extracting dates...Done.");
}
/** Get a string list of all file names in the set or its training / test
* subsets.
*@param iSubset A value of either FROM_TRAINING_SET, FROM_TEST_SET,
* FROM_WHOLE_SET indicating the subset used to extract filenames.
*@return A {@link Set} of strings, that are the filenames of the files in the
*set.
*/
public Set<String> toFilenameSet(int iSubset) {
// Init set
HashSet s = new HashSet();
if ((iSubset & FROM_TRAINING_SET) > 0)
// For all training files
for (Object elem : getTrainingSet()) {
CategorizedFileEntry cfeCur = (CategorizedFileEntry)elem;
// Get name
s.add(cfeCur.getFileName());
}
if ((iSubset & FROM_TEST_SET) > 0)
// For all test files
for (Object elem : getTestSet()) {
CategorizedFileEntry cfeCur = (CategorizedFileEntry)elem;
// Get name
s.add(cfeCur.getFileName());
}
return s;
}
}
| 37.555249 | 113 | 0.609268 |
f0320e8c0b37a542edfdf96f382d49a62dc89cb7 | 2,620 | package com.projectd.colorfullife.view.game;
import android.graphics.Color;
import android.graphics.RectF;
import android.text.Layout.Alignment;
import com.projectd.colorfullife.R;
import com.projectd.colorfullife.CacheManager;
import com.projectd.colorfullife.DataManager;
import com.projectd.framework.WindowBase;
import com.projectd.framework.sprite.Sprite2D;
import com.projectd.framework.sprite.SpriteBatch;
import com.projectd.framework.sprite.SpriteButton;
import com.projectd.framework.sprite.TextField;
public class WindowItemInfo extends WindowBase {
Sprite2D bg;
Sprite2D windowBg;
Sprite2D itemIco;
TextField txtItemInfo;
public SpriteButton btnBack;
public SpriteButton btnConfirm;
public int itemIndex;
TextField txtItemName;
public WindowItemInfo(){
bg = new Sprite2D(CacheManager.black.texture,
new RectF(0, 0, 1024, 512),
new RectF(0, 0, 1, 1)
);
bg.alpha = 0.8f;
windowBg = new Sprite2D(CacheManager.getTextureById(R.drawable.ui_game), 0, 640, 432, 208);
windowBg.setLocation(288, 144);
btnBack = new SpriteButton(CacheManager.getTextureById(R.drawable.ui_game), 608, 640, 144, 80);
btnBack.setLocation(160,432);
btnConfirm = new SpriteButton(CacheManager.getTextureById(R.drawable.ui_game), 608, 720, 144, 80);
btnConfirm.setLocation(720,432);
itemIco = CacheManager.getEventIcoById(0, 128, 128);
itemIco.setLocation(310, 160);
txtItemInfo = new TextField("", 256, 128);
txtItemInfo.setColor(Color.BLACK);
txtItemInfo.setLocation(440, 200);
txtItemInfo.setAlign(Alignment.ALIGN_CENTER);
txtItemName = new TextField("", 256, 64);
txtItemName.setSize(26);
txtItemName.setColor(Color.BLACK);
txtItemName.setAlign(Alignment.ALIGN_CENTER);
txtItemName.setLocation(440, 158);
}
public void onDrawFrame(){
if(isOpening == false){
return;
}
SpriteBatch.draw(bg);
SpriteBatch.draw(windowBg);
SpriteBatch.draw(btnBack);
SpriteBatch.draw(btnConfirm);
SpriteBatch.draw(itemIco);
SpriteBatch.drawText(txtItemName);
SpriteBatch.drawText(txtItemInfo);
}
@Override
public void dispose() {
txtItemName.dispose();
txtItemInfo.dispose();
}
@Override
public void resume() {
txtItemName.resume();
txtItemInfo.resume();
}
public void open(int setItemIndex) {
isOpening = true;
itemIndex = setItemIndex;
int x = 128 * (DataManager.items.get(setItemIndex).spId % 16);
int y = 128 * (DataManager.items.get(setItemIndex).spId / 16);
itemIco.setSrcRectLocation(x, y);
txtItemInfo.text = DataManager.items.get(setItemIndex).info;
txtItemName.text = DataManager.items.get(setItemIndex).name;
}
}
| 28.791209 | 100 | 0.752672 |
121bd9dc8e3b2571c2f6e93cd5c8ef30c6b78e21 | 1,296 | package com.elepy.auth;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class Permissions {
public static final String SUPER_USER = "owner";
public static final String CAN_ADMINISTRATE_FILES = "files";
public static final String CAN_ADMINISTRATE_USERS = "users";
public static final String AUTHENTICATED = "authenticated";
public static final String[] NONE = new String[]{};
public static final String[] DEFAULT = new String[]{AUTHENTICATED};
private final Set<String> grantedPermissions = new TreeSet<>();
public void addPermissions(String... permissions) {
addPermissions(Arrays.asList(permissions));
}
public void addPermissions(Collection<String> permissions) {
this.grantedPermissions.addAll(permissions);
}
public boolean hasPermissions(Collection<String> permissionsToCheck) {
if (grantedPermissions.contains(SUPER_USER) || permissionsToCheck.isEmpty()) {
return true;
}
return (grantedPermissions.stream().map(String::toLowerCase).collect(Collectors.toSet())
.containsAll(permissionsToCheck.stream().map(String::toLowerCase).collect(Collectors.toSet())));
}
}
| 33.230769 | 112 | 0.716049 |
70d12f90304b710b2b3a5a5c88dfaa0304678d63 | 6,636 | package edu.indiana.soic.spidal.damds.timing;
import com.google.common.base.Stopwatch;
import edu.indiana.soic.spidal.damds.ParallelOps;
import mpi.MPIException;
import java.nio.LongBuffer;
import java.util.Arrays;
import java.util.OptionalLong;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class MMTimings {
public enum TimingTask{
MM_INTERNAL,COMM, MM_MERGE, MM_EXTRACT
}
private Stopwatch timerMMInternal = Stopwatch.createUnstarted();
private Stopwatch timerComm = Stopwatch.createUnstarted();
private Stopwatch timerMMMerge = Stopwatch.createUnstarted();
private Stopwatch timerMMExtract = Stopwatch.createUnstarted();
private long tMMInternal;
private long tComm;
private long tMMMerge;
private long tMMExtract;
private long countMMInternal;
private long countComm;
private long countMMMerge;
private long countMMExtract;
public void startTiming(TimingTask task){
switch (task){
case MM_INTERNAL:
timerMMInternal.start();
++countMMInternal;
break;
case COMM:
timerComm.start();
++countComm;
break;
case MM_MERGE:
timerMMMerge.start();
++countMMMerge;
break;
case MM_EXTRACT:
timerMMExtract.start();
++countMMExtract;
break;
}
}
public void endTiming(TimingTask task){
switch (task){
case MM_INTERNAL:
timerMMInternal.stop();
tMMInternal += timerMMInternal.elapsed(
TimeUnit.MILLISECONDS);
timerMMInternal.reset();
break;
case COMM:
timerComm.stop();
tComm += timerComm.elapsed(TimeUnit.MILLISECONDS);
timerComm.reset();
break;
case MM_MERGE:
timerMMMerge.stop();
tMMMerge += timerMMMerge.elapsed(TimeUnit.MILLISECONDS);
timerMMMerge.reset();
break;
case MM_EXTRACT:
timerMMExtract.stop();
tMMExtract += timerMMExtract.elapsed(TimeUnit.MILLISECONDS);
timerMMExtract.reset();
break;
}
}
public double getTotalTime(TimingTask task){
switch (task){
case MM_INTERNAL:
return tMMInternal;
case COMM:
return tComm;
case MM_MERGE:
return tMMMerge;
case MM_EXTRACT:
return tMMExtract;
}
return 0.0;
}
public double getAverageTime(TimingTask task){
switch (task){
case MM_INTERNAL:
return tMMInternal * 1.0/ countMMInternal;
case COMM:
return tComm *1.0/ countComm;
case MM_MERGE:
return tMMMerge * 1.0 / countMMMerge;
case MM_EXTRACT:
return tMMExtract * 1.0 / countMMExtract;
}
return 0.0;
}
/*public long[] getTotalTimeDistribution(TimingTask task)
throws MPIException {
LongBuffer threadsAndMPITimingBuffer =
ParallelOps.threadsAndMPIBuffer;
LongBuffer mpiOnlyTimingBuffer = ParallelOps.mpiOnlyBuffer;
threadsAndMPITimingBuffer.position(0);
mpiOnlyTimingBuffer.position(0);
long [] threadsAndMPITimingArray = new long[numThreads * ParallelOps.worldProcsCount];
long [] mpiOnlyTimingArray = new long[ParallelOps.worldProcsCount];
switch (task){
case MM_INTERNAL:
threadsAndMPITimingBuffer.put(tMMInternal);
ParallelOps.gather(threadsAndMPITimingBuffer, numThreads, 0);
threadsAndMPITimingBuffer.position(0);
threadsAndMPITimingBuffer.get(threadsAndMPITimingArray);
return threadsAndMPITimingArray;
case COMM:
mpiOnlyTimingBuffer.put(tComm);
ParallelOps.gather(mpiOnlyTimingBuffer, 1, 0);
mpiOnlyTimingBuffer.position(0);
mpiOnlyTimingBuffer.get(mpiOnlyTimingArray);
return mpiOnlyTimingArray;
case MM_MERGE:
mpiOnlyTimingBuffer.put(tMMMerge);
ParallelOps.gather(mpiOnlyTimingBuffer, 1, 0);
mpiOnlyTimingBuffer.position(0);
mpiOnlyTimingBuffer.get(mpiOnlyTimingArray);
return mpiOnlyTimingArray;
case MM_EXTRACT:
mpiOnlyTimingBuffer.put(tMMExtract);
ParallelOps.gather(mpiOnlyTimingBuffer, 1, 0);
mpiOnlyTimingBuffer.position(0);
mpiOnlyTimingBuffer.get(mpiOnlyTimingArray);
return mpiOnlyTimingArray;
}
return null;
}*/
/*public long[] getCountDistribution(TimingTask task)
throws MPIException {
LongBuffer threadsAndMPIBuffer =
ParallelOps.threadsAndMPIBuffer;
LongBuffer mpiOnlyBuffer = ParallelOps.mpiOnlyBuffer;
threadsAndMPIBuffer.position(0);
mpiOnlyBuffer.position(0);
long [] threadsAndMPIArray = new long[numThreads * ParallelOps.worldProcsCount];
long [] mpiOnlyArray = new long[ParallelOps.worldProcsCount];
switch (task){
case MM_INTERNAL:
threadsAndMPIBuffer.put(countMMInternal);
ParallelOps.gather(threadsAndMPIBuffer, numThreads, 0);
threadsAndMPIBuffer.position(0);
threadsAndMPIBuffer.get(threadsAndMPIArray);
return threadsAndMPIArray;
case COMM:
mpiOnlyBuffer.put(countComm);
ParallelOps.gather(mpiOnlyBuffer, 1, 0);
mpiOnlyBuffer.position(0);
mpiOnlyBuffer.get(mpiOnlyArray);
return mpiOnlyArray;
case MM_MERGE:
mpiOnlyBuffer.put(countMMMerge);
ParallelOps.gather(mpiOnlyBuffer, 1, 0);
mpiOnlyBuffer.position(0);
mpiOnlyBuffer.get(mpiOnlyArray);
return mpiOnlyArray;
case MM_EXTRACT:
mpiOnlyBuffer.put(countMMExtract);
ParallelOps.gather(mpiOnlyBuffer, 1, 0);
mpiOnlyBuffer.position(0);
mpiOnlyBuffer.get(mpiOnlyArray);
return mpiOnlyArray;
}
return null;
}*/
}
| 35.111111 | 94 | 0.582881 |
b9dc3067ecb9e2dc0876d177c75b98969ef4191b | 10,365 | package com.jthink.shop.facade;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.jthink.cms.entity.Post;
import com.jthink.cms.service.PostService;
import com.jthink.member.entity.Member;
import com.jthink.shop.entity.CartItem;
import com.jthink.shop.entity.Coupon;
import com.jthink.shop.entity.CouponMember;
import com.jthink.shop.entity.MemberAddress;
import com.jthink.shop.entity.MemberOrder;
import com.jthink.shop.entity.OrderItem;
import com.jthink.shop.entity.ProductSku;
import com.jthink.shop.service.CouponMemberService;
import com.jthink.shop.service.MemberOrderService;
import com.jthink.shop.service.OrderItemService;
import com.jthink.shop.service.ProductSkuService;
import com.jthink.utils.OrderNumUtil;
import cn.hutool.core.date.DateUtil;
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class OrderFacade {
@Autowired
private CouponMemberService couponMemberService;
@Autowired
private MemberOrderService orderService;
@Autowired
private OrderItemService orderItemService;
@Autowired
private PostService productService;
@Autowired
private ProductSkuService productSkuService;
public int saveOrder(MemberOrder order, Coupon coupon, Member member, MemberAddress address, List<CartItem> items,
CouponMember couponUser) throws Exception {
// 生成订单
String nsNumber = new OrderNumUtil(2, 3).nextId();
order.setNs(nsNumber);
order.setBuyerId(member.getId());
order.setBuyerNickname(member.getUsername());
order.setCreateTime(new Date());
order.setUpdateTime(new Date());
order.setPayStatus(1);
order.setTradeStatus(1);
order.setInvoiceStatus(1);
order.setDeliveryAddrProvince(address.getProvince());
order.setDeliveryAddrCity(address.getCity());
order.setDeliveryAddrDistrict(address.getDistricts());
order.setDeliveryAddrDetail(address.getAddrDetails());
order.setDeliveryAddrZipcode(address.getZipcode());
order.setDeliveryAddrUsername(address.getContactName());
order.setDeliveryAddrMobile(address.getContactMobile());
String summary = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm") +" "+ member.getUsername() + " 生成订单 \n <br/>";
order.setOrderSummary(summary);
orderService.save(order);
BigDecimal totalFee = new BigDecimal(0);
StringBuffer buff = new StringBuffer();
// 遍历购物车
for (CartItem item : items) {
Post product = productService.selectByKey(item.getProductId());
if (null == product) {
throw new Exception(item.getProductName() + "-购物车信息有误,请移除后重新下单");
}
if (null == product.getStocks() || item.getQuantity() > product.getStocks()) {
throw new Exception(item.getProductName() + "-库存不足,请移除后重新下单");
} else {
// 减库存
product.setStocks(product.getStocks() - item.getQuantity());
productService.updateNotNull(product);
}
OrderItem orderItem = new OrderItem();
orderItem.setOrderId(order.getId());
orderItem.setOrderNs(nsNumber);
orderItem.setProductTitle(item.getProductName());
orderItem.setProductId(item.getProductId());
orderItem.setBuyerId(member.getId());
orderItem.setBuyerNickname(member.getUsername());
orderItem.setProductCount(item.getQuantity());
orderItem.setProductPrice(product.getPrice());
orderItem.setProductType("product");
orderItem.setProductTypeText("产品");
BigDecimal itemFee = orderItem.getProductPrice().multiply(new BigDecimal(orderItem.getProductCount()));
orderItem.setTotalAmount(itemFee.setScale(2, RoundingMode.HALF_UP));
totalFee = totalFee.add(itemFee);
buff.append(item.getProductName() + " ");
orderItemService.save(orderItem);
// 更新销量
productService.updateAddSaleCount(item.getQuantity(), item.getProductId());
}
order.setOrderTitle(buff.toString());
BigDecimal totalHalf = totalFee.setScale(2, RoundingMode.HALF_UP);
// 运费计算(大于200名运费,默认10元运费)
BigDecimal deliveryFee = new BigDecimal("10");
if (totalHalf.compareTo(new BigDecimal(200)) == 1) {
deliveryFee = new BigDecimal("0");
}
order.setOrderTotalAmount(totalHalf.add(deliveryFee));
order.setCouponAmount(new BigDecimal(0));
order.setDeliveryFee(deliveryFee);
boolean hasMin = false;
Integer type = coupon == null ? null : coupon.getType();
if (null != type) {
hasMin = type == 1 ? true : false;
}
if ((hasMin && totalHalf.compareTo(coupon.getWithAmount()) < 0)) {
throw new Exception("优惠券金额未达到");
}
if (hasMin && totalHalf.compareTo(coupon.getWithAmount()) >= 0) {
couponUser.setCouStatus(2);
couponUser.setOrderNs(nsNumber);
couponUser.setUsedOrderId(order.getId());
couponUser.setUseTime(new Date());
couponMemberService.updateNotNull(couponUser);
order.setCouponUserId(couponUser.getId());
order.setCouponAmount(coupon.getAmount());
// 有门槛,判断是否符合门槛
order.setOrderRealAmount(totalHalf.subtract(coupon.getAmount()).add(deliveryFee));
} else if (hasMin == false && null != type) {
couponUser.setCouStatus(2);
couponUser.setOrderNs(nsNumber);
couponUser.setUsedOrderId(order.getId());
couponUser.setUseTime(new Date());
couponMemberService.updateNotNull(couponUser);
order.setCouponUserId(couponUser.getId());
order.setCouponAmount(coupon.getAmount());
BigDecimal realAmount = totalHalf.compareTo(coupon.getAmount()) < 0 ? new BigDecimal(0)
: totalHalf.subtract(coupon.getAmount());
// 无门槛,直接减
order.setOrderRealAmount(realAmount.add(deliveryFee));
} else {
// 没券直接和总价相等
order.setOrderRealAmount(totalHalf.add(deliveryFee));
}
orderService.updateNotNull(order);
return 1;
}
public int saveSkuOrder(MemberOrder order, Coupon coupon, Member member, MemberAddress address,
List<CartItem> items, CouponMember couponUser) throws Exception {
// 生成订单
String nsNumber = new OrderNumUtil(2, 3).nextId();
order.setNs(nsNumber);
order.setBuyerId(member.getId());
order.setBuyerNickname(member.getUsername());
order.setCreateTime(new Date());
order.setUpdateTime(new Date());
order.setPayStatus(1);
order.setTradeStatus(1);
order.setInvoiceStatus(1);
order.setDeliveryAddrProvince(address.getProvince());
order.setDeliveryAddrCity(address.getCity());
order.setDeliveryAddrDistrict(address.getDistricts());
order.setDeliveryAddrDetail(address.getAddrDetails());
order.setDeliveryAddrZipcode(address.getZipcode());
order.setDeliveryAddrUsername(address.getContactName());
order.setDeliveryAddrMobile(address.getContactMobile());
String summary = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm") + " "+member.getUsername() + " 生成订单 \n <br/>";
order.setOrderSummary(summary);
orderService.save(order);
BigDecimal totalFee = new BigDecimal(0);
StringBuffer buff = new StringBuffer();
// 遍历购物车
for (CartItem item : items) {
Post product = productService.selectByKey(item.getProductId());
ProductSku sku = productSkuService.getSku(item.getProductId(), item.getSpuvalIds());
if (null == sku) {
throw new Exception("商品规格有误");
}
if (null == product) {
throw new Exception(item.getProductName() + "-购物车信息有误,请移除后重新下单");
}
if (null == sku.getStock() || sku.getStock() <= 0 || item.getQuantity() > sku.getStock()) {
throw new Exception(item.getProductName() + "-库存不足,请移除后重新下单");
} else {
// 减库存
productSkuService.updateStock(sku.getId(), sku.getStock() - item.getQuantity());
}
OrderItem orderItem = new OrderItem();
orderItem.setOrderId(order.getId());
orderItem.setOrderNs(nsNumber);
orderItem.setProductTitle(item.getProductName());
orderItem.setProductId(item.getProductId());
orderItem.setBuyerId(member.getId());
orderItem.setBuyerNickname(member.getUsername());
orderItem.setProductCount(item.getQuantity());
orderItem.setProductPrice(product.getPrice());
orderItem.setProductType("product");
orderItem.setProductTypeText("产品");
BigDecimal itemFee = orderItem.getProductPrice().multiply(new BigDecimal(orderItem.getProductCount()));
orderItem.setTotalAmount(itemFee.setScale(2, RoundingMode.HALF_UP));
totalFee = totalFee.add(itemFee);
buff.append(item.getProductName() + " ");
orderItemService.save(orderItem);
// 更新销量
productService.updateAddSaleCount(item.getQuantity(), item.getProductId());
}
order.setOrderTitle(buff.toString());
BigDecimal totalHalf = totalFee.setScale(2, RoundingMode.HALF_UP);
// 运费计算(大于200名运费,默认10元运费)
BigDecimal deliveryFee = new BigDecimal("10");
if (totalHalf.compareTo(new BigDecimal(200)) == 1) {
deliveryFee = new BigDecimal("0");
}
order.setOrderTotalAmount(totalHalf.add(deliveryFee));
order.setCouponAmount(new BigDecimal(0));
order.setDeliveryFee(deliveryFee);
boolean hasMin = false;
Integer type = coupon == null ? null : coupon.getType();
if (null != type) {
hasMin = type == 1 ? true : false;
}
if ((hasMin && totalHalf.compareTo(coupon.getWithAmount()) < 0)) {
throw new Exception("优惠券金额未达到");
}
if (hasMin && totalHalf.compareTo(coupon.getWithAmount()) >= 0) {
couponUser.setCouStatus(2);
couponUser.setOrderNs(nsNumber);
couponUser.setUsedOrderId(order.getId());
couponUser.setUseTime(new Date());
couponMemberService.updateNotNull(couponUser);
order.setCouponUserId(couponUser.getId());
order.setCouponAmount(coupon.getAmount());
// 有门槛,判断是否符合门槛
order.setOrderRealAmount(totalHalf.subtract(coupon.getAmount()).add(deliveryFee));
} else if (hasMin == false && null != type) {
couponUser.setCouStatus(2);
couponUser.setOrderNs(nsNumber);
couponUser.setUsedOrderId(order.getId());
couponUser.setUseTime(new Date());
couponMemberService.updateNotNull(couponUser);
order.setCouponUserId(couponUser.getId());
order.setCouponAmount(coupon.getAmount());
BigDecimal realAmount = totalHalf.compareTo(coupon.getAmount()) < 0 ? new BigDecimal(0)
: totalHalf.subtract(coupon.getAmount());
// 无门槛,直接减
order.setOrderRealAmount(realAmount.add(deliveryFee));
} else {
// 没券直接和总价相等
order.setOrderRealAmount(totalHalf.add(deliveryFee));
}
orderService.updateNotNull(order);
return 1;
}
}
| 39.261364 | 135 | 0.744139 |
ce8586a709c89e56262bdadbd0dc13369a7a4c23 | 1,216 | package com.lab.nosql.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import java.util.List;
@Aspect
@Component
public class ValidAOP {
// 定义切点
private final String POINT_CUT = "execution( * com.lab.nosql..controller.*.*(..))";
@Pointcut(value = POINT_CUT)
public void pointCut() {
}
@Around(value = "pointCut() && args(.., bindingResult)")
public Object around(ProceedingJoinPoint proceedingJoinPoint, BindingResult bindingResult) throws Throwable {
Object obj = null;
if (bindingResult.hasErrors()) {
List<ObjectError> errors = bindingResult.getAllErrors();
StringBuffer sb = new StringBuffer();
for (ObjectError error : errors) {
sb.append(error.getDefaultMessage() + "\n");
}
obj = sb.toString();
} else {
obj = proceedingJoinPoint.proceed();
}
return obj;
}
}
| 31.179487 | 113 | 0.669408 |
695b3c378976632ef351dc4180172139d9e14d3c | 9,677 | package com.elong.pb.newdda.client.router.parser;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.visitor.SQLEvalVisitor;
import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils;
import com.alibaba.druid.util.JdbcUtils;
import com.elong.pb.newdda.client.constants.DatabaseType;
import com.elong.pb.newdda.client.router.parser.visitor.basic.mysql.MySqlEvalVisitor;
import com.elong.pb.newdda.client.router.result.router.*;
import com.elong.pb.newdda.client.util.SqlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 解析的上下文
* Created by zhangyong on 2016/8/18.
*/
public class SqlParserContext {
private final static Logger logger = LoggerFactory.getLogger(SqlParserContext.class);
private RouterTable currentRouterTable;
private boolean hasOrCondition = false;
private final ConditionContext currentConditionContext = new ConditionContext();
private final SqlParserResult sqlParserResult = new SqlParserResult();
public void setCurrentTable(final String currentTableName, final String currentAlias) {
String exactlyAlias = SqlUtil.getExactlyValue(currentAlias);
String exactlyTableName = SqlUtil.getExactlyValue(currentTableName);
RouterTable routerTable = new RouterTable(exactlyTableName, exactlyAlias);
sqlParserResult.getRouteContext().getRouterTables().add(routerTable);
this.currentRouterTable = routerTable;
}
public void addCondition(final SQLExpr expr, final BinaryOperator operator, final List<SQLExpr> valueExprList, final DatabaseType databaseType, final List<Object> paramters) {
RouterColumn routerColumn = getRouterColumn(expr);
if (routerColumn == null) {
return;
}
List<ValuePair> values = new ArrayList<ValuePair>(valueExprList.size());
for (SQLExpr each : valueExprList) {
ValuePair evalValue = evalExpression(databaseType, each, paramters);
if (null != evalValue) {
values.add(evalValue);
}
}
if (values.isEmpty()) {
return;
}
addCondition(routerColumn, operator, values);
}
public void addCondition(final String columnName, final String tableName, final BinaryOperator operator, final SQLExpr valueExpr, final DatabaseType databaseType, final List<Object> parameters) {
RouterColumn column = createColumn(columnName, tableName);
ValuePair value = evalExpression(databaseType, valueExpr, parameters);
if (null != value) {
addCondition(column, operator, Collections.singletonList(value));
}
}
public RouterTable addTable(final SQLExprTableSource x) {
String tableName = SqlUtil.getExactlyValue(x.getExpr().toString());
String alias = SqlUtil.getExactlyValue(x.getAlias());
RouterTable result = new RouterTable(tableName, alias);
sqlParserResult.getRouteContext().getRouterTables().add(result);
return result;
}
/**
* 判断SQL表达式是否为二元操作且带有别名.
*
* @param x 待判断的SQL表达式
* @param tableOrAliasName 表名称或别名
* @return 是否为二元操作且带有别名
*/
public boolean isBinaryOperateWithAlias(final SQLPropertyExpr x, final String tableOrAliasName) {
RouterTable routerTable = findTableFromAlias(SqlUtil.getExactlyValue(tableOrAliasName));
if (routerTable == null) {
return false;
}
return (x.getParent() instanceof SQLBinaryOpExpr);
}
/**
* 将当前解析的条件对象归并入解析结果
*/
public void mergeCurrentConditionContext() {
if (!sqlParserResult.getRouteContext().getRouterTables().isEmpty()) {
if (sqlParserResult.getConditionContexts().isEmpty()) {
sqlParserResult.getConditionContexts().add(currentConditionContext);
}
return;
}
//是否需要解析子解析上下文?不太能理解
}
//=========================================================== private method start ==========================================================
private RouterColumn getRouterColumn(final SQLExpr expr) {
if (expr instanceof SQLPropertyExpr) {
return getColumnWithQualifiedName((SQLPropertyExpr) expr);
}
if (expr instanceof SQLIdentifierExpr) {
return getColumnWithoutAlias((SQLIdentifierExpr) expr);
}
return null;
}
private RouterColumn getColumnWithQualifiedName(final SQLPropertyExpr expr) {
String aliasName = ((SQLIdentifierExpr) expr.getOwner()).getName();
RouterTable routerTable = findTable(aliasName);
if (routerTable == null) {
return null;
}
RouterColumn routerColumn = createColumn(expr.getName(), routerTable.getName());
return routerColumn;
}
private RouterColumn getColumnWithoutAlias(final SQLIdentifierExpr expr) {
return (null != currentRouterTable) ? createColumn(expr.getName(), currentRouterTable.getName()) : null;
}
private RouterTable findTableFromName(final String name) {
for (RouterTable each : sqlParserResult.getRouteContext().getRouterTables()) {
if (each.getName().equalsIgnoreCase(SqlUtil.getExactlyValue(name))) {
return each;
}
}
return null;
}
private RouterTable findTableFromAlias(final String alias) {
for (RouterTable each : sqlParserResult.getRouteContext().getRouterTables()) {
if (each.getAlias() != null && each.getAlias().equalsIgnoreCase(SqlUtil.getExactlyValue(alias))) {
return each;
}
}
return null;
}
private RouterTable findTable(final String tableNameOrAlias) {
RouterTable routerTable = findTableFromName(tableNameOrAlias);
return routerTable == null ?
findTableFromAlias(tableNameOrAlias) :
routerTable;
}
private RouterColumn createColumn(final String columnName, final String tableName) {
return new RouterColumn(
SqlUtil.getExactlyValue(columnName),
SqlUtil.getExactlyValue(tableName)
);
}
private ValuePair evalExpression(final DatabaseType databaseType, final SQLObject sqlObject, final List<Object> parameters) {
if (sqlObject instanceof SQLMethodInvokeExpr) {
// TODO 解析函数中的sharingValue不支持
return null;
}
SQLEvalVisitor visitor;
if (JdbcUtils.MYSQL.equals(databaseType.name().toLowerCase()) || JdbcUtils.H2.equals(databaseType.name().toLowerCase())) {
visitor = new MySqlEvalVisitor();
} else {
visitor = SQLEvalVisitorUtils.createEvalVisitor(databaseType.name());
}
visitor.setParameters(parameters);
sqlObject.accept(visitor);
Object value = SQLEvalVisitorUtils.getValue(sqlObject);
if (null == value) {
// TODO 对于NULL目前解析为空字符串,此处待考虑解决方法
return null;
}
Comparable<?> finalValue;
if (value instanceof Comparable<?>) {
finalValue = (Comparable<?>) value;
} else {
finalValue = "";
}
Integer index = (Integer) sqlObject.getAttribute(MySqlEvalVisitor.EVAL_VAR_INDEX);
if (null == index) {
index = -1;
}
return new ValuePair(finalValue, index);
}
private void addCondition(final RouterColumn routerColumn, final BinaryOperator operator, final List<ValuePair> valuePairs) {
RouterCondition routerCondition = currentConditionContext.find(routerColumn.getTableName(), routerColumn.getColumnName(), operator);
if (routerCondition == null) {
routerCondition = new RouterCondition(routerColumn, operator);
currentConditionContext.add(routerCondition);
}
for (ValuePair each : valuePairs) {
routerCondition.getValues().add(each.value);
if (each.paramIndex > -1) {
routerCondition.getValueIndices().add(each.paramIndex);
}
}
}
//=========================================================== private method end =======================================================
//============================================================set get method start =====================================================
public SqlParserResult getSqlParsedResult() {
return this.sqlParserResult;
}
public boolean isHasOrCondition() {
return hasOrCondition;
}
public void setHasOrCondition(boolean hasOrCondition) {
this.hasOrCondition = hasOrCondition;
}
//============================================================set get method end ==========================================================
private static class ValuePair {
private final Comparable<?> value;
private final Integer paramIndex;
public ValuePair(Comparable<?> value, Integer paramIndex) {
this.value = value;
this.paramIndex = paramIndex;
}
public Comparable<?> getValue() {
return value;
}
public Integer getParamIndex() {
return paramIndex;
}
}
}
| 38.249012 | 199 | 0.634597 |
74f2ad2935257f39396535ddde868ec97b6f51a8 | 19,495 | package team1.PageRankScoringFilterPlugin;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;
import edu.uci.ics.jung.algorithms.scoring.PageRank;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.graph.util.EdgeType;
public class PageRankAlgorithm {
private enum MetadataTypes {GUN_CATEGORIES, GEOGRAPHIC, TEMPORAL};
// private String solrUrl = "http://localhost:8983/solr/memexcollection/select?q=*%3A*&rows=151680&wt=json&indent=true";
private static final String JSON_FILE_PATH = "/Users/redshepherd/Documents/assignment2/PAgeRankScoringFilter/src/main/java/team1/PAgeRankScoringFilter/nutch1000.json";
//values which can override default values for pagerank algorithm
private int maxIterations;
//private double tolerance;
private double alpha;
public PageRankAlgorithm(int maxIterations, double tolerance, double alpha) {
this.maxIterations = maxIterations;
//this.tolerance = tolerance;
this.alpha = alpha;
}
/**
* ================================================================================
* ****************Create Directed Graph for MetaData*****************************
* ================================================================================
* Based upon below logic : Add a directed edge between Nodes
* 1. Get the metadata list and check all metadatas in each document.
* 2. Maintain a hashmap <Integer,List<Node>>. Integer is count of meta data matches and List will contain all nodes with same count.
* 3. Sort hashmap in desc order of count. Create a directed edge between nodes between each level to all levels up
* eg. 10 - {A, B, C, D}; 9 - {E, F, G}; 8 - {H, I, J}, 7 - {K, L, M}
* Then directed edge between :
* E -> A, E -> B, E -> C, E -> D, F -> A etc
*
*/
private DirectedSparseGraph<String, Integer> createDirectedGraph (List<Node> nodesForGraph,
Map<Integer, List<String>> nodeHierarchyMap) {
long start = System.currentTimeMillis();
int edgeCnt = 0;
DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();
//Add all Nodes to Graph
for(Node n : nodesForGraph){
graph.addVertex(n.getId());
}
//Create Directed Edges between the Nodes from nodeHierarchyMap
List<Integer> mapKeys = new LinkedList<Integer>();
mapKeys.addAll(nodeHierarchyMap.keySet());
Collections.sort(mapKeys);
// System.out.println(mapKeys);
System.out.println(nodeHierarchyMap.size());
for(int i=0; i < mapKeys.size(); i++) {
Integer startKey = mapKeys.get(i);
List<String> startNodes = nodeHierarchyMap.get(startKey);
//System.out.println("start nodes - " + i + " : "+startNodes.size());
//int level = 0;
for(int j=i+1; j < mapKeys.size(); j++){
Integer endKey = mapKeys.get(j);
List<String> endNodes = nodeHierarchyMap.get(endKey);
//System.out.println("end nodes - " + j + " : "+endNodes.size());
//System.out.println(startKey + " -> " + endKey);
for(String startNode : startNodes) {
for(String endNode : endNodes) {
//Create a directed edge between StartNode and EndNode
graph.addEdge(edgeCnt++, startNode, endNode, EdgeType.DIRECTED);
}
}
//break; //only 1 level
/*level++;
if(level == 3){ //check diff levels
break;
}*/
}
}
System.out.println(String.format("Loaded %d nodes and %d links in %d ms", graph.getVertexCount(), graph.getEdgeCount(), (System.currentTimeMillis()-start)));
return graph;
}
private Map<Integer, List<String>> createHirarchyMapForDirectedGraph (String metaData,
List<Node> nodesForGraph, MetadataTypes metadataType) {
Map<Integer, List<String>> nodeHierarchyMap = new HashMap<Integer, List<String>>();
String[] metaDatas = metaData.split(",");
//For each node, check how many metadata matches
for(Node node : nodesForGraph){
int matchCount = 0;
for(String meta : metaDatas) {
//Depending upon MetaDataType Check in specific attribute of Node
if(metadataType.equals(MetadataTypes.GUN_CATEGORIES)) {
//GUN_CATEGORIES => check (title, keywords, content)
matchCount += StringUtils.countMatches(node.getTitle().toLowerCase(), meta.trim().toLowerCase());
matchCount += StringUtils.countMatches(node.getKeywords().toLowerCase(), meta.trim().toLowerCase());
matchCount += StringUtils.countMatches(node.getContent().toLowerCase(), meta.trim().toLowerCase());
} else if(metadataType.equals(MetadataTypes.GEOGRAPHIC)) {
//Geographic => check (title, availableFrom, content, Geographical_Name_State)
matchCount += StringUtils.countMatches(node.getTitle().toLowerCase(), meta.trim().toLowerCase());
matchCount += StringUtils.countMatches(node.getAvailableFrom().toLowerCase(), meta.trim().toLowerCase());
matchCount += StringUtils.countMatches(node.getContent().toLowerCase(), meta.trim().toLowerCase());
matchCount += StringUtils.countMatches(node.getGeographical_Name_State().toLowerCase(), meta.trim().toLowerCase());
} else if(metadataType.equals(MetadataTypes.TEMPORAL)) {
//Temporal => check in (buyerStartDate, sellerStartDate)
matchCount += StringUtils.countMatches(node.getBuyerStartDate().toLowerCase(), meta.trim().toLowerCase());
matchCount += StringUtils.countMatches(node.getSellerStartDate().toLowerCase(), meta.trim().toLowerCase());
}
}
//Populate nodeHierarchyMap used to create the directed graph structure
if(nodeHierarchyMap.containsKey(matchCount)) {
List<String> list = nodeHierarchyMap.get(matchCount);
list.add(node.getId());
nodeHierarchyMap.put(matchCount, list);
}else {
List<String> list = new ArrayList<String>();
list.add(node.getId());
nodeHierarchyMap.put(matchCount, list);
}
}//end loop
//System.out.println(nodeHierarchyMap);
return nodeHierarchyMap;
}
public Map<String, Double> compute(DirectedSparseGraph<String, Integer> graph) {
long start = System.currentTimeMillis() ;
PageRank<String, Integer> ranker = new PageRank<String, Integer>(graph, alpha);
//ranker.setTolerance(this.tolerance) ;
ranker.setMaxIterations(this.maxIterations);
ranker.evaluate();
System.out.println ("Tolerance = " + ranker.getTolerance() );
System.out.println ("Dump factor = " + (1.00d - ranker.getAlpha() ) ) ;
System.out.println ("Max iterations = " + ranker.getMaxIterations() ) ;
System.out.println ("PageRank computed in " + (System.currentTimeMillis()-start) + " ms");
Map<String, Double> result = new HashMap<String, Double>();
for (String n : graph.getVertices()) {
result.put(n, ranker.getVertexScore(n));
}
return result;
}
/**
* ==============================================================================================
* *********************************** UTILITY METHODS ****************************************
* ==============================================================================================
*/
private String getDocumentJSONFromSolrRest(){
String output = "";
StringBuilder sb = new StringBuilder();
try {
URL url = new URL("http://10.120.121.140:8983/solr/memexcollection/select?q=*%3A*&rows=1000&wt=json&indent=true");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("output" + sb.toString());
return sb.toString();
}
/**
* Load the documents from Solr.
* Two options :
* 1. Do REST call to Solr and get the documents from json response
* 2. Save the Solr Json reponse to local file and read data from file
*/
/**
from urllib2 import *
import simplejson
import json
conn = urlopen('http://localhost:8983/solr/memexcollection/select?q=*%3A*&rows=25000&wt=json&indent=true')
rsp = simplejson.load(conn)
f = open('workfile', 'w')
json.dump(rsp, f)
*
*/
private List<Node> loadDocumentsFromSolr() {
File file = new File(JSON_FILE_PATH);
List<Node> nodesForGraph = new ArrayList<Node>();
//create ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode rootNode = mapper.readTree(file);
JsonNode responseNode = rootNode.path("response");
JsonNode documents = responseNode.path("docs");
Iterator<JsonNode> elements = documents.elements();
int i=0;
while(elements.hasNext()){
JsonNode document = elements.next();
//System.out.println(document.has("content1"));
//System.out.println(document.path("_version_").asText());
/**
* Map json document to Node object and add Node to nodesForGraph list
*/
Node node = mapJSONDocumentToNode(document);
//System.out.println(node);
nodesForGraph.add(node);
i++;
}
System.out.println(i);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return nodesForGraph;
}
/**
* Map JSON document to Node object. Convert values to appropriate datatype and these
* Nodes will be used later for graph creation and computing page rank.
* @param document
* @return
*/
private Node mapJSONDocumentToNode(JsonNode document){
Node node = new Node();
node.setId(document.path("id").asText());
node.setSiteName(document.path("siteName").asText());
node.setImages(document.path("images").asText());
node.setKeywords(document.path("keywords").asText());
node.setTitle(document.path("title").asText());
node.setContent(document.path("content").asText());
node.setPrice(document.path("price").asDouble());
node.setCategory(document.path("category").asText());
//dummy value is -9999.0
node.setGeographical_Latitude(document.path("Geographical_Latitude").asDouble());
//dummy value is -9999.0
node.setGeographical_Latitude(document.path("Geographical_Longitude").asDouble());
node.setGeographical_Name_State(document.path("Geographical_Name_State").asText());
node.setGeographical_Name(document.path("Geographical_Name").asText());
node.setAvailableFrom(document.path("availableFrom").asText());
node.setSellerContentDescription(document.path("sellerContentDescription").asText());
node.setSellerContactName(document.path("sellerContactName").asText());
node.setSellerTelephoneNumber(document.path("sellerTelephoneNumber").asText());
node.setSellerUrl(document.path("sellerUrl").asText());
node.setSellerStartDate(document.path("sellerStartDate").asText());
node.setSellerType(document.path("sellerType").asText());
node.setBuyerDescription(document.path("buyerDescription").asText());
node.setBuyerStartDate(document.path("buyerStartDate").asText());
node.setBuyerType(document.path("buyerType").asText());
node.setBuyerOrgName(document.path("buyerOrgName").asText());
node.setPage_rank(document.path("page_rank").asDouble());
node.setVersion(document.path("_version_").asText());
return node;
}
private static Double getMaxPageRank(Double categoryPG, Double geographicPG, Double temporalPG){
Double finalPG = categoryPG;
if(geographicPG > finalPG){
finalPG = geographicPG;
}else if(temporalPG > finalPG){
finalPG = temporalPG;
}
return finalPG * 100;
}
public Map<String,Double> getFinalPageRankMap(){
//Load Solr JSON documents from and create List of Nodes for Graph
List<Node> nodesForGraph = loadDocumentsFromSolr();
//Node List is populated now. So create directed graph based on meta-data features extracted by NER
String metaCategories = "Handguns,Pistols,Semi-automatic,Machine,Revolvers,Revolver,Derringers,"
+ "Rifles,Rifle,Shotguns,Shotgun,Long,Shoulder,Guns,Gun,Cannons,Tactical,Luger,Double,Single,"
+ "Action,ACP,Bolt,Striker,Fire,6.8mm,9mm,45mm,Gauge,Magnum,Colt,Pump";
String metaGeographic = "Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Florida, Georgia, "
+ "Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Massachusetts, Michigan, "
+ "Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, "
+ "New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, "
+ "South Carolina, South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, Washington, "
+ "D.C., Wisconsin";
String metaTemporal = "January, February, March, April, May, June, July, August, September, October, "
+ "November, December, Jan, Feb, Mar, Apr, May, June, July, Aug, Sept, Oct, Nov, Dec,"
+ "01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,"
+ " 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015";
// 1. Gun Categories
//Create node Hierarchy Map used to create directed graph
Map<Integer, List<String>> nodeHierarchyMapCategory = createHirarchyMapForDirectedGraph(metaCategories, nodesForGraph, MetadataTypes.GUN_CATEGORIES);
//System.out.println(nodeHierarchyMapCategory);
//Create Directed Graph
DirectedSparseGraph<String, Integer> categoriesGraph = createDirectedGraph(nodesForGraph, nodeHierarchyMapCategory);
//Compute Page Rank
Map<String, Double> pageRanksCategories = compute(categoriesGraph);
categoriesGraph = null; System.gc();
//System.out.println("Categories PG => " + pageRanksCategories);
// 2. Geographic
//Create node Hierarchy Map used to create directed graph
Map<Integer, List<String>> nodeHierarchyMapGeographic = createHirarchyMapForDirectedGraph(metaGeographic, nodesForGraph, MetadataTypes.GEOGRAPHIC);
//System.out.println(nodeHierarchyMapGeographic);
//Create Directed Graph
DirectedSparseGraph<String, Integer> geographicGraph = createDirectedGraph(nodesForGraph, nodeHierarchyMapGeographic);
//Compute Page Rank
Map<String, Double> pageRanksGeographic = compute(geographicGraph);
geographicGraph = null; System.gc();
//System.out.println("Geographic PG => " + pageRanksGeographic);
// 3. Temporal
//Create node Hierarchy Map used to create directed graph
Map<Integer, List<String>> nodeHierarchyMapTemporal = createHirarchyMapForDirectedGraph(metaTemporal, nodesForGraph, MetadataTypes.TEMPORAL);
//System.out.println(nodeHierarchyMapTemporal);
//Create Directed Graph
DirectedSparseGraph<String, Integer> temporalGraph = createDirectedGraph(nodesForGraph, nodeHierarchyMapTemporal);
//Compute Page Rank
Map<String, Double> pageRanksTemporal = compute(temporalGraph);
temporalGraph = null; System.gc();
//System.out.println("Temporal PG => " + pageRanksTemporal);
//Loop all nodes in Graph and compute final page rank
Map<String, Double> finalPageRank = new HashMap<String, Double>();
Map<Double, List<String>> pageRankCheck = new TreeMap<Double, List<String>>();
for(Node n : nodesForGraph) {
Double categoryPG = pageRanksCategories.get(n.getId());
Double geographicPG = pageRanksGeographic.get(n.getId());
Double temporalPG = pageRanksTemporal.get(n.getId());
Double finalPG = getMaxPageRank(categoryPG, geographicPG, temporalPG);
//System.out.println(categoryPG + " , " + geographicPG + " , " + temporalPG + " => " + finalPG);
finalPageRank.put(n.getId(), finalPG);
//checking docs with same PG
if(pageRankCheck.containsKey(finalPG)){
List<String> docs = pageRankCheck.get(finalPG);
docs.add(n.getId());
pageRankCheck.put(finalPG, docs);
}else{
List<String> docs = new ArrayList<String>();
docs.add(n.getId());
pageRankCheck.put(finalPG, docs);
}
}
//System.out.println("PG check : " + pageRankCheck);
//System.out.println("Final PG : " + finalPageRank);
return finalPageRank;
}
public static void main(String[] args) {
PageRankAlgorithm pageRankAlgo = new PageRankAlgorithm(10, 0.1, 0.85);
Map<String, Double> finalPageRank = pageRankAlgo.getFinalPageRankMap();
/*String jsonOuput = pageRankAlgo.getDocumentJSONFromSolrRest();
File jsonFile = new File("temp.json");
try {
FileUtils.writeStringToFile(jsonFile, jsonOuput);
} catch (IOException e) {
e.printStackTrace();
}*/
System.out.println("Final PG : " + finalPageRank);
//System.out.println("PG check : " + pageRankCheck);
//JSONObject json = new JSONObject(pageRankCheck);
//json.putAll( data );
//System.out.printf("JSON: %s", json.toString());
//Update Solr with PageRank
//updateSolrDocumentsPageRank(finalPageRank);
System.out.println("------------- END --------------");
}
private static void updateSolrDocumentsPageRank(Map<String, Double> finalPageRank) {
String solrUrl = "http://10.120.125.77:8983/solr/memexcollection";
SolrServer server = new HttpSolrServer(solrUrl);
Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
//Loop PageRank Map
for (Map.Entry<String, Double> entry : finalPageRank.entrySet()) {
//System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
Map<String,Object> fieldModifier = new HashMap<String,Object>(1);
fieldModifier.put("set", entry.getValue());
SolrInputDocument doc1 = new SolrInputDocument();
doc1.addField( "id", entry.getKey());
doc1.addField("page_rank", fieldModifier); // add the map as the field value
docs.add(doc1);
}
try {
System.out.println("Updating page rank to Solr");
server.add( docs );
server.commit();
System.out.println("Success");
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 41.042105 | 169 | 0.68397 |
860c8f00edd54dc3a84d0df7d6b9fda234f02b3f | 2,106 | package dera.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public final class CollectionUtil {
private static final Logger LOG = LoggerFactory.getLogger(CollectionUtil.class);
private CollectionUtil() {
}
public static Set newSet(Object... elements) {
return new HashSet(java.util.Arrays.asList(elements));
}
public static Set newUnmodifiableSet(Object... elements) {
return Collections.unmodifiableSet(new HashSet(java.util.Arrays.asList(elements)));
}
public static boolean nullOrEmpty(Collection c) {
return (c == null || c.isEmpty());
}
public static boolean neitherNullNorEmpty(Collection c) {
return (c != null && !c.isEmpty());
}
public static boolean nullOrEmpty(Map map) {
return (map == null || map.isEmpty());
}
public static boolean neitherNullNorEmpty(Map map) {
return (map != null && !map.isEmpty());
}
public static boolean nullOrEmpty(Object[] array) {
return (array == null || array.length == 0);
}
public static boolean neitherNullNorEmpty(Object[] array) {
return (array != null && array.length > 0);
}
public static void print(Collection c) {
if (c != null) {
LOG.info("=========================================================================================");
for (Object o : c) {
LOG.info("{}", new Object[]{o});
}
LOG.info("=========================================================================================");
}
}
public static void print(Map<Object, Object> m) {
if (m != null) {
LOG.info("=========================================================================================");
for (Map.Entry entry : m.entrySet()) {
LOG.info("{} => {}", new Object[]{entry.getKey(), entry.getValue()});
}
LOG.info("=========================================================================================");
}
}
}
| 30.970588 | 114 | 0.47151 |
3454251944972bc1df7b4e0577933e5131f46ba2 | 779 | package shadows.hitwithaxe.block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import shadows.hitwithaxe.EnumBarkType;
public class BlockDebarkedSpectre extends BlockDebarkedLog {
public BlockDebarkedSpectre(EnumBarkType type) {
super(type);
}
@Override
public BlockRenderLayer getRenderLayer() {
return BlockRenderLayer.TRANSLUCENT;
}
@Override
public boolean isOpaqueCube(IBlockState state) {
return false;
}
@Override
public boolean shouldSideBeRendered(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {
return state != world.getBlockState(pos.offset(side));
}
}
| 24.34375 | 108 | 0.802311 |
208f8e6b3325054265e348b55d39cf4c82de9d88 | 8,617 | /**
*
*/
package io.github.luzzu.linkeddata.qualitymetrics.intrinsic.syntacticvalidity;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.jena.graph.Node;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.sparql.core.Quad;
import org.apache.jena.vocabulary.RDF;
import org.apache.jena.vocabulary.RDFS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cybozu.labs.langdetect.LangDetectException;
import au.com.bytecode.opencsv.CSVReader;
import io.github.luzzu.exceptions.AfterException;
import io.github.luzzu.exceptions.BeforeException;
import io.github.luzzu.linkeddata.qualitymetrics.commons.AbstractComplexQualityMetric;
import io.github.luzzu.linkeddata.qualitymetrics.commons.datatypes.Pair;
import io.github.luzzu.linkeddata.qualitymetrics.intrinsic.syntacticvalidity.helper.LanguageDetector;
import io.github.luzzu.linkeddata.qualitymetrics.intrinsic.syntacticvalidity.helper.LanguageDetectorSM;
import io.github.luzzu.linkeddata.qualitymetrics.vocabulary.DQM;
import io.github.luzzu.linkeddata.qualitymetrics.vocabulary.DQMPROB;
import io.github.luzzu.operations.properties.EnvironmentProperties;
import io.github.luzzu.qualityproblems.ProblemCollection;
import io.github.luzzu.qualityproblems.ProblemCollectionModel;
import io.github.luzzu.semantics.commons.ResourceCommons;
import io.github.luzzu.semantics.vocabularies.DAQ;
import io.github.luzzu.semantics.vocabularies.QPRO;
/**
* @author Jeremy Debattista
*
*/
public class CorrectLanguageTag extends AbstractComplexQualityMetric<Double> {
private static Logger logger = LoggerFactory.getLogger(CorrectLanguageTag.class);
private String lexvoDataURI = "http://www.lexvo.org/data/term/{language}/{term}";
private String lexvoResourceURI = "http://lexvo.org/id/term/{language}/{term}";
// private String languageTranslatorURI = "https://services.open.xerox.com/bus/op/LanguageIdentifier/GetLanguageForString";
private double languageThresholdConfidence = 0.90;
private double languageThresholdConfidenceSM = 0.70;
private Map<String,String> langMap = new HashMap<String, String>();
private ProblemCollection<Model> problemCollection = new ProblemCollectionModel(DQM.CorrectLanguageTag);
private boolean requireProblemReport = EnvironmentProperties.getInstance().requiresQualityProblemReport();
private int totalvalidLangStrings = 0;
private int totalCorrectStrings = 0;
@Override
public void compute(Quad quad) {
Node obj = quad.getObject();
if (obj.isLiteral()){
RDFNode n = ResourceCommons.asRDFNode(obj);
Literal lt = (Literal) n;
String language = lt.getLanguage();
if (!language.equals("")){
totalvalidLangStrings++;
try {
Pair<Boolean,String> lTag = this.correctLanguageTag(obj);
if (lTag.getFirstElement())
totalCorrectStrings++;
else {
if (requireProblemReport) {
Model m = ModelFactory.createDefaultModel();
Resource pUri = ResourceCommons.generateURI();
m.add(pUri, QPRO.exceptionDescription, DQMPROB.IncorrectLanguageTag);
m.add(pUri, DQMPROB.actualLiteralValue, lt);
m.add(pUri, DQMPROB.actualLanguageTag, ResourceCommons.generateTypeLiteral(language));
m.add(pUri, DQMPROB.expectedLanguageTag, ResourceCommons.generateTypeLiteral(lTag.getSecondElement()));
// problemCollection.addProblem(m);
((ProblemCollectionModel)problemCollection).addProblem(m, pUri);
}
}
} catch (UnsupportedEncodingException | LangDetectException e) {
e.printStackTrace();
}
}
}
}
@Override
public Double metricValue() {
double metricValue = (double) totalCorrectStrings / (double) totalvalidLangStrings;
statsLogger.info("Correct Language Tag. Dataset: {} - Total # Correct Strings : {}; # Total Valid Language Strings : {}, Metric Value: {}",
this.getDatasetURI(), totalCorrectStrings, totalvalidLangStrings,metricValue);
return metricValue;
}
@Override
public Resource getMetricURI() {
return DQM.CorrectLanguageTag;
}
@Override
public boolean isEstimate() {
return true;
}
@Override
public Resource getAgentURI() {
return DQM.LuzzuProvenanceAgent;
}
private Pair<Boolean, String> correctLanguageTag(Node lit_obj) throws UnsupportedEncodingException, LangDetectException{
Pair<Boolean, String> result = new Pair<Boolean, String>(false, "unknown");
RDFNode n = ResourceCommons.asRDFNode(lit_obj);
Literal lt = (Literal) n;
logger.info("Checking for {} :"+lt.toString());
String stringValue = lt.getLexicalForm().trim();
String language = lt.getLanguage();
if (!language.equals("")){
String[] splited = stringValue.split("\\b+");
if (splited.length > 2){
//its a sentence
String lang = "";
if (splited.length > 15) {
lang = LanguageDetector.getInstance().identifyLanguageOfLabel(stringValue, languageThresholdConfidence).replace("\"","");
} else {
lang = LanguageDetectorSM.getInstance().identifyLanguageOfLabel(stringValue, languageThresholdConfidenceSM).replace("\"","");
}
if (lang.equals("")){
// we cannot identify the languag
return result;
} else {
// String shortLang = language.length() > 2 ? language.substring(language.length() - 2) : language;
result.setFirstElement(language.equals(lang));
result.setSecondElement(lang);
return result;
}
} else {
//its one word
String shortLang = language.length() > 2 ? language.substring(language.length() - 2) : language;
String lexvoLang = "";
if (langMap.containsKey(shortLang)) lexvoLang = langMap.get(shortLang).substring(langMap.get(shortLang).length() - 3);
if (!(lexvoLang.equals(""))){
String data = this.lexvoDataURI.replace("{language}", lexvoLang).replace("{term}", URLEncoder.encode(stringValue, "UTF-8"));
String uri = this.lexvoResourceURI.replace("{language}", lexvoLang).replace("{term}", URLEncoder.encode(stringValue, "UTF-8"));
Model m = RDFDataMgr.loadModel(data);
boolean exists = m.contains(m.createResource(uri), RDFS.seeAlso);
result.setFirstElement(exists);
return result;
}
}
}
return result;
}
@Override
public void before(Object... args) throws BeforeException {
String filename = CorrectLanguageTag.class.getClassLoader().getResource("lexvo/language_mapping.tsv").getFile();
try {
logger.info("Loading language file");
CSVReader reader = new CSVReader(new FileReader(filename),'\t');
List<String[]> allLanguages = reader.readAll();
for(String[] language : allLanguages)
langMap.put(language[0], language[1]);
reader.close();
} catch (IOException e) {
logger.error("Error Loading language file: {}", e.toString());
e.printStackTrace();
}
}
@Override
public void after(Object... args) throws AfterException {
// Nothing to do here
}
@Override
public ProblemCollection<?> getProblemCollection() {
return this.problemCollection;
}
@Override
public Model getObservationActivity() {
Model activity = ModelFactory.createDefaultModel();
Resource mp = ResourceCommons.generateURI();
activity.add(mp, RDF.type, DAQ.MetricProfile);
activity.add(mp, DQM.totalNumberOfLiteralsWithLanguageTag, ResourceCommons.generateTypeLiteral(this.totalvalidLangStrings));
activity.add(mp, DQM.externalToolUsed, ResourceCommons.generateTypeLiteral(this.totalvalidLangStrings));
Resource ep = ResourceCommons.generateURI();
activity.add(mp, DAQ.estimationParameter, ep);
activity.add(ep, RDF.type, DAQ.EstimationParameter);
activity.add(ep, DAQ.estimationParameterValue, ResourceCommons.generateTypeLiteral(languageThresholdConfidence));
activity.add(ep, DAQ.estimationParameterKey, ResourceCommons.generateTypeLiteral("Confidence Threshold Large Text"));
Resource ep2 = ResourceCommons.generateURI();
activity.add(mp, DAQ.estimationParameter, ep2);
activity.add(ep2, RDF.type, DAQ.EstimationParameter);
activity.add(ep2, DAQ.estimationParameterValue, ResourceCommons.generateTypeLiteral(languageThresholdConfidenceSM));
activity.add(ep2, DAQ.estimationParameterKey, ResourceCommons.generateTypeLiteral("Confidence Threshold Short Text"));
return activity;
}
}
| 36.054393 | 142 | 0.746664 |
90273e434b4ecfd74c7eebe77e22fe3e474bb077 | 3,730 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer.audio;
import com.google.android.exoplayer.util.Assertions;
import com.google.android.exoplayer.util.Util;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioFormat;
import android.media.AudioManager;
/**
* Notifies a listener when the audio playback capabilities change. Call {@link #register} to start
* receiving notifications, and {@link #unregister} to stop.
*/
public final class AudioCapabilitiesReceiver {
/** Listener notified when audio capabilities change. */
public interface Listener {
/** Called when the audio capabilities change. */
void onAudioCapabilitiesChanged(AudioCapabilities audioCapabilities);
}
/** Default to stereo PCM on SDK < 21 and when HDMI is unplugged. */
private static final AudioCapabilities DEFAULT_AUDIO_CAPABILITIES =
new AudioCapabilities(new int[] {AudioFormat.ENCODING_PCM_16BIT}, 2);
private final Context context;
private final Listener listener;
private final BroadcastReceiver receiver;
/**
* Constructs a new audio capabilities receiver.
*
* @param context Application context for registering to receive broadcasts.
* @param listener Listener to notify when audio capabilities change.
*/
public AudioCapabilitiesReceiver(Context context, Listener listener) {
this.context = Assertions.checkNotNull(context);
this.listener = Assertions.checkNotNull(listener);
this.receiver = Util.SDK_INT >= 21 ? new HdmiAudioPlugBroadcastReceiver() : null;
}
/**
* Registers to notify the listener when audio capabilities change. The listener will immediately
* receive the current audio capabilities. It is important to call {@link #unregister} so that
* the listener can be garbage collected.
*/
@TargetApi(21)
public void register() {
if (receiver != null) {
Intent initialStickyIntent =
context.registerReceiver(receiver, new IntentFilter(AudioManager.ACTION_HDMI_AUDIO_PLUG));
if (initialStickyIntent != null) {
receiver.onReceive(context, initialStickyIntent);
return;
}
}
listener.onAudioCapabilitiesChanged(DEFAULT_AUDIO_CAPABILITIES);
}
/** Unregisters to stop notifying the listener when audio capabilities change. */
public void unregister() {
if (receiver != null) {
context.unregisterReceiver(receiver);
}
}
@TargetApi(21)
private final class HdmiAudioPlugBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (isInitialStickyBroadcast()) {
return;
}
String action = intent.getAction();
if (!action.equals(AudioManager.ACTION_HDMI_AUDIO_PLUG)) {
return;
}
listener.onAudioCapabilitiesChanged(
new AudioCapabilities(intent.getIntArrayExtra(AudioManager.EXTRA_ENCODINGS),
intent.getIntExtra(AudioManager.EXTRA_MAX_CHANNEL_COUNT, 0)));
}
}
}
| 33.603604 | 100 | 0.735121 |
32a47673803e0ce83c8bc896dbdac9b54721dbe1 | 3,803 | /*
* Copyright (c) 2020-2021 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.ore.ores;
import net.jafama.FastMath;
import java.util.Map;
import java.util.Random;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.block.BlockType;
import com.dfsek.terra.api.block.state.BlockState;
import com.dfsek.terra.api.util.Range;
import com.dfsek.terra.api.util.collection.MaterialSet;
import com.dfsek.terra.api.util.vector.Vector3;
import com.dfsek.terra.api.world.Chunk;
public class VanillaOre extends Ore {
private final Range sizeRange;
public VanillaOre(BlockState material, MaterialSet replaceable, boolean applyGravity, Range size, Platform platform,
Map<BlockType, BlockState> materials) {
super(material, replaceable, applyGravity, platform, materials);
this.sizeRange = size;
}
@Override
public void generate(Vector3 location, Chunk chunk, Random random) {
double size = sizeRange.get(random);
int centerX = location.getBlockX();
int centerZ = location.getBlockZ();
int centerY = location.getBlockY();
double f = random.nextFloat() * Math.PI;
double fS = FastMath.sin(f) * size / 8.0F;
double fC = FastMath.cos(f) * size / 8.0F;
double d1 = centerX + 8 + fS;
double d2 = centerX + 8 - fS;
double d3 = centerZ + 8 + fC;
double d4 = centerZ + 8 - fC;
double d5 = centerY + random.nextInt(3) - 2D;
double d6 = centerY + random.nextInt(3) - 2D;
for(int i = 0; i < size; i++) {
double iFactor = i / size;
double d10 = random.nextDouble() * size / 16.0D;
double d11 = (FastMath.sin(Math.PI * iFactor) + 1.0) * d10 + 1.0;
int xStart = FastMath.roundToInt(FastMath.floor(d1 + (d2 - d1) * iFactor - d11 / 2.0D));
int yStart = FastMath.roundToInt(FastMath.floor(d5 + (d6 - d5) * iFactor - d11 / 2.0D));
int zStart = FastMath.roundToInt(FastMath.floor(d3 + (d4 - d3) * iFactor - d11 / 2.0D));
int xEnd = FastMath.roundToInt(FastMath.floor(d1 + (d2 - d1) * iFactor + d11 / 2.0D));
int yEnd = FastMath.roundToInt(FastMath.floor(d5 + (d6 - d5) * iFactor + d11 / 2.0D));
int zEnd = FastMath.roundToInt(FastMath.floor(d3 + (d4 - d3) * iFactor + d11 / 2.0D));
for(int x = xStart; x <= xEnd; x++) {
double d13 = (x + 0.5D - (d1 + (d2 - d1) * iFactor)) / (d11 / 2.0D);
if(d13 * d13 < 1.0D) {
for(int y = yStart; y <= yEnd; y++) {
double d14 = (y + 0.5D - (d5 + (d6 - d5) * iFactor)) / (d11 / 2.0D);
if(d13 * d13 + d14 * d14 < 1.0D) {
for(int z = zStart; z <= zEnd; z++) {
double d15 = (z + 0.5D - (d3 + (d4 - d3) * iFactor)) / (d11 / 2.0D);
if(x > 15 || z > 15 || y > 255 || x < 0 || z < 0 || y < 0) continue;
BlockType type = chunk.getBlock(x, y, z).getBlockType();
if((d13 * d13 + d14 * d14 + d15 * d15 < 1.0D) && getReplaceable().contains(type)) {
chunk.setBlock(x, y, z, getMaterial(type), isApplyGravity());
}
}
}
}
}
}
}
}
}
| 41.336957 | 120 | 0.512753 |
8d05d51b3514774ab08b421509326b0fa0be6c93 | 5,121 | package basic;
import java.security.*;
import java.util.*;
public class Matrix {
public static void main (String [] args) {
int u=4,w=3,t=5,v=0,s=10000,y=0,x=0,z=0;
Random rnda = new Random();
Random rndb = new Random();
Random rndc = new Random();
Random rndd = new Random();
Random rnde = new Random();
Random rndf = new Random();
Random rndg = new Random();
Random rndh = new Random();
Random rndi = new Random();
Random rndj = new Random();
Random rndk = new Random();
Random rndl = new Random();
Random rndm = new Random();
Random rndn = new Random();
Random rndo = new Random();
Random rndp = new Random();
int rnga = rnda.nextInt(10);
int rngb = rndb.nextInt(10);
int rngc = rndc.nextInt(10);
int rngd = rndd.nextInt(10);
int rnge = rnde.nextInt(10);
int rngf = rndf.nextInt(10);
int rngg = rndg.nextInt(10);
int rngh = rndh.nextInt(10);
int rngi = rndi.nextInt(10);
int rngj = rndj.nextInt(10);
int rngk = rndk.nextInt(10);
int rngl = rndl.nextInt(10);
int rngm = rndm.nextInt(10);
int rngn = rndn.nextInt(10);
int rngo = rndo.nextInt(10);
int rngp = rndp.nextInt(10);
boolean flag= false;
//byte bytes[] = new byte[20];
//rng.nextBytes(bytes);
int a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0;
int i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;
do{
try {
Thread.sleep(2500);
flag = true;
break;
}
catch(InterruptedException ex){
}
for(v=0; v<s ;v++){
System.out.print("\f");
for(x=0; x<t ;x++){
for(y=0; y<w; y++) {
for(z=0; z<u; z++){
rnga = rnda.nextInt(10);
rngb = rndb.nextInt(10);
rngc = rndc.nextInt(10);
rngd = rndd.nextInt(10);
rnge = rnde.nextInt(10);
rngf = rndf.nextInt(10);
rngg = rndg.nextInt(10);
rngh = rndh.nextInt(10);
rngi = rndi.nextInt(10);
rngj = rndj.nextInt(10);
rngk = rndk.nextInt(10);
rngl = rndl.nextInt(10);
rngm = rndm.nextInt(10);
rngn = rndn.nextInt(10);
rngo = rndo.nextInt(10);
rngp = rndp.nextInt(10);
a=rnga;
b=rngb;
c=rngc;
d=rngd;
e=rnge;
f=rngf;
g=rngg;
h=rngh;
i=rngi;
j=rngj;
k=rngk;
l=rngl;
m=rngm;
n=rngn;
o=rngo;
p=rngp;
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print(d);
System.out.print(e);
System.out.print(f);
System.out.print(g);
System.out.print(h);
System.out.print(i);
System.out.print(j);
System.out.print(k);
System.out.print(l);
System.out.print(m);
System.out.print(n);
System.out.print(o);
System.out.print(p);
}
System.out.println(a);
System.out.print(b);
System.out.print(c);
System.out.print(d);
System.out.print(e);
System.out.print(f);
System.out.print(g);
System.out.print(h);
System.out.print(i);
System.out.print(j);
System.out.print(k);
System.out.print(l);
System.out.print(m);
System.out.print(n);
System.out.print(o);
System.out.print(p);
}
}
}
}while(flag!=true);
}
} | 37.379562 | 52 | 0.347784 |
2ffc7fd55e70a5db14ec449da4aa3defb1766840 | 2,100 | package org.spoofax.jsglr2.tests.sdf;
import java.io.IOException;
import java.net.URISyntaxException;
import org.junit.Test;
import org.spoofax.jsglr.client.InvalidParseTableException;
import org.spoofax.jsglr2.parsetable.ParseTableReadException;
import org.spoofax.jsglr2.tests.util.BaseTest;
import org.spoofax.jsglr2.util.WithGrammar;
import org.spoofax.jsglr2.util.WithJSGLR1;
import org.spoofax.terms.ParseError;
public class ListsTest extends BaseTest implements WithJSGLR1, WithGrammar {
public ListsTest() throws ParseError, ParseTableReadException, IOException, InvalidParseTableException,
InterruptedException, URISyntaxException {
setupParseTableFromDefFile("lists");
}
@Test
public void testEmpty() throws ParseError, ParseTableReadException, IOException {
testSuccessByExpansions("", "amb([ZeroOrMoreXs([]),ZeroOrMoreXsCommaSeparated([])])");
}
@Test
public void testSingleX() throws ParseError, ParseTableReadException, IOException {
testSuccessByExpansions("x",
"amb([ZeroOrMoreXs([X]),ZeroOrMoreXsCommaSeparated([X]),OneOrMoreXs([X]),OneOrMoreXsCommaSeparated([X])])");
}
@Test
public void testTwoLayoutSeparatedXs() throws ParseError, ParseTableReadException, IOException {
testSuccessByExpansions("x x", "amb([ZeroOrMoreXs([X, X]), OneOrMoreXs([X, X])])");
}
@Test
public void testTwoCommaSeparatedXs() throws ParseError, ParseTableReadException, IOException {
testSuccessByExpansions("x,x", "amb([ZeroOrMoreXsCommaSeparated([X, X]), OneOrMoreXsCommaSeparated([X, X])])");
}
@Test
public void testThreeLayoutSeparatedXs() throws ParseError, ParseTableReadException, IOException {
testSuccessByExpansions("x x x", "amb([ZeroOrMoreXs([X, X, X]), OneOrMoreXs([X, X, X])])");
}
@Test
public void testThreeCommaSeparatedXs() throws ParseError, ParseTableReadException, IOException {
testSuccessByExpansions("x,x , x",
"amb([ZeroOrMoreXsCommaSeparated([X, X, X]), OneOrMoreXsCommaSeparated([X, X, X])])");
}
} | 39.622642 | 120 | 0.73 |
a2161d7ca82cf60cfd4b8d3bcb3c8d791e2809d0 | 312 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: grpc/metric_master.proto
package alluxio.grpc;
public interface ClearMetricsPRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:alluxio.grpc.metric.ClearMetricsPRequest)
com.google.protobuf.MessageOrBuilder {
}
| 31.2 | 91 | 0.804487 |
fcb2bf3424ce5d561b991dad33c8a3d86ddb5e20 | 430 | package com.tokelon.toktales.samples.desktop.application;
import com.tokelon.toktales.core.game.IGameAdapter;
import com.tokelon.toktales.desktop.application.TokTalesApplication;
import com.tokelon.toktales.samples.core.DefaultAdapter;
public class DefaultApplication extends TokTalesApplication {
@Override
public Class<? extends IGameAdapter> makeDefaultGameAdapter() {
return DefaultAdapter.class;
}
}
| 26.875 | 68 | 0.8 |
7fe2432b379a962704b52587e274ec30fc69b6dc | 2,565 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 彩票赠送订单
*
* @author auto create
* @since 1.0, 2017-07-24 14:37:51
*/
public class LotteryPresent extends AlipayObject {
private static final long serialVersionUID = 3335585292583699314L;
/**
* 用户的支付宝用户ID
*/
@ApiField("alipay_user_id")
private String alipayUserId;
/**
* 彩种名称
*/
@ApiField("lottery_type_name")
private String lotteryTypeName;
/**
* 赠送时间,格式yyyy-MM-dd hh:mm:ss
*/
@ApiField("present_date")
private String presentDate;
/**
* 订单ID
*/
@ApiField("present_id")
private Long presentId;
/**
* 彩票注数
*/
@ApiField("stake_count")
private Long stakeCount;
/**
* 订单状态,含义如下:0-卖家资金未冻结;1-买家未领取;2-买家己领取;3-己创建彩票订单;4-彩票订单出票成功;5-资金己转交代理商;6-订单己过期,待退款;7-冻结资金己退款;8-订单取消。
*/
@ApiField("status")
private Long status;
/**
* 订单状态描述,参见status描述。
*/
@ApiField("status_desc")
private String statusDesc;
/**
* 赠言,不超过20个汉字
*/
@ApiField("sweety_words")
private String sweetyWords;
/**
* 中奖金额,单位:分,为0表示未中奖
*/
@ApiField("win_fee")
private Long winFee;
public String getAlipayUserId() {
return this.alipayUserId;
}
public void setAlipayUserId(String alipayUserId) {
this.alipayUserId = alipayUserId;
}
public String getLotteryTypeName() {
return this.lotteryTypeName;
}
public void setLotteryTypeName(String lotteryTypeName) {
this.lotteryTypeName = lotteryTypeName;
}
public String getPresentDate() {
return this.presentDate;
}
public void setPresentDate(String presentDate) {
this.presentDate = presentDate;
}
public Long getPresentId() {
return this.presentId;
}
public void setPresentId(Long presentId) {
this.presentId = presentId;
}
public Long getStakeCount() {
return this.stakeCount;
}
public void setStakeCount(Long stakeCount) {
this.stakeCount = stakeCount;
}
public Long getStatus() {
return this.status;
}
public void setStatus(Long status) {
this.status = status;
}
public String getStatusDesc() {
return this.statusDesc;
}
public void setStatusDesc(String statusDesc) {
this.statusDesc = statusDesc;
}
public String getSweetyWords() {
return this.sweetyWords;
}
public void setSweetyWords(String sweetyWords) {
this.sweetyWords = sweetyWords;
}
public Long getWinFee() {
return this.winFee;
}
public void setWinFee(Long winFee) {
this.winFee = winFee;
}
}
| 19.141791 | 102 | 0.672904 |
fb3acca43dc7298b876ad9588be0f9a36e40c0c3 | 2,355 | /*
* Copyright 2018 John Grosh <[email protected]>.
*
* 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.jagrosh.jmusicbot.commands.admin;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.commons.utils.FinderUtil;
import com.jagrosh.jmusicbot.commands.AdminCommand;
import com.jagrosh.jmusicbot.settings.Settings;
import net.dv8tion.jda.core.entities.TextChannel;
/**
*
* @author John Grosh <[email protected]>
*/
public class SettcCmd extends AdminCommand<TextChannel>
{
public SettcCmd()
{
this.name = "settc";
this.help = "sets the text channel for music commands";
this.arguments = "<channel|NONE>";
this.nullArgsInEventMessage = " Please include a text channel or NONE";
this.noneArgsInEventMessage = " Music commands can now be used in any channel";
this.emptyListMessage = " No Text Channels found matching \"";
}
protected void setSettingsTonull(Settings settings) {
settings.setTextChannel(null);
}
protected void setList(CommandEvent event) {
this.list = FinderUtil.findTextChannels(event.getArgs(), event.getGuild());
}
protected void setSettingsToListEntry(Settings settings) {
settings.setTextChannel(list.get(0));
}
protected String executeSuccessMessage() {
return " Music commands can now only be used in <#"+list.get(0).getId()+">";
}
protected String multiChannelsHeader(String eventArgs) {
return " Multiple text channels found matching \""+eventArgs+"\":";
}
protected String[] multiChannelsBody(CommandEvent event) {
String temp[] = {};
for(int i=0; i<6 && i<list.size(); i++)
temp[i] = "\n - "+list.get(i).getName()+" (<#"+list.get(i).getId()+">)";
return temp;
}
}
| 34.130435 | 87 | 0.686624 |
1d21a96dc4c66ac0f454a6f67f5e9df828921fdd | 19,008 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.internal.ads;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECPoint;
import java.security.spec.ECPrivateKeySpec;
// Referenced classes of package com.google.android.gms.internal.ads:
// zzaug, zzbbu, zzaws, zzazq,
// zzawu, zzavh, zzawq, zzaww,
// zzbah, zzayt, zzayy, zzavj,
// zzawm, zzayo, zzaue, zzawo,
// zzbbo, zzaxi, zzazy, zzbcu
final class zzava
implements zzaug
{
zzava()
{
// 0 0:aload_0
// 1 1:invokespecial #11 <Method void Object()>
// 2 4:return
}
private final zzaue zzf(zzbah zzbah1)
throws GeneralSecurityException
{
try
{
zzbah1 = ((zzbah) (zzaws.zzx(zzbah1)));
// 0 0:aload_1
// 1 1:invokestatic #24 <Method zzaws zzaws.zzx(zzbah)>
// 2 4:astore_1
if(!(zzbah1 instanceof zzaws))
//* 3 5:aload_1
//* 4 6:instanceof #20 <Class zzaws>
//* 5 9:ifne 22
throw new GeneralSecurityException("expected EciesAeadHkdfPrivateKey proto");
// 6 12:new #16 <Class GeneralSecurityException>
// 7 15:dup
// 8 16:ldc1 #26 <String "expected EciesAeadHkdfPrivateKey proto">
// 9 18:invokespecial #29 <Method void GeneralSecurityException(String)>
// 10 21:athrow
Object obj1 = ((Object) ((zzaws)zzbah1));
// 11 22:aload_1
// 12 23:checkcast #20 <Class zzaws>
// 13 26:astore 4
zzazq.zzj(((zzaws) (obj1)).getVersion(), 0);
// 14 28:aload 4
// 15 30:invokevirtual #33 <Method int zzaws.getVersion()>
// 16 33:iconst_0
// 17 34:invokestatic #39 <Method void zzazq.zzj(int, int)>
zzavh.zza(((zzaws) (obj1)).zzxz().zzxs());
// 18 37:aload 4
// 19 39:invokevirtual #43 <Method zzawu zzaws.zzxz()>
// 20 42:invokevirtual #49 <Method zzawq zzawu.zzxs()>
// 21 45:invokestatic #55 <Method void zzavh.zza(zzawq)>
zzbah1 = ((zzbah) (((zzaws) (obj1)).zzxz().zzxs()));
// 22 48:aload 4
// 23 50:invokevirtual #43 <Method zzawu zzaws.zzxz()>
// 24 53:invokevirtual #49 <Method zzawq zzawu.zzxs()>
// 25 56:astore_1
zzaww zzaww1 = ((zzawq) (zzbah1)).zzxu();
// 26 57:aload_1
// 27 58:invokevirtual #61 <Method zzaww zzawq.zzxu()>
// 28 61:astore_2
Object obj = ((Object) (zzavh.zza(zzaww1.zzyh())));
// 29 62:aload_2
// 30 63:invokevirtual #67 <Method zzawy zzaww.zzyh()>
// 31 66:invokestatic #70 <Method zzayv zzavh.zza(zzawy)>
// 32 69:astore_3
byte abyte0[] = ((zzaws) (obj1)).zzwv().toByteArray();
// 33 70:aload 4
// 34 72:invokevirtual #74 <Method zzbah zzaws.zzwv()>
// 35 75:invokevirtual #80 <Method byte[] zzbah.toByteArray()>
// 36 78:astore 4
obj = ((Object) (zzayt.zza(((zzayv) (obj)))));
// 37 80:aload_3
// 38 81:invokestatic #85 <Method java.security.spec.ECParameterSpec zzayt.zza(zzayv)>
// 39 84:astore_3
obj = ((Object) (new ECPrivateKeySpec(new BigInteger(1, abyte0), ((java.security.spec.ECParameterSpec) (obj)))));
// 40 85:new #87 <Class ECPrivateKeySpec>
// 41 88:dup
// 42 89:new #89 <Class BigInteger>
// 43 92:dup
// 44 93:iconst_1
// 45 94:aload 4
// 46 96:invokespecial #92 <Method void BigInteger(int, byte[])>
// 47 99:aload_3
// 48 100:invokespecial #95 <Method void ECPrivateKeySpec(BigInteger, java.security.spec.ECParameterSpec)>
// 49 103:astore_3
obj = ((Object) ((ECPrivateKey)((KeyFactory)zzayy.zzdof.zzek("EC")).generatePrivate(((java.security.spec.KeySpec) (obj)))));
// 50 104:getstatic #101 <Field zzayy zzayy.zzdof>
// 51 107:ldc1 #103 <String "EC">
// 52 109:invokevirtual #107 <Method Object zzayy.zzek(String)>
// 53 112:checkcast #109 <Class KeyFactory>
// 54 115:aload_3
// 55 116:invokevirtual #113 <Method java.security.PrivateKey KeyFactory.generatePrivate(java.security.spec.KeySpec)>
// 56 119:checkcast #115 <Class ECPrivateKey>
// 57 122:astore_3
abyte0 = ((byte []) (new zzavj(((zzawq) (zzbah1)).zzxv().zzxp())));
// 58 123:new #117 <Class zzavj>
// 59 126:dup
// 60 127:aload_1
// 61 128:invokevirtual #121 <Method zzawm zzawq.zzxv()>
// 62 131:invokevirtual #127 <Method zzaxn zzawm.zzxp()>
// 63 134:invokespecial #130 <Method void zzavj(zzaxn)>
// 64 137:astore 4
zzbah1 = ((zzbah) ((zzaue)new zzayo(((ECPrivateKey) (obj)), zzaww1.zzyj().toByteArray(), zzavh.zza(zzaww1.zzyi()), zzavh.zza(((zzawq) (zzbah1)).zzxw()), ((zzayn) (abyte0)))));
// 65 139:new #132 <Class zzayo>
// 66 142:dup
// 67 143:aload_3
// 68 144:aload_2
// 69 145:invokevirtual #135 <Method zzbah zzaww.zzyj()>
// 70 148:invokevirtual #80 <Method byte[] zzbah.toByteArray()>
// 71 151:aload_2
// 72 152:invokevirtual #139 <Method zzaxa zzaww.zzyi()>
// 73 155:invokestatic #142 <Method String zzavh.zza(zzaxa)>
// 74 158:aload_1
// 75 159:invokevirtual #146 <Method zzawk zzawq.zzxw()>
// 76 162:invokestatic #149 <Method zzayw zzavh.zza(zzawk)>
// 77 165:aload 4
// 78 167:invokespecial #152 <Method void zzayo(ECPrivateKey, byte[], String, zzayw, zzayn)>
// 79 170:checkcast #154 <Class zzaue>
// 80 173:astore_1
}
//* 81 174:aload_1
//* 82 175:areturn
// Misplaced declaration of an exception variable
catch(zzbah zzbah1)
//* 83 176:astore_1
{
throw new GeneralSecurityException("expected serialized EciesAeadHkdfPrivateKey proto", ((Throwable) (zzbah1)));
// 84 177:new #16 <Class GeneralSecurityException>
// 85 180:dup
// 86 181:ldc1 #156 <String "expected serialized EciesAeadHkdfPrivateKey proto">
// 87 183:aload_1
// 88 184:invokespecial #159 <Method void GeneralSecurityException(String, Throwable)>
// 89 187:athrow
}
return ((zzaue) (zzbah1));
}
public final int getVersion()
{
return 0;
// 0 0:iconst_0
// 1 1:ireturn
}
public final Object zza(zzbah zzbah1)
throws GeneralSecurityException
{
return ((Object) (zzf(zzbah1)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #163 <Method zzaue zzf(zzbah)>
// 3 5:areturn
}
public final Object zza(zzbcu zzbcu)
throws GeneralSecurityException
{
if(!(zzbcu instanceof zzaws))
//* 0 0:aload_1
//* 1 1:instanceof #20 <Class zzaws>
//* 2 4:ifne 17
{
throw new GeneralSecurityException("expected EciesAeadHkdfPrivateKey proto");
// 3 7:new #16 <Class GeneralSecurityException>
// 4 10:dup
// 5 11:ldc1 #26 <String "expected EciesAeadHkdfPrivateKey proto">
// 6 13:invokespecial #29 <Method void GeneralSecurityException(String)>
// 7 16:athrow
} else
{
Object obj1 = ((Object) ((zzaws)zzbcu));
// 8 17:aload_1
// 9 18:checkcast #20 <Class zzaws>
// 10 21:astore 4
zzazq.zzj(((zzaws) (obj1)).getVersion(), 0);
// 11 23:aload 4
// 12 25:invokevirtual #33 <Method int zzaws.getVersion()>
// 13 28:iconst_0
// 14 29:invokestatic #39 <Method void zzazq.zzj(int, int)>
zzavh.zza(((zzaws) (obj1)).zzxz().zzxs());
// 15 32:aload 4
// 16 34:invokevirtual #43 <Method zzawu zzaws.zzxz()>
// 17 37:invokevirtual #49 <Method zzawq zzawu.zzxs()>
// 18 40:invokestatic #55 <Method void zzavh.zza(zzawq)>
zzbcu = ((zzbcu) (((zzaws) (obj1)).zzxz().zzxs()));
// 19 43:aload 4
// 20 45:invokevirtual #43 <Method zzawu zzaws.zzxz()>
// 21 48:invokevirtual #49 <Method zzawq zzawu.zzxs()>
// 22 51:astore_1
zzaww zzaww1 = ((zzawq) (zzbcu)).zzxu();
// 23 52:aload_1
// 24 53:invokevirtual #61 <Method zzaww zzawq.zzxu()>
// 25 56:astore_2
Object obj = ((Object) (zzavh.zza(zzaww1.zzyh())));
// 26 57:aload_2
// 27 58:invokevirtual #67 <Method zzawy zzaww.zzyh()>
// 28 61:invokestatic #70 <Method zzayv zzavh.zza(zzawy)>
// 29 64:astore_3
byte abyte0[] = ((zzaws) (obj1)).zzwv().toByteArray();
// 30 65:aload 4
// 31 67:invokevirtual #74 <Method zzbah zzaws.zzwv()>
// 32 70:invokevirtual #80 <Method byte[] zzbah.toByteArray()>
// 33 73:astore 4
obj = ((Object) (zzayt.zza(((zzayv) (obj)))));
// 34 75:aload_3
// 35 76:invokestatic #85 <Method java.security.spec.ECParameterSpec zzayt.zza(zzayv)>
// 36 79:astore_3
obj = ((Object) (new ECPrivateKeySpec(new BigInteger(1, abyte0), ((java.security.spec.ECParameterSpec) (obj)))));
// 37 80:new #87 <Class ECPrivateKeySpec>
// 38 83:dup
// 39 84:new #89 <Class BigInteger>
// 40 87:dup
// 41 88:iconst_1
// 42 89:aload 4
// 43 91:invokespecial #92 <Method void BigInteger(int, byte[])>
// 44 94:aload_3
// 45 95:invokespecial #95 <Method void ECPrivateKeySpec(BigInteger, java.security.spec.ECParameterSpec)>
// 46 98:astore_3
obj = ((Object) ((ECPrivateKey)((KeyFactory)zzayy.zzdof.zzek("EC")).generatePrivate(((java.security.spec.KeySpec) (obj)))));
// 47 99:getstatic #101 <Field zzayy zzayy.zzdof>
// 48 102:ldc1 #103 <String "EC">
// 49 104:invokevirtual #107 <Method Object zzayy.zzek(String)>
// 50 107:checkcast #109 <Class KeyFactory>
// 51 110:aload_3
// 52 111:invokevirtual #113 <Method java.security.PrivateKey KeyFactory.generatePrivate(java.security.spec.KeySpec)>
// 53 114:checkcast #115 <Class ECPrivateKey>
// 54 117:astore_3
abyte0 = ((byte []) (new zzavj(((zzawq) (zzbcu)).zzxv().zzxp())));
// 55 118:new #117 <Class zzavj>
// 56 121:dup
// 57 122:aload_1
// 58 123:invokevirtual #121 <Method zzawm zzawq.zzxv()>
// 59 126:invokevirtual #127 <Method zzaxn zzawm.zzxp()>
// 60 129:invokespecial #130 <Method void zzavj(zzaxn)>
// 61 132:astore 4
return ((Object) (new zzayo(((ECPrivateKey) (obj)), zzaww1.zzyj().toByteArray(), zzavh.zza(zzaww1.zzyi()), zzavh.zza(((zzawq) (zzbcu)).zzxw()), ((zzayn) (abyte0)))));
// 62 134:new #132 <Class zzayo>
// 63 137:dup
// 64 138:aload_3
// 65 139:aload_2
// 66 140:invokevirtual #135 <Method zzbah zzaww.zzyj()>
// 67 143:invokevirtual #80 <Method byte[] zzbah.toByteArray()>
// 68 146:aload_2
// 69 147:invokevirtual #139 <Method zzaxa zzaww.zzyi()>
// 70 150:invokestatic #142 <Method String zzavh.zza(zzaxa)>
// 71 153:aload_1
// 72 154:invokevirtual #146 <Method zzawk zzawq.zzxw()>
// 73 157:invokestatic #149 <Method zzayw zzavh.zza(zzawk)>
// 74 160:aload 4
// 75 162:invokespecial #152 <Method void zzayo(ECPrivateKey, byte[], String, zzayw, zzayn)>
// 76 165:areturn
}
}
public final zzbcu zzb(zzbah zzbah1)
throws GeneralSecurityException
{
try
{
zzbah1 = ((zzbah) (zzb(((zzbcu) (zzawo.zzw(zzbah1))))));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokestatic #172 <Method zzawo zzawo.zzw(zzbah)>
// 3 5:invokevirtual #175 <Method zzbcu zzb(zzbcu)>
// 4 8:astore_1
}
//* 5 9:aload_1
//* 6 10:areturn
// Misplaced declaration of an exception variable
catch(zzbah zzbah1)
//* 7 11:astore_1
{
throw new GeneralSecurityException("invalid EciesAeadHkdf key format", ((Throwable) (zzbah1)));
// 8 12:new #16 <Class GeneralSecurityException>
// 9 15:dup
// 10 16:ldc1 #177 <String "invalid EciesAeadHkdf key format">
// 11 18:aload_1
// 12 19:invokespecial #159 <Method void GeneralSecurityException(String, Throwable)>
// 13 22:athrow
}
return ((zzbcu) (zzbah1));
}
public final zzbcu zzb(zzbcu zzbcu)
throws GeneralSecurityException
{
if(!(zzbcu instanceof zzawo))
//* 0 0:aload_1
//* 1 1:instanceof #168 <Class zzawo>
//* 2 4:ifne 17
{
throw new GeneralSecurityException("expected EciesAeadHkdfKeyFormat proto");
// 3 7:new #16 <Class GeneralSecurityException>
// 4 10:dup
// 5 11:ldc1 #179 <String "expected EciesAeadHkdfKeyFormat proto">
// 6 13:invokespecial #29 <Method void GeneralSecurityException(String)>
// 7 16:athrow
} else
{
zzbcu = ((zzbcu) ((zzawo)zzbcu));
// 8 17:aload_1
// 9 18:checkcast #168 <Class zzawo>
// 10 21:astore_1
zzavh.zza(((zzawo) (zzbcu)).zzxs());
// 11 22:aload_1
// 12 23:invokevirtual #180 <Method zzawq zzawo.zzxs()>
// 13 26:invokestatic #55 <Method void zzavh.zza(zzawq)>
Object obj = ((Object) (zzayt.zza(zzayt.zza(zzavh.zza(((zzawo) (zzbcu)).zzxs().zzxu().zzyh())))));
// 14 29:aload_1
// 15 30:invokevirtual #180 <Method zzawq zzawo.zzxs()>
// 16 33:invokevirtual #61 <Method zzaww zzawq.zzxu()>
// 17 36:invokevirtual #67 <Method zzawy zzaww.zzyh()>
// 18 39:invokestatic #70 <Method zzayv zzavh.zza(zzawy)>
// 19 42:invokestatic #85 <Method java.security.spec.ECParameterSpec zzayt.zza(zzayv)>
// 20 45:invokestatic #183 <Method KeyPair zzayt.zza(java.security.spec.ECParameterSpec)>
// 21 48:astore_2
Object obj1 = ((Object) ((ECPublicKey)((KeyPair) (obj)).getPublic()));
// 22 49:aload_2
// 23 50:invokevirtual #189 <Method java.security.PublicKey KeyPair.getPublic()>
// 24 53:checkcast #191 <Class ECPublicKey>
// 25 56:astore_3
obj = ((Object) ((ECPrivateKey)((KeyPair) (obj)).getPrivate()));
// 26 57:aload_2
// 27 58:invokevirtual #195 <Method java.security.PrivateKey KeyPair.getPrivate()>
// 28 61:checkcast #115 <Class ECPrivateKey>
// 29 64:astore_2
obj1 = ((Object) (((ECPublicKey) (obj1)).getW()));
// 30 65:aload_3
// 31 66:invokeinterface #199 <Method ECPoint ECPublicKey.getW()>
// 32 71:astore_3
zzbcu = ((zzbcu) ((zzawu)(zzbbo)((zzbbo.zza) (zzawu.zzye().zzas(0).zzc(((zzawo) (zzbcu)).zzxs()).zzac(zzbah.zzo(((ECPoint) (obj1)).getAffineX().toByteArray())).zzad(zzbah.zzo(((ECPoint) (obj1)).getAffineY().toByteArray())))).zzadi()));
// 33 72:invokestatic #203 <Method zzawu$zza zzawu.zzye()>
// 34 75:iconst_0
// 35 76:invokevirtual #209 <Method zzawu$zza zzawu$zza.zzas(int)>
// 36 79:aload_1
// 37 80:invokevirtual #180 <Method zzawq zzawo.zzxs()>
// 38 83:invokevirtual #213 <Method zzawu$zza zzawu$zza.zzc(zzawq)>
// 39 86:aload_3
// 40 87:invokevirtual #219 <Method BigInteger ECPoint.getAffineX()>
// 41 90:invokevirtual #220 <Method byte[] BigInteger.toByteArray()>
// 42 93:invokestatic #224 <Method zzbah zzbah.zzo(byte[])>
// 43 96:invokevirtual #228 <Method zzawu$zza zzawu$zza.zzac(zzbah)>
// 44 99:aload_3
// 45 100:invokevirtual #231 <Method BigInteger ECPoint.getAffineY()>
// 46 103:invokevirtual #220 <Method byte[] BigInteger.toByteArray()>
// 47 106:invokestatic #224 <Method zzbah zzbah.zzo(byte[])>
// 48 109:invokevirtual #234 <Method zzawu$zza zzawu$zza.zzad(zzbah)>
// 49 112:invokevirtual #240 <Method zzbbo zzbbo$zza.zzadi()>
// 50 115:checkcast #242 <Class zzbbo>
// 51 118:checkcast #45 <Class zzawu>
// 52 121:astore_1
return ((zzbcu) ((zzbbo)((zzbbo.zza) (zzaws.zzya().zzar(0).zzb(((zzawu) (zzbcu))).zzy(zzbah.zzo(((ECPrivateKey) (obj)).getS().toByteArray())))).zzadi()));
// 53 122:invokestatic #246 <Method zzaws$zza zzaws.zzya()>
// 54 125:iconst_0
// 55 126:invokevirtual #252 <Method zzaws$zza zzaws$zza.zzar(int)>
// 56 129:aload_1
// 57 130:invokevirtual #255 <Method zzaws$zza zzaws$zza.zzb(zzawu)>
// 58 133:aload_2
// 59 134:invokeinterface #258 <Method BigInteger ECPrivateKey.getS()>
// 60 139:invokevirtual #220 <Method byte[] BigInteger.toByteArray()>
// 61 142:invokestatic #224 <Method zzbah zzbah.zzo(byte[])>
// 62 145:invokevirtual #262 <Method zzaws$zza zzaws$zza.zzy(zzbah)>
// 63 148:invokevirtual #240 <Method zzbbo zzbbo$zza.zzadi()>
// 64 151:checkcast #242 <Class zzbbo>
// 65 154:areturn
}
}
public final zzaxi zzc(zzbah zzbah1)
throws GeneralSecurityException
{
zzbah1 = ((zzbah) ((zzaws)zzb(zzbah1)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokevirtual #265 <Method zzbcu zzb(zzbah)>
// 3 5:checkcast #20 <Class zzaws>
// 4 8:astore_1
return (zzaxi)(zzbbo)((zzbbo.zza) (zzaxi.zzyz().zzeb("type.googleapis.com/google.crypto.tink.EciesAeadHkdfPrivateKey").zzai(((zzazy) (zzbah1)).zzaav()).zzb(zzaxi.zzb.zzdky))).zzadi();
// 5 9:invokestatic #271 <Method zzaxi$zza zzaxi.zzyz()>
// 6 12:ldc2 #273 <String "type.googleapis.com/google.crypto.tink.EciesAeadHkdfPrivateKey">
// 7 15:invokevirtual #279 <Method zzaxi$zza zzaxi$zza.zzeb(String)>
// 8 18:aload_1
// 9 19:invokevirtual #284 <Method zzbah zzazy.zzaav()>
// 10 22:invokevirtual #288 <Method zzaxi$zza zzaxi$zza.zzai(zzbah)>
// 11 25:getstatic #294 <Field zzaxi$zzb zzaxi$zzb.zzdky>
// 12 28:invokevirtual #297 <Method zzaxi$zza zzaxi$zza.zzb(zzaxi$zzb)>
// 13 31:invokevirtual #240 <Method zzbbo zzbbo$zza.zzadi()>
// 14 34:checkcast #242 <Class zzbbo>
// 15 37:checkcast #267 <Class zzaxi>
// 16 40:areturn
}
}
| 46.817734 | 238 | 0.578546 |
00611bf67bb2d424a83bdc93d777684b8217cdf6 | 1,904 | /**Copyright 2013 The Cybercat project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cybercat.automation.addons.common;
import java.nio.file.Path;
import org.cybercat.automation.addons.common.MakeScreenshotEvent.ImageFormat;
import org.cybercat.automation.events.Event;
import org.cybercat.automation.events.EventManager.EventTypes;
public class ExceptionScreenEvent extends Event {
private Path path;
private Throwable exception;
private String fileName;
private ImageFormat format;
private Class<?> testClass;
public ExceptionScreenEvent(Class<?> testClass, Path path, Throwable exception, String fileName, ImageFormat format) {
super();
this.testClass = testClass;
this.path = path;
this.exception = exception;
this.fileName = fileName;
this.format = format;
}
@Override
public EventTypes getType() {
return EventTypes.EXCEPTION;
}
public Path getPath() {
return path;
}
public Throwable getException() {
return exception;
}
public String getFileName() {
return fileName;
}
public ImageFormat getFormat() {
return format;
}
public Class<?> getTestClass() {
return testClass;
}
public void setTestClass(Class<?> testClass) {
this.testClass = testClass;
}
}
| 26.816901 | 122 | 0.6875 |
980b3724cfcb67a6e05f149ea9afcd4d6d1ff774 | 5,546 | /**
* Copyright 2015-2018 the original author or authors.
*
* 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 ch.rasc.bsoncodec.test;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.assertj.core.data.MapEntry;
import org.bson.Document;
import org.bson.codecs.ObjectIdGenerator;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.junit.Test;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Projections;
import ch.rasc.bsoncodec.test.pojo.DatePojo;
import ch.rasc.bsoncodec.test.pojo.DatePojoCodec;
public class DatePojoTest extends AbstractMongoDBTest {
private final static String COLL_NAME = "Dates";
private MongoDatabase connect() {
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromCodecs(new DatePojoCodec(new ObjectIdGenerator())));
MongoDatabase db = getMongoClient().getDatabase("pojo")
.withCodecRegistry(codecRegistry);
return db;
}
private static Date createDate(int year, int month, int day) {
return Date.from(
LocalDate.of(year, month, day).atStartOfDay(ZoneOffset.UTC).toInstant());
}
private static DatePojo insert(MongoDatabase db) {
MongoCollection<DatePojo> coll = db.getCollection(COLL_NAME, DatePojo.class);
DatePojo pojo = new DatePojo();
pojo.setScalar(createDate(2015, 1, 1));
pojo.setArray(new Date[] { createDate(2015, 2, 1), createDate(2015, 2, 2),
createDate(2015, 2, 3) });
pojo.setArray2(new Date[][] { { createDate(2015, 3, 1), createDate(2015, 3, 2) },
{ createDate(2015, 4, 1), createDate(2015, 4, 2) } });
pojo.setList(Arrays.asList(createDate(2015, 12, 20)));
Set<Date> set = new HashSet<>();
set.add(createDate(2015, 8, 8));
set.add(createDate(2015, 9, 9));
pojo.setSet(set);
Map<Long, Date> map = new HashMap<>();
map.put(1L, createDate(2017, 1, 1));
map.put(2L, createDate(2017, 1, 2));
map.put(3L, createDate(2017, 1, 3));
map.put(4L, null);
pojo.setMap(map);
coll.insertOne(pojo);
return pojo;
}
private static DatePojo insertEmpty(MongoDatabase db) {
MongoCollection<DatePojo> coll = db.getCollection(COLL_NAME, DatePojo.class);
DatePojo pojo = new DatePojo();
coll.insertOne(pojo);
return pojo;
}
@Test
public void testInsertAndFind() {
MongoDatabase db = connect();
DatePojo pojo = insert(db);
MongoCollection<DatePojo> coll = db.getCollection(COLL_NAME, DatePojo.class);
DatePojo read = coll.find().first();
assertThat(read).usingRecursiveComparison().isEqualTo(pojo);
DatePojo empty = coll.find().projection(Projections.include("id")).first();
assertThat(empty.getScalar()).isNull();
assertThat(empty.getArray()).isNull();
assertThat(empty.getArray2()).isNull();
assertThat(empty.getList()).isNull();
assertThat(empty.getSet()).isNull();
assertThat(empty.getMap()).isNull();
}
@Test
public void testInsertAndFindEmpty() {
MongoDatabase db = connect();
DatePojo pojo = insertEmpty(db);
MongoCollection<DatePojo> coll = db.getCollection(COLL_NAME, DatePojo.class);
DatePojo read = coll.find().first();
assertThat(read).usingRecursiveComparison().isEqualTo(pojo);
}
@SuppressWarnings("unchecked")
@Test
public void testWithDocument() {
MongoDatabase db = connect();
DatePojo pojo = insert(db);
MongoCollection<Document> coll = db.getCollection(COLL_NAME);
Document doc = coll.find().first();
assertThat(doc).hasSize(7);
assertThat(doc.get("_id")).isEqualTo(pojo.getId());
assertThat(doc.get("scalar")).isEqualTo(createDate(2015, 1, 1));
assertThat((List<Date>) doc.get("array")).containsExactly(createDate(2015, 2, 1),
createDate(2015, 2, 2), createDate(2015, 2, 3));
assertThat((List<List<Date>>) doc.get("array2")).containsExactly(
Arrays.asList(createDate(2015, 3, 1), createDate(2015, 3, 2)),
Arrays.asList(createDate(2015, 4, 1), createDate(2015, 4, 2)));
assertThat((List<Date>) doc.get("list"))
.containsExactly(createDate(2015, 12, 20));
assertThat((List<Date>) doc.get("set")).containsOnly(createDate(2015, 8, 8),
createDate(2015, 9, 9));
assertThat((Map<String, Date>) doc.get("map")).containsOnly(
MapEntry.entry("1", createDate(2017, 1, 1)),
MapEntry.entry("2", createDate(2017, 1, 2)),
MapEntry.entry("3", createDate(2017, 1, 3)), MapEntry.entry("4", null));
}
@Test
public void testEmptyWithDocument() {
MongoDatabase db = connect();
DatePojo pojo = insertEmpty(db);
MongoCollection<Document> coll = db.getCollection(COLL_NAME);
Document doc = coll.find().first();
assertThat(doc).hasSize(1);
assertThat(doc.get("_id")).isEqualTo(pojo.getId());
}
}
| 33.817073 | 83 | 0.723585 |
e2712065cb059fc5b0383e6a63ff1553f0d991e8 | 778 | package com.flying.email.service;
import com.flying.email.bean.ConnectInfo;
import com.flying.email.dao.IConnectinfo;
import com.flying.email.daoimpl.ConnectInfoImpl;
import com.flying.email.factory.ConnectionFactory;
/**
* auth:flying date:2017年7月27日
**/
public class ConnectInfoService {
//// 数据操作接口
private IConnectinfo iConnectinfo = null;
/**
* 构造函数
*/
public ConnectInfoService() {
this.iConnectinfo = new ConnectInfoImpl();
}
/**
* 根据数据库链接名,获取数据库链接信息
*
* @param connectaccount
* 数据库链接名
* @return
*/
public ConnectInfo getConnectionInfoByAccount(String connectaccount) {
String condtion = " connectaccount='" + connectaccount + "'";
return this.iConnectinfo.getConnectInfo(ConnectionFactory.getConnection(), condtion);
}
}
| 22.228571 | 87 | 0.728792 |
68849a4d69f6ae364684a21dd74264aded9d14ce | 1,704 | package com.sqap.ui.config;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
public class CustomErrorFilter extends ZuulFilter {
private static final Logger LOG = LoggerFactory.getLogger(CustomErrorFilter.class);
@Override
public String filterType() {
return "error";
}
@Override
public int filterOrder() {
return -1; // Needs to run before SendErrorFilter which has filterOrder == 0
}
@Override
public boolean shouldFilter() {
// only forward to errorPath if it hasn't been forwarded to already
return RequestContext.getCurrentContext().getThrowable() != null;
}
@Override
public Object run() {
try {
LOG.error("Custom error filter runing ");
RequestContext ctx = RequestContext.getCurrentContext();
Throwable throwable = ctx.getThrowable();
if (throwable != null) {
LOG.error("Zuul failure detected: " + throwable.getMessage(), throwable);
// Populate context with new response values
ctx.setResponseBody("Zuul exception (ui):" + throwable.getMessage() + " cause: " + throwable.getCause());
ctx.getResponse().setContentType("application/json");
ctx.setResponseStatusCode(500); //Can set any error code as excepted
}
}
catch (Exception ex) {
LOG.error("Exception filtering in custom error filter", ex);
ReflectionUtils.rethrowRuntimeException(ex);
}
return null;
}
}
| 34.08 | 121 | 0.642019 |
f7a68c74422be45d15a239cabf363adce847dcb3 | 969 | package org.metricity.metric.service;
import java.util.function.Consumer;
import java.util.stream.Stream;
/** A structure that provides information about the current state of metric value computation */
public interface MetricWork {
/** @return Whether metric value computation is currently executing or scheduled for immediate execution */
boolean isActive();
/** @return The notional amount of work that is scheduled */
double getWaitingWorkAmount();
/** @return The number of metric channels for which computation is scheduled */
int getCurrentJobCount();
/** @return Metric channels for which data is currently being computed */
Stream<MetricChannel<?>> getCurrentJobs();
/**
* @param active
* The listener to be notified when new work is scheduled after being idle or when all work is completed
* @return A runnable to unsubscribe the listener
*/
Runnable addActiveListener(Consumer<Boolean> active);
}
| 35.888889 | 117 | 0.734778 |
2f67688c475bd665af4e5e52d46a42bafe05c7bc | 3,490 | /*
* Copyright (c) 2016 Spotify AB.
*
* 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.spotify.helios.servicescommon;
import com.google.common.collect.Lists;
import com.spotify.helios.ZooKeeperTestManager;
import com.spotify.helios.ZooKeeperTestingServerManager;
import com.spotify.helios.master.MasterZooKeeperRegistrar;
import com.spotify.helios.servicescommon.coordination.DefaultZooKeeperClient;
import com.spotify.helios.servicescommon.coordination.Paths;
import com.spotify.helios.servicescommon.coordination.ZooKeeperClient;
import org.apache.curator.framework.AuthInfo;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static com.spotify.helios.servicescommon.ZooKeeperAclProviders.digest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ZooKeeperAclInitializerTest {
private static final String AGENT_USER = "agent-user";
private static final String AGENT_PASSWORD = "agent-pass";
private static final String MASTER_USER = "master-user";
private static final String MASTER_PASSWORD = "master-pass";
private static final List<AuthInfo> MASTER_AUTH = Lists.newArrayList(new AuthInfo(
"digest", String.format("%s:%s", MASTER_USER, MASTER_PASSWORD).getBytes()));
private static final String CLUSTER_ID = "helios";
private ZooKeeperTestManager zk;
private ACLProvider aclProvider;
@Before
public void setUp() {
aclProvider = ZooKeeperAclProviders.heliosAclProvider(
MASTER_USER, digest(MASTER_USER, MASTER_PASSWORD),
AGENT_USER, digest(AGENT_USER, AGENT_PASSWORD));
zk = new ZooKeeperTestingServerManager();
}
@After
public void tearDown() throws Exception {
if (zk != null) {
zk.stop();
}
}
@Test
public void testInitializeAcl() throws Exception {
// setup the initial helios tree
final ZooKeeperClient zkClient = new DefaultZooKeeperClient(zk.curatorWithSuperAuth());
zkClient.ensurePath(Paths.configId(CLUSTER_ID));
new MasterZooKeeperRegistrar("helios-master").tryToRegister(zkClient);
// to start with, nothing should have permissions
for (final String path : zkClient.listRecursive("/")) {
assertEquals(ZooDefs.Ids.OPEN_ACL_UNSAFE, zkClient.getAcl(path));
}
// initialize ACL's
ZooKeeperAclInitializer.initializeAcl(zk.connectString(), CLUSTER_ID,
MASTER_USER, MASTER_PASSWORD,
AGENT_USER, AGENT_PASSWORD);
for (final String path : zkClient.listRecursive("/")) {
final List<ACL> expected = aclProvider.getAclForPath(path);
final List<ACL> actual = zkClient.getAcl(path);
assertEquals(expected.size(), actual.size());
assertTrue(expected.containsAll(actual));
}
}
}
| 34.9 | 91 | 0.740115 |
57be52b917600aff3e33d9acd1823daf7ca964e8 | 1,246 | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
int best = 0; int res = 0;
for (int i = 1; i <= n; i++) {
int sum = 0;
if (n % i == 0) {
int value = i;
while (value != 0) {
sum += value % 10;
value = value/10;
}
if (sum > best) {
best = sum;
res = i;
}
}
}
bufferedWriter.write(String.valueOf(res));
bufferedReader.close();
bufferedWriter.close();
}
}
| 28.976744 | 105 | 0.545746 |
fe7c8d185d8d313c67e5d1ca2484203cd14edc98 | 1,364 | package com.xtremelabs.robolectric.shadows;
import android.util.SparseArray;
import android.util.SparseIntArray;
import com.xtremelabs.robolectric.internal.Implementation;
import com.xtremelabs.robolectric.internal.Implements;
import com.xtremelabs.robolectric.internal.RealObject;
@Implements(SparseIntArray.class)
public class ShadowSparseIntArray {
private SparseArray<Integer> sparseArray = new SparseArray<Integer>();
@RealObject
private SparseIntArray realObject;
@Implementation
public int get( int key ){
return get( key, 0 );
}
@Implementation
public int get(int key, int valueIfKeyNotFound){
return sparseArray.get( key, valueIfKeyNotFound );
}
@Implementation
public void put( int key, int value ){
sparseArray.put( key, value );
}
@Implementation
public int size() {
return sparseArray.size();
}
@Implementation
public int indexOfValue( int value ) {
return sparseArray.indexOfValue( value );
}
@Implementation
public int keyAt( int index ){
return sparseArray.keyAt( index );
}
@Implementation
public int valueAt( int index ){
return sparseArray.valueAt( index );
}
@Implementation
@Override
public SparseIntArray clone() {
SparseIntArray clone = new SparseIntArray();
for (int i = 0, length = size(); i < length; i++) {
clone.put( keyAt(i), valueAt(i) );
}
return clone;
}
}
| 21.650794 | 71 | 0.734604 |
83bbc8704b909bb83351eb4fc4dbdc415db9f477 | 134 | package de.fraunhofer.abm.domain;
public class ProjectDTO {
public String id;
public String cp;
public String libcp_defaults;
}
| 13.4 | 33 | 0.768657 |
6f97a2251fca4326c1af8c6fa787af657c75c936 | 2,638 | package org.xcolab.view.pages.proposals.requests;
import org.xcolab.client.contest.proposals.StaticProposalContext;
import org.xcolab.util.enums.promotion.JudgingSystemActions;
import org.xcolab.view.pages.proposals.wrappers.ProposalFellowWrapper;
import java.io.Serializable;
import java.util.List;
public class FellowProposalScreeningBean extends RatingBean implements Serializable {
private JudgingSystemActions.FellowAction fellowScreeningAction;
private String fellowScreeningActionCommentBody;
private List<Long> selectedJudges;
private static final String[] EMAIL_TEMPLATES_TO_LOAD = {
"SCREENING_DO_NOT_ADVANCE_INCOMPLETE",
"SCREENING_DO_NOT_ADVANCE_OFF_TOPIC",
"SCREENING_DO_NOT_ADVANCE_OTHER"
};
private ContestEmailTemplateBean emailTemplateBean;
public FellowProposalScreeningBean(ProposalFellowWrapper proposalWrapper) {
super(proposalWrapper, StaticProposalContext.getProposalJudgeRatingClient()
.getRatingTypesForFellows());
fellowScreeningAction = proposalWrapper.getFellowAction();
selectedJudges = proposalWrapper.getSelectedJudges();
//initialize email templates
this.emailTemplateBean = new ContestEmailTemplateBean(EMAIL_TEMPLATES_TO_LOAD,
proposalWrapper.getName(), proposalWrapper.getContest().getTitle());
fellowScreeningActionCommentBody = proposalWrapper.getFellowActionComment();
}
public FellowProposalScreeningBean() {
}
public ContestEmailTemplateBean getEmailTemplateBean() {
return this.emailTemplateBean;
}
public int getFellowScreeningAction() {
if (fellowScreeningAction == null) {
return JudgingSystemActions.FellowAction.NO_DECISION.getAttributeValue();
} else {
return fellowScreeningAction.getAttributeValue();
}
}
public void setFellowScreeningAction(int fellowActionValue) {
this.fellowScreeningAction = JudgingSystemActions.FellowAction.fromInt(fellowActionValue);
}
public void addSelectedJudge(Long userId){
selectedJudges.add(userId);
}
public List<Long> getSelectedJudges() {
return selectedJudges;
}
public void setSelectedJudges(List<Long> selectedJudges) {
this.selectedJudges = selectedJudges;
}
public String getFellowScreeningActionCommentBody() {
return fellowScreeningActionCommentBody;
}
public void setFellowScreeningActionCommentBody(String fellowActionCommentBody) {
this.fellowScreeningActionCommentBody = fellowActionCommentBody;
}
}
| 33.820513 | 98 | 0.74602 |
fa8decbfda510fdd7cfcfd67f4aebdf8ee128205 | 2,716 | package com.jet.jet.action;
import android.app.Activity;
import android.support.annotation.CallSuper;
import android.support.v4.app.Fragment;
import android.view.View;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* 通用Action,注解有各自处理类
*
* @author zhengxiaobin
* @since 17/6/30
*/
public class BaseAction {
protected static final String TAG = "BaseAction";
// protected Class<? extends Activity> activityClass;
//
// public BaseAction(Class<? extends Activity> activityClass) {
// this.activityClass = activityClass;
// }
@CallSuper
public void run(Activity activity) throws Exception {
}
// @CallSuper
// public void run(Activity activity, Class<? extends Activity> activityClass) throws Exception {
//
// }
@CallSuper
public void run(Activity activity, Method method) throws Exception {
}
@CallSuper
public void run(Activity activity, Field field) throws Exception {
}
/**
* Fragment调用
*
* @param fragment
* @param field
* @param view
* @throws Exception
*/
@CallSuper
public void run(Fragment fragment, Field field, View view) throws Exception {
}
/**
* ViewHolder调用
*
* @param container
* @param field
* @param view
* @throws Exception
*/
@CallSuper
public void run(Object container, Field field, View view) throws Exception {
}
/**
* 基本类型返回值
*/
protected static void addValuePrimitive(ArrayList param, Class clazz) {
if (clazz.isAssignableFrom(int.class)) {
param.add(0);
} else if (clazz.isAssignableFrom(byte.class)) {
param.add((byte) 0);
} else if (clazz.isAssignableFrom(short.class)) {
param.add((short) 0);
} else if (clazz.isAssignableFrom(long.class)) {
param.add(0L);
} else if (clazz.isAssignableFrom(float.class)) {
param.add(0.0f);
} else if (clazz.isAssignableFrom(double.class)) {
param.add(0.0d);
} else if (clazz.isAssignableFrom(char.class)) {
param.add('\u0000');
} else if (clazz.isAssignableFrom(boolean.class)) {
param.add(false);
}
}
public static ArrayList getMethodDefault(Method method) {
Class<?>[] types = method.getParameterTypes();
ArrayList param = new ArrayList();
for (Class<?> type : types) {
if (type.isPrimitive()) {
addValuePrimitive(param, type);
} else {
//new Object();
param.add(null);
}
}
return param;
}
}
| 24.25 | 100 | 0.596465 |
69e542d37721eee894f9e7d0963d55ed9c6c6748 | 279 | package com.mathtabolism.util.unit;
/**
* An enum representing the types of Units available in a Unit System.
* <p>
* These values are {@link #DISTANCE}, {@link #WEIGHT}, and {@link #VOLUME}
*
* @author mlaursen
*
*/
public enum UnitType {
DISTANCE, WEIGHT, VOLUME,
}
| 19.928571 | 75 | 0.670251 |
499b937e4b218299ba0650773e25e7a12999ecd4 | 30,488 | package gameObjects.crud;
import authoringUtils.exception.*;
import conversion.authoring.SavedEntityDB;
import conversion.authoring.SerializerCRUD;
import gameObjects.IdManager;
import gameObjects.IdManagerClass;
import gameObjects.ThrowingBiConsumer;
import gameObjects.ThrowingConsumer;
import gameObjects.category.CategoryClass;
import gameObjects.category.CategoryInstance;
import gameObjects.category.CategoryInstanceFactory;
import gameObjects.category.SimpleCategoryClass;
import gameObjects.entity.EntityClass;
import gameObjects.entity.EntityInstance;
import gameObjects.entity.EntityInstanceFactory;
import gameObjects.entity.SimpleEntityClass;
import gameObjects.gameObject.GameObjectClass;
import gameObjects.gameObject.GameObjectInstance;
import gameObjects.gameObject.GameObjectType;
import gameObjects.player.PlayerClass;
import gameObjects.player.PlayerInstance;
import gameObjects.player.PlayerInstanceFactory;
import gameObjects.player.SimplePlayerClass;
import gameObjects.tile.SimpleTileClass;
import gameObjects.tile.TileClass;
import gameObjects.tile.TileInstance;
import gameObjects.tile.TileInstanceFactory;
import grids.Point;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class SimpleGameObjectsCRUD implements GameObjectsCRUDInterface {
private static final String ROOT_NAME = "Game Objects";
private int numCols;
private int numRows;
private String bgmPath;
private Map<String, GameObjectClass> gameObjectClassMapByName;
private Map<Integer, GameObjectClass> gameObjectClassMapById;
private Map<Integer, GameObjectInstance> gameObjectInstanceMapById;
private TileInstanceFactory myTileInstanceFactory;
private EntityInstanceFactory myEntityInstanceFactory;
private CategoryInstanceFactory myCategoryInstanceFactory;
// private SoundInstanceFactory mySoundInstanceFactory;
private PlayerInstanceFactory myPlayerInstanceFactory;
private IdManager myIdManager;
public SimpleGameObjectsCRUD(int numCols, int numRows, boolean fromXML) {
this.numCols = numCols;
this.numRows = numRows;
gameObjectClassMapByName = new HashMap<>();
gameObjectClassMapById = new HashMap<>();
gameObjectInstanceMapById = new HashMap<>();
myIdManager = new IdManagerClass(
getGameObjectClassFromMapFunc(),
getGameObjectInstanceFromMapFunc(),
gameObjectClassMapById,
gameObjectInstanceMapById
);
myTileInstanceFactory = instantiateTileInstanceFactory();
myEntityInstanceFactory = instantiateEntityInstanceFactory();
myCategoryInstanceFactory = instantiateCategoryInstanceFactory();
// mySoundInstanceFactory = instantiateSoundInstanceFactory();
myPlayerInstanceFactory = instantiatePlayerInstanceFactory();
if (fromXML) return;
try {
createCategoryClass(ROOT_NAME);
createCategoryClass("ENTITY");
createCategoryClass("TILE");
// createCategoryClass("SOUND");
createCategoryClass("PLAYER");
createEntityClass("O");
createEntityClass("X");
createTileClass("Default Grid");
createPlayerClass("Default Player");
// createSoundClass("Sound file");
} catch (DuplicateGameObjectClassException e) {
// TODO: proper error handling
e.printStackTrace();
}
}
public SimpleGameObjectsCRUD(SavedEntityDB saved) {
this(saved.numCols(), saved.numRows(), true);
bgmPath = saved.bgmPath();
for (var c : saved.classes()) {
switch (c.getType()) {
case CATEGORY:
createCategoryClass((CategoryClass) c);
break;
case PLAYER:
createPlayerClass((PlayerClass) c);
break;
case ENTITY:
createEntityClass((EntityClass) c);
break;
case TILE:
createTileClass((TileClass) c);
break;
// case SOUND: createSoundClass((SoundClass) c); break;
case UNSPECIFIED: // fuck it. honestly
}
}
for (var i : saved.instances()) {
try {
addGameObjectInstanceToMapFunc().accept(i);
} catch (InvalidIdException e) {
e.printStackTrace();
} // not gonna happen in normal... circumstances
}
}
@Override
public int getNumCols() {
return numCols;
}
@Override
public int getNumRows() {
return numRows;
}
private TileInstanceFactory instantiateTileInstanceFactory() {
return new TileInstanceFactory(
numRows,
numCols,
myIdManager.requestInstanceIdFunc(),
addGameObjectInstanceToMapFunc());
}
private EntityInstanceFactory instantiateEntityInstanceFactory() {
return new EntityInstanceFactory(
// TODO
myIdManager.verifyTileInstanceIdFunc(),
myIdManager.requestInstanceIdFunc(),
addGameObjectInstanceToMapFunc()
);
}
private CategoryInstanceFactory instantiateCategoryInstanceFactory() {
return new CategoryInstanceFactory(
myIdManager.requestInstanceIdFunc(),
addGameObjectInstanceToMapFunc());
}
private PlayerInstanceFactory instantiatePlayerInstanceFactory() {
return new PlayerInstanceFactory(
myIdManager.requestInstanceIdFunc(),
addGameObjectInstanceToMapFunc());
}
// private SoundInstanceFactory instantiateSoundInstanceFactory() {
// return new SoundInstanceFactory(
// myIdManager.requestInstanceIdFunc(),
// addGameObjectInstanceToMapFunc());
// }
private void checkDuplicate(String className)
throws DuplicateGameObjectClassException {
System.out.println(gameObjectClassMapByName.keySet());
if (gameObjectClassMapByName.containsKey(className)) {
throw new DuplicateGameObjectClassException();
}
}
@Override
public TileClass createTileClass(String className)
throws DuplicateGameObjectClassException {
checkDuplicate(className);
TileClass newTileClass = new SimpleTileClass(
className,
myTileInstanceFactory,
changeGameObjectClassNameFunc(),
getAllInstancesFunc(),
deleteGameObjectInstanceFunc());
addGameObjectClassToMaps(newTileClass);
return newTileClass;
}
private TileClass createTileClass(TileClass tile) {
tile.equipContext(
myTileInstanceFactory,
this::changeAllGameObjectInstancesClassName,
this::getAllInstances,
this::deleteGameObjectInstance
);
addGameObjectClassToMaps(tile);
return tile;
}
@Override
public CategoryClass createCategoryClass(String className)
throws DuplicateGameObjectClassException {
checkDuplicate(className);
CategoryClass newCategoryClass = new SimpleCategoryClass(
className,
myCategoryInstanceFactory,
changeGameObjectClassNameFunc(),
getAllInstancesFunc(),
deleteGameObjectInstanceFunc());
addGameObjectClassToMaps(newCategoryClass);
return newCategoryClass;
}
private CategoryClass createCategoryClass(CategoryClass category) {
category.equipContext(
myCategoryInstanceFactory,
this::changeAllGameObjectInstancesClassName,
this::getAllInstances,
this::deleteGameObjectInstance
);
addGameObjectClassToMaps(category);
return category;
}
// @Override
// public SoundClass createSoundClass(String className)
// throws DuplicateGameObjectClassException {
// checkDuplicate(className);
// SoundClass newSoundClass = new SimpleSoundClass(
// className,
// mySoundInstanceFactory,
// changeGameObjectClassNameFunc(),
// getAllInstancesFunc(),
// deleteGameObjectInstanceFunc());
// addGameObjectClassToMaps(newSoundClass);
// return newSoundClass;
// }
//
// private SoundClass createSoundClass(SoundClass sound) {
// sound.equipContext(
// mySoundInstanceFactory,
// this::changeAllGameObjectInstancesClassName,
// this::getAllInstances,
// this::deleteGameObjectInstance
// );
// addGameObjectClassToMaps(sound);
// return sound;
// }
@Override
public EntityClass createEntityClass(String className)
throws DuplicateGameObjectClassException {
checkDuplicate(className);
EntityClass newEntityClass = new SimpleEntityClass(
className,
myEntityInstanceFactory,
changeGameObjectClassNameFunc(),
getAllInstancesFunc(),
deleteGameObjectInstanceFunc());
addGameObjectClassToMaps(newEntityClass);
return newEntityClass;
}
private EntityClass createEntityClass(EntityClass entity) {
entity.equipContext(
myEntityInstanceFactory,
this::changeAllGameObjectInstancesClassName,
this::getAllInstances,
this::deleteGameObjectInstance
);
addGameObjectClassToMaps(entity);
return entity;
}
@Override
public PlayerClass createPlayerClass(String className)
throws DuplicateGameObjectClassException {
checkDuplicate(className);
PlayerClass newPlayerClass = new SimplePlayerClass(
className,
myPlayerInstanceFactory,
changeGameObjectClassNameFunc(),
getAllInstancesFunc(),
deleteGameObjectInstanceFunc());
addGameObjectClassToMaps(newPlayerClass);
return newPlayerClass;
}
private PlayerClass createPlayerClass(PlayerClass player) {
player.equipContext(
myPlayerInstanceFactory,
this::changeAllGameObjectInstancesClassName,
this::getAllInstances,
this::deleteGameObjectInstance
);
addGameObjectClassToMaps(player);
return player;
}
/**
* Reformate for example TILE to Tile.
*
* @param str original string
* @return reformatted string
*/
private String reformat(String str) {
return str.charAt(0) + str.substring(1).toLowerCase();
}
private GameObjectClass getSpecificClass(String className, GameObjectType objectType)
throws GameObjectClassNotFoundException {
if (!gameObjectClassMapByName.containsKey(className)) {
throw new GameObjectClassNotFoundException(reformat(objectType.name()));
}
return gameObjectClassMapByName.get(className);
}
@Override
public TileClass getTileClass(String className)
throws GameObjectClassNotFoundException {
return (TileClass) getSpecificClass(className, GameObjectType.TILE);
}
@Override
public EntityClass getEntityClass(String className)
throws GameObjectClassNotFoundException {
return (EntityClass) getSpecificClass(className, GameObjectType.ENTITY);
}
// @Override
// public SoundClass getSoundClass(String className)
// throws GameObjectClassNotFoundException {
// return (SoundClass) getSpecificClass(className, GameObjectType.SOUND);
// }
@Override
public PlayerClass getPlayerClass(String className)
throws GameObjectClassNotFoundException {
return (PlayerClass) getSpecificClass(className, GameObjectType.PLAYER);
}
@Override
public CategoryClass getCategoryClass(String className)
throws GameObjectClassNotFoundException {
return (CategoryClass) getSpecificClass(className, GameObjectType.CATEGORY);
}
private <T extends GameObjectInstance> T checkExist(String className, GameObjectType objectType)
throws GameObjectClassNotFoundException, GameObjectTypeException {
if (!gameObjectClassMapByName.containsKey(className)) {
throw new GameObjectClassNotFoundException(reformat(objectType.name()));
}
GameObjectClass t = gameObjectClassMapByName.get(className);
if (t.getType() != objectType) {
throw new GameObjectTypeException(className, objectType);
}
return (T) t;
}
@Override
public TileInstance createTileInstance(String className, Point topLeftCoord)
throws GameObjectClassNotFoundException, GameObjectTypeException {
TileClass t = checkExist(className, GameObjectType.TILE);
return createTileInstance(t, topLeftCoord);
}
@Override
public TileInstance createTileInstance(TileClass tileClass, Point topLeftCoord)
throws GameObjectTypeException {
try {
return myTileInstanceFactory.createInstance(tileClass, topLeftCoord);
} catch (InvalidIdException e) {
// TODO
e.printStackTrace();
return null;
}
}
@Override
public EntityInstance createEntityInstance(String className, Point point)
throws GameObjectClassNotFoundException, GameObjectTypeException {
EntityClass t = checkExist(className, GameObjectType.ENTITY);
return createEntityInstance(t, point);
}
@Override
public EntityInstance createEntityInstance(EntityClass entityClass, Point point)
throws GameObjectTypeException {
try {
return myEntityInstanceFactory.createInstance(entityClass, point);
} catch (InvalidIdException e) {
// TODO
e.printStackTrace();
return null;
}
}
@Override
public CategoryInstance createCategoryInstance(String className)
throws GameObjectClassNotFoundException, GameObjectTypeException {
CategoryClass t = checkExist(className, GameObjectType.CATEGORY);
return createCategoryInstance(t);
}
@Override
public CategoryInstance createCategoryInstance(CategoryClass categoryClass)
throws GameObjectTypeException {
try {
return myCategoryInstanceFactory.createInstance(categoryClass);
} catch (InvalidIdException e) {
// TODO
e.printStackTrace();
return null;
}
}
// @Override
// public SoundInstance createSoundInstance(String className)
// throws GameObjectClassNotFoundException, GameObjectTypeException {
// SoundClass t = checkExist(className, GameObjectType.SOUND);
// return createSoundInstance(t);
// }
//
// @Override
// public SoundInstance createSoundInstance(SoundClass soundClass)
// throws GameObjectTypeException {
// try {
// return mySoundInstanceFactory.createInstance(soundClass);
// } catch (InvalidIdException e) {
// // TODO
// e.printStackTrace();
// return null;
// }
// }
@Override
public PlayerInstance createPlayerInstance(String className)
throws GameObjectClassNotFoundException, GameObjectTypeException {
PlayerClass t = checkExist(className, GameObjectType.PLAYER);
return createPlayerInstance(t);
}
@Override
public PlayerInstance createPlayerInstance(PlayerClass playerClass)
throws GameObjectTypeException {
try {
return myPlayerInstanceFactory.createInstance(playerClass);
} catch (InvalidIdException e) {
// TODO
e.printStackTrace();
return null;
}
}
@SuppressWarnings("unchecked")
@Override
public <T extends GameObjectClass> T getGameObjectClass(String className)
throws GameObjectClassNotFoundException {
if (!gameObjectClassMapByName.containsKey(className)) {
throw new GameObjectClassNotFoundException("GameObject");
}
return (T) gameObjectClassMapByName.get(className);
}
@SuppressWarnings("unchecked")
@Override
public <T extends GameObjectInstance> T getGameObjectInstance(int instanceId)
throws GameObjectInstanceNotFoundException {
if (!gameObjectInstanceMapById.containsKey(instanceId)) {
throw new GameObjectInstanceNotFoundException("GameObject");
}
return (T) gameObjectInstanceMapById.get(instanceId);
}
@Override
public Collection<GameObjectInstance> getAllInstances() {
return gameObjectInstanceMapById.values();
}
@Override
public Collection<GameObjectClass> getAllClasses() {
return gameObjectClassMapById.values();
}
@Override
public Collection<GameObjectInstance> getAllInstances(String className) {
Set<GameObjectInstance> instancesSet = new HashSet<>();
for (Map.Entry<Integer, GameObjectInstance> entry : gameObjectInstanceMapById.entrySet()) {
if (entry.getValue().getClassName().equals(className)) {
instancesSet.add(entry.getValue());
}
}
return instancesSet;
}
@Override
public Collection<GameObjectInstance> getAllInstances(GameObjectClass gameObjectClass) {
String className = gameObjectClass.getClassName();
return getAllInstances(className);
}
// TODO
@Override
public Collection<GameObjectInstance> getAllInstancesAtPoint(int x, int y) {
return null;
}
// TODO
@Override
public Collection<GameObjectInstance> getAllInstancesAtPoint(Point point) {
return null;
}
/**
* This method deletes the GameObjectClasses with the input String name. It scans through all possible maps of the String -> GameObjectClass.
*
* @param className : The name of the GameObjectClass to be deleted.
* @return true if the GameObjectClass is successfully deleted and false otherwise.
*/
@Override
public boolean deleteGameObjectClass(String className) {
if (!gameObjectClassMapByName.containsKey(className)) {
return false;
}
return deleteGameObjectClass(gameObjectClassMapByName.get(className));
}
@Override
public boolean deleteGameObjectClass(int classId) {
if (!gameObjectClassMapById.containsKey(classId)) {
return false;
}
return deleteGameObjectClass(gameObjectClassMapById.get(classId));
}
@Override
public boolean deleteGameObjectClass(GameObjectClass gameObjectClass) {
try {
removeGameObjectClassFromMaps(gameObjectClass);
} catch (InvalidIdException e) {
// TODO
e.printStackTrace();
}
try {
return removeAllGameObjectInstancesFromMap(gameObjectClass.getClassName());
} catch (InvalidIdException e) {
// TODO
e.printStackTrace();
return false;
}
}
@Override
public boolean deleteGameObjectInstance(int instanceId) {
if (!gameObjectInstanceMapById.containsKey(instanceId)) {
return false;
}
try {
removeGameObjectInstanceFromMap(instanceId);
} catch (InvalidIdException e) {
// TODO
e.printStackTrace();
}
return true;
}
/**
* Delete all instances currently in the CRUD.
*/
@Override
public void deleteAllInstances() {
gameObjectInstanceMapById.clear();
}
/**
* This method is a convenient method that creates different GameObjectClasses, depending on the class name and the gameObjectType.
*
* @param gameObjectType : The GameObjectType that determines the type of GameObjectClass that is to be created.
* @param name : The name of the GameObjectClass to be created.
* @return A Subclass of GameObjectClass depending on the String name and the GameObjectType.
* @throws DuplicateGameObjectClassException
*/
@SuppressWarnings("unchecked")
@Override
public <E extends GameObjectClass> E createGameObjectClass(GameObjectType gameObjectType, String name) throws DuplicateGameObjectClassException {
switch (gameObjectType) {
case CATEGORY:
return (E) createCategoryClass(name);
// case SOUND:
// return (E) createSoundClass(name);
case TILE:
return (E) createTileClass(name);
case ENTITY:
return (E) createEntityClass(name);
case UNSPECIFIED:
// TODO
break;
case PLAYER:
return (E) createPlayerClass(name);
}
return null;
}
/**
* This method is a convenient method that creates concrete GameObjectInstances, depending on the type of GameObjectClass that is passed in or inferred from class name.
*
* @param name : The String class name of the input GameObjectClass.
* @param topleft : A Point representing the topleft of the GameObjectInstance deployed.
* @return A concrete GameObjectInstance inferred from input.
* @throws GameObjectTypeException
* @throws GameObjectClassNotFoundException
*/
@Override
public <E extends GameObjectInstance> E createGameObjectInstance(String name, Point topleft) throws GameObjectClassNotFoundException, GameObjectTypeException {
if (!gameObjectClassMapByName.containsKey(name)) {
throw new GameObjectClassNotFoundException(String.format("%s is not a valid GameObjectClass", name));
}
GameObjectClass gameObjectClass = gameObjectClassMapByName.get(name);
return createGameObjectInstance(gameObjectClass, topleft);
}
/**
* This method is a convenient method that creates concrete GameObjectInstances, depending on the type of GameObjectClass that is passed in or inferred from class name.
*
* @param gameObjectClass : The input GameObjectClass.
* @param topleft : A Point representing the topleft of the GameObjectInstance deployed.
* @return A concrete GameObjectInstance inferred from input.
* @throws GameObjectTypeException
*/
@SuppressWarnings("unchecked")
@Override
public <E extends GameObjectInstance> E createGameObjectInstance(GameObjectClass gameObjectClass, Point topleft) throws GameObjectTypeException {
switch (gameObjectClass.getType()) {
case ENTITY:
return (E) createEntityInstance((EntityClass) gameObjectClass, topleft);
case PLAYER:
// TODO: confirm Player API
return (E) createPlayerInstance((PlayerClass) gameObjectClass);
case UNSPECIFIED:
// TODO
break;
case TILE:
return (E) createTileInstance((TileClass) gameObjectClass, topleft);
// case SOUND:
// return (E) createSoundInstance((SoundClass) gameObjectClass);
case CATEGORY:
return (E) createCategoryInstance((CategoryClass) gameObjectClass);
}
return null;
}
@Override
public boolean changeGameObjectClassName(String oldClassName, String newClassName)
throws InvalidOperationException {
if (!gameObjectClassMapByName.containsKey(oldClassName)) {
return false;
}
if (newClassName.equals(oldClassName)) {
return true;
}
GameObjectClass gameObjectClass = gameObjectClassMapByName.get(oldClassName);
gameObjectClass.setClassName(newClassName);
gameObjectClassMapByName.put(newClassName, gameObjectClass);
gameObjectClassMapByName.remove(oldClassName);
changeAllGameObjectInstancesClassName(oldClassName, newClassName);
return true;
}
private void addGameObjectClassToMaps(GameObjectClass g) {
myIdManager.requestClassIdFunc().accept(g);
gameObjectClassMapByName.put(g.getClassName(), g);
gameObjectClassMapById.put(g.getClassId(), g);
}
private void removeGameObjectClassFromMaps(GameObjectClass g)
throws InvalidIdException {
gameObjectClassMapByName.remove(g.getClassName());
gameObjectClassMapById.remove(g.getClassId());
}
private void removeGameObjectInstanceFromMap(int instanceId)
throws InvalidIdException {
GameObjectInstance gameObjectInstance = gameObjectInstanceMapById.get(instanceId);
gameObjectInstanceMapById.remove(instanceId);
}
private boolean removeAllGameObjectInstancesFromMap(String className)
throws InvalidIdException {
if (!gameObjectClassMapByName.containsKey(className)) {
return false;
}
for (Map.Entry<Integer, GameObjectInstance> e : gameObjectInstanceMapById.entrySet()) {
if (e.getValue().getClassName().equals(className)) {
removeGameObjectInstanceFromMap(e.getKey());
}
}
return true;
}
private void changeAllGameObjectInstancesClassName(String oldClassName, String newClassName)
throws InvalidOperationException {
for (Map.Entry<Integer, GameObjectInstance> e : gameObjectInstanceMapById.entrySet()) {
if (e.getValue().getClassName().equals(oldClassName)) {
e.getValue().setClassName(newClassName);
}
}
}
private Function<Integer, GameObjectClass> getGameObjectClassFromMapFunc() {
return classId -> gameObjectClassMapById.get(classId);
}
private Function<Integer, GameObjectInstance> getGameObjectInstanceFromMapFunc() {
return instanceId -> gameObjectInstanceMapById.get(instanceId);
}
private Function<String, Collection<GameObjectInstance>> getAllInstancesFunc() {
return this::getAllInstances;
}
private Function<Integer, Boolean> deleteGameObjectInstanceFunc() {
return this::deleteGameObjectInstance;
}
private ThrowingBiConsumer<String, String, InvalidOperationException> changeGameObjectClassNameFunc() {
return this::changeGameObjectClassName;
}
private ThrowingConsumer<GameObjectInstance, InvalidIdException> addGameObjectInstanceToMapFunc() {
return gameObjectInstance -> {
int instanceId = gameObjectInstance.getInstanceId();
if (instanceId == 0) {
throw new InvalidIdException();
}
gameObjectInstanceMapById.put(instanceId, gameObjectInstance);
};
}
@Override
public void setDimension(int width, int height) {
numCols = width;
numRows = height;
}
public int getWidth() {
return numCols;
}
public void setWidth(int width) {
numCols = width;
}
public int getHeight() {
return numRows;
}
public void setHeight(int height) {
numRows = height;
}
@Override
public Iterable<EntityClass> getEntityClasses() {
return getSpecificClasses(GameObjectType.ENTITY);
}
@Override
public String getBGMpath() {
return bgmPath;
}
@Override
public void setBGMpath(String path) {
System.out.println(bgmPath);
bgmPath = path;
}
@Override
public Iterable<TileClass> getTileClasses() {
return getSpecificClasses(GameObjectType.TILE);
}
@Override
public Iterable<CategoryClass> getCategoryClasses() {
return getSpecificClasses(GameObjectType.CATEGORY);
}
//
// @Override
// public Iterable<SoundClass> getSoundClasses() { return getSpecificClasses(GameObjectType.SOUND); }
@Override
public Iterable<PlayerClass> getPlayerClasses() {
return getSpecificClasses(GameObjectType.PLAYER);
}
private <T extends GameObjectClass> Set<T> getSpecificClasses(GameObjectType objectType) {
Set<T> ret = new HashSet<>();
for (GameObjectClass objectClass : gameObjectClassMapByName.values()) {
if (objectClass.getType() == objectType) {
ret.add((T) objectClass);
}
}
return ret;
}
private <T extends GameObjectInstance> Set<T> getSpecificInstances(GameObjectType objectType) {
Set<T> ret = new HashSet<>();
for (GameObjectInstance objectInstance : gameObjectInstanceMapById.values()) {
if (objectInstance.getType() == objectType) {
ret.add((T) objectInstance);
}
}
return ret;
}
@Override
public Iterable<EntityInstance> getEntityInstances() {
return getSpecificInstances(GameObjectType.ENTITY);
}
@Override
public Iterable<TileInstance> getTileInstances() {
return getSpecificInstances(GameObjectType.TILE);
}
@Override
@Deprecated
public Iterable<PlayerInstance> getPlayerInstances() {
return null;
}
@Override
public Iterable<CategoryInstance> getCategoryInstances() {
return getSpecificInstances(GameObjectType.CATEGORY);
}
// @Override
// public Iterable<SoundInstance> getSoundInstances() {
// return getSpecificInstances(GameObjectType.SOUND);
// }
@Override
public Set<String> getPlayerNames(GameObjectInstance gameObjectInstance) {
return gameObjectClassMapByName.values().stream()
.filter(gameObjectClass -> gameObjectClass.getType() == GameObjectType.PLAYER)
.filter(gameObjectClass -> ((PlayerClass) gameObjectClass).isOwnedByPlayer(gameObjectInstance))
.map(GameObjectClass::getClassName)
.collect(Collectors.toSet());
}
@Override
public String toXML() {
return new SerializerCRUD().getXMLString(this);
}
} | 35.327926 | 172 | 0.659473 |
9eba61e69bdf53eba31473606f73bcb6be4c0ebb | 11,650 | package com.emistoolbox.server.renderer.gis.impl;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import com.emistoolbox.common.renderer.ChartConfig;
import com.emistoolbox.server.ServerUtil;
import com.emistoolbox.server.renderer.gis.ColourScheme;
import com.emistoolbox.server.renderer.gis.GisFeatureSet;
public class GisImageRendererImpl extends GisRendererImpl
{
private BufferedImage bufferedImage;
private AffineTransform transformation;
private Graphics2D graphics;
private StringBuffer htmlMap;
private Map<Point, String> labels = new HashMap<Point, String>();
private String filename = null;
public List<String> getFileNames()
{ return Arrays.asList(new String[] { filename }); }
public List<String> getContentTypes()
{ return Arrays.asList(new String[] { "image/png" }); }
synchronized public void renderMap(List<GisFeatureSet> results, List<ColourScheme> colours, ChartConfig config, File outputFile) throws IOException
{
filename = outputFile.getName();
double[] boundary = getBoundary(results);
bufferedImage = new BufferedImage(config.getChartWidth(), config.getChartHeight(), 7);
graphics = (Graphics2D) bufferedImage.getGraphics();
graphics.setFont(new Font("Sanserif", Font.PLAIN, 10));
transformation = getTransformation(boundary[0], boundary[1], boundary[2], boundary[3], config.getChartWidth() - 5, config.getChartHeight() - 5);
htmlMap = new StringBuffer();
renderAll(results, colours);
for (Map.Entry<Point, String> entry : labels.entrySet())
renderLabel(entry.getValue(), entry.getKey().getX(), entry.getKey().getY());
// Finish request.
ImageIO.write(bufferedImage, "PNG", outputFile);
bufferedImage = null;
graphics = null;
transformation = null;
labels.clear();
}
public String getHtmlMap()
{ return htmlMap == null ? null : htmlMap.toString(); }
protected void renderFeatureSet(GisFeatureSet feature, ColourScheme colourScheme, boolean setRange, boolean showLabels, boolean selected)
{
if (setRange)
{
double max = (-1.0D / 0.0D);
double min = (1.0D / 0.0D);
for (int f = 0; f < feature.getCount(); f++)
{
double value = feature.getValue(f);
if (Double.isNaN(value))
continue;
max = Math.max(value, max);
min = Math.min(value, min);
}
colourScheme.setRange(min, max);
}
for (int f = 0; f < feature.getCount(); f++)
{
System.out.println(feature.getTitle(f) + " " + feature.getBoundary(feature.getFeature(f)));
draw(feature.getFeature(f), colourScheme, feature.getValue(f), feature.getTitle(f), showLabels, selected ? htmlMap : null);
}
}
protected void renderLabel(String text, double x, double y)
{
graphics.setColor(Color.BLACK);
graphics.drawString(text, (int) x, (int) y);
}
private void draw(double[] feature, ColourScheme colours, double value, String title, boolean showLabels, StringBuffer mapBuffer)
{
graphics.setStroke(colours.getLineStroke(value));
Color fillColor = colours.getFillColour(value);
Color lineColor = colours.getLineColour(value);
Point2D labelPt = null;
if (feature.length == 2)
{
Point2D pt = transformation.transform(new Point2D.Double(feature[0], feature[1]), new Point2D.Double());
graphics.setBackground(fillColor);
graphics.setColor(fillColor);
graphics.fillRect((int) pt.getX() - 1, (int) pt.getY() - 1, 3, 3);
if (mapBuffer != null)
addMapBuffer(mapBuffer, value, title, pt);
if (showLabels)
labelPt = new Point((int) pt.getX(), (int) pt.getY());
}
else
{
labelPt = null;
double bestLabelWeight = 0.0D;
int index = 0;
while (index < feature.length - 1)
{
Point2D.Double resultPoint = new Point2D.Double();
double resultFactor = 0.0D;
GeneralPath path = new GeneralPath();
int startIndex = index;
path.moveTo(feature[index], feature[(index + 1)]);
index += 2;
while ((index < feature.length - 1) && (!Double.isNaN(feature[index])))
{
path.lineTo(feature[index], feature[(index + 1)]);
if (showLabels)
{
double factor = getFactor(feature, index - 2, index);
resultFactor += factor;
resultPoint = addPoint(resultPoint, factorPoint(getPoint(feature, index - 2, index), factor));
}
index += 2;
}
if (index <= startIndex + 4)
{
index++;
continue;
}
path.closePath();
transformAndDraw(graphics, path, transformation, lineColor, fillColor);
if (mapBuffer != null)
addMapBuffer(mapBuffer, value, title, path, transformation);
if (showLabels)
{
double factor = getFactor(feature, index - 2, startIndex);
resultFactor += factor;
resultPoint = addPoint(resultPoint, factorPoint(getPoint(feature, index - 2, startIndex), factor));
}
if (Math.abs(resultFactor) > bestLabelWeight)
{
bestLabelWeight = Math.abs(resultFactor);
labelPt = factorPoint(resultPoint, 1.0D / (resultFactor * 3.0D));
}
index++;
}
if (labelPt != null)
labelPt = transformation.transform(labelPt, null);
}
if (showLabels && (labelPt != null))
{
graphics.setColor(Color.BLACK);
title = getText(title, value, false); // (no more values in image) mapBuffer != null);
FontMetrics fm = graphics.getFontMetrics(graphics.getFont());
Rectangle2D rect = fm.getStringBounds(title, graphics);
labels.put(new Point((int) (labelPt.getX() - rect.getWidth() / 2.0D), (int) (labelPt.getY() + rect.getHeight() / 2.0D)), title);
}
}
private AffineTransform getTransformation(double xmin, double ymin, double xmax, double ymax, int width, int height)
{
double scale = Math.min(width / (xmax - xmin), height / (ymax - ymin));
AffineTransform result = new AffineTransform();
result.translate(0.0D, height);
result.scale(1.0D, -1.0D);
result.translate((width - (xmax - xmin) * scale) / 2.0D, (height - (ymax - ymin) * scale) / 2.0D);
result.scale(scale, scale);
result.translate(-xmin, -ymin);
return result;
}
private void addMapBuffer(StringBuffer mapBuffer, double value, String text, Point2D pt)
{
addMapBuffer(mapBuffer, "rect", value, text, (int) (pt.getX() - 1.0D) + "," + (int) (pt.getY() - 1.0D) + "," + (int) (pt.getX() + 2.0D) + "," + (int) (pt.getY() + 2.0D));
}
private void addMapBuffer(StringBuffer mapBuffer, double value, String text, GeneralPath path, AffineTransform transformation)
{
double lastX = 0.0D;
double lastY = 0.0D;
StringBuffer coords = new StringBuffer();
for (PathIterator iterator = path.getPathIterator(null); !iterator.isDone(); iterator.next())
{
double[] pathCoords = new double[6];
Point2D pt = null;
switch (iterator.currentSegment(pathCoords)) {
case 1:
pt = getPoint(pathCoords, transformation);
if ((Math.abs(lastX - pt.getX()) < 3.0D) && (Math.abs(lastY - pt.getY()) < 3.0D))
{
continue;
}
case 0:
if (pt == null)
{
pt = getPoint(pathCoords, transformation);
}
lastX = pt.getX();
lastY = pt.getY();
if (coords.length() > 0)
{
coords.append(",");
}
coords.append((int) pt.getX() + "," + (int) pt.getY());
}
}
addMapBuffer(mapBuffer, "poly", value, text, coords.toString());
}
private Point2D getPoint(double[] coords, AffineTransform transformation)
{
return transformation.transform(new Point2D.Double(coords[0], coords[1]), null);
}
private void addMapBuffer(StringBuffer mapBuffer, String shape, double value, String text, String coords)
{
String title = getText(text, value, true);
mapBuffer.append("<area shape='" + shape + "' onClick='return false;' nohref='' alt='" + title + "' title='" + title + "' coords='" + coords + "'>\n");
}
private String getText(String text, double value, boolean useValue)
{
String tmp = null;
if (useValue)
{
tmp = ServerUtil.getFormattedValue(getValueFormat(), value);
if (StringUtils.isEmpty(text))
return tmp;
if (StringUtils.isEmpty(tmp))
return text;
return text + " (" + tmp + ")";
}
return text;
}
private double getFactor(double[] values, int index1, int index2)
{
return values[index1] * values[(index2 + 1)] - values[index2] * values[(index1 + 1)];
}
private Point2D.Double getPoint(double[] values, int index1, int index2)
{
return new Point2D.Double(values[index1] + values[index2], values[(index1 + 1)] + values[(index2 + 1)]);
}
private Point2D.Double addPoint(Point2D.Double pt1, Point2D.Double pt2)
{
return new Point2D.Double(pt1.x + pt2.x, pt1.y + pt2.y);
}
private Point2D.Double factorPoint(Point2D.Double pt, double factor)
{
return new Point2D.Double(pt.x * factor, pt.y * factor);
}
private Shape transformAndDraw(Graphics2D g, GeneralPath path, AffineTransform t, Color lineColor, Color fillColor)
{
Shape s = path.createTransformedShape(t);
Color old = g.getColor();
if (fillColor != null)
{
g.setColor(fillColor);
g.fill(s);
}
g.setColor(lineColor);
g.draw(s);
g.setColor(old);
return s;
}
}
| 36.292835 | 179 | 0.553648 |
19665eea1dca3a1bb8a70f751dd64615b5db80db | 2,277 | package com.hdsf.base.file;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
/**
* 递归寻找某目录下 符合条件的所有文件
*/
class Search implements FileVisitor {
private final PathMatcher matcher;
public Search(String ext) {
matcher = FileSystems.getDefault().getPathMatcher("glob:" + ext);
}
public void judgeFile(Path file) throws IOException {
Path name = file.getFileName();
if (name != null && matcher.matches(name)) {
System.out.println("Searched file was found: " + name + " in " + file.toRealPath().toString());
}
}
/**
* 访问目录后调用
* @param dir
* @param exc
* @return
* @throws IOException
*/
@Override
public FileVisitResult postVisitDirectory(Object dir, IOException exc) throws IOException {
System.out.println("Visited: " + (Path) dir);
return FileVisitResult.CONTINUE;
}
/**
* 访问目录前调用
* @param dir
* @param attrs
* @return
* @throws IOException
*/
@Override
public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
/**
* 访问文件时调用
* @param file
* @param attrs
* @return
* @throws IOException
*/
@Override
public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
judgeFile((Path) file);
return FileVisitResult.CONTINUE;
}
/**
* 访问文件失败后调用
* @param file
* @param exc
* @return
* @throws IOException
*/
@Override
public FileVisitResult visitFileFailed(Object file, IOException exc) throws IOException {
// report an error if necessary
return FileVisitResult.CONTINUE;
}
}
//����ijһ��Ŀ¼�����е�jpg�ļ����������ļ���
public class SearchJPGFiles {
public static void main(String[] args) throws IOException {
String ext = "*.jpg";
Path fileTree = Paths.get("./");
Search walk = new Search(ext);
EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
Path path = Files.walkFileTree(fileTree, opts, Integer.MAX_VALUE, walk);
}
}
| 23.71875 | 101 | 0.71278 |
7c9589be028238d62762acaccc202c2ab67843c9 | 4,077 | /*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dempsy.distconfig.apahcevfs;
import static net.dempsy.distconfig.apahcevfs.Utils.cleanPath;
import static net.dempsy.distconfig.apahcevfs.Utils.getLatest;
import static net.dempsy.distconfig.apahcevfs.Utils.getVersion;
import static net.dempsy.distconfig.apahcevfs.Utils.nextFile;
import static net.dempsy.distconfig.apahcevfs.Utils.read;
import static net.dempsy.util.Functional.mapChecked;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Properties;
import java.util.function.Function;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.VFS;
import net.dempsy.distconfig.PropertiesStore;
public class ApacheVfsPropertiesStore extends PropertiesStore {
private final FileObject parentDirObj;
private final static String COMMENT = "These properties loaded using " + ApacheVfsPropertiesStore.class.getSimpleName();
private final static Function<Exception, IOException> em = e -> IOException.class.isAssignableFrom(e.getClass()) ? (IOException) e
: new IOException(e);
public ApacheVfsPropertiesStore(final String parentUri, final String childPropertiesName) throws IOException {
final FileObject baseDir = mapChecked(() -> VFS.getManager().resolveFile(parentUri), em);
parentDirObj = mapChecked(() -> VFS.getManager().resolveFile(baseDir, cleanPath(childPropertiesName)), em);
}
public ApacheVfsPropertiesStore(final String pathUri) throws IOException {
parentDirObj = mapChecked(() -> VFS.getManager().resolveFile(pathUri), em);
}
@Override
public int push(final Properties props) throws IOException {
return mapChecked(() -> {
final FileObject next = nextFile(getLatest(parentDirObj), parentDirObj);
try (OutputStream os = next.getContent().getOutputStream()) {
props.store(os, COMMENT);
}
return new Integer(getVersion(next));
} , em).intValue();
}
@Override
public int merge(final Properties props) throws IOException {
return mapChecked(() -> {
final FileObject latest = getLatest(parentDirObj);
if (latest == null)
return push(props);
final Properties oldProps = read(latest);
final Properties newProps = new Properties();
newProps.putAll(oldProps);
newProps.putAll(props);
final FileObject next = nextFile(latest, parentDirObj);
try (OutputStream os = next.getContent().getOutputStream()) {
newProps.store(os, COMMENT);
}
return new Integer(getVersion(next));
} , em).intValue();
}
@Override
public int clear(final String... props) throws IOException {
return mapChecked(() -> {
final FileObject latest = getLatest(parentDirObj);
if (latest == null)
return -1;
final Properties oldProps = read(latest);
final Properties newProps = new Properties();
newProps.putAll(oldProps);
Arrays.stream(props).forEach(newProps::remove);
final FileObject next = nextFile(latest, parentDirObj);
try (OutputStream os = next.getContent().getOutputStream()) {
newProps.store(os, COMMENT);
}
return new Integer(getVersion(next));
} , em).intValue();
}
}
| 38.462264 | 134 | 0.676968 |
abd3e3d99580cb1bc9cac0ef67eefac2e946ad56 | 1,591 | package br.com.zupacademy.breno.casadocodigo.validator;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import br.com.zupacademy.breno.casadocodigo.cliente.ClienteRequest;
import br.com.zupacademy.breno.casadocodigo.estado.Estado;
import br.com.zupacademy.breno.casadocodigo.pais.Pais;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Component
public class EstadoPertenceAPaisValidator implements Validator{
@PersistenceContext
private EntityManager manager;
@Override
public boolean supports(Class<?> clazz) {
return ClienteRequest.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
if(errors.hasErrors()) {
return;
}
ClienteRequest request = (ClienteRequest) target;
Pais pais = manager.find(Pais.class, request.getPaisId());
Query query = manager.createQuery("from Estado where pais_id = :id");
query.setParameter("id", request.getPaisId());
if (query.getResultList().isEmpty())
return;
Estado estado = null;
if (request.getEstadoId() != null)
estado = manager.find(Estado.class, request.getEstadoId());
if(estado == null || !estado.pertence(pais)) {
errors.rejectValue("estadoId",null,"este estado não é o do país selecionado");
}
}
} | 30.596154 | 91 | 0.680704 |
884ec8a28e29377b4df7f585c496f101ea3165f7 | 2,297 | package org.aigor.r2dbc.presto;
interface PrestoSampleQueries {
String HELLO_QUERY =
"select " +
"15 as day, " +
"'February' as month, " +
"'Lviv' as city, " +
"'Java Day Lviv' as event";
String TPC_H_QUERY_5 =
"SELECT\n" +
" n.name,\n" +
" sum(l.extendedprice * (1 - l.discount)) as revenue\n" +
"FROM\n" +
" customer c,\n" +
" orders o,\n" +
" lineitem l,\n" +
" supplier s,\n" +
" nation n,\n" +
" region r\n" +
"WHERE\n" +
" c.custkey = o.custkey\n" +
" AND l.orderkey = o.orderkey\n" +
" AND l.suppkey = s.suppkey\n" +
" AND c.nationkey = s.nationkey\n" +
" AND s.nationkey = n.nationkey\n" +
" AND n.regionkey = r.regionkey\n" +
" AND r.name = 'ASIA'\n" +
" AND o.orderdate >= date '1994-01-01'\n" +
" AND o.orderdate < date '1994-01-01' + interval '1' year\n" +
"GROUP BY\n" +
" n.name\n" +
"ORDER BY\n" +
" revenue desc";
String TPC_H_QUERY_10 = "SELECT\n" +
" c.custkey,\n" +
" c.name,\n" +
" sum(l.extendedprice * (1 - l.discount)) as revenue,\n" +
" c.acctbal,\n" +
" n.name,\n" +
" c.address,\n" +
" c.phone,\n" +
" c.comment\n" +
"FROM\n" +
" customer c,\n" +
" orders o,\n" +
" lineitem l,\n" +
" nation n\n" +
"WHERE\n" +
" c.custkey = o.custkey\n" +
" AND l.orderkey = o.orderkey\n" +
" AND o.orderdate >= date '1993-10-01'\n" +
" AND o.orderdate < date '1993-10-01' + interval '3' month\n" +
" AND l.returnflag = 'R'\n" +
" AND c.nationkey = n.nationkey\n" +
"GROUP BY\n" +
" c.custkey,\n" +
" c.name,\n" +
" c.acctbal,\n" +
" c.phone,\n" +
" n.name,\n" +
" c.address,\n" +
" c.comment\n" +
"ORDER BY\n" +
" revenue desc\n" +
"LIMIT 100";
} | 32.352113 | 77 | 0.393992 |
e8e8de411fdbe1b58b8fdf0c2051c8697e447087 | 3,657 | package com.dbspring.domain;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name = "fastfood")
public class FastFood {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "fastfood_id", nullable = false)
private Long fastfood_id;
@Column(name = "fastfood_name", nullable = false, length = 45)
private String fastfood_name;
@Column(name = "author", nullable = false, length = 45)
private String author;
@Column(name = "seller", nullable = true, length = 50)
private String seller;
@Column(name = "year_of_creating", nullable = true)
private Integer year_of_creating;
@Column(name = "amount", nullable = false)
private Integer amount;
@ManyToMany(mappedBy = "fastFoods")
private Set<FastFoodMarket> fastFoodMarkets;
FastFood(){}
FastFood(String fastfood_name, String author, String seller, Integer year_of_creating){
this.fastfood_name=fastfood_name;
this.author=author;
this.seller=seller;
this.year_of_creating=year_of_creating;
}
public Long getId() {
return fastfood_id;
}
public void setId(Long idFastFood) {
this.fastfood_id = idFastFood;
}
public String getFastFoodName() {
return fastfood_name;
}
public void setFastFoodName(String fastfood_name) {
this.fastfood_name = fastfood_name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getSeller() {
return seller;
}
public void setSeller(String seller) {
this.seller = seller;
}
public Integer getYearOfCreating() {
return year_of_creating;
}
public void setYearOfCreating(Integer year_of_creating) {
this.year_of_creating = year_of_creating;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Set<FastFoodMarket> getFastFoodMarkets() {
return fastFoodMarkets;
}
public void setPersons(Set<FastFoodMarket> fastFoodMarkets) {
this.fastFoodMarkets = fastFoodMarkets;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FastFood that = (FastFood) o;
if (fastfood_id != null ? !fastfood_id.equals(that.fastfood_id) : that.fastfood_id != null) return false;
if (fastfood_name != null ? !fastfood_name.equals(that.fastfood_name) : that.fastfood_name != null) return false;
if (author != null ? !author.equals(that.author) : that.author != null) return false;
if (seller != null ? !seller.equals(that.seller) : that.seller != null) return false;
if (year_of_creating != null ? !year_of_creating.equals(that.year_of_creating) : that.year_of_creating != null) return false;
if (amount != null ? !amount.equals(that.amount) : that.amount != null) return false;
return true;
}
@Override
public int hashCode() {
int result = fastfood_id != null ? fastfood_id.hashCode() : 0;
result = 31 * result + (fastfood_name != null ? fastfood_name.hashCode() : 0);
result = 31 * result + (author != null ? author.hashCode() : 0);
result = 31 * result + (seller != null ? seller.hashCode() : 0);
result = 31 * result + (year_of_creating != null ? year_of_creating.hashCode() : 0);
result = 31 * result + (amount != null ? amount.hashCode() : 0);
return result;
}
}
| 34.17757 | 133 | 0.643697 |
3ed82b147ca8215738bd0d681ede502b6517b1af | 1,013 | package com.sree.textbytes.jtopia;
/**
*
* @author Sree
*
* Configurations for different POS taggers, filter values
*
*
*/
public class Configuration {
static String taggerType = "";
static int singleStrengthMinOccur;
static int noLimitStrength;
static String modelFileLocation = "";
public static void setTaggerType(String type) {
taggerType = type;
}
public static String getTaggerType() {
return taggerType;
}
public static void setSingleStrength(int strength) {
singleStrengthMinOccur = strength;
}
public static int getSingleStrength() {
return singleStrengthMinOccur;
}
public static void setNoLimitStrength(int noLimit) {
noLimitStrength = noLimit;
}
public static int getNoLimitStrength() {
return noLimitStrength;
}
public static void setModelFileLocation(String modelFile) {
modelFileLocation = modelFile;
}
public static String getModelFileLocation() {
return modelFileLocation;
}
}
| 19.480769 | 61 | 0.699901 |
f450a34b0ea8aa4e07d6da2d09bf63b4446eef95 | 1,315 | package com.github.llyb120.namilite.init;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: Administrator
* @Date: 2020/9/20 18:43
*/
@ConfigurationProperties(prefix = "nami")
public class NamiProperties {
private List<String> springHotPackages = new ArrayList<>();
private int compileWaitSeconds = 5;
private boolean useLombok = false;
private String compiler = "javac";
public List<String> getSpringHotPackages() {
return springHotPackages;
}
public boolean isUseLombok() {
return useLombok;
}
public void setUseLombok(boolean useLombok) {
this.useLombok = useLombok;
}
public String getCompiler() {
return compiler;
}
public void setCompiler(String compiler) {
this.compiler = compiler;
}
public void setSpringHotPackages(List<String> springHotPackages) {
this.springHotPackages = springHotPackages;
}
public int getCompileWaitSeconds() {
if(compileWaitSeconds <= 0){
compileWaitSeconds = 5;
}
return compileWaitSeconds;
}
public void setCompileWaitSeconds(int compileWaitSeconds) {
this.compileWaitSeconds = compileWaitSeconds;
}
}
| 23.909091 | 75 | 0.681369 |
7f9227ef96c939744193d8312807a69da8171671 | 4,083 | /*
* Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Simon McDuff - initial API and implementation
*/
package org.eclipse.emf.internal.cdo.transaction;
import org.eclipse.emf.cdo.CDOObjectReference;
import org.eclipse.emf.cdo.common.branch.CDOBranch;
import org.eclipse.emf.cdo.common.commit.CDOCommitData;
import org.eclipse.emf.cdo.common.commit.CDOCommitInfo;
import org.eclipse.emf.cdo.spi.common.commit.InternalCDOCommitInfoManager;
import org.eclipse.emf.cdo.util.CommitException;
import org.eclipse.emf.cdo.util.ReferentialIntegrityException;
import org.eclipse.emf.internal.cdo.bundle.OM;
import org.eclipse.net4j.util.om.monitor.EclipseMonitor;
import org.eclipse.net4j.util.om.monitor.OMMonitor;
import org.eclipse.net4j.util.om.trace.ContextTracer;
import org.eclipse.emf.spi.cdo.CDOSessionProtocol;
import org.eclipse.emf.spi.cdo.CDOSessionProtocol.CommitTransactionResult;
import org.eclipse.emf.spi.cdo.CDOTransactionStrategy;
import org.eclipse.emf.spi.cdo.InternalCDOSavepoint;
import org.eclipse.emf.spi.cdo.InternalCDOSession;
import org.eclipse.emf.spi.cdo.InternalCDOTransaction;
import org.eclipse.emf.spi.cdo.InternalCDOTransaction.InternalCDOCommitContext;
import org.eclipse.emf.spi.cdo.InternalCDOUserSavepoint;
import org.eclipse.core.runtime.IProgressMonitor;
import java.util.List;
/**
* @author Simon McDuff
* @since 2.0
*/
public class CDOSingleTransactionStrategyImpl implements CDOTransactionStrategy
{
public static final CDOSingleTransactionStrategyImpl INSTANCE = new CDOSingleTransactionStrategyImpl();
private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_TRANSACTION,
CDOSingleTransactionStrategyImpl.class);
public CDOSingleTransactionStrategyImpl()
{
}
public CDOCommitInfo commit(InternalCDOTransaction transaction, IProgressMonitor progressMonitor) throws Exception
{
String comment = transaction.getCommitComment();
InternalCDOCommitContext commitContext = transaction.createCommitContext();
if (TRACER.isEnabled())
{
TRACER.format("CDOCommitContext.preCommit"); //$NON-NLS-1$
}
commitContext.preCommit();
CDOCommitData commitData = commitContext.getCommitData();
InternalCDOSession session = transaction.getSession();
CommitTransactionResult result = null;
OMMonitor monitor = new EclipseMonitor(progressMonitor);
CDOSessionProtocol sessionProtocol = session.getSessionProtocol();
result = sessionProtocol.commitTransaction(commitContext, monitor);
commitContext.postCommit(result);
String rollbackMessage = result.getRollbackMessage();
if (rollbackMessage != null)
{
List<CDOObjectReference> xRefs = result.getXRefs();
if (xRefs != null)
{
throw new ReferentialIntegrityException(rollbackMessage, xRefs);
}
throw new CommitException(rollbackMessage);
}
transaction.setCommitComment(null);
long previousTimeStamp = result.getPreviousTimeStamp();
CDOBranch branch = transaction.getBranch();
long timeStamp = result.getTimeStamp();
String userID = session.getUserID();
InternalCDOCommitInfoManager commitInfoManager = session.getCommitInfoManager();
return commitInfoManager.createCommitInfo(branch, timeStamp, previousTimeStamp, userID, comment, commitData);
}
public void rollback(InternalCDOTransaction transaction, InternalCDOUserSavepoint savepoint)
{
transaction.handleRollback((InternalCDOSavepoint)savepoint);
}
public InternalCDOUserSavepoint setSavepoint(InternalCDOTransaction transaction)
{
return transaction.handleSetSavepoint();
}
public void setTarget(InternalCDOTransaction transaction)
{
// Do nothing
}
public void unsetTarget(InternalCDOTransaction transaction)
{
// Do nothing
}
}
| 34.310924 | 116 | 0.782513 |
74f0cc545bdb3985ebbf1203828c0867f9d368d7 | 916 | /*
* Copyright (C) 2018 NickAc.
*
* 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 me.nickac.cspoet;
public enum CSharpModifier {
PUBLIC,
PRIVATE,
INTERNAL,
PROTECTED,
ABSTRACT,
ASYNC,
CONST,
EVENT,
EXTERN,
NEW,
OVERRIDE,
PARTIAL,
READONLY,
SEALED,
STATIC,
UNSAFE,
VIRTUAL,
VOLATILE,
IMPLICIT,
EXPLICIT,
OPERATOR
}
| 22.341463 | 75 | 0.680131 |
5e4988cdb041c85acbcf89df65baaa70491611d5 | 8,353 | /*
* 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.fluo.core.impl;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Map.Entry;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.curator.framework.CuratorFramework;
import org.apache.fluo.accumulo.util.AccumuloProps;
import org.apache.fluo.accumulo.util.ZookeeperPath;
import org.apache.fluo.api.config.FluoConfiguration;
import org.apache.fluo.api.config.SimpleConfiguration;
import org.apache.fluo.api.metrics.MetricsReporter;
import org.apache.fluo.core.client.FluoAdminImpl;
import org.apache.fluo.core.metrics.MetricNames;
import org.apache.fluo.core.metrics.MetricsReporterImpl;
import org.apache.fluo.core.observer.ObserverUtil;
import org.apache.fluo.core.observer.RegisteredObservers;
import org.apache.fluo.core.util.AccumuloUtil;
import org.apache.fluo.core.util.CuratorUtil;
/**
* Holds common environment configuration and shared resources
*/
public class Environment implements AutoCloseable {
private String table;
private Authorizations auths = new Authorizations();
private String accumuloInstance;
private RegisteredObservers observers;
private AccumuloClient client;
private String accumuloInstanceID;
private String fluoApplicationID;
private FluoConfiguration config;
private SharedResources resources;
private MetricNames metricNames;
private SimpleConfiguration appConfig;
private String metricsReporterID;
private void ensureDeletesAreDisabled() {
String value = null;
Iterable<Entry<String, String>> props;
try {
props = client.tableOperations().getProperties(table);
} catch (AccumuloException | TableNotFoundException e) {
throw new IllegalStateException(e);
}
for (Entry<String, String> entry : props) {
if (entry.getKey().equals(AccumuloProps.TABLE_DELETE_BEHAVIOR)) {
value = entry.getValue();
}
}
Preconditions.checkState(AccumuloProps.TABLE_DELETE_BEHAVIOR_VALUE.equals(value),
"The Accumulo table %s is not configured correctly. Please set %s=%s for this table in Accumulo.",
table, AccumuloProps.TABLE_DELETE_BEHAVIOR, AccumuloProps.TABLE_DELETE_BEHAVIOR_VALUE);
}
/**
* Constructs an environment from given FluoConfiguration
*
* @param configuration Configuration used to configure environment
*/
public Environment(FluoConfiguration configuration) {
config = configuration;
client = AccumuloUtil.getClient(config);
readZookeeperConfig();
ensureDeletesAreDisabled();
String instanceName = client.properties().getProperty(AccumuloProps.CLIENT_INSTANCE_NAME);
if (!instanceName.equals(accumuloInstance)) {
throw new IllegalArgumentException(
"unexpected accumulo instance name " + instanceName + " != " + accumuloInstance);
}
if (!client.instanceOperations().getInstanceID().equals(accumuloInstanceID)) {
throw new IllegalArgumentException("unexpected accumulo instance id "
+ client.instanceOperations().getInstanceID() + " != " + accumuloInstanceID);
}
try {
resources = new SharedResources(this);
} catch (TableNotFoundException e1) {
throw new IllegalStateException(e1);
}
}
/**
* Constructs an environment from another environment
*
* @param env Environment
*/
@VisibleForTesting
public Environment(Environment env) throws Exception {
this.table = env.table;
this.auths = env.auths;
this.accumuloInstance = env.accumuloInstance;
this.observers = env.observers;
this.client = env.client;
this.accumuloInstanceID = env.accumuloInstanceID;
this.fluoApplicationID = env.fluoApplicationID;
this.config = env.config;
this.resources = new SharedResources(this);
}
/**
* Read configuration from zookeeper
*/
private void readZookeeperConfig() {
try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) {
curator.start();
accumuloInstance =
new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME),
StandardCharsets.UTF_8);
accumuloInstanceID =
new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_ID),
StandardCharsets.UTF_8);
fluoApplicationID =
new String(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID),
StandardCharsets.UTF_8);
table = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_TABLE),
StandardCharsets.UTF_8);
observers = ObserverUtil.load(curator);
config = FluoAdminImpl.mergeZookeeperConfig(config);
// make sure not to include config passed to env, only want config from zookeeper
appConfig = config.getAppConfiguration();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public void setAuthorizations(Authorizations auths) {
this.auths = auths;
// TODO the following is a big hack, this method is currently not exposed in API
resources.close();
try {
this.resources = new SharedResources(this);
} catch (TableNotFoundException e) {
throw new RuntimeException(e);
}
}
public Authorizations getAuthorizations() {
return auths;
}
public String getAccumuloInstance() {
return accumuloInstance;
}
public String getAccumuloInstanceID() {
return accumuloInstanceID;
}
public String getFluoApplicationID() {
return fluoApplicationID;
}
public RegisteredObservers getConfiguredObservers() {
return observers;
}
public String getTable() {
return table;
}
public AccumuloClient getAccumuloClient() {
return client;
}
public SharedResources getSharedResources() {
return resources;
}
public FluoConfiguration getConfiguration() {
return config;
}
public synchronized String getMetricsReporterID() {
if (metricsReporterID == null) {
String mid = System.getProperty(MetricNames.METRICS_REPORTER_ID_PROP);
if (mid == null) {
try {
String hostname = InetAddress.getLocalHost().getHostName();
int idx = hostname.indexOf('.');
if (idx > 0) {
hostname = hostname.substring(0, idx);
}
mid = hostname + "_" + getSharedResources().getTransactorID();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
metricsReporterID = mid.replace('.', '_');
}
return metricsReporterID;
}
public String getMetricsAppName() {
return config.getApplicationName().replace('.', '_');
}
public synchronized MetricNames getMetricNames() {
if (metricNames == null) {
metricNames = new MetricNames(getMetricsReporterID(), getMetricsAppName());
}
return metricNames;
}
public MetricsReporter getMetricsReporter() {
return new MetricsReporterImpl(getConfiguration(), getSharedResources().getMetricRegistry(),
getMetricsReporterID());
}
public SimpleConfiguration getAppConfiguration() {
// TODO create immutable wrapper
return new SimpleConfiguration(appConfig);
}
@Override
public void close() {
resources.close();
client.close();
}
}
| 32.375969 | 107 | 0.72465 |
9c597aaa1b63d3d3dae78c5c28de25ed1ff12ed9 | 2,100 | /*
* Copyright 2015 TheShark34
*
* This file is part of OpenAuth.
* OpenAuth is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenAuth is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with OpenAuth. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.litarvan.openauth.model;
/**
* JSON model of an error
*
* @version 1.0.4
* @author Litarvan
*/
public class AuthError {
/**
* Short description of the error
*/
private String error;
/**
* Longer description wich can be shown to the user
*/
private String errorMessage;
/**
* Cause of the error (optional)
*/
private String cause;
/**
* Auth Error constructor
*
* @param error
* Short description of the error
* @param errorMessage
* Longer description wich can be shown to the user
* @param cause
* Cause of the error
*/
public AuthError(String error, String errorMessage, String cause) {
this.error = error;
this.errorMessage = errorMessage;
this.cause = cause;
}
/**
* Returns the error (Short description of the error)
*
* @return The error
*/
public String getError() {
return error;
}
/**
* Returns the error message (Longer description of the error)
*
* @return The error message
*/
public String getErrorMessage() {
return this.errorMessage;
}
/**
* Returns the cause of the error
*
* @return The cause
*/
public String getCause() {
return cause;
}
}
| 23.863636 | 78 | 0.622857 |
f03c28f5104daf1615427d17402fd25c3dc79b47 | 1,733 | package com.tysonmak.states;
import com.tysonmak.application.Application;
import com.tysonmak.graphics.Assets;
import com.tysonmak.graphics.FontLoader;
import com.tysonmak.states.manager.GameState;
import com.tysonmak.states.manager.GameStateManager;
import java.awt.*;
import java.awt.event.KeyEvent;
public class SplashState extends GameState {
private final int fadeIn = 120, length = 180, fadeOut = 120;
private int count;
private int alpha;
public SplashState(Application app, GameStateManager gsm) {
super(app, gsm);
count = 0;
}
@Override
public void update() {
count++;
if(app.getKeys().keyJustPressed(KeyEvent.VK_ENTER))
gsm.setState(GameStateManager.MENU);
if(count < fadeIn) {
alpha = (int) (255 - 255 * (1.0f * count / fadeIn));
if(alpha < 0)
alpha = 0;
}
if(count > fadeIn + length) {
alpha = (int) (255 * (1.0f * count - fadeIn - length) / fadeOut);
if(alpha > 255)
alpha = 255;
}
if(count > fadeIn + length + fadeOut)
gsm.setState(GameStateManager.MENU);
}
@Override
public void render(Graphics2D g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, app.getWidth(), app.getHeight());
FontLoader.drawString(g, "This game was programmed", app.getWidth() / 2, app.getHeight() / 2 - 15, true, Color.WHITE, Assets.font2);
FontLoader.drawString(g, "in java by Tyson Mak", app.getWidth() / 2, app.getHeight() / 2 + 15, true, Color.WHITE, Assets.font2);
g.setColor(new Color(0, 0, 0, alpha));
g.fillRect(0, 0, app.getWidth(), app.getHeight());
}
}
| 28.409836 | 140 | 0.605886 |
b5941835ecc25b8beb48c1719d45a4006235e1f9 | 563 | package dora.permission.notify;
import dora.permission.Action;
import dora.permission.Rationale;
public interface PermissionRequest {
/**
* Set request rationale.
*/
PermissionRequest rationale(Rationale<Void> rationale);
/**
* Action to be taken when all permissions are granted.
*/
PermissionRequest onGranted(Action<Void> granted);
/**
* Action to be taken when all permissions are denied.
*/
PermissionRequest onDenied(Action<Void> denied);
/**
* Start install.
*/
void start();
} | 20.107143 | 59 | 0.65897 |
701d2f54f5c3fd68120bbcd503df20c58a6b066f | 1,624 | package com.sanri.tools.modules.core.dtos;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
/**
* 用于向前端展示文件信息
* 文件名+是否是目录
*/
public class ConfigPath implements Comparable<ConfigPath>{
private String pathName;
private boolean isDirectory;
@JsonIgnore
private File file;
public ConfigPath(String pathName, boolean isDirectory) {
this.pathName = pathName;
this.isDirectory = isDirectory;
}
public ConfigPath(String pathName, boolean isDirectory, File file) {
this.pathName = pathName;
this.isDirectory = isDirectory;
this.file = file;
}
public ConfigPath() {
}
public String getPathName() {
return pathName;
}
public boolean isDirectory() {
return isDirectory;
}
public File getFile() {
return file;
}
@Override
public int compareTo(ConfigPath o) {
try {
BasicFileAttributes basicFileAAttributes = Files.readAttributes(this.file.toPath(), BasicFileAttributes.class);
FileTime aFileaccessTime = basicFileAAttributes.lastAccessTime();
BasicFileAttributes basicBFileAttributes = Files.readAttributes(o.file.toPath(), BasicFileAttributes.class);
FileTime bFileaccessTime = basicBFileAttributes.lastAccessTime();
return bFileaccessTime.compareTo(aFileaccessTime);
} catch (IOException e) {
return -1 ;
}
}
}
| 26.193548 | 123 | 0.678571 |
89d872ca09f62f31b66cb63ccea92cd91966a420 | 4,010 | /*
* 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.scavi.de.gw2imp.data.entity.achievement;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.ForeignKey;
import android.support.annotation.NonNull;
import com.scavi.de.gw2imp.communication.response.achievement.Achievement;
import com.scavi.de.gw2imp.communication.response.achievement.Tier;
import com.scavi.de.gw2imp.data.util.DbConst;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
@Entity(tableName = DbConst.TABLE_ACHIEVEMENT_TIERS,
primaryKeys = {"achievement_id", "count", "points"},
foreignKeys = @ForeignKey(
entity = AchievementEntity.class,
parentColumns = "id",
childColumns = "achievement_id"))
public class TierEntity {
@NonNull
@ColumnInfo(name = "achievement_id")
private final Integer mAchievementId;
@NonNull
@ColumnInfo(name = "count")
private final Integer mCount;
@NonNull
@ColumnInfo(name = "points")
private final Integer mPoints;
/**
* Constructor
*
* @param achievementId The id of the achievement this reward is referenced
* @param count The number of "things" (achievement-specific) that must be completed to
* achieve this tier.
* @param points The amount of AP awarded for completing this tier.
*/
public TierEntity(final Integer achievementId,
final Integer count,
final Integer points) {
mAchievementId = achievementId;
mCount = count;
mPoints = points;
}
/**
* @return The id of the achievement this reward is referenced
*/
@NonNull
public Integer getAchievementId() {
return mAchievementId;
}
/**
* @return The number of "things" (achievement-specific) that must be completed to achieve
* this tier.
*/
@NonNull
public Integer getCount() {
return mCount;
}
/**
* @return The amount of AP awarded for completing this tier.
*/
@NonNull
public Integer getPoints() {
return mPoints;
}
/**
* Factory method to create a list of {@link TierEntity} from the given tiers of the
* achievement
*
* @param achievement the parent achievement for the current flags
* @param tiers Describes the achievement's tiers. Each object contains:
* count (number) - The number of "things" (achievement-specific) that
* must be completed to
* achieve this tier.
* points (number) The amount of AP awarded for completing this tier.
* @return the achievement entities for the given flags
*/
public static List<TierEntity> from(final Achievement achievement,
@Nullable final List<Tier> tiers) {
if (tiers == null || tiers.size() == 0) {
return new ArrayList<>(0);
}
List<TierEntity> tierEntities = new ArrayList<>(tiers.size());
for (Tier tier : tiers) {
tierEntities.add(new TierEntity(
achievement.getId(), tier.getCount(), tier.getPoints()));
}
return tierEntities;
}
} | 33.983051 | 99 | 0.642394 |
55f1fcd5e9dc2463aa2381f0adf5141d97b99148 | 1,451 | package com.Spring.Blog.Models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String mail;
private String password;
public User() {
}
public User(Long id) {
this.id = id;
}
public User(Long id, String firstName, String lastName, String mail, String password) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.mail = mail;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| 19.092105 | 91 | 0.616127 |
82b380070b14b29ce3d5e1c1586ce5a342944a52 | 2,200 | package org.reldb.rel.v0.storage.relvars.external.jdbc;
import org.reldb.rel.v0.storage.relvars.external.Info;
import org.reldb.rel.v0.storage.relvars.external.InfoComponent;
import org.reldb.rel.v0.storage.relvars.external.InfoComponentOption;
public class InfoJDBC extends Info {
@Override
public String getIdentifier() {
return "JDBC";
}
@Override
public String getDescription() {
return "Connection to a specified table in a SQL database.";
}
@Override
public String getConnectionStringDocumentation() {
return
"Built-in JDBC support is provided for MySQL, MariaDB, PostgreSQL, Oracle and Microsoft SQL Server:\n" +
"\tVAR myvar EXTERNAL JDBC \"jdbc:mysql://localhost/database,sqluser,sqluserpw,MyTable\";\n" +
"\tVAR myvar EXTERNAL JDBC \"jdbc:mariadb://localhost/database,sqluser,sqluserpw,MyTable\";\n" +
"\tVAR myvar EXTERNAL JDBC \"jdbc:postgresql://localhost/database,sqluser,sqluserpw,MyTable\";\n" +
"\tVAR myvar EXTERNAL JDBC \"jdbc:oracle:thin:@localhost:1521:database,sqluser,sqluserpw,MyTable\";\n" +
"\tVAR myvar EXTERNAL JDBC \"jdbc:sqlserver://localhost:1433;databaseName=database,sqluser,sqluserpw,MyTable\";\n";
}
private static class InfoComponentJDBC extends InfoComponent {
private String documentation;
InfoComponentJDBC(int componentNumber, String documentation) {
super(componentNumber);
this.documentation = documentation;
}
@Override
public boolean isOptional() {
return false;
}
@Override
public boolean isAFile() {
return false;
}
@Override
public String[] getAppropriateFileExtension() {
return null;
}
@Override
public InfoComponentOption[] getOptions() {
return null;
}
@Override
public String getDocumentation() {
return documentation;
}
}
@Override
public InfoComponent[] getConnectionStringComponents() {
return new InfoComponent[] {
new InfoComponentJDBC(0, "JDBC connection string"),
new InfoComponentJDBC(1, "SQL user name"),
new InfoComponentJDBC(2, "SQL password"),
new InfoComponentJDBC(3, "SQL table name")
};
}
@Override
public boolean isGuaranteedUnique() {
return false;
}
}
| 27.5 | 122 | 0.720909 |
d572729e93f861e76cc4a09cae276e644d9a8658 | 322 | package com.example.mchapagai.fragment;
import android.os.Bundle;
import dagger.android.support.DaggerFragment;
public class BaseFragment extends DaggerFragment {
public BaseFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
| 18.941176 | 53 | 0.73913 |
1a32a3627d1709228cc77e44ff936e3d5d40b5ce | 14,381 | package Gui;
import Game.*;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* The entire game view
*/
public class GameView extends Canvas {
public static final int CELL_SIZE = 16;
private static final int GAME_WIDTH = 26;
private static final int GAME_HEIGHT = 27;
private static final int CANVAS_WIDTH = GAME_WIDTH * CELL_SIZE;
private static final int CANVAS_HEIGHT = GAME_HEIGHT * CELL_SIZE;
private Game game;
private Window window;
private Player currentPlayer;
private GameController controller;
private List<String> characters;
private List<String> names;
private JPanel messagePanel, buttonPanel, cardPanel;
private Dice dice;
/**
* Create a view containing the game
*/
public GameView(Window window, List<String> characters, List<String> names) {
this.window = window;
this.characters = characters;
this.names = names;
game = new Game(this, characters, names);
currentPlayer = game.getPlayer(0);
controller = new GameController(this);
window.removeAll();
window.setLayout(new BoxLayout(window, BoxLayout.Y_AXIS));
// menu bar
JMenuBar menuBar = new JMenuBar();
JMenu gameMenu = new JMenu("Game");
menuBar.add(gameMenu);
JMenuItem restart = new JMenuItem("Restart");
restart.addActionListener((ActionEvent e) -> restartGame());
JMenuItem btMenu = new JMenuItem("Back To Menu");
btMenu.addActionListener((ActionEvent e) -> backToMenu());
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener((ActionEvent e) -> this.window.close());
gameMenu.add(restart);
gameMenu.add(btMenu);
gameMenu.add(exit);
window.setMenuBar(menuBar);
// create game canvas
setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
setMaximumSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
addMouseListener(controller);
window.add(this);
// key listener
setFocusable(true);
requestFocus();
addKeyListener(controller);
// footer panel sizes
int footerSize = (window.getHeight() - CANVAS_HEIGHT);
dice = new Dice((int) (footerSize * 0.2));
// message panel
messagePanel = new JPanel();
messagePanel.setMaximumSize(new Dimension(window.getWidth(), (int) (footerSize * 0.2)));
window.add(messagePanel);
// button panel
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.setMaximumSize(new Dimension(window.getWidth(), (int) (footerSize * 0.4)));
window.add(buttonPanel);
// card panel
cardPanel = new JPanel(new FlowLayout());
cardPanel.setMaximumSize(new Dimension(window.getWidth(), (int) (footerSize * 0.4)));
window.add(cardPanel);
swapPlayer(currentPlayer);
updatePlayerState();
}
/**
* Update the buttons on the screen to reflect the player's current state
*/
public void updatePlayerState() {
buttonPanel.removeAll();
messagePanel.removeAll();
messagePanel.add(new JLabel(currentPlayer + "'s turn."));
Player.PlayerState state = currentPlayer.getCurrentState();
// moving state
if (state == Player.PlayerState.MOVING) {
buttonPanel.add(dice);
JLabel turnsLeftLabel = new JLabel("Moves Left: " + currentPlayer.getMovesLeft());
buttonPanel.add(turnsLeftLabel);
messagePanel.add(new JLabel("Use the mouse or WASD/Arrow Keys to move."));
} else {
// roll dice
if (state == Player.PlayerState.WAITING) {
JButton rollDice = new JButton("Roll Dice");
rollDice.setMnemonic(KeyEvent.VK_R);
rollDice.setFocusable(false);
rollDice.addActionListener((ActionEvent e) -> {
currentPlayer.rollDice(dice);
repaint();
});
buttonPanel.add(rollDice);
}
// finish turn
else {
JButton finishTurn = new JButton("Finish Turn");
finishTurn.setMnemonic(KeyEvent.VK_F);
finishTurn.setFocusable(false);
finishTurn.addActionListener((ActionEvent e) -> {
currentPlayer.finishTurn();
repaint();
});
buttonPanel.add(finishTurn);
}
// accuse
JButton accuse = new JButton("Accuse");
accuse.setMnemonic(KeyEvent.VK_A);
accuse.setFocusable(false);
accuse.addActionListener((ActionEvent e) -> accuse());
buttonPanel.add(accuse);
// suggest
if (currentPlayer.getSuspect().getCurrentRoom() != null) {
JButton suggest = new JButton("Suggest");
suggest.setMnemonic(KeyEvent.VK_S);
suggest.setFocusable(false);
suggest.addActionListener((ActionEvent e) -> suggest());
buttonPanel.add(suggest);
}
}
buttonPanel.repaint();
window.redraw();
}
/**
* Go back to the menu view
*/
public void backToMenu() {
new MenuView(window);
}
/**
* Restart the game
*/
public void restartGame() {
game = new Game(this, characters, names);
currentPlayer = game.getPlayer(0);
swapPlayer(currentPlayer);
repaint();
window.redraw();
}
/**
* Open accuse dialog
*/
public void accuse() {
// check in correct state
if (currentPlayer.getCurrentState() == Player.PlayerState.MOVING || currentPlayer.getCurrentState() == Player.PlayerState.NOT_TURN)
return;
// create panel layouts
JPanel accusePanel = new JPanel();
accusePanel.setLayout(new FlowLayout());
// suspects
JPanel suspectPanel = new JPanel();
accusePanel.add(suspectPanel);
suspectPanel.setLayout(new BoxLayout(suspectPanel, BoxLayout.Y_AXIS));
suspectPanel.add(new JLabel("Pick Suspect:"));
ButtonGroup suspects = new ButtonGroup();
for (String suspect : Game.allSuspects) {
JRadioButton button = new JRadioButton(suspect);
button.setActionCommand(suspect);
suspects.add(button);
suspectPanel.add(button);
}
// weapons
JPanel weaponPanel = new JPanel();
accusePanel.add(weaponPanel);
weaponPanel.setLayout(new BoxLayout(weaponPanel, BoxLayout.Y_AXIS));
weaponPanel.add(new JLabel("Pick Weapon:"));
ButtonGroup weapons = new ButtonGroup();
for (String weapon : Game.allWeapons) {
JRadioButton button = new JRadioButton(weapon);
button.setActionCommand(weapon);
weapons.add(button);
weaponPanel.add(button);
}
// rooms
JPanel roomPanel = new JPanel();
accusePanel.add(roomPanel);
roomPanel.setLayout(new BoxLayout(roomPanel, BoxLayout.Y_AXIS));
roomPanel.add(new JLabel("Pick Room:"));
ButtonGroup rooms = new ButtonGroup();
for (String room : Game.allRooms) {
JRadioButton button = new JRadioButton(room);
button.setActionCommand(room);
rooms.add(button);
roomPanel.add(button);
}
// get the picked option
int option = JOptionPane.showConfirmDialog(window, accusePanel, "Pick the circumstances of the murder", JOptionPane.OK_CANCEL_OPTION);
if (option == 0 && suspects.getSelection() != null && weapons.getSelection() != null && rooms.getSelection() != null) {
Card suspect = new Card(suspects.getSelection().getActionCommand(), Card.CardType.SUSPECT);
Card weapon = new Card(weapons.getSelection().getActionCommand(), Card.CardType.WEAPON);
Card room = new Card(rooms.getSelection().getActionCommand(), Card.CardType.ROOM);
// Check the accusation
if (game.checkAccusation(suspect, weapon, room)) {
showMessage("You guessed correctly! You win the game!");
backToMenu();
} else {
showMessage("You guessed incorrectly! You are no longer in the game!");
if (game.invalidAccusation(currentPlayer)) {
game.nextPlayer();
} else {
showMessage("No one managed to guess the circumstances of the murder correctly so the game is over.");
backToMenu();
}
}
}
}
/**
* Open suggest dialog
*/
public void suggest() {
// check in correct state
if (currentPlayer.getCurrentState() == Player.PlayerState.MOVING || currentPlayer.getCurrentState() == Player.PlayerState.NOT_TURN ||
currentPlayer.getSuspect().getCurrentRoom() == null) return;
// create panel layouts
JPanel accusePanel = new JPanel();
accusePanel.setLayout(new FlowLayout());
// suspects
JPanel suspectPanel = new JPanel();
accusePanel.add(suspectPanel);
suspectPanel.setLayout(new BoxLayout(suspectPanel, BoxLayout.Y_AXIS));
suspectPanel.add(new JLabel("Pick Suspect:"));
ButtonGroup suspects = new ButtonGroup();
for (String suspect : Game.allSuspects) {
JRadioButton button = new JRadioButton(suspect);
button.setActionCommand(suspect);
suspects.add(button);
suspectPanel.add(button);
}
// weapons
JPanel weaponPanel = new JPanel();
accusePanel.add(weaponPanel);
weaponPanel.setLayout(new BoxLayout(weaponPanel, BoxLayout.Y_AXIS));
weaponPanel.add(new JLabel("Pick Weapon:"));
ButtonGroup weapons = new ButtonGroup();
for (String weapon : Game.allWeapons) {
JRadioButton button = new JRadioButton(weapon);
button.setActionCommand(weapon);
weapons.add(button);
weaponPanel.add(button);
}
// get the picked option
int option = JOptionPane.showConfirmDialog(window, accusePanel, "Suggest the weapon and suspect for the murder", JOptionPane.OK_CANCEL_OPTION);
if (option == 0 && suspects.getSelection() != null && weapons.getSelection() != null) {
Card suspect = new Card(suspects.getSelection().getActionCommand(), Card.CardType.SUSPECT);
Card weapon = new Card(weapons.getSelection().getActionCommand(), Card.CardType.WEAPON);
Card room = new Card(currentPlayer.getSuspect().getCurrentRoom().getName(), Card.CardType.ROOM);
game.checkSuggestion(suspect, weapon, room);
game.nextPlayer();
}
}
/**
* Show the dialog that appears when someone has one of the cards that someone suggested
*
* @param player
* @param refutedCards
*/
public void showRefutationDialog(Player player, List<Card> refutedCards) {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new JLabel(player + ", Pick a card to refute:"));
ButtonGroup cards = new ButtonGroup();
boolean first = true;
for (Card card : refutedCards) {
JRadioButton button = new JRadioButton(card.toString());
button.setActionCommand(card.toString());
panel.add(button);
cards.add(button);
if (first) button.setSelected(true);
first = false;
}
JOptionPane.showMessageDialog(window, panel, player + ", choose a card to refute to " + currentPlayer, JOptionPane.QUESTION_MESSAGE);
showMessage(currentPlayer + ", " + player + " has the " + cards.getSelection().getActionCommand() + " card.");
}
/**
* Swap the current player in the window to the view of another player
*
* @param newPlayer
*/
public void swapPlayer(Player newPlayer) {
this.currentPlayer = newPlayer;
window.setTitle(newPlayer.toString());
// update the cards
cardPanel.removeAll();
for (Card card : newPlayer.getCards()) {
JLabel c = new JLabel(card.toString());
c.setBorder(new CompoundBorder(BorderFactory.createLineBorder(Color.BLACK), new EmptyBorder(5, 10, 5, 10)));
cardPanel.add(c);
}
cardPanel.repaint();
repaint();
window.redraw();
}
/**
* Draw the current state of the board
*/
public void paint(Graphics g) {
Board board = game.getBoard();
for (int y = 0; y < GAME_HEIGHT; y++) {
for (int x = 0; x < GAME_WIDTH; x++) {
Cell cell = board.getCell(x, y);
cell.draw(g, CELL_SIZE);
}
}
// highlight the player
currentPlayer.getSuspect().getLocation().highlightCell(g, CELL_SIZE, Color.YELLOW);
currentPlayer.getSuspect().getLocation().outlineCell(g, CELL_SIZE, Color.YELLOW);
// highlight possible moves
if (currentPlayer.getCurrentState() == Player.PlayerState.MOVING) {
List<Cell> cells = currentPlayer.getAvailableCells();
for(Cell cell : cells) {
cell.highlightCell(g, CELL_SIZE, new Color(255, 255, 50));
}
}
}
/**
* Get the current player
*
* @return
*/
public Player getPlayer() {
return currentPlayer;
}
/**
* Get the game
*
* @return
*/
public Game getGame() {
return game;
}
/**
* Show a message dialog
*
* @param message
*/
public void showMessage(String message) {
JOptionPane.showMessageDialog(window, message);
}
/**
* Get the dice
*
* @return
*/
public Dice getDice() {
return dice;
}
}
| 33.135945 | 151 | 0.594952 |
05677af0e484cb623c386fd73410e67f11476d0f | 1,812 | package com.github.flaxsearch.util;
/*
* Copyright (c) 2016 Lemur Consulting Ltd.
*
* 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.
*/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import io.dropwizard.lifecycle.Managed;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.IOUtils;
public class FSReaderManager implements ReaderManager, Managed {
private final Directory directory;
private final IndexReader reader;
public FSReaderManager(String indexPath) throws IOException {
Path path = Paths.get(indexPath);
if (Files.exists(path) == false)
throw new FileNotFoundException("Path " + path + " does not exist");
this.directory = FSDirectory.open(path);
this.reader = DirectoryReader.open(directory);
}
@Override
public IndexReader getIndexReader() {
return reader;
}
@Override
public void start() throws Exception {
}
@Override
public void stop() throws Exception {
IOUtils.close(reader, directory);
}
}
| 30.711864 | 80 | 0.718543 |
1b8eb1e3df74ba8a5dead02efc820f6586ec9138 | 817 | package com.alvis.exam.service;
import com.alvis.exam.domain.Chapter;
import com.alvis.exam.viewmodel.admin.user.ChapterVM;
import java.util.List;
/**
* @author yangsy
* 章节管理
*/
public interface ChapterService {
/**
* insertChapter
*添加章节
* @param chapter
*/
void insertChapter(ChapterVM chapter);
/**
* updateChapter
*修改章节
* @param chapter
*/
void updateChapter(ChapterVM chapter);
/**
* deleteChapterByIds
*删除章节
* @param id
*/
void deleteChapterById(Integer id, Integer state);
/**
* queryChapter
* 查询章节
* @param typeId
*/
List<Chapter> queryChapter(Integer typeId);
/**
* 获取下一排序号
*/
Chapter getNextSequence(Integer typeId);
Chapter findChapterById(Integer chapterId);
}
| 17.020833 | 54 | 0.615667 |
cadade6ed6ac3452db05d1f2ab92b38af704fe8f | 2,737 | /* =========================================================
* IPropertySet.java
*
* Author: kmchugh
* Created: 12-Dec-2007, 16:06:03
*
* Description
* --------------------------------------------------------
* Interface for controlling a property bag
*
* Change Log
* --------------------------------------------------------
* Init.Date Ref. Description
* --------------------------------------------------------
*
* =======================================================*/
package Goliath.Interfaces.Collections;
/**
* Interface for adding and removing properties from
* a property bag
*
* @see Goliath.Collections.PropertyBag
* @version 1.0 12-Dec-2007
* @author kmchugh
**/
public interface IPropertySet extends java.util.Map<String, java.lang.Object>,
java.lang.Iterable<java.lang.Object >
{
/**
* Returns the value of a property
*
* @param <K> The type of the property
* @param tcName the property specified
* @return returns the property value or null if the property is not found
*/
<K> K getProperty(String tcName);
/**
* Checks if the property set has the specified property
* @param tcProperty the property to check for
* @return true if contained
*/
boolean hasProperty(String tcProperty);
/**
* Clears a property from the collection, this will remove the item from the internal list
*
* @param tcName the property specified
* @return true if the collection is changed due to this call
*/
boolean clearProperty(String tcName);
/**
* Returns the value of a property
* @param <K> The type of the property
* @param tcName the property specified
* @param tlThrowError Throws an error if the property is not found
* @return returns the property value
* @throws Goliath.Exceptions.InvalidIndexException if the property was not found and tlThrowError is true
*/
<K> K getProperty(String tcName, boolean tlThrowError) throws Goliath.Exceptions.InvalidIndexException;
/**
* Sets the property specified, returns true if this call resulted in a change
* to the internal data structure
* @param <K> The type of the property
* @param tcProperty the property to get
* @param toValue the new value of the property
* @return true if the value was changed, false if the new value was inserted
*/
<K> boolean setProperty(String tcProperty, K toValue);
/**
* Gets the list of keys that are in the property bag
* @return the list of keys that exist in the property bag
*/
Goliath.Collections.List<String> getPropertyKeys();
}
| 32.583333 | 110 | 0.588966 |
d3b877e942bb4987441d5ab5158d63a5b383d313 | 2,694 | package com.lanking.uxb.service.data.api.impl.job;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.google.common.collect.Sets;
import com.lanking.cloud.domain.yoomath.holidayHomework.HolidayStuHomeworkItem;
import com.lanking.cloud.sdk.data.CP;
import com.lanking.cloud.sdk.data.CursorPage;
import com.lanking.uxb.service.holiday.api.HolidayStuHomeworkItemService;
import com.lanking.uxb.service.holiday.api.impl.HolidayHomeworkCalculateService;
import com.lanking.uxb.service.holiday.api.impl.HolidayHomeworkRankService;
/**
* 假期作业统计定时
*
* @author xinyu.zhou
* @since yoomath V1.9
*/
public class YoomathHolidayHomeworkJob implements SimpleJob {
private static Logger logger = LoggerFactory.getLogger(YoomathHolidayHomeworkJob.class);
// 学生专项正确率统计每次查询条数
private static final int HOLIDAY_STU_HOMEWORK_ITEM_FETCH_SIZE = 200;
@Autowired
private HolidayStuHomeworkItemService holidayStuHomeworkItemService;
@Autowired
private HolidayHomeworkCalculateService holidayHomeworkCalculateService;
@Autowired
private HolidayHomeworkRankService holidayHomeworkRankService;
@Override
public void execute(ShardingContext shardingContext) {
Collection<Long> hkIds = calculate();
rank(hkIds);
}
/**
* 计算正确率
*
* 以学生专项为入口计算单位,筛选条件符合如下几点: 1. 专项没有计算出正确率。 2. 专项中的题目全部完成。 3.
* 专项中的题目全部经过人工批改过。
*/
public Collection<Long> calculate() {
Set<Long> hkIds = Sets.newHashSet();
CursorPage<Long, HolidayStuHomeworkItem> page = holidayStuHomeworkItemService
.queryNotCalculate(CP.cursor(Long.MAX_VALUE, HOLIDAY_STU_HOMEWORK_ITEM_FETCH_SIZE));
while (page.isNotEmpty()) {
List<HolidayStuHomeworkItem> stuItems = page.getItems();
logger.info("begin calculate {} right rate ", JSON.toJSONString(stuItems));
Map<String, Collection<Long>> retMap = holidayHomeworkCalculateService.calculateStuItems(stuItems);
hkIds.addAll(retMap.get("hkIds"));
logger.info("end calculate right rate");
page = holidayStuHomeworkItemService.queryNotCalculate(CP.cursor(page.getLast().getId()));
}
return hkIds;
}
/**
* 计算排名 1. 学生各专项在班级中的排名。 2. 学生假期作业在班级中排名。
*/
public void rank(Collection<Long> hkIds) {
for (Long hkId : hkIds) {
logger.info("begin calculate {} holiday homework rank.", hkId);
holidayHomeworkRankService.calculateStuHomeworkItemRank(hkId);
logger.info("end calculate {} holiday homework rank.", hkId);
}
}
}
| 30.965517 | 102 | 0.782108 |
06a6c75e83dca3fcb9ec0360aad79ce4a0a7e217 | 95 | package dataBase;
public abstract class Domain {
public abstract Domain clone();
}
| 11.875 | 33 | 0.684211 |
2d24407935dc04a379fc34b084ba58e09d175b84 | 232 | package havis.llrpservice.sbc.rfc;
public class RFCTimeoutException extends RFCException {
private static final long serialVersionUID = -2740304948236198088L;
public RFCTimeoutException(String message) {
super(message);
}
}
| 21.090909 | 68 | 0.801724 |
fb711c349a33769c616b4fde85b7907f3939b007 | 1,405 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 0.9.7</a>, using an XML
* Schema.
* $Id$
*/
package auth_2_0;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import java.io.Serializable;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
/**
* Class BiosItem.
*
* @version $Revision$ $Date$
*/
public class BiosItem implements Serializable {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _bio
*/
private auth_2_0.Bio _bio;
//----------------/
//- Constructors -/
//----------------/
public BiosItem()
{
super();
} //-- auth_2_0.BiosItem()
//-----------/
//- Methods -/
//-----------/
/**
* Returns the value of field 'bio'.
*
* @return Bio
* @return the value of field 'bio'.
*/
public auth_2_0.Bio getBio()
{
return this._bio;
} //-- auth_2_0.Bio getBio()
/**
* Sets the value of field 'bio'.
*
* @param bio the value of field 'bio'.
*/
public void setBio(auth_2_0.Bio bio)
{
this._bio = bio;
} //-- void setBio(auth_2_0.Bio)
}
| 19.513889 | 66 | 0.442705 |
6879d27f59cf2dd81d87d4588dfb90d572d8c154 | 9,599 | /*
* MIT License
*
* Copyright (c) 2021-2022 Jannis Weis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.github.weisj.jsvg.geometry.path;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import com.github.weisj.jsvg.geometry.size.Length;
/**
* A helper for parsing {@link PathCommand}s.
*
* @author Jannis Weis
*/
public class PathParser {
private final String input;
private final int inputLength;
private int index;
private char currentCommand;
public PathParser(@Nullable String input) {
this.input = input;
this.inputLength = input != null ? input.length() : 0;
}
private boolean isCommandChar(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
private boolean isWhiteSpaceOrSeparator(char c) {
return c == ',' || Character.isWhitespace(c);
}
private char peek() {
return input.charAt(index);
}
private void consume() {
index++;
}
private boolean hasNext() {
return index < inputLength;
}
// This only checks for the rough structure of a number as we need to know
// when to separate the next token.
// Explicit parsing is done by Float#parseFloat.
private boolean isValidNumberChar(char c, NumberCharState state) {
boolean valid = '0' <= c && c <= '9';
if (valid && state.iteration == 1 && input.charAt(index - 1) == '0') {
// Break up combined zeros into multiple numbers.
return false;
}
state.signAllowed = state.signAllowed && !valid;
if (state.dotAllowed && !valid) {
valid = c == '.';
state.dotAllowed = !valid;
}
if (state.signAllowed && !valid) {
valid = c == '+' || c == '-';
state.signAllowed = valid;
}
if (state.exponentAllowed && !valid) {
// Possible exponent notation. Needs at least one preceding number
valid = c == 'e' || c == 'E';
state.exponentAllowed = !valid;
state.signAllowed = valid;
}
state.iteration++;
return valid;
}
private void consumeWhiteSpaceOrSeparator() {
while (hasNext() && isWhiteSpaceOrSeparator(peek())) {
consume();
}
}
private float nextFloatOrUnspecified() {
if (!hasNext()) return Length.UNSPECIFIED_RAW;
return nextFloat();
}
private float nextFloat() {
int start = index;
NumberCharState state = new NumberCharState();
while (hasNext() && isValidNumberChar(peek(), state)) {
consume();
}
int end = index;
consumeWhiteSpaceOrSeparator();
String token = input.substring(start, end);
try {
return Float.parseFloat(token);
} catch (NumberFormatException e) {
String msg = "Unexpected element while parsing cmd '" + currentCommand
+ "' encountered token '" + token + "' rest="
+ input.substring(start, Math.min(input.length(), start + 10))
+ " (index=" + index + " in input=" + input + ")";
throw new IllegalStateException(msg, e);
}
}
public @Nullable BezierPathCommand parseMeshCommand() {
if (input == null) return null;
char peekChar = peek();
currentCommand = 'z';
if (isCommandChar(peekChar)) {
consume();
currentCommand = peekChar;
}
consumeWhiteSpaceOrSeparator();
switch (currentCommand) {
case 'l':
return new LineToBezier(true, nextFloatOrUnspecified(), nextFloatOrUnspecified());
case 'L':
return new LineToBezier(false, nextFloatOrUnspecified(), nextFloatOrUnspecified());
case 'c':
return new CubicBezierCommand(true, nextFloat(), nextFloat(), nextFloat(), nextFloat(),
nextFloatOrUnspecified(), nextFloatOrUnspecified());
case 'C':
return new CubicBezierCommand(false, nextFloat(), nextFloat(), nextFloat(), nextFloat(),
nextFloatOrUnspecified(), nextFloatOrUnspecified());
default:
throw new IllegalStateException("Only commands c C l L allowed");
}
}
public PathCommand[] parsePathCommand() {
if (input == null) return new PathCommand[0];
List<PathCommand> commands = new ArrayList<>();
currentCommand = 'Z';
while (hasNext()) {
char peekChar = peek();
if (isCommandChar(peekChar)) {
consume();
currentCommand = peekChar;
}
consumeWhiteSpaceOrSeparator();
PathCommand cmd;
switch (currentCommand) {
case 'M':
cmd = new MoveTo(false, nextFloat(), nextFloat());
currentCommand = 'L';
break;
case 'm':
cmd = new MoveTo(true, nextFloat(), nextFloat());
currentCommand = 'l';
break;
case 'L':
cmd = new LineTo(false, nextFloat(), nextFloat());
break;
case 'l':
cmd = new LineTo(true, nextFloat(), nextFloat());
break;
case 'H':
cmd = new Horizontal(false, nextFloat());
break;
case 'h':
cmd = new Horizontal(true, nextFloat());
break;
case 'V':
cmd = new Vertical(false, nextFloat());
break;
case 'v':
cmd = new Vertical(true, nextFloat());
break;
case 'A':
cmd = new Arc(false, nextFloat(), nextFloat(),
nextFloat(),
nextFloat() == 1f, nextFloat() == 1f,
nextFloat(), nextFloat());
break;
case 'a':
cmd = new Arc(true, nextFloat(), nextFloat(),
nextFloat(),
nextFloat() == 1f, nextFloat() == 1f,
nextFloat(), nextFloat());
break;
case 'Q':
cmd = new Quadratic(false, nextFloat(), nextFloat(),
nextFloat(), nextFloat());
break;
case 'q':
cmd = new Quadratic(true, nextFloat(), nextFloat(),
nextFloat(), nextFloat());
break;
case 'T':
cmd = new QuadraticSmooth(false, nextFloat(), nextFloat());
break;
case 't':
cmd = new QuadraticSmooth(true, nextFloat(), nextFloat());
break;
case 'C':
cmd = new Cubic(false, nextFloat(), nextFloat(),
nextFloat(), nextFloat(),
nextFloat(), nextFloat());
break;
case 'c':
cmd = new Cubic(true, nextFloat(), nextFloat(),
nextFloat(), nextFloat(),
nextFloat(), nextFloat());
break;
case 'S':
cmd = new CubicSmooth(false, nextFloat(), nextFloat(),
nextFloat(), nextFloat());
break;
case 's':
cmd = new CubicSmooth(true, nextFloat(), nextFloat(),
nextFloat(), nextFloat());
break;
case 'Z':
case 'z':
cmd = new Terminal();
break;
default:
throw new IllegalArgumentException("Invalid path element "
+ currentCommand + "(at index=" + index + " in input=" + input + ")");
}
commands.add(cmd);
}
return commands.toArray(new PathCommand[0]);
}
private static class NumberCharState {
int iteration = 0;
boolean dotAllowed = true;
boolean signAllowed = true;
boolean exponentAllowed = true;
}
}
| 37.496094 | 104 | 0.512553 |
87bf5cdfa97930c16c4f9861d52f86459855a98d | 6,809 | /*
* Copyright 2017 Otavio R. Piske <[email protected]>
*
* 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 org.maestro.test.scripts.support;
import net.orpiske.jms.test.annotations.Provider;
import org.maestro.client.exchange.MaestroTopics;
import org.maestro.common.LogConfigurator;
import org.maestro.client.Maestro;
import org.maestro.common.client.notes.MaestroCommand;
import org.maestro.common.client.notes.MaestroNote;
import org.maestro.common.client.notes.MaestroNoteType;
import net.orpiske.jms.provider.activemq.ActiveMqProvider;
import org.maestro.worker.tests.support.annotations.MaestroPeer;
import org.maestro.worker.tests.support.annotations.ReceivingPeer;
import org.maestro.worker.tests.support.annotations.SendingPeer;
import org.maestro.worker.tests.support.common.EndToEndTest;
import org.maestro.worker.tests.support.runner.MiniBrokerConfiguration;
import org.maestro.worker.tests.support.runner.MiniPeer;
import org.maestro.worker.tests.support.runner.WorkerTestRunner;
import org.junit.*;
import org.junit.runner.RunWith;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
@RunWith(WorkerTestRunner.class)
@Provider(
value = ActiveMqProvider.class,
configuration = MiniBrokerConfiguration.class)
public class ScriptTest extends EndToEndTest {
@ReceivingPeer
private MiniPeer miniReceivingPeer;
@SendingPeer
private MiniPeer miniSendingPeer;
@MaestroPeer
private Maestro maestro;
@Before
public void setUp() throws Exception {
LogConfigurator.silent();
System.setProperty("maestro.mqtt.no.reuse", "true");
miniSendingPeer.start();
miniReceivingPeer.start();
}
@After
public void tearDown() {
miniSendingPeer.stop();
miniReceivingPeer.stop();
}
@Test
public void testPing() throws InterruptedException, ExecutionException, TimeoutException {
System.out.println("Sending the ping request");
List<? extends MaestroNote> replies = maestro
.pingRequest(MaestroTopics.WORKERS_TOPIC)
.get(10, TimeUnit.SECONDS);
assertEquals("Unexpected reply size", 2, replies.size());
MaestroNote note = replies.get(0);
assertEquals(note.getNoteType(), MaestroNoteType.MAESTRO_TYPE_RESPONSE);
assertEquals(note.getMaestroCommand(), MaestroCommand.MAESTRO_NOTE_PING);
}
@Test
public void testSetFixedMessageSize() throws ExecutionException, InterruptedException, TimeoutException {
System.out.println("Sending the set fixed message size request");
List<? extends MaestroNote> replies = maestro
.setMessageSize(MaestroTopics.WORKERS_TOPIC, 100)
.get(10, TimeUnit.SECONDS);
assertEquals(2, replies.size());
MaestroNote note = replies.get(0);
assertEquals(note.getNoteType(), MaestroNoteType.MAESTRO_TYPE_RESPONSE);
assertEquals(note.getMaestroCommand(), MaestroCommand.MAESTRO_NOTE_OK);
}
@Test
public void testSetVariableMessageSize() throws ExecutionException, InterruptedException, TimeoutException {
System.out.println("Sending the set variable message size request");
List<? extends MaestroNote> replies = maestro.setMessageSize(MaestroTopics.WORKERS_TOPIC, "~100")
.get(10, TimeUnit.SECONDS);
assertEquals("Current size = " + replies.size(), 2, replies.size());
MaestroNote note = replies.get(0);
assertEquals(note.getNoteType(), MaestroNoteType.MAESTRO_TYPE_RESPONSE);
assertEquals(note.getMaestroCommand(), MaestroCommand.MAESTRO_NOTE_OK);
}
@Test
public void testSetBroker() throws InterruptedException, ExecutionException, TimeoutException {
System.out.println("Sending the set broker request");
List<? extends MaestroNote> replies = maestro
.setBroker(MaestroTopics.WORKERS_TOPIC, "amqp://localhost/unit.test.queue")
.get(10, TimeUnit.SECONDS);
assertEquals(2, replies.size());
MaestroNote note = replies.get(0);
assertEquals(note.getNoteType(), MaestroNoteType.MAESTRO_TYPE_RESPONSE);
assertEquals(note.getMaestroCommand(), MaestroCommand.MAESTRO_NOTE_OK);
}
@Test
public void testSetParallelCount() throws InterruptedException, ExecutionException, TimeoutException {
System.out.println("Sending the set parallel count request");
List<? extends MaestroNote> replies = maestro
.setParallelCount(MaestroTopics.WORKERS_TOPIC, 100)
.get(10, TimeUnit.SECONDS);
assertEquals(2, replies.size());
MaestroNote note = replies.get(0);
assertEquals(note.getNoteType(), MaestroNoteType.MAESTRO_TYPE_RESPONSE);
assertEquals(note.getMaestroCommand(), MaestroCommand.MAESTRO_NOTE_OK);
}
@Test
public void testSetFCL() throws InterruptedException, ExecutionException, TimeoutException {
System.out.println("Sending the set fail condition request");
List<? extends MaestroNote> replies = maestro
.setFCL(MaestroTopics.WORKERS_TOPIC, 100)
.get(10, TimeUnit.SECONDS);
assertEquals(2, replies.size());
MaestroNote note = replies.get(0);
assertEquals(note.getNoteType(), MaestroNoteType.MAESTRO_TYPE_RESPONSE);
assertEquals(note.getMaestroCommand(), MaestroCommand.MAESTRO_NOTE_OK);
}
/*
* Deliberately marked as ignored because this feature is not yet complete
*/
@Test
public void testStatsRequest() throws InterruptedException, ExecutionException, TimeoutException {
System.out.println("Sending the stats request");
List<? extends MaestroNote> replies = maestro
.statsRequest()
.get(10, TimeUnit.SECONDS);
assertEquals("Unexpected reply size", 2, replies.size());
MaestroNote note = replies.get(0);
assertEquals(note.getNoteType(), MaestroNoteType.MAESTRO_TYPE_RESPONSE);
assertEquals(note.getMaestroCommand(), MaestroCommand.MAESTRO_NOTE_STATS);
}
}
| 38.468927 | 112 | 0.715524 |
c1febf37d608cea00001072388fb69b4e047dad4 | 4,222 | package com.mingrisoft;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends Activity {
private Handler handler; // 定义一个android.os.Handler对象
private String result = ""; // 定义一个代表显示内容的字符串
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView step = (TextView) findViewById(R.id.text1); //获取TextView显示单日步数
final TextView time = (TextView) findViewById(R.id.text2); //获取TextView显示单日时间
final TextView heat = (TextView) findViewById(R.id.text3); //获取TextView显示单日热量
final TextView km = (TextView) findViewById(R.id.text4); //获取TextView显示单日公里
final TextView step1 = (TextView) findViewById(R.id.text5); //获取TextView显示周步数
final TextView time1 = (TextView) findViewById(R.id.text6); //获取TextView显示周时间
final TextView heat1 = (TextView) findViewById(R.id.text7); //获取TextView显示周热量
final TextView km1 = (TextView) findViewById(R.id.text8); //获取TextView显示周公里
handler = new Handler() { //解析返回的JSON串数据并显示
@Override
public void handleMessage(Message msg) {
//创建TextView二维数组
TextView[][] tv = {{step, time, heat, km}, {step1, time1, heat1, km1}};
try {
JSONArray jsonArray = new JSONArray(result); //将获取的数据保存在JSONArray数组中
for (int i = 0; i < jsonArray.length(); i++) { //通过for循环遍历JSON数据
JSONObject jsonObject = jsonArray.getJSONObject(i); //解析JSON数据
tv[i][0].setText(jsonObject.getString("step")); //获取JSON中的步数值
tv[i][1].setText(jsonObject.getString("time")); //获取JSON中的时间值
tv[i][2].setText(jsonObject.getString("heat")); //获取JSON中的热量值
tv[i][3].setText(jsonObject.getString("km")); //获取JSON中的公里数
}
} catch (JSONException e) {
e.printStackTrace();
}
super.handleMessage(msg);
}
};
new Thread(new Runnable() { // 创建一个新线程,用于从服务器中获取JSON数据
public void run() {
send(); //调用send()方法,用于发送请求并获取JSON数据
Message m = handler.obtainMessage(); // 获取一个Message
handler.sendMessage(m); // 发送消息
}
}).start(); // 开启线程
}
public void send() { //创建send()方法,实现发送请求并获取JSON数据
String target = "http://192.168.1.198:8080/example/index.json"; //要发送请求的服务器地址
URL url;
try {
url = new URL(target); //创建URL对象
// 创建一个HTTP连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("POST"); // 指定使用POST请求方式
urlConn.setDoOutput(true); // 从连接中读取数据
urlConn.setUseCaches(false); // 禁止缓存
urlConn.setInstanceFollowRedirects(true); //自动执行HTTP重定向
InputStreamReader in = new InputStreamReader(
urlConn.getInputStream()); // 获得读取的内容
BufferedReader buffer = new BufferedReader(in); // 获取输入流对象
String inputLine = null;
while ((inputLine = buffer.readLine()) != null) { //通过循环逐行读取输入流中的内容
result += inputLine;
}
in.close(); //关闭输入流
urlConn.disconnect(); //断开连接
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 43.979167 | 92 | 0.575793 |
fc3b9f07de1d6f2125d12da8889426ef349986d5 | 13,757 | package cz.metacentrum.perun.core.impl.modules.attributes;
import cz.metacentrum.perun.audit.events.AuditEvent;
import cz.metacentrum.perun.audit.events.GroupManagerEvents.DirectMemberAddedToGroup;
import cz.metacentrum.perun.audit.events.GroupManagerEvents.IndirectMemberAddedToGroup;
import cz.metacentrum.perun.audit.events.GroupManagerEvents.MemberExpiredInGroup;
import cz.metacentrum.perun.audit.events.GroupManagerEvents.MemberRemovedFromGroupTotally;
import cz.metacentrum.perun.audit.events.GroupManagerEvents.MemberValidatedInGroup;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.ExtSource;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.UserExtSource;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.UserExtSourceAlreadyRemovedException;
import cz.metacentrum.perun.core.api.exceptions.UserExtSourceExistsException;
import cz.metacentrum.perun.core.api.exceptions.UserExtSourceNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;
import cz.metacentrum.perun.core.implApi.modules.attributes.UserVirtualAttributesModuleAbstract;
import cz.metacentrum.perun.core.implApi.modules.attributes.UserVirtualAttributesModuleImplApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Reacts on audit messages about adding, removing... member to group.
* When member is added or validated it will create userExtSource with appropriate attributes.
* When member is removed or expired it will remove the userExtSource.
*
* @author Ľuboslav Halama [email protected]
*/
public class urn_perun_user_attribute_def_virt_studentIdentifiers extends UserVirtualAttributesModuleAbstract implements UserVirtualAttributesModuleImplApi {
private static final String studentIdentifiersValuePrefix = "urn:schac:personalUniqueCode:int:esi:";
private static final String affiliationPrefix = "student@";
private static final String organizationNamespaceFriendlyName = "organizationNamespace";
private static final String organizationScopeFriendlyName = "organizationScope";
private static final String organizationPersonalCodeScopeFriendlyName = "organizationPersonalCodeScope";
private static final String schacHomeOrganizationFriendlyName = "schacHomeOrganization";
private static final String eduPersonScopedAffiliationFriendlyName = "affiliation";
private static final String schacPersonalUniqueCodeFriendlyName = "schacPersonalUniqueCode";
private static final String A_G_D_organizationNamespaceFriendlyName = AttributesManager.NS_GROUP_ATTR_DEF + ":" + organizationNamespaceFriendlyName;
private static final String A_G_D_organizationScopeFriendlyName = AttributesManager.NS_GROUP_ATTR_DEF + ":" + organizationScopeFriendlyName;
private static final String A_G_D_organizationPersonalCodeScopeFriendlyName = AttributesManager.NS_GROUP_ATTR_DEF + ":" + organizationPersonalCodeScopeFriendlyName;
private static final String A_U_D_loginNamespaceFriendlyNamePrefix = AttributesManager.NS_USER_ATTR_DEF + ":" + AttributesManager.LOGIN_NAMESPACE + ":";
private static final String A_UES_D_schacHomeOrganizationFriendlyName = AttributesManager.NS_UES_ATTR_DEF + ":" + schacHomeOrganizationFriendlyName;
private static final String A_UES_D_eduPersonScopedAffiliationFriendlyName = AttributesManager.NS_UES_ATTR_DEF + ":" + eduPersonScopedAffiliationFriendlyName;
private static final String A_UES_D_schacPersonalUniqueCodeFriendlyName = AttributesManager.NS_UES_ATTR_DEF + ":" + schacPersonalUniqueCodeFriendlyName;
private final static Logger log = LoggerFactory.getLogger(urn_perun_user_attribute_def_virt_studentIdentifiers.class);
@Override
public List<AuditEvent> resolveVirtualAttributeValueChange(PerunSessionImpl sess, AuditEvent message) throws AttributeNotExistsException, WrongAttributeAssignmentException {
List<AuditEvent> resolvingMessages = new ArrayList<>();
if (message == null) return resolvingMessages;
if (message instanceof DirectMemberAddedToGroup) {
processAddUserExtSource(sess, ((DirectMemberAddedToGroup) message).getGroup(), ((DirectMemberAddedToGroup) message).getMember());
} else if (message instanceof IndirectMemberAddedToGroup) {
processAddUserExtSource(sess, ((IndirectMemberAddedToGroup) message).getGroup(), ((IndirectMemberAddedToGroup) message).getMember());
} else if (message instanceof MemberValidatedInGroup) {
processAddUserExtSource(sess, ((MemberValidatedInGroup) message).getGroup(), ((MemberValidatedInGroup) message).getMember());
} else if (message instanceof MemberRemovedFromGroupTotally) {
processRemoveUserExtSource(sess, ((MemberRemovedFromGroupTotally) message).getGroup(), ((MemberRemovedFromGroupTotally) message).getMember());
} else if (message instanceof MemberExpiredInGroup) {
processRemoveUserExtSource(sess, ((MemberExpiredInGroup) message).getGroup(), ((MemberExpiredInGroup) message).getMember());
}
return resolvingMessages;
}
@Override
public AttributeDefinition getAttributeDefinition() {
AttributeDefinition attr = new AttributeDefinition();
attr.setNamespace(AttributesManager.NS_USER_ATTR_VIRT);
attr.setFriendlyName("studentIdentifiers");
attr.setDisplayName("student identifiers");
attr.setType(ArrayList.class.getName());
attr.setDescription("Virtual attribute, which creates and removes userExtSource" +
" with identifiers according to audit events.");
return attr;
}
/**
* Set userExtSource with attributes for member's user if not exists.
*
* @param sess Perun session
* @param group from which appropriate attributes will be obtained
* @param member for which the xtSource with attributes will be processed
*/
private void processAddUserExtSource(PerunSessionImpl sess, Group group, Member member) {
User user = sess.getPerunBl().getUsersManagerBl().getUserByMember(sess, member);
Attribute organizationScope = tryGetAttribute(sess, group, A_G_D_organizationScopeFriendlyName);
if (organizationScope == null|| organizationScope.getValue() == null) {
return;
}
String schacPersonalCodeScope = organizationScope.valueAsString();
Attribute organizationNamespace = this.tryGetAttribute(sess, group, A_G_D_organizationNamespaceFriendlyName);
if (organizationNamespace == null || organizationNamespace.getValue() == null) {
return;
}
Attribute userLoginID = tryGetAttribute(sess, user, A_U_D_loginNamespaceFriendlyNamePrefix + organizationNamespace.valueAsString());
if (userLoginID == null || userLoginID.getValue() == null) {
return;
}
// In case this attribute exists and it is filled, it will be used in SPUC attribute instead of sHO
Attribute organizationPersonalCodeScope = tryGetAttribute(sess, group, A_G_D_organizationPersonalCodeScopeFriendlyName);
if (organizationPersonalCodeScope != null && organizationPersonalCodeScope.getValue() != null) {
schacPersonalCodeScope = organizationPersonalCodeScope.valueAsString();
}
ExtSource extSource = tryGetExtSource(sess, organizationScope.valueAsString());
//Create and set userExtSource if not exists
try {
sess.getPerunBl().getUsersManagerBl().getUserExtSourceByExtLogin(sess, extSource, userLoginID.valueAsString());
} catch (UserExtSourceNotExistsException e) {
UserExtSource ues = new UserExtSource(extSource, userLoginID.valueAsString());
try {
ues = sess.getPerunBl().getUsersManagerBl().addUserExtSource(sess, user, ues);
} catch (UserExtSourceExistsException userExtSourceExistsException) {
//Should not happened
throw new InternalErrorException(e);
}
Attribute schacHomeOrganization = tryGetAttribute(sess, ues, A_UES_D_schacHomeOrganizationFriendlyName);
Attribute eduPersonScopedAffiliation = tryGetAttribute(sess, ues, A_UES_D_eduPersonScopedAffiliationFriendlyName);
Attribute schacPersonalUniqueCode = tryGetAttribute(sess, ues, A_UES_D_schacPersonalUniqueCodeFriendlyName);
schacHomeOrganization.setValue(organizationScope.valueAsString());
eduPersonScopedAffiliation.setValue(affiliationPrefix + organizationScope.valueAsString());
List<String> spucValue = new ArrayList<>();
spucValue.add(studentIdentifiersValuePrefix + schacPersonalCodeScope + ":" + userLoginID.valueAsString());
schacPersonalUniqueCode.setValue(spucValue);
try {
sess.getPerunBl().getAttributesManagerBl().setAttributes(sess, ues, Arrays.asList(schacHomeOrganization, eduPersonScopedAffiliation, schacPersonalUniqueCode));
} catch (WrongAttributeValueException |WrongAttributeAssignmentException| WrongReferenceAttributeValueException ex) {
//Should not happened
throw new InternalErrorException(ex);
}
}
}
/**
* Remove userExtSource with attributes for member's user if exists.
*
* @param sess Perun session
* @param group from which appropriate attributes will be obtained
* @param member for which the xtSource with attributes will be processed
*/
private void processRemoveUserExtSource(PerunSessionImpl sess, Group group, Member member) {
User user = sess.getPerunBl().getUsersManagerBl().getUserByMember(sess, member);
Attribute organizationScope = tryGetAttribute(sess, group, A_G_D_organizationScopeFriendlyName);
if (organizationScope == null|| organizationScope.getValue() == null) {
return;
}
Attribute organizationNamespace = this.tryGetAttribute(sess, group, A_G_D_organizationNamespaceFriendlyName);
if (organizationNamespace == null || organizationNamespace.getValue() == null) {
return;
}
Attribute userLoginID = tryGetAttribute(sess, user, A_U_D_loginNamespaceFriendlyNamePrefix + organizationNamespace.valueAsString());
if (userLoginID == null || userLoginID.getValue() == null) {
return;
}
ExtSource extSource = tryGetExtSource(sess, organizationScope.valueAsString());
//Remove userExtSource if exists
try {
UserExtSource ues = sess.getPerunBl().getUsersManagerBl().getUserExtSourceByExtLogin(sess, extSource, userLoginID.valueAsString());
sess.getPerunBl().getUsersManagerBl().removeUserExtSource(sess, user, ues);
} catch (UserExtSourceNotExistsException e) {
//Means that the ues was already removed, which is ok
} catch (UserExtSourceAlreadyRemovedException e) {
//Should not happened
throw new InternalErrorException(e);
}
}
/**
* Fetches ExtSource from the database.
*
* @param sess PerunSession
* @param name ExtSource name
* @return ExtSource
*/
private ExtSource tryGetExtSource(PerunSessionImpl sess, String name) {
try {
return sess.getPerunBl().getExtSourcesManagerBl().getExtSourceByName(sess, name);
} catch (ExtSourceNotExistsException e) {
//Should not happened
throw new InternalErrorException(e);
}
}
/**
* Fetches ues attribute if it is possible
*
* @param sess PerunSession
* @param ues userextSource for which the attribute will be fetched
* @param attributeName full name of the attribute
* @return Attribute
*/
private Attribute tryGetAttribute(PerunSessionImpl sess, UserExtSource ues, String attributeName) {
try {
return sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, ues, attributeName);
} catch (WrongAttributeAssignmentException e) {
throw new InternalErrorException("Wrong assignment of " + attributeName + " for userExtSource " + ues.getId(), e);
} catch (AttributeNotExistsException e) {
throw new InternalErrorException("Attribute " + attributeName + " for userExtSource " + ues.getId() + " does not exists.", e);
}
}
/**
* Fetches group attribute if it is possible
*
* @param sess PerunSession
* @param group Group for which the attribute will be fetched
* @param attributeName full name of the attribute
* @return Attribute
*/
private Attribute tryGetAttribute(PerunSessionImpl sess, Group group, String attributeName) {
try {
return sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, attributeName);
} catch (WrongAttributeAssignmentException e) {
throw new InternalErrorException("Wrong assignment of " + attributeName + " for group " + group.getId(), e);
} catch (AttributeNotExistsException e) {
log.debug("Attribute " + attributeName + " of group " + group.getId() + " does not exist, values will be skipped", e);
}
return null;
}
/**
* Fetches user attribute if it is possible
*
* @param sess PerunSession
* @param user User for which the attribute will be fetched
* @param attributeName full name of the attribute
* @return Attribute
*/
private Attribute tryGetAttribute(PerunSessionImpl sess, User user, String attributeName) {
try {
return sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, user, attributeName);
} catch (WrongAttributeAssignmentException e) {
throw new InternalErrorException("Wrong assignment of " + attributeName + " for user " + user.getId(), e);
} catch (AttributeNotExistsException e) {
log.debug("Attribute " + attributeName + " of user " + user.getId() + " does not exist, values will be skipped", e);
}
return null;
}
}
| 51.913208 | 174 | 0.796685 |
836c375e8ef5221e400c5529d9c963e607bae0db | 7,955 | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*/
//----------------------------------------------------
// THIS CODE IS GENERATED. MANUAL EDITS WILL BE LOST.
//----------------------------------------------------
package co.elastic.clients.elasticsearch._types.analysis;
import co.elastic.clients.json.JsonpDeserializable;
import co.elastic.clients.json.JsonpDeserializer;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.ObjectBuilderDeserializer;
import co.elastic.clients.json.ObjectDeserializer;
import co.elastic.clients.util.ApiTypeHelper;
import co.elastic.clients.util.ObjectBuilder;
import jakarta.json.stream.JsonGenerator;
import java.lang.Boolean;
import java.lang.Integer;
import java.lang.String;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nullable;
// typedef: _types.analysis.CompoundWordTokenFilterBase
/**
*
* @see <a href=
* "../../doc-files/api-spec.html#_types.analysis.CompoundWordTokenFilterBase">API
* specification</a>
*/
public abstract class CompoundWordTokenFilterBase extends TokenFilterBase {
@Nullable
private final String hyphenationPatternsPath;
@Nullable
private final Integer maxSubwordSize;
@Nullable
private final Integer minSubwordSize;
@Nullable
private final Integer minWordSize;
@Nullable
private final Boolean onlyLongestMatch;
private final List<String> wordList;
@Nullable
private final String wordListPath;
// ---------------------------------------------------------------------------------------------
protected CompoundWordTokenFilterBase(AbstractBuilder<?> builder) {
super(builder);
this.hyphenationPatternsPath = builder.hyphenationPatternsPath;
this.maxSubwordSize = builder.maxSubwordSize;
this.minSubwordSize = builder.minSubwordSize;
this.minWordSize = builder.minWordSize;
this.onlyLongestMatch = builder.onlyLongestMatch;
this.wordList = ApiTypeHelper.unmodifiable(builder.wordList);
this.wordListPath = builder.wordListPath;
}
/**
* API name: {@code hyphenation_patterns_path}
*/
@Nullable
public final String hyphenationPatternsPath() {
return this.hyphenationPatternsPath;
}
/**
* API name: {@code max_subword_size}
*/
@Nullable
public final Integer maxSubwordSize() {
return this.maxSubwordSize;
}
/**
* API name: {@code min_subword_size}
*/
@Nullable
public final Integer minSubwordSize() {
return this.minSubwordSize;
}
/**
* API name: {@code min_word_size}
*/
@Nullable
public final Integer minWordSize() {
return this.minWordSize;
}
/**
* API name: {@code only_longest_match}
*/
@Nullable
public final Boolean onlyLongestMatch() {
return this.onlyLongestMatch;
}
/**
* API name: {@code word_list}
*/
public final List<String> wordList() {
return this.wordList;
}
/**
* API name: {@code word_list_path}
*/
@Nullable
public final String wordListPath() {
return this.wordListPath;
}
protected void serializeInternal(JsonGenerator generator, JsonpMapper mapper) {
super.serializeInternal(generator, mapper);
if (this.hyphenationPatternsPath != null) {
generator.writeKey("hyphenation_patterns_path");
generator.write(this.hyphenationPatternsPath);
}
if (this.maxSubwordSize != null) {
generator.writeKey("max_subword_size");
generator.write(this.maxSubwordSize);
}
if (this.minSubwordSize != null) {
generator.writeKey("min_subword_size");
generator.write(this.minSubwordSize);
}
if (this.minWordSize != null) {
generator.writeKey("min_word_size");
generator.write(this.minWordSize);
}
if (this.onlyLongestMatch != null) {
generator.writeKey("only_longest_match");
generator.write(this.onlyLongestMatch);
}
if (ApiTypeHelper.isDefined(this.wordList)) {
generator.writeKey("word_list");
generator.writeStartArray();
for (String item0 : this.wordList) {
generator.write(item0);
}
generator.writeEnd();
}
if (this.wordListPath != null) {
generator.writeKey("word_list_path");
generator.write(this.wordListPath);
}
}
protected abstract static class AbstractBuilder<BuilderT extends AbstractBuilder<BuilderT>>
extends
TokenFilterBase.AbstractBuilder<BuilderT> {
@Nullable
private String hyphenationPatternsPath;
@Nullable
private Integer maxSubwordSize;
@Nullable
private Integer minSubwordSize;
@Nullable
private Integer minWordSize;
@Nullable
private Boolean onlyLongestMatch;
@Nullable
private List<String> wordList;
@Nullable
private String wordListPath;
/**
* API name: {@code hyphenation_patterns_path}
*/
public final BuilderT hyphenationPatternsPath(@Nullable String value) {
this.hyphenationPatternsPath = value;
return self();
}
/**
* API name: {@code max_subword_size}
*/
public final BuilderT maxSubwordSize(@Nullable Integer value) {
this.maxSubwordSize = value;
return self();
}
/**
* API name: {@code min_subword_size}
*/
public final BuilderT minSubwordSize(@Nullable Integer value) {
this.minSubwordSize = value;
return self();
}
/**
* API name: {@code min_word_size}
*/
public final BuilderT minWordSize(@Nullable Integer value) {
this.minWordSize = value;
return self();
}
/**
* API name: {@code only_longest_match}
*/
public final BuilderT onlyLongestMatch(@Nullable Boolean value) {
this.onlyLongestMatch = value;
return self();
}
/**
* API name: {@code word_list}
* <p>
* Adds all elements of <code>list</code> to <code>wordList</code>.
*/
public final BuilderT wordList(List<String> list) {
this.wordList = _listAddAll(this.wordList, list);
return self();
}
/**
* API name: {@code word_list}
* <p>
* Adds one or more values to <code>wordList</code>.
*/
public final BuilderT wordList(String value, String... values) {
this.wordList = _listAdd(this.wordList, value, values);
return self();
}
/**
* API name: {@code word_list_path}
*/
public final BuilderT wordListPath(@Nullable String value) {
this.wordListPath = value;
return self();
}
}
// ---------------------------------------------------------------------------------------------
protected static <BuilderT extends AbstractBuilder<BuilderT>> void setupCompoundWordTokenFilterBaseDeserializer(
ObjectDeserializer<BuilderT> op) {
TokenFilterBase.setupTokenFilterBaseDeserializer(op);
op.add(AbstractBuilder::hyphenationPatternsPath, JsonpDeserializer.stringDeserializer(),
"hyphenation_patterns_path");
op.add(AbstractBuilder::maxSubwordSize, JsonpDeserializer.integerDeserializer(), "max_subword_size");
op.add(AbstractBuilder::minSubwordSize, JsonpDeserializer.integerDeserializer(), "min_subword_size");
op.add(AbstractBuilder::minWordSize, JsonpDeserializer.integerDeserializer(), "min_word_size");
op.add(AbstractBuilder::onlyLongestMatch, JsonpDeserializer.booleanDeserializer(), "only_longest_match");
op.add(AbstractBuilder::wordList, JsonpDeserializer.arrayDeserializer(JsonpDeserializer.stringDeserializer()),
"word_list");
op.add(AbstractBuilder::wordListPath, JsonpDeserializer.stringDeserializer(), "word_list_path");
}
}
| 26.694631 | 113 | 0.709114 |
5c1b8526e319af5a85f154a414b0e64bae9bbe5c | 437 | class Solution {
public boolean XXX(TreeNode root) {
if(root == null) return true;
if(Math.abs(getTreeHeight(root.left) - getTreeHeight(root.right) > 1) return false;
return XXX(root.left) && XXX(root.right);
}
private int getTreeHeight(TreeNode root) {
if(root == null) return 0;
return Math.max(getTreeHeight(root.left) + 1, getTreeHeight(root.right) + 1);
}
}
| 29.133333 | 91 | 0.604119 |
fdc73bf843c09c986550cd77b2f32e74a79bd803 | 741 | package io.oneko.projectmesh.rest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import io.oneko.automations.LifetimeBehaviourDTO;
import io.oneko.deployable.AggregatedDeploymentStatus;
import io.oneko.deployable.DeploymentBehaviour;
import io.oneko.namespace.rest.NamespaceDTO;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@Data
public class ProjectMeshDTO {
private UUID id;
private String name;
private NamespaceDTO implicitNamespace;
private NamespaceDTO namespace;
private DeploymentBehaviour deploymentBehaviour;
private LifetimeBehaviourDTO lifetimeBehaviour;
private List<MeshComponentDTO> components = new ArrayList<>();
private AggregatedDeploymentStatus status;
}
| 28.5 | 63 | 0.840756 |
40b13eba20c30cba493b0b3e9fcc78d11124d285 | 282 | package business;
public class CourseFullException extends Exception {
public CourseFullException() {
super("Course enrollment limit reached. No more students can be registered.");
}
public CourseFullException(String message) {
super(message);
}
}
| 23.5 | 86 | 0.702128 |
99d2ac31e6f8536dbfab0c8f35a611f9f12a5bc0 | 7,633 | /*
* Copyright (c) 2016, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of Salesforce.com, Inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.desk.java.apiclient.model;
import com.desk.java.apiclient.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Customer implements Serializable {
private static final long serialVersionUID = 5362546629837209181L;
private long id;
private String firstName;
private String lastName;
private String avatar;
private String title;
private String language;
private String background;
private String companyName;
private String displayName;
private CustomerContact[] emails;
private CustomerContact[] addresses;
private CustomerContact[] phoneNumbers;
private CustomerLinks _links;
private HashMap<String, String> customFields;
private CustomerEmbedded _embedded;
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
@Nullable
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Nullable
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@NotNull
public String getName() {
StringBuilder name = new StringBuilder();
if (!StringUtils.isEmpty(getFirstName())) {
name.append(getFirstName());
}
if (!StringUtils.isEmpty(getLastName())) {
if (name.length() > 0) {
name.append(" ");
}
name.append(getLastName());
}
return name.toString();
}
@Nullable
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Nullable
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
@Nullable
public String getBackground() {
return background;
}
public void setBackground(String background) {
this.background = background;
}
@Nullable
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
@Nullable
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
@Nullable
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
@NotNull
public CustomerContact[] getEmails() {
return emails != null ? emails : new CustomerContact[0];
}
public void setEmails(CustomerContact... emails) {
this.emails = emails;
}
@NotNull
public CustomerContact[] getAddresses() {
return addresses != null ? addresses : new CustomerContact[0];
}
public void setAddresses(CustomerContact... addresses) {
this.addresses = addresses;
}
@NotNull
public CustomerContact[] getPhoneNumbers() {
return phoneNumbers != null ? phoneNumbers : new CustomerContact[0];
}
public void setPhoneNumbers(CustomerContact... phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
@NotNull
public CustomerLinks getLinks() {
return _links == null ? _links = new CustomerLinks() : _links;
}
public void setLinks(CustomerLinks links) {
this._links = links;
}
@NotNull
public Map<String, String> getCustomFields() {
return customFields != null ? customFields : Collections.<String, String>emptyMap();
}
public void setCustomFields(HashMap<String, String> customFields) {
this.customFields = customFields;
}
@NotNull
public CustomerEmbedded getEmbedded() {
return _embedded == null ? _embedded = new CustomerEmbedded() : _embedded;
}
public void setEmbedded(CustomerEmbedded embedded) {
this._embedded = embedded;
}
/**
* Gets the first email
* @return the first email or null if no email
*/
@Nullable
public String getFirstEmail() {
if (getEmails().length == 0) {
return null;
}
return getEmails()[0].getValue();
}
/**
* Gets the first phone number
* @return the first phone number or null if no phone number exists
*/
@Nullable
public String getFirstPhone() {
if (getPhoneNumbers().length == 0) {
return null;
}
return getPhoneNumbers()[0].getValue();
}
/**
* Gets the handle of the first twitter user
* @return the handle of the first twitter user or null if no twitter user
*/
@Nullable
public String getTwitterHandle() {
if (getTwitterUser() == null) {
return null;
}
return getTwitterUser().getHandle();
}
/**
* Gets the embedded facebook user
* @return the embedded facebook user or null if there is no embedded facebook user
*/
@Nullable
public FacebookUser getFacebookUser() {
return getEmbedded().getFacebookUser();
}
/**
* Gets the embedded twitter user
* @return the embedded twitter user or null if there is no embedded twitter user
*/
@Nullable
public TwitterUser getTwitterUser() {
return getEmbedded().getTwitterUser();
}
/**
* Gets the self link
* @return the self link
*/
@NotNull
public Link getSelfLink() {
return getLinks().getSelf();
}
/**
* Get the company link or null if there is no company
* @return the company link or null
*/
@Nullable
public Link getCompanyLink() {
return getLinks().getCompany();
}
}
| 26.876761 | 109 | 0.651251 |
d3d6d3660eb364b3f75845324a82406af1ed2074 | 285 | package Compiler.AST;
import Compiler.Utils.Position;
public class NullLiteralNode extends ConstExprNode {
public NullLiteralNode(Position position) {
super(position);
}
@Override
public void accept(ASTVisitor visitor) {
visitor.visit(this);
}
}
| 19 | 52 | 0.694737 |
7678962434aaab0393914fc6ce1142b680b776b3 | 517 | import java.util.ArrayList;
import java.util.List;
public class _0094BinaryTreeInorderTraversal {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if (root == null) return list;
list.addAll(inorderTraversal(root.left));
list.add(root.val);
list.addAll(inorderTraversal(root.right));
return list;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}
| 24.619048 | 58 | 0.659574 |
aedbfd764438b85bc5bda654fe77f35fc25984df | 2,223 | package com.nasa.api.scrapper;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
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.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;
import com.nasa.api.scrapper.deserialization.Deserializer;
import com.nasa.api.scrapper.model.Weather;
import com.nasa.api.scrapper.services.SolService;
/**
* Scrapper Application
*
* @author Pierre
*
*/
@SpringBootApplication
@PropertySource("classpath:application.properties")
@EnableScheduling
public class ScrapperApplication {
@Value("${api.url}")
private String apiUrl;
@Autowired
private SolService solService;
private static final Logger logger = LoggerFactory.getLogger(ScrapperApplication.class);
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
@Bean
public Weather getWeatherData() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity(this.apiUrl, String.class);
return Deserializer.gson.fromJson(response.getBody(), Weather.class);
}
public static void main(String[] args) {
SpringApplication.run(ScrapperApplication.class, args);
}
/**
* Runs every five minutes.
*/
@Scheduled(fixedRate = 300000, initialDelay = 10000)
public void scheduleTaskWithFixedRate() {
logger.info("Scheduled Task :: Execution Time - {}", dateTimeFormatter.format(LocalDateTime.now()));
Weather weather = getWeatherData();
logger.info("Scheduled Task :: Printing weather data :: " + weather.toString());
weather.getSols().forEach((k, v) -> {
logger.info("Scheduled Task :: Sol " + k);
this.solService.save(v);
});
}
}
| 31.309859 | 102 | 0.786775 |
b98479fb25d04390a6677d90f9d20b3bdef3ad48 | 2,826 | package frc.robot.commands.autocommands;
import java.util.List;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
import frc.robot.subsystems.DriveTrainSubsystem;
import frc.robot.subsystems.ShootingSubsystem;
public class RandomCommands extends SequentialCommandGroup {
public RandomCommands(DriveTrainSubsystem driveTrainSubsystem, ShootingSubsystem shootingSubsystem)
{
// drive forward and look for ball
addCommands(
new RotateDegrees(15, driveTrainSubsystem, 2.0),
new RotateDegrees(30, driveTrainSubsystem, -2.0),
new RotateDegrees(30, driveTrainSubsystem, 2.0),
new RotateDegrees(30, driveTrainSubsystem, -2.0),
new RotateDegrees(30, driveTrainSubsystem, 2.0),
new RotateDegrees(30, driveTrainSubsystem, -2.0),
new DriveForwardSeconds(0.3, 0.8, driveTrainSubsystem),
new RotateDegrees(180, driveTrainSubsystem, 2.0),
new DriveForwardSeconds(0.3, -0.8, driveTrainSubsystem),
new RotateDegrees(180, driveTrainSubsystem, 4.0),
new DriveForwardSeconds(0.3, 0.8, driveTrainSubsystem),
new RotateDegrees(180, driveTrainSubsystem, -4.0),
new DriveForwardSeconds(0.3, -0.8, driveTrainSubsystem),
new RotateDegrees(180, driveTrainSubsystem, 4.0),
new DriveForwardSeconds(0.3, 0.8, driveTrainSubsystem),
new RotateDegrees(180, driveTrainSubsystem, -4.0),
new DriveForwardSeconds(0.3, -0.8, driveTrainSubsystem),
new ShootForSecondsCommand(0.1, driveTrainSubsystem, shootingSubsystem),
new DoAbsolutelyNothingForSeconds(0.1, driveTrainSubsystem, shootingSubsystem),
new ShootForSecondsCommand(0.1, driveTrainSubsystem, shootingSubsystem),
new DoAbsolutelyNothingForSeconds(0.1, driveTrainSubsystem, shootingSubsystem),
new ShootForSecondsCommand(0.1, driveTrainSubsystem, shootingSubsystem),
new DoAbsolutelyNothingForSeconds(0.1, driveTrainSubsystem, shootingSubsystem),
new ShootForSecondsCommand(0.1, driveTrainSubsystem, shootingSubsystem),
new DoAbsolutelyNothingForSeconds(0.1, driveTrainSubsystem, shootingSubsystem),
new ShootForSecondsCommand(0.1, driveTrainSubsystem, shootingSubsystem),
new DoAbsolutelyNothingForSeconds(0.1, driveTrainSubsystem, shootingSubsystem),
new ShootForSecondsCommand(0.1, driveTrainSubsystem, shootingSubsystem),
new DoAbsolutelyNothingForSeconds(0.1, driveTrainSubsystem, shootingSubsystem)
);
addRequirements(driveTrainSubsystem, shootingSubsystem);
}
}
| 55.411765 | 104 | 0.710545 |
bdc3ca75c3b3af867787573bc0671035d2fb8761 | 11,219 | /*
* Copyright (c) 2002-2010 Atsuhiko Yamanaka, JCraft,Inc. All rights reserved.
* Copyright (c) 2010-2011 Michael Laudati, N1 Concepts LLC.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
* INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.vngx.jsch;
import static org.vngx.jsch.constants.ConnectionProtocol.*;
import org.vngx.jsch.constants.SSHConstants;
import org.vngx.jsch.util.Logger.Level;
import org.vngx.jsch.util.SocketFactory;
import java.io.IOException;
import java.net.Socket;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.vngx.jsch.algorithm.AlgorithmManager;
import org.vngx.jsch.algorithm.Algorithms;
import org.vngx.jsch.algorithm.Random;
/**
* Implementation of <code>Channel</code> for an X11 agent.
*
* The X Window System (commonly X or X11) is a computer software system and
* network protocol that provides a graphical user interface (GUI) for networked
* computers. It creates a hardware abstraction layer where software is written
* to use a generalized set of commands, allowing for device independence and
* reuse of programs on any computer that implements X.
*
* X11 forwarding may be requested for a session by sending a
* SSH_MSG_CHANNEL_REQUEST message.
*
* byte SSH_MSG_CHANNEL_REQUEST
* uint32 recipient channel
* string "x11-req"
* boolean want reply
* boolean single connection
* string x11 authentication protocol
* string x11 authentication cookie
* uint32 x11 screen number
*
* It is RECOMMENDED that the 'x11 authentication cookie' that is sent be a
* fake, random cookie, and that the cookie be checked and replaced by the real
* cookie when a connection request is received.
*
* X11 connection forwarding should stop when the session channel is closed.
* However, already opened forwardings should not be automatically closed when
* the session channel is closed.
*
* If 'single connection' is TRUE, only a single connection should be forwarded.
* No more connections will be forwarded after the first, or after the session
* channel has been closed.
*
* The 'x11 authentication protocol' is the name of the X11 authentication
* method used, e.g., "MIT-MAGIC-COOKIE-1". The 'x11 authentication cookie'
* must be hexadecimal encoded.
*
* X11 channels are opened with a channel open request. The resulting channels
* are independent of the session, and closing the session channel does not
* close the forwarded X11 channels.
*
* byte SSH_MSG_CHANNEL_OPEN
* string "x11"
* uint32 sender channel
* uint32 initial window size
* uint32 maximum packet size
* string originator address (e.g., "192.168.7.38")
* uint32 originator port
*
* The recipient should respond with SSH_MSG_CHANNEL_OPEN_CONFIRMATION or
* SSH_MSG_CHANNEL_OPEN_FAILURE. Implementations must reject any X11 channel
* open requests if they have not requested X11 forwarding.
*
* TODO Why are there class variables instead of instance variables? Can only
* one X11 forwarding channel be opened per JVM? If two sessions are open in
* the same JVM, only one can use X11 forwarding? All sorts of issus with this
* design... damn, sometimes i hate programming... =/ Why mix static and non-
* static shit?!
*
* @author Atsuhiko Yamanaka
* @author Michael Laudati
*/
class ChannelX11 extends Channel {
/** Constant for local maximum window size. */
private static final int LOCAL_WINDOW_SIZE_MAX = 0x20000;
/** Constant for local maximum packet size. */
private static final int LOCAL_MAXIMUM_PACKET_SIZE = 0x4000;
/** Constant for timeout in milliseconds. */
private static final int TIMEOUT = 10 * 1000;
/** Map of faked cookies stored by session instance. */
private static final Map<Session,byte[]> FAKED_COOKIE_POOL = new HashMap<Session,byte[]>();
/** Map of faked hexadecimal cookies stored by session instance. */
private static final Map<Session,byte[]> FAKED_COOKIE_HEX_POOL = new HashMap<Session,byte[]>();
/** TODO ??? */
private static final byte[] TABLE = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66
};
/** Host to display forwarded X11 session to (default localhost). */
private static String $host = SSHConstants.LOCALHOST;
/** PORt to display forwarded X11 session to (default 6000). */
private static int $port = 6000;
/** Cookie containing random data to be send with forwarded X11 packets. */
private static byte[] $cookie = null;
/** Hexadecimal value of cookie value as per X11 forwarding spec. */
private static byte[] $cookieHex = null;
/** Random instance for generating random data. */
private static Random $random = null;
/** Socket connection to X window session receiving forwarded remote X session. */
private Socket _socket = null;
/** True if the channel needs to be initialized at first write() call. */
private boolean _init = true;
/** TODO ??? local cache? */
private byte[] _cache = new byte[0];
/**
* Returns the index of the specified byte value in the constant table.
*
* @param foo byte to lookup index
* @return index of byte in table or zero if no match
*/
static int revtable(byte c) {
for( int i = 0; i < TABLE.length; i++ ) {
if( TABLE[i] == c ) {
return i;
}
}
return 0;
}
static void setCookie(String cookieHex) {
$cookieHex = Util.str2byte(cookieHex);
$cookie = new byte[16];
for( int i = 0; i < 16; i++ ) {
$cookie[i] = (byte) (
((revtable($cookieHex[i * 2]) << 4) & 0xf0) |
((revtable($cookieHex[i * 2 + 1])) & 0xf)
);
}
}
static void setHost(String host) {
$host = host;
}
static void setPort(int port) {
$port = port;
}
static byte[] getFakedCookie(Session session) {
synchronized( FAKED_COOKIE_HEX_POOL ) {
byte[] fakedCookie = FAKED_COOKIE_HEX_POOL.get(session);
if( fakedCookie == null ) {
fakedCookie = new byte[16];
getRandom().fill(fakedCookie, 0, 16);
FAKED_COOKIE_POOL.put(session, fakedCookie);
byte[] bar = new byte[32];
for( int i = 0; i < 16; i++ ) {
bar[2 * i] = TABLE[(fakedCookie[i] >>> 4) & 0xf];
bar[2 * i + 1] = TABLE[(fakedCookie[i]) & 0xf];
}
FAKED_COOKIE_HEX_POOL.put(session, bar);
fakedCookie = bar;
}
return fakedCookie;
}
}
/**
* Creates a new instance of <code>ChannelX11</code>.
*
* @param session
*/
ChannelX11(Session session) {
super(session, ChannelType.X11);
setLocalWindowSizeMax(LOCAL_WINDOW_SIZE_MAX);
setLocalWindowSize(LOCAL_WINDOW_SIZE_MAX);
setLocalPacketSize(LOCAL_MAXIMUM_PACKET_SIZE);
_connected = true; // TODO Why set to true before actually connected?
}
@Override
public void run() {
try {
_socket = SocketFactory.DEFAULT_SOCKET_FACTORY.createSocket($host, $port, TIMEOUT);
_socket.setTcpNoDelay(true);
_io = new IO();
_io.setInputStream(_socket.getInputStream());
_io.setOutputStream(_socket.getOutputStream());
sendOpenConfirmation();
} catch (Exception e) {
// TODO Error handling? Log this somewhere to notify user
sendOpenFailure(SSH_OPEN_ADMINISTRATIVELY_PROHIBITED);
_closed = true;
disconnect();
return;
}
_thread = Thread.currentThread();
Buffer buffer = new Buffer(_remoteMaxPacketSize);
Packet packet = new Packet(buffer);
int i = 0;
try {
while( _thread != null && _io != null && _io.in != null ) {
if( (i = _io.in.read(buffer.buffer, 14, buffer.buffer.length - 14 - (32 - 20 /* padding and mac */))) <= 0 ) {
eof();
break;
} else if( _closed ) {
break;
}
packet.reset();
buffer.putByte(SSH_MSG_CHANNEL_DATA);
buffer.putInt(_recipient);
buffer.putInt(i);
buffer.skip(i);
_session.write(packet, this, i);
}
} catch (Exception e) {
/* Ignore error, don't bubble exception. */
JSch.getLogger().log(Level.WARN, "Failed to run channel X11", e);
} finally {
disconnect(); // Always disconnect at end
}
}
private byte[] addCache(byte[] buffer, int offset, int length) {
byte[] temp = new byte[_cache.length + length];
System.arraycopy(buffer, offset, temp, _cache.length, length);
if( _cache.length > 0 ) {
System.arraycopy(_cache, 0, temp, 0, _cache.length);
}
_cache = temp;
return _cache;
}
@Override
void write(byte[] buffer, int offset, int length) throws IOException {
if( _init ) {
buffer = addCache(buffer, offset, length);
offset = 0;
length = buffer.length;
if( length < 9 ) {
return;
}
int plen = (buffer[offset + 6] & 0xff) * 256 + (buffer[offset + 7] & 0xff);
int dlen = (buffer[offset + 8] & 0xff) * 256 + (buffer[offset + 9] & 0xff);
if( (buffer[offset] & 0xff) == 0x42 ) {
// TODO ???
} else if( (buffer[offset] & 0xff) == 0x6c ) {
plen = ((plen >>> 8) & 0xff) | ((plen << 8) & 0xff00);
dlen = ((dlen >>> 8) & 0xff) | ((dlen << 8) & 0xff00);
} else {
// TODO ???
}
if( length < 12 + plen + ((-plen) & 3) + dlen ) {
return;
}
byte[] temp = new byte[dlen];
System.arraycopy(buffer, offset + 12 + plen + ((-plen) & 3), temp, 0, dlen);
byte[] faked_cookie = null;
synchronized( FAKED_COOKIE_POOL ) {
faked_cookie = FAKED_COOKIE_POOL.get(_session);
}
if( Arrays.equals(temp, faked_cookie) ) {
if( $cookie != null ) {
System.arraycopy($cookie, 0, buffer, offset + 12 + plen + ((-plen) & 3), dlen);
}
} else {
_thread = null;
eof();
_io.close();
disconnect();
}
_init = false;
_io.put(buffer, offset, length);
_cache = null;
return;
}
_io.put(buffer, offset, length);
}
private static Random getRandom() {
if( $random == null ) {
try {
$random = AlgorithmManager.getManager().createAlgorithm(Algorithms.RANDOM);
} catch(Exception e) {
throw new IllegalStateException("Failed to create Random instance", e);
}
}
return $random;
}
}
| 33.89426 | 114 | 0.688208 |
af81ecd1d5899046b133fad25af5bc06257eae53 | 2,109 | package analysis.typeinfo;
import analysis.typeinfo.nonPrimativeTypes.*;
/**
*.
* SpecialType class provides static members which are
* implementation of Type class
*
* @author rezae, ahmad hussein
*
* @see Type We have three special type: Null
* @see Null Undefined
* @see UNDEFINED Empty
* @see EMPTY
*/
public abstract class SpecialType {
/**
*.
* Null type represent null in program */
public static final Type NULL =
new Type() {
@Override
public boolean isSubtypeOf(Type other) {
return other == this
|| other instanceof ArrayType
|| other instanceof ClassType
|| other == EMPTY;
}
@Override
public String toString() {
return "null";
}
};
/**
*
* Undefined type represent types which are not supported
* by our current NQJ grammer */
public static final Type UNDEFINED =
new Type() {
@Override
public boolean isSubtypeOf(Type other) {
return false;
}
@Override
public String toString() {
return "undefined type";
}
};
/**
*.
* Empty type does not represent any type but it is a
* placeholder which will be used when Analyser find a
* type error Then analyzer will register an error and to
* continue with analyzing process, it will use Empty type.
* for a typical use case
*
* @see ExprChecker #case_FunctionCall()
*/
public static final Type EMPTY =
new Type() {
@Override
public boolean isSubtypeOf(Type other) {
return true;
}
@Override
public String toString() {
return "empty";
}
};
}
| 26.037037 | 68 | 0.485538 |
5d385ff8019d79e5a8953dea07c670728b21f95f | 2,139 | package ru.ingvord.http2.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.sse.OutboundSseEvent;
import javax.ws.rs.sse.Sse;
import javax.ws.rs.sse.SseBroadcaster;
import javax.ws.rs.sse.SseEventSink;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Igor Khokhriakov <[email protected]>
* @since 11/5/18
*/
@Path("/multi-event")
public class MultiEventSource {
private Sse sse;
private SseBroadcaster sseBroadcaster;
@Context
public void setSse(Sse sse) {
this.sse = sse;
// this.eventBuilder = sse.newEventBuilder();
this.sseBroadcaster = sse.newBroadcaster();
exec.submit(new Runnable() {
Random random = new Random();
@Override
public void run() {
try {
do{
Thread.sleep(1);
OutboundSseEvent event = sse.newEventBuilder().
id("EventId").
name(String.valueOf(random.nextInt(500))).
data(Math.random()).
reconnectDelay(10000).
comment("Anything i wanna comment here!").
build();
sseBroadcaster.broadcast(event);
} while(!Thread.currentThread().isInterrupted());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
}
private final ExecutorService exec = Executors.newSingleThreadExecutor();
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void get(@Context SseEventSink sink){
sseBroadcaster.register(sink);
}
@GET
@Path("/{id}")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void getSingle(@Context SseEventSink sink){
sseBroadcaster.register(sink);
}
}
| 28.52 | 77 | 0.570827 |
f67a2680096ec985f222af68e503ea3573817589 | 1,319 | package se.magnus.api.composite.product;
import java.util.List;
public class ProductAggregate {
private final int productId;
private final String name;
private final int weight;
private final List<RecommendationSummary> recommendations;
private final List<ReviewSummary> reviews;
private final ServiceAddresses serviceAddresses;
public ProductAggregate(
int productId,
String name,
int weight,
List<RecommendationSummary> recommendations,
List<ReviewSummary> reviews,
ServiceAddresses serviceAddresses) {
this.productId = productId;
this.name = name;
this.weight = weight;
this.recommendations = recommendations;
this.reviews = reviews;
this.serviceAddresses = serviceAddresses;
}
public int getProductId() {
return productId;
}
public String getName() {
return name;
}
public int getWeight() {
return weight;
}
public List<RecommendationSummary> getRecommendations() {
return recommendations;
}
public List<ReviewSummary> getReviews() {
return reviews;
}
public ServiceAddresses getServiceAddresses() {
return serviceAddresses;
}
}
| 24.886792 | 63 | 0.636088 |
b01029e553de6d3d80e733c78906b8237f47c08e | 14,269 | /* */ package me.ninethousand.ninehack.feature.features.client;
/* */
/* */ import java.awt.Color;
/* */ import java.util.Objects;
/* */ import me.ninethousand.ninehack.NineHack;
/* */ import me.ninethousand.ninehack.event.events.Render2DEvent;
/* */ import me.ninethousand.ninehack.feature.Category;
/* */ import me.ninethousand.ninehack.feature.Feature;
/* */ import me.ninethousand.ninehack.feature.annotation.NineHackFeature;
/* */ import me.ninethousand.ninehack.feature.setting.NumberSetting;
/* */ import me.ninethousand.ninehack.feature.setting.Setting;
/* */ import me.ninethousand.ninehack.mixin.accessors.game.IMinecraft;
/* */ import me.ninethousand.ninehack.util.ColorUtil;
/* */ import me.ninethousand.ninehack.util.RenderUtil;
/* */ import net.minecraft.client.gui.ScaledResolution;
/* */ import net.minecraft.client.multiplayer.ServerData;
/* */ import net.minecraft.client.renderer.GlStateManager;
/* */ import net.minecraft.init.Items;
/* */ import net.minecraft.item.ItemStack;
/* */ import net.minecraft.util.text.TextFormatting;
/* */
/* */ @NineHackFeature(name = "HUD", description = "Based HUD", category = Category.Client)
/* */ public class HUD
/* */ extends Feature {
/* */ public static Feature INSTANCE;
/* 26 */ private static ScaledResolution res = new ScaledResolution(mc);
/* 27 */ private static final ItemStack totem = new ItemStack(Items.field_190929_cY);
/* */
/* 29 */ public static final Setting<Boolean> rainbow = new Setting("Rainbow", Boolean.valueOf(true));
/* 30 */ public static final Setting<Boolean> rolling = new Setting("Rolling", Boolean.valueOf(true));
/* 31 */ public static final NumberSetting<Integer> factor = new NumberSetting("Rolling Factor", Integer.valueOf(0), Integer.valueOf(10), Integer.valueOf(100), 1);
/* 32 */ public static final NumberSetting<Integer> hue = new NumberSetting("Hue", Integer.valueOf(0), Integer.valueOf(255), Integer.valueOf(255), 1);
/* 33 */ public static final NumberSetting<Integer> saturation = new NumberSetting("Saturation", Integer.valueOf(0), Integer.valueOf(255), Integer.valueOf(255), 1);
/* 34 */ public static final NumberSetting<Integer> brightness = new NumberSetting("Brightness", Integer.valueOf(0), Integer.valueOf(255), Integer.valueOf(255), 1);
/* */
/* 36 */ public static final Setting<Boolean> watermark = new Setting("Watermark", Boolean.valueOf(true));
/* 37 */ public static final Setting<WatermarkMode> watermarkMode = new Setting("Watermark Mode", WatermarkMode.Default);
/* 38 */ public static final NumberSetting<Integer> watermarkX = new NumberSetting("Watermark X", Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(960), 1);
/* 39 */ public static final NumberSetting<Integer> watermarkY = new NumberSetting("Watermark Y", Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(530), 1);
/* */
/* 41 */ public static final Setting<Boolean> ping = new Setting("Ping", Boolean.valueOf(true));
/* 42 */ public static final NumberSetting<Integer> pingX = new NumberSetting("Ping X", Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(960), 1);
/* 43 */ public static final NumberSetting<Integer> pingY = new NumberSetting("Ping Y", Integer.valueOf(1), Integer.valueOf(10), Integer.valueOf(530), 1);
/* */
/* 45 */ public static final Setting<Boolean> welcomer = new Setting("Welcomer", Boolean.valueOf(true));
/* 46 */ public static final Setting<WelcomeMode> welcomerMode = new Setting("Welcomer Mode", WelcomeMode.Default);
/* 47 */ public static final NumberSetting<Integer> welcomerX = new NumberSetting("Welcomer X", Integer.valueOf(1), Integer.valueOf(480), Integer.valueOf(960), 1);
/* 48 */ public static final NumberSetting<Integer> welcomerY = new NumberSetting("Welcomer Y", Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(530), 1);
/* */
/* 50 */ public static final Setting<Boolean> coords = new Setting("Coords", Boolean.valueOf(true));
/* 51 */ public static final NumberSetting<Integer> coordX = new NumberSetting("Coords X", Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(960), 1);
/* 52 */ public static final NumberSetting<Integer> coordY = new NumberSetting("Coords Y", Integer.valueOf(1), Integer.valueOf(530), Integer.valueOf(530), 1);
/* */
/* 54 */ public static final Setting<Boolean> totems = new Setting("Totem", Boolean.valueOf(true));
/* */
/* 56 */ public static final Setting<Boolean> armor = new Setting("Armor", Boolean.valueOf(true));
/* 57 */ public static final Setting<Boolean> percent = new Setting("Armor %", Boolean.valueOf(true));
/* */
/* */ public HUD() {
/* 60 */ addSettings(new Setting[] { rainbow, rolling, (Setting)factor, (Setting)hue, (Setting)saturation, (Setting)brightness, watermark, watermarkMode, (Setting)watermarkX, (Setting)watermarkY, ping, (Setting)pingX, (Setting)pingY, welcomer, welcomerMode, (Setting)welcomerX, (Setting)welcomerY, coords, (Setting)coordX, (Setting)coordY, totems, armor, percent });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void onUpdate() {
/* 89 */ if (((Boolean)rainbow.getValue()).booleanValue()) {
/* 90 */ if (((Integer)hue.getValue()).intValue() < 255) {
/* 91 */ hue.setValue(Integer.valueOf(((Integer)hue.getValue()).intValue() + 1));
/* */ } else {
/* */
/* 94 */ hue.setValue(Integer.valueOf(0));
/* */ }
/* */ }
/* */ }
/* */
/* */
/* */ public void on2DRenderEvent(Render2DEvent event) {
/* 101 */ if (((Boolean)watermark.getValue()).booleanValue()) drawWatermark(((Integer)watermarkX.getValue()).intValue(), ((Integer)watermarkY.getValue()).intValue());
/* 102 */ if (((Boolean)ping.getValue()).booleanValue()) drawPing(((Integer)pingX.getValue()).intValue(), ((Integer)pingY.getValue()).intValue());
/* 103 */ if (((Boolean)welcomer.getValue()).booleanValue()) drawWelcomer(((Integer)welcomerX.getValue()).intValue(), ((Integer)welcomerY.getValue()).intValue());
/* 104 */ if (((Boolean)coords.getValue()).booleanValue()) drawCoords(((Integer)coordX.getValue()).intValue(), ((Integer)coordY.getValue()).intValue());
/* 105 */ if (((Boolean)totems.getValue()).booleanValue()) drawTotem();
/* 106 */ if (((Boolean)armor.getValue()).booleanValue()) drawArmor(((Boolean)percent.getValue()).booleanValue());
/* */
/* */ }
/* */
/* */
/* */ public void drawWatermark(int x, int y) {
/* 112 */ String watermark = "Ninehack";
/* */
/* 114 */ if (watermarkMode.getValue() == WatermarkMode.Default) {
/* 115 */ watermark = "NineHack v1.0.1";
/* */ }
/* 117 */ else if (watermarkMode.getValue() == WatermarkMode.Tesco) {
/* 118 */ if (((IMinecraft)mc).getIntegratedServerIsRunning()) {
/* 119 */ watermark = "NineHack v1.0.1 : " + mc.field_71439_g.func_70005_c_() + " : Singleplayer";
/* */ } else {
/* */
/* 122 */ watermark = "NineHack v1.0.1 : " + mc.field_71439_g.func_70005_c_() + " : " + ((ServerData)Objects.requireNonNull((T)mc.func_147104_D())).field_78845_b;
/* */ }
/* */ }
/* */
/* 126 */ drawText(watermark, x, y);
/* */ }
/* */
/* */ public void drawPing(int x, int y) {
/* 130 */ String text = "Ping " + TextFormatting.WHITE + (!mc.func_71356_B() ? mc.func_147114_u().func_175102_a(mc.field_71439_g.func_110124_au()).func_178853_c() : -1) + " ms";
/* 131 */ drawText(text, x, y);
/* */ }
/* */
/* */ public void drawWelcomer(int x, int y) {
/* 135 */ String text = "Hello";
/* */
/* 137 */ switch ((WelcomeMode)welcomerMode.getValue()) {
/* */ case Default:
/* 139 */ text = "Welcome, " + mc.field_71439_g.func_70005_c_() + " :^)";
/* */ break;
/* */ }
/* 142 */ drawText(text, x, y);
/* */ }
/* */
/* */ public void drawCoords(int x, int y) {
/* 146 */ boolean inHell = mc.field_71441_e.func_180494_b(mc.field_71439_g.func_180425_c()).func_185359_l().equals("Hell");
/* 147 */ int posX = (int)mc.field_71439_g.field_70165_t;
/* 148 */ int posY = (int)mc.field_71439_g.field_70163_u;
/* 149 */ int posZ = (int)mc.field_71439_g.field_70161_v;
/* 150 */ float nether = inHell ? 8.0F : 0.125F;
/* 151 */ int hposX = (int)(mc.field_71439_g.field_70165_t * nether);
/* 152 */ int hposZ = (int)(mc.field_71439_g.field_70161_v * nether);
/* */
/* 154 */ String coordinates = "XYZ " + posX + ", " + posY + ", " + posZ + " [" + hposX + ", " + hposZ + "]";
/* */
/* 156 */ drawText(coordinates, x, y);
/* */ }
/* */
/* */ public void drawText(String text, int x, int y) {
/* 160 */ if (((Boolean)rolling.getValue()).booleanValue()) { NineHack.TEXT_MANAGER.drawRainbowString(text, x, y, Color.HSBtoRGB(((Integer)hue.getValue()).intValue() / 255.0F, ((Integer)saturation.getValue()).intValue() / 255.0F, ((Integer)brightness.getValue()).intValue() / 255.0F), ((Integer)factor.getValue()).intValue(), ((Boolean)CustomFont.shadow.getValue()).booleanValue()); }
/* 161 */ else { NineHack.TEXT_MANAGER.drawStringWithShadow(text, x, y, Color.HSBtoRGB(((Integer)hue.getValue()).intValue() / 255.0F, ((Integer)saturation.getValue()).intValue() / 255.0F, ((Integer)brightness.getValue()).intValue() / 255.0F)); }
/* */
/* */ }
/* */ public void drawTotem() {
/* 165 */ int width = NineHack.TEXT_MANAGER.scaledWidth;
/* 166 */ int height = NineHack.TEXT_MANAGER.scaledHeight;
/* 167 */ int totems = mc.field_71439_g.field_71071_by.field_70462_a.stream().filter(itemStack -> (itemStack.func_77973_b() == Items.field_190929_cY)).mapToInt(ItemStack::func_190916_E).sum();
/* 168 */ if (mc.field_71439_g.func_184592_cb().func_77973_b() == Items.field_190929_cY) {
/* 169 */ totems += mc.field_71439_g.func_184592_cb().func_190916_E();
/* */ }
/* 171 */ if (totems > 0) {
/* 172 */ GlStateManager.func_179098_w();
/* 173 */ int i = width / 2;
/* 174 */ int iteration = 0;
/* 175 */ int y = height - 55 - ((mc.field_71439_g.func_70090_H() && mc.field_71442_b.func_78763_f()) ? 10 : 0);
/* 176 */ int x = i - 189 + 180 + 2;
/* 177 */ GlStateManager.func_179126_j();
/* 178 */ RenderUtil.itemRender.field_77023_b = 200.0F;
/* 179 */ RenderUtil.itemRender.func_180450_b(totem, x, y);
/* 180 */ RenderUtil.itemRender.func_180453_a(mc.field_71466_p, totem, x, y, "");
/* 181 */ RenderUtil.itemRender.field_77023_b = 0.0F;
/* 182 */ GlStateManager.func_179098_w();
/* 183 */ GlStateManager.func_179140_f();
/* 184 */ GlStateManager.func_179097_i();
/* 185 */ drawText(totems + "", x + 19 - NineHack.TEXT_MANAGER.getStringWidth(totems + ""), y + 9);
/* 186 */ GlStateManager.func_179126_j();
/* 187 */ GlStateManager.func_179140_f();
/* */ }
/* */ }
/* */
/* */ public void drawArmor(boolean percent) {
/* 192 */ int width = NineHack.TEXT_MANAGER.scaledWidth;
/* 193 */ int height = NineHack.TEXT_MANAGER.scaledHeight;
/* 194 */ GlStateManager.func_179098_w();
/* 195 */ int i = width / 2;
/* 196 */ int iteration = 0;
/* 197 */ int y = height - 55 - ((mc.field_71439_g.func_70090_H() && mc.field_71442_b.func_78763_f()) ? 10 : 0);
/* 198 */ for (ItemStack is : mc.field_71439_g.field_71071_by.field_70460_b) {
/* 199 */ iteration++;
/* 200 */ if (is.func_190926_b()) {
/* */ continue;
/* */ }
/* 203 */ int x = i - 90 + (9 - iteration) * 20 + 2;
/* 204 */ GlStateManager.func_179126_j();
/* 205 */ RenderUtil.itemRender.field_77023_b = 200.0F;
/* 206 */ RenderUtil.itemRender.func_180450_b(is, x, y);
/* 207 */ RenderUtil.itemRender.func_180453_a(mc.field_71466_p, is, x, y, "");
/* 208 */ RenderUtil.itemRender.field_77023_b = 0.0F;
/* 209 */ GlStateManager.func_179098_w();
/* 210 */ GlStateManager.func_179140_f();
/* 211 */ GlStateManager.func_179097_i();
/* 212 */ String s = (is.func_190916_E() > 1) ? (is.func_190916_E() + "") : "";
/* 213 */ NineHack.TEXT_MANAGER.drawStringWithShadow(s, (x + 19 - 2 - NineHack.TEXT_MANAGER.getStringWidth(s)), (y + 9), 16777215);
/* 214 */ if (!percent) {
/* */ continue;
/* */ }
/* 217 */ int dmg = 0;
/* 218 */ int itemDurability = is.func_77958_k() - is.func_77952_i();
/* 219 */ float green = (is.func_77958_k() - is.func_77952_i()) / is.func_77958_k();
/* 220 */ float red = 1.0F - green;
/* 221 */ if (percent) {
/* 222 */ dmg = 100 - (int)(red * 100.0F);
/* */ } else {
/* 224 */ dmg = itemDurability;
/* */ }
/* 226 */ NineHack.TEXT_MANAGER.drawStringWithShadow(dmg + "", (x + 8 - NineHack.TEXT_MANAGER.getStringWidth(dmg + "") / 2), (y - 11), ColorUtil.toRGBA((int)(red * 255.0F), (int)(green * 255.0F), 0));
/* */ }
/* 228 */ GlStateManager.func_179126_j();
/* 229 */ GlStateManager.func_179140_f();
/* */ }
/* */
/* */ public enum WatermarkMode {
/* 233 */ Default,
/* 234 */ Tesco;
/* */ }
/* */
/* */ public enum WelcomeMode {
/* 238 */ Default;
/* */ }
/* */ }
/* Location: C:\Users\tarka\Downloads\ninehack-1.0.1-release.jar!\me\ninethousand\ninehack\feature\features\client\HUD.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | 58.004065 | 389 | 0.590721 |
2ceacb908f505b09b51c645fd8a62e64c8008d95 | 288 | package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
@Autonomous(name="RED: KBEMC2 Auto", group="KBEMC2")
public class AutoRed extends Auto {
@Override
protected Utilities.Side getSide() {
return Utilities.Side.RED;
}
}
| 24 | 58 | 0.732639 |
22892942e50658f4b2d1ab1f1b2880f8551ebc0f | 2,541 | package us.innodea.aws.springboot.crud.filter;
import com.amazonaws.serverless.proxy.RequestReader;
import com.amazonaws.serverless.proxy.model.AwsProxyRequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
/**
* Simple Filter implementation that looks for a Cognito identity id in the API Gateway request context
* and stores the value in a request attribute. The filter is registered with aws-serverless-java-container
* in the onStartup method from the {com.amazonaws.serverless.sample.spring.StreamLambdaHandler} class.
*/
public class CognitoIdentityFilter implements Filter {
public static final String COGNITO_IDENTITY_ATTRIBUTE = "com.amazonaws.serverless.cognitoId";
private static Logger log = LoggerFactory.getLogger(CognitoIdentityFilter.class);
@Override
public void init(FilterConfig filterConfig) {
// nothing to do in init
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
Object apiGwContext = servletRequest.getAttribute(RequestReader.API_GATEWAY_CONTEXT_PROPERTY);
if (apiGwContext == null) {
log.warn("API Gateway context is null");
filterChain.doFilter(servletRequest, servletResponse);
}
if (!AwsProxyRequestContext.class.isAssignableFrom(apiGwContext.getClass())) {
log.warn("API Gateway context object is not of valid type");
filterChain.doFilter(servletRequest, servletResponse);
}
AwsProxyRequestContext ctx = (AwsProxyRequestContext)apiGwContext;
if (ctx.getIdentity() == null) {
log.warn("Identity context is null");
filterChain.doFilter(servletRequest, servletResponse);
}
String cognitoIdentityId = ctx.getIdentity().getCognitoIdentityId();
if (cognitoIdentityId == null || "".equals(cognitoIdentityId.trim())) {
log.warn("Cognito identity id in request is null");
}
servletRequest.setAttribute(COGNITO_IDENTITY_ATTRIBUTE, cognitoIdentityId);
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
// nothing to do in destroy
}
} | 38.5 | 113 | 0.730815 |
b71dc74a99c3f1d8f64784bf555f8a232e8979f7 | 2,866 | /*
* Zyonic Software - 2020 - Tobias Rempe
* This File, its contents and by extention the corresponding project may be used freely in compliance with the Apache 2.0 License.
*
* [email protected]
*/
package com.zyonicsoftware.maddox.core.engine.handling.privatemessage;
import com.zyonicsoftware.maddox.core.main.Maddox;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.PrivateChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent;
import java.util.ArrayList;
import java.util.Arrays;
public class PrivateMessageCommandEvent {
private final PrivateMessageReceivedEvent event;
private final PrivateMessageCommand command;
private final Maddox maddox;
public PrivateMessageCommandEvent(final PrivateMessageCommand command, final PrivateMessageReceivedEvent event, final Maddox maddox) {
this.event = event;
this.command = command;
this.maddox = maddox;
}
public PrivateMessageCommand getCommand() {
return this.command;
}
public PrivateMessageReceivedEvent getEvent() {
return this.event;
}
public User getAuthor() {
return this.event.getAuthor();
}
public PrivateChannel getChannel() {
return this.event.getChannel();
}
public Message getMessage() {
return this.event.getMessage();
}
public JDA getJDA() {
return this.event.getJDA();
}
public void reply(final String pMessage) {
this.getChannel().sendMessage(pMessage).queue();
}
public void reply(final MessageEmbed messageEmbed) {
this.getChannel().sendMessage(messageEmbed).queue();
}
public Message returnReply(final String pMessage) {
return this.getChannel().sendMessage(pMessage).complete();
}
public Message returnReply(final MessageEmbed messageEmbed) {
return this.getChannel().sendMessage(messageEmbed).complete();
}
public ArrayList<String> getArguments() {
String arguments;
arguments = this.event.getMessage().getContentRaw().substring(this.command.getName().length() + this.maddox.getDefaultPrefix().length());
if (this.event.getMessage().getContentRaw().startsWith(this.maddox.getDefaultPrefix() + " ")) {
arguments = this.event.getMessage().getContentRaw().substring(this.command.getName().length() + this.maddox.getDefaultPrefix().length() + 1);
}
if (arguments.length() > 0) {
arguments = arguments.substring(1);
final String[] args = arguments.split(" ");
return (ArrayList<String>) Arrays.asList(args);
} else {
return new ArrayList<>();
}
}
}
| 31.494505 | 153 | 0.690509 |
47da4d98c243c7e3df9fe953659188a5edb1d273 | 361 | package ca.utils.web.exceptions.headers;
/** The exception throws if the key of the header is null or empty. */
public class KeyHeaderNullException extends Exception {
/** Initialize a new instance of {@link KeyHeaderNullException} is null or empty. */
public KeyHeaderNullException(){
super("A header's key can't be null or empty.");
}
}
| 36.1 | 89 | 0.711911 |
a8aa409895e64101d84b7eae4719242f65872b9e | 3,610 | /**
*/
package IFML.Core.impl;
import IFML.Core.CorePackage;
import IFML.Core.UMLDomainConcept;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.uml2.uml.Classifier;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>UML Domain Concept</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link IFML.Core.impl.UMLDomainConceptImpl#getClassifier <em>Classifier</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class UMLDomainConceptImpl extends DomainConceptImpl implements UMLDomainConcept {
/**
* The cached value of the '{@link #getClassifier() <em>Classifier</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getClassifier()
* @generated
* @ordered
*/
protected Classifier classifier;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected UMLDomainConceptImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return CorePackage.Literals.UML_DOMAIN_CONCEPT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Classifier getClassifier() {
if (classifier != null && classifier.eIsProxy()) {
InternalEObject oldClassifier = (InternalEObject)classifier;
classifier = (Classifier)eResolveProxy(oldClassifier);
if (classifier != oldClassifier) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, CorePackage.UML_DOMAIN_CONCEPT__CLASSIFIER, oldClassifier, classifier));
}
}
return classifier;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Classifier basicGetClassifier() {
return classifier;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setClassifier(Classifier newClassifier) {
Classifier oldClassifier = classifier;
classifier = newClassifier;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CorePackage.UML_DOMAIN_CONCEPT__CLASSIFIER, oldClassifier, classifier));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case CorePackage.UML_DOMAIN_CONCEPT__CLASSIFIER:
if (resolve) return getClassifier();
return basicGetClassifier();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case CorePackage.UML_DOMAIN_CONCEPT__CLASSIFIER:
setClassifier((Classifier)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case CorePackage.UML_DOMAIN_CONCEPT__CLASSIFIER:
setClassifier((Classifier)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case CorePackage.UML_DOMAIN_CONCEPT__CLASSIFIER:
return classifier != null;
}
return super.eIsSet(featureID);
}
} //UMLDomainConceptImpl
| 22.993631 | 135 | 0.663712 |
9b6b08f72d5e6ab986b6ae6e8acf8caae56b03de | 2,265 | package com.ruoyi.web.controller.system;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.MinioUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
@RestController
@RequestMapping("/system/minio")
public class MInioController {
@Autowired
MinioUtil minioUtil;
@ApiOperation("上传一个文件")
@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
@ResponseBody
public AjaxResult fileupload(@RequestParam MultipartFile file) throws Exception { //, @RequestParam String bucket, @RequestParam(required=false) String objectName
String fileName = file.getName() ;
String bucket = "ruoyi-plan" ;
String url = "" ;
minioUtil.createBucket(bucket);
if (fileName != null) {
url = minioUtil.uploadFile(file.getInputStream(), bucket, fileName+"/"+file.getOriginalFilename());
} else {
url = minioUtil.uploadFile(file.getInputStream(), bucket, file.getOriginalFilename());
}
AjaxResult ajax = AjaxResult.success() ;
ajax.put("url", url);
ajax.put("fileName", fileName);
return ajax;
}
@ApiOperation("下载一个文件")
@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
@ResponseBody
public void downloadFile(@RequestParam String bucket, @RequestParam String objectName,
HttpServletResponse response) throws Exception {
InputStream stream = minioUtil.download(bucket, objectName);
ServletOutputStream output = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectName.substring(objectName.lastIndexOf("/") + 1), "UTF-8"));
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
IOUtils.copy(stream, output);
}
}
| 38.389831 | 173 | 0.707726 |
4588e90af04255b662b0bfa75228ae7ea63cf235 | 2,617 | /*
* Copyright (c) 2012-2017 ZoxWeb.com LLC.
*
* 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 io.xlogistx.shared.data;
import org.zoxweb.shared.accounting.AmountDAO;
import org.zoxweb.shared.data.SetNameDescriptionDAO;
import org.zoxweb.shared.util.*;
@SuppressWarnings("serial")
public class OrderItemDAO
extends SetNameDescriptionDAO {
public enum Param
implements GetNVConfig {
ITEM(NVConfigManager.createNVConfigEntity("item", "Item", "Item", true, true, ItemDAO.class,
NVConfigEntity.ArrayType.NOT_ARRAY)),
QUANTITY(
NVConfigManager.createNVConfig("quantity", "Quantity", "Quantity", true, true, int.class)),
TOTAL(NVConfigManager
.createNVConfigEntity("total", "Total", "Total", true, true, AmountDAO.class,
NVConfigEntity.ArrayType.NOT_ARRAY)),
;
private final NVConfig nvc;
Param(NVConfig nvc) {
this.nvc = nvc;
}
@Override
public NVConfig getNVConfig() {
return nvc;
}
}
public static final NVConfigEntity NVC_ORDER_ITEM_DAO = new NVConfigEntityLocal(
"order_item_dao",
null,
OrderItemDAO.class.getSimpleName(),
true,
false,
false,
false,
OrderItemDAO.class,
SharedUtil.extractNVConfigs(Param.values()),
null,
false,
SetNameDescriptionDAO.NVC_NAME_DESCRIPTION_DAO
);
public OrderItemDAO() {
super(NVC_ORDER_ITEM_DAO);
}
/**
* Returns the item.
*/
public ItemDAO getItem() {
return lookupValue(Param.ITEM);
}
/**
* Sets the item.
*/
public void setItem(ItemDAO item) {
setValue(Param.ITEM, item);
}
/**
* Returns the quantity.
*/
public int getQuantity() {
return lookupValue(Param.QUANTITY);
}
/**
* Sets the quantity.
*/
public void setQuantity(int quantity) {
setValue(Param.QUANTITY, quantity);
}
/**
* Returns the total.
*/
public AmountDAO getTotal() {
return lookupValue(Param.TOTAL);
}
/**
* Sets the total.
*/
public void setTotal(AmountDAO total) {
setValue(Param.TOTAL, total);
}
} | 23.366071 | 99 | 0.670997 |
7f063f2363440245fadde472510e86ef7dd91ce7 | 2,118 | /*
* 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.aliyuncs.linkedmall.transform.v20180116;
import com.aliyuncs.linkedmall.model.v20180116.ValidateTaobaoAccountResponse;
import com.aliyuncs.linkedmall.model.v20180116.ValidateTaobaoAccountResponse.Model;
import com.aliyuncs.transform.UnmarshallerContext;
public class ValidateTaobaoAccountResponseUnmarshaller {
public static ValidateTaobaoAccountResponse unmarshall(ValidateTaobaoAccountResponse validateTaobaoAccountResponse, UnmarshallerContext context) {
validateTaobaoAccountResponse.setRequestId(context.stringValue("ValidateTaobaoAccountResponse.RequestId"));
validateTaobaoAccountResponse.setCode(context.stringValue("ValidateTaobaoAccountResponse.Code"));
validateTaobaoAccountResponse.setMessage(context.stringValue("ValidateTaobaoAccountResponse.Message"));
validateTaobaoAccountResponse.setSubCode(context.stringValue("ValidateTaobaoAccountResponse.SubCode"));
validateTaobaoAccountResponse.setSubMessage(context.stringValue("ValidateTaobaoAccountResponse.SubMessage"));
validateTaobaoAccountResponse.setLogsId(context.stringValue("ValidateTaobaoAccountResponse.LogsId"));
validateTaobaoAccountResponse.setSuccess(context.booleanValue("ValidateTaobaoAccountResponse.Success"));
validateTaobaoAccountResponse.setTotalCount(context.longValue("ValidateTaobaoAccountResponse.TotalCount"));
Model model = new Model();
model.setMatch(context.booleanValue("ValidateTaobaoAccountResponse.Model.Match"));
validateTaobaoAccountResponse.setModel(model);
return validateTaobaoAccountResponse;
}
} | 51.658537 | 147 | 0.829084 |
011330f67df1ca4a992f4eecbbca29ba8ab695db | 928 | package com.zte.mao.common.service;
import java.util.List;
import com.zte.mao.common.entity.UserEntity;
public interface UserService {
/**
* 添加用户
* @param user
*/
void add(UserEntity user) throws Exception;
/**
* 更新租户用户
* @param user
*/
void update(UserEntity user) throws Exception;
/**
* 删除租户
* @param tenantId
* @param login_name
*/
void delete(String tenantId,String login_name) throws Exception;
/**
* 查询租户用户
* @param tenantId 租户id
* @param login_name 登录名称
* @return
*/
List<UserEntity> getUsers(String tenantId,String login_name)throws Exception;
/**
* 判断租户用户是否存在
* @param tenantId
* @param login_name
* @return
* @throws Exception
*/
boolean isUserExist(String tenantId,String login_name)throws Exception;
}
| 21.090909 | 82 | 0.578664 |
57113a18702bc266ff2b2f852b81895adad5770c | 2,953 | package com.adaptris.kubernetes.metrics.prometheus;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryExp;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.adaptris.core.interceptor.MessageMetricsStatistics;
import com.adaptris.core.interceptor.MessageMetricsStatisticsMBean;
import com.adaptris.core.interceptor.MessageStatistic;
public class JmxMessageMetricsCollectorTest {
private JmxMessageMetricsCollector collector;
@Mock private MBeanServer mockMBeanServer;
private Set<ObjectInstance> objectSet;
@Mock private ObjectInstance mockObjectInstance;
@Mock private ObjectName mockObjectName;
private ObjectName realObjectName;
@Mock private MessageMetricsStatisticsMBean mockMMSMBean;
private List<MessageStatistic> messagesStatisticsList;
@Mock MessageMetricsListener mockListener;
private AutoCloseable closeable;
@BeforeEach
public void setUp() throws Exception {
closeable = MockitoAnnotations.openMocks(this);
collector = new JmxMessageMetricsCollector();
collector.setInterlokMBeanServer(mockMBeanServer);
objectSet = new HashSet<>();
objectSet.add(mockObjectInstance);
realObjectName = new ObjectName("com.adaptris:type=Metrics,adapter=adapter,channel=channel,workflow=workflow");
messagesStatisticsList = new ArrayList<>();
when(mockMBeanServer.queryMBeans(any(ObjectName.class), any(QueryExp.class)))
.thenReturn(objectSet);
when(mockMMSMBean.getStatistics())
.thenReturn(messagesStatisticsList);
}
@AfterEach
public void tearDown() throws Exception {
closeable.close();
}
@Test
public void testMBeansLoadedFirstExecution() {
when(mockObjectInstance.getClassName()).thenReturn(MessageMetricsStatistics.class.getName());
when(mockObjectInstance.getObjectName()).thenReturn(mockObjectName);
try {
collector.run();
} catch (Throwable t) {};
verify(mockMBeanServer).queryMBeans(any(ObjectName.class), isNull());
}
@Test
public void testNotifyNewStats() throws Exception {
Map<ObjectName, MessageMetricsStatisticsMBean> mbeans = new HashMap<>();
mbeans.put(realObjectName, mockMMSMBean);
collector.registerListener(mockListener);
collector.setMetricsMBeans(mbeans);
collector.run();
collector.deregisterListener(mockListener);
Thread.sleep(500);
verify(mockListener).notifyMessageMetrics(any());
}
}
| 27.342593 | 115 | 0.781917 |
95ee566e0648082495cb2fab5e3fdcaab2d0bd4c | 187 | package cs652.j.codegen.model;
/**
* Created by tuo on 01/04/17.
*/
public class PrimitiveType extends Type {
public PrimitiveType(String name)
{
super(name);
}
}
| 14.384615 | 41 | 0.631016 |
de1526ea7a98616ee6a49643c2c441ac6b764c2f | 553 | package com.github.rstockbridge.showstats.database;
import androidx.annotation.NonNull;
public final class ShowNote {
@NonNull
private final String id;
@NonNull
private String text;
ShowNote(@NonNull final String id, @NonNull final String text) {
this.id = id;
this.text = text;
}
@NonNull
public String getId() {
return id;
}
@NonNull
public String getText() {
return text;
}
public void setText(@NonNull final String text) {
this.text = text;
}
}
| 17.28125 | 68 | 0.614828 |
65e9ede88d4c13bde90adbd6bd5af9efae84ae6c | 3,174 | package org.firstinspires.ftc.teamcode.finals;
import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.acmerobotics.roadrunner.geometry.Vector2d;
import com.acmerobotics.roadrunner.trajectory.Trajectory;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import org.firstinspires.ftc.internal.OptimizedRobot;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.internal.roadrunner.drive.SampleMecanumDrive;
@Autonomous(name = "Auto for Scarab match")
public class AutoWithScarabs extends LinearOpMode {
DcMotor duckSpinner, armMotor, intakeMotor, odometryMotor;
OptimizedRobot robot;
ColorSensor colorSensor;
Telemetry.Log log;
@Override
public void runOpMode() throws InterruptedException {
log = telemetry.log();
robot = new OptimizedRobot(telemetry, hardwareMap);
duckSpinner = robot.getMotor("duckSpinner");
armMotor = robot.getMotor("arm", DcMotor.RunMode.RUN_TO_POSITION);
intakeMotor = robot.getMotor("intake");
odometryMotor = robot.getMotor("odometry");
colorSensor = hardwareMap.colorSensor.get("colorSensor");
colorSensor.enableLed(true);
org.firstinspires.ftc.teamcode.internal.roadrunner.drive.SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap);
drive.setPoseEstimate(new Pose2d(-40.5, 63, Math.toRadians(-90)));
Trajectory forwardForDuck = drive.trajectoryBuilder(new Pose2d(-40.5, 63, Math.toRadians(-90)))
.splineTo(new Vector2d(-55.5, 49), Math.toRadians(-90))
.build();
Trajectory reverseForDuck = drive.trajectoryBuilder(forwardForDuck.end())
.back(11)
.build();
Trajectory goToAllianceWobbleFromDuck = drive.trajectoryBuilder(reverseForDuck.end())
.splineTo(new Vector2d(-30, 24), Math.toRadians(0))
.build();
Trajectory backFromWobble = drive.trajectoryBuilder(goToAllianceWobbleFromDuck.end())
.back(12)
.build();
Trajectory toParkZone = drive.trajectoryBuilder(new Pose2d(-42, 24, Math.toRadians(180)))
.splineTo(new Vector2d(-60, 35), Math.toRadians(180))
.build();
waitForStart();
armMotor.setPower(1);
drive.followTrajectory(forwardForDuck);
drive.followTrajectory(reverseForDuck);
duckSpinner.setPower(0.6);
sleep(2500);
duckSpinner.setPower(0);
armMotor.setTargetPosition(-900);
drive.followTrajectory(goToAllianceWobbleFromDuck);
intakeMotor.setPower(0.8);
sleep(3000);
intakeMotor.setPower(0);
armMotor.setTargetPosition(-3200);
intakeMotor.setPower(-1);
drive.followTrajectory(backFromWobble);
drive.turn(Math.toRadians(180));
drive.followTrajectory(toParkZone);
intakeMotor.setPower(0);
armMotor.setTargetPosition(-900);
}
} | 35.266667 | 128 | 0.689351 |
da8ae88adefbb31060b469724277a328d1bf5a47 | 55 | package settings;
public class SettingsEditorTest {
} | 11 | 33 | 0.8 |
Subsets and Splits