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
735548bba66b3fd14f3554cf1c45328d86b8b75f
316
package com.github.cuzfrog.psmm; import com.github.cuzfrog.psmm.PsmmConfiguration; final class NullFactoryPool extends AbstractFactoryPool { NullFactoryPool(PsmmConfiguration config) { super(config); } @Override protected PsmmFactory createOrFetch() { return new PsmmFactoryImpl(); } }
18.588235
58
0.743671
245d6135e90ced174b10a10f61183280fb85b555
530
package com.progetto.OOP.other; /** Rappresenta la superclasse per i calcolatori di statistiche. * @author Lorenzo Benenchia * @author Riccardo Iobbi */ import java.util.ArrayList; import com.progetto.OOP.model.Record; public class StatisticheSuperclasse { protected ArrayList<Record> records; /**Al costruttore gli passiamo il * @param ListaRecord (ArrayList) su cui calcolare la statistica. */ public StatisticheSuperclasse(ArrayList<Record> ListaRecord) { this.records=ListaRecord; } }
24.090909
67
0.735849
5eca7c8f45dd9a910c7fa6026f74775ad7c67a3a
4,149
package org.knowm.xchange.bittrex.dto.marketdata; import com.fasterxml.jackson.annotation.JsonProperty; import java.math.BigDecimal; import java.time.LocalDateTime; public class BittrexV2Summary { private Integer openSellOrders; private LocalDateTime timeStamp; private BigDecimal last; private BigDecimal low; private LocalDateTime created; private BigDecimal prevDay; private Integer openBuyOrders; private BigDecimal volume; private BigDecimal baseVolume; private BigDecimal bid; private BigDecimal ask; private String marketName; private BigDecimal high; public BittrexV2Summary( @JsonProperty("OpenSellOrders") Integer openSellOrders, @JsonProperty("TimeStamp") String timeStamp, @JsonProperty("Last") BigDecimal last, @JsonProperty("Low") BigDecimal low, @JsonProperty("Created") String created, @JsonProperty("PrevDay") BigDecimal prevDay, @JsonProperty("OpenBuyOrders") Integer openBuyOrders, @JsonProperty("Volume") BigDecimal volume, @JsonProperty("BaseVolume") BigDecimal baseVolume, @JsonProperty("Bid") BigDecimal bid, @JsonProperty("Ask") BigDecimal ask, @JsonProperty("MarketName") String marketName, @JsonProperty("High") BigDecimal high) { this.openSellOrders = openSellOrders; this.timeStamp = LocalDateTime.parse(timeStamp); this.last = last; this.low = low; this.created = LocalDateTime.parse(created); this.prevDay = prevDay; this.openBuyOrders = openBuyOrders; this.volume = volume; this.baseVolume = baseVolume; this.bid = bid; this.ask = ask; this.marketName = marketName; this.high = high; } public Integer getOpenSellOrders() { return openSellOrders; } public void setOpenSellOrders(Integer openSellOrders) { this.openSellOrders = openSellOrders; } public LocalDateTime getTimeStamp() { return timeStamp; } public void setTimeStamp(LocalDateTime timeStamp) { this.timeStamp = timeStamp; } public BigDecimal getLast() { return last; } public void setLast(BigDecimal last) { this.last = last; } public BigDecimal getLow() { return low; } public void setLow(BigDecimal low) { this.low = low; } public LocalDateTime getCreated() { return created; } public void setCreated(LocalDateTime created) { this.created = created; } public BigDecimal getPrevDay() { return prevDay; } public void setPrevDay(BigDecimal prevDay) { this.prevDay = prevDay; } public Integer getOpenBuyOrders() { return openBuyOrders; } public void setOpenBuyOrders(Integer openBuyOrders) { this.openBuyOrders = openBuyOrders; } public BigDecimal getVolume() { return volume; } public void setVolume(BigDecimal volume) { this.volume = volume; } public BigDecimal getBaseVolume() { return baseVolume; } public void setBaseVolume(BigDecimal baseVolume) { this.baseVolume = baseVolume; } public BigDecimal getBid() { return bid; } public void setBid(BigDecimal bid) { this.bid = bid; } public BigDecimal getAsk() { return ask; } public void setAsk(BigDecimal ask) { this.ask = ask; } public String getMarketName() { return marketName; } public void setMarketName(String marketName) { this.marketName = marketName; } public BigDecimal getHigh() { return high; } public void setHigh(BigDecimal high) { this.high = high; } @Override public String toString() { return "BittrexV2Summary{" + "openSellOrders=" + openSellOrders + ", timeStamp=" + timeStamp + ", last=" + last + ", low=" + low + ", created=" + created + ", prevDay=" + prevDay + ", openBuyOrders=" + openBuyOrders + ", volume=" + volume + ", baseVolume=" + baseVolume + ", bid=" + bid + ", ask=" + ask + ", marketName='" + marketName + '\'' + ", high=" + high + '}'; } }
22.069149
61
0.648108
bfdabef936b3f47b6702a0b71bb19da201b85f30
588
package io.tony.arcaretrofit.datasets; import io.pivotal.arca.provider.Column; import io.pivotal.arca.provider.SQLiteTable; import io.pivotal.arca.provider.Unique; public class CardTable extends SQLiteTable { public interface Columns extends SQLiteTable.Columns { @Unique(Unique.OnConflict.REPLACE) @Column(Column.Type.INTEGER) String ID = "id"; @Column(Column.Type.TEXT) String NAME = "name"; @Column(Column.Type.TEXT) String MANACOST = "manacost"; @Column(Column.Type.TEXT) String TEXT = "text"; } }
24.5
58
0.670068
98600e802a74cf1a1df0da3a846cd2255b84157a
1,871
package com.example.hai_da_shi_tang2019; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class suan_cai_yu_pian_ba_fan extends AppCompatActivity { private String[]data={"营养价值:\n" + "酸菜鱼的主材鱼含丰富优质蛋白,人体消化吸收率可达96%,并能供给人体必需的氨基酸、矿物质、维生素A和维生素D;鱼的脂肪多为不饱和脂肪酸,能很好的降低胆固醇,可以防治动脉硬化、冠心病,因此,多吃鱼可以健康长寿。\n" + "鲤鱼含丰富优质蛋白,人体消化吸收率可达96%,并能供给人体必需的氨基酸、矿物质、维生素A和维生素D;鲤鱼的脂肪多为不饱和脂肪酸,能很好的降低胆固醇,可以防治动脉硬化、冠心病,因此,多吃鱼可以健康长寿。鲤鱼味甘、性平,具有滋补健胃、利水消肿、通乳、清热解毒、止号嗽下气之功效,对各种水肿、浮肿、腹胀、少尿、黄疸、乳汁不通皆有益。\n" + "酸白菜:\n" + "酸菜中的乳酸能开胃提神、醒酒去腻,还能能增进食欲、帮助消化,还可以促进人体对铁元素的吸收。同时,白菜变酸,其所含营养成分不易损失。但酸菜只能偶尔食用,如果人体缺乏维C就应少吃,长期贪食,则可能引起泌尿系统结石,使红细胞失去携氧能力,导致组织缺氧,出现皮肤和嘴唇青紫、头痛头晕、恶心呕吐、心慌等中毒症状,严重者还能致死。\n" + "营养成分:\n" + "热量(1182.25千卡) 维生素B6(0.15毫克) 蛋白质(183.25克) 脂肪(41.56克) 泛酸(0.07毫克)\n" + "碳水化合物(16.59克) 叶酸(9.20微克) 膳食纤维(1.43克) 胆固醇(840.00毫克) 维生素A (263.50微克) 胡萝卜素(81.20微克) 硫胺素(0.36毫克) 核黄素(1.04毫克) 尼克酸(28.44毫克) 维生素C(5.10毫克) 维生素E(14.53毫克) 钙(608.00毫克) 磷(2139.12毫克) 钾(3650.88毫克) 钠(1993.10毫克) 镁(385.76毫克) 铁(14.18毫克) 锌(21.69毫克) 硒(159.00微克) 铜(0.74毫克) 锰(1.03毫克)\n" + "适宜人群:\n" + "一般人群均可食用,尤其适宜虚劳、风虚头痛、肝阳上亢高血压、头痛、久疟、心血管病人。\n" + "注意事项:\n" + "患痛风的人吃鱼会使症状加重。患有血小板减少、血友病、维生素E缺少等出血性疾病,还是少吃或不吃鱼。\n" + "营养疗效:\n" + "草鱼味甘、性温、无毒,入肝、胃经;\n" + "具有暖胃和中、平降肝阳、祛风、治痹、截疟、益肠明眼目之功效;\n" + "主治虚劳、风虚头痛、肝阳上亢、高血压、头痛、久疟。"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_suan_cai_yu_pian_ba_fan); ArrayAdapter<String> adapter=new ArrayAdapter<String>(suan_cai_yu_pian_ba_fan.this,android.R.layout.simple_list_item_1,data); ListView listView=(ListView)findViewById(R.id.list_view); listView.setAdapter(adapter); } }
53.457143
275
0.701229
fa4cc6309d2be0dc1b9d39400075a6df6d6d448b
2,100
package com.udacity.webcrawler.json; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.Objects; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * A static utility class that loads a JSON configuration file. */ @JsonDeserialize(builder = CrawlerConfiguration.Builder.class) public final class ConfigurationLoader { private final Path path; /** * Create a {@link ConfigurationLoader} that loads configuration from the given {@link Path}. */ public ConfigurationLoader(Path path) { this.path = Objects.requireNonNull(path); } /** * Loads configuration from this {@link ConfigurationLoader}'s path * * @return the loaded {@link CrawlerConfiguration}. */ public CrawlerConfiguration load() { // TODO: Fill in this method. try(Reader bufferedReader = Files.newBufferedReader(path)){ CrawlerConfiguration crawlerConfiguration = read(bufferedReader); return crawlerConfiguration; } catch (Exception ex) { ex.printStackTrace(); } return new CrawlerConfiguration.Builder().build(); } /** * Loads crawler configuration from the given reader. * * @param reader a Reader pointing to a JSON string that contains crawler configuration. * @return a crawler configuration */ public static CrawlerConfiguration read(Reader reader) { // This is here to get rid of the unused variable warning. Objects.requireNonNull(reader); // TODO: Fill in this method ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE); try{ CrawlerConfiguration crawlerConfiguration = objectMapper.readValue(reader, CrawlerConfiguration.class); return crawlerConfiguration; } catch (Exception ex){ ex.printStackTrace(); } return new CrawlerConfiguration.Builder().build(); } }
30.434783
110
0.733333
559a9e83565fad716dfff9d4e76613a2309e31d5
3,017
package phoenixTeam.util; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; /** * @author Strikingwolf, chbachman */ public class ReflectionUtil { public static void runMethodsFromObjects(ArrayList<Object> objects, String methodName, Object... args) { for (Object object : objects) { runMethodFromObj(object, methodName, args); } } public static void runMethodsFromClasses(ArrayList<Class<?>> classes, String methodName, Object... args) { for (Class<?> aClass : classes) { runMethodFromClass(aClass, methodName, args); } } public static void runMethodFromObj(Object obj, String methodName, Object... args) { try { Class<?>[] params = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { params[i] = args[i].getClass(); } Method method = obj.getClass().getDeclaredMethod(methodName, params); method.setAccessible(true); method.invoke(obj, args); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public static void runMethodFromClass(Class<?> aClass, String methodName, Object... args) { try { Class<?>[] params = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { params[i] = args[i].getClass(); } Method method = aClass.getDeclaredMethod(methodName, params); method.setAccessible(true); method.invoke(aClass, args); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public static void changeFieldFromObj(Object obj, String fieldName, Object value) { Class<?> aClass = obj.getClass(); Field field; try { field = aClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(obj, value); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public static Object getFieldValFromObj(Object obj, String fieldName) { Class<?> aClass = obj.getClass(); Field field; try { field = aClass.getDeclaredField(fieldName); field.setAccessible(true); return field.get(obj); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } }
33.898876
110
0.582035
b7a6ed6bc13f2af85a2492591a82db151e671c1c
439
package algo.array; public class FindMinimumRotatedSortedArrayII { public int findMin(int[] nums) { int l = 0; int r = nums.length; while(l < r){ int mid = (l+r)/2; if(nums[mid] < nums[r]){ r = mid; }else if(nums[mid] > nums[r]){ l = mid + 1; }else{ l++; } } return nums[l]; } }
19.086957
46
0.394077
702ee37af6647ca833cf01197b79c2fe640190ac
2,531
package com.elisacapololo.bustrip.ui.trips; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.elisacapololo.bustrip.R; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class TripsFragment extends Fragment { View view; List<Trips> list; RecyclerView recyclerView; public TripsFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_trips, container, false); recyclerView = view.findViewById(R.id.recyclerview_trips); MyAdapter myAdapter = new MyAdapter(getContext(), list); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setAdapter(myAdapter); return view; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); list = new ArrayList<>(); list.add(new Trips("Luanda", "Namibia", "08:00", "19:30","16/02/2020","24000","Luanda, Bengo")); list.add(new Trips("Luanda", "Namibe", "08:00", "19:30","01/06/2010","4000","Luanda, Bengo")); list.add(new Trips("Mbanza-Congo", "Luanda", "05:30", "12:00","30/08/2020","3500","Luanda, Bengo")); list.add(new Trips("Luanda", "Huila", "00:30", "10:00","10/03/2020","4500","Luanda, Bengo")); list.add(new Trips("Luanda", "Benguela", "19:00", "06:00","16/12/2020","5000","Luanda, Bengo")); list.add(new Trips("Namibia", "Cunene", "05:30", "12:00","16/05/2020","3600","Luanda, Bengo")); list.add(new Trips("Luanda", "Cabo-Ledo", "05:0", "11:00","9/04/2020","3500","Luanda, Bengo")); list.add(new Trips("Caluquembe", "Menongue", "05:30", "12:00","16/05/2020","3500","Luanda, Bengo")); list.add(new Trips("Luanda", "Negage", "05:30", "12:00","16/07/2020","3500","Luanda, Bengo")); } /*@Override public void onAttach(Context context) { super.onAttach(context); Toast.makeText(context, "Mostrando Viagens", Toast.LENGTH_SHORT).show(); }*/ }
37.220588
108
0.655867
8828f1cb5d62907e2e0ca7b0fec344aa5990c8e9
4,188
/** * <copyright> * </copyright> * * $Id$ */ package org.reclipse.behavior.specification; import org.fujaba.commons.identifier.Identifier; import org.eclipse.emf.ecore.ENamedElement; import org.eclipse.emf.ecore.EObject; import org.reclipse.structure.specification.PSObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>BP Argument</b></em>'. * <!-- end-user-doc --> * * <!-- begin-model-doc --> * A BPArgument belongs to a BPMessage. It has a reference to a PSObject from the structure specification plugin. * <!-- end-model-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.reclipse.behavior.specification.BPArgument#getMessage <em>Message</em>}</li> * <li>{@link org.reclipse.behavior.specification.BPArgument#getStatement <em>Statement</em>}</li> * <li>{@link org.reclipse.behavior.specification.BPArgument#getType <em>Type</em>}</li> * </ul> * </p> * * @see org.reclipse.behavior.specification.BehavioralpatternPackage#getBPArgument() * @model * @generated */ public interface BPArgument extends Identifier { /** * Returns the value of the '<em><b>Message</b></em>' container reference. * It is bidirectional and its opposite is '{@link org.reclipse.behavior.specification.BPMessage#getArguments <em>Arguments</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Message</em>' container reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Message</em>' container reference. * @see #setMessage(BPMessage) * @see org.reclipse.behavior.specification.BehavioralpatternPackage#getBPArgument_Message() * @see org.reclipse.behavior.specification.BPMessage#getArguments * @model opposite="arguments" required="true" transient="false" * @generated */ BPMessage getMessage(); /** * Sets the value of the '{@link org.reclipse.behavior.specification.BPArgument#getMessage <em>Message</em>}' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Message</em>' container reference. * @see #getMessage() * @generated */ void setMessage(BPMessage value); /** * Returns the value of the '<em><b>Statement</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Statement</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Statement</em>' attribute. * @see #setStatement(String) * @see org.reclipse.behavior.specification.BehavioralpatternPackage#getBPArgument_Statement() * @model * @generated */ String getStatement(); /** * Sets the value of the '{@link org.reclipse.behavior.specification.BPArgument#getStatement <em>Statement</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Statement</em>' attribute. * @see #getStatement() * @generated */ void setStatement(String value); /** * Returns the value of the '<em><b>Type</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Type</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Type</em>' reference. * @see #setType(PSObject) * @see org.reclipse.behavior.specification.BehavioralpatternPackage#getBPArgument_Type() * @model * @generated */ PSObject getType(); /** * Sets the value of the '{@link org.reclipse.behavior.specification.BPArgument#getType <em>Type</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Type</em>' reference. * @see #getType() * @generated */ void setType(PSObject value); } // BPArgument
34.9
135
0.626791
72f1dc0121b26f0313215500ddce670a00dd8d50
395
package good; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class FileStoage implements IStorage { @Override public void writeToFile(String data, String path) throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(path, true)); out.write(data); out.newLine();; out.close(); } }
20.789474
74
0.688608
7611ffe498bc737d1067d44e573efc43bd7ac95f
12,158
package com.google.android.gms.drive.sample.quickstart; import android.app.Activity; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.drive.Drive; import com.google.android.gms.drive.DriveApi.DriveContentsResult; import com.google.android.gms.drive.DriveContents; import com.google.android.gms.drive.DriveFile; import com.google.android.gms.drive.DriveFolder; import com.google.android.gms.drive.DriveId; import com.google.android.gms.drive.DriveResource; import com.google.android.gms.drive.MetadataChangeSet; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import static com.google.android.gms.drive.DriveId.decodeFromString; /** * Android Drive Quickstart activity. This activity takes a photo and saves it * in Google Drive. The user is prompted with a pre-made dialog which allows * them to choose the file location. */ public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener { private static final String TAG = "drive-quickstart"; private static final int REQUEST_CODE_RESOLUTION = 3; private GoogleApiClient mGoogleApiClient; private boolean isFileEmpty = true; private DriveId mDriveId; private ArrayList<String> driveIDs; /** * Create a new file and save it to Drive. */ private void saveFileToDrive(String path) { File file = new File(path); int length = (int) file.length(); byte[] byteFile = new byte[length]; try { FileInputStream in = new FileInputStream(file); in.read(byteFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String ext = FilenameUtils.getExtension(path); final String filename = FilenameUtils.getBaseName(path); // allocate additional 10 bytes for extension of the file and 4 bytes for extension size byte[] bytesExtLength = ByteBuffer.allocate(4).putInt(ext.length()).array(); Toast.makeText(getApplicationContext(), String.valueOf(length), Toast.LENGTH_LONG).show(); final byte[] byteEncodedFile = new byte[length + 14]; for (int i = 0; i < length; i++) { byteEncodedFile[i] = byteFile[i]; } for (int i = 0; i < 4; i++) { byteEncodedFile[length + i] = bytesExtLength[i]; } for (int i = 0; i < ext.length(); i++) { byteEncodedFile[length + i + 4] = (byte) ext.charAt(i); } // Start by creating a new contents, and setting a callback. Log.i(TAG, "Creating new contents."); Drive.DriveApi.newDriveContents(mGoogleApiClient) .setResultCallback(new ResultCallback<DriveContentsResult>() { @Override public void onResult(DriveContentsResult result) { // If the operation was not successful, we cannot do anything // and must fail. if (!result.getStatus().isSuccess()) { Log.i(TAG, "Failed to create new contents."); return; } // Otherwise, we can write our data to the new contents. Log.i(TAG, "New contents created."); // Get an output stream for the contents. OutputStream outputStream = result.getDriveContents().getOutputStream(); try { outputStream.write(byteEncodedFile); } catch (IOException e1) { Log.i(TAG, "Unable to write file contents."); } // Create the initial metadata - MIME type and title. // Note that the user will be able to change the title later. MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder() .setMimeType("application/octet-stream").setTitle(filename + ".bin").build(); // Create a file in the root folder Drive.DriveApi.getRootFolder(mGoogleApiClient) .createFile(mGoogleApiClient, metadataChangeSet, result.getDriveContents()) .setResultCallback(fileCallback); } }); } final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new ResultCallback<DriveFolder.DriveFileResult>() { @Override public void onResult(DriveFolder.DriveFileResult result) { if (!result.getStatus().isSuccess()) { System.out.println("Error while trying to create the file"); return; } mDriveId = result.getDriveFile().getDriveId(); System.out.println("Created a file with content: " + result.getDriveFile().getDriveId()); driveIDs.add(mDriveId.encodeToString()); System.out.println("driveID size is " + driveIDs.size()); Intent returnIntent = new Intent(); returnIntent.putExtra("driveIDs", driveIDs); setResult(RESULT_OK, returnIntent); finish(); } }; @Override protected void onResume() { super.onResume(); if (mGoogleApiClient == null) { // Create the API client and bind it to an instance variable. // We use this instance as the callback for connection and connection failures. // Since no account name is passed, the user is prompted to choose. mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Drive.API) .addScope(Drive.SCOPE_FILE) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } // connect the client mGoogleApiClient.connect(); } @Override protected void onPause() { if (mGoogleApiClient != null) { mGoogleApiClient.disconnect(); } super.onPause(); } @Override public void onConnectionFailed(ConnectionResult result) { // Called whenever the API client fails to connect. Log.i(TAG, "GoogleApiClient connection failed: " + result.toString()); if (!result.hasResolution()) { // show the localized error dialog. GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show(); return; } // The failure has a resolution. Resolve it. Called typically when the app is not // yet authorized, and an authorization dialog is displayed to the user. try { result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION); } catch (SendIntentException e) { Log.e(TAG, "Exception while starting resolution activity", e); } } @Override public void onConnected(Bundle connectionHint) { System.out.println("upload intent received"); Log.i(TAG, "API client connected."); Toast.makeText(getApplicationContext(), "Drive API launched", Toast.LENGTH_LONG).show(); driveIDs = new ArrayList<>(); int reqCode = getIntent().getIntExtra("requestcode", -1); if (reqCode == -1) { finish(); } // 100: upload if (isFileEmpty) { if (reqCode == 100) { String[] path = getIntent().getStringArrayExtra("path"); for (int i = 0; i < path.length; i++) { saveFileToDrive(path[i]); } isFileEmpty = false; } // 200: download if (reqCode == 200) { String driveIdAsString = getIntent().getStringExtra("driveId"); downloadFile(decodeFromString(driveIdAsString)); isFileEmpty = false; } } } @Override public void onConnectionSuspended(int cause) { Log.i(TAG, "GoogleApiClient connection suspended"); } public void downloadFile(DriveId driveID) { DriveFile file = driveID.asDriveFile(); Toast.makeText(getApplicationContext(), String.valueOf(mGoogleApiClient.isConnected()), Toast.LENGTH_LONG).show(); Toast.makeText(getApplicationContext(), driveID.toString(), Toast.LENGTH_LONG).show(); file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null) .setResultCallback(driveContentsCallback); } private ResultCallback<DriveContentsResult> driveContentsCallback = new ResultCallback<DriveContentsResult>() { @Override public void onResult(DriveContentsResult result) { if (!result.getStatus().isSuccess()) { System.out.println("Error while opening the file contents"); return; } DriveContents contents = result.getDriveContents(); try { byte[] bytes = IOUtils.toByteArray(contents.getInputStream()); int length = bytes.length; Toast.makeText(getApplicationContext(), String.valueOf(length), Toast.LENGTH_LONG).show(); byte[] fileBytes = new byte[length - 14]; byte[] extLengthBytes = new byte[4]; for (int i = 0; i < length - 14; i++) { fileBytes[i] = bytes[i]; } for (int i = 0; i < 4; i++) { extLengthBytes[i] = bytes[length - 14 + i]; } int extLength = ByteBuffer.wrap(extLengthBytes).getInt(); byte[] extBytes = new byte[extLength]; for (int i = 0; i < extLength; i++) { extBytes[i] = bytes[length - 10 + i]; } String ext = new String(extBytes); Intent returnIntent = new Intent(); returnIntent.putExtra("extension", ext); returnIntent.putExtra("filebytes", fileBytes); setResult(RESULT_OK, returnIntent); finish(); } catch (IOException e) { e.printStackTrace(); } } }; public static void saveFile(byte[] fileBytes, String extension, String filename) throws IOException { File file = new File(Environment.getExternalStorageDirectory() + File.separator + filename + "." + extension); file.createNewFile(); //write the bytes in file if (file.exists()) { OutputStream fo = new FileOutputStream(file); fo.write(fileBytes); fo.close(); System.out.println("file created: " + file); } } }
42.215278
122
0.577069
c8f6e4bd4dd49bc894181ee1ac45a2cfb5139b69
903
package com.ftpix.sherdogparser.models; public enum SearchWeightClass { CATCHWEIGHT(11, "Catchweight"), MINIMUMWEIGHT(17, "Minimumweight"), POUND_FOR_POUND(8, "Pound for Pound"), ATOMWEIGHT(15, "Atomweight"), STRAWWEIGHT(13, "Strawweight"), FLYWEIGHT(10, "Flyweight"), BANTAMWEIGHT(9, "Bantamweight"), FEATHERWEIGHT(7, "Featherweight"), LIGHTWEIGHT(6, "Lightweight"), WELTERWEIGHT(5, "Welterweight"), MIDDLEWEIGHT(4, "Middleweight"), LIGHT_HEAVYWEIGHT(3, "Light Heavyweight"), HEAVYWEIGHT(2, "Heavyweight"), SUPER_HEAVYWEIGHT(1, "Super Heavyweight"); SearchWeightClass(Integer value, String label) { this.value = value; this.label = label; } private Integer value; private String label; public Integer getValue() { return value; } public String getLabel() { return label; } }
24.405405
52
0.655592
d1e9567c581fe9121b72b5eae30ae069e3549b32
450
package com.javarush.test.level14.lesson06.home01; public class BelarusianHen extends Hen { @Override String getDescription() { return super.getDescription() + String.format( " Моя страна - %s. Я несу %d яиц в месяц.", Country.BELARUS, getCountOfEggsPerMonth() ); } @Override int getCountOfEggsPerMonth() { return 200; } }
23.684211
120
0.544444
c9b20623ac09a277d3d729a874644c21ba61cf34
1,974
package net.seesharpsoft.spring.data.domain; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.util.Assert; public class OffsetLimitRequest implements Pageable { private final long offset; private final int limit; private final Sort sort; public OffsetLimitRequest(long offset, int limit, Sort sort) { Assert.isTrue(offset >= 0, "offset must be greater or equal than 0!"); Assert.isTrue(limit > 0, "limit must be greater than 0!"); this.offset = offset; this.limit = limit; this.sort = sort; } public OffsetLimitRequest(long offset, int limit) { this(offset, limit, Sort.unsorted()); } @Override public int getPageNumber() { return (int) Math.floorDiv(getOffset() + getPageSize() - 1, getPageSize()); } @Override public int getPageSize() { return this.limit; } @Override public long getOffset() { return offset; } @Override public Sort getSort() { return this.sort; } @Override public Pageable next() { return new OffsetLimitRequest(getOffset() + getPageSize(), getPageSize(), getSort()); } @Override public Pageable previousOrFirst() { long start = getOffset() - getPageSize(); if (start < 0) { start = 0; } return new OffsetLimitRequest(start, (int) (getOffset() - start), getSort()); } @Override public Pageable first() { int firstPageSize = (int) getOffset() % getPageSize(); return new OffsetLimitRequest(0, firstPageSize, getSort()); } @Override public boolean hasPrevious() { return getOffset() > 0; } @Override public String toString() { return String.format("Offset-Limit request [offset: %d, limit: %d, sort: %s]", getOffset(), getPageSize(), getSort()); } }
26.32
126
0.615502
2575976441a2e11e1733d7f63a6ed6877e932683
5,455
package com.example.jay3165.garglibrary; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.entity.StringEntity; import static android.R.attr.thumb; public class search_book extends AppCompatActivity implements AllBookAdapter.Clickable { ArrayList<particularbook> mArrayList; private RecyclerView mRecyclerView; String name=null; private RecyclerView.LayoutManager booksearchActivityLayout; AllBookAdapter.Clickable clickable = this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_book); mArrayList = new ArrayList<particularbook>(); mRecyclerView = (RecyclerView) findViewById(R.id.rvBookSearch); booksearchActivityLayout = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(booksearchActivityLayout); Intent it = getIntent(); getSupportActionBar().setTitle(it.getStringExtra("s")); name = it.getStringExtra("s"); } @Override protected void onStart() { super.onStart(); if (mArrayList.size() == 0) { BookData(); } } public void BookData(){ AsyncHttpClient mClient = new AsyncHttpClient(); mClient.addHeader("Accept", "application/json"); mClient.addHeader("Content-Type", "application/json"); mClient.get(this, "http://khedutstore.com/garglibrary/ws/search.php?keyword="+name, new JsonHttpResponseHandler() { ProgressDialog mProgressDialog; @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); try { String thumb =response.getString("thmbimg_url"); JSONArray mJsonArray = response.getJSONArray("details"); JSONObject mJsonObject; for (int i = 0; i < mJsonArray.length(); i++) { mJsonObject = mJsonArray.getJSONObject(i); int discount=(Integer.parseInt(mJsonObject.getString("p_price")) * Integer.parseInt(mJsonObject.getString("p_discount")))/100; int newprice=Integer.parseInt(mJsonObject.getString("p_price")) - discount; Log.i("jjjjjjjj",mJsonObject.getString("p_price")); Log.i("lllllll",mJsonObject.getString("p_discount")); Log.i("discount",discount+""); mArrayList.add(new particularbook(mJsonObject.getString("p_id"), mJsonObject.getString("p_name"), mJsonObject.getString("p_price"),mJsonObject.getString("p_brand_name"),mJsonObject.getString("main_cat_id"),mJsonObject.getString("main_sub_id"),mJsonObject.getString("sub_cat_id"),mJsonObject.getString("p_specification"),thumb+mJsonObject.getString("p_image"),mJsonObject.getString("p_discount"),mJsonObject.getString("p_cat_id"),mJsonObject.getString("p_status"),mJsonObject.getString("p_stock"),newprice+"",discount+"")); Log.e("Array Length",mArrayList.size() + ""); mRecyclerView.setAdapter(new AllBookAdapter(mArrayList, getApplicationContext(), clickable)); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); Toast.makeText(search_book.this, "No Data Connection!", Toast.LENGTH_SHORT).show(); } @Override public void onStart() { super.onStart(); mProgressDialog = ProgressDialog.show(search_book.this, "Loading", "Please Wait", true, false); } @Override public void onFinish() { super.onFinish(); if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } } ); } @Override public void click(int position) { Intent i=new Intent(search_book.this,AllBookdetailsActivity.class); i.putExtra("p_id",mArrayList.get(position).getP_id()); startActivity(i); Toast.makeText(this,mArrayList.get(position).getP_name(),Toast.LENGTH_SHORT).show(); } }
45.840336
554
0.610816
77ccda1e1fcdc0caadef05dd0fd1251546a8b414
4,966
package com.example.android.tourguideapp; // TODO: Update coordinates import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class DiningFragment extends Fragment { public LocationService gps; public double lat; public double lon; public DiningFragment() { // Required empty public constructor } @Override public void onAttach(Context context) { super.onAttach(context); getLocation(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.list_landmark, container, false); getLocation(); final ArrayList<Landmark> landmarks = new ArrayList<>(); landmarks.add(new Landmark(R.string.name_d001, R.string.description_d001, R.drawable.d001, 56.95185, 24.117, 20225000, R.string.website_d001)); landmarks.add(new Landmark(R.string.name_d002, R.string.description_d002, R.drawable.d002, 56.94882, 24.12259, 67099763, R.string.website_d002)); landmarks.add(new Landmark(R.string.name_d003, R.string.description_d003, R.drawable.d003, 56.94976, 24.11024, 67224576, R.string.website_d003)); landmarks.add(new Landmark(R.string.name_d004, R.string.description_d004, R.drawable.d004, 56.9272, 24.16021, 67504420, R.string.website_d004)); landmarks.add(new Landmark(R.string.name_d005, R.string.description_d005, R.drawable.d005, 56.95108, 24.10241, 29533523, R.string.website_d005)); landmarks.add(new Landmark(R.string.name_d006, R.string.description_d006, R.drawable.d006, 56.94716, 24.11095, 67225699, R.string.website_d006)); landmarks.add(new Landmark(R.string.name_d007, R.string.description_d007, R.drawable.d007, 56.95156, 24.10779, 20370537, R.string.website_d007)); landmarks.add(new Landmark(R.string.name_d008, R.string.description_d008, R.drawable.d008, 56.94966, 24.10307, 29529200, R.string.website_d008)); landmarks.add(new Landmark(R.string.name_d009, R.string.description_d009, R.drawable.d009, 56.95886, 24.10452, 67332830, R.string.website_d008)); LandmarkAdapter adapter = new LandmarkAdapter(getActivity(), landmarks, R.color.diningBackground_light, lat, lon); ListView listView = rootView.findViewById(R.id.list); listView.setAdapter(adapter); // What will happen when a used clicks on a list item: listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /* PASSING DATA BETWEEN ACTIVITIES IMPORTANT: FIRST start new activity, AFTER THAT pass the data to new activity! */ Intent i = new Intent(getActivity(), LandmarkActivity.class); startActivity(i); Intent intent = new Intent(DiningFragment.this.getActivity(), LandmarkActivity.class); intent.putExtra("LandmarkImageResource_FromIntent", landmarks.get(position).getLandmarkImageResourceId()); intent.putExtra("LandmarkName_FromIntent", landmarks.get(position).getLandmarkNameId()); intent.putExtra("LandmarkDescription_FromIntent", landmarks.get(position).getLandmarkDescriptionId()); intent.putExtra("LandmarkPhone_FromIntent", landmarks.get(position).getLandmarkPhoneId()); intent.putExtra("LandmarkWebsite_FromIntent", landmarks.get(position).getLandmarkWebsiteId()); intent.putExtra("LandmarkLatitude_FromIntent", landmarks.get(position).getLandmarkLatitudeId()); intent.putExtra("LandmarkLongitude_FromIntent", landmarks.get(position).getLandmarkLongitudeId()); intent.putExtra("Background_FromIntent", getResources().getColor(R.color.diningBackground_light)); startActivity(intent); } }); return rootView; } public void getLocation() { // GETTING GPS DATA TO THIS FRAGMENT FROM ANOTHER CLASS gps = new LocationService(getActivity().getApplicationContext()); lat = 0; lon = 0; // Checking if GPS enabled if (gps.canGetLocation()) { lat = gps.getLatitude(); lon = gps.getLongitude(); // Replace GPS logic with below mock data if needed for test purposes: // lat = 56.94703; // lon = 24.10646; } } @Override public void onResume(){ super.onResume(); getLocation (); } }
40.373984
153
0.682843
8798c57b24454fcc04653cc7f6650c4800e77af4
1,365
package org.tus.servlet.upload; import javax.servlet.http.HttpServletRequest; /* A single instance of the datastore will be created. */ public interface Datastore { /* Initialize the datastore service */ public void init(Config config, Locker locker) throws Exception; /* Return list of extensions supported by this datastore. */ public String getExtensions(); /* Create binary and auxillary files to start an upload. */ public void create(FileInfo fi) throws Exception; /* Writes up to max bytes, starting at offset, to id's storage, from request. Returns the number of bytes written. */ public long write(HttpServletRequest request, String id, long offset, long max) throws Exception; /* Retrieve FileInfo describing the upload identified by filename. Returns null if info or bin file for filename doesn't exist. */ public FileInfo getFileInfo(String id) throws Exception; /* Persist FileInfo */ public void saveFileInfo(FileInfo fileInfo) throws Exception; /* Delete partial or complete upload in response to a DELETE request. */ public void terminate(String id) throws Exception; /* If there's any work to do when the upload is finished, this is where it's done. */ public void finish(String id) throws Exception; /* Shutdown the datastore service */ public void destroy() throws Exception; }
22.75
82
0.740659
b6021772755b1d79666ececa759338feaa685099
4,220
package edu.washington.cs.detector.guider; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import edu.washington.cs.detector.util.Utils; import edu.washington.cs.detector.util.WALAUtils; public class CGTraverseExploreClientRunnableStrategy implements CGTraverseGuider { public final String[] clientRunnablePackage; public final Map<String, String> methodCallMapping = new LinkedHashMap<String, String>(); public final Set<String> exclusionMethods = new LinkedHashSet<String>(); CGTraverseGuider safeGuier = new CGTraverseAndroidSafeMethodGuider(); public CGTraverseExploreClientRunnableStrategy(String[] clientCodePackage) { this.clientRunnablePackage = clientCodePackage; } //the format: a.b.c.Class.methodName public void addMethodGuidance(String srcSig, String destSig) { methodCallMapping.put(srcSig, destSig); } public void addExclusionGuidance(String exclusionMethod) { exclusionMethods.add(exclusionMethod); } @Override public boolean traverse(CGNode src, CGNode dest) { // if(src.toString().indexOf("dispatchMessage") != -1) { // System.out.println("Checking traverse: src: " + src // + "\n dest: " + dest); // IMethod srcMethod = src.getMethod(); // IClass srcClass = srcMethod.getDeclaringClass(); // String classFullName = WALAUtils.getJavaFullClassName(srcClass); // //System.err.println(classFullName); // String methodName = srcMethod.getName().toString(); // String srcmethod = classFullName + "." + methodName; // System.out.println(" src method: " + srcmethod); // } if(!safeGuier.traverse(src, dest)) { return false; } if(Utils.containIn(dest.getMethod().getSignature(), exclusionMethods.toArray(new String[0]))) { return false; } if(this.clientRunnablePackage.length == 0 && methodCallMapping.isEmpty()) { return true; } IMethod srcMethod = src.getMethod(); IClass srcClass = srcMethod.getDeclaringClass(); String classFullName = WALAUtils.getJavaFullClassName(srcClass); //System.err.println(classFullName); String methodName = srcMethod.getName().toString(); if (this.clientRunnablePackage.length > 0) { if (classFullName.equals("java.lang.Thread") && (methodName.equals("start") /*|| methodName.equals("run")*/)) { IClass destClass = dest.getMethod().getDeclaringClass(); String destCode = WALAUtils.getJavaFullClassName(destClass) + "." + dest.getMethod().getName().toString() ; // System.out.println("source node: " + src); // System.out.println("dest node: " + dest); if (this.isInClientPackage(destCode.trim())) { // System.err.println("thread start: " + dest); // System.out.println(" XX starting traverse! " + src + " --> " + dest); return true; } else { return false; //be aware of this } } } if(!methodCallMapping.isEmpty()) { String srcmethod = classFullName + "." + methodName; if(methodCallMapping.containsKey(srcmethod)) { IClass destClass = dest.getMethod().getDeclaringClass(); String destCode = WALAUtils.getJavaFullClassName(destClass) + "." + dest.getMethod().getName().toString(); // System.out.println("Checking method call mapping: "); // System.out.println(" srcmethod: " + srcmethod); // System.out.println(" destcode: " + destCode); // System.out.println(" methodCallMapping.get(srcmethod): " + methodCallMapping.get(srcmethod)); if(!destCode.startsWith(methodCallMapping.get(srcmethod))) { // System.out.println(" checking fails..."); return false; } else { // System.out.println("visiting: " + srcmethod + " --> " + destCode); return true; } } } //System.out.println("visiting: " + src + " --> " + dest); return true; } private boolean isInClientPackage(String destCode) { // System.out.println(" ===== " +destCode); for(String pName : this.clientRunnablePackage) { // System.out.println(" +++++ " + pName); if(destCode.startsWith(pName.trim())) { return true; } } return false; } }
35.166667
114
0.688152
b2a9caa8bcba2439d167d4151eba38a17411e897
1,744
package com.aopphp.go.index; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment; import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag; import com.jetbrains.php.lang.psi.PhpFile; import com.jetbrains.php.lang.psi.elements.Function; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpClassMember; import com.jetbrains.php.lang.psi.elements.PhpNamedElement; import gnu.trove.THashMap; import java.util.Map; abstract class AbstractDataIndexer<T> { private final Map<String, T> map = new THashMap<>(); private final PhpFile phpFile; AbstractDataIndexer(final PhpFile phpFile) { this.phpFile = phpFile; } Map<String, T> map() { for (final PhpNamedElement element : phpFile.getTopLevelDefs().values()) { if (element instanceof Function) { visitPhpNamedElement(element, map); } else if (element instanceof PhpClass) { for (PhpClassMember member : PsiTreeUtil.getChildrenOfTypeAsList(element, PhpClassMember.class)) { visitPhpNamedElement(member, map); } } } return map; } private void visitPhpNamedElement(final PhpNamedElement element, final Map<String, T> map) { final PhpDocComment docComment = element.getDocComment(); if (docComment != null) { for (final PhpDocTag phpDocTag : PsiTreeUtil.getChildrenOfTypeAsList(docComment, PhpDocTag.class)) { visitPhpDocTag(phpDocTag, map); } } } protected abstract void visitPhpDocTag(final PhpDocTag phpDocTag, final Map<String, T> map); }
36.333333
114
0.686927
ffeb1aa6e392616cac4d63fa3e4acc603a699008
1,242
package controller; import java.text.NumberFormat; import java.util.Locale; public class Ex_6 { public static void main(String[] args){ Locale.setDefault(Locale.FRANCE); NumberFormat f = NumberFormat.getCurrencyInstance(); double valor = 123456.789; System.out.println(f.format(valor)); Locale.setDefault(Locale.US); NumberFormat u = NumberFormat.getCurrencyInstance(); System.out.println(u.format(valor)); Locale.setDefault(Locale.ENGLISH); NumberFormat e = NumberFormat.getCurrencyInstance(); System.out.println(e.format(valor)); Locale.setDefault(Locale.UK); NumberFormat uk = NumberFormat.getCurrencyInstance(); System.out.println(uk.format(valor)); Locale.setDefault(Locale.CANADA_FRENCH); NumberFormat cf = NumberFormat.getCurrencyInstance(); System.out.println(cf.format(valor)); Locale.setDefault(Locale.GERMAN); NumberFormat g = NumberFormat.getCurrencyInstance(); System.out.println(g.format(valor)); Locale.setDefault(Locale.CHINA); NumberFormat ch = NumberFormat.getCurrencyInstance(); System.out.println(ch.format(valor)); Locale.setDefault(Locale.ITALIAN); NumberFormat i = NumberFormat.getCurrencyInstance(); System.out.println(i.format(valor)); } }
29.571429
55
0.752013
759966f1667d42fdc5379aeedf0fac4047884c12
14,188
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.openapi.updateSettings.impl; import com.intellij.ide.util.BrowseFilesListener; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.fileChooser.FileChooserFactory; import com.intellij.openapi.fileChooser.FileTextField; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogBuilder; import com.intellij.openapi.ui.LabeledComponent; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.components.JBList; import com.intellij.util.JdomKt; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.Collections; public class ShowUpdateInfoDialogAction extends AnAction { public ShowUpdateInfoDialogAction() { } @Override public void update(AnActionEvent e) { e.getPresentation().setEnabledAndVisible(e.getProject() != null); } @Override public void actionPerformed(AnActionEvent e) { Project project = e.getProject(); if (project == null) return; String title = "Updates.xml <channel> Text"; JBList list = new JBList("Manual Text", "Sample Text (short)", "Sample Text (long)"); JBPopupFactory.getInstance().createListPopupBuilder(list) .setTitle(title) .setFilteringEnabled(o -> (String)o) .setItemChoosenCallback(() -> { int index = list.getSelectedIndex(); Pair<String, VirtualFile> info = index == 0 ? getUserText(project, title) : Pair.create(getXML(index == 2), null); showDialog(info.first, info.second); }) .createPopup() .showCenteredInCurrentWindow(project); } @NotNull private static Pair<String, VirtualFile> getUserText(@NotNull Project project, @NotNull String title) { JTextArea textArea = new JTextArea(10, 50); UIUtil.addUndoRedoActions(textArea); textArea.setWrapStyleWord(true); textArea.setLineWrap(true); JPanel panel = new JPanel(new BorderLayout(0, 10)); panel.add(ScrollPaneFactory.createScrollPane(textArea), BorderLayout.CENTER); Disposable disposable = Disposer.newDisposable(); FileTextField fileField = FileChooserFactory.getInstance().createFileTextField(BrowseFilesListener.SINGLE_FILE_DESCRIPTOR, disposable); TextFieldWithBrowseButton fileCompo = new TextFieldWithBrowseButton(fileField.getField()); FileChooserDescriptor fileDescriptor = FileChooserDescriptorFactory.createSingleLocalFileDescriptor(); fileCompo.addBrowseFolderListener("Patch File", "Patch file", project, fileDescriptor); panel.add(LabeledComponent.create(fileCompo, "Patch file:"), BorderLayout.SOUTH); DialogBuilder builder = new DialogBuilder(project); builder.addDisposable(disposable); builder.setCenterPanel(panel); builder.setPreferredFocusComponent(textArea); builder.setTitle(title); builder.addOkAction(); builder.addCancelAction(); return builder.showAndGet() ? Pair.create(textArea.getText(), fileField.getSelectedFile()) : Pair.empty(); } protected void showDialog(@Nullable String text, @Nullable VirtualFile patchFile) { String trim = StringUtil.trim(text); if (StringUtil.isEmpty(trim)) return; Element element; try { element = JdomKt.loadElement(trim); if (!"channel".equals(element.getName())) return; } catch (Exception ex) { Logger.getInstance(ShowUpdateInfoDialogAction.class).error(ex); return; } UpdateChannel channel = new UpdateChannel(element); BuildInfo newBuild = ContainerUtil.getFirstItem(channel.getBuilds()); if (newBuild == null) return; PatchInfo patch = ContainerUtil.getFirstItem(newBuild.getPatches()); UpdateInfoDialog dialog = new UpdateInfoDialog(channel, newBuild, patch, true, UpdateSettings.getInstance().canUseSecureConnection(), Collections.emptyList(), Collections.emptyList()) { @NotNull @Override File doDownloadPatch(@NotNull ProgressIndicator indicator) throws IOException { File file = patchFile == null ? null : VfsUtilCore.virtualToIoFile(patchFile); return file != null ? file : super.doDownloadPatch(indicator); } }; dialog.setTitle("[TEST] " + dialog.getTitle()); dialog.show(); } private static final String PARAGRAPH = " <li><strong>Refactoring to Java 8</strong>: more powerful inspections.</li>\n" + " <li><strong>JVM Debugger</strong>: Class-level Watches; the JVM Memory View plugin.</li>\n" + " <li><strong>User Interface</strong>: Parameter Hints; Semantic Highlighting; flat file icons.</li>\n" + " <li><strong>Build Tools</strong>: Delegate IDE build/run actions to Gradle; Composite <br>\n" + " Builds support; Polyglot Maven.</li>\n" + " <li><strong>Scala</strong>: scala.meta and Scala.js</li>\n" + " <li><strong>JavaScript</strong>: refactoring to ECMAScript 6; Flow-based inspections; <br>\n" + " React Native debugger, Protractor, Stylelint, PostCSS, and more.</li>\n" + " <li><strong>VCS</strong>: Faster and more ergonomic Log for Git/Mercurial; automatic <br>\n" + " resolving conflicts; managing Git remotes.</li>\n" + " <li><strong>Android</strong>: Blueprint; Constraint Layout, APK Analyzer, and better Instant Run.</li>\n" + " <li><strong>Database</strong>: editing multiple cells at once; submit changes in bulk; <br>\n" + " find usages of objects within the source code of other objects.</li>\n"; private static final String CHANNEL_XML_START = "<!DOCTYPE products SYSTEM \"updates.dtd\">\n" + "<channel id=\"IDEA_EAP\" name=\"IntelliJ IDEA EAP\" status=\"eap\"\n" + " url=\"https://confluence.jetbrains.com/display/IDEADEV/IDEA+2016.3+EAP\"\n" + " feedback=\"http://youtrack.jetbrains.net\"\n" + " majorVersion=\"2016\" licensing=\"eap\">\n" + " <build number=\"163.7743.44\" version=\"2016.3\" releaseDate=\"20161122\">\n" + " <message><![CDATA[\n" + " <p>Please meet IntelliJ IDEA 2016.3, the third update planned for 2016!</p>\n" + "\n" + "<p>Visit <a href=\"https://www.jetbrains.com/idea/whatsnew/?landing\">What's New</a> page for a full list of new features and an overview video.</p>\n" + "\n" + "<p>And here're the highlights:</p>\n" + "\n" + "<ul>\n"; private static final String CHANNEL_XML_END = "</ul>\n" + "]]></message>\n" + " <button name=\"Download\" url=\"https://www.jetbrains.com/idea/download/\" download=\"true\"/>\n" + " <button name=\"What's New\" url=\"https://www.jetbrains.com/idea/whatsnew/?landing\"/>\n" + " <patch from=\"163.7743.17\" size=\"from 2 to 18\"/>\n" + " <patch from=\"163.7743.37\" size=\"from 2 to 18\"/>\n" + " </build>\n" + " <build number=\"162.2228.15\" version=\"2016.2.5\" releaseDate=\"20160712\">\n" + " <message><![CDATA[\n" + " <p>The <strong>IntelliJ IDEA 2016.2.5</strong> update is available. <br>\n" + " Apart from bugfixes, the update brings support for <strong>macOS Sierra</strong>.</p>\n" + "]]></message>\n" + " <button name=\"Download\" url=\"https://www.jetbrains.com/idea/download/\" download=\"true\"/>\n" + " <button name=\"Release Notes\" url=\"https://confluence.jetbrains.com/display/IDEADEV/IntelliJ+IDEA+2016.2.5+Release+Notes\"/>\n" + " <patch from=\"162.2032.8\" size=\"from 1 to 13\"/>\n" + " <patch from=\"162.2228.14\" size=\"from 21 to 53\"/>\n" + " <patch from=\"162.1812.17\" size=\"from 21 to 55\"/>\n" + " <patch from=\"162.1628.40\" size=\"from 21 to 59\"/>\n" + " <patch from=\"162.1447.26\" size=\"from 21 to 67\"/>\n" + " <patch from=\"162.1121.32\" size=\"from 33 to 80\"/>\n" + " </build>\n" + " <build number=\"162.1121.32\" version=\"2016.2\" releaseDate=\"20160712\">\n" + " <message><![CDATA[\n" + " <p>Welcome <strong>IntelliJ IDEA 2016.2</strong>, a second update planned for this year.<br>\n" + " The update brings lots of new features and improvements across the <br>\n" + " built-in tools, UI, and support for languages and frameworks.\n" + "</p>\n" + "\n" + "<p>Learn more about the update by reading the <a href=\"http://blog.jetbrains.com/idea/2016/07/intellij-idea-2016-2-is-here/\">blog post</a>.</p>\n" + "]]></message>\n" + " <button name=\"What's New\" url=\"https://www.jetbrains.com/idea/whatsnew/\"/>\n" + " <button name=\"Download\" url=\"https://www.jetbrains.com/idea/download/\" download=\"true\"/>\n" + " <patch from=\"162.1121.10\" size=\"from 1 to 12\"/>\n" + " </build>\n" + " <build number=\"145.2070\" version=\"2016.1.4\" releaseDate=\"20160316\">\n" + " <message><![CDATA[\n" + " <p>IntelliJ IDEA 2016.1.4 build 145.2070 is available with important bugfixes.</p>\n" + "]]></message>\n" + " <button name=\"Release Notes\" url=\"https://confluence.jetbrains.com/display/IDEADEV/IntelliJ+IDEA+2016.1.4+Release+Notes\"/>\n" + " <button name=\"Download\" url=\"https://confluence.jetbrains.com/display/IntelliJIDEA/Previous+IntelliJ+IDEA+Releases\"\n" + " download=\"true\"/>\n" + " <patch from=\"145.1617\" size=\"from 42 to 58\"/>\n" + " </build>\n" + " </channel>\n"; private static String getXML(boolean bigData) { StringBuilder sb = new StringBuilder(CHANNEL_XML_START); int count = bigData ? 4 : 1; for (int i = 0; i < count; i++) { sb.append(PARAGRAPH); } sb.append(CHANNEL_XML_END); return sb.toString(); } }
64.490909
204
0.527629
ac1d0c1b1117c62bddcb4f69d623fc078631f71d
1,410
package com.commercetools.api.models.me; import java.time.*; import java.util.*; import java.util.function.Function; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.annotation.*; import io.vrap.rmf.base.client.utils.Generated; @Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen") @JsonDeserialize(as = MyCartSetLocaleActionImpl.class) public interface MyCartSetLocaleAction extends MyCartUpdateAction { String SET_LOCALE = "setLocale"; @JsonProperty("locale") public String getLocale(); public void setLocale(final String locale); public static MyCartSetLocaleAction of() { return new MyCartSetLocaleActionImpl(); } public static MyCartSetLocaleAction of(final MyCartSetLocaleAction template) { MyCartSetLocaleActionImpl instance = new MyCartSetLocaleActionImpl(); instance.setLocale(template.getLocale()); return instance; } public static MyCartSetLocaleActionBuilder builder() { return MyCartSetLocaleActionBuilder.of(); } public static MyCartSetLocaleActionBuilder builder(final MyCartSetLocaleAction template) { return MyCartSetLocaleActionBuilder.of(template); } default <T> T withMyCartSetLocaleAction(Function<MyCartSetLocaleAction, T> helper) { return helper.apply(this); } }
30.652174
120
0.748936
0511c2c2922b6c26721ebd30768540a6ae4a7a3c
1,005
package com.zhl.userguideview; import android.app.Activity; import android.content.Context; import android.util.DisplayMetrics; /** * * des:测量工具类 * Created by xsf * on 2016.08.11:59 */ public final class MeasureUtil { public static final int RATION_WIDTH = 0; public static final int RATION_HEIGHT = 1; /** * 获取屏幕尺寸 * * @param activity * Activity * @return 屏幕尺寸像素值,下标为0的值为宽,下标为1的值为高 */ public static int[] getScreenSize(Activity activity) { DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); return new int[] { metrics.widthPixels, metrics.heightPixels }; } /** * 获取状态栏高度 * @param context * @return */ public static int getStatusBarHeight(Context context) { int result = 0; int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resId > 0) { result = context.getResources().getDimensionPixelOffset(resId); } return result; } }
22.333333
92
0.699502
2ae86c0a8d8c6875dc5fb90077480b3d8788b425
2,425
package edu.utah.bmi.nlp.easycie; import edu.utah.bmi.nlp.core.Interval1D; import edu.utah.bmi.nlp.core.IntervalST; import edu.utah.bmi.nlp.type.system.ConceptBASE; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.FSIndex; import org.apache.uima.jcas.JCas; import java.util.ArrayList; import java.util.Iterator; /** * Find overlapped annotations with the same annotation type, choose the widest one * @author Jianlin Shi * Created on 7/6/16. */ public class CoordinateNERResults_AE extends JCasAnnotator_ImplBase { @Override public void process(JCas jCas) throws AnalysisEngineProcessException{ ArrayList<ConceptBASE> concepts = new ArrayList<>(); FSIndex annoIndex = jCas.getAnnotationIndex(ConceptBASE.type); Iterator annoIter = annoIndex.iterator(); while (annoIter.hasNext()) { concepts.add((ConceptBASE) annoIter.next()); } IntervalST presentTree = new IntervalST(); IntervalST absentTree = new IntervalST(); for (ConceptBASE concept : concepts) { if (concept.getClass().getSimpleName().equals("PseudoConcept")) { checkOverlap(absentTree, concept); continue; } else { checkOverlap(presentTree, concept); continue; } } } /** * Because FastNER and FastCNER may have overlapped matches. * * @param intervalTree * @param concept */ private void checkOverlap(IntervalST intervalTree, ConceptBASE concept) { Interval1D interval = new Interval1D(concept.getBegin(), concept.getEnd()); ConceptBASE overlapped = (ConceptBASE) intervalTree.get(interval); if (overlapped != null && (overlapped.getEnd() != concept.getBegin() && concept.getEnd() != overlapped.getBegin())) { if ((overlapped.getEnd() - overlapped.getBegin()) < (concept.getEnd() - concept.getBegin())) { overlapped.removeFromIndexes(); intervalTree.remove(new Interval1D(overlapped.getBegin(), overlapped.getEnd())); intervalTree.put(interval, concept); } else { concept.removeFromIndexes(); } } else { intervalTree.put(interval, concept); } } }
36.19403
125
0.647835
77d2dab953357e64bf5a91a574facf0a6845a576
235
package com.elopez.almacen.core.models.dao; import com.elopez.almacen.core.models.entity.Producto; import org.springframework.data.jpa.repository.JpaRepository; public interface IProductoDao extends JpaRepository<Producto, Long> { }
29.375
69
0.829787
a124ad2691c36bca4620c086f5ab26bfa915fbc1
19,603
package Nuskin; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDate; import java.time.YearMonth; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name="orders") public class Order { @Transient private Logger log = LoggerFactory.getLogger(Order.class); @Id @Column(unique=true) String orderNumber = ""; @Column String account = ""; @Column String date = ""; @Column String shippingAddress = ""; @Column BigDecimal subtotal = new BigDecimal(0); @Column BigDecimal shipping = new BigDecimal(0); @Column BigDecimal tax = new BigDecimal(0); @Transient ArrayList<Product> products = new ArrayList<Product>(); @Transient Account accnt = null; @Transient final BigDecimal oneCent = new BigDecimal("0.01"); @JsonGetter(value="hasUnsoldItems") public boolean hasUnsoldItems() { for (Product product: products) { if (product.getEndUse() == Product.EndUse.INSTOCK) { return true; } } // No unsold items found return false; } @JsonGetter(value="hasOnlyInStockItems") public boolean hasOnlyInStockItems() { for (Product product: products) { if (product.getEndUse() != Product.EndUse.INSTOCK) { return false; } } // Only instock items found return true; } public String getMonth() { LocalDate d = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/uuuu")); YearMonth yandm = YearMonth.from(d); return yandm.toString(); } public String getAccountName() { if (accnt == null) { accnt = ProductDatabase.getDB().getAccount(account); } if (accnt != null) { return accnt.getAccountName(); } else { return "Unknown"; } } @JsonIgnore public String getMonthName() { LocalDate d = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/uuuu")); String s = d.format(DateTimeFormatter.ofPattern("MMM")); return s; } // Function<T,R> - function which takes a single argument of type T and returns an R public static Predicate<Product> distinctProductByKey(Function<Product, String> keyExtractor) { Map<String, Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } class CustomerItems { CustomerItems(String name, String desc) { this.name = name; this.desc = desc; } String name; String desc; public String getName() { return name; } public String getDesc() { return desc; } } public ArrayList<CustomerItems> getSoldItemsPerCustomer() { ArrayList<CustomerItems> perCustomer = new ArrayList<CustomerItems>(); // Find sold items on this order List<Product> soldItems = products.stream() .filter( p-> p.getEndUse() == Product.EndUse.SOLD ) .collect(Collectors.toList()); // Sort the sold items by customer name Map<String, List<Product>> customerMap = soldItems.stream().collect(Collectors.groupingBy(Product::getCustomerName)); // Product a summary for each customer customerMap.forEach( (customer, products) -> { String s = ""; for ( Product p: products) { if (s.length() > 0) s += ','; s += p.getDescription(); } perCustomer.add(new CustomerItems(customer, s)); } ); return perCustomer; } public String getItemSummary() { final StringBuilder sb = new StringBuilder(); // Summarize INSTOCK items only List<Product> unsoldItems = products.stream() .filter( p-> p.getEndUse() == Product.EndUse.INSTOCK ) .collect(Collectors.toList()); if (unsoldItems.size() == 0) { sb.append( "None"); } else { // Group items with the same DESCRIPTION together Map<String, Long> descMap = unsoldItems.stream().collect(Collectors.groupingBy(Product::getDescription, Collectors.counting())); descMap.forEach((desc, count) -> { if (sb.length() > 0) sb.append(","); sb.append(desc); if (count > 1) { sb.append( " [x" + count + "]"); } }); /* // Alternatively, group items with the same SKU together Map<String, List<Product>> map = products.stream().collect(Collectors.groupingBy( Product::getSku)); // Counting map.forEach( (k,v) -> { if (sb.length() > 0) sb.append(","); // Get the description from the first item in each list sb.append(v.get(0).getDescription()); if (v.size() > 1) { sb.append( " [x" + v.size() + "]"); } }); */ } return sb.toString(); } public String getDisposedItemSummary() { final StringBuilder sb = new StringBuilder(); // Summarize NOT INSTOCK items only List<Product> unsoldItems = products.stream() .filter( p-> p.getEndUse() != Product.EndUse.INSTOCK ) .collect(Collectors.toList()); if (unsoldItems.size() == 0) { sb.append( "None"); } else { // Group items with the same DESCRIPTION together Map<String, Long> descMap = unsoldItems.stream().collect(Collectors.groupingBy(Product::getDescription, Collectors.counting())); descMap.forEach((desc, count) -> { if (sb.length() > 0) sb.append(","); sb.append(desc); if (count > 1) { sb.append( " [x" + count + "]"); } }); } return sb.toString(); } // Provide getters and setters for JSON conversion public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getShippingAddress() { return shippingAddress; } public void setShippingAddress(String shippingAddress) { this.shippingAddress = shippingAddress; } public BigDecimal getSubtotal() { return subtotal; } public void setSubtotal(BigDecimal subtotal) { this.subtotal = subtotal; } public BigDecimal getShipping() { return shipping; } public void setShipping(BigDecimal shipping) { this.shipping = shipping; } public BigDecimal getTax() { return tax; } public void setTax(BigDecimal tax) { this.tax = tax; } public ArrayList<Product> getUnknownProductTypes() { ArrayList<Product> itemsWithUnknownProductType = new ArrayList<Product>(); for (Product product: products) { if (product.getProductType() == null) { itemsWithUnknownProductType.add(product); } } return itemsWithUnknownProductType; } public boolean hasUnknownProductTypes() { for (Product product: products) { if (product.getProductType() == null) { return true; } } return false; } BigDecimal getTotal() { BigDecimal total = subtotal; total = total.add(shipping); total = total.add(tax); return total; } BigDecimal getTaxOnShipping() { return shipping.multiply(getTaxRate()) .setScale(2, RoundingMode.HALF_UP); } BigDecimal getShippingIncTax() { // Shipping is also subject to tax return shipping.add(getTaxOnShipping()); } BigDecimal getItemCost() { BigDecimal sum = BigDecimal.ZERO; for (Product p : products) { sum = sum.add(p.getCostPrice()); } if (sum.compareTo(this.getSubtotal()) != 0) { System.err.println(orderNumber + ": sum of item cost " + sum + " is not equal to order subtotal " + getSubtotal()); } return sum; } BigDecimal getItemTax() { BigDecimal sum = BigDecimal.ZERO; for (Product p : products) { sum = sum.add(p.getTax()); } BigDecimal itemTax = getTax().subtract(getTaxOnShipping()); if (sum.compareTo(itemTax) != 0) { System.err.println(orderNumber+ ": sum of item tax " + sum + " is not equal to order tax " + itemTax); } return sum; } BigDecimal sumItemAndShippingTax() { BigDecimal taxSum = getItemTax(); // Shipping is also subject to tax taxSum = taxSum.add(getTaxOnShipping()); return taxSum; } BigDecimal getItemShipping() { BigDecimal sum = BigDecimal.ZERO; for (Product p : products) { sum = sum.add(p.getShipping()); } BigDecimal orderShipping = this.getShippingIncTax(); if (sum.compareTo(orderShipping) != 0) { // We might be one cent out for each item System.err.println(orderNumber + ": sum of item shipping " + sum + " is not equal to order shipping " + orderShipping); } return sum; } BigDecimal getSales() { BigDecimal sales = BigDecimal.ZERO; for (Product product: products) { if (product.getEndUse() == Product.EndUse.SOLD) { sales = sales.add(product.getSellingPrice()); } } return sales; } BigDecimal getCost(Product.EndUse endUse) { // Cost of items still in stock BigDecimal val = BigDecimal.ZERO; for (Product product: products) { if (product.getEndUse() == endUse) { val = val.add(product.getTotalCost()); } } return val; } BigDecimal getSalesCost() { return getCost(Product.EndUse.SOLD); } BigDecimal getInventoryCost() { return getCost(Product.EndUse.INSTOCK); } BigDecimal getSampleCost() { return getCost(Product.EndUse.SAMPLE); } BigDecimal getPersonalUseCost() { return getCost(Product.EndUse.PERSONAL); } BigDecimal getDemoCost() { return getCost(Product.EndUse.DEMO); } int getItemCount(Product.EndUse endUse) { int count = 0; for (Product product: products) { if (product.getEndUse() == endUse) { count++; } } return count; } int getPurchasedItemCount() { return products.size(); } int getSoldItemCount() { return getItemCount(Product.EndUse.SOLD); } int getInventoryItemCount() { return getItemCount(Product.EndUse.INSTOCK); } int getSampleItemCount() { return getItemCount(Product.EndUse.SAMPLE); } int getPersonalUseItemCount() { return getItemCount(Product.EndUse.PERSONAL); } int getDemoItemCount() { return getItemCount(Product.EndUse.DEMO); } void addProduct(Product p, int quantity) { p.order = this; for (int i =0 ; i < quantity; i++) { Product p1 = new Product(p); products.add(p1); } } void applyShippingToProducts() { if (shipping.compareTo(BigDecimal.ZERO) != 0) { int numberOfItems = products.size(); // Shipping is subject to tax // Need to set a scale and a rounding for BigDecimal.divide otherwise can get arithmetic exceptions BigDecimal shippingCostPerItem = getShippingIncTax().divide(new BigDecimal(numberOfItems), 2, RoundingMode.HALF_UP); for (Product product: products) { product.setShipping(shippingCostPerItem); } } } private BigDecimal getTaxRate() { // HST rate depends on the shipping address // For Ontario, its 13% // New Brunswick is 15% // Others - TODO BigDecimal taxRate = new BigDecimal("0.15"); if (shippingAddress.contains(" NB,")) { //taxRate = new BigDecimal("0.13"); } else if (shippingAddress.contains(" ON,")) { taxRate = new BigDecimal("0.13"); } return taxRate; } void applyTaxToProducts() { // If this is a preferred customer account, tax is % of the wholesale price // If its a distributor account, tax is % of the retail price // This applies also to product bought with points // First can I work out if its a distributor account from the order, or do I just // go off knowing the account number? BigDecimal taxSum = new BigDecimal(0); boolean isDistributorAccount = account.startsWith("CA6"); BigDecimal taxRate = getTaxRate(); for (Product product: products) { product.calculateTax(isDistributorAccount, taxRate); } taxSum = sumItemAndShippingTax(); BigDecimal error = taxSum.subtract(getTax()).abs(); if (error.compareTo(oneCent) > 0) { System.err.println("Expected tax " + taxSum + " Actual tax charged " + tax); // OK, something went wrong. Maybe a product price has changed or is wrong in the database // This can happen if either or both: // (a) products were purchased with points. Tax is charged on retail or wholesale price // Its also possible that products bought with points on a distributor account are taxed on the wholesale price // - that seems to get close to (but not exactly) the actual tax charged on at least one order // (b) order made on a distributor account, cost is wholesale price but tax is charged on the retail price // Under these circumstances we don't have sufficient information on the order, as it does not itemise tax // so we are relying on the product type (SKU) database to provide the price information. If the price has // changed, or perhaps a special offer, then it won't match. // For case (a), maybe we could compare the points cost with the database - a price change may also imply a // points value change // I can't know which item or items are wrong, will instead simply make an adjustment to each product, as // we don't need to account for GST/HST to CRA, just need to know how much we should be charging to cover // our costs. // To avoid ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result // have to provide scale and rounding mode. Use sufficient decimal places (6 seems ok) to get the accuracy to 1 penny. // We need to REMOVE the shipping tax as we know what that is and we've added it to the // shipping cost per item. Adjust only the item tax. BigDecimal a = tax.subtract(this.getTaxOnShipping()); BigDecimal b = getItemTax(); BigDecimal adjustRatio = a.divide(b, 8, RoundingMode.HALF_UP); for (Product product: products) { BigDecimal newTax = product.getTax().multiply(adjustRatio); product.setTax(newTax.setScale(2, RoundingMode.HALF_UP)); } // Might be pennies out still taxSum = sumItemAndShippingTax(); if (taxSum.compareTo(tax) != 0 ) { System.err.println("Adjusted expected tax " + taxSum + " Actual tax charged " + tax); } else { System.err.println("After adjustment, sum = actual tax charged = " + tax); } } else { System.err.println("Expected tax matches actual tax charged: " + tax); } } boolean isSet(String s) { return !(s == null || s.length() == 0); } boolean hasAllInfo() { boolean complete = true; if (!isSet(orderNumber)) complete = false; if (!isSet(account)) complete = false; if (!isSet(date)) complete = false; if (!isSet(shippingAddress)) complete = false; if (subtotal.compareTo(BigDecimal.ZERO) == 0 ) complete = false; if (tax.compareTo(BigDecimal.ZERO) == 0) complete = false; // shipping may be zero // Must have at least one product item if (products.isEmpty()) complete = false; return complete; } void show() { System.out.println("Order number: " + orderNumber); System.out.println("Account : " + account); System.out.println("Date : " + date); System.out.println("Subtotal : $" + subtotal); System.out.println("Shipping : $" + shipping); System.out.println("Tax : $" + tax); System.out.println("Total : $" + getTotal()); for (Product product : products) { product.show(); } } void getProductsFromDatabase() { ProductDatabase db = ProductDatabase.getDB(); products = db.getOrderItems(this.orderNumber); // Make sure they are sorted by ID so they are in the same order as // when the Order was added to the database Collections.sort( products, (p1, p2) -> { return (int)(p1.getId() - p2.getId()); }); } void checkItemCount() { BigDecimal itemCost = getInventoryCost() .add( getSalesCost()) .add(getSampleCost()) .add(getPersonalUseCost()) .add(getDemoCost()); if (itemCost.compareTo(getTotal()) != 0 ) { log.error("Order " + getOrderNumber() + " TOTAL " + getTotal() + " ITEM COST " + itemCost); } } void correctTaxAndShipping() { /// Debug code used when I had the products of an order twice in the database so totals didnt tally //checkItemCount(); BigDecimal itemShipping = getItemShipping(); boolean fixNeeded = false; // Fix shipping first, as there was a gross error in the calculation of the tax // on shipping if (this.getShippingIncTax().compareTo(itemShipping) != 0 ) { fixNeeded = true; System.err.println("Fixing shipping"); applyShippingToProducts(); } BigDecimal taxOnOrder = getTax(); BigDecimal taxOnItems = sumItemAndShippingTax(); // includes tax on shipping // If its 1 cent its probably not worth bothering BigDecimal error = taxOnOrder.subtract(taxOnItems).abs(); if (error.compareTo( oneCent ) > 0 ) { fixNeeded = true; System.err.println("Fixing tax"); applyTaxToProducts(); } if (fixNeeded) { ProductDatabase db = ProductDatabase.getDB(); //db.addOrder(this); // Not modifying this, just the items' tax and shipping // Add each product to the database for (Product product : products) { db.addProduct(product); } } } void deleteFromDatabase() { ProductDatabase db = ProductDatabase.getDB(); for (Product product: products) { db.deleteProduct(product); } db.deleteOrder(this); } void addToDatabase() { ProductDatabase db = ProductDatabase.getDB(); // If being used outside of Spring the database is not set up if (db == null) return; // Is this order already in the database? Order existing = db.getOrder(this.orderNumber); if (existing == null) { db.addOrder(this); // Add each product to the database for (Product product : products) { db.addProduct(product); } } else { System.out.println("Order already in the database"); if (!this.date.equals(existing.date)) { System.err.println("Dates don't match"); } if (!this.account.equals(existing.account)) { System.err.println("Accounts don't match"); } if (!this.shippingAddress.equals(existing.shippingAddress)) { System.err.println("Shipping addresses don't match"); } if (this.subtotal.compareTo(existing.subtotal) != 0) { System.err.println("Subtotals don't match"); } if (this.tax.compareTo(existing.tax) != 0) { System.err.println("Subtotals don't match"); } if (existing.products.size() != this.products.size()) { System.err.println("Order has different number of items"); } else { for (int i=0; i< products.size(); i++) { existing.products.get(i).compare(this.products.get(i)); } } } } }
24.412204
131
0.652247
50b098bcb5e100ad50e3c3198ebf21abb7daa2a1
1,744
/** * Copyright (C) FuseSource, Inc. * http://fusesource.com * * 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.fabric8.itests.paxexam.support; import io.fabric8.api.Container; import io.fabric8.api.FabricService; import io.fabric8.api.ServiceProxy; import io.fabric8.internal.ContainerImpl; import java.io.Closeable; import java.io.IOException; public class ContainerProxy extends ContainerImpl implements Closeable { private ServiceProxy<FabricService> proxy; public static ContainerProxy wrap(Container container, ServiceProxy<FabricService> proxy) { if (container == null) { return null; } ContainerProxy parentProxy = wrap(container.getParent(), proxy); return new ContainerProxy(parentProxy, container.getId(), proxy); } private ContainerProxy(ContainerProxy parent, String id, ServiceProxy<FabricService> proxy) { super(parent, id, proxy.getService()); this.proxy = proxy; } @Override public void stop(boolean force) { try { super.stop(force); } finally { proxy.close(); } } @Override public void close() throws IOException { proxy.close(); } }
29.559322
97
0.692661
a7afc0c504a481aaba30c0ea88b729e464851055
2,522
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package FXMLS.FINANCIAL.CLASSFILES; import javafx.beans.property.SimpleStringProperty; /** * * @author Gilbert */ public class Disbursement_request_classfile { public SimpleStringProperty drID; public SimpleStringProperty drReqno; public SimpleStringProperty drDatereq; public SimpleStringProperty drReqname; public SimpleStringProperty drDescription; public SimpleStringProperty drDepartment; public SimpleStringProperty drprioritylvl; public SimpleStringProperty drAmount; public SimpleStringProperty drdisbursementStatus; public Disbursement_request_classfile(String dr_id,String Requestno, String datereq, String reqname, String department, String description, String priority_level, String amount, String disbursestatus){ this.drID = new SimpleStringProperty(dr_id); this.drReqno = new SimpleStringProperty(Requestno); this.drDatereq = new SimpleStringProperty(datereq); this.drReqname = new SimpleStringProperty(reqname); this.drDepartment = new SimpleStringProperty(department); this.drDescription = new SimpleStringProperty(description); this.drprioritylvl = new SimpleStringProperty(priority_level); this.drAmount = new SimpleStringProperty(amount); this.drdisbursementStatus = new SimpleStringProperty(disbursestatus); } public String getDr_id(){ return drID.get(); } public String getRequestno(){ return drReqno.get(); } public String getDatereq(){ return drDatereq.get(); } public String getReqname(){ return drReqname.get(); } public String getDepartment(){ return drDepartment.get(); } public String getDescription(){ return drDescription.get(); } public String getPriority_level(){ return drprioritylvl.get(); } public String getAmount(){ return drAmount.get(); } public String getDisbursementStatus(){ return drdisbursementStatus.get(); } }
34.547945
79
0.629659
946d17c57e8a33923a6050703494b286fa2c62b2
1,812
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.ballerinalang.net.http.compiler.websocket; import io.ballerina.tools.diagnostics.DiagnosticSeverity; import org.ballerinalang.net.http.websocket.WebSocketConstants; import org.ballerinalang.util.diagnostic.DiagnosticLog; import org.wso2.ballerinalang.compiler.tree.BLangFunction; /** * Service validator for WebSocket failover. * * @since 1.2.0 */ class WebSocketFailoverClientResourceValidator extends WebSocketClientResourceValidator { WebSocketFailoverClientResourceValidator(DiagnosticLog dlog, BLangFunction resource) { super(dlog, resource); } @Override void validateEndpointParameter() { if (paramDetails != null && !paramDetails.isEmpty() && !WebSocketConstants.FULL_FAILOVER_WEBSOCKET_CLIENT_NAME.equals(paramDetails.get(0).type.toString())) { dlog.logDiagnostic(DiagnosticSeverity.ERROR, resource.pos, INVALID_RESOURCE_SIGNATURE_FOR + resource.getName().getValue() + RESOURCE_IN_SERVICE + ": The first parameter should be a " + WebSocketConstants.FULL_FAILOVER_WEBSOCKET_CLIENT_NAME); } } }
39.391304
118
0.732892
31652dab17904ce5c428cb3c78c6e1240dbae784
1,517
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package me.zero.tls.proplan.gui.controller; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import me.zero.tls.proplan.components.Plan; import me.zero.tls.proplan.gui.view.ProPlanUI; import me.zero.tls.proplan.components.Process; /** * * @author Julius.Schoenhut */ public class DeleteController implements ActionListener{ //Plan to work with private Plan plan; //Process to worki with private Process node; public DeleteController(Plan plan,Process node){ this.plan = plan; this.node = node; } public DeleteController(){} @Override public void actionPerformed(ActionEvent e) { //Löschen angesagt if(e == null){ for(Process pro : node.getPredecessor()){ pro.removeSuccessor(node); } for(me.zero.tls.proplan.components.Process pro : node.getSuccecessor()){ pro.removePredecessor(node); } plan.nodes.remove(node); plan.startForward_scheduling(); plan.startBackward_scheduling(); plan.startTotalPufferCalculation(); plan.repaint(); ProPlanUI.mode = -1; }else{ ProPlanUI.mode = 1; } } }
28.092593
85
0.60646
cece4e7c5089c320bcac0de018b024a82902ab02
505
class ProxyVerticalTrapezoidVertex { public VerticalTrapezoid t = null; public Vertex v = null; public ProxyVerticalTrapezoidVertex(VerticalTrapezoid t) { this.t = t; } public ProxyVerticalTrapezoidVertex(Vertex v) { this.v = v; } public String toString() { if(t != null) return t.toString(); if(v != null) return v.toString(); return "Keine ahnung"; } public VerticalTrapezoid toTrapezoid() { return t; } public Vertex toVertex() { return v; } }
18.035714
60
0.657426
333ec2fc473bc903e22e203d352bb3a51a0aa9c6
2,064
package com.github.datalking.web.mvc; import com.github.datalking.util.Assert; import com.github.datalking.util.ClassUtils; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; /** * 定制map用来存放string -> Object * * @author yaoo on 4/26/18 */ public class ModelMap extends LinkedHashMap<String, Object> { public ModelMap() { } public ModelMap(String attributeName, Object attributeValue) { addAttribute(attributeName, attributeValue); } public ModelMap(Object attributeValue) { addAttribute(attributeValue); } public ModelMap addAttribute(String attributeName, Object attributeValue) { Assert.notNull(attributeName, "Model attribute name must not be null"); put(attributeName, attributeValue); return this; } public ModelMap addAttribute(Object attributeValue) { Assert.notNull(attributeValue, "Model object must not be null"); if (attributeValue instanceof Collection && ((Collection) attributeValue).isEmpty()) { return this; } return addAttribute(ClassUtils.getCamelCaseNameFromClass(attributeValue.getClass()), attributeValue); } public ModelMap addAllAttributes(Collection<?> attributeValues) { if (attributeValues != null) { for (Object attributeValue : attributeValues) { addAttribute(attributeValue); } } return this; } public ModelMap addAllAttributes(Map<String, ?> attributes) { if (attributes != null) { putAll(attributes); } return this; } public ModelMap mergeAttributes(Map<String, ?> attributes) { if (attributes != null) { for (String key : attributes.keySet()) { if (!containsKey(key)) { put(key, attributes.get(key)); } } } return this; } public boolean containsAttribute(String attributeName) { return containsKey(attributeName); } }
27.157895
109
0.635174
8647865b8c3fe25948937a9d48dec85fd406decc
242
package com.catfish.ums.service; import com.catfish.ums.entity.domain.UmsMenu; import com.hisaige.dbcore.service.BaseService; /** * @author chenyj * 2020/5/23 - 18:54. **/ public interface UmsMenuService extends BaseService<UmsMenu> { }
20.166667
62
0.752066
b73c33c4ad43d7298c7de5028c353e09bc1d7b78
1,531
/* * #%L * Protempa Framework * %% * Copyright (C) 2012 - 2013 Emory University * %% * 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. * #L% */ package org.protempa.backend; import org.protempa.backend.asb.AlgorithmSourceBackend; import org.protempa.backend.dsb.DataSourceBackend; import org.protempa.backend.ksb.KnowledgeSourceBackend; /** * Interface for PROTEMPA backend provider modules. * * @author Andrew Post */ public interface BackendProvider { String getDisplayName(); BackendSpecLoader<DataSourceBackend> getDataSourceBackendSpecLoader() throws BackendProviderSpecLoaderException; BackendSpecLoader<KnowledgeSourceBackend> getKnowledgeSourceBackendSpecLoader() throws BackendProviderSpecLoaderException; BackendSpecLoader<AlgorithmSourceBackend> getAlgorithmSourceBackendSpecLoader() throws BackendProviderSpecLoaderException; Object newInstance(String resourceId) throws BackendNewInstanceException ; }
34.022222
78
0.745265
2ad3b0c8742f52b0b01b6af857e49b941e5b61d4
789
package com.onevgo.leetcode; public class Ex28StrStr { public int strStr(String haystack, String needle) { if (needle == null || needle.equals("")) return 0; char[] srcArr = haystack.toCharArray(); char[] destArr = needle.toCharArray(); for (int i = 0; i <= srcArr.length - destArr.length; i++) { boolean flag = true; for (int j = 0; j < destArr.length; j++) { if (srcArr[i + j] != destArr[j]) { flag = false; break; } } if (flag) { return i; } } return -1; } public static void main(String[] args) { System.out.println(new Ex28StrStr().strStr("hello", "ll")); } }
27.206897
67
0.470215
3cc00588c171bd0ffb38d9cc1da7afd10c169d67
2,816
/*************************GO-LICENSE-START********************************* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.cruise.api; import com.thoughtworks.cruise.Urls; import com.thoughtworks.cruise.client.TalkToCruise; import com.thoughtworks.cruise.client.TalkToCruise.CruiseResponse; import com.thoughtworks.cruise.util.CruiseConstants; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.StringRequestEntity; import java.io.UnsupportedEncodingException; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class UsingUserApi { private TalkToCruise talkToCruise; public UsingUserApi(TalkToCruise talkToCruise){ this.talkToCruise = talkToCruise; } public void disableUser(String userName) throws Exception { NameValuePair operation = new NameValuePair("operation", "Disable"); NameValuePair selected = new NameValuePair("selected[]", userName); CruiseResponse response = talkToCruise.post(Urls.urlFor("/admin/users/operate"), operation, selected); assertThat(response.getStatus(), is(302)); } @com.thoughtworks.gauge.Step("Attempt to delete <username> user and should return <httpStatus>") public void attemptToDeleteUserAndShouldReturn(String username, String httpStatus) throws Exception { CruiseResponse response = talkToCruise.delete(Urls.urlFor(String.format("/api/users/%s", username)), true, CruiseConstants.apiV2); assertThat(response.getStatus(), is(Integer.parseInt(httpStatus))); } @com.thoughtworks.gauge.Step("Add user <username> - Using user API") public void AddUser(String username) throws Exception { CruiseResponse response = addUserApiCall(username); assertThat(response.getStatus(), is(201)); } private CruiseResponse addUserApiCall(String username) throws UnsupportedEncodingException { StringRequestEntity requestEntity = new StringRequestEntity( "{\"login_name\": \""+ username + "\"}", "application/json", "UTF-8"); String url = Urls.urlFor(String.format("/api/users")); CruiseResponse response = talkToCruise.post(url, requestEntity, "CONFIRM", CruiseConstants.apiV2); return response; } }
42.029851
132
0.742188
42c0104fe6368c08c434688c9ca6a7c82b9286eb
22
package A; class A{ }
5.5
10
0.636364
6fb9a106660c98a2791542e1607cbdae5f1e0c09
232
package grp2.fitness.Helpers; public class AccountHandler { private boolean isLoggedIn = true; public boolean isLoggedIn(){ return isLoggedIn; } public void logout(){ isLoggedIn = false; } }
14.5
38
0.637931
3fbdb58b493007ae2394aba10d79384715bc28ca
2,115
package com.tjnu.club.utils; import com.tjnu.club.constants.TJNUConstants; import com.tjnu.club.exceptions.TJNUException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.mail.*; import javax.mail.Message.RecipientType; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; @Component @Slf4j public class MailUtil { @Value("${tjnu.email.address}") private String FROM_MAIL; @Value("${tjnu.email.password}") private String PASSWORD; /** * 发送邮件 * * @param address 收件人地址 * @param code 自定义激活码 * @throws MessagingException * @throws AddressException */ public Boolean sendMail(String address, String code) { try { Properties prop = new Properties(); prop.setProperty("mail.host", "smtp.163.com"); //设置服务器主机名 prop.setProperty("mail.smtp.auth", "true"); //设置需要认证 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(FROM_MAIL, PASSWORD);//用户名和密码 } }; Session session = Session.getInstance(prop, auth); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(FROM_MAIL)); message.setRecipient(RecipientType.TO, new InternetAddress(address)); message.setSubject("TJNUClub致信"); message.setContent("<a style='font-weight:bold;'>您正在进行安全邮箱验证操作,验证码</a><a style='color:blue;text-decoration:underline;'>" + code + "</a><a style='font-weight:bold;'>。(验证码告知他人将导致账号危险,请勿泄露)</a>", "text/html;charset=UTF-8"); Transport.send(message); return Boolean.TRUE; } catch (MessagingException e) { log.error(e.getMessage(),e); throw new TJNUException(TJNUConstants.VERIFY_SEND_FAILURE); } } }
36.465517
232
0.658629
c09ae2c089a49de4122f4558f3e43d6068711c34
409
package com.joelzhu.bindview.annotations; import androidx.annotation.LayoutRes; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface RootView { @LayoutRes int resId() default -1; String resName() default ""; }
25.5625
44
0.797066
6e482d24d63ab1de880b0eb4ff86e41083316446
2,139
package chronosacaria.mcdw.mixin; import chronosacaria.mcdw.bases.McdwAxe; import chronosacaria.mcdw.bases.McdwCustomWeaponBase; import chronosacaria.mcdw.enchants.EnchantsRegistry; import chronosacaria.mcdw.enums.DaggersID; import chronosacaria.mcdw.items.ItemsInit; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentTarget; import net.minecraft.enchantment.Enchantments; import net.minecraft.item.ItemStack; import net.minecraft.util.Util; import net.minecraft.util.registry.Registry; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(Enchantment.class) public abstract class EnchantmentMixin { @Shadow protected abstract boolean canAccept(Enchantment other); @Shadow protected abstract String getOrCreateTranslationKey(); @Shadow @Final public EnchantmentTarget type; @Inject(method = "isAcceptableItem", at = @At("RETURN"), cancellable = true) private void isAcceptablePlz(ItemStack stack, CallbackInfoReturnable<Boolean> cir){ if (stack.getItem() instanceof McdwAxe && isEnchantment(Enchantments.FIRE_ASPECT)) { cir.setReturnValue(true); } if (stack.getItem() instanceof McdwCustomWeaponBase && this.type.equals(EnchantmentTarget.WEAPON)){ cir.setReturnValue(true); } if (stack.isOf(ItemsInit.daggerItems.get(DaggersID.DAGGER_SWIFT_STRIKER)) && isEnchantment(EnchantsRegistry.ECHO, EnchantsRegistry.AMBUSH)){ cir.setReturnValue(true); } } private boolean isEnchantment(Enchantment ...enchantments){ for (Enchantment enchantment : enchantments){ if (Util.createTranslationKey("enchantment", Registry.ENCHANTMENT.getId(enchantment)).equals(this.getOrCreateTranslationKey())){ return true; } } return false; } }
38.196429
140
0.742403
e444acb426fb30a1a853bdc743fa4f52a5884626
2,100
/* * $# * FOS R implementation *   * Copyright (C) 2013 Feedzai SA *   * This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU * Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern * your use of this software only upon the condition that you accept all of the terms of either the Apache * License or the LGPL License. * * You may obtain a copy of the Apache License and the LGPL License at: * * http://www.apache.org/licenses/LICENSE-2.0.txt * http://www.gnu.org/licenses/lgpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software distributed under the Apache License * or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the Apache License and the LGPL License for the specific language governing * permissions and limitations under the Apache License and the LGPL License. * #$ */ package com.feedzai.fos.impl.r.config; import com.feedzai.fos.api.config.FosConfig; import com.google.common.base.Objects; import static com.google.common.base.Preconditions.checkNotNull; /** * Configuration required for the r manager. * @author miguel.duarte * @since 1.0.2 */ public class RManagerConfig { /** * Name of the configuration parameter for: the size of the thread pool classifier. */ private FosConfig configuration; /** * Creates a new object from the given configuration. * <p/> * * @param configuration creates a FosConfig with the given configuration. */ public RManagerConfig(FosConfig configuration) { checkNotNull(configuration, "Configuration cannot be null"); this.configuration = configuration; } @Override public String toString() { return Objects.toStringHelper(this) .add("configuration", configuration) .toString(); } public void setConfiguration(FosConfig configuration) { this.configuration = configuration; } }
31.818182
109
0.704762
22f8bb746e82de52eebf971d342d9a81d54171b7
14,294
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.ilm; import com.carrotsearch.hppc.cursors.ObjectCursor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.lucene.util.SetOnce; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterStateApplier; import org.elasticsearch.cluster.ClusterStateListener; import org.elasticsearch.cluster.LocalNodeMasterListener; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.Strings; import org.elasticsearch.common.component.Lifecycle.State; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.xpack.core.XPackField; import org.elasticsearch.xpack.core.ilm.IndexLifecycleMetadata; import org.elasticsearch.xpack.core.ilm.LifecycleExecutionState; import org.elasticsearch.xpack.core.ilm.LifecyclePolicy; import org.elasticsearch.xpack.core.ilm.LifecycleSettings; import org.elasticsearch.xpack.core.ilm.OperationMode; import org.elasticsearch.xpack.core.ilm.ShrinkStep; import org.elasticsearch.xpack.core.ilm.Step.StepKey; import org.elasticsearch.xpack.core.scheduler.SchedulerEngine; import java.io.Closeable; import java.time.Clock; import java.util.Collections; import java.util.Set; import java.util.function.LongSupplier; /** * A service which runs the {@link LifecyclePolicy}s associated with indexes. */ public class IndexLifecycleService implements ClusterStateListener, ClusterStateApplier, SchedulerEngine.Listener, Closeable, LocalNodeMasterListener { private static final Logger logger = LogManager.getLogger(IndexLifecycleService.class); private static final Set<String> IGNORE_STEPS_MAINTENANCE_REQUESTED = Collections.singleton(ShrinkStep.NAME); private volatile boolean isMaster = false; private volatile TimeValue pollInterval; private final SetOnce<SchedulerEngine> scheduler = new SetOnce<>(); private final Clock clock; private final PolicyStepsRegistry policyRegistry; private final IndexLifecycleRunner lifecycleRunner; private final Settings settings; private ClusterService clusterService; private LongSupplier nowSupplier; private SchedulerEngine.Job scheduledJob; public IndexLifecycleService(Settings settings, Client client, ClusterService clusterService, ThreadPool threadPool, Clock clock, LongSupplier nowSupplier, NamedXContentRegistry xContentRegistry) { super(); this.settings = settings; this.clusterService = clusterService; this.clock = clock; this.nowSupplier = nowSupplier; this.scheduledJob = null; this.policyRegistry = new PolicyStepsRegistry(xContentRegistry, client); this.lifecycleRunner = new IndexLifecycleRunner(policyRegistry, clusterService, threadPool, nowSupplier); this.pollInterval = LifecycleSettings.LIFECYCLE_POLL_INTERVAL_SETTING.get(settings); clusterService.addStateApplier(this); clusterService.addListener(this); clusterService.addLocalNodeMasterListener(this); clusterService.getClusterSettings().addSettingsUpdateConsumer(LifecycleSettings.LIFECYCLE_POLL_INTERVAL_SETTING, this::updatePollInterval); } public void maybeRunAsyncAction(ClusterState clusterState, IndexMetaData indexMetaData, StepKey nextStepKey) { String policyName = LifecycleSettings.LIFECYCLE_NAME_SETTING.get(indexMetaData.getSettings()); lifecycleRunner.maybeRunAsyncAction(clusterState, indexMetaData, policyName, nextStepKey); } public ClusterState moveClusterStateToStep(ClusterState currentState, String indexName, StepKey currentStepKey, StepKey nextStepKey) { return IndexLifecycleRunner.moveClusterStateToStep(indexName, currentState, currentStepKey, nextStepKey, nowSupplier, policyRegistry, false); } public ClusterState moveClusterStateToFailedStep(ClusterState currentState, String[] indices) { return lifecycleRunner.moveClusterStateToFailedStep(currentState, indices); } @Override public void onMaster() { this.isMaster = true; maybeScheduleJob(); ClusterState clusterState = clusterService.state(); IndexLifecycleMetadata currentMetadata = clusterState.metaData().custom(IndexLifecycleMetadata.TYPE); if (currentMetadata != null) { OperationMode currentMode = currentMetadata.getOperationMode(); if (OperationMode.STOPPED.equals(currentMode)) { return; } boolean safeToStop = true; // true until proven false by a run policy // If we just became master, we need to kick off any async actions that // may have not been run due to master rollover for (ObjectCursor<IndexMetaData> cursor : clusterState.metaData().indices().values()) { IndexMetaData idxMeta = cursor.value; String policyName = LifecycleSettings.LIFECYCLE_NAME_SETTING.get(idxMeta.getSettings()); if (Strings.isNullOrEmpty(policyName) == false) { final LifecycleExecutionState lifecycleState = LifecycleExecutionState.fromIndexMetadata(idxMeta); StepKey stepKey = IndexLifecycleRunner.getCurrentStepKey(lifecycleState); if (OperationMode.STOPPING == currentMode) { if (stepKey != null && IGNORE_STEPS_MAINTENANCE_REQUESTED.contains(stepKey.getName())) { logger.info("waiting to stop ILM because index [{}] with policy [{}] is currently in step [{}]", idxMeta.getIndex().getName(), policyName, stepKey.getName()); lifecycleRunner.maybeRunAsyncAction(clusterState, idxMeta, policyName, stepKey); // ILM is trying to stop, but this index is in a Shrink step (or other dangerous step) so we can't stop safeToStop = false; } else { logger.info("skipping policy execution of step [{}] for index [{}] with policy [{}] because ILM is stopping", stepKey == null ? "n/a" : stepKey.getName(), idxMeta.getIndex().getName(), policyName); } } else { lifecycleRunner.maybeRunAsyncAction(clusterState, idxMeta, policyName, stepKey); } } } if (safeToStop && OperationMode.STOPPING == currentMode) { submitOperationModeUpdate(OperationMode.STOPPED); } } } @Override public void offMaster() { this.isMaster = false; cancelJob(); } @Override public String executorName() { return ThreadPool.Names.MANAGEMENT; } private void updatePollInterval(TimeValue newInterval) { this.pollInterval = newInterval; maybeScheduleJob(); } // pkg-private for testing SchedulerEngine getScheduler() { return scheduler.get(); } // pkg-private for testing SchedulerEngine.Job getScheduledJob() { return scheduledJob; } private synchronized void maybeScheduleJob() { if (this.isMaster) { if (scheduler.get() == null) { // don't create scheduler if the node is shutting down if (isClusterServiceStoppedOrClosed() == false) { scheduler.set(new SchedulerEngine(settings, clock)); scheduler.get().register(this); } } // scheduler could be null if the node might be shutting down if (scheduler.get() != null) { scheduledJob = new SchedulerEngine.Job(XPackField.INDEX_LIFECYCLE, new TimeValueSchedule(pollInterval)); scheduler.get().add(scheduledJob); } } } @Override public void clusterChanged(ClusterChangedEvent event) { IndexLifecycleMetadata lifecycleMetadata = event.state().metaData().custom(IndexLifecycleMetadata.TYPE); if (this.isMaster && lifecycleMetadata != null) { triggerPolicies(event.state(), true); } } @Override public void applyClusterState(ClusterChangedEvent event) { if (event.localNodeMaster()) { // only act if we are master, otherwise // keep idle until elected if (event.state().metaData().custom(IndexLifecycleMetadata.TYPE) != null) { policyRegistry.update(event.state()); } } } private void cancelJob() { if (scheduler.get() != null) { scheduler.get().remove(XPackField.INDEX_LIFECYCLE); scheduledJob = null; } } @Override public void triggered(SchedulerEngine.Event event) { if (event.getJobName().equals(XPackField.INDEX_LIFECYCLE)) { logger.trace("job triggered: " + event.getJobName() + ", " + event.getScheduledTime() + ", " + event.getTriggeredTime()); triggerPolicies(clusterService.state(), false); } } public boolean policyExists(String policyId) { return policyRegistry.policyExists(policyId); } /** * executes the policy execution on the appropriate indices by running cluster-state tasks per index. * * If stopping ILM was requested, and it is safe to stop, this will also be done here * when possible after no policies are executed. * * @param clusterState the current cluster state * @param fromClusterStateChange whether things are triggered from the cluster-state-listener or the scheduler */ void triggerPolicies(ClusterState clusterState, boolean fromClusterStateChange) { IndexLifecycleMetadata currentMetadata = clusterState.metaData().custom(IndexLifecycleMetadata.TYPE); if (currentMetadata == null) { return; } OperationMode currentMode = currentMetadata.getOperationMode(); if (OperationMode.STOPPED.equals(currentMode)) { return; } boolean safeToStop = true; // true until proven false by a run policy // loop through all indices in cluster state and filter for ones that are // managed by the Index Lifecycle Service they have a index.lifecycle.name setting // associated to a policy for (ObjectCursor<IndexMetaData> cursor : clusterState.metaData().indices().values()) { IndexMetaData idxMeta = cursor.value; String policyName = LifecycleSettings.LIFECYCLE_NAME_SETTING.get(idxMeta.getSettings()); if (Strings.isNullOrEmpty(policyName) == false) { final LifecycleExecutionState lifecycleState = LifecycleExecutionState.fromIndexMetadata(idxMeta); StepKey stepKey = IndexLifecycleRunner.getCurrentStepKey(lifecycleState); if (OperationMode.STOPPING == currentMode) { if (stepKey != null && IGNORE_STEPS_MAINTENANCE_REQUESTED.contains(stepKey.getName())) { logger.info("waiting to stop ILM because index [{}] with policy [{}] is currently in step [{}]", idxMeta.getIndex().getName(), policyName, stepKey.getName()); if (fromClusterStateChange) { lifecycleRunner.runPolicyAfterStateChange(policyName, idxMeta); } else { lifecycleRunner.runPeriodicStep(policyName, idxMeta); } // ILM is trying to stop, but this index is in a Shrink step (or other dangerous step) so we can't stop safeToStop = false; } else { logger.info("skipping policy execution of step [{}] for index [{}] with policy [{}] because ILM is stopping", stepKey == null ? "n/a" : stepKey.getName(), idxMeta.getIndex().getName(), policyName); } } else { if (fromClusterStateChange) { lifecycleRunner.runPolicyAfterStateChange(policyName, idxMeta); } else { lifecycleRunner.runPeriodicStep(policyName, idxMeta); } } } } if (safeToStop && OperationMode.STOPPING == currentMode) { submitOperationModeUpdate(OperationMode.STOPPED); } } @Override public synchronized void close() { // this assertion is here to ensure that the check we use in maybeScheduleJob is accurate for detecting a shutdown in // progress, which is that the cluster service is stopped and closed at some point prior to closing plugins assert isClusterServiceStoppedOrClosed() : "close is called by closing the plugin, which is expected to happen after " + "the cluster service is stopped"; SchedulerEngine engine = scheduler.get(); if (engine != null) { engine.stop(); } } public void submitOperationModeUpdate(OperationMode mode) { clusterService.submitStateUpdateTask("ilm_operation_mode_update", new OperationModeUpdateTask(mode)); } /** * Method that checks if the lifecycle state of the cluster service is stopped or closed. This * enhances the readability of the code. */ private boolean isClusterServiceStoppedOrClosed() { final State state = clusterService.lifecycleState(); return state == State.STOPPED || state == State.CLOSED; } }
45.961415
138
0.664754
3ec2648c2eeceb7c813cc3ca3d9f3e615634646d
2,911
package de.dfki.nlp.chemspot.amqp; import static de.dfki.nlp.domain.PredictionResult.Section.T; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.dfki.nlp.chemspot.ChemSpotRunner; import de.dfki.nlp.chemspot.QueueAdapterChemSpot; import de.dfki.nlp.domain.ParsedInputText; import de.dfki.nlp.domain.PredictionResult; import de.dfki.nlp.domain.PredictionType; import lombok.extern.slf4j.Slf4j; @Component @Slf4j public class QueueAdapter { @Autowired private ChemSpotRunner chemSpotRunner; @Autowired private ObjectMapper objectMapper; @RabbitListener(queuesToDeclare = @Queue(name = QueueAdapterChemSpot.queueName, durable = "false")) public String processOrder(ParsedInputText payload) throws JsonProcessingException { String docId = payload.getExternalId(); if (docId == null) return objectMapper.writeValueAsString(Collections.emptySet()); Set<PredictionResult> results = new HashSet<>(); log.trace("Parsing {}", docId); // iterate over the text sections for (PredictionResult.Section section : PredictionResult.Section.values()) { String analyzetext = section == T ? payload.getTitle() : payload.getAbstractText(); if (analyzetext == null) continue; results.addAll( detectChemSpot(analyzetext, section, docId).collect(Collectors.toList())); } log.trace("Done parsing {}", docId); return objectMapper.writeValueAsString(results); } private Stream<PredictionResult> detectChemSpot(String analyzetext, PredictionResult.Section section, String externalID) { return chemSpotRunner.parse(analyzetext).stream().map(m -> { PredictionResult predictionResult = new PredictionResult(); predictionResult.setSection(section); predictionResult.setDocumentId(externalID); predictionResult.setInit(m.getStart()); predictionResult.setEnd(m.getEnd()); predictionResult.setAnnotatedText(m.getText()); predictionResult.setDatabaseId(m.getCHID()); /** * SYSTEMATIC, IDENTIFIER, FORMULA, TRIVIAL, ABBREVIATION, FAMILY, MULTIPLE, * UNKNOWN; */ predictionResult.setType(PredictionType.CHEMICAL); predictionResult.setScore(1.0); return predictionResult; }); } }
31.641304
103
0.698042
d0c4f03f3d98a391643ab2473cec4775861f32be
4,852
/* * Copyright 2014 Oleksiy Voronin <[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 net.ninjacat.smooth.utils; import net.ninjacat.smooth.functions.Func; import net.ninjacat.smooth.functions.Procedure; import net.ninjacat.smooth.functions.Provider; /** * An immutable object that contains either a non-null reference to another object or contains nothing, i.e. absent. * It is never {@code null}. * * @param <T> - type of wrapped value */ @SuppressWarnings("unchecked") public class Option<T> { private static final Option<?> ABSENT = new Option(null); private final T ref; Option(final T ref) { this.ref = ref; } /** * Creates a new option that does not hold any value. * * @param <T> Type of optional value. * @return A new empty optional value. */ public static <T> Option<T> absent() { return (Option<T>) ABSENT; } /** * Creates a new option from supplied value. Value can be null. * * @param value Value to wrap into Option * @param <T> Type of optional value. * @return A new optional value. */ public static <T> Option<T> of(final T value) { return new Option<T>(value); } /** * @return {@code true} if this Option is not absent, or {@code false} otherwise. */ public boolean isPresent() { return null != this.ref; } /** * Executes {@link Procedure} if this option has value. * * @param proc Procedure that accepts parameter of the type of the Option */ public void ifPresent(final Procedure<T> proc) { if (isPresent()) { proc.apply(this.ref); } } /** * Returns wrapped value, if this Option is not absent or supplied alternative otherwise. * * @param alternative Alternative value to return if this Option is absent. * @return Wrapped value. */ public T or(final T alternative) { return isPresent() ? this.ref : alternative; } /** * Returns wrapped value if this Option is not absent, otherwise calls supplied {@link Provider} to calculate a new * value. * * @param provider Provider to create an alternative value/ * @return Wrapped or generated value. */ public T orGet(final Provider<T> provider) { return isPresent() ? this.ref : provider.get(); } /** * @return Wrapped value or null if this Option is absent. */ public T orNull() { return isPresent() ? this.ref : null; } /** * Retrieves wrapped value. If this Option is empty, then {@link NullPointerException} will be thrown. * * @return Wrapped value. * @throws NullPointerException if Option is empty. */ public T get() { if (null == this.ref) { throw new NullPointerException("No value"); } else { return this.ref; } } /** * If this option is not empty, its value is transformed with the given Function; otherwise, absent() is returned. * Function is permitted to return null, in this case absent() will be returned. * <p> * If function throws exception, absent() will be returned. * </p> * * @param transform Function {@link Func} to transform value from one type to another. * @param <K> Type of the new value * @return Optional value (or absent Option). */ public <K> Option<K> map(final Func<K, T> transform) { if (isPresent()) { return Try.execute(transform).with(this.ref).get(); } else { return Option.absent(); } } @Override public boolean equals(final Object o) { if (this == o) return true; if (null == o || getClass() != o.getClass()) return false; final Option option = (Option) o; if (null != this.ref ? !this.ref.equals(option.ref) : null != option.ref) return false; return true; } @Override public int hashCode() { return null != this.ref ? this.ref.hashCode() : 0; } @Override public String toString() { if (isPresent()) { return "Option{" + this.ref + '}'; } else { return "Option{ absent }"; } } }
29.053892
119
0.605523
d91fc15396eb992b7fde90177f8f1976b1cd527c
1,466
package ictk.boardgame.chess.io; import java.net.URISyntaxException; import java.net.URL; import java.io.*; import junit.framework.TestCase; /** * Parent class for the PGN tests. */ public abstract class AbstractPGNTest extends TestCase { public AbstractPGNTest(String name) { super(name); } /* protected String dataDir = "ictk/boardgame/chess/io/"; protected static Reader getReaderFromResource(String file) { BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(PGNReaderTest.class.getClassLoader().getResourceAsStream(file))); } catch (RuntimeException e) { throw new RuntimeException("Failed to load + '" + file + "'.", e); } return reader; } */ //UTILITY////////////////////////////////////////////////////////////////// /** load the local test resource file by leveraging the classpath. * This should grab the file from where the tests are being run. */ public File getTestFile (String filename) throws URISyntaxException { File file = null; if (file == null || !file.exists()) { URL r = this.getClass().getResource(filename); assertNotNull("Couldn't find '" + filename + "' on classpath", r); file = new File(r.toURI()); } assertNotNull("Null resource file: '" + filename + "'", file); assertTrue("Couldn't read resource: '" + filename + "'", file.exists()); return file; } }
28.745098
124
0.621419
e578148a48e5711f9d43dbdf5d999e112ddb3608
4,606
package rocks.appconcept.testing.perf; /** * Created by imeta on 18-Dec-16. */ import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.management.ThreadMXBean; import java.util.HashMap; import java.util.Map; /** CPU usage monitor in pure Java Goal: get CPU usage of whole java application (in percents) using pure Java. Steps to achieve goal: Assumptions: Lets assume we are gathering CPU load each second on 4 cores computer. Step 1 : calculate total time available to CPU In our case: 1 sec * number of cores (4) = 4 sec. Well, if you can't accept that from one real world second we get four, what probably is a legitimate concern, then think that each second we have 4 "units" of CPU resources. Step 2: calculate how much of CPU time your application (all application threads) used during last second. For example we've got 0.43 sec, in other words, 0.43 units of CPU resources. Step 3: try to remember what you've been taught at elementary school: 4 = 100% 0.43 = X % So X = (0.43 * 100) / 4 == 10.75 % of all CPU power during last second. Step 4: implement. */ public class CpuProfiler extends Thread { private final long interval; private final double processorTimeAvailable; private boolean continueProfiling = true; private static final int MILLISEC_IN_SEC = 1000; private static final int NANOSEC_IN_SEC = 1000000000; private ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); private Map<Long, Stat> threadStats = new HashMap<Long, Stat>(); private UpdateHandler updateHandler; private static class Stat { long prevCpuTime; long currCpuTime; } /** CPU load percentage will be passed to onUpdate method */ public interface UpdateHandler { /** * @param cpuLoad * CPU load in percents. */ void onUpdate(double cpuLoad); } /** * Constructor. * * @param interval * how often update stats, in milliseconds. */ public CpuProfiler(long interval) { super("Thread timing monitor"); this.interval = interval; setDaemon(true); OperatingSystemMXBean osMXBean = ManagementFactory.getOperatingSystemMXBean(); int processorsCount = osMXBean.getAvailableProcessors(); processorTimeAvailable = (double) this.interval / MILLISEC_IN_SEC * processorsCount; } /** Thread meat. */ @Override public void run() { while (continueProfiling) { updateStats(); double usedCpu = (double) getUsedCpuTimeForLastPeriod() / NANOSEC_IN_SEC; double cpuLoad = (double) usedCpu * 100 / processorTimeAvailable; if (updateHandler != null) { updateHandler.onUpdate(cpuLoad); } try { Thread.sleep(interval); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Update stats, current monitor thread is also included into stats. */ private void updateStats() { long[] ids = threadMXBean.getAllThreadIds(); for (long id : ids) { long cpuTime = threadMXBean.getThreadCpuTime(id); if (cpuTime == -1)// thread is not alive { threadStats.remove(id); continue; } Stat stat = threadStats.get(id); if (stat == null)// thread is not monitored yet { stat = new Stat(); stat.prevCpuTime = cpuTime; stat.currCpuTime = cpuTime; threadStats.put(id, stat); } else // thread is already monitored { stat.prevCpuTime = stat.currCpuTime; stat.currCpuTime = cpuTime; } } } /** Get total used CPU time in nanoseconds for last interval. */ private long getUsedCpuTimeForLastPeriod() { long time = 0; for (Stat threadStat : threadStats.values()) { time += threadStat.currCpuTime - threadStat.prevCpuTime; } return time; } public void setUpdateHandler(UpdateHandler updateHandler) { this.updateHandler = updateHandler; } public void stopProfiling() { this.continueProfiling = false; } }
28.968553
227
0.597916
acab2b6a3cc8e764057d0d50e4555f0af9fe25e3
556
package com.icepoint.base.web.entp.service; import com.icepoint.base.api.entity.QueryCondition; import com.icepoint.base.web.basic.service.CrudService; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional(propagation = Propagation.SUPPORTS) public interface QueryConditionService extends CrudService<QueryCondition, Long> { List<String> listName(); List<QueryCondition> getListByName(String name); Integer deleted(Long id); }
30.888889
82
0.814748
243ff564b8e7b7f8cc092e5dcf70c62c2114ab0b
415
package chapter21.part2.section2.practice1; /** * @author xuyong * @since 2019-03-21 00:01 **/ public class Practice1 implements Runnable { public Practice1() { System.out.println("started"); } @Override public void run() { for (int i = 0; i < 3; i++) { System.out.print("xyong "); Thread.yield(); } System.out.println("ended"); } }
18.863636
44
0.544578
72d955e9e277a90388b426013fdf776e42ed6b5c
648
public class HeapSortThread extends Thread { private int[] inputData; private int[] result; public void run(){ try { this.result = HeapSort.sort(inputData, inputData.length); } catch(ThreadDeath td) { // timeout this.result = null; System.out.println(toString() + "Timed out"); System.out.println("Running secondary..."); } } public HeapSortThread(int[] inputData) { super(); this.inputData = inputData; this.result = null; } public int[] getResult() { return this.result; } public int getMemCount() { return HeapSort.getMemCount(); } public String toString() { return "Variant 1 (HeapSort) "; } }
19.058824
60
0.666667
78db8364b0849d2a2978e2fbf9478116bdd428f6
1,726
/* * [y] hybris Platform * * Copyright (c) 2000-2015 hybris AG * All rights reserved. * * This software is the confidential and proprietary information of hybris * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with hybris. * * */ package com.osfglobal.hybris.emarsys.fulfilmentprocess.actions.order; import de.hybris.platform.orderprocessing.model.OrderProcessModel; import de.hybris.platform.ordersplitting.model.ConsignmentProcessModel; import de.hybris.platform.processengine.action.AbstractSimpleDecisionAction; import org.apache.log4j.Logger; /** * */ public class SubprocessesCompletedAction extends AbstractSimpleDecisionAction<OrderProcessModel> { private static final Logger LOG = Logger.getLogger(SubprocessesCompletedAction.class); @Override public Transition executeAction(final OrderProcessModel process) { LOG.info("Process: " + process.getCode() + " in step " + getClass()); LOG.info("Process: " + process.getCode() + " is checking for " + process.getConsignmentProcesses().size() + " subprocess results"); for (final ConsignmentProcessModel subProcess : process.getConsignmentProcesses()) { if (!subProcess.isDone()) { LOG.info("Process: " + process.getCode() + " found subprocess " + subProcess.getCode() + " incomplete -> wait again!"); return Transition.NOK; } LOG.info("Process: " + process.getCode() + " found subprocess " + subProcess.getCode() + " complete ..."); } LOG.info("Process: " + process.getCode() + " found all subprocesses complete"); return Transition.OK; } }
34.52
135
0.72248
f684b9b74bf9d68a8d3f38e12d1c5907031df331
1,009
package br.com.zupacademy.vinicius.casadocodigo.livro.detalhar; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.zupacademy.vinicius.casadocodigo.livro.Livro; import br.com.zupacademy.vinicius.casadocodigo.livro.LivroRepository; @RestController @RequestMapping("/detalhar") public class DetalherLivroController { @Autowired private LivroRepository livroRepository; @GetMapping("/{id}") public ResponseEntity<?> detalhar(@PathVariable Long id) { Optional<Livro> livro = livroRepository.findById(id); if (livro.isPresent()) { return ResponseEntity.ok(new DetalharLivroDTO(livro.get())); } return ResponseEntity.notFound().build(); } }
29.676471
69
0.80773
89ec5a8ec9a5c766345bdbb2401d64476cb137d9
923
package cn.fantasticmao.pokemon.web.repoistory; import cn.fantasticmao.pokemon.web.SpringTest; import cn.fantasticmao.pokemon.web.domain.Ability; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import javax.annotation.Resource; import java.util.List; /** * AbilityRepositoryTest * * @author fantasticmao * @since 2018/8/29 */ public class AbilityRepositoryTest extends SpringTest { @Resource private AbilityRepository abilityRepository; @Test public void findByNameZh() { List<Ability> abilityList = abilityRepository.findByNameZh("茂盛"); Assertions.assertNotNull(abilityList); Assertions.assertEquals(1, abilityList.size()); } @Test public void find() { List<Ability> abilityList = abilityRepository.find(0, 20); Assertions.assertNotNull(abilityList); Assertions.assertEquals(20, abilityList.size()); } }
26.371429
73
0.725894
e11102342e9d219855eb5075bb12f74c40f07d67
407
package com.roxiemobile.networkingapi.network.rest.response.error.nested; public class ConnectionException extends Exception { // MARK: - Construction /** * Construct a new instance of {@code ConnectionException}. */ public ConnectionException(Throwable cause) { super(cause); } // MARK: - Constants private static final long serialVersionUID = 6805154194145428738L; }
22.611111
73
0.717445
e12ae3a8bc6d99f15d27c7341c66f15efab9dd67
304
package com.concurnas.lang.precompiled; import java.util.ArrayList; public class HoldingAStaticVarWithNonFinal { public static final int CL_INVALID_VALUE = -30; public static int CL_INVALID_VALUE2 = 100; public int getInvalidValue() { return HoldingAStaticVarWithNonFinal.CL_INVALID_VALUE; } }
25.333333
56
0.805921
783f844a31c3aec0770955ac8e2e0db00d219050
1,748
package pl.edu.agh.to.busregistration.admin.routes; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import pl.edu.agh.to.busregistration.admin.buses.Bus; import java.util.List; import java.util.Optional; @Controller @RequestMapping("/routes") public class RouteController { private RouteService routeService; @Autowired public RouteController(RouteService routeService) { this.routeService = routeService; } @GetMapping public String getAllRoutes(Model model) { List<Route> routes = routeService.getAllRoutes(); model.addAttribute("routes", routes); return "admin/routes/routes"; } @GetMapping("/add") public String showRouteForm(Model model) { Route route = new Route(); model.addAttribute("route", route); model.addAttribute("update", false); return "admin/routes/route-form"; } @PostMapping("/add") public String addRoute(@ModelAttribute("route") Route route) { routeService.saveRoute(route); return "redirect:/routes"; } @GetMapping("/update") public String updateRouteForm(@RequestParam("id") int routeId, Model model) { Optional<Route> route = routeService.findById(routeId); route.ifPresent(b -> model.addAttribute("route", route)); model.addAttribute("update", true); return "admin/routes/route-form"; } @GetMapping("/delete/{routeId}") public String deleteRoute(@PathVariable("routeId") int routeId) { routeService.deleteRoute(routeId); return "redirect:/routes"; } }
27.746032
81
0.686499
ca1c0bead318a05c2dc13b90eb9e578fdf1ca5d6
16,117
/* * Copyright 2013 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 ratpack.codahale.metrics; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.CsvReporter; import com.codahale.metrics.JmxReporter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.annotation.Timed; import com.codahale.metrics.health.HealthCheckRegistry; import com.codahale.metrics.annotation.Metered; import com.codahale.metrics.jvm.GarbageCollectorMetricSet; import com.codahale.metrics.jvm.MemoryUsageGaugeSet; import com.codahale.metrics.jvm.ThreadStatesGaugeSet; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.matcher.Matchers; import com.google.inject.name.Names; import ratpack.codahale.metrics.internal.ConsoleReporterProvider; import ratpack.codahale.metrics.internal.CsvReporterProvider; import ratpack.codahale.metrics.internal.GaugeTypeListener; import ratpack.codahale.metrics.internal.JmxReporterProvider; import ratpack.codahale.metrics.internal.MeteredMethodInterceptor; import ratpack.codahale.metrics.internal.RequestTimingHandler; import ratpack.codahale.metrics.internal.TimedMethodInterceptor; import ratpack.guice.HandlerDecoratingModule; import ratpack.guice.internal.GuiceUtil; import ratpack.handling.Handler; import ratpack.path.internal.TokenPathBinder; import ratpack.func.Action; import java.io.File; /** * An extension module that provides support for Coda Hale's Metrics. * <p> * To use it one has to register the module and enable the required functionality by chaining the various configuration * options. For example, to enable the capturing and reporting of metrics to {@link ratpack.codahale.metrics.CodaHaleMetricsModule#jmx()} * one would write: (Groovy DSL) * </p> * <pre class="groovy-ratpack-dsl"> * import ratpack.codahale.metrics.CodaHaleMetricsModule * import static ratpack.groovy.Groovy.ratpack * * ratpack { * modules { * register new CodaHaleMetricsModule().jmx() * } * } * </pre> * <p> * To enable the capturing and reporting of metrics to JMX and the {@link ratpack.codahale.metrics.CodaHaleMetricsModule#console()}, one would * write: (Groovy DSL) * </p> * <pre class="groovy-ratpack-dsl"> * import ratpack.codahale.metrics.CodaHaleMetricsModule * import static ratpack.groovy.Groovy.ratpack * * ratpack { * modules { * register new CodaHaleMetricsModule().jmx().console() * } * } * </pre> * <p> * This module supports both metric collection and health checks. For further details on both please see * {@link ratpack.codahale.metrics.CodaHaleMetricsModule#metrics()} and {@link ratpack.codahale.metrics.CodaHaleMetricsModule#healthChecks()} * respectively. By default metric collection is not enabled but health checks are. * </p> * <p> * <b>It is important that this module is registered first in the modules list to ensure that request metrics are as accurate as possible.</b> * </p> * * @see <a href="http://metrics.codahale.com/" target="_blank">Coda Hale's Metrics</a> */ public class CodaHaleMetricsModule extends AbstractModule implements HandlerDecoratingModule { private boolean reportMetricsToJmx; private boolean reportMetricsToConsole; private File csvReportDirectory; private boolean healthChecksEnabled = true; private boolean jvmMetricsEnabled; private boolean metricsEnabled; private boolean isMetricsEnabled() { return metricsEnabled || jvmMetricsEnabled || reportMetricsToConsole || reportMetricsToJmx || csvReportDirectory != null; } @Override protected void configure() { if (isMetricsEnabled()) { final MetricRegistry metricRegistry = new MetricRegistry(); bind(MetricRegistry.class).toInstance(metricRegistry); MeteredMethodInterceptor meteredMethodInterceptor = new MeteredMethodInterceptor(); requestInjection(meteredMethodInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(Metered.class), meteredMethodInterceptor); TimedMethodInterceptor timedMethodInterceptor = new TimedMethodInterceptor(); requestInjection(timedMethodInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(Timed.class), timedMethodInterceptor); GaugeTypeListener gaugeTypeListener = new GaugeTypeListener(metricRegistry); bindListener(Matchers.any(), gaugeTypeListener); if (reportMetricsToJmx) { bind(JmxReporter.class).toProvider(JmxReporterProvider.class).asEagerSingleton(); } if (reportMetricsToConsole) { bind(ConsoleReporter.class).toProvider(ConsoleReporterProvider.class).asEagerSingleton(); } if (csvReportDirectory != null) { bind(File.class).annotatedWith(Names.named(CsvReporterProvider.CSV_REPORT_DIRECTORY)).toInstance(csvReportDirectory); bind(CsvReporter.class).toProvider(CsvReporterProvider.class).asEagerSingleton(); } } if (healthChecksEnabled) { bind(HealthCheckRegistry.class).in(Singleton.class); bind(HealthCheckEndpoint.class).toInstance(new HealthCheckEndpoint(new TokenPathBinder("health-check/:name?", true))); } } /** * Enables the collection of metrics. * <p> * To enable one of the built in metric reporters please chain the relevant reporter configuration * e.g. {@link ratpack.codahale.metrics.CodaHaleMetricsModule#jmx()}, {@link ratpack.codahale.metrics.CodaHaleMetricsModule#console()}. * </p> * <p> * By default {@link com.codahale.metrics.Timer} metrics are collected for all requests received. The module adds a * {@link RequestTimingHandler} to the handler chain <b>before</b> any user handlers. This means that response times do not take any * framework overhead into account and purely the amount of time spent in handlers. It is important that the module is * registered first in the modules list to ensure that <b>all</b> handlers are included in the metric. * </p> * <p> * Additional custom metrics can be registered with the provided {@link MetricRegistry} instance * </p> * <p> * Example custom metrics: (Groovy DSL) * </p> * <pre class="groovy-ratpack-dsl"> * import ratpack.codahale.metrics.CodaHaleMetricsModule * import com.codahale.metrics.MetricRegistry * import static ratpack.groovy.Groovy.ratpack * * ratpack { * modules { * register new CodaHaleMetricsModule().jmx() * } * * handlers { MetricRegistry metricRegistry -> * handler { * metricRegistry.meter("my custom meter").mark() * render "" * } * } * } * </pre> * <p> * Custom metrics can also be added via the Metrics annotations ({@link Metered}, {@link Timed} and {@link com.codahale.metrics.annotation.Gauge}) * to any Guice injected classes. * </p> * * @return this {@code CodaHaleMetricsModule} * @see <a href="http://metrics.codahale.com/getting-started/" target="_blank">Coda Hale Metrics - Getting Started</a> * @see ratpack.codahale.metrics.CodaHaleMetricsModule#jmx() * @see ratpack.codahale.metrics.CodaHaleMetricsModule#console() * @see CodaHaleMetricsModule#csv(java.io.File) */ public CodaHaleMetricsModule metrics() { return metrics(true); } /** * Enables or disables the collecting of metrics. * * @param enabled If the metric collection should be enabled. * @return this {@code CodaHaleMetricsModule} * @see ratpack.codahale.metrics.CodaHaleMetricsModule#metrics() */ public CodaHaleMetricsModule metrics(boolean enabled) { this.metricsEnabled = enabled; return this; } /** * Enables the automatic registering of health checks. * <p> * Health checks verify that application components or responsibilities are performing as expected. * <p> * To create a health check simply create a class that extends {@link NamedHealthCheck} and Bind it with Guice. When * health checks are enabled then all bound classes of type NamedHealthCheck will automatically be registered with the * {@link HealthCheckRegistry}. * <p> * Health checks can be run using {@link com.codahale.metrics.health.HealthCheckRegistry#runHealthChecks()} * or by using the provided {@link HealthCheckEndpoint}. Using HealthCheckEndpoint provides {@link ratpack.path.internal.PathHandler} * handlers with paths /health-check and /health-check/:name that can be inserted anywhere in the handler chain. * <p> * Example health checks: (Groovy DSL) * </p> * <pre class="groovy-ratpack-dsl"> * import com.codahale.metrics.health.HealthCheck * import com.codahale.metrics.health.HealthCheckRegistry * import ratpack.codahale.metrics.CodaHaleMetricsModule * import ratpack.codahale.metrics.HealthCheckEndpoint * import ratpack.codahale.metrics.NamedHealthCheck * import static ratpack.groovy.Groovy.ratpack * * class FooHealthCheck extends NamedHealthCheck { * * protected HealthCheck.Result check() throws Exception { * // perform the health check logic here and return HealthCheck.Result.healthy() or HealthCheck.Result.unhealthy("Unhealthy message") * HealthCheck.Result.healthy() * } * * def String getName() { * "foo_health_check" * } * } * * ratpack { * modules { * register new CodaHaleMetricsModule() * bind FooHealthCheck // if you don't bind the health check with Guice it will not be automatically registered * } * * handlers { * // Use the default health check handler to run health checks. /health-check will run all health checks and /health-check/:name will run individual checks * handler(registry.get(HealthCheckEndpoint)) * * // Use the default health check handler wrapped in a Prefix to run health checks. Health checks can be run using /admin/health-check and /admin/health-check/:name * prefix("admin") { * handler(registry.get(HealthCheckEndpoint)) * } * * // Use your own handlers to run health checks * get("healthChecks") { HealthCheckRegistry healthCheckRegistry -> * render healthCheckRegistry.runHealthChecks().toString() * } * * get("healthCheck/:name") { HealthCheckRegistry healthCheckRegistry -> * render healthCheckRegistry.runHealthCheck(pathTokens.get("name")).toString() * } * } * } * </pre> * * @return this {@code CodaHaleMetricsModule} * @see <a href="http://metrics.codahale.com/manual/healthchecks/" target="_blank">Coda Hale Metrics - Health Checks</a> * @see HealthCheckEndpoint * @see com.codahale.metrics.health.HealthCheckRegistry#runHealthChecks() * @see HealthCheckRegistry#runHealthCheck(String) * @see HealthCheckRegistry#runHealthChecks(java.util.concurrent.ExecutorService) */ public CodaHaleMetricsModule healthChecks() { return healthChecks(true); } /** * Enables or disables the automatic registering of health checks. * * @param enabled If the automatic registering of health checks should be enabled. * @return this {@code CodaHaleMetricsModule} * @see CodaHaleMetricsModule#healthChecks() */ public CodaHaleMetricsModule healthChecks(boolean enabled) { this.healthChecksEnabled = enabled; return this; } /** * Enable the collection of JVM metrics. * <p> * The JVM Gauges and Metric Sets provided by Coda Hale's Metrics will be registered to this module's Metric Registry. * * @return this {@code CodaHaleMetricsModule} * @see <a href="http://metrics.codahale.com/manual/jvm/" target="_blank">Coda Hale Metrics - JVM Instrumentation</a> */ public CodaHaleMetricsModule jvmMetrics() { return jvmMetrics(true); } /** * Enables or disables the collecting of JVM metrics. * * @param enabled If JVM metric collection should be enabled. * @return this {@code CodaHaleMetricsModule} * @see CodaHaleMetricsModule#jvmMetrics() */ public CodaHaleMetricsModule jvmMetrics(boolean enabled) { this.jvmMetricsEnabled = enabled; return this; } /** * Enable the reporting of metrics via JMX. The collecting of metrics will also be enabled. * * @return this {@code CodaHaleMetricsModule} * @see <a href="http://metrics.codahale.com/getting-started/#reporting-via-jmx" target="_blank">Coda Hale Metrics - Reporting Via JMX</a> * @see ratpack.codahale.metrics.CodaHaleMetricsModule#console() * @see CodaHaleMetricsModule#csv(java.io.File) */ public CodaHaleMetricsModule jmx() { return jmx(true); } /** * Enables or disables the reporting of metrics via JMX. * * @param enabled If JMX metric reporting should be enabled. * @return this {@code CodaHaleMetricsModule} * @see CodaHaleMetricsModule#jmx() */ public CodaHaleMetricsModule jmx(boolean enabled) { this.reportMetricsToJmx = enabled; return this; } /** * Enable the reporting of metrics to the Console. The collecting of metrics will also be enabled. * * @return this {@code CodaHaleMetricsModule} * @see <a href="http://metrics.codahale.com/manual/core/#man-core-reporters-console" target="_blank">Coda Hale Metrics - Console Reporting</a> * @see ratpack.codahale.metrics.CodaHaleMetricsModule#jmx() * @see CodaHaleMetricsModule#csv(java.io.File) */ public CodaHaleMetricsModule console() { return console(true); } /** * Enables or disables the reporting of metrics to the Console. * * @param enabled If Console metric reporting should be enabled. * @return this {@code CodaHaleMetricsModule} * @see ratpack.codahale.metrics.CodaHaleMetricsModule#console() */ public CodaHaleMetricsModule console(boolean enabled) { this.reportMetricsToConsole = enabled; return this; } /** * Enable the reporting of metrics to a CSV file. The collecting of metrics will also be enabled. * * @param reportDirectory The directory in which to create the CSV report files. * @return this {@code CodaHaleMetricsModule} * @see <a href="http://metrics.codahale.com/manual/core/#man-core-reporters-csv" target="_blank">Coda Hale Metrics - CSV Reporting</a> * @see ratpack.codahale.metrics.CodaHaleMetricsModule#jmx() * @see ratpack.codahale.metrics.CodaHaleMetricsModule#console() */ public CodaHaleMetricsModule csv(File reportDirectory) { if (reportDirectory == null) { throw new IllegalArgumentException("reportDirectory cannot be null"); } csvReportDirectory = reportDirectory; return this; } @Override public Handler decorate(Injector injector, Handler handler) { if (healthChecksEnabled) { final HealthCheckRegistry registry = injector.getInstance(HealthCheckRegistry.class); GuiceUtil.eachOfType(injector, TypeLiteral.get(NamedHealthCheck.class), new Action<NamedHealthCheck>() { public void execute(NamedHealthCheck healthCheck) throws Exception { registry.register(healthCheck.getName(), healthCheck); } }); } if (jvmMetricsEnabled) { final MetricRegistry metricRegistry = injector.getInstance(MetricRegistry.class); metricRegistry.registerAll(new GarbageCollectorMetricSet()); metricRegistry.registerAll(new ThreadStatesGaugeSet()); metricRegistry.registerAll(new MemoryUsageGaugeSet()); } if (isMetricsEnabled()) { return new RequestTimingHandler(handler); } else { return handler; } } }
39.697044
172
0.727431
1147d95260f72d92715fb574ccd2f683932c327f
2,299
package com.xiaochu.dao; import java.util.List; import java.util.Map; import org.hibernate.Criteria; import org.springframework.stereotype.Component; import com.base.dao.BaseDao; /** * @author zhaodongchao * 2016年9月16日 */ @Component public class UserEntityDao extends BaseDao{ /** * 查询系统中所有的角色 * @return * @throws Exception */ public List<Map<String,String>> listRoles()throws Exception{ String sql = "select cr.role_id,cr.role_name,cr.role_code,cr.description from hr.cf_role cr "; return getSession().createSQLQuery(sql).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list(); } public List<Map<String,String>> listAutoritysByRoleId(String roleId)throws Exception{ String sql = "select ca.authority_id," + "ca.authority_name," + "ca.operation_uri," + "ca.descriptions " + "from hr.cf_authority ca " + "inner join hr.cf_role_authority cra on cra.authority_id = ca.authority_id " + "where cra.role_id =:roleId " ; return getSession().createSQLQuery(sql).setParameter("roleId", roleId).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list(); } public Map<String,Object> findUserByName(String username)throws Exception{ String sql = "select cu.user_id,cu.login_name,cu.login_password,cu.real_name,cu.selfdeclare," + "cu.city,cu.address,cu.age,cu.sex,cu.birthday,cu.telphone ,cu.email," + "cu.create_time,cu.login_count,cu.last_login_time,cu.is_lock," + "cu.is_expired,cu.expired_time " + "from hr.cf_user cu " + "where cu.login_name=:username" ; return (Map<String, Object>) getSession().createSQLQuery(sql).setParameter("username", username).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list().get(0); } public List<Map<String,String>> findRolesByUserId(String userId)throws Exception{ String sql = " select cr.role_id,cr.role_name,cr.role_code,cr.description "+ " from hr.cf_role cr "+ " inner join hr.cf_user_role cur on cr.role_id = cur.role_id "+ " where cur.user_id =:userId "; return getSession().createSQLQuery(sql).setParameter("userId", userId).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list(); } }
45.078431
168
0.686385
bd59ec32379fd8f2e055841519f2f5391c87c2c1
495
package com.lajospolya.spotifyapiwrapper.response; import java.util.List; /** * @author Lajos Polya * Represent the response of GetRecommendationGenres as described at * https://developer.spotify.com/documentation/web-api/reference-beta/ */ public class RecommendationGenres { List<String> genres; public List<String> getGenres() { return genres; } public void setGenres(List<String> genres) { this.genres = genres; } }
20.625
71
0.662626
7a395f31c261643728a8239e4967055b789ff837
6,893
/* * __ .__ .__ ._____. * _/ |_ _______ __|__| ____ | | |__\_ |__ ______ * \ __\/ _ \ \/ / |/ ___\| | | || __ \ / ___/ * | | ( <_> > <| \ \___| |_| || \_\ \\___ \ * |__| \____/__/\_ \__|\___ >____/__||___ /____ > * \/ \/ \/ \/ * * Copyright (c) 2006-2011 Karsten Schmidt * * This library 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 2.1 of the License, or (at your option) any later version. * * http://creativecommons.org/licenses/LGPL/2.1/ * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ package toxi.sim.dla; import toxi.geom.Vec3D; import toxi.util.datatypes.BiasedFloatRange; public class DLAConfiguration { protected float snapDistance = 1.8f; protected float snapDistanceSquared = snapDistance * snapDistance; protected float curveAttachDistance = 2; protected float curveAttachDistanceSquared = curveAttachDistance * curveAttachDistance; protected float spawnRadius = 12; protected float escapeRadius = 36; protected float particleRadius = 0.25f; protected float stickiness = 0.1f; protected float curveAlign = 0.74f; protected float curveSpeed = 0.00045f; protected float searchSpeed = snapDistance * 0.66f; protected float particleSpeed = 0.001f; protected double guideLineDensity = 0.1; protected float continuousGrowthRatio = 0.1f; protected Vec3D growthScale = new Vec3D(1, 1, 1); protected BiasedFloatRange growthBiasRange = new BiasedFloatRange(0, 1, 0, 1); public DLAConfiguration() { } public float getContinuousGrowthBias() { return growthBiasRange.getBias(); } public float getContinuousGrowthCoeff() { return growthBiasRange.pickRandom(); } /** * @return the continuousGrowthRatio */ public float getContinuousGrowthRatio() { return continuousGrowthRatio; } /** * @return the curveAlign */ public float getCurveAlign() { return curveAlign; } /** * @return the curveAttachDistance */ public float getCurveAttachDistance() { return curveAttachDistance; } public float getCurveAttachDistanceSquared() { return curveAttachDistanceSquared; } /** * @return the curveSpeed */ public float getCurveSpeed() { return curveSpeed; } /** * @return the escapeRadius */ public float getEscapeRadius() { return escapeRadius; } public Vec3D getGrowthScale() { return growthScale; } /** * @return the guideLineDensity */ public double getGuideLineDensity() { return guideLineDensity; } /** * @return the particleRadius */ public float getParticleRadius() { return particleRadius; } /** * @return the particleSpeed */ public float getParticleSpeed() { return particleSpeed; } /** * @return the searchSpeed */ public float getSearchSpeed() { return searchSpeed; } /** * @return the snapDistance */ public float getSnapDistance() { return snapDistance; } public float getSnapDistanceSquared() { return snapDistanceSquared; } /** * @return the spawnRadius */ public float getSpawnRadius() { return spawnRadius; } /** * @return the stickiness */ public float getStickiness() { return stickiness; } /** * @param bias * @param sd */ public void setContinuousGrowthBias(float bias, float sd) { growthBiasRange.setBias(bias); growthBiasRange.setStandardDeviation(sd); } /** * @param continousGrowthRatio * the continuousGrowthRatio to set */ public void setContinuousGrowthRatio(float continousGrowthRatio) { this.continuousGrowthRatio = continousGrowthRatio; } /** * @param curveAlign * the curveAlign to set */ public void setCurveAlign(float curveAlign) { this.curveAlign = curveAlign; } /** * @param curveAttachDistance * the curveAttachDistance to set */ public void setCurveAttachDistance(float curveAttachDistance) { this.curveAttachDistance = curveAttachDistance; } /** * @param curveSpeed * the curveSpeed to set */ public void setCurveSpeed(float curveSpeed) { this.curveSpeed = curveSpeed; } /** * @param escapeRadius * the escapeRadius to set */ public void setEscapeRadius(float escapeRadius) { this.escapeRadius = escapeRadius; } /** * @param growthScale * the growthScale to set */ public void setGrowthScale(Vec3D growthScale) { this.growthScale = growthScale; } /** * @param guideLineDensity * the guideLineDensity to set */ public void setGuideLineDensity(double guideLineDensity) { this.guideLineDensity = guideLineDensity; } /** * @param particleRadius * the particleRadius to set */ public void setParticleRadius(float particleRadius) { this.particleRadius = particleRadius; } /** * @param particleSpeed * the particleSpeed to set */ public void setParticleSpeed(float particleSpeed) { this.particleSpeed = particleSpeed; } /** * @param searchSpeed * the searchSpeed to set */ public void setSearchSpeed(float searchSpeed) { this.searchSpeed = searchSpeed; } /** * @param snapDistance * the snapDistance to set */ public void setSnapDistance(float snapDistance) { this.snapDistance = snapDistance; } /** * @param spawnRadius * the spawnRadius to set */ public void setSpawnRadius(float spawnRadius) { this.spawnRadius = spawnRadius; } /** * @param stickiness * the stickiness to set */ public void setStickiness(float stickiness) { this.stickiness = stickiness; } }
24.617857
78
0.605977
90ba959a094fb87e00ce49ec90ab555774264810
652
package wicket.in.action.chapter13.dbdiscounts.web.model; import java.util.Iterator; import org.apache.wicket.markup.repeater.util.ModelIteratorAdapter; import org.apache.wicket.model.IModel; import wicket.in.action.chapter13.dbdiscounts.domain.DomainObject; public class DomainModelIteratorAdaptor<T> extends ModelIteratorAdapter { public DomainModelIteratorAdaptor( Iterator<? extends DomainObject> delegate) { super(delegate); } @SuppressWarnings("unchecked") @Override protected IModel model(Object object) { DomainObject domainObject = (DomainObject) object; return new DomainObjectModel(domainObject); } }
26.08
67
0.782209
f1e908cb046fcc1b8268bc1fcd53da6bcdb1088f
1,540
/* * Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften * All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ch.icclab.cyclops.services.iaas.openstack.model; /** * <b>POJO Object</b><p/> * Author: Srikanta * Created on: 16-Jan-15 * Description: POJO class for representing the response for an incoming api request * <p/> * Change Log * Name Date Comments */ public class Response { private String timestamp; private String status; private String message; public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
26.551724
84
0.664286
d9dfdfbcb91fa133a516fb2358ee28d61e5d4efb
1,570
package model; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; /* GameObject * This class represent all of the object present in the scene * (Tiles, Player, Enemy, Item Drop) */ public abstract class GameObject { private int id; private IntegerProperty coordXProperty; private IntegerProperty coordYProperty; private int width; private int height; private Hitbox hitbox; public GameObject(int id, int x, int y, int width, int height) { this.id = id; this.coordXProperty = new SimpleIntegerProperty(x); this.coordYProperty = new SimpleIntegerProperty(y); this.width = width; this.height = height; } public void setCoordXProperty(int x) { this.coordXProperty.setValue(x); } public void setCoordYProperty(int y) { this.coordYProperty.setValue(y); } public final IntegerProperty coordXProperty() { return this.coordXProperty; } public final IntegerProperty coordYProperty() { return this.coordYProperty; } public int getWidth() { return this.width; } public int getHeight() { return this.height; } public Hitbox getHitbox() { return this.hitbox; } abstract public void removeHitbox(); abstract public void changeHitbox(); public void setHitbox() { this.hitbox = new Hitbox(this.coordXProperty, this.coordYProperty, width, height, this); } public int getId() { return id; } }
23.432836
93
0.657325
7b013c66c7648f78ca5b8382d7843ef4ad440932
566
package com.tuling.dynamicproxy.anno; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Created by smlz on 2020/3/31. */ public class AngelProxyInterceptor { private Object targetObj; public AngelProxyInterceptor(Object targetObj) { this.targetObj = targetObj; } public Object invoke(Method method,Object[] args ) throws InvocationTargetException, IllegalAccessException { System.out.println("执行方法之前"); Object result = method.invoke(targetObj,args); System.out.println("执行目标方法之后"); return result; } }
21.769231
110
0.765018
9924a850963f4f36e3043a7dc38ef8b52909b019
502
package io.flowing.retail.order_validation.dto; public class Item { private String articleId; private int amount; public String getArticleId() { return articleId; } public void setArticleId(String articleId) { this.articleId = articleId; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } @Override public String toString() { return "Item [articleId=" + articleId + ", amount=" + amount + "]"; } }
20.08
71
0.665339
098dbff42a35c32574124375585862a9fc70a6b8
2,250
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * 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.jbpm.workbench.pr.backend.server; import java.util.Map; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.dashbuilder.dataset.DataSet; import org.dashbuilder.dataset.DataSetGenerator; import org.dashbuilder.dataset.def.DataSetDef; import org.dashbuilder.dataset.def.DataSetDefRegistry; import org.jbpm.workbench.pr.model.ProcessDefinitionDataSetProviderType; import org.uberfire.commons.services.cdi.Startup; import static org.jbpm.workbench.pr.model.ProcessDefinitionDataSetConstants.*; @Startup @ApplicationScoped public class ProcessDefinitionDataSetGenerator implements DataSetGenerator { @Inject protected DataSetDefRegistry dataSetDefRegistry; protected DataSetDef dataSetdef = ProcessDefinitionDataSetDefBuilder.get() .uuid(PROCESS_DEFINITION_DATASET) .generatorClass(ProcessDefinitionDataSetGenerator.class.getName()) .name(PROCESS_DEFINITION_DATASET_NAME) .label(COL_ID_PROCESSNAME) .label(COL_ID_PROCESSVERSION) .label(COL_ID_PROJECT) .label(COL_ID_PROCESSDEF) .label(COL_DYNAMIC) .buildDef(); @PostConstruct protected void init() { dataSetdef.setProvider(new ProcessDefinitionDataSetProviderType()); dataSetdef.setPublic(false); dataSetDefRegistry.registerDataSetDef(dataSetdef); } @Override public DataSet buildDataSet(Map<String, String> params) { return null; } public DataSetDef getDataSetDef() { return dataSetdef; } }
33.58209
78
0.742667
7bfeeacfefc5570623b4c595b26107d4b1d90bb3
1,133
package processing.utility; import java.util.Date; /** * Class Representing a Timestamp * * @author Ahmed Zaheer Dadarkar * @reviewer Himanshu Jain */ public class Timestamp implements Comparable<Timestamp> { /** Timestamp is internally stored as a Date */ private Date date; /** * Timestamp Constructor * * @param date Date to build the timestamp */ public Timestamp(Date date) { this.date = date; } /** Copy Constructor */ public Timestamp(Timestamp timestampObj) { date = new Date(timestampObj.date.getTime()); } /** * Converts to String * * @return Timestamp as a String */ public String toString() { return date.toString(); } /** * Converts to Date * * @return Timestamp as a Date */ public Date toDate() { return date; } /** Equals Method */ @Override public boolean equals(Object obj) { if(obj instanceof Timestamp) { Timestamp timestamp = (Timestamp)obj; return date.equals(timestamp.date); } else return false; } /** Compare Method */ @Override public int compareTo(Timestamp timestamp) { return date.compareTo(timestamp.date); } }
17.703125
57
0.669903
2e5c75a58fb35f20c1084f6400abb64a090566a0
330
package com.saimon.Stock.portfolio.Database.Repository; import com.saimon.Stock.portfolio.Database.Model.Balance; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface BalanceRepository extends JpaRepository<Balance, Long> { Optional<Balance> findTopByOrderByIdDesc(); }
30
73
0.827273
073c0bbe2d438d492b66c3c16e2d91b6567c973e
726
package org.jboss.seam.examples.seamcrm.core; import javax.enterprise.context.Conversation; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import org.jboss.solder.logging.Logger; @RequestScoped @Named public class ConversationManagement { @Inject private Logger log; @Inject private Conversation conversation; public String begin() { if(conversation.isTransient()) { conversation.begin(); log.info("Began Long Running Conversation <" + conversation.getId() + ">"); return null; } else { log.info("Long Running Conversation <" + conversation.getId() + "> already active"); return null; } } }
20.166667
88
0.69146
8da865ad6989b8445d5f47923abd76b40441c14a
1,509
package org.infinispan.it.endpoints; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE; import java.io.IOException; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.Index; import org.testng.annotations.Test; /** * Tests for indexing json using object storage. The entity {@link CryptoCurrency} is annotated * with both Protobuf and Hibernate Search. * * @since 9.2 */ @Test(groups = "functional", testName = "it.endpoints.JsonPojoStoreTest") public class JsonPojoStoreTest extends BaseJsonTest { @Override protected ConfigurationBuilder getIndexCacheConfiguration() { ConfigurationBuilder indexedCache = new ConfigurationBuilder(); indexedCache.indexing().index(Index.PRIMARY_OWNER) .addProperty("default.directory_provider", "ram"); indexedCache.encoding().key().mediaType(APPLICATION_OBJECT_TYPE); indexedCache.encoding().value().mediaType(APPLICATION_OBJECT_TYPE); return indexedCache; } @Override protected String getEntityName() { return CryptoCurrency.class.getName(); } @Override protected RemoteCacheManager createRemoteCacheManager() throws IOException { return new RemoteCacheManager(new org.infinispan.client.hotrod.configuration.ConfigurationBuilder() .addServer().host("localhost").port(hotRodServer.getPort()) .build()); } }
32.106383
105
0.756793
120d65b3f50632ab391000bed3af8854786fa497
11,108
/* * Copyright 2016-2017 Luca Zanconato * * 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.nharyes.libsaltpack; import org.junit.Test; import org.junit.function.ThrowingRunnable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Random; import static org.junit.Assert.*; public class SignatureTest { @Test public void binaryAttached() throws Exception { byte[] secretkey = new byte[Constants.CRYPTO_SIGN_SECRETKEYBYTES]; byte[] publickey = new byte[Constants.CRYPTO_SIGN_PUBLICKEYBYTES]; Utils.generateSignKeypair(publickey, secretkey); ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputParameters op = new OutputParameters(bout); op.setArmored(false); MessageWriter mw = new MessageWriter(op, secretkey, false); mw.addBlock("A simple".getBytes("UTF-8"), false); mw.addBlock(" message".getBytes("UTF-8"), false); mw.addBlock(".".getBytes("UTF-8"), true); mw.destroy(); byte[] raw = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(raw); InputParameters ip = new InputParameters(bin); ip.setArmored(false); MessageReader mr = new MessageReader(ip); StringBuilder sb = new StringBuilder(); while (mr.hasMoreBlocks()) { sb.append(new String(mr.getBlock(), "UTF-8")); } assertEquals(sb.toString(), "A simple message."); assertArrayEquals(mr.getSender(), publickey); mr.destroy(); } @Test public void binaryDetached() throws Exception { byte[] secretkey = new byte[Constants.CRYPTO_SIGN_SECRETKEYBYTES]; byte[] publickey = new byte[Constants.CRYPTO_SIGN_PUBLICKEYBYTES]; Utils.generateSignKeypair(publickey, secretkey); ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputParameters op = new OutputParameters(bout); op.setArmored(false); byte[] buf1 = new byte[1024]; byte[] buf2 = new byte[1024 * 1024]; Random r = new Random(); r.nextBytes(buf1); r.nextBytes(buf2); ByteArrayOutputStream merged = new ByteArrayOutputStream(); merged.write(buf1); merged.write(buf2); MessageWriter mw = new MessageWriter(op, secretkey, true); mw.addBlock(buf1, false); mw.addBlock(buf2, true); mw.destroy(); byte[] raw = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(raw); InputParameters ip = new InputParameters(bin); ip.setArmored(false); MessageReader mr = new MessageReader(ip, new ByteArrayInputStream(merged.toByteArray())); assertArrayEquals(mr.getSender(), publickey); mr.destroy(); } @Test public void armoredAttached() throws Exception { byte[] secretkey = new byte[Constants.CRYPTO_SIGN_SECRETKEYBYTES]; byte[] publickey = new byte[Constants.CRYPTO_SIGN_PUBLICKEYBYTES]; Utils.generateSignKeypair(publickey, secretkey); ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputParameters op = new OutputParameters(bout); op.setArmored(true); MessageWriter mw = new MessageWriter(op, secretkey, false); mw.addBlock("A simple".getBytes("UTF-8"), false); mw.addBlock(" message".getBytes("UTF-8"), false); mw.addBlock(".".getBytes("UTF-8"), true); mw.destroy(); byte[] raw = bout.toByteArray(); assertTrue(new String(raw, "UTF-8").contains("SIGNED MESSAGE")); ByteArrayInputStream bin = new ByteArrayInputStream(raw); InputParameters ip = new InputParameters(bin); ip.setArmored(true); MessageReader mr = new MessageReader(ip); StringBuilder sb = new StringBuilder(); while (mr.hasMoreBlocks()) { sb.append(new String(mr.getBlock(), "UTF-8")); } assertEquals(sb.toString(), "A simple message."); assertArrayEquals(mr.getSender(), publickey); mr.destroy(); } @Test public void armoredDetached() throws Exception { byte[] secretkey = new byte[Constants.CRYPTO_SIGN_SECRETKEYBYTES]; byte[] publickey = new byte[Constants.CRYPTO_SIGN_PUBLICKEYBYTES]; Utils.generateSignKeypair(publickey, secretkey); ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputParameters op = new OutputParameters(bout); op.setArmored(true); byte[] buf1 = new byte[1024]; byte[] buf2 = new byte[1024 * 1024]; Random r = new Random(); r.nextBytes(buf1); r.nextBytes(buf2); ByteArrayOutputStream merged = new ByteArrayOutputStream(); merged.write(buf1); merged.write(buf2); MessageWriter mw = new MessageWriter(op, secretkey, true); mw.addBlock(buf1, false); mw.addBlock(buf2, true); mw.destroy(); byte[] raw = bout.toByteArray(); assertTrue(new String(raw, "UTF-8").contains("DETACHED SIGNATURE")); ByteArrayInputStream bin = new ByteArrayInputStream(raw); InputParameters ip = new InputParameters(bin); ip.setArmored(true); MessageReader mr = new MessageReader(ip, new ByteArrayInputStream(merged.toByteArray())); assertArrayEquals(mr.getSender(), publickey); mr.destroy(); } @Test public void exceptions() throws Exception { assertThrows(SaltpackException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { MessageReader mr = null; try { byte[] secretkey = new byte[Constants.CRYPTO_SIGN_SECRETKEYBYTES]; byte[] publickey = new byte[Constants.CRYPTO_SIGN_PUBLICKEYBYTES]; Utils.generateSignKeypair(publickey, secretkey); ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputParameters op = new OutputParameters(bout); op.setArmored(false); MessageWriter mw = new MessageWriter(op, secretkey, false); mw.addBlock("A signed message".getBytes("UTF-8"), true); mw.destroy(); byte[] raw = bout.toByteArray(); raw[raw.length - 80] %= 12; ByteArrayInputStream bin = new ByteArrayInputStream(raw); InputParameters ip = new InputParameters(bin); ip.setArmored(false); mr = new MessageReader(ip); while (mr.hasMoreBlocks()) { mr.getBlock(); } mr.destroy(); } finally { if (mr != null) mr.destroy(); } } }); assertThrows(SaltpackException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { MessageReader mr = null; try { byte[] secretkey = new byte[Constants.CRYPTO_SIGN_SECRETKEYBYTES]; byte[] publickey = new byte[Constants.CRYPTO_SIGN_PUBLICKEYBYTES]; Utils.generateSignKeypair(publickey, secretkey); ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputParameters op = new OutputParameters(bout); op.setArmored(true); byte[] buf1 = new byte[1024]; byte[] buf2 = new byte[1024 * 1024]; Random r = new Random(); r.nextBytes(buf1); r.nextBytes(buf2); ByteArrayOutputStream merged = new ByteArrayOutputStream(); merged.write(buf1); merged.write(buf2); MessageWriter mw = new MessageWriter(op, secretkey, true); mw.addBlock(buf1, false); mw.addBlock(buf2, true); mw.destroy(); byte[] raw = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(raw); InputParameters ip = new InputParameters(bin); ip.setArmored(true); merged.write('L'); mr = new MessageReader(ip, new ByteArrayInputStream(merged.toByteArray())); mr.destroy(); } finally { if (mr != null) mr.destroy(); } } }); assertThrows(SaltpackException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { MessageReader mr = null; try { byte[] secretkey = new byte[Constants.CRYPTO_SIGN_SECRETKEYBYTES]; byte[] publickey = new byte[Constants.CRYPTO_SIGN_PUBLICKEYBYTES]; Utils.generateSignKeypair(publickey, secretkey); ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputParameters op = new OutputParameters(bout); op.setArmored(true); byte[] buf1 = new byte[1024]; byte[] buf2 = new byte[1024 * 1024]; Random r = new Random(); r.nextBytes(buf1); r.nextBytes(buf2); ByteArrayOutputStream merged = new ByteArrayOutputStream(); merged.write(buf1); merged.write(buf2); MessageWriter mw = new MessageWriter(op, secretkey, true); mw.addBlock(buf1, false); mw.addBlock(buf2, false); mw.destroy(); byte[] raw = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(raw); InputParameters ip = new InputParameters(bin); ip.setArmored(true); mr = new MessageReader(ip, new ByteArrayInputStream(merged.toByteArray())); mr.destroy(); } finally { if (mr != null) mr.destroy(); } } }); } }
30.855556
97
0.57238
cff13d370cb80ad433a0516c3ce668c311d1a88a
2,372
package org.allenai.ml.classification; import com.gs.collections.api.tuple.primitive.IntObjectPair; import lombok.RequiredArgsConstructor; import org.allenai.ml.linalg.Vector; import org.allenai.ml.math.SloppyMath; import org.allenai.ml.objective.ExampleObjectiveFn; @RequiredArgsConstructor public class MaxEntObjective implements ExampleObjectiveFn<IntObjectPair<Vector>> { private final int numClasses; public static int weightIdx(int predIdx, int classIdx, int numClasses) { return predIdx * numClasses + classIdx; } @Override public double evaluate(IntObjectPair<Vector> labeledExample, Vector inParams, Vector outGrad) { int trueClassIdx = labeledExample.getOne(); double[] classProbs = classProbs(labeledExample.getTwo(), inParams, numClasses); Vector.Iterator iter = labeledExample.getTwo().iterator(); while (!iter.isExhausted()) { int predIdx = (int) iter.index(); double predVal = iter.value(); // increment gradient for true class features outGrad.inc(weightIdx(predIdx, trueClassIdx, numClasses), predVal); // decrement gradient for all classes by posterior prob for (int classIdx = 0; classIdx < numClasses; classIdx++) { outGrad.inc(weightIdx(predIdx, classIdx, numClasses), -predVal * classProbs[classIdx]); } iter.advance(); } return Math.log(classProbs[trueClassIdx]); } public static double[] classProbs(Vector featVec, Vector weights, int numClasses) { double[] logScores = new double[numClasses]; Vector.Iterator it = featVec.iterator(); while (!it.isExhausted()) { int predIdx = (int) it.index(); double predVal = it.value(); for (int classIdx = 0; classIdx < numClasses; classIdx++) { int weightIdx = weightIdx(predIdx, classIdx, numClasses); logScores[classIdx] += weights.at(weightIdx) * predVal; } it.advance(); } // Exponentiate in place to get probabilities double logZ = SloppyMath.logSumExp(logScores); for (int classIdx = 0; classIdx < numClasses; classIdx++) { logScores[classIdx] = SloppyMath.sloppyExp(logScores[classIdx] - logZ); } return logScores; } }
41.614035
103
0.650506
fb4d13dd92340ba3fad004d89784aa6c26ecc316
3,677
/** * Copyright (c) 2015-2018, CJ Hare 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 [project] 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 HOLDER 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.systematic.trading.strategy.model.collection; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.Test; /** * Tests the limited size implementation of LinkedList * * @author CJ Hare */ public class LimitedSizeQueueTest { /** List instance being tested. */ private LimitedSizeQueue<String> list; @Before public void setUp() { list = new LimitedSizeQueue<String>(String.class, 2); } @Test public void addUnderLimit() { final String one = "one"; list.add(one); verifyContents(one); } @Test public void addOnLimit() { final String one = "one"; final String two = "two"; list.add(one); list.add(two); verifyContents(one, two); } @Test public void addOverLimit() { final String one = "one"; final String two = "two"; final String three = "three"; list.add(one); list.add(two); list.add(three); verifyContents(two, three); } @Test(expected = UnsupportedOperationException.class) public void toArrayException() { list.toArray(new String[0]); } @Test public void toArray() { final String[] converted = list.toArray(); verifyContents(converted); } @Test public void toArrayPartiallyPopulated() { list.add("first"); final String[] converted = list.toArray(); verifyContents(converted, "first"); } @Test public void toArrayFullyPopulated() { list.add("first"); list.add("second"); final String[] converted = list.toArray(); verifyContents(converted, "first", "second"); } private void verifyContents( final String[] converted, final String... expectedContents ) { assertEquals(expectedContents.length, converted.length); for (int i = 0; i < expectedContents.length; i++) { assertNotNull(converted[i]); assertEquals(expectedContents[i], converted[i]); } } private void verifyContents( final String... expectedContents ) { assertEquals(expectedContents.length, list.size()); for (int i = 0; i < expectedContents.length; i++) { assertNotNull(list.get(i)); assertEquals(expectedContents[i], list.get(i)); } } }
26.078014
100
0.727223
30f89ff234cf1cfa78a0b025e08f167b8ba5d4b2
1,537
package me.violinsolo.testlibsapp.activity; import android.os.Bundle; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import me.violinsolo.testlibsapp.R; import me.violinsolo.testlibsapp.base.BaseActivity; import me.violinsolo.testlibsapp.databinding.ActivityTestGifBinding; public class TestGifActivity extends BaseActivity<ActivityTestGifBinding> { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_gif); } /** * need to initilize the ViewBinding Class in every sub activity class. * * @return mBinder the field of view binding handler. Initialize it before use * eg. * mBinder = ActivityXMLNameBinding.inflate(getLayoutInflater()); */ @Override protected ActivityTestGifBinding onBind() { return ActivityTestGifBinding.inflate(getLayoutInflater()); } /** * init data here, like you can get data from extra. * eg. * var data = getIntent().getParcelableExtra(EXTRA_KEY_XXX); */ @Override protected void initData() { } /** * write init view codes, such as toolbar. */ @Override protected void initViews() { Glide.with(this).asGif().diskCacheStrategy(DiskCacheStrategy.RESOURCE).load(R.drawable.bluetooth_intro).into(mBinder.imageView); } /** * bind all listeners here. */ @Override protected void bindListeners() { } }
26.5
136
0.696812
0d19d4a5a49052f99b3c250b1cf31c3b9bc8cf93
11,943
/* * Copyright 2016-2018 Crown Copyright * * 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 uk.gov.gchq.gaffer.data.elementdefinition; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import uk.gov.gchq.gaffer.commonutil.CloseableUtil; import uk.gov.gchq.gaffer.commonutil.ToStringBuilder; import uk.gov.gchq.gaffer.data.elementdefinition.exception.SchemaException; import uk.gov.gchq.gaffer.exception.SerialisationException; import uk.gov.gchq.gaffer.jsonserialisation.JSONSerialiser; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY; /** * <p> * Contains the full list of groups in the graph. * </p> * <p> * This class must be JSON serialisable. * A schema should normally be written in JSON and then deserialised at runtime. * Examples of JSON schemas can be found in the example projects. * </p> * * @param <ENTITY_DEF> the type of {@link ElementDefinition} for the entities * @param <EDGE_DEF> the type of {@link ElementDefinition} for the edges */ public abstract class ElementDefinitions<ENTITY_DEF extends ElementDefinition, EDGE_DEF extends ElementDefinition> { /** * Map of edge type to edge definition. */ private Map<String, EDGE_DEF> edges; /** * Map of entity type to entity definition. */ private Map<String, ENTITY_DEF> entities; protected ElementDefinitions() { edges = new HashMap<>(); entities = new HashMap<>(); } public byte[] toJson(final boolean prettyPrint, final String... fieldsToExclude) throws SchemaException { try { return JSONSerialiser.serialise(this, prettyPrint, fieldsToExclude); } catch (final SerialisationException e) { throw new SchemaException(e.getMessage(), e); } } /** * Looks the group up in the entity definitions then if it doesn't find a definition it will look it up in the edge definitions. * If you know the type of the element (Entity or Edge) then use getEntity or getEdge. * * @param group an group * @return the {@link uk.gov.gchq.gaffer.data.elementdefinition.ElementDefinition} for the given group */ public ElementDefinition getElement(final String group) { return isEntity(group) ? getEntity(group) : getEdge(group); } public EDGE_DEF getEdge(final String group) { return edges.get(group); } public ENTITY_DEF getEntity(final String group) { return entities.get(group); } public boolean isEntity(final String group) { return entities.containsKey(group); } public boolean isEdge(final String group) { return edges.containsKey(group); } @JsonIgnore public Set<String> getEdgeGroups() { return null != edges ? edges.keySet() : Collections.emptySet(); } @JsonIgnore public Set<String> getEntityGroups() { return null != entities ? entities.keySet() : Collections.emptySet(); } /** * Returns a new hash set with all entity and edge groups. * * @return a new hash set with all entity and edge groups. */ @JsonIgnore public Set<String> getGroups() { final Set<String> entityGroups = getEntityGroups(); final Set<String> edgeGroups = getEdgeGroups(); final Set<String> groups = new HashSet<>(entityGroups.size() + edgeGroups.size()); groups.addAll(entityGroups); groups.addAll(edgeGroups); return groups; } @JsonIgnore public boolean hasEntities() { return null != entities && !entities.isEmpty(); } @JsonIgnore public boolean hasEdges() { return null != edges && !edges.isEmpty(); } @JsonIgnore public boolean hasGroups() { return hasEntities() || hasEdges(); } @JsonInclude(NON_EMPTY) public Map<String, EDGE_DEF> getEdges() { return edges; } @JsonInclude(NON_EMPTY) public Map<String, ENTITY_DEF> getEntities() { return entities; } protected void setEdges(final Map<String, EDGE_DEF> edges) { this.edges = edges; } protected void setEntities(final Map<String, ENTITY_DEF> entities) { this.entities = entities; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (null == obj || getClass() != obj.getClass()) { return false; } final ElementDefinitions<?, ?> that = (ElementDefinitions<?, ?>) obj; return new EqualsBuilder() .append(edges, that.edges) .append(entities, that.entities) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(31, 5) .append(edges) .append(entities) .toHashCode(); } @Override public String toString() { return new ToStringBuilder(this) .append("edges", edges) .append("entities", entities) .toString(); } protected void lock() { edges = Collections.unmodifiableMap(edges); entities = Collections.unmodifiableMap(entities); } /** * Builder for {@link uk.gov.gchq.gaffer.data.elementdefinition.ElementDefinitions}. * * @param <ENTITY_DEF> the entity definition type. * @param <EDGE_DEF> the entity definition type. */ @JsonPOJOBuilder(buildMethodName = "build", withPrefix = "set") public abstract static class BaseBuilder<ELEMENT_DEFS extends ElementDefinitions<ENTITY_DEF, EDGE_DEF>, ENTITY_DEF extends ElementDefinition, EDGE_DEF extends ElementDefinition, CHILD_CLASS extends BaseBuilder<ELEMENT_DEFS, ENTITY_DEF, EDGE_DEF, ?>> { private ELEMENT_DEFS elementDefs; protected BaseBuilder(final ELEMENT_DEFS elementDefs) { this.elementDefs = elementDefs; } /** * Adds an edge definition for a given edge type. * * @param group the edge type * @param edgeDef the edge definition for the given edge type. * @return this Builder */ public CHILD_CLASS edge(final String group, final EDGE_DEF edgeDef) { elementDefs.getEdges().put(group, edgeDef); return self(); } @JsonSetter("edges") public CHILD_CLASS edges(final Map<String, EDGE_DEF> edges) { elementDefs.getEdges().clear(); if (null != edges) { elementDefs.getEdges().putAll(edges); } return self(); } /** * Adds an entity definition for a given entity type. * * @param group the entity type * @param entityDef the entity definition for the given entity type. * @return this Builder */ public CHILD_CLASS entity(final String group, final ENTITY_DEF entityDef) { if (null == entityDef) { throw new IllegalArgumentException("Entity definition is required"); } elementDefs.getEntities().put(group, entityDef); return self(); } @JsonSetter("entities") public CHILD_CLASS entities(final Map<String, ENTITY_DEF> entities) { elementDefs.getEntities().clear(); if (null != entities) { elementDefs.getEntities().putAll(entities); } return self(); } public CHILD_CLASS removeEdges(final Predicate<Map.Entry<String, EDGE_DEF>> filter) { elementDefs.getEdges().entrySet().removeIf(filter); return self(); } public CHILD_CLASS removeEntities(final Predicate<Map.Entry<String, ENTITY_DEF>> filter) { elementDefs.getEntities().entrySet().removeIf(filter); return self(); } public CHILD_CLASS json(final Class<? extends ELEMENT_DEFS> clazz, final Path... filePaths) throws SchemaException { return json(clazz, (Object[]) filePaths); } public CHILD_CLASS json(final Class<? extends ELEMENT_DEFS> clazz, final InputStream... inputStreams) throws SchemaException { try { return json(clazz, (Object[]) inputStreams); } finally { if (null != inputStreams) { for (final InputStream inputStream : inputStreams) { CloseableUtil.close(inputStream); } } } } public CHILD_CLASS json(final Class<? extends ELEMENT_DEFS> clazz, final byte[]... jsonBytes) throws SchemaException { return json(clazz, (Object[]) jsonBytes); } public CHILD_CLASS json(final Class<? extends ELEMENT_DEFS> clazz, final Object[] jsonItems) throws SchemaException { if (null != jsonItems) { for (final Object jsonItem : jsonItems) { try { if (jsonItem instanceof InputStream) { merge(JSONSerialiser.deserialise((InputStream) jsonItem, clazz)); } else if (jsonItem instanceof Path) { final Path path = (Path) jsonItem; if (Files.isDirectory(path)) { for (final Path filePath : Files.newDirectoryStream(path)) { merge(JSONSerialiser.deserialise(Files.readAllBytes(filePath), clazz)); } } else { merge(JSONSerialiser.deserialise(Files.readAllBytes(path), clazz)); } } else { merge(JSONSerialiser.deserialise((byte[]) jsonItem, clazz)); } } catch (final IOException e) { throw new SchemaException("Failed to load element definitions from bytes", e); } } } return self(); } protected abstract CHILD_CLASS merge(final ELEMENT_DEFS newElementDefs); /** * Builds the {@link uk.gov.gchq.gaffer.data.elementdefinition.ElementDefinitions} validates it and returns it. * * @return the build {@link uk.gov.gchq.gaffer.data.elementdefinition.ElementDefinitions}. */ public ELEMENT_DEFS build() { elementDefs.lock(); return elementDefs; } protected ELEMENT_DEFS getElementDefs() { return elementDefs; } protected void setElementDefs(final ELEMENT_DEFS elementDefs) { this.elementDefs = elementDefs; } protected abstract CHILD_CLASS self(); } }
34.517341
255
0.614753
01376e2d11db610e4b798da01d5d3c5a73f7bc22
3,179
package com.cmu.smartphone.allavailable.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.cmu.smartphone.allavailable.R; import com.cmu.smartphone.allavailable.entities.CommentBean; import java.util.List; /** * This class fill in the item of the Comment List in the Comment page * * @author Xi Wang * @version 1.0 */ public class CommentListAdapter extends BaseAdapter { private Context context; private List<CommentBean> lists; private LayoutInflater layoutInflater; private ImageView commentIcon; private TextView commentInfo; private TextView commentTitle; /** * Default Constructor * * @param context the Activity Context * @param lists the List of all comments */ public CommentListAdapter(Context context, List<CommentBean> lists) { this.context = context; this.lists = lists; layoutInflater = LayoutInflater.from(context); } /** * Get the count of the list * * @return the count of the list */ @Override public int getCount() { return lists.size(); } /** * Get the item of the given position * * @param position the position number * @return the item of the given position */ @Override public Object getItem(int position) { return lists.get(position); } /** * Get the item id of the given position * * @param position the position number * @return the item of the given position */ @Override public long getItemId(int position) { return position; } /** * Get the view of the given position * * @param position the position number * @param convertView the convert view * @param parent the parent view * @return the view of the given position */ @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = layoutInflater.inflate(R.layout.comment_item, null); } commentIcon = (ImageView) convertView.findViewById(R.id.comment_icon); commentInfo = (TextView) convertView.findViewById(R.id.comment_info); commentTitle = (TextView) convertView.findViewById(R.id.comment_title); CommentBean comment = lists.get(position); if (comment.getImagePath() == null || comment.getImagePath().equals("N/A")) { commentIcon.setVisibility(View.INVISIBLE); } else { commentIcon.setVisibility(View.VISIBLE); } StringBuilder sb = new StringBuilder(); sb.append(comment.getUserId().substring(0, comment.getUserId().indexOf('@'))); sb.append("("); sb.append(comment.getDate()); sb.append(","); sb.append(comment.getTime()); sb.append(")"); commentTitle.setText(sb.toString()); commentInfo.setText(comment.getContent()); return convertView; } }
28.132743
86
0.647688
c6a544922585f5f0ccc1b2690539a7dc634851a2
252
package org.shaolin.javacc.sql.node; public abstract class OQLSimpleField implements IOQLExpressionNode { public boolean isCategoryField() { return false; } private static final long serialVersionUID = 2291418435386989200L; }
21
70
0.746032
55090e7b3530899c803397700fb3803ee721f950
7,118
package io.split.client; import io.split.TestHelper; import io.split.client.dtos.Split; import io.split.client.dtos.SplitChange; import io.split.engine.common.FetchOptions; import io.split.engine.metrics.Metrics; import io.split.telemetry.storage.InMemoryTelemetryStorage; import io.split.telemetry.storage.TelemetryRuntimeProducer; import io.split.telemetry.storage.TelemetryStorage; import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.*; import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import java.io.Closeable; import java.io.IOException; import java.io.StringBufferInputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.mockito.Mockito.when; public class HttpSplitChangeFetcherTest { private static final TelemetryStorage TELEMETRY_STORAGE = Mockito.mock(InMemoryTelemetryStorage.class); @Test public void testDefaultURL() throws URISyntaxException { URI rootTarget = URI.create("https://api.split.io"); CloseableHttpClient httpClient = HttpClients.custom().build(); Metrics.NoopMetrics metrics = new Metrics.NoopMetrics(); HttpSplitChangeFetcher fetcher = HttpSplitChangeFetcher.create(httpClient, rootTarget, TELEMETRY_STORAGE); Assert.assertThat(fetcher.getTarget().toString(), Matchers.is(Matchers.equalTo("https://api.split.io/api/splitChanges"))); } @Test public void testCustomURLNoPathNoBackslash() throws URISyntaxException { URI rootTarget = URI.create("https://kubernetesturl.com/split"); CloseableHttpClient httpClient = HttpClients.custom().build(); Metrics.NoopMetrics metrics = new Metrics.NoopMetrics(); HttpSplitChangeFetcher fetcher = HttpSplitChangeFetcher.create(httpClient, rootTarget, TELEMETRY_STORAGE); Assert.assertThat(fetcher.getTarget().toString(), Matchers.is(Matchers.equalTo("https://kubernetesturl.com/split/api/splitChanges"))); } @Test public void testCustomURLAppendingPath() throws URISyntaxException { URI rootTarget = URI.create("https://kubernetesturl.com/split/"); CloseableHttpClient httpClient = HttpClients.custom().build(); Metrics.NoopMetrics metrics = new Metrics.NoopMetrics(); HttpSplitChangeFetcher fetcher = HttpSplitChangeFetcher.create(httpClient, rootTarget, TELEMETRY_STORAGE); Assert.assertThat(fetcher.getTarget().toString(), Matchers.is(Matchers.equalTo("https://kubernetesturl.com/split/api/splitChanges"))); } @Test public void testCustomURLAppendingPathNoBackslash() throws URISyntaxException { URI rootTarget = URI.create("https://kubernetesturl.com/split"); CloseableHttpClient httpClient = HttpClients.custom().build(); Metrics.NoopMetrics metrics = new Metrics.NoopMetrics(); HttpSplitChangeFetcher fetcher = HttpSplitChangeFetcher.create(httpClient, rootTarget, TELEMETRY_STORAGE); Assert.assertThat(fetcher.getTarget().toString(), Matchers.is(Matchers.equalTo("https://kubernetesturl.com/split/api/splitChanges"))); } @Test public void testFetcherWithSpecialCharacters() throws URISyntaxException, InvocationTargetException, NoSuchMethodException, IllegalAccessException, IOException { URI rootTarget = URI.create("https://api.split.io"); CloseableHttpClient httpClientMock = TestHelper.mockHttpClient("split-change-special-characters.json", HttpStatus.SC_OK); Metrics.NoopMetrics metrics = new Metrics.NoopMetrics(); HttpSplitChangeFetcher fetcher = HttpSplitChangeFetcher.create(httpClientMock, rootTarget, TELEMETRY_STORAGE); SplitChange change = fetcher.fetch(1234567, new FetchOptions.Builder().cacheControlHeaders(true).build()); Assert.assertNotNull(change); Assert.assertEquals(1, change.splits.size()); Assert.assertNotNull(change.splits.get(0)); Split split = change.splits.get(0); Map<String, String> configs = split.configurations; Assert.assertEquals(2, configs.size()); Assert.assertEquals("{\"test\": \"blue\",\"grüne Straße\": 13}", configs.get("on")); Assert.assertEquals("{\"test\": \"blue\",\"size\": 15}", configs.get("off")); } @Test public void testFetcherWithCDNBypassOption() throws IOException, URISyntaxException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { URI rootTarget = URI.create("https://api.split.io"); HttpEntity entityMock = Mockito.mock(HttpEntity.class); when(entityMock.getContent()).thenReturn(new StringBufferInputStream("{\"till\": 1}")); ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); when(response.getCode()).thenReturn(200); when(response.getEntity()).thenReturn(entityMock); when(response.getHeaders()).thenReturn(new Header[0]); ArgumentCaptor<ClassicHttpRequest> requestCaptor = ArgumentCaptor.forClass(ClassicHttpRequest.class); CloseableHttpClient httpClientMock = Mockito.mock(CloseableHttpClient.class); when(httpClientMock.execute(requestCaptor.capture())).thenReturn(TestHelper.classicResponseToCloseableMock(response)); HttpSplitChangeFetcher fetcher = HttpSplitChangeFetcher.create(httpClientMock, rootTarget, Mockito.mock(TelemetryRuntimeProducer.class)); fetcher.fetch(-1, new FetchOptions.Builder().targetChangeNumber(123).build()); fetcher.fetch(-1, new FetchOptions.Builder().build()); List<ClassicHttpRequest> captured = requestCaptor.getAllValues(); Assert.assertEquals(captured.size(), 2); Assert.assertTrue(captured.get(0).getUri().toString().contains("till=123")); Assert.assertFalse(captured.get(1).getUri().toString().contains("till=")); } @Test public void testRandomNumberGeneration() throws URISyntaxException { URI rootTarget = URI.create("https://api.split.io"); CloseableHttpClient httpClientMock = Mockito.mock(CloseableHttpClient.class); HttpSplitChangeFetcher fetcher = HttpSplitChangeFetcher.create(httpClientMock, rootTarget, Mockito.mock(TelemetryRuntimeProducer.class)); Set<Long> seen = new HashSet<>(); long min = (long)Math.pow(2, 63) * (-1); final long total = 10000000; for (long x = 0; x < total; x++) { long r = fetcher.makeRandomTill(); Assert.assertTrue(r < 0 && r > min); seen.add(r); } Assert.assertTrue(seen.size() >= (total * 0.9999)); } }
50.842857
165
0.737567
7977e0d348bdb72d6e2ef8a484a7e26298cf8b13
2,296
package org.statemach.db.schema; import java.util.Objects; import org.statemach.db.jdbc.Vendor; import org.statemach.db.sql.SchemaAccess; import org.statemach.util.Java; import io.vavr.Tuple2; import io.vavr.collection.HashMap; import io.vavr.collection.List; import io.vavr.collection.Map; public class Schema { public final Vendor vendor; public final String name; public final Map<String, TableInfo> tables; public Schema(Vendor vendor, String name, Map<String, TableInfo> tables) { this.vendor = vendor; this.name = name; this.tables = tables; } @Override public int hashCode() { return Objects.hash(vendor, name, tables); } @Override public boolean equals(Object other) { return Java.equalsByFields(this, other, t -> t.vendor, t -> t.name, t -> t.tables); } @Override public String toString() { return "Schema@{name: " + name + "}"; } public static Schema from(SchemaAccess access) { Map<String, Map<String, ColumnInfo>> columnsByNameByTable = access.getAllTables() .mapValues(l -> l.toLinkedMap(c -> c.name, c -> c)); Map<String, PrimaryKey> primaryByTable = access.getAllPrimaryKeys() .toMap(p -> new Tuple2<>(p.table, p)); List<ForeignKey> foreignKeys = access.getAllForeignKeys(); Map<String, Map<String, ForeignKey>> incomingByNameByTable = foreignKeys .groupBy(f -> f.toTable) .mapValues(s -> s.toLinkedMap(f -> new Tuple2<>(f.name, f))); Map<String, Map<String, ForeignKey>> outgoingByNameByTable = foreignKeys .groupBy(f -> f.fromTable) .mapValues(s -> s.toLinkedMap(f -> new Tuple2<>(f.name, f))); Map<String, TableInfo> tablesByName = columnsByNameByTable .toLinkedMap(t -> new Tuple2<>(t._1, new TableInfo(t._1, t._2, primaryByTable.get(t._1), incomingByNameByTable.get(t._1).getOrElse(HashMap.empty()), outgoingByNameByTable.get(t._1).getOrElse(HashMap.empty())))); return new Schema(access.getVendor(), access.getSchemaName(), tablesByName); } }
33.275362
91
0.607578
5c2fb1aedfda4c6f5b43fa4741acc723469949de
1,501
package com.gentics.mesh.core.data.root; import com.gentics.mesh.core.data.Project; import com.gentics.mesh.core.data.Release; import com.gentics.mesh.core.data.User; /** * Aggregation vertex for Releases. */ public interface ReleaseRoot extends RootVertex<Release> { public static final String TYPE = "releases"; /** * Get the project of this release root. * * @return */ Project getProject(); /** * Create a new release and make it the latest The new release will be the initial release, if it is the first created. * * @param name * release name * @param creator * creator * @return new Release */ default Release create(String name, User creator) { return create(name, creator, null); } /** * Create a new release and make it the latest The new release will be the initial release, if it is the first created. * * @param name * release name * @param creator * creator * @param uuid * Optional uuid * @return new Release */ Release create(String name, User creator, String uuid); /** * Get the initial release of this root. * * @return */ Release getInitialRelease(); /** * Get the latest release of this root. * * @return */ Release getLatestRelease(); /** * Get the unique index key for names of releases attached to this root. * * @param name * release name * @return unique index key */ String getUniqueNameKey(String name); }
21.442857
120
0.648901
59f5a3f5b59abc73a400edb5b93f5d7d71f1392d
387
package kr.co.popone.fitts.di.component; import dagger.android.AndroidInjector; import kr.co.popone.fitts.feature.coupon.CouponUseConfirmActivity; public interface CouponUseConfirmActivityComponent extends AndroidInjector<CouponUseConfirmActivity> { public static abstract class Builder extends dagger.android.AndroidInjector.Builder<CouponUseConfirmActivity> { } }
35.181818
116
0.819121
c004e516968a66bd3828731972acc5a528fe4d77
2,742
package io.github.kavahub.learnjava.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.commons.io.FileUtils; import lombok.experimental.UtilityClass; /** * 目录复制 * * @author PinWei Wan * @since 1.0.0 * */ public class DirectoryCopier { @UtilityClass public static class CoreOld { public void copyDirectoryJavaUnder7(File source, File destination) throws IOException { if (source.isDirectory()) { copyDirectory(source, destination); } else { copyFile(source, destination); } } private void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException { if (!destinationDirectory.exists()) { destinationDirectory.mkdir(); } for (String f : sourceDirectory.list()) { copyDirectoryJavaUnder7(new File(sourceDirectory, f), new File(destinationDirectory, f)); } } private void copyFile(File sourceFile, File destinationFile) throws IOException { try (InputStream in = new FileInputStream(sourceFile); OutputStream out = new FileOutputStream(destinationFile)) { byte[] buf = new byte[1024]; int length; while ((length = in.read(buf)) > 0) { out.write(buf, 0, length); } } } } @UtilityClass public static class JavaNio { public void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException { Files.walk(Paths.get(sourceDirectoryLocation)) .forEach(source -> { Path destination = Paths.get(destinationDirectoryLocation, source.toString() .substring(sourceDirectoryLocation.length())); try { Files.copy(source, destination); } catch (IOException e) { e.printStackTrace(); } }); } } @UtilityClass public static class ApacheCommons { public void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException { File sourceDirectory = new File(sourceDirectoryLocation); File destinationDirectory = new File(destinationDirectoryLocation); FileUtils.copyDirectory(sourceDirectory, destinationDirectory); } } }
32.642857
126
0.615244
12cf2384b96fb7643bfb0b0a01cd3101811137a1
343
/* (c) British Telecommunications plc, 2010, All Rights Reserved */ package com.bt.pi.ops.website.exception; import org.junit.Test; import com.bt.pi.ops.website.exception.CannotCreateException; public class CannotCreateExceptionTest { @Test public void canInstantiateCannotCreateException(){ //act new CannotCreateException(""); } }
22.866667
67
0.77551
29d09e22da61db7cc1adb4522908ae1411ad0ad0
673
package com.lindar.realvault.client.model.internal; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @XmlRootElement(name = "autosettle") @XmlAccessorType(XmlAccessType.FIELD) @Data @AllArgsConstructor @NoArgsConstructor public class RealExAutoSettle implements Serializable { private static final long serialVersionUID = 3360392440856283878L; @XmlAttribute(name = "flag") private String flag; }
28.041667
70
0.821694
00fc0ac274666e34ba99b26c1a9d6ddd3bfbf33c
3,098
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.requests.extensions.IWindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequest; import com.microsoft.graph.requests.extensions.WindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequest; import com.microsoft.graph.core.BaseActionRequestBuilder; import com.microsoft.graph.core.BaseFunctionRequestBuilder; import com.microsoft.graph.core.IBaseClient; import com.google.gson.JsonElement; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Windows Autopilot Device Identity Unassign Resource Account From Device Request Builder. */ public class WindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequestBuilder extends BaseActionRequestBuilder implements IWindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequestBuilder { /** * The request builder for this WindowsAutopilotDeviceIdentityUnassignResourceAccountFromDevice * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public WindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } /** * Creates the IWindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequest * * @param requestOptions the options for the request * @return the IWindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequest instance */ public IWindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the IWindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequest with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for the request * @return the IWindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequest instance */ public IWindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { WindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequest request = new WindowsAutopilotDeviceIdentityUnassignResourceAccountFromDeviceRequest( getRequestUrl(), getClient(), requestOptions ); return request; } }
53.413793
224
0.757908
e176e07dafa27bd5c45f4612fb860af6d1ebacca
2,674
package im.heart.material.service.impl; import java.math.BigInteger; import java.util.Collection; import java.util.HashSet; import java.util.List; import com.google.common.collect.Sets; import im.heart.core.service.impl.CommonServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import im.heart.material.entity.PeriodicalCategory; import im.heart.material.repository.PeriodicalCategoryRepository; import im.heart.material.service.PeriodicalCategoryService; import im.heart.core.plugins.persistence.DynamicSpecifications; import im.heart.core.plugins.persistence.SearchFilter; import im.heart.core.plugins.persistence.SearchFilter.Operator; /** * @author gg */ @Service(value = PeriodicalCategoryService.BEAN_NAME) @Transactional(propagation = Propagation.SUPPORTS) public class PeriodicalCategoryServiceImpl extends CommonServiceImpl<PeriodicalCategory, BigInteger> implements PeriodicalCategoryService { @Autowired private PeriodicalCategoryRepository periodicalCategoryRepository; @Override public List<PeriodicalCategory> saveAll(Iterable<PeriodicalCategory> entities) { return this.periodicalCategoryRepository.saveAll(entities); } @Override public List<PeriodicalCategory> findByParentId(BigInteger parentId) { return this.periodicalCategoryRepository.findByParentId(parentId); } @Override public boolean exit(String categoryCode) { final Collection<SearchFilter> filters = Sets.newHashSet(); filters.add(new SearchFilter("categoryCode", Operator.EQ, categoryCode)); Specification<PeriodicalCategory> spec = DynamicSpecifications.bySearchFilter(filters, PeriodicalCategory.class); long countSign = this.periodicalCategoryRepository.count(spec); return countSign <= 0; } @Override public List<PeriodicalCategory> findByPParentIdAndLevel(String ppCode, Integer level) { final Collection<SearchFilter> filters = Sets.newHashSet(); filters.add(new SearchFilter("categoryCode", Operator.LIKES, ppCode)); filters.add(new SearchFilter("level", Operator.EQ, level)); Specification<PeriodicalCategory> spec = DynamicSpecifications.bySearchFilter(filters, PeriodicalCategory.class); return this.periodicalCategoryRepository.findAll(spec); } @Override public List<PeriodicalCategory> findByCategoryCodeStartingWith(String categoryCode) { // TODO Auto-generated method stub return this.periodicalCategoryRepository.findByCategoryCodeStartingWith(categoryCode); } }
40.515152
142
0.829469
bd56e1a0e2f2e0cbc8d41e772fa25b32e1942b81
2,230
package experimental.trees; public class SegmentTreeIntervalAddSum { int n; int[] tsum; int[] tadd; public SegmentTreeIntervalAddSum(int n) { this.n = n; tsum = new int[4 * n]; tadd = new int[4 * n]; } void push(int node, int left, int right) { tsum[node] += tadd[node] * (right - left + 1); if (left < right) { tadd[node * 2] += tadd[node]; tadd[node * 2 + 1] += tadd[node]; } tadd[node] = 0; } void pop(int node, int left, int right) { int mid = (left + right) >> 1; tsum[node] = tsum[node * 2] + tadd[node * 2] * (mid - left + 1); tsum[node] += tsum[node * 2 + 1] + tadd[node * 2 + 1] * (right - mid); } void add(int a, int b, int value) { add(a, b, value, 1, 0, n - 1); } void add(int a, int b, int value, int node, int left, int right) { push(node, left, right); if (left >= a && right <= b) { tadd[node] += value; return; } int mid = (left + right) >> 1; if (a <= mid) add(a, b, value, node * 2, left, mid); if (b > mid) add(a, b, value, node * 2 + 1, mid + 1, right); pop(node, left, right); } int sum(int a, int b) { return sum(a, b, 1, 0, n - 1); } int sum(int a, int b, int node, int left, int right) { push(node, left, right); if (left >= a && right <= b) return tsum[node]; int mid = (left + right) >> 1; int res = 0; if (a <= mid) res += sum(a, b, node * 2, left, mid); if (b > mid) res += sum(a, b, node * 2 + 1, mid + 1, right); // pop(node, left, right); return res; } int get(int i) { return get(i, 1, 0, n - 1); } int get(int i, int node, int left, int right) { push(node, left, right); if (left == right) return tsum[node]; int mid = (left + right) >> 1; int res = i <= mid ? get(i, node * 2, left, mid) : get(i, node * 2 + 1, mid + 1, right); // pop(node, left, right); return res; } void set(int i, int value) { add(i, i, -get(i) + value); } public static void main(String[] args) { SegmentTreeIntervalAddSum t = new SegmentTreeIntervalAddSum(10); t.add(0, 0, 1); t.set(0, 4); t.set(1, 5); t.set(2, 5); t.add(2, 2, 5); t.add(0, 2, 1); System.out.println(5 == t.get(0)); System.out.println(22 == t.sum(0, 2)); System.out.println(17 == t.sum(1, 2)); } }
22.755102
90
0.544843
b28f91822d2741eb1fdd8a4e8f6411876f3fc37d
2,030
package service; import java.util.List; import com.pojo.Repertory; import common.Assist; public interface RepertoryService{ /** * 获得Repertory数据的总行数,可以通过辅助工具Assist进行条件查询,如果没有条件则传入null * @param assist * @return */ long getRepertoryRowCount(Assist assist); /** * 获得Repertory数据集合,可以通过辅助工具Assist进行条件查询,如果没有条件则传入null * @param assist * @return */ List<Repertory> selectRepertory(Assist assist); /** * 获得Repertory数据集合,该方法为多表关联时保证分页的数据不缺失不重复,可以正常得到所有数据,如果非多表分页的情况建议使用不带ofPaging的方法,可以通过辅助工具Assist进行查询,如果没有条件则传入null * @param assist * @return */ List<Repertory> selectRepertoryOfPaging(Assist assist); /** * 获得一个Repertory对象,以参数Repertory对象中不为空的属性作为条件进行查询 * @param obj * @return */ Repertory selectRepertoryByObj(Repertory obj); /** * 通过Repertory的id获得Repertory对象 * @param id * @return */ Repertory selectRepertoryById(Integer id); /** * 插入Repertory到数据库,包括null值 * @param value * @return */ int insertRepertory(Repertory value); /** * 插入Repertory中属性值不为null的数据到数据库 * @param value * @return */ int insertNonEmptyRepertory(Repertory value); /** * 批量插入Repertory到数据库 * @param value * @return */ int insertRepertoryByBatch(List<Repertory> value); /** * 通过Repertory的id删除Repertory * @param id * @return */ int deleteRepertoryById(Integer id); /** * 通过辅助工具Assist的条件删除Repertory * @param assist * @return */ int deleteRepertory(Assist assist); /** * 通过Repertory的id更新Repertory中的数据,包括null值 * @param enti * @return */ int updateRepertoryById(Repertory enti); /** * 通过辅助工具Assist的条件更新Repertory中的数据,包括null值 * @param value * @param assist * @return */ int updateRepertory(Repertory value, Assist assist); /** * 通过Repertory的id更新Repertory中属性不为null的数据 * @param enti * @return */ int updateNonEmptyRepertoryById(Repertory enti); /** * 通过辅助工具Assist的条件更新Repertory中属性不为null的数据 * @param value * @param assist * @return */ int updateNonEmptyRepertory(Repertory value, Assist assist); }
22.065217
114
0.706897
268f6bb8015edefa0f2ca0a7a30bcca7ff81bcda
3,423
/* * Copyright (C) 2019 The Turms Project * https://github.com/turms-im/turms * * 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 im.turms.server.common.rpc.request; import im.turms.common.model.dto.request.TurmsRequest; import im.turms.server.common.cluster.service.rpc.NodeTypeToHandleRpc; import im.turms.server.common.cluster.service.rpc.dto.RpcRequest; import im.turms.server.common.dto.ServiceRequest; import im.turms.server.common.dto.ServiceResponse; import im.turms.server.common.rpc.service.IServiceRequestDispatcher; import io.micrometer.core.instrument.Tag; import lombok.Data; import org.springframework.context.ApplicationContext; import reactor.core.publisher.Mono; /** * @author James Chen */ @Data public class HandleServiceRequest extends RpcRequest<ServiceResponse> { private static final String NAME = "handleServiceRequest"; private static final String METRICS_TAG_CLIENT_REQUEST_TYPE = "type"; private static IServiceRequestDispatcher dispatcher; private final ServiceRequest serviceRequest; public HandleServiceRequest(ServiceRequest serviceRequest) { this.serviceRequest = serviceRequest; } @Override public String toString() { return "HandleServiceRequest{" + "name='" + name() + "'" + ", tag=" + tag() + ", requestTime=" + getRequestTime() + ", tracingContext=" + getTracingContext() + ", serviceRequest=" + serviceRequest + '}'; } @Override public String name() { return NAME; } @Override public NodeTypeToHandleRpc nodeTypeToRequest() { return NodeTypeToHandleRpc.GATEWAY; } @Override public NodeTypeToHandleRpc nodeTypeToRespond() { return NodeTypeToHandleRpc.SERVICE; } @Override public Tag tag() { TurmsRequest.KindCase type = serviceRequest.getType(); if (type == null) { return null; } return Tag.of(METRICS_TAG_CLIENT_REQUEST_TYPE, type.name()); } @Override public boolean isAsync() { return true; } @Override public void setApplicationContext(ApplicationContext applicationContext) { super.setApplicationContext(applicationContext); if (dispatcher == null) { dispatcher = getBean(IServiceRequestDispatcher.class); } } @Override public Mono<ServiceResponse> callAsync() { return dispatcher.dispatch(getTracingContext(), serviceRequest); } @Override public void retainBoundBuffer() { serviceRequest.getTurmsRequestBuffer().retain(); } @Override public void releaseBoundBuffer() { serviceRequest.getTurmsRequestBuffer().release(); } @Override public void touchBuffer(Object hint) { serviceRequest.getTurmsRequestBuffer().touch(hint); } }
29.508621
78
0.685364
fbe291c3ae57a58bf2ed7e1d917a96511b317dcc
1,740
/** * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file * except in compliance with the License. A copy of the License is located at * *     http://aws.amazon.com/apache2.0/ * * or in the "LICENSE.TXT" file accompanying this file. This file 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 nullren.global.table.hack.hive.dynamodb.type; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import nullren.global.table.hack.dynamodb.type.DynamoDBListType; import nullren.global.table.hack.hive.dynamodb.util.DynamoDBDataParser; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import java.util.ArrayList; import java.util.List; public class HiveDynamoDBListType extends DynamoDBListType implements HiveDynamoDBType { private final DynamoDBDataParser parser = new DynamoDBDataParser(); @Override public AttributeValue getDynamoDBData(Object data, ObjectInspector objectInspector) { List<Object> values = parser.getListAttribute(data, objectInspector, getDynamoDBType()); if ((values != null) && (!values.isEmpty())) { List<AttributeValue> toSet = new ArrayList<AttributeValue>(); AttributeValue outer = new AttributeValue(); for (Object v : values) { toSet.add(HiveDynamoDBTypeUtil.parseObject(v)); } return outer.withL(toSet); } else { return null; } } @Override public Object getHiveData(AttributeValue data, String hiveType) { if (data == null) { return null; } return data.getL(); } }
34.8
94
0.736207
0328f6907e98a4408d0af473d1a862559bc4e8c2
1,155
/*** * Excerpted from "Language Implementation Patterns", * published by The Pragmatic Bookshelf. * Copyrights apply to this code. It may not be used to create training material, * courses, books, articles, and the like. Contact us if you are in doubt. * We make no guarantees that this code is fit for any purpose. * Visit http://www.pragmaticprogrammer.com/titles/tpdsl for more book information. ***/ import java.io.*; public class StreamVacuum implements Runnable { StringBuilder buf = new StringBuilder(); BufferedReader in; Thread sucker; public StreamVacuum(InputStream in) { this.in = new BufferedReader( new InputStreamReader(in) ); } public void start() { sucker = new Thread(this); sucker.start(); } public void run() { try { String line = in.readLine(); while (line!=null) { buf.append(line); buf.append('\n'); line = in.readLine(); } } catch (IOException ioe) { System.err.println("can't read output from process"); } } /** wait for the thread to finish */ public void join() throws InterruptedException { sucker.join(); } public String toString() { return buf.toString(); } }
26.860465
83
0.690909
6c3708cef460656744219e4eeeba4a631fae5df0
2,466
/** * 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.avro.file; import java.io.IOException; import java.nio.ByteBuffer; import org.junit.Test; import static org.junit.Assert.assertTrue; public class TestBZip2Codec { @Test public void testBZip2CompressionAndDecompression() throws IOException { Codec codec = CodecFactory.fromString("bzip2").createInstance(); assertTrue(codec instanceof BZip2Codec); assertTrue(codec.getName().equals("bzip2")); //This is 3 times the byte buffer on the BZip2 decompress plus some extra final int inputByteSize = BZip2Codec.DEFAULT_BUFFER_SIZE * 3 + 42; byte[] inputByteArray = new byte[inputByteSize]; //Generate something that will compress well for (int i = 0; i < inputByteSize; i++) { inputByteArray[i] = (byte)(65 + i % 10); } ByteBuffer inputByteBuffer = ByteBuffer.wrap(inputByteArray); ByteBuffer compressedBuffer = codec.compress(inputByteBuffer); //Make sure something returned assertTrue(compressedBuffer.array().length > 0); //Make sure the compressed output is smaller then the original assertTrue(compressedBuffer.array().length < inputByteArray.length); ByteBuffer decompressedBuffer = codec.decompress(compressedBuffer); //The original array should be the same length as the decompressed array assertTrue(decompressedBuffer.array().length == inputByteArray.length); //Every byte in the outputByteArray should equal every byte in the input array byte[] outputByteArray = decompressedBuffer.array(); for (int i = 0; i < inputByteSize; i++) { inputByteArray[i] = outputByteArray[i]; } } }
37.938462
83
0.725872
c14c90565df522ee5368a44fb8efcd20ce6f8ace
488
package me.philcali.device.pool.lock; import me.philcali.device.pool.exceptions.LockingException; import me.philcali.device.pool.model.LockInput; import me.philcali.device.pool.model.LockOutput; import java.util.Optional; import java.util.concurrent.CompletableFuture; public interface LockingMechanism { CompletableFuture<LockOutput> lock(LockInput input); LockOutput extend(LockInput input) throws LockingException; void lease(String lockId) throws LockingException; }
28.705882
63
0.815574
047d975867ebd8025500b7881a2722756d608d41
1,835
package com.example.tetianapriadko.myapplication; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class Lesson104_2 extends Fragment{ final String LOG_TAG = "myLogs"; @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(LOG_TAG, "Fragment2 onAttach"); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(LOG_TAG, "Fragment2 onCreate"); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(LOG_TAG, "Fragment2 onCreateView"); return inflater.inflate(R.layout.activity_lesson104_2, null) ; } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.d(LOG_TAG, "Fragment2 onActivityCreated"); } public void onStart() { super.onStart(); Log.d(LOG_TAG, "Fragment2 onStart"); } public void onResume() { super.onResume(); Log.d(LOG_TAG, "Fragment2 onResume"); } public void onPause() { super.onPause(); Log.d(LOG_TAG, "Fragment2 onPause"); } public void onStop() { super.onStop(); Log.d(LOG_TAG, "Fragment2 onStop"); } public void onDestroyView() { super.onDestroyView(); Log.d(LOG_TAG, "Fragment2 onDestroyView"); } public void onDestroy() { super.onDestroy(); Log.d(LOG_TAG, "Fragment2 onDestroy"); } public void onDetach() { super.onDetach(); Log.d(LOG_TAG, "Fragment2 onDetach"); } }
25.84507
74
0.643597
0fde2f18a2876a6dff282ef6c47a200620769829
5,092
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference // Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.11.10 at 01:13:12 PM EET // package ee.ria.dhx.types.eu.x_road.xsd.xroad; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p> * Java class for SecurityServerType complex type. * * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SecurityServerType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="owner" type="{http://www.w3.org/2001/XMLSchema}IDREF"/&gt; * &lt;element name="serverCode" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="address" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="authCertHash" type="{http://www.w3.org/2001/XMLSchema}base64Binary" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;element name="client" type="{http://www.w3.org/2001/XMLSchema}IDREF" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SecurityServerType", propOrder = { "owner", "serverCode", "address", "authCertHash", "client" }) public class SecurityServerType { @XmlElement(required = true) @XmlIDREF @XmlSchemaType(name = "IDREF") protected Object owner; @XmlElement(required = true) protected String serverCode; protected String address; protected List<byte[]> authCertHash; @XmlElementRef(name = "client", type = JAXBElement.class, required = false) protected List<JAXBElement<Object>> client; /** * Gets the value of the owner property. * * @return possible object is {@link Object } * */ public Object getOwner() { return owner; } /** * Sets the value of the owner property. * * @param value allowed object is {@link Object } * */ public void setOwner(Object value) { this.owner = value; } /** * Gets the value of the serverCode property. * * @return possible object is {@link String } * */ public String getServerCode() { return serverCode; } /** * Sets the value of the serverCode property. * * @param value allowed object is {@link String } * */ public void setServerCode(String value) { this.serverCode = value; } /** * Gets the value of the address property. * * @return possible object is {@link String } * */ public String getAddress() { return address; } /** * Sets the value of the address property. * * @param value allowed object is {@link String } * */ public void setAddress(String value) { this.address = value; } /** * Gets the value of the authCertHash property. * * <p> * This accessor method returns a reference to the live list, not a snapshot. Therefore any * modification you make to the returned list will be present inside the JAXB object. This is why * there is not a <CODE>set</CODE> method for the authCertHash property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getAuthCertHash().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list byte[] * * @return list of byte */ public List<byte[]> getAuthCertHash() { if (authCertHash == null) { authCertHash = new ArrayList<byte[]>(); } return this.authCertHash; } /** * Gets the value of the client property. * * <p> * This accessor method returns a reference to the live list, not a snapshot. Therefore any * modification you make to the returned list will be present inside the JAXB object. This is why * there is not a <CODE>set</CODE> method for the client property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getClient().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link JAXBElement }{@code <} * {@link Object }{@code >} * * @return list of {@link JAXBElement} */ public List<JAXBElement<Object>> getClient() { if (client == null) { client = new ArrayList<JAXBElement<Object>>(); } return this.client; } }
26.941799
137
0.647486
d201430aa761bb1ad5ae2256b105857daabb7ed3
1,072
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.freebasicacc.ui.observer; import com.freebasicacc.util.DateUtil; import com.qt.datapicker.DatePicker; import java.util.Calendar; import java.util.Observable; import java.util.Observer; import javax.swing.JTextField; /** * * @author benzyaa */ public class DateInputFieldObserver implements Observer{ private JTextField dateTextField; @Override public void update(Observable o, Object arg) { Calendar calendar = (Calendar)arg; DatePicker dp = (DatePicker)o; this.dateTextField.setText(DateUtil.convertDateUtilToDateStr(calendar.getTime())); this.dateTextField.setText(dp.formatDate(calendar)); } /** * @return the dateTextField */ public JTextField getDateTextField() { return dateTextField; } /** * @param dateTextField the dateTextField to set */ public void setDateTextField(JTextField dateTextField) { this.dateTextField = dateTextField; } }
25.52381
90
0.702425
776cdd6e28312731431980d1cb56807bfc53c16a
4,565
package de.minecrafthaifl.nyanfighters; import com.minnymin.command.CommandFramework; import de.minecrafthaifl.nyanfighters.commands.NyanfightersCommands; import de.minecrafthaifl.nyanfighters.listeners.*; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; /** * Created by Paul on 27.04.2016. */ public class Nyanfighters extends JavaPlugin { private static Nyanfighters plugin; //Klasse Nyanfighters private CommandFramework framework; //framework für die Commands private File spawnpoints; //Spawnpointsfile private FileConfiguration spawnpointsc; private File players; //Attacker-File private FileConfiguration playersc; private File stats; //Stats-File private FileConfiguration statsc; private boolean game; //Spiel-Variable private boolean nomove; //Vorbereitung-Variable //private boolean noblocks; //skyfall-Variable public void onEnable() { game=false; nomove=false; // noblocks=false; plugin = this; framework = new CommandFramework(this); framework.registerCommands(new NyanfightersCommands()); spawnpoints = YamlHandler.createFile("spawnpoints.yml"); spawnpointsc = YamlHandler.createYamlFile(spawnpoints); players = YamlHandler.createTempFile("players.yml"); playersc = YamlHandler.createYamlFile(players); stats= YamlHandler.createTempFile("stats.yml"); statsc= YamlHandler.createYamlFile(stats); registerListener(); GameListener.lobbyWait(); } public void onDisable() { for(Player p: Bukkit.getOnlinePlayers()) //Notwendig wegen der Spectator-Collection { p.kickPlayer("Reload!"); } } public static Nyanfighters getInstance() { return plugin; } public File getSpawnpoints() { return spawnpoints; } public FileConfiguration getSpawnpointsConfi() { return spawnpointsc; } public File getPlayers() { return players; } public FileConfiguration getPlayersConfi() { return playersc; } public File getStats() { return stats; } public FileConfiguration getStatsConfi() { return statsc; } public boolean getGame() {return game;} public void setGame(boolean g){game=g;} public void setNoMove(boolean g){nomove=g;} public boolean getNoMove() {return nomove;} //public void setNoBlocks(boolean b){noblocks=b;} //public boolean getNoBlocks() {return noblocks;} public void registerListener() { Bukkit.getPluginManager().registerEvents(new JoinListener(), this); Bukkit.getPluginManager().registerEvents(new HungerListener(), this); Bukkit.getPluginManager().registerEvents(new MoveListener(), this); Bukkit.getPluginManager().registerEvents(new AttackListener(),this); Bukkit.getPluginManager().registerEvents(new ProjectileHitListener(), this); Bukkit.getPluginManager().registerEvents(new RightClickListener(), this); Bukkit.getPluginManager().registerEvents(new LeaveListener(), this); Bukkit.getPluginManager().registerEvents(new EntityDamageListener(), this); Bukkit.getPluginManager().registerEvents(new FallDamageListener(), this); Bukkit.getPluginManager().registerEvents(new DeathListener(), this); Bukkit.getPluginManager().registerEvents(new BlockBreakListener(), this); Bukkit.getPluginManager().registerEvents(new ChatListener(), this); } }
44.320388
163
0.562103
5c049bd2b7e85112ae34b9cbc9ee3c8bb44272b1
700
package com.periscope.qviz.json; import java.util.ArrayList; import java.util.List; /** * JSON Model for API Test Case Details */ public class TestCaseAPI extends TestCase { /** * List of Test Case Step Objects associated with the Test Case */ public List<TestCaseStep> testCaseSteps; /** * Lise of Test Action Objects associated with the Test Case */ public List<Action> testActions; /** * List of Test API Objects associated with the Test Case */ public List<TestAPI> testAPIs; /** * Default Constructor */ public TestCaseAPI() { super(); this.testCaseSteps = new ArrayList<>(); this.testActions = new ArrayList<>(); this.testAPIs = new ArrayList<>(); } }
18.918919
64
0.692857
21657dcb3f851227f43d90d33779af99950f3478
62
package io.qiot.covid19.datahub.collector.gas.service.station;
62
62
0.854839