blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
cf6aa0a46bca866af43a2b119ca4b52535a89ab9
|
Java
|
zippo88li/netstudy
|
/src/main/java/com/gupao/lzp/pattern/factory/factorymethod/NokiaMobileFactory.java
|
UTF-8
| 314
| 2.3125
| 2
|
[] |
no_license
|
package com.gupao.lzp.pattern.factory.factorymethod;
import com.gupao.lzp.pattern.factory.simplefactory.IMobile;
import com.gupao.lzp.pattern.factory.simplefactory.NokiaMobile;
public class NokiaMobileFactory implements IMobileFactory {
public IMobile create() {
return new NokiaMobile();
}
}
| true
|
8883771b734c3a9ae0b949e120988d75917fa0ca
|
Java
|
yuripourre/etyllica-slides
|
/Mario Slide/src/MarioExample.java
|
UTF-8
| 876
| 2.140625
| 2
|
[] |
no_license
|
import mario.editor.MarioMapEditor;
import mario.stages.first.YoshiIsland2;
import br.com.etyllica.EtyllicaFrame;
import br.com.etyllica.context.Application;
import br.com.etyllica.core.loader.JoystickLoader;
public class MarioExample extends EtyllicaFrame {
private static final long serialVersionUID = 1L;
public MarioExample() {
//super(255, 236);
//super(800, 600);
super(512, 432);
//initJoysick = true;
}
public static void main(String[] args){
MarioExample marioExample = new MarioExample();
marioExample.init();
}
@Override
public Application startApplication() {
/*hideCursor();
addLoader(MultimediaLoader.getInstance());
return new YoshiHouse(w,h);*/
JoystickLoader.getInstance().start(1);
new Thread(JoystickLoader.getInstance()).start();
return new YoshiIsland2(w,h);
//return new MarioMapEditor(w, h);
}
}
| true
|
3a67965a67320da28f29ec026ca9bf0557ec05a6
|
Java
|
RevelationCollection/study
|
/study-jdk/src/main/java/com/algorithm/sort/tree/TreeNode.java
|
UTF-8
| 992
| 3.53125
| 4
|
[] |
no_license
|
package com.algorithm.sort.tree;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
public static TreeNode initRoot(int[] arr){
if (arr==null||arr.length<1){
return null;
}
TreeNode root = new TreeNode(arr[0]);
if (arr.length<2){
return root;
}
for (int i = 1; i < arr.length; i++) {
addNode(root,arr[i]);
}
return root;
}
public static void addNode(TreeNode node, int val){
if (node==null){
return;
}
if (node.val > val){
if (node.left==null){
node.left = new TreeNode(val);
}else {
addNode(node.left,val);
}
return;
}
if (node.right ==null){
node.right = new TreeNode(val);
return;
}
addNode(node.right,val);
}
}
| true
|
d76ab45048e3df7f970cc646a9bacfe24199b9e0
|
Java
|
TOOP4EU/toop-commons-ng
|
/toop-edm/src/main/java/eu/toop/edm/xml/IJAXBVersatileReader.java
|
UTF-8
| 9,430
| 1.898438
| 2
|
[
"LicenseRef-scancode-unknown-license-reference",
"EUPL-1.2"
] |
permissive
|
/**
* Copyright 2021 - TOOP Project
*
* This file and its contents are licensed under the EUPL, Version 1.2
* or – as soon they will be approved by the European Commission – subsequent
* versions of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the Licence for the specific language governing permissions and limitations under the Licence.
*/
package eu.toop.edm.xml;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.charset.CharsetHelper;
import com.helger.commons.charset.CharsetHelper.InputStreamAndCharset;
import com.helger.commons.io.IHasInputStream;
import com.helger.commons.io.resource.IReadableResource;
import com.helger.commons.io.stream.ByteBufferInputStream;
import com.helger.commons.io.stream.NonBlockingByteArrayInputStream;
import com.helger.commons.io.stream.NonBlockingStringReader;
import com.helger.commons.io.stream.StreamHelper;
import com.helger.xml.EXMLParserFeature;
import com.helger.xml.sax.InputSourceFactory;
import com.helger.xml.serialize.read.SAXReaderFactory;
import com.helger.xml.serialize.read.SAXReaderSettings;
/**
* Interface for reading XML documents from various sources.
*
* @author Philip Helger
* @param <T>
* The type to be read
*/
public interface IJAXBVersatileReader <T>
{
/**
* Read a document from the specified input source. The secure reading feature
* has affect when using this method.
*
* @param aInputSource
* The source to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final InputSource aInputSource)
{
// Initialize settings with defaults
return read (new SAXReaderSettings (), aInputSource);
}
/**
* Read a document from the specified input source using the specified SAX
* reader settings. The secure reading must be enabled in the SAX settings.
*
* @param aSettings
* The SAX Settings to use.
* @param aInputSource
* The source to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final SAXReaderSettings aSettings, @Nonnull final InputSource aInputSource)
{
ValueEnforcer.notNull (aSettings, "Settings");
ValueEnforcer.notNull (aInputSource, "InputSource");
// Apply settings that make reading more secure
aSettings.setFeatureValues (EXMLParserFeature.AVOID_XML_ATTACKS);
// Create new XML reader
final XMLReader aParser = SAXReaderFactory.createXMLReader ();
aSettings.applyToSAXReader (aParser);
// And read via JAXB
return read (new SAXSource (aParser, aInputSource));
}
/**
* Read a document from the specified input stream. The secure reading feature
* has affect when using this method.
*
* @param aIS
* The input stream to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final InputStream aIS)
{
ValueEnforcer.notNull (aIS, "InputStream");
final InputStreamAndCharset aISAndBOM = CharsetHelper.getInputStreamAndCharsetFromBOM (aIS);
if (aISAndBOM.hasCharset ())
{
// BOM was found - read from Reader
return read (StreamHelper.createReader (aISAndBOM.getInputStream (), aISAndBOM.getCharset ()));
}
// No BOM found - use the returned InputStream anyway, so that the pushed
// back bytes are read
return read (InputSourceFactory.create (aISAndBOM.getInputStream ()));
}
/**
* Read a document from the specified reader. The secure reading feature has
* affect when using this method.
*
* @param aReader
* The reader to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final Reader aReader)
{
ValueEnforcer.notNull (aReader, "Reader");
return read (InputSourceFactory.create (aReader));
}
/**
* Read a document from the specified file. The secure reading feature has
* affect when using this method.
*
* @param aFile
* The file to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final File aFile)
{
ValueEnforcer.notNull (aFile, "File");
// Use InputSourceFactory to have the systemId if possible
return read (InputSourceFactory.create (aFile));
}
/**
* Read a document from the specified Path. The secure reading feature has
* affect when using this method.
*
* @param aPath
* The path to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final Path aPath)
{
ValueEnforcer.notNull (aPath, "Path");
// Use InputSourceFactory to have the systemId if possible
return read (InputSourceFactory.create (aPath));
}
/**
* Read a document from the specified resource. The secure reading feature has
* affect when using this method.
*
* @param aResource
* The resource to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final IReadableResource aResource)
{
ValueEnforcer.notNull (aResource, "Resource");
// Use InputSourceFactory to have the systemId if possible
return read (InputSourceFactory.create (aResource));
}
/**
* Read a document from the specified input stream provider. The secure
* reading feature has affect when using this method.
*
* @param aISP
* The input stream provider to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final IHasInputStream aISP)
{
ValueEnforcer.notNull (aISP, "Resource");
// Ensure to use InputStream for BOM handling
return read (aISP.getInputStream ());
}
/**
* Read a document from the specified byte array. The secure reading feature
* has affect when using this method.
*
* @param aXML
* The XML bytes to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final byte [] aXML)
{
ValueEnforcer.notNull (aXML, "XML");
// Ensure to use InputStream for BOM handling
return read (new NonBlockingByteArrayInputStream (aXML));
}
/**
* Read a document from the specified byte buffer. The secure reading feature
* has affect when using this method.
*
* @param aXML
* The XML bytes to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final ByteBuffer aXML)
{
ValueEnforcer.notNull (aXML, "XML");
// Ensure to use InputStream for BOM handling
return read (new ByteBufferInputStream (aXML));
}
/**
* Read a document from the specified String. The secure reading feature has
* affect when using this method.
*
* @param sXML
* The XML string to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final String sXML)
{
ValueEnforcer.notNull (sXML, "XML");
return read (new NonBlockingStringReader (sXML));
}
/**
* Read a document from the specified char array. The secure reading feature
* has affect when using this method.
*
* @param aXML
* The XML string to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
default T read (@Nonnull final char [] aXML)
{
ValueEnforcer.notNull (aXML, "XML");
return read (new NonBlockingStringReader (aXML));
}
/**
* Read a document from the specified source. The secure reading feature has
* <b>NO</b> affect when using this method because the parameter type is too
* generic.
*
* @param aSource
* The source to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
T read (@Nonnull final Source aSource);
/**
* Read a document from the specified DOM node. The secure reading feature has
* <b>NO</b> affect when using this method because no parsing happens! To
* ensure secure reading the Node must first be serialized to a String and be
* parsed again!
*
* @param aNode
* The DOM node to read. May not be <code>null</code>.
* @return <code>null</code> in case reading fails.
*/
@Nullable
T read (@Nonnull final Node aNode);
}
| true
|
3e449459d6cb8119212a9e2f2a6943d4c868235f
|
Java
|
MagnusPoppe/6120Eksamen2017
|
/app/src/main/java/no/byteme/magnuspoppe/eksamen/AsynkronDestinasjon.java
|
UTF-8
| 12,185
| 2.546875
| 3
|
[] |
no_license
|
package no.byteme.magnuspoppe.eksamen;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import no.byteme.magnuspoppe.eksamen.datamodel.Bruker;
import no.byteme.magnuspoppe.eksamen.datamodel.Destinasjon;
/**
* En klasse for å asynkront koble seg opp mot REST api
* kjørende på tjeneren itfag.usn.no/~210852/
*
* Created by MagnusPoppe on 29/05/2017.
*/
public class AsynkronDestinasjon
{
// URL for å koble seg opp:
private final String GRUNN_URL = "http://itfag.usn.no/~210852/api.php/destination/";
// Variabler for opplasting av lokalt lagrede destinasjoner:
private boolean utførSlettingEtterOpplasting;
private int[] skalSlettes;
ActivityCtrl aktivitet;
/**
* Konstruktør for REST rammeverk:
* @param activity
*/
public AsynkronDestinasjon(ActivityCtrl activity)
{
this.aktivitet = activity;
this.utførSlettingEtterOpplasting = false;
}
/**
* Henter ut alle destinasjoner liggende i databasen.
*/
public void get()
{
DestinasjonsOppgave oppgave = new DestinasjonsOppgave();
oppgave.execute(GRUNN_URL, "GET");
}
/**
* Henter ut alle destinasjonene for en gitt bruker:
* @param bruker epost
* @return
*/
public ArrayList<Destinasjon> get( Bruker bruker )
{
return null; // NOT YET IMPLEMENTED
}
/**
* Henter ut en gitt destinasjon med en gitt ID fra databasen
* @param id i global database
* @return
*/
public ArrayList<Destinasjon> get(int id )
{
return null; // NOT YET IMPLEMENTED
}
/**
* Lagrer et destinasjonsobjekt inn i databasen ved hjelp av POST.
* Destinasjon konverteres til JSON før opplasting.
* @param destinasjon som skal lagres.
*/
public void post(Destinasjon destinasjon)
{
DestinasjonsOppgave oppgave = new DestinasjonsOppgave();
oppgave.execute(GRUNN_URL, "POST", destinasjon.toJSON());
}
/**
* Laster opp en gruppe med destinasjonsobjekter i en sending.
* Dette krever at JSON objektene blir formatert inn i en JSON
* array.
* @param destinasjoner som skal sendes
*/
public void post(Destinasjon[] destinasjoner)
{
// Bygger JSON streng:
StringBuilder json = new StringBuilder("[");
for (int i = 0; i < destinasjoner.length; i++)
{
json.append(destinasjoner[i].toJSON());
if (i < destinasjoner.length-1) json.append(",");
}
json.append("]");
// Laster opp:
DestinasjonsOppgave oppgave = new DestinasjonsOppgave();
oppgave.execute(GRUNN_URL, "POST", json.toString());
}
/**
* Spesial case, setter variabler for bruk av Callback
* definert i "mellomLagerKontrakt" for å slette etter
* komplett opplasting.
* @param destinasjoner
*/
public void postUopplastet(Destinasjon[] destinasjoner)
{
// Setter variabel for utføring av callback:
utførSlettingEtterOpplasting = true;
// Lagrer IDer på rader som skal slettes lokalt:
skalSlettes = new int[destinasjoner.length];
for (int i = 0; i < destinasjoner.length; i++)
{
skalSlettes[i] = destinasjoner[i].getDatabaseID();
}
// Utfører opplasting:
post(destinasjoner);
}
/**
* Den asynkrone opplastingsklassen. Denne laster opp elementer med HTTP
* metode. Den kan sende med data også. Her følger jeg hovedsakelig
* mønsteret vist i forelesning, men med en vri jeg lærte fra et sett
* med videoer på YouTube, publisert av Udacity i samarbeid med Google:
* https://www.youtube.com/playlist?list=PLAwxTw4SYaPmXoZF20ky_Amke3Mu4lZEo
*
* Her sender jeg med de nødvendige parameterene som Strenger. Man kan ha
* et ubestemt antall parametere til "exectute()" metoden til AsyncTask.
* Parametere:
* 0: URL til opplastingsplassering
* 1: HTTP METODE som skal brukes
* 2: Pakken som skal lastes opp i JSON format:
*/
private class DestinasjonsOppgave extends AsyncTask<String, Void, Long>
{
// PARAMS KONSTANTER:
final static int URL = 0;
final static int HTTP_METODE = 1;
final static int PAKKE = 2;
// Statuscodes:
final static long FEIL = 0l;
final static long OK = 1l;
final static long JSON_ANALYSE_FEIL = 3l;
final static long IO_FEIL = 4l;
final static long FEILFORMATERT_URL_FEIL = 5l;
/**
* Bakgrunnsoppgaven som utfører opplastingen til tjeneren:
* @param params parametere som legges ved i sendingen
* 0: URL til opplastingsplassering
* 1: HTTP METODE som skal brukes
* 2: Pakken som skal lastes opp i JSON format, Tom hvis ingen sending
* @return statuskode
*/
@Override
protected Long doInBackground(String... params)
{
HttpURLConnection oppkobling = null;
long resultat = 0L;
try
{
// Setter opp koblingen:
java.net.URL url = new URL(params[URL]);
oppkobling = (HttpURLConnection) url.openConnection();
oppkobling.setRequestMethod(params[HTTP_METODE]);
// Denne gjelder egentlig bare "PUT" og "POST" men
// er med alikevel.
oppkobling.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// Hvis PUT / POST / DELETE metoden er i bruk skal man sende med data.
if (params[HTTP_METODE].equals("PUT")
|| params[HTTP_METODE].equals("POST")
|| params[HTTP_METODE].equals("DELETE"))
{
// For å motta data tilbake. Denne kan ikke settes for begge
// utefor IF av ukjente oversaker.
oppkobling.setDoInput(true);
// oppsett for å sende med data:
oppkobling.setDoOutput(true);
oppkobling.setChunkedStreamingMode(0);
oppkobling.setRequestProperty("Transfer-Encoding", "chunked");
}
// Elles skal man fortsatt motta data:
else {
oppkobling.setDoInput(true);
}
// Kobler opp:
oppkobling.connect();
// Hvis PUT / POST / DELETE metoden er i bruk skal man sende med data.
if (params[HTTP_METODE].equals("PUT")
|| params[HTTP_METODE].equals("POST")
|| params[HTTP_METODE].equals("DELETE"))
{
// Utfører sendingen av data:
OutputStreamWriter ut = new OutputStreamWriter(oppkobling.getOutputStream());
ut.write(params[PAKKE]);
ut.close();
}
// Sjekker statuskoden for feil. Et REST API skal alltid levere
// tilbake en fornuftig statuskode. Dette gjeler også mitt API:
int respons = oppkobling.getResponseCode();
if (respons != HttpURLConnection.HTTP_OK)
return FEIL;
// Ved GET forespørsel skal vi ha tilbake data:
if (params[HTTP_METODE].equals("GET"))
{
// Lager innlesingsobjekt:
BufferedReader innleser = new BufferedReader(new InputStreamReader(
oppkobling.getInputStream())
);
// Bruker string builder for raskere oppbygging av JSON svaret:
StringBuilder pakke = new StringBuilder();
String linje;
// Leser inn data:
while ((linje = innleser.readLine()) != null)
pakke.append(linje);
// Analyse (PARSE) og gjennomgang av JSON:
analyserData(pakke.toString());
}
// Sender tilbake at alt er OK!
resultat = OK;
}
// CATCH FRO FORSKJELLIGE FEILMELDINGER:
catch (MalformedURLException e)
{
Log.e("ASYNC FEIL", aktivitet.getResources().getString(R.string.error) + e);
resultat = FEILFORMATERT_URL_FEIL;
} catch (IOException e)
{
Log.e("ASYNC FEIL", aktivitet.getResources().getString(R.string.error) + e);
resultat = IO_FEIL;
} catch (JSONException e)
{
Log.e("ASYNC FEIL", aktivitet.getResources().getString(R.string.error) + e);
resultat = JSON_ANALYSE_FEIL;
} finally
{
// Tilslutt skal det uansett kobles ned:
if (oppkobling != null)
oppkobling.disconnect();
}
return resultat;
}
/**
* Lager objekter ut av de mottatte dataene. Dataene blir også sortert.
* Jeg har valgt å gjøre dette i bakgrunn grunnet at det er en tung prosess
* som ikke er ønsket på UI tråden.
*
* Som kommentar til obligatorisk innlevering 2 fikk jeg beskjed om at denne
* typen tolkingsmetode hører hjemme i Modellklassen (som i dette tilfellet
* skulle vært Destinasjon). Dette mener jeg er motsatt. At selve analysen
* av strengen burde gjøres her, mens lagringen av hvert objekt gjøres med
* konstruktør.
*
* @param json data hentet ut av nettverkskallet.
* @throws JSONException
*/
private void analyserData(String json) throws JSONException
{
// Tolker dataene
JSONArray tabell = new JSONArray(json);
// Lager en ut liste
ArrayList<Destinasjon> destinasjoner = new ArrayList<>();
for (int i = 0; i < tabell.length(); i++)
destinasjoner.add(new Destinasjon( (JSONObject) tabell.get(i)));
// Setter på og sorterer:
aktivitet.setDestinasjoner(destinasjoner);
}
/**
* "onPostExecute" lagrer kun en statusmelding. Dette blir logget i
* android enheten.
* @param resultat av oppkobling
*/
@Override
protected void onPostExecute(Long resultat)
{
super.onPostExecute(resultat);
String status = "";
if (resultat == OK)
{
status = "Executed rest call successfully.";
// Utfører callback hvis nødvendig:
if (utførSlettingEtterOpplasting)
aktivitet.vedKomplettOpplastingAvDestinasjoner(skalSlettes);
// Oppdaterer uansett listen hvis nødvending:
aktivitet.oppdaterDestnasjonsliste();
} else if (resultat == FEILFORMATERT_URL_FEIL)
{
status = "Bad url...";
} else if (resultat == IO_FEIL)
{
status = "Problems reading the downloaded data. ( I/O FEIL )";
} else if (resultat == JSON_ANALYSE_FEIL)
{
status = "Bad JSON format on data.";
} else if (resultat == FEIL)
{
status = "Something went wrong.";
} else
{
status = "Unknown errorcode... WHAT?!";
}
// Logger resultat:
Log.d("ASYNC_POST_EXECUTE", "Result-code=" + resultat + ", Message=" + status);
}
}
}
| true
|
ba6890d5a72cd4850bfd307907b8ca75b7b98a60
|
Java
|
mcdehaan/GildedRose-Refactoring-Kata
|
/Java/src/test/java/com/gildedrose/GildedRoseTestHelper.java
|
UTF-8
| 1,251
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
package com.gildedrose;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class GildedRoseTestHelper {
public void testAssertion(Item[] items, int expectedSellInChange, int expectedQualityChange) throws Exception {
//Assert each item in list of items
for (Item itemUnderTest : items) {
//Prepare app under test
GildedRose appUnderTest = new GildedRose(items);
//Define original and expected sellIn values of item under test
int originalSellIn = itemUnderTest.sellIn;
int expectedSellIn = originalSellIn + expectedSellInChange;
//Define original and expected quality values of item under test
int originalQuality = itemUnderTest.quality;
int expectedQuality = originalQuality + expectedQualityChange;
//Build expected string output to compare with output of app under test
String expectedResult = itemUnderTest.name+", "+expectedSellIn+", "+expectedQuality;
//Run app under test
appUnderTest.updateQuality();
//Compare expected output to output of app under test
assertEquals(expectedResult, itemUnderTest.toString());
}
}
}
| true
|
6c3336cb9bf6dfae0386455d0c617a7d6c91b75d
|
Java
|
suxuehui/OMS-2
|
/src/main/java/com/oms/core/customer/service/ClientServiceImpl.java
|
UTF-8
| 1,777
| 2.15625
| 2
|
[] |
no_license
|
package com.oms.core.customer.service;
import com.oms.core.customer.dao.ClientDao;
import com.oms.core.customer.entity.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.List;
@Service
@Transactional(readOnly = true)
public class ClientServiceImpl implements ClientService{
@Autowired
private ClientDao clientDao;
@Transactional
@Override
public void save(Client client){
Assert.notNull(client, "客户信息不能我为空");
Assert.hasText(client.getAccountId(), "关联账户ID不能为空");
Assert.hasText(client.getName(), "客户姓名不能为空");
Assert.hasText(client.getWxno(), "客户微信不能为空");
clientDao.saveOrUpdate(client);
}
@Transactional
@Override
public void update(Client client){
Assert.notNull(client, "客户信息不能我为空");
Assert.hasText(client.getId(), "客户ID不能为空");
clientDao.saveOrUpdate(client);
}
@Override
public boolean existByAccountIdAndWxno(String accountId, String wxno){
Assert.hasText(accountId, "关联的账户ID不能为空");
Assert.hasText(wxno, "客户微信号不能为空");
return clientDao.existByAccountIdAndWxno(accountId, wxno);
}
@Override
public List<Client> find(String accountId, String name, String wxno, String remark){
return clientDao.find(accountId, name, wxno, remark);
}
@Override
public Client getById(String id){
Assert.hasText(id, "客户ID不能为空");
return clientDao.getById(id);
}
}
| true
|
837244d8545c4aa156e341a9fc27d1e08d62808b
|
Java
|
aixohub/aixohub-leetcode
|
/src/main/java/com/aixohub/leetcode/simple/validParentheses/ValidParentheses.java
|
UTF-8
| 1,629
| 3.671875
| 4
|
[
"Apache-2.0"
] |
permissive
|
package com.aixohub.leetcode.simple.validParentheses;
import com.google.common.primitives.Chars;
import java.nio.charset.Charset;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
*
* 有效字符串需满足:
*
* 左括号必须用相同类型的右括号闭合。
* 左括号必须以正确的顺序闭合。
*
* 示例 1:
*
* 输入:s = "()"
* 输出:true
* 示例 2:
*
* 输入:s = "()[]{}"
* 输出:true
* 示例 3:
*
* 输入:s = "(]"
* 输出:false
* 示例 4:
*
* 输入:s = "([)]"
* 输出:false
* 示例 5:
*
* 输入:s = "{[]}"
* 输出:true
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/valid-parentheses
*/
public class ValidParentheses {
public boolean isValid(String s) {
if(s.length() % 2 == 1){
return false;
}
Map<Character, Character> dict = new HashMap<Character, Character>(){{
put('}', '{');
put(']', '[');
put(')', '(');
}};
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
if(dict.containsKey(s.charAt(i))){
if(stack == null || stack.peek() != dict.get(s.charAt(i))){
return false;
}
stack.pop();
}else{
stack.push(s.charAt(i));
}
}
return stack.isEmpty();
}
}
| true
|
40a6090a3260bd3c4a58f8d8730bc8230c0b166e
|
Java
|
XoYoKing/HN
|
/app/src/main/java/com/example/admin/hn/model/OrderUseInfo.java
|
UTF-8
| 1,285
| 2.140625
| 2
|
[] |
no_license
|
package com.example.admin.hn.model;
/**
* 船舶资料管理 订单为已选状态下数据对象
*/
public class OrderUseInfo {
public String id;//资料id
public String code;//资料编号
public String chs_name;//中文名
public String eng_name;//英文名
public String doc_id;//
public int quantity;//购买数量
public int storage_amount;//库存
public String publish_at;//出版日期
public String category_name;//资料类别
public String ship_name;//船舶名称
public String distribute_no;//分配编号(岸端分配)
public String source;//状态(区分是自选还是 岸端分配)
@Override
public String toString() {
return "OrderUseInfo{" +
"code='" + code + '\'' +
", chs_name='" + chs_name + '\'' +
", eng_name='" + eng_name + '\'' +
", quantity=" + quantity +
", storage_amount=" + storage_amount +
", publish_at='" + publish_at + '\'' +
", category_name='" + category_name + '\'' +
", ship_name='" + ship_name + '\'' +
", distribute_no='" + distribute_no + '\'' +
", source='" + source + '\'' +
'}';
}
}
| true
|
49cd9b604abd0931e877c2fea0fb290bc3d4fad2
|
Java
|
gdufexzq/DataStructures
|
/src/com/gdufe/extend/CountPrimeSetBits.java
|
UTF-8
| 1,163
| 3.28125
| 3
|
[] |
no_license
|
package com.gdufe.extend;
/**
* @Description: ${todo}
* @author xuzq
* @date 2020/1/13 11:34
* @version V1.0
*/
public class CountPrimeSetBits {
public static int countPrimeSetBits(int L, int R) {
int count = 0;
int sum = 0;
for(int i = L; i <= R; i++) {
String str = Integer.toBinaryString(i);
// 统计1的个数,然后判断1的个数之和是否是质数
for(int j = 0; j < str.length(); j++) {
if(str.charAt(j) == '1') {
sum++;
}
}
// System.out.println(sum + " " + isZhi(sum));
if(isZhi(sum)) {
count++;
}
sum = 0;
}
return count;
}
public static boolean isZhi(int sum) {
if(sum == 1) {
return false;
}
for(int i = 2; i <= Math.sqrt(sum); i++) {
if(sum % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int count = countPrimeSetBits(842, 888);
System.out.println(count);
}
}
| true
|
c41c6d9136216cb40ef289f46985530d15d8c07c
|
Java
|
sararathje/ENSF-409-Final-Project
|
/BackEnd/FileHelper.java
|
UTF-8
| 1,853
| 3.046875
| 3
|
[] |
no_license
|
package BackEnd;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import Constants.ConnectionConstants;
public class FileHelper implements ConnectionConstants
{
/**
* Uploads a file to the server's memory and saves the file name to the database.
* @param name file name
* @param content file content
* @param extension file extension
*/
void saveFile(String name, byte[] content, String extension)
{
File newFile = new File(serverDirPath + name + extension);
try{
if(! newFile.exists())
newFile.createNewFile();
FileOutputStream writer = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(writer);
bos.write(content);
bos.close();
}
catch(IOException e){
e.printStackTrace();
}
}
byte[] getFile(String name, String extension)
{
byte[] content = null;
try
{
if (extension.equals(TXT) || extension.equals(PDF))
{
File selectedFile = new File(serverDirPath + name + extension);
if(selectedFile.canRead())
{
long length = selectedFile.length();
content = new byte[(int) length];
FileInputStream fis = new FileInputStream(selectedFile);
BufferedInputStream bos = new BufferedInputStream(fis);
bos.read(content, 0, (int)length);
bos.close();
fis.close();
}
}
else
{
System.err.println("Invalid extension");
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return content;
}
public static void main()
{
FileHelper h = new FileHelper();
h.getFile("Test", TXT);
}
}
| true
|
b3cde29d6752f8550c8c3adc1ffdbdd1488db485
|
Java
|
W1nt0r/mge-gadgeothek
|
/app/src/main/java/com/example/schef/gadgeothek/ServerAddFragment.java
|
UTF-8
| 6,024
| 2.09375
| 2
|
[] |
no_license
|
package com.example.schef.gadgeothek;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Fragment;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.schef.domain.Gadget;
import com.example.schef.service.Callback;
import com.example.schef.service.DBService;
import com.example.schef.service.LibraryService;
import java.util.List;
public class ServerAddFragment extends Fragment implements View.OnClickListener, View.OnFocusChangeListener {
private EditText serverName;
private EditText serverUri;
private TextInputLayout serverNameLayout;
private TextInputLayout serverUriLayout;
private DBService db;
private Activity activity;
private Button addButton;
private ProgressBar progressBar;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_server_add, container, false);
((AppCompatActivity) activity).getSupportActionBar().setTitle(getString(R.string.server_add_title));
db = DBService.getDBService(null);
progressBar = rootView.findViewById(R.id.progressBar);
addButton = rootView.findViewById(R.id.serverAddButton);
serverName = rootView.findViewById(R.id.serverName);
serverUri = rootView.findViewById(R.id.serverUri);
serverNameLayout = rootView.findViewById(R.id.serverNameLayout);
serverUriLayout = rootView.findViewById(R.id.serverUriLayout);
serverNameLayout.setErrorEnabled(true);
serverUriLayout.setErrorEnabled(true);
serverUri.setOnFocusChangeListener(this);
rootView.findViewById(R.id.serverAddButton).setOnClickListener(this);
return rootView;
}
private void onAttachHelper(Context context) {
if (context instanceof ServerChanger) {
activity = (Activity) context;
} else {
throw new AssertionError("Activity must implement interface ServerChanger");
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
onAttachHelper(context);
}
/**
* Needed because of Android SDK 21
*/
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
onAttachHelper(activity);
}
@Override
public void onClick(final View view) {
serverUri.clearFocus();
serverName.clearFocus();
final String name = serverName.getText().toString().trim();
final String address = serverUri.getText().toString().trim();
if (name.isEmpty()) {
serverNameLayout.setError(getString(R.string.server_add_name));
} else if (address.isEmpty()) {
serverUriLayout.setError(getString(R.string.server_add_address));
} else {
// Hide keyboard
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
boolean nameExists = db.checkExistenceByName(name);
boolean addressExists = db.checkExistenceByAddress(address);
if ((!nameExists) && (!addressExists)) {
addButton.setEnabled(false);
addButton.setText(getString(R.string.server_add_waiting));
progressBar.setVisibility(ProgressBar.VISIBLE);
LibraryService.checkGadgeothekServerAddress(address, new Callback<List<Gadget>>() {
@Override
public void onCompletion(List<Gadget> input) {
db.insertNewConnection(name, address);
Toast toast = Toast.makeText(activity.getApplicationContext(), getString(R.string.server_add_added, name), Toast.LENGTH_SHORT);
toast.show();
((ServerChanger) activity).addNewServer();
}
@Override
public void onError(String message) {
addButton.setEnabled(true);
addButton.setText(getString(R.string.server_add_button));
progressBar.setVisibility(ProgressBar.GONE);
serverUriLayout.setError(getString(R.string.server_add_error));
}
});
} else {
if (nameExists) {
serverNameLayout.setError(getString(R.string.server_add_name_used));
}
if (addressExists) {
serverUriLayout.setError(getString(R.string.server_add_address_used));
}
}
}
}
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
String address = serverUri.getText().toString();
if (address.length() > 4) {
if (!address.substring(0, 4).equals("http")) {
address = "http://" + address;
}
if (address.substring(address.length() - 1).equals("/")) {
address = address.substring(0, address.length() - 1);
}
serverUri.setText(address);
}
}
}
}
| true
|
1af52290db0a50ece4b427ea2e5aeb37bcfa414c
|
Java
|
nicohe/alg
|
/tp4_ayed/src/tp04/ejercicio1/NodoGeneral.java
|
UTF-8
| 2,117
| 2.921875
| 3
|
[] |
no_license
|
package tp04.ejercicio1;
import tp02.ejercicio2.ColaGenerica;
import tp02.ejercicio2.ListaEnlazadaGenerica;
import tp02.ejercicio2.ListaGenerica;
public class NodoGeneral<T> {
private T dato;
private ListaGenerica<NodoGeneral<T>> listaHijos;
public NodoGeneral(T dato){
this.dato = dato;
listaHijos = new ListaEnlazadaGenerica<NodoGeneral<T>>();
}
public T getDato(){
return this.dato;
}
public ListaGenerica<NodoGeneral<T>> getHijos(){
return this.listaHijos;
}
public void setDato(T dato){
this.dato = dato;
}
public void setListaHijos(ListaGenerica<NodoGeneral<T>> lista){
this.listaHijos = lista;
}
public void preOrden(ListaGenerica<T> l){
l.agregarFinal(this.getDato());
ListaGenerica<NodoGeneral<T>> lHijos = this.getHijos();
lHijos.comenzar();
while(!lHijos.fin()){
(lHijos.proximo()).preOrden(l);
}
}
public void postOrden(ListaGenerica<T> l){
ListaGenerica<NodoGeneral<T>> lHijos = this.getHijos();
lHijos.comenzar();
while(!lHijos.fin()){
(lHijos.proximo()).postOrden(l);
}
l.agregarFinal(this.getDato());
}
public void inOrden(ListaGenerica<T> l){
ListaGenerica<NodoGeneral<T>> lHijos = this.getHijos();
if(lHijos.tamanio() == 0) {
l.agregarFinal(this.getDato());
} else {
lHijos.comenzar();
if(!lHijos.fin()){
(lHijos.proximo()).inOrden(l);
}
l.agregarFinal(this.getDato());
while(!lHijos.fin()){
(lHijos.proximo()).inOrden(l);
}
}
}
public void porNiveles(ListaEnlazadaGenerica<T> lis) {
NodoGeneral<T> aux;
ColaGenerica<NodoGeneral<T>> cola = new ColaGenerica<NodoGeneral<T>>();
ListaGenerica<NodoGeneral<T>> hijos;
cola.encolar(this);
while(!cola.esVacia()) {
aux = cola.desencolar();
if(aux != null) {
lis.agregarFinal(aux.getDato());
hijos = aux.getHijos();
hijos.comenzar();
while (!hijos.fin()) {
cola.encolar(hijos.proximo());
}
}else{
if(!cola.esVacia()){
cola.encolar(null);
}
}
}
}
}
| true
|
5e33c995d214bc7ea65f81df616beaa95371d6e0
|
Java
|
mjhost/anagrafica
|
/server/code/src/main/java/org/mjhost/anagrafica/repository/OrganizationRepository.java
|
UTF-8
| 307
| 1.671875
| 2
|
[] |
no_license
|
package org.mjhost.anagrafica.repository;
import org.mjhost.anagrafica.model.node.Organization;
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface OrganizationRepository extends GraphRepository<Organization> {}
| true
|
f5d5cab9bd641acd06338cf99f52df77b9a01e97
|
Java
|
AdrChacon/Dots---Proyecto-1
|
/dots/src/GUI/MainClass.java
|
UTF-8
| 800
| 3.34375
| 3
|
[] |
no_license
|
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel {
/*Busca las cordenadas en "x" y en "y" para saber donde pintar la figura*/
public void paint(Graphics g) {
int xpoints[] = {155, 205, 255, 255, 255, 255, 205, 155};
int ypoints[] = {155, 105, 55, 105, 155, 205, 155, 205};
int npoints = 8;
/*Define el color y llama a la funcion*/
g.setColor(Color.GREEN);
g.fillPolygon(xpoints, ypoints, npoints);
}
/* Crea la figura pintada*/
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}
| true
|
e1bba2687a8803c6099b4f5f56d83467e9ba0597
|
Java
|
rajneeshkumar146/java_workspace
|
/Assingments/src/Assingment_06_Recursion/Q05_Nth_Triangle.java
|
UTF-8
| 531
| 3.4375
| 3
|
[] |
no_license
|
package Assingment_06_Recursion;
import java.util.Scanner;
public class Q05_Nth_Triangle {
public static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("enter number of row's");
int n = scn.nextInt();
System.out.println(triangle(n, 0, 1));
}
public static int triangle(int n, int res, int i) {
if (i > n) {
return 0;
}
res = triangle(n, res, i + 1); // oha_tk_ke_i_traingle_ka_sum_i_ke_pass_hai_and_i+1_ke_liye_recursive_call.
return res + i;
}
}
| true
|
3e37d831da042d1f23806ad4c3981b415300729b
|
Java
|
EfanRu/Spring-Boot-JUnit
|
/src/main/java/com/example/spring_junit/dao/UserDao.java
|
UTF-8
| 836
| 2.078125
| 2
|
[] |
no_license
|
package com.example.spring_junit.dao;
import com.example.spring_junit.model.Role;
import com.example.spring_junit.model.User;
import java.util.Collection;
import java.util.List;
public interface UserDao {
List<User> getAllUsers();
boolean addUser(User user);
boolean addRole(Role rrole);
boolean deleteUser(String id);
boolean updateUser(String id, String firstName, String lastName, String phoneNumber, Collection<Role> roles, String login, String password);
boolean updateUser(String id, String firstName, String lastName, String phoneNumber, Collection<Role> roles, String login);
boolean updateUser(User user);
boolean checkAuth(String login, String password);
User getUserByLogin(String login);
User getUserById(String id);
Collection<Role> getRoleByName(Collection<String> roles);
}
| true
|
60197d16b64fea6d17a8302d17f3bbaf5bc0784a
|
Java
|
chamoddissanayake/SchoolManagementSystem
|
/src/main/java/com/itp/util/QueryUtil.java
|
UTF-8
| 2,762
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.itp.util;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.itp.exception.QueryLoadingException;
public class QueryUtil extends CommonUtil{
/** Initialize logger */
public static final Logger log = Logger.getLogger(QueryUtil.class.getName());
private static QueryUtil SINGLE_INSTANCE = null;
private NodeList nodeList;
private QueryUtil() throws QueryLoadingException {
try {
/*
* Read the Query.xml file and read each query node into node
* list. It refers tag name query
*/
nodeList = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(QueryUtil.class.getResourceAsStream("/Query.xml"))
.getElementsByTagName(CommonConstants.TAG_NAME);
} catch (SAXException | IOException |ParserConfigurationException e) {
log.log(Level.SEVERE, e.getMessage());
throw new QueryLoadingException("Error loading queries from files",e);
}
}
public static QueryUtil getInstance() throws QueryLoadingException {
if (SINGLE_INSTANCE == null) {
synchronized(QueryUtil.class) {
if (SINGLE_INSTANCE == null) {
SINGLE_INSTANCE = new QueryUtil();
}
}
}
return SINGLE_INSTANCE;
}
/**
* This method read the Query.xml file and retrieve the query by
* query id.
*
* @param id
* QueryID to retrieve elements
*
* @return String formatted query will be returned as output
*
* @throws ParserConfigurationException
* - Indicates a serious configuration error.
* @throws IOException
* - This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws SAXException
* - Encapsulate a general SAX error or warning.
* @throws QueryLoadingException
*
*
*/
public String queryByID(String id) throws SAXException, IOException, ParserConfigurationException, QueryLoadingException {
/*
* Extract the node from node list using query id query id is taken from
* query node attribute
*/
for (int value = 0; value < nodeList.getLength(); value++) {
Element element = (Element) nodeList.item(value);
if (element.getAttribute(CommonConstants.ATTRIB_ID).equals(id))
return element.getTextContent().trim();
}
throw new QueryLoadingException("Query not found for the Id:"+id);
}
}
| true
|
3ceeb699d002adb3dfb2eff76edd44e52e1dec87
|
Java
|
mP1/walkingkooka-tree
|
/src/test/java/walkingkooka/tree/expression/ExpressionEvaluationContextPrepareParametersListTestCase.java
|
UTF-8
| 5,907
| 2.09375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2020 Miroslav Pokorny (github.com/mP1)
*
* 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 walkingkooka.tree.expression;
import walkingkooka.collect.list.ListTesting;
import walkingkooka.collect.map.Maps;
import walkingkooka.collect.set.Sets;
import walkingkooka.reflect.ClassTesting;
import walkingkooka.reflect.JavaVisibility;
import walkingkooka.tree.expression.function.ExpressionFunctionParameter;
import walkingkooka.tree.expression.function.ExpressionFunctionParameterKind;
import walkingkooka.tree.expression.function.ExpressionFunctionParameterName;
import java.util.Map;
import java.util.Optional;
public abstract class ExpressionEvaluationContextPrepareParametersListTestCase<T extends ExpressionEvaluationContextPrepareParametersList> implements ClassTesting<T>,
ListTesting {
final static ExpressionFunctionParameter<Integer> REQUIRED = ExpressionFunctionParameterName.with("required-integer")
.required(Integer.class);
final static ExpressionFunctionParameter<Long> OPTIONAL = ExpressionFunctionParameterName.with("optional-long")
.optional(Long.class);
final static ExpressionFunctionParameter<Double> VARIABLE = ExpressionFunctionParameterName.with("variable-double")
.variable(Double.class);
final static ExpressionFunctionParameter<?> FLATTEN = ExpressionFunctionParameterName.with("flatten")
.variable(Object.class)
.setKinds(
Sets.of(
ExpressionFunctionParameterKind.FLATTEN)
);
final static ExpressionNumberKind EXPRESSION_NUMBER_KIND = ExpressionNumberKind.DOUBLE;
final static ExpressionNumber EXPRESSION_NUMBER = EXPRESSION_NUMBER_KIND.create(999);
final static Expression EXPRESSION = Expression.value(EXPRESSION_NUMBER);
final static ExpressionReference REFERENCE = new FakeExpressionReference() {
@Override
public String toString() {
return "*reference*";
}
};
ExpressionEvaluationContextPrepareParametersListTestCase() {
super();
}
final ExpressionEvaluationContext createContextWithReference(final ExpressionReference reference,
final Object value) {
return new FakeExpressionEvaluationContext() {
@Override
public Optional<Optional<Object>> reference(final ExpressionReference r) {
return Optional.ofNullable(
reference.equals(r) ?
Optional.ofNullable(value) :
null
);
}
@Override
public Object handleException(final RuntimeException exception) {
return "@@@" + exception.getMessage();
}
@Override
public String toString() {
return REFERENCE + "->" + value;
}
};
}
final ExpressionEvaluationContext createContextWhichConverts(final Object from,
final Object to) {
return this.createContextWhichConverts(
Maps.of(from, to)
);
}
final ExpressionEvaluationContext createContextWhichConverts(final Map<Object, Object> conversions) {
return new FakeExpressionEvaluationContext() {
@Override
public <TT> TT prepareParameter(final ExpressionFunctionParameter<TT> parameter,
final Object value) {
return this.convertOrFail(value, parameter.type());
}
@Override
public <TT> TT convertOrFail(final Object value,
final Class<TT> target) {
final Object converted = conversions.get(value);
if (null == converted) {
throw new UnsupportedOperationException("Unexpected convert from " + value + " to " + target.getName());
}
return target.cast(converted);
}
@Override
public String toString() {
return conversions.toString();
}
};
}
final ExpressionEvaluationContext createContextWhichConvertFails() {
return new FakeExpressionEvaluationContext() {
@Override
public <TT> TT prepareParameter(final ExpressionFunctionParameter<TT> parameter,
final Object value) {
return this.convertOrFail(value, parameter.type());
}
@Override
public <TT> TT convertOrFail(final Object value,
final Class<TT> target) {
throw new UnsupportedOperationException("Unable to convert " + value + " to " + target.getSimpleName());
}
@Override
public Object handleException(final RuntimeException exception) {
return "@@@" + exception.getMessage();
}
};
}
// ClassTesting....................................................................................................
@Override
public final JavaVisibility typeVisibility() {
return JavaVisibility.PACKAGE_PRIVATE;
}
}
| true
|
f0c9a57eae0f9ea17e60b0b4b1ae6183d3b0051a
|
Java
|
bobinush/2DV515
|
/A4/src/main/java/A4/App.java
|
UTF-8
| 497
| 2.21875
| 2
|
[] |
no_license
|
package A4;
import weka.core.Instances;
public class App
{
public static final String DATAFILE="spiral.arff";
public static void main( String[] args )
{
//System.out.println( "Hello World!" );
LogisticRegressionDemo test = new LogisticRegressionDemo();
Instances data;
try {
data = test.getDataSet(DATAFILE);
test.startLogistic(data);
test.startMP(data);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
edc7b485b79b2a23350474fa3258b1478bed10ad
|
Java
|
JakubCachovan/JAVA-letisko
|
/test/letisko/LetiskoTest.java
|
UTF-8
| 9,518
| 2.671875
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package letisko;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.sql.Date;
import java.time.Instant;
import java.util.GregorianCalendar;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Acer
*/
public class LetiskoTest {
public LetiskoTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of zriadLet method, of class Letisko.
*/
@Test
public void testZriadLet() {
System.out.println("zriadLet");
String destinacia = "destinacia";
Date datum = new Date(java.util.Date.from(Instant.MIN).getTime());
Kapitan kapitan = new Kapitan(0, "", "", "");
Lietadla lietadlo = Lietadla.Boeing737;
Letisko instance = new Letisko();
Let result = instance.zriadLet(destinacia, datum, kapitan, lietadlo);
Let expResult = instance.getZoznamLetov().get(0);
assertEquals(expResult, result);
}
/**
* Test of zrusLet method, of class Letisko.
*/
@Test
public void testZrusLet() {
System.out.println("zrusLet");
int id = 0;
Letisko instance = new Letisko();
boolean expResult = true;
Let let = instance.zriadLet("", null, null, null);
boolean result = instance.zrusLet(id);
assertEquals(expResult, result);
}
/**
* Test of najdiCestujuceho method, of class Letisko.
*/
@Test
public void testNajdiCestujuceho() {
System.out.println("najdiCestujuceho");
String rc = "123";
int idLetu = 0;
Letisko instance = new Letisko();
Let let = instance.zriadLet("destinacia", null, null, Lietadla.Boeing747);
let.setID(idLetu);
Cestujuci cestujuci = new Cestujuci("Meno", "", "123");
let.rezervujLetenku(null, cestujuci);
boolean expResult = true;
boolean result = instance.najdiCestujuceho(rc, idLetu);
assertEquals(expResult, result);
}
/**
* Test of najdiNajBlizsiLet method, of class Letisko.
*/
@Test
public void testNajdiNajBlizsiLet() {
System.out.println("najdiNajBlizsiLet");
/*Date datum = new Date();
Date datum1 = new GregorianCalendar(2020, Calendar.FEBRUARY, 11).getTime();
Date datum2 = new GregorianCalendar(2019, Calendar.FEBRUARY, 11).getTime();
Date datum3 = new GregorianCalendar(2018, Calendar.FEBRUARY, 11).getTime();
String destinacia = "destinacia";
Letisko instance = new Letisko();
Let let1 = instance.zriadLet(destinacia, datum1, null, Lietadla.Boeing747);
Let let2 = instance.zriadLet(destinacia, datum2, null, Lietadla.Boeing747);
Let let3 = instance.zriadLet(destinacia, datum3, null, Lietadla.Boeing747);
Let expResult = let3;
Let result = instance.najdiNajBlizsiLet(datum, destinacia);
assertEquals(expResult, result);*/
}
/**
* Test of getZoznamKapitanov method, of class Letisko.
*/
@Test
public void testGetZoznamKapitanov() {
System.out.println("getZoznamKapitanov");
Letisko instance = new Letisko();
ArrayList<Kapitan> expResult = new ArrayList<>();
ArrayList<Kapitan> result = instance.getZoznamKapitanov();
assertEquals(expResult, result);
}
/**
* Test of getZoznamLietadiel method, of class Letisko.
*/
@Test
public void testGetZoznamLietadiel() {
System.out.println("getZoznamLietadiel");
Letisko instance = new Letisko();
ArrayList<Lietadla> expResult = new ArrayList<>();
ArrayList<Lietadla> result = instance.getZoznamLietadiel();
assertEquals(expResult, result);
}
/**
* Test of getZoznamLetov method, of class Letisko.
*/
@Test
public void testGetZoznamLetov() {
System.out.println("getZoznamLetov");
Letisko instance = new Letisko();
ArrayList<Let> expResult = new ArrayList<>();
ArrayList<Let> result = instance.getZoznamLetov();
assertEquals(expResult, result);
}
/**
* Test of addKapitan method, of class Letisko.
*/
@Test
public void testAddKapitan() {
System.out.println("addKapitan");
Kapitan kapitan = new Kapitan(0, "Meno", "Priezvisko", "");
Letisko instance = new Letisko();
instance.addKapitan(kapitan);
ArrayList<Kapitan> zoznamKap = instance.getZoznamKapitanov();
Kapitan expResult = zoznamKap.get(0);
assertEquals(expResult, kapitan);
}
/**
* Test of load method, of class Letisko.
*/
@Test
public void testLoad() {
System.out.println("load");
File f = null;
Letisko instance = new Letisko();
boolean expResult = true;
//boolean result = instance.load(f);
//assertEquals(expResult, result);
}
/**
* Test of save method, of class Letisko.
*/
@Test
public void testSave() {
System.out.println("save");
File f = null;
Letisko instance = new Letisko();
boolean expResult = true;
boolean result = instance.save(f);
assertEquals(expResult, result);
}
/**
* Test of najdiCestujuceho method, of class Letisko.
*/
@Test
public void testNajdiCestujuceho_String_int() {
System.out.println("najdiCestujuceho");
String rc = "";
int idLetu = 0;
Letisko instance = new Letisko();
boolean expResult = false;
boolean result = instance.najdiCestujuceho(rc, idLetu);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of najdiCestujuceho method, of class Letisko.
*/
@Test
public void testNajdiCestujuceho_String_String() {
System.out.println("najdiCestujuceho");
String meno = "";
String priezvisko = "";
Letisko instance = new Letisko();
Cestujuci expResult = null;
Cestujuci result = instance.najdiCestujuceho(meno, priezvisko);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of najdiCestujuceho method, of class Letisko.
*/
@Test
public void testNajdiCestujuceho_String() {
System.out.println("najdiCestujuceho");
String rc = "";
Letisko instance = new Letisko();
Cestujuci expResult = null;
Cestujuci result = instance.najdiCestujuceho(rc);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setZoznamKapitanov method, of class Letisko.
*/
@Test
public void testSetZoznamKapitanov() {
System.out.println("setZoznamKapitanov");
ArrayList<Kapitan> zoznamKapitanov = null;
Letisko instance = new Letisko();
instance.setZoznamKapitanov(zoznamKapitanov);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setZoznamLietadiel method, of class Letisko.
*/
@Test
public void testSetZoznamLietadiel() {
System.out.println("setZoznamLietadiel");
ArrayList<Lietadla> zoznamLietadiel = null;
Letisko instance = new Letisko();
instance.setZoznamLietadiel(zoznamLietadiel);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setZoznamLetov method, of class Letisko.
*/
@Test
public void testSetZoznamLetov() {
System.out.println("setZoznamLetov");
ArrayList<Let> zoznamLetov = null;
Letisko instance = new Letisko();
instance.setZoznamLetov(zoznamLetov);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of toString method, of class Letisko.
*/
@Test
public void testToString() {
System.out.println("toString");
Letisko instance = new Letisko();
String expResult = "";
String result = instance.toString();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
| true
|
d7c28af5106ec3c2fa937ede0c3995e0ead32847
|
Java
|
thepawlo/ContactsApp
|
/src/main/java/com/model/Contact.java
|
UTF-8
| 2,550
| 2.3125
| 2
|
[] |
no_license
|
package com.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* Created by Pawel on 2017-05-12.
*/
@Entity
@NamedQuery(name = "Contact.findContactByEmail", query = "select c from Contact c where c.email = :email")
public class Contact implements Serializable {
public static final String FIND_BY_EMAIL = "Contact.findContactByEmail";
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String surname;
@Column(unique = true)
private String email;
@ManyToOne
@JoinColumn(name = "mainContactCategoryID")
private MainContactCategory mainContactCategory;
@ManyToOne
@JoinColumn(name = "businessContactCategoryID")
private BusinessContactCategory businessContactCategory;
private String otherContactCategory;
private String phoneNumber;
private Date birthdayDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public MainContactCategory getMainContactCategory() {
return mainContactCategory;
}
public void setMainContactCategory(MainContactCategory mainContactCategory) {
this.mainContactCategory = mainContactCategory;
}
public BusinessContactCategory getBusinessContactCategory() {
return businessContactCategory;
}
public void setBusinessContactCategory(BusinessContactCategory businessContactCategory) {
this.businessContactCategory = businessContactCategory;
}
public String getOtherContactCategory() {
return otherContactCategory;
}
public void setOtherContactCategory(String otherContactCategory) {
this.otherContactCategory = otherContactCategory;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Date getBirthdayDate() {
return birthdayDate;
}
public void setBirthdayDate(Date birthdayDate) {
this.birthdayDate = birthdayDate;
}
}
| true
|
b5a3afc6a164fe46362e9388585db45f779c3b90
|
Java
|
ollleg111/moveSHT
|
/app/src/main/java/movesht/com/movesht/storage/BaseStorageAbs.java
|
UTF-8
| 891
| 2.34375
| 2
|
[] |
no_license
|
package movesht.com.movesht.storage;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public abstract class BaseStorageAbs implements BaseStorageInterface {
protected static BaseStorageAbs baseStorageAbs;
protected SharedPreferences sharedPreferences;
protected final static String TOKEN = "movesht.com.movesht.storage.token";
protected final static String USERDATA = "register.user.data";
@Override
public String loadUserRegisterData() {
return sharedPreferences.getString(USERDATA, null);
}
@Override
public String loadToken() {
return sharedPreferences.getString(TOKEN, null);
}
public <T extends Object> void save(String key, T value) {
if (value instanceof String) {
sharedPreferences.edit().putString(key, value.toString()).commit();
}
}
}
| true
|
7f66a8a68c18fbe90ae27b61ac0f4f74b36de6a4
|
Java
|
bicerin/Itenjoy
|
/Itenjoy/src/com/itenjoy/action/BuyFormAction.java
|
UTF-8
| 2,620
| 2.3125
| 2
|
[] |
no_license
|
package com.itenjoy.action;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.itenjoy.svc.BuyFormService;
import com.itenjoy.svc.GetProductOneService;
import com.itenjoy.vo.ActionForward;
import com.itenjoy.vo.CustomerVO;
import com.itenjoy.vo.ProductVO;
public class BuyFormAction implements Action {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("BuyFormAction 안으로 들어왔음");
HttpSession session = request.getSession();
String id = (String)session.getAttribute("id");
String[] cart_idArr = request.getParameterValues("selected");
BuyFormService buyFormService = new BuyFormService();
ProductVO productVO = new ProductVO();
List<ProductVO> productVOList = new ArrayList<ProductVO>();
List<Byte> buy_countList = new ArrayList<Byte>();
// 상품 소개페이지에서 구매 버튼 클릭시
if(cart_idArr == null) {
int com_id = Integer.parseInt(request.getParameter("com_id"));
Byte buy_count = Byte.parseByte(request.getParameter("buy_count"));
productVO = buyFormService.getProductOne(com_id);
productVOList.add(productVO);
request.setAttribute("productVOList", productVOList);
buy_countList.add(buy_count);
request.setAttribute("buy_countList", buy_countList);
session.removeAttribute("cart_idArr");
}
// 장바구니 페이지에서 구매 버튼 클릭시
if(cart_idArr != null) {
GetProductOneService getProductOneService = new GetProductOneService();
for(int i=0; i<cart_idArr.length; i++) {
int com_Id = buyFormService.getCartCom_id(Integer.parseInt(cart_idArr[i]));
productVO = getProductOneService.getProductOne(com_Id);
productVOList.add(productVO);
request.setAttribute("productVOList", productVOList);
Byte buy_Count = buyFormService.getCartBuy_count(Integer.parseInt(cart_idArr[i]));
buy_countList.add(buy_Count);
request.setAttribute("buy_countList", buy_countList);
session.setAttribute("cart_idArr", cart_idArr); // 구매후 장바구니에서 구매한 상품들 삭제하기 위함
}
}
CustomerVO customerVO = new CustomerVO();
customerVO = buyFormService.getCustomerOne(id);
request.setAttribute("customerVO", customerVO);
ActionForward forward = new ActionForward();
forward.setPath("shopping/buyForm.jsp");
return forward;
}
}
| true
|
deab3e02c433d2d4cb65719c977d25646ee35a56
|
Java
|
994108345/sbc
|
/sbc-prod/sbc-prod-web/src/test/java/data/Parent.java
|
UTF-8
| 280
| 2.03125
| 2
|
[] |
no_license
|
package data;
/**
* @author wzl
* @date Created in 2019/4/9 17:17
*/
public class Parent {
private String parentId;
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
}
| true
|
671243d7c6758c2b1328b55b5a5d4d80df39f59b
|
Java
|
NoeliaAlbornoz/POOFlix
|
/PooFlix/src/app/Serie.java
|
UTF-8
| 1,148
| 3.15625
| 3
|
[] |
no_license
|
package app;
import java.util.ArrayList;
import java.util.List;
public class Serie extends Contenido {
public Serie(String nombre, int anio, double calificacion){
this.setNombre(nombre);
this.setAnio(anio);
this.setCalificacion(calificacion);
}
//Constructor que reutiliza el constructor de arriba (similar a como lo hace super)
public Serie(String nombre, int anio, double calificacion, Genero genero){
this(nombre, anio, calificacion); //Reutilizacion
this.setGenero(genero);
}
private List<Temporada> temporadas = new ArrayList<>();
public List<Temporada> getTemporadas(){
return this.temporadas;
}
public void setTemporadas(List<Temporada> temporadas){
this.temporadas = temporadas;
}
public Temporada getTemporada(int numero) {
// Recorrer cada temporada
// Si el nro de temporada del ciclo es igual a nro
// Devolver temporada
for (Temporada tempo : this.temporadas) {
if (tempo.getNumero() == numero) {
return tempo;
}
}
return null;
}
}
| true
|
9e24dbeeb21ca5cc63038980f2c57cc98f0d664d
|
Java
|
jeffzhengye/lablucene
|
/src/application/org/apache/lucene/postProcess/termselector/SocialTermSelector.java
|
UTF-8
| 29,026
| 1.695313
| 2
|
[] |
no_license
|
/**
*
*/
package org.apache.lucene.postProcess.termselector;
import gnu.trove.TIntObjectHashMap;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.lucene.document.SetBasedFieldSelector;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermFreqVector;
import org.apache.lucene.index.TermPositionVector;
import org.apache.lucene.postProcess.QueryExpansionModel;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RBooleanClause;
import org.apache.lucene.search.RBooleanQuery;
import org.apache.lucene.search.RQuery;
import org.apache.lucene.search.RTermQuery;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocCollector;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.RBooleanClause.Occur;
import org.apache.lucene.search.model.Idf;
import org.dutir.lucene.ISManager;
import org.dutir.lucene.IndexUtility;
import org.dutir.lucene.util.ApplicationSetup;
import org.dutir.lucene.util.ExpansionTerms;
import org.dutir.lucene.util.ExpansionTerms.ExpansionTerm;
import org.dutir.util.AbstractExternalizable;
import org.dutir.util.FastCache;
import org.dutir.util.Strings;
/**
* @author zheng
*
*/
public class SocialTermSelector extends TermSelector {
private static Logger logger = Logger.getLogger(SocialTermSelector.class);
static Searcher socialSearch = ISManager
.getSearcheFromPath(ApplicationSetup.getProperty(
"SocialTermSelector.social.indexpath", ""));
static IndexReader socialReader = socialSearch.getIndexReader();
static IndexUtility indexUtil = new IndexUtility(socialSearch);
static Idf socialIDF = new Idf(indexUtil.maxDoc());
static String socialField = ApplicationSetup.getProperty(
"SocialTermSelector.searchFiled", "tagtitle");
static int expDoc = Integer.parseInt(ApplicationSetup.getProperty(
"SocialTermSelector.documents", "100"));
static int strategy = Integer.parseInt(ApplicationSetup.getProperty(
"SocialTermSelector.strategy", "10"));
static float lambda = Float.parseFloat(ApplicationSetup.getProperty(
"SocialTermSelector.lambda", "0.5"));
static boolean combiningTag = Boolean.parseBoolean(ApplicationSetup
.getProperty("SocialTermSelector.combiningTag", "false"));
static FastCache<String, Float> conditinProbCache = null;
static String socialCondPath = ApplicationSetup.LUCENE_ETC + "/"
+ socialField + "_socialCondPro.cache";
String addInfo = "";
static {
File file = new File(socialCondPath);
if(logger.isInfoEnabled()) logger.info("socialCondCachePath: " + socialCondPath);
if (file.exists()) {
try {
conditinProbCache = (FastCache<String, Float>) AbstractExternalizable
.readObject(file);
} catch (Exception e) {
e.printStackTrace();
}
} else
conditinProbCache = new FastCache<String, Float>(1024 * 1024);
}
public RQuery getSocailQuery() {
String terms[] = this.originalQueryTermidSet.toArray(new String[0]);
RBooleanQuery bquery = new RBooleanQuery();
for (int i = 0; i < terms.length; i++) {
bquery.add(new RTermQuery(new Term(socialField, terms[i])),
RBooleanClause.Occur.SHOULD);
}
return bquery;
}
public Query getMustSocailQuery(String _terms[]) {
return getSocailQuery(_terms, BooleanClause.Occur.MUST);
}
public Query getSocailQuery(String _terms[], BooleanClause.Occur occur) {
String terms[] = _terms;
BooleanQuery bquery = new BooleanQuery();
for (int i = 0; i < terms.length; i++) {
bquery.add(new TermQuery(new Term(socialField, terms[i])), occur);
}
return bquery;
}
static String sQEModel = ApplicationSetup.getProperty(
"Lucene.QueryExpansion.Model", "KL");
private QueryExpansionModel socialQEModel;
public QueryExpansionModel getSocialExpansionModel() {
if (socialQEModel == null) {
try {
if (sQEModel.indexOf(".") == -1) {
sQEModel = "org.apache.lucene.postProcess." + sQEModel;
}
socialQEModel = (QueryExpansionModel) Class.forName(sQEModel)
.newInstance();
socialQEModel.setCollectionLength(socialSearch
.getNumTokens(socialField));
socialQEModel.setAverageDocumentLength(socialSearch
.getAverageLength(socialField));
socialQEModel.setNumberOfDocuments(socialSearch.maxDoc());
} catch (Exception e) {
e.printStackTrace();
}
}
return socialQEModel;
}
static String dmu = ApplicationSetup.getProperty("slm.mu", "500");
static float mu = Integer.parseInt(ApplicationSetup.getProperty("rm.mu",
dmu));
// float numOfTokens = this.searcher.getNumTokens(field);
public float score(float tf, float docLength, float termFrequency,
float numberOfTokens) {
float pc = termFrequency / numberOfTokens;
return (tf + mu * pc) / (docLength + mu);
}
/*
* (non-Javadoc)
*
* @see
* org.apache.lucene.postProcess.termselector.TermSelector#assignTermWeights
* (int[], float[], org.apache.lucene.postProcess.QueryExpansionModel)
*/
@Override
public void assignTermWeights(int[] docids, float[] scores,
QueryExpansionModel QEModel) {
try {
TopDocCollector topdc = new TopDocCollector(1000);
String originalModel = ApplicationSetup.getProperty(
"Lucene.Search.WeightingModel", "BM25");
ApplicationSetup
.setProperty("Lucene.Search.WeightingModel", "BM25");
socialSearch.search(getSocailQuery(), topdc);
ApplicationSetup.setProperty("Lucene.Search.WeightingModel",
originalModel);
TopDocs tdocs = topdc.topDocs();
int minDoc = Math.min(expDoc, tdocs.totalHits);
int socialdocIDs[] = new int[minDoc];
float socialScores[] = new float[minDoc];
for (int i = 0; i < minDoc; i++) {
socialdocIDs[i] = tdocs.scoreDocs[i].doc;
socialScores[i] = tdocs.scoreDocs[i].score;
}
ApplicationSetup.setProperty("Lucene.Search.WeightingModel",
originalModel);
// ///////////////////////////////////////////////////////////////
if (strategy == 1) { // \sig p(t|e)*p(e|F)
QueryExpansionModel socialQEModel = getSocialExpansionModel();
TermSelector selector = TermSelector.getTermSelector(
"DFRTermSelector", socialSearch);
selector.setResultSet(topdc);
selector.setOriginalQueryTerms(this.originalQueryTermidSet);
selector.setField(socialField);
selector.assignTermWeights(socialdocIDs, socialScores,
socialQEModel);
ExpansionTerm[] expTerms = selector
.getMostWeightedTerms(selector.getNumberOfUniqueTerms());
this.termMap = new HashMap<String, ExpansionTerm>(100);
// for(int i=0; i < expTerms.length; i++){
// String term = expTerms[i].getTerm();
// // if(this.searcher.getIndexReader().docFreq(new
// Term(this.field,
// term)) > 0){
// this.termMap.put(term, expTerms[i]);
// // }
// }
// generative model
int queryLen = this.originalQueryTermidSet.size();
float pF[] = new float[queryLen];
int pos = 0;
String sq[] = new String[queryLen];
for (String q : this.originalQueryTermidSet) {
sq[pos] = q;
pF[pos++] = indexUtil.getDF(new Term(socialField, q))
/ indexUtil.maxDoc();
}
for (int i = 0; i < expTerms.length; i++) {
String term = expTerms[i].getTerm();
float weight = 0;
for (int j = 0; j < queryLen; j++) {
weight += pF[j] * conditionProb(term, sq[j]);
}
expTerms[i].setWeightExpansion(weight
* expTerms[i].getWeightExpansion());
this.termMap.put(term, expTerms[i]);
// }
}
} else if (strategy == 2) { // co-occurrence
QueryExpansionModel socialQEModel = getSocialExpansionModel();
TermSelector selector = TermSelector.getTermSelector(
"DFRTermSelector", socialSearch);
selector.setResultSet(topdc);
selector.setOriginalQueryTerms(this.originalQueryTermidSet);
selector.setField(socialField);
selector.assignTermWeights(socialdocIDs, socialScores,
socialQEModel);
ExpansionTerm[] expTerms = selector
.getMostWeightedTerms(selector.getNumberOfUniqueTerms());
Arrays.sort(expTerms, ExpansionTerms.AlphaBetaComparator);
this.termMap = new HashMap<String, ExpansionTerm>(100);
// co-occurrence model
int queryLen = this.originalQueryTermidSet.size();
float pF[] = new float[queryLen];
int pos = 0;
String sq[] = new String[queryLen];
float qidf[] = new float[queryLen];
for (String q : this.originalQueryTermidSet) {
sq[pos] = q;
float df = indexUtil.getDF(new Term(socialField, q));
int N = indexUtil.maxDoc();
qidf[pos] = socialIDF.idfNENQUIRY(df);
pF[pos++] = df / (float) N;
}
// Set set = new HashSet();
// set.add(socialField);
// SetBasedFieldSelector fieldsel = new
// SetBasedFieldSelector(set,
// set);
// TermFreqVector tfvcache[] = new TermFreqVector[minDoc];
for (int i = 0; i < expTerms.length; i++) {
String term = expTerms[i].getTerm();
float weight = 0;
for (int j = 0; j < queryLen; j++) {
String keys[] = { term, sq[j] };
String key = tocachekey(keys);
weight += (conditinProbCache.get(key) != null ? conditinProbCache
.get(key)
: 0) + 0.0001;
}
// trigram
for (int j = 0; j < queryLen - 1; j++) {
for (int j1 = j + 1; j1 < queryLen; j1++) {
String keys[] = { term, sq[j], sq[j1] };
String key = tocachekey(keys);
weight += (conditinProbCache.get(key) != null ? conditinProbCache
.get(key)
: 0) + 0.0001;
}
}
expTerms[i].setWeightExpansion(weight);
this.termMap.put(term, expTerms[i]);
// }
}
} else if (strategy == 3) { // sig p(t|e)*p(e|d)*p(d|F)
QueryExpansionModel socialQEModel = getSocialExpansionModel();
TermSelector selector = TermSelector.getTermSelector(
"DFRTermSelector", socialSearch);
selector.setResultSet(topdc);
selector.setOriginalQueryTerms(this.originalQueryTermidSet);
selector.setField(socialField);
selector.assignTermWeights(socialdocIDs, scores, socialQEModel);
ExpansionTerm[] expTerms = selector
.getMostWeightedTerms(selector.getNumberOfUniqueTerms());
Arrays.sort(expTerms, ExpansionTerms.AlphaBetaComparator);
this.termMap = new HashMap<String, ExpansionTerm>(100);
// co-occurrence model
int queryLen = this.originalQueryTermidSet.size();
float pF[] = new float[queryLen];
int pos = 0;
String sq[] = new String[queryLen];
float qidf[] = new float[queryLen];
for (String q : this.originalQueryTermidSet) {
sq[pos] = q;
float df = indexUtil.getDF(new Term(socialField, q));
int N = indexUtil.maxDoc();
qidf[pos] = socialIDF.idfNENQUIRY(df);
pF[pos++] = df / (float) N;
}
Set set = new HashSet();
set.add(socialField);
SetBasedFieldSelector fieldsel = new SetBasedFieldSelector(set,
set);
TermFreqVector tfvcache[] = new TermFreqVector[minDoc];
for (int i = 0; i < expTerms.length; i++) {
String term = expTerms[i].getTerm();
float termFrequency = socialSearch.termFreq(toTerm(term));
float numberOfTokens = socialSearch
.getNumTokens(socialField);
float weight = 0;
for (int k = 0; k < minDoc; k++) {
float dl = 0;
float tf = 0;
TermFreqVector tfv = null;
if (tfvcache[k] == null) {
tfvcache[k] = socialReader.getTermFreqVector(
socialdocIDs[k], socialField);
}
tfv = tfvcache[k];
String strterms[] = tfv.getTerms();
int freqs[] = tfv.getTermFrequencies();
dl = org.dutir.util.Arrays.sum(freqs);
int curPos = Arrays.binarySearch(strterms, 0,
strterms.length, term);
float docWeight = 0;
float selfWeight = 0;
if (curPos >= 0) {
tf = freqs[curPos];
selfWeight += socialIdf(term)
* Idf.log(1 + freqs[curPos])
* Idf.log(1 + freqs[curPos]);
for (int j = 0; j < queryLen; j++) {
int qid = Arrays.binarySearch(strterms, 0,
strterms.length, sq[j]);
if (qid >= 0)
docWeight += qidf[j]
* Idf.log(1 + freqs[qid])
* Idf.log(1 + freqs[curPos]);
}
// trigram
selfWeight += socialIdf(term)
* Idf.log(1 + freqs[curPos])
* socialIdf(term)
* Idf.log(1 + freqs[curPos])
* Idf.log(1 + freqs[curPos]);
for (int j = 0; j < queryLen - 1; j++) {
for (int j1 = j + 1; j1 < queryLen; j1++) {
int qid = Arrays.binarySearch(strterms, 0,
strterms.length, sq[j]);
if (qid >= 0) {
int qid1 = Arrays.binarySearch(
strterms, 0, strterms.length,
sq[j1]);
if (qid1 >= 0)
docWeight += qidf[j]
* Idf.log(1 + freqs[qid])
* Idf
.log(1 + freqs[curPos])
* qidf[j1]
* Idf.log(1 + freqs[qid1]);
}
}
}
}
weight += (docWeight + selfWeight) * socialScores[k]
* score(tf, dl, termFrequency, numberOfTokens);
// *socialScores[k];
// * score(tf, dl, termFrequency, numberOfTokens);
// (docWeight + 0)*
}
expTerms[i].setWeightExpansion(weight * socialIdf(term));
this.termMap.put(term, expTerms[i]);
}
} else if (strategy == 4) { // sig p(t|e)*p(e|d)*p(d|F)
QueryExpansionModel socialQEModel = getSocialExpansionModel();
TermSelector selector = TermSelector.getTermSelector(
"DFRTermSelector", socialSearch);
selector.setResultSet(topdc);
selector.setOriginalQueryTerms(this.originalQueryTermidSet);
selector.setField(socialField);
selector.assignTermWeights(socialdocIDs, scores, socialQEModel);
ExpansionTerm[] expTerms = selector
.getMostWeightedTerms(selector.getNumberOfUniqueTerms());
Arrays.sort(expTerms, ExpansionTerms.AlphaBetaComparator);
this.termMap = new HashMap<String, ExpansionTerm>(100);
// co-occurrence model
int queryLen = this.originalQueryTermidSet.size();
float pF[] = new float[queryLen];
int pos = 0;
String sq[] = new String[queryLen];
float qidf[] = new float[queryLen];
for (String q : this.originalQueryTermidSet) {
sq[pos] = q;
float df = indexUtil.getDF(new Term(socialField, q));
int N = indexUtil.maxDoc();
qidf[pos] = socialIDF.idfNENQUIRY(df);
pF[pos++] = df / (float) N;
}
Set set = new HashSet();
set.add(socialField);
SetBasedFieldSelector fieldsel = new SetBasedFieldSelector(set,
set);
TermFreqVector tfvcache[] = new TermFreqVector[minDoc];
for (int i = 0; i < expTerms.length; i++) {
String term = expTerms[i].getTerm();
float termFrequency = socialSearch.termFreq(toTerm(term));
float numberOfTokens = socialSearch
.getNumTokens(socialField);
float weight = 0;
for (int k = 0; k < minDoc; k++) {
float dl = 0;
float tf = 0;
TermFreqVector tfv = null;
if (tfvcache[k] == null) {
tfvcache[k] = socialReader.getTermFreqVector(
socialdocIDs[k], socialField);
}
tfv = tfvcache[k];
String strterms[] = tfv.getTerms();
int freqs[] = tfv.getTermFrequencies();
dl = org.dutir.util.Arrays.sum(freqs);
int curPos = Arrays.binarySearch(strterms, 0,
strterms.length, term);
float docWeight = 0;
float selfWeight = 0;
if (curPos >= 0) {
tf = freqs[curPos];
selfWeight += socialIdf(term)
* Idf.log(1 + freqs[curPos])
* Idf.log(1 + freqs[curPos]);
for (int j = 0; j < queryLen; j++) {
int qid = Arrays.binarySearch(strterms, 0,
strterms.length, sq[j]);
if (qid >= 0)
docWeight += qidf[j]
* Idf.log(1 + freqs[qid])
* Idf.log(1 + freqs[curPos]);
}
// trigram
selfWeight += socialIdf(term)
* Idf.log(1 + freqs[curPos])
* socialIdf(term)
* Idf.log(1 + freqs[curPos])
* Idf.log(1 + freqs[curPos]);
for (int j = 0; j < queryLen - 1; j++) {
for (int j1 = j + 1; j1 < queryLen; j1++) {
int qid = Arrays.binarySearch(strterms, 0,
strterms.length, sq[j]);
if (qid >= 0) {
int qid1 = Arrays.binarySearch(
strterms, 0, strterms.length,
sq[j1]);
if (qid1 >= 0)
docWeight += qidf[j]
* Idf.log(1 + freqs[qid])
* Idf
.log(1 + freqs[curPos])
* qidf[j1]
* Idf.log(1 + freqs[qid1]);
}
}
}
}
weight += (docWeight + selfWeight) * socialScores[k]
* score(tf, dl, termFrequency, numberOfTokens);
// *socialScores[k];
// * score(tf, dl, termFrequency, numberOfTokens);
// (docWeight + 0)*
}
for (int k = 0; k < docids.length; k++) {
float dl = 0;
float tf = 0;
TermFreqVector tfv = null;
if (tfvcache[k] == null) {
tfvcache[k] = this.searcher.getIndexReader()
.getTermFreqVector(docids[k], this.field);
}
tfv = tfvcache[k];
String strterms[] = tfv.getTerms();
int freqs[] = tfv.getTermFrequencies();
dl = org.dutir.util.Arrays.sum(freqs);
int curPos = Arrays.binarySearch(strterms, 0,
strterms.length, term);
float docWeight = 0;
float selfWeight = 0;
if (curPos >= 0) {
tf = freqs[curPos];
selfWeight += socialIdf(term)
* Idf.log(1 + freqs[curPos])
* Idf.log(1 + freqs[curPos]);
for (int j = 0; j < queryLen; j++) {
int qid = Arrays.binarySearch(strterms, 0,
strterms.length, sq[j]);
if (qid >= 0)
docWeight += qidf[j]
* Idf.log(1 + freqs[qid])
* Idf.log(1 + freqs[curPos]);
}
// trigram
selfWeight += socialIdf(term)
* Idf.log(1 + freqs[curPos])
* socialIdf(term)
* Idf.log(1 + freqs[curPos])
* Idf.log(1 + freqs[curPos]);
for (int j = 0; j < queryLen - 1; j++) {
for (int j1 = j + 1; j1 < queryLen; j1++) {
int qid = Arrays.binarySearch(strterms, 0,
strterms.length, sq[j]);
if (qid >= 0) {
int qid1 = Arrays.binarySearch(
strterms, 0, strterms.length,
sq[j1]);
if (qid1 >= 0)
docWeight += qidf[j]
* Idf.log(1 + freqs[qid])
* Idf
.log(1 + freqs[curPos])
* qidf[j1]
* Idf.log(1 + freqs[qid1]);
}
}
}
}
weight += (docWeight + selfWeight) * socialScores[k]
* score(tf, dl, termFrequency, numberOfTokens);
}
expTerms[i].setWeightExpansion(weight * socialIdf(term));
this.termMap.put(term, expTerms[i]);
}
} else if (strategy == 5) { // RM or KL using socialTags
QueryExpansionModel socialQEModel = getSocialExpansionModel();
TermSelector selector = TermSelector.getTermSelector(
"RMTermSelector", socialSearch);
selector.setResultSet(topdc);
selector.setOriginalQueryTerms(this.originalQueryTermidSet);
selector.setField(socialField);
selector.assignTermWeights(socialdocIDs, socialScores,
socialQEModel);
ExpansionTerm[] expTerms = selector
.getMostWeightedTerms(selector.getNumberOfUniqueTerms());
this.termMap = new HashMap<String, ExpansionTerm>(100);
for (int i = 0; i < expTerms.length; i++) {
String term = expTerms[i].getTerm();
this.termMap.put(term, expTerms[i]);
}
} else if (strategy == 10) { // // generate cache file
QueryExpansionModel socialQEModel = getSocialExpansionModel();
TermSelector selector = TermSelector.getTermSelector(
"DFRTermSelector", socialSearch);
selector.setResultSet(topdc);
selector.setOriginalQueryTerms(this.originalQueryTermidSet);
selector.setField(socialField);
selector.assignTermWeights(socialdocIDs, scores, socialQEModel);
ExpansionTerm[] expTerms = selector
.getMostWeightedTerms(selector.getNumberOfUniqueTerms());
Arrays.sort(expTerms, ExpansionTerms.AlphaBetaComparator);
this.termMap = new HashMap<String, ExpansionTerm>(100);
// co-occurrence model
int queryLen = this.originalQueryTermidSet.size();
float pF[] = new float[queryLen];
int pos = 0;
String sq[] = new String[queryLen];
float qidf[] = new float[queryLen];
for (String q : this.originalQueryTermidSet) {
sq[pos] = q;
float df = indexUtil.getDF(new Term(socialField, q));
int N = indexUtil.maxDoc();
qidf[pos] = socialIDF.idfNENQUIRY(df);
pF[pos++] = df / (float) N;
}
TIntObjectHashMap<TermFreqVector> idVectorMap = new TIntObjectHashMap<TermFreqVector>(
20000);
// bigram
for (int i = 0; i < expTerms.length; i++) {
String term = expTerms[i].getTerm();
for (int j = 0; j < queryLen; j++) {
float weight = 0;
int maxCompute = 20000;
TopDocCollector temptopdc = new TopDocCollector(
maxCompute);
originalModel = ApplicationSetup.getProperty(
"Lucene.Search.WeightingModel", "BM25");
ApplicationSetup.setProperty(
"Lucene.Search.WeightingModel", "BM25");
String ssquery[] = { term, sq[j] };
socialSearch.search(getMustSocailQuery(ssquery),
temptopdc);
ApplicationSetup.setProperty(
"Lucene.Search.WeightingModel", originalModel);
minDoc = Math.min(maxCompute, temptopdc.getTotalHits());
logger.debug("bi_minDoc:" + minDoc);
for (int k = 0; k < minDoc; k++) {
int docid = temptopdc.topDocs().scoreDocs[k].doc;
TermFreqVector tfv = null;
if (idVectorMap.contains(docid)) {
tfv = idVectorMap.get(docid);
} else {
tfv = socialReader.getTermFreqVector(docid,
socialField);
}
String strterms[] = tfv.getTerms();
int freqs[] = tfv.getTermFrequencies();
int curPos = Arrays.binarySearch(strterms, 0,
strterms.length, term);
if (curPos >= 0) {
int qid = Arrays.binarySearch(strterms, 0,
strterms.length, sq[j]);
if (qid >= 0)
weight += qidf[j] * Idf.log(1 + freqs[qid])
* Idf.log(1 + freqs[curPos]);
}
}
// co-occurrence
weight = weight * socialIdf(term);
String keys[] = { term, sq[j] };
String key = tocachekey(keys);
conditinProbCache.put(key, weight);
if (weight <= 0) {
logger.error("weigh=" + weight + " < 0 for: " + key
+ ":" + socialIdf(term) + "," + qidf[j]);
}
}
// trigram
for (int j = 0; j < queryLen - 1; j++) {
for (int j1 = j + 1; j1 < queryLen; j1++) {
float weight = 0;
int maxCompute = 20000;
TopDocCollector temptopdc = new TopDocCollector(
maxCompute);
originalModel = ApplicationSetup.getProperty(
"Lucene.Search.WeightingModel", "BM25");
ApplicationSetup.setProperty(
"Lucene.Search.WeightingModel", "BM25");
String ssquery[] = { term, sq[j], sq[j1] };
socialSearch.search(getMustSocailQuery(ssquery),
temptopdc);
ApplicationSetup.setProperty(
"Lucene.Search.WeightingModel",
originalModel);
minDoc = Math.min(maxCompute, temptopdc
.getTotalHits());
logger.debug("tri_minDoc:" + minDoc);
for (int k = 0; k < minDoc; k++) {
int docid = temptopdc.topDocs().scoreDocs[k].doc;
TermFreqVector tfv = null;
if (idVectorMap.contains(docid)) {
tfv = idVectorMap.get(docid);
} else {
tfv = socialReader.getTermFreqVector(docid,
socialField);
}
String strterms[] = tfv.getTerms();
int freqs[] = tfv.getTermFrequencies();
int curPos = Arrays.binarySearch(strterms, 0,
strterms.length, term);
if (curPos >= 0) {
int qid = Arrays.binarySearch(strterms, 0,
strterms.length, sq[j]);
if (qid >= 0) {
int qid1 = Arrays.binarySearch(
strterms, 0, strterms.length,
sq[j1]);
if (qid1 >= 0)
weight += qidf[j]
* Idf.log(1 + freqs[qid])
* Idf
.log(1 + freqs[curPos])
* qidf[j1]
* Idf.log(1 + freqs[qid1]);
}
}
}
// co-occurrence
weight = weight * socialIdf(term)
* socialIDF.idfENQUIRY(10 + minDoc);
String keys[] = { term, sq[j], sq[j1] };
String key = tocachekey(keys);
conditinProbCache.put(key, weight);
if (weight <= 0) {
logger.error("weigh =" + weight + "< 0 for: "
+ key + ":" + socialIdf(term) + ","
+ qidf[j] + ", " + qidf[j1]);
}
}
}
// }
}
AbstractExternalizable.serializeTo(conditinProbCache, new File(
socialCondPath));
}
// ////////////////////////////////////////////////////////////////
if (combiningTag) {
TermSelector selector = TermSelector.getTermSelector(
"RocchioTermSelector", searcher);
// selector.setResultSet(this.topDoc);
selector.setOriginalQueryTerms(this.originalQueryTermidSet);
selector.setField(this.field);
selector.setResultSet(topdc);
selector.assignTermWeights(docids, scores, QEModel);
ExpansionTerm[] expTerms = selector
.getMostWeightedTerms(selector.getNumberOfUniqueTerms());
addInfo += selector.getInfo();
norm(expTerms);
ExpansionTerm currentExpTerms[] = this
.getMostWeightedTerms(selector.getNumberOfUniqueTerms());
norm(currentExpTerms);
this.termMap = new HashMap<String, ExpansionTerm>(1024);
for (ExpansionTerm eterm : expTerms) {
String term = eterm.getTerm();
eterm.setWeightExpansion(eterm.getWeightExpansion()
* lambda);
this.termMap.put(term, eterm);
}
for (ExpansionTerm eterm : currentExpTerms) {
String term = eterm.getTerm();
ExpansionTerm tmp_eterm = this.termMap.get(term);
if (tmp_eterm == null) {
tmp_eterm = new ExpansionTerm(term, 2);
tmp_eterm.setWeightExpansion(eterm.getWeightExpansion()
* (1 - lambda));
// tmp_eterm.setWeightExpansion(eterm.getWeightExpansion()
// );
this.termMap.put(term, tmp_eterm);
} else {
// tmp_eterm.setWeightExpansion(tmp_eterm
// .getWeightExpansion()
// + eterm.getWeightExpansion());
tmp_eterm.setWeightExpansion(tmp_eterm
.getWeightExpansion()
+ eterm.getWeightExpansion() * (1 - lambda));
this.termMap.put(term, tmp_eterm);
}
}
}
ExpansionTerm currentExpTerms[] = this
.getMostWeightedTerms(ApplicationSetup.EXPANSION_TERMS);
norm(currentExpTerms);
} catch (IOException e) {
e.printStackTrace();
}
}
public void norm(ExpansionTerm allTerms[]) {
if (allTerms == null || allTerms.length < 1)
return;
Arrays.sort(allTerms);
float normaliser = allTerms[0].getWeightExpansion();
for (ExpansionTerm term : allTerms) {
if (normaliser != 0) {
if(normaliser< term.getWeightExpansion()){
logger.error("program logic error, exit");
System.exit(1);
}
term.setWeightExpansion(term.getWeightExpansion() / normaliser);
}
}
}
public static String tocachekey(String keys[]) {
Arrays.sort(keys);
String key = Strings.concatenate(keys);
return key;
}
public float socialIdf(String term) {
float df = indexUtil.getDF(new Term(socialField, term));
int N = indexUtil.maxDoc();
return socialIDF.idfNENQUIRY(df);
}
public float conditionProb(String term1, String term2) {
return (float) ((indexUtil.getPhraseDF(toTerm(term1), toTerm(term2),
100) + 0.5) / (indexUtil.getDF(toTerm(term2)) + 0.5));
}
public Term toTerm(String sterm) {
return new Term(socialField, sterm);
}
/*
* (non-Javadoc)
*
* @see
* org.apache.lucene.postProcess.termselector.TermSelector#assignTermWeights
* (java.lang.String[][], int[][],
* org.apache.lucene.index.TermPositionVector[],
* org.apache.lucene.postProcess.QueryExpansionModel)
*/
@Override
public void assignTermWeights(String[][] terms, int[][] freqs,
TermPositionVector[] tfvs, QueryExpansionModel QEModel) {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see org.apache.lucene.postProcess.termselector.TermSelector#getInfo()
*/
@Override
public String getInfo() {
return "S_" + socialField + "_sDoc" + expDoc + "_stra" + strategy
+ (combiningTag == true ? ("Comb" + lambda) : "") +addInfo;
}
/**
* @param args
*/
public static void main(String[] args) {
boolean combiningTag = true;
System.out.println((combiningTag == true ? ("Comb" + lambda) : ""));
}
}
| true
|
8483c0ce417c27aa736ec4efc223fa500b13d89e
|
Java
|
danielversiane13/full-coffee-cups-bb
|
/src/main/java/br/com/gamabank/bluebank/services/BalanceMovementService.java
|
UTF-8
| 4,859
| 2.5625
| 3
|
[] |
no_license
|
package br.com.gamabank.bluebank.services;
import java.time.LocalDateTime;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamabank.bluebank.dto.BalanceMovementDto;
import br.com.gamabank.bluebank.entities.BalanceMovement;
import br.com.gamabank.bluebank.entities.BankAccount;
import br.com.gamabank.bluebank.entities.OperationTypeEnum;
import br.com.gamabank.bluebank.exceptions.ExceptionHandler;
import br.com.gamabank.bluebank.exceptions.NotAcceptableException;
import br.com.gamabank.bluebank.exceptions.NotFoundException;
import br.com.gamabank.bluebank.factories.BalanceMovementFactory;
import br.com.gamabank.bluebank.forms.BalanceMovementForm;
import br.com.gamabank.bluebank.repositories.BalanceMovementRepository;
import br.com.gamabank.bluebank.repositories.BankAccountRepository;
@Service
public class BalanceMovementService {
@Autowired
private BalanceMovementRepository repository;
@Autowired
private BankAccountRepository bankAccountRepository;
public BalanceMovementDto findById(UUID id) throws ExceptionHandler {
BalanceMovement balanceMovement = repository.findById(id)
.orElseThrow(() -> new NotFoundException("Balance Movement not found"));
return BalanceMovementFactory.Create(balanceMovement);
}
public BalanceMovementDto create(BalanceMovementForm form) throws ExceptionHandler {
boolean hasToAccount = form.toBankAccountId != null;
boolean hasFromAccount = form.fromBankAccountId != null;
if (!hasToAccount && !hasFromAccount) {
throw new NotAcceptableException("Invalid operation");
}
BalanceMovement balanceMovement = BalanceMovementFactory.Create(form);
if (!hasFromAccount) {
this.operationDeposit(balanceMovement, form);
} else if (!hasToAccount) {
this.operationWithdraw(balanceMovement, form);
} else {
this.operationTransfer(balanceMovement, form);
}
repository.save(balanceMovement);
return BalanceMovementFactory.Create(balanceMovement);
}
private void operationDeposit(BalanceMovement balanceMovement, BalanceMovementForm form) throws ExceptionHandler {
BankAccount toBankAccount = bankAccountRepository.findById(form.toBankAccountId)
.orElseThrow(() -> new NotFoundException("To BankAccount not found"));
if (toBankAccount.isActive() == false) {
throw new NotAcceptableException("To BankAccount is inactive");
}
balanceMovement.setOperationType(OperationTypeEnum.DEPOSIT);
balanceMovement.setToBankAccount(toBankAccount);
toBankAccount.balanceDeposit(form.value);
toBankAccount.setUpdatedAt(LocalDateTime.now());
bankAccountRepository.save(toBankAccount);
}
private void operationWithdraw(BalanceMovement balanceMovement, BalanceMovementForm form) throws ExceptionHandler {
BankAccount fromBankAccount = bankAccountRepository.findById(form.fromBankAccountId)
.orElseThrow(() -> new NotFoundException("From BankAccount not found"));
if (fromBankAccount.isActive() == false) {
throw new NotAcceptableException("From BankAccount is inactive");
}
balanceMovement.setOperationType(OperationTypeEnum.WITHDRAW);
balanceMovement.setFromBankAccount(fromBankAccount);
if (fromBankAccount.getBalance() < form.value) {
throw new NotAcceptableException("Insufficient balance");
}
fromBankAccount.balanceWithdraw(form.value);
fromBankAccount.setUpdatedAt(LocalDateTime.now());
bankAccountRepository.save(fromBankAccount);
}
private void operationTransfer(BalanceMovement balanceMovement, BalanceMovementForm form) throws ExceptionHandler {
if (form.toBankAccountId.equals(form.fromBankAccountId)) {
throw new NotAcceptableException("Invalid operation");
}
BankAccount toBankAccount = bankAccountRepository.findById(form.toBankAccountId)
.orElseThrow(() -> new NotFoundException("To BankAccount not found"));
if (toBankAccount.isActive() == false) {
throw new NotAcceptableException("To BankAccount is inactive");
}
BankAccount fromBankAccount = bankAccountRepository.findById(form.fromBankAccountId)
.orElseThrow(() -> new NotFoundException("From BankAccount not found"));
if (fromBankAccount.isActive() == false) {
throw new NotAcceptableException("From BankAccount is inactive");
}
balanceMovement.setOperationType(OperationTypeEnum.TRANSFER);
balanceMovement.setToBankAccount(toBankAccount);
balanceMovement.setFromBankAccount(fromBankAccount);
if (fromBankAccount.getBalance() < form.value) {
throw new NotAcceptableException("Insufficient balance");
}
toBankAccount.balanceDeposit(form.value);
toBankAccount.setUpdatedAt(LocalDateTime.now());
fromBankAccount.balanceWithdraw(form.value);
fromBankAccount.setUpdatedAt(LocalDateTime.now());
bankAccountRepository.save(toBankAccount);
bankAccountRepository.save(fromBankAccount);
}
}
| true
|
242f88dce94d971022c9bcb1d1ae7feca3bd6e65
|
Java
|
yjjungyo/happicklive-product
|
/src/main/java/com/factory/happickliveproduct/domain/vo/ProductImage.java
|
UTF-8
| 339
| 1.609375
| 2
|
[] |
no_license
|
package com.factory.happickliveproduct.domain.vo;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data //lombok annotation
@AllArgsConstructor //lombok annotation
@NoArgsConstructor //lombok annotation
public class ProductImage {
String imagePath;
String imageName;
}
| true
|
57ae77ec180a90d180f91f2c586c157eea38475e
|
Java
|
ahmedibrahim6699/jbpm-form-builder
|
/jbpm-gwt-form-builder/src/main/java/org/jbpm/formbuilder/client/form/items/CheckBoxFormItem.java
|
UTF-8
| 5,128
| 1.96875
| 2
|
[] |
no_license
|
/*
* Copyright 2011 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.formbuilder.client.form.items;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jbpm.formapi.client.FormBuilderException;
import org.jbpm.formapi.client.effect.FBFormEffect;
import org.jbpm.formapi.client.form.FBFormItem;
import org.jbpm.formapi.shared.api.FormItemRepresentation;
import org.jbpm.formapi.shared.api.items.CheckBoxRepresentation;
import org.jbpm.formbuilder.client.FormBuilderGlobals;
import org.jbpm.formbuilder.client.messages.I18NConstants;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Widget;
import com.gwtent.reflection.client.Reflectable;
/**
* UI form item. Represents a checkbox
*/
@Reflectable
public class CheckBoxFormItem extends FBFormItem {
private final I18NConstants i18n = FormBuilderGlobals.getInstance().getI18n();
private CheckBox checkBox = new CheckBox();
private String formValue;
private Boolean checked;
private String name;
private String id;
public CheckBoxFormItem() {
this(new ArrayList<FBFormEffect>());
}
public CheckBoxFormItem(List<FBFormEffect> formEffects) {
super(formEffects);
add(checkBox);
setWidth("15px");
setHeight("15px");
checkBox.setSize(getWidth(), getHeight());
}
@Override
public Map<String, Object> getFormItemPropertiesMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("formValue", this.formValue);
map.put("checked", this.checked);
map.put("name", this.name);
map.put("id", this.id);
map.put("height", getHeight());
map.put("width", getWidth());
return map;
}
@Override
public void saveValues(Map<String, Object> asPropertiesMap) {
this.formValue = extractString(asPropertiesMap.get("formValue"));
this.name = extractString(asPropertiesMap.get("name"));
this.id = extractString(asPropertiesMap.get("id"));
this.checked = extractBoolean(asPropertiesMap.get("checked"));
setHeight(extractString(asPropertiesMap.get("height")));
setWidth(extractString(asPropertiesMap.get("width")));
populate(this.checkBox);
}
private void populate(CheckBox checkBox) {
if (this.formValue != null) {
checkBox.setFormValue(formValue);
}
if (this.name != null) {
checkBox.setName(name);
}
if (this.checked != null) {
checkBox.setValue(checked);
}
if (getWidth() != null) {
checkBox.setWidth(getWidth());
}
if (getHeight() != null) {
checkBox.setHeight(getHeight());
}
}
@Override
public FormItemRepresentation getRepresentation() {
CheckBoxRepresentation rep = super.getRepresentation(new CheckBoxRepresentation());
rep.setFormValue(formValue);
rep.setName(name);
rep.setId(id);
rep.setChecked(checked);
return rep;
}
@Override
public void populate(FormItemRepresentation rep) throws FormBuilderException {
if (!(rep instanceof CheckBoxRepresentation)) {
throw new FormBuilderException(i18n.RepNotOfType(rep.getClass().getName(), "CheckBoxRepresentation"));
}
super.populate(rep);
CheckBoxRepresentation crep = (CheckBoxRepresentation) rep;
this.formValue = crep.getFormValue();
this.name = crep.getName();
this.id = crep.getId();
this.checked = crep.getChecked();
populate(this.checkBox);
}
@Override
public FBFormItem cloneItem() {
CheckBoxFormItem clone = new CheckBoxFormItem(getFormEffects());
clone.setWidth(getWidth());
clone.setHeight(getHeight());
clone.checked = this.checked;
clone.formValue = this.formValue;
clone.id = this.id;
clone.name = this.name;
clone.populate(clone.checkBox);
return clone;
}
@Override
public Widget cloneDisplay(Map<String, Object> data) {
CheckBox cb = new CheckBox();
populate(cb);
Object input = getInputValue(data);
if (input != null) {
cb.setValue(Boolean.valueOf(input.toString()));
}
if (getOutput() != null && getOutput().getName() != null) {
cb.setName(getOutput().getName());
}
super.populateActions(cb.getElement());
return cb;
}
}
| true
|
826fbb3e0b59643afcdf3b7085d980f46dc98844
|
Java
|
oviski/Java3_home_buh
|
/core-app/src/main/java/java3/core/domain/CheckDetails.java
|
UTF-8
| 2,548
| 2.078125
| 2
|
[] |
no_license
|
package java3.core.domain;
import javax.persistence.*;
/**
* Created by admin on 20.04.2017.
*/
@Entity
@Table(name = "checkdetails")
public class CheckDetails extends BaseEntity{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column (name = "checkdetailid")
private Long checkDetailID;
@Column (name = "checkid")
private Long checkID;
@Column (name = "checkpositionid")
private Integer checkPositionID;
@Column (name = "categoryid")
private Integer categoryID;
@Column (name = "subcategoryid")
private Integer subcategoryID;
@Column (name = "productid")
private Long productID;
@Column (name = "sumofproduct")
private Long sumOfProducts;
@Column (name = "positiondetail")
private String positionDetail;
public Long getCheckDetailID() {
return checkDetailID;
}
public void setCheckDetailID(Long checkDetailID) {
this.checkDetailID = checkDetailID;
}
public Long getCheckID() {
return checkID;
}
public void setCheckID(Long checkID) {
this.checkID = checkID;
}
public Integer getCheckPositionID() {
return checkPositionID;
}
public void setCheckPositionID(Integer checkPositionID) {
this.checkPositionID = checkPositionID;
}
public Integer getCategoryID() {
return categoryID;
}
public void setCategoryID(Integer categoryID) {
this.categoryID = categoryID;
}
public Integer getSubcategoryID() {
return subcategoryID;
}
public void setSubcategoryID(Integer subcategoryID) {
this.subcategoryID = subcategoryID;
}
public Long getProductID() {
return productID;
}
public void setProductID(Long productID) {
this.productID = productID;
}
public Long getSumOfProducts() {
return sumOfProducts;
}
public void setSumOfProducts(Long sumOfProducts) {
this.sumOfProducts = sumOfProducts;
}
public String getPositionDetail() {
return positionDetail;
}
public void setPositionDetail(String positionDetails) {
this.positionDetail = positionDetails;
}
}
/*
CREATE TABLE `CheckDetails` (
`CheckID` bigint NOT NULL,
`ChekPositionID` bigint NOT NULL,
`CategoryID` int NOT NULL,
`SubcategoryID` int NOT NULL,
`ProductID` bigint NOT NULL,
`SumOfProduct` bigint DEFAULT '0',
`PositionDatails` varchar,
`DetailsID` varchar NOT NULL,
PRIMARY KEY (`DetailsID`)
)
ENGINE = InnoDB
AUTO_INCREMENT = 1002;
)
*/
| true
|
0724973ecb333c738df204d068cdddc3ad704e10
|
Java
|
Jnoee/xo-starter
|
/xo-starter-jpa/src/main/java/com/github/jnoee/xo/jpa/entity/UuidEntity.java
|
UTF-8
| 627
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.github.jnoee.xo.jpa.entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.hibernate.annotations.GenericGenerator;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* 基于UUID主键的实体基类。
*/
@MappedSuperclass
@Getter
@Setter
@EqualsAndHashCode(of = "id")
@ToString
public abstract class UuidEntity {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "org.hibernate.id.UUIDGenerator")
protected String id;
}
| true
|
e12a45940635222e42a8d3e31c3220de46dabd63
|
Java
|
abdurahmanovart/KsWeather
|
/app/src/main/java/com/github/arturx/weatherbykulibin/CurrentWeatherFragment.java
|
UTF-8
| 3,135
| 2.4375
| 2
|
[] |
no_license
|
package com.github.arturx.weatherbykulibin;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.arturx.weatherbykulibin.bean.WeatherData;
/**
* Created by arturx on 06.12.17.
*/
public class CurrentWeatherFragment extends Fragment {
private ImageView mWeatherImage;
private TextView mTemperatureTextView;
private TextView mWindTextView;
private TextView mHumidityTextView;
private TextView mCityTextView;
private WeatherData mWeatherData;
private String mCityName;
public static CurrentWeatherFragment newInstance(WeatherData data, String city) {
CurrentWeatherFragment fragment = new CurrentWeatherFragment();
Bundle args = new Bundle();
args.putParcelable(MainActivity.TAG, data);
args.putString(MainActivity.EXTRA_CITY_NAME, city);
fragment.setArguments(args);
return fragment;
}
public CurrentWeatherFragment() {
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWeatherData = getArguments().getParcelable(MainActivity.TAG);
mCityName = getArguments().getString(MainActivity.EXTRA_CITY_NAME);
System.out.println(mWeatherData.getMainWeatherData().getTemperature());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_current_weather, null);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initUI(view);
setValuesToViews();
}
private void setValuesToViews() {
mWeatherImage.setImageResource(R.drawable.icon_rainy_weather);
mTemperatureTextView.setText(String.format("Температура воздуха %sC", String.valueOf(mWeatherData.getMainWeatherData().getTemperature())));
mWindTextView.setText(String.format("Скорость ветра %sм/с", String.valueOf(mWeatherData.getWindData().getSpeed())));
mHumidityTextView.setText(String.format("Влажность воздуха %s процентов", String.valueOf(mWeatherData.getMainWeatherData().getHumidity())));
mCityTextView.setText(String.format("Погода в %s", mCityName));
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
private void initUI(View view) {
mWeatherImage = view.findViewById(R.id.current_weather_image_view);
mTemperatureTextView = view.findViewById(R.id.temperature_text_view);
mWindTextView = view.findViewById(R.id.wind_text_view);
mCityTextView = view.findViewById(R.id.city_text_view);
mHumidityTextView = view.findViewById(R.id.humidity_text_view);
}
}
| true
|
64ddc08b448572d5d7dcd229611d7097b256a169
|
Java
|
rainkin1993/AnomalyDetection
|
/src/main/java/edu/zju/BasicClass/semantic/SemanticFile.java
|
UTF-8
| 825
| 2.953125
| 3
|
[] |
no_license
|
package edu.zju.BasicClass.semantic;
public class SemanticFile extends SemanticVertex{
public String filePath;
public SemanticFile(String filePath) {
super();
this.filePath = filePath;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((filePath == null) ? 0 : filePath.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SemanticFile other = (SemanticFile) obj;
if (filePath == null) {
if (other.filePath != null)
return false;
} else if (!filePath.equals(other.filePath))
return false;
return true;
}
@Override
public String toString() {
return "\"" + filePath + "\"";
}
}
| true
|
ece5c85d2cf434a2bdb6c2ff1c7d470b687cb922
|
Java
|
lyh7712/disease-notification
|
/src/main/java/nsuproject/diseasenotification/worlddata/WorldDataController.java
|
UTF-8
| 787
| 1.828125
| 2
|
[] |
no_license
|
package nsuproject.diseasenotification.worlddata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class WorldDataController {
@Autowired
WorldService service;
@GetMapping("/world/data")
public List<WorldData> getAllData() {
String url = "https://search.naver.com/search.naver?where=nexearch&sm=top_sug.pre&fbm=1&acr=1&acq=%EC%84%B8%EA%B3%84+%EC%BD%94%EB%A1%9C%EB%82%98+%ED%99%95%EC%A7%84&qdt=0&ie=utf8&query=%EC%A0%84%EC%84%B8%EA%B3%84+%EC%BD%94%EB%A1%9C%EB%82%98+%ED%99%95%EC%A7%84%EC%9E%90";
service.insertData(url);
return service.findAllData();
}
}
| true
|
e58f89253691f045ef590be5578b6f713115d235
|
Java
|
275779273/zrzk
|
/zrzk_shiro/src/main/java/com/zrzk/pojo/TUser.java
|
UTF-8
| 1,655
| 2.3125
| 2
|
[] |
no_license
|
package com.zrzk.pojo;
import java.util.Set;
public class TUser {
private Integer id;
private String username;
private String password;
private String loginname;
/**
* 用户对应的角色集合
*/
private Set<TRole> roles;
public TUser(Integer id, String username, String password, String loginname, Set<TRole> roles) {
this.id = id;
this.username = username;
this.password = password;
this.loginname = loginname;
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getLoginname() {
return loginname;
}
public void setLoginname(String loginname) {
this.loginname = loginname == null ? null : loginname.trim();
}
public Set<TRole> getRoles() {
return roles;
}
public void setRoles(Set<TRole> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "TUser{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", loginname='" + loginname + '\'' +
", roles=" + roles +
'}';
}
}
| true
|
98a518ff96eae66e4125e90df96e58f69c61a264
|
Java
|
JiessieJ/test01
|
/src/main/java/com/jiessie/test01/utils/VerificationUtil.java
|
UTF-8
| 2,244
| 2.390625
| 2
|
[] |
no_license
|
package com.jiessie.test01.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.util.*;
@Slf4j
@Component
public class VerificationUtil {
public String authPrams(String accountNo, String secretCode, Long timestamp, Object paramObj) {
String signCode = null;
Map<String, Object> requestMap = new HashMap<>();
List<String> paramList = new ArrayList<>();
try {
requestMap.put("accountNo", accountNo);
requestMap.put("secretCode", secretCode);
requestMap.put("timestamp", timestamp);
requestMap.put("data", paramObj != null ? paramObj : new HashMap<String, Object>());
String preAuthStr = JSONObject.toJSONString(requestMap);
JSONObject requestJ = JSONObject.parseObject(preAuthStr);
paramObj2ParamList(null, requestJ, paramList);
Collections.sort(paramList);
String paramCode = StringUtils.join(paramList, "&");
signCode = StringUtil.md5(paramCode);
return signCode;
} catch (Exception e) {
e.printStackTrace();
}
return signCode;
}
private void paramObj2ParamList(String authKey, Object authValue, List<String> paramList) {
try {
if (authValue instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) authValue;
for (String pkey : jsonObject.keySet()) {
paramObj2ParamList(pkey, jsonObject.get(pkey), paramList);
}
} else if (authValue instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) authValue;
for (Object valueObj : jsonArray) {
paramObj2ParamList(authKey, valueObj, paramList);
}
} else {
if (authValue != null) {
paramList.add(authKey.trim() + "=" + authValue);
}
}
} catch (Exception e) {
e.printStackTrace();
log.error(e.toString());
}
}
}
| true
|
ebfc87de847ed602785fd0424ceff1a8fcd19f53
|
Java
|
jerr/jboss-as-addon
|
/common/src/main/java/org/jboss/forge/addon/as/jboss/common/util/Files.java
|
UTF-8
| 11,659
| 2.46875
| 2
|
[] |
no_license
|
/*
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/package org.jboss.forge.addon.as.jboss.common.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
/**
* Utility for {@link java.io.File files}.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
public class Files {
static final String TMP_DIR_PROPERTY = "java.io.tmpdir";
/**
* Creates a file from the base with each path element.
*
* @param base the parent directory
* @param paths the paths to create
*
* @return a new file
*/
public static File createFile(final File base, final String... paths) {
final StringBuilder sb = new StringBuilder();
int count = 0;
for (String path : paths) {
sb.append(path);
if (!path.endsWith(File.separator) && (++count < paths.length)) {
sb.append(File.separator);
}
}
return new File(base, sb.toString());
}
/**
* Creates a new file based on the path elements.
*
* @param paths the path elements
*
* @return a new file
*/
public static String createPath(final String... paths) {
final StringBuilder sb = new StringBuilder();
int count = 0;
for (String path : paths) {
sb.append(path);
if (!path.endsWith(File.separator) && (++count < paths.length)) {
sb.append(File.separator);
}
}
return sb.toString();
}
/**
* Returns the temporary directory.
*
* @return the temporary directory
*/
public static File getTempDirectory() {
return new File(getProperty(TMP_DIR_PROPERTY));
}
public static boolean extractAppServer(final String zipPath, final File target) throws IOException {
return extractAppServer(zipPath, target, false);
}
public static boolean extractAppServer(final String zipPath, final File target, final boolean overwrite) throws IOException {
if (target.exists() && !overwrite) {
throw new IllegalStateException(Messages.INSTANCE.getMessage("files.not.empty.directory"));
}
// Create a temporary directory
final File tmpDir = new File(getTempDirectory(), "jboss-as-" + zipPath.hashCode());
if (tmpDir.exists()) {
deleteRecursively(tmpDir);
}
try {
final byte buff[] = new byte[1024];
ZipFile file = null;
try {
file = new ZipFile(zipPath);
final Enumeration<ZipArchiveEntry> entries = file.getEntries();
while (entries.hasMoreElements()) {
final ZipArchiveEntry entry = entries.nextElement();
// Create the extraction target
final File extractTarget = new File(tmpDir, entry.getName());
if (entry.isDirectory()) {
extractTarget.mkdirs();
} else {
final File parent = new File(extractTarget.getParent());
parent.mkdirs();
final BufferedInputStream in = new BufferedInputStream(file.getInputStream(entry));
try {
final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(extractTarget));
try {
int read;
while ((read = in.read(buff)) != -1) {
out.write(buff, 0, read);
}
} finally {
Streams.safeClose(out);
}
} finally {
Streams.safeClose(in);
}
// Set the file permissions
if (entry.getUnixMode() > 0) {
setPermissions(extractTarget, FilePermissions.of(entry.getUnixMode()));
}
}
}
} catch (IOException e) {
throw new IOException(Messages.INSTANCE.getMessage("files.extraction.error", file), e);
} finally {
ZipFile.closeQuietly(file);
// Streams.safeClose(file);
}
// If the target exists, remove then rename
if (target.exists()) {
deleteRecursively(target);
}
// First child should be a directory and there should only be one child
final File[] children = tmpDir.listFiles();
if (children != null && children.length == 1) {
return moveDirectory(children[0], target);
}
return moveDirectory(tmpDir, target);
} finally {
deleteRecursively(tmpDir);
}
}
/**
* Checks to see if a directory is empty.
*
* @param dir the directory to check
*
* @return {@code true} if the directory is empty, otherwise {@code false}
*
* @throws IllegalArgumentException if the parameter in is not a directory
*/
public static boolean isEmptyDirectory(final File dir) {
if (!dir.exists()) return true;
if (dir.isDirectory()) {
final String[] files = dir.list();
return files == null || files.length == 0;
}
throw new IllegalArgumentException(Messages.INSTANCE.getMessage("files.not.directory", dir));
}
/**
* Recursively deletes all files and directories within the directory as well as the directory itself.
* <p/>
* On a failure this does not preserve files that have been deleted.
*
* @param dir the directory to delete
*
* @return {@code true} if the directory and all it's contents were deleted, otherwise {@code false}
*/
public static boolean deleteRecursively(final File dir) {
if (dir.isDirectory()) {
final File[] files = dir.listFiles();
if (files != null) {
for (final File f : files) {
if (f.isDirectory()) {
if (!deleteRecursively(f)) {
return false;
}
} else if (!f.delete()) {
return false;
}
}
}
}
return dir.delete();
}
/**
* Recursively copies a directories contents to the target directory then deletes the source directory.
* <p/>
* If a non-fatal failure occurs the {@code srcDir} might be partially deleted if the failure occurred during the
* delete, otherwise it should be left as is. The {@code targetDir} may or may not have been created and may or may
* not contain some or all of the contents from the {@code srcDir}.
*
* @param srcDir the source directory
* @param targetDir the target directory
*
* @return {@code true} if the contents were successfully copied, {@code false} if the contents were not copied or
* partially copied but a failure occurred
*
* @throws IOException if an IO error occurs copying a file or creating directories
*/
public static boolean moveDirectory(final File srcDir, final File targetDir) throws IOException {
boolean result = srcDir.renameTo(targetDir);
// First try rename
if (!result) {
result = copyDirectory(srcDir, targetDir) && deleteRecursively(srcDir);
}
return result;
}
/**
* Recursively copies a directories contents to the target directory.
*
* @param srcDir the source directory
* @param targetDir the target directory
*
* @return {@code true} if the contents were successfully copied, {@code false} if the contents were not copied or
* partially copied but a failure occurred
*
* @throws IOException if an IO error occurs copying a file or creating directories
*/
public static boolean copyDirectory(final File srcDir, final File targetDir) throws IOException {
final File[] contents = srcDir.listFiles();
for (File file : contents != null ? contents : new File[0]) {
final File target = new File(targetDir, file.getName());
if (file.isDirectory()) {
target.mkdirs();
if (!copyDirectory(file, target)) {
return false;
}
} else {
target.getParentFile().mkdirs();
if (!copyFile(file, target)) {
return false;
}
}
}
return true;
}
/**
* Copies the source file to the destination file.
*
* @param srcFile the file to copy
* @param targetFile the target file
*
* @return {@code true} if the file was successfully copied, {@code false} if the copy failed or was incomplete
*
* @throws IOException if an IO error occurs copying the file
*/
public static boolean copyFile(final File srcFile, final File targetFile) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
in = new FileInputStream(srcFile);
inChannel = in.getChannel();
out = new FileOutputStream(targetFile);
outChannel = out.getChannel();
long bytesTransferred = 0;
while (bytesTransferred < inChannel.size()) {
bytesTransferred += inChannel.transferTo(0, inChannel.size(), outChannel);
}
} finally {
Streams.safeClose(outChannel);
Streams.safeClose(out);
Streams.safeClose(inChannel);
Streams.safeClose(in);
}
return srcFile.length() == targetFile.length();
}
/**
* Sets the permissions on the file.
*
* @param file the file
* @param permissions the permissions to set
*/
public static void setPermissions(final File file, final FilePermissions permissions) {
file.setExecutable(permissions.owner().canExecute(), !(permissions.group().canExecute() && permissions.pub()
.canExecute()));
file.setReadable(permissions.owner().canWrite(), !(permissions.group().canWrite() && permissions.pub()
.canWrite()));
file.setWritable(permissions.owner().canWrite(), !(permissions.group().canWrite() && permissions.pub()
.canWrite()));
}
static String getProperty(final String key) {
if (System.getSecurityManager() == null) {
return System.getProperty(key);
}
return AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty(key);
}
});
}
}
| true
|
4d8aff091c40620bc0bae74afa545537588c0829
|
Java
|
zhouluoyang0406/SelfIntroduction
|
/DesignPatterns/src/main/java/interpreter/Client.java
|
UTF-8
| 397
| 2.75
| 3
|
[] |
no_license
|
package interpreter;
import java.util.HashMap;
public class Client {
public static void main(String[] args) {
String ex="a+b-c";
HashMap<String,Integer> var=new HashMap<String, Integer>();
var.put("a",3);
var.put("b",4);
var.put("c",1);
Calculator cal=new Calculator(ex);//封装成一棵树
System.out.println(cal.run(var));
}
}
| true
|
6dadade932dc60fa029e959ebc9fea1232c09da1
|
Java
|
green-fox-academy/ZaitzeV16
|
/week-08/day-2/connectMySQL/src/main/java/com/greenfox/mysql/connect_mysql/services/AssigneeService.java
|
UTF-8
| 536
| 2.015625
| 2
|
[] |
no_license
|
package com.greenfox.mysql.connect_mysql.services;
import com.greenfox.mysql.connect_mysql.models.Assignee;
import com.greenfox.mysql.connect_mysql.models.Todo;
import java.util.List;
public interface AssigneeService {
public List<Assignee> findAll();
public List<Assignee> findAllByName(String name);
public Assignee findById(long id);
public void save(Assignee assignee);
public void save(Assignee assignee, Todo todo);
public void update(long id, String name, String email);
public void deleteById(long id);
}
| true
|
f92bc691ed1b291910cd57845203536a908bd7ac
|
Java
|
RoscaS/java_dreamteam-clean
|
/PLambda/src/ch/arc/cours/g_annexe/tools/Int.java
|
UTF-8
| 2,010
| 3.078125
| 3
|
[] |
no_license
|
package ch.arc.cours.g_annexe.tools;
import java.io.Serializable;
/**
* Wrapper Alterable
*/
public class Int implements Serializable
{
/*------------------------------------------------------------------*\
|* Constructeurs *|
\*------------------------------------------------------------------*/
public Int(int i)
{
this.i = i;
}
public Int(Int source)
{
this(source.intvalue());
}
/*------------------------------------------------------------------*\
|* Methodes Public *|
\*------------------------------------------------------------------*/
@Override
public String toString()
{
return EMPTY + i;
}
public Int cloneOf()
{
return new Int(this);
}
@Override
protected Int clone() throws CloneNotSupportedException
{
return this.cloneOf();
}
public int inc()
{
i++;
return i;
}
/*------------------------------*\
|* Get *|
\*------------------------------*/
public int intvalue()
{
return this.i;
}
/*------------------------------*\
|* Set *|
\*------------------------------*/
public void setValue(int i)
{
this.i = i;
}
/*------------------------------*\
|* Static *|
\*------------------------------*/
public static int sum(int a, int b)
{
return a + b;
}
public static int prod(int a, int b)
{
return a * b;
}
public static int inc(int a)
{
return a + 1;
}
public static boolean isPaire(int x)
{
return x % 2 == 0;
}
/*------------------------------------------------------------------*\
|* Methodes Private *|
\*------------------------------------------------------------------*/
/*------------------------------------------------------------------*\
|* Attributs Private *|
\*------------------------------------------------------------------*/
private int i;
/*------------------------------*\
|* Static *|
\*------------------------------*/
private static final String EMPTY = "";
}
| true
|
6e8fcf3f609d7015535915543fded6fbd9f3a59d
|
Java
|
blacksider/javafx-demo
|
/src/main/java/demo/control/EventBus.java
|
UTF-8
| 629
| 2.375
| 2
|
[
"MIT"
] |
permissive
|
package demo.control;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.PublishSubject;
/**
* Created by Snart Lu on 2018/2/5.
*/
public class EventBus {
private static final EventBus INSTANCE = new EventBus();
private final PublishSubject<Event> mBusSubject = PublishSubject.create();
public static EventBus getInstance() {
return INSTANCE;
}
public Disposable register(Consumer<Event> onNext) {
return mBusSubject.subscribe(onNext);
}
public void postSave(Event event) {
mBusSubject.onNext(event);
}
}
| true
|
7c7138899b14c572e77497fc404204b94af2d07e
|
Java
|
VoQspu/kwiaciarniaserver
|
/service/src/test/pl/kielce/tu/kwiaciarnia/service/flower/FlowerServiceImplTest.java
|
UTF-8
| 4,693
| 2.4375
| 2
|
[] |
no_license
|
package pl.kielce.tu.kwiaciarnia.service.flower;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import pl.kielce.tu.kwiaciarnia.dto.bouquet.Bouquet;
import pl.kielce.tu.kwiaciarnia.exception.FailedToDeleteException;
import pl.kielce.tu.kwiaciarnia.exception.FailedToEditException;
import pl.kielce.tu.kwiaciarnia.model.flower.Flower;
import pl.kielce.tu.kwiaciarnia.repository.FlowerRepository;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class FlowerServiceImplTest {
private FlowerServiceImpl flowerService;
@Mock
private FlowerRepository flowerRepository;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
flowerService = spy(new FlowerServiceImpl(flowerRepository));
}
@Test
void shouldGetAllFlowers() {
//given
List<Flower> givenFlowers = prepareFlowers();
when(flowerRepository.findAll()).thenReturn(givenFlowers);
//when
List<Flower> allFlowers = flowerService.findAll();
//then
assertEquals(givenFlowers, allFlowers);
verify(flowerRepository).findAll();
}
@Test
void shouldAddNewFlower() {
//given
Flower flower = new Flower();
flower.setId(1L);
//when
String result = flowerService.add(flower);
//then
assertEquals("Item o podanym id: " + flower.getId() + " został pomyślnie dodany", result);
verify(flowerRepository).save(any(Flower.class));
}
@Test
void shouldUpdateFlower() {
//given
Flower existingFlower = new Flower();
existingFlower.setId(1L);
when(flowerRepository.findById(anyLong())).thenReturn(Optional.of(existingFlower));
//when
String result = flowerService.update(1L, new Flower());
//then
assertEquals("Item o podanym id: " + 1L + " został pomyślnie zedytowany", result);
verify(flowerRepository).findById(anyLong());
verify(flowerRepository).save(any(Flower.class));
}
@Test
void updateShouldThrowExceptionIfFlowerNotExist() {
//given
when(flowerRepository.findById(anyLong())).thenReturn(Optional.empty());
//when
//then
Assertions.assertThrows(FailedToEditException.class, () -> flowerService.update(1L, new Flower()));
verify(flowerRepository).findById(anyLong());
}
@Test
void shouldDeleteFlower() {
//given
Flower existingFlower = new Flower();
existingFlower.setId(1L);
when(flowerRepository.findById(anyLong())).thenReturn(Optional.of(existingFlower));
//when
String result = flowerService.delete(1L);
//then
assertEquals("Item o podanym id: " + 1L + " został pomyślnie usunięty", result);
verify(flowerRepository).findById(anyLong());
verify(flowerRepository).deleteById(anyLong());
}
@Test
void deleteShouldThrowExceptionIfFlowerNotExist() {
//given
when(flowerRepository.findById(anyLong())).thenReturn(Optional.empty());
//when
//then
Assertions.assertThrows(FailedToDeleteException.class, () -> flowerService.delete(1L));
verify(flowerRepository).findById(anyLong());
}
@Test
void shouldReduceAmountOfFlowers() {
//given
List<Bouquet> bouquets = new ArrayList<>();
List<Flower> flowers = new ArrayList<>();
Flower flower = prepareFlower();
Bouquet bouquet = new Bouquet();
flowers.add(flower);
bouquet.setFlowers(flowers);
bouquets.add(bouquet);
when(flowerRepository.findById(anyLong())).thenReturn(Optional.of(flower));
when(flowerRepository.save(any(Flower.class))).then(i -> i.getArgument(0, Flower.class));
//when
flowerService.reduce(bouquets);
//then
assertEquals(0, flower.getAmount());
verify(flowerRepository).findById(anyLong());
}
private Flower prepareFlower() {
Flower flower = new Flower();
flower.setId(1L);
flower.setAmount(5);
return flower;
}
private List<Flower> prepareFlowers() {
Flower flower0 = new Flower();
Flower flower1 = new Flower();
Flower flower2 = new Flower();
flower0.setId(0L);
flower1.setId(1L);
flower2.setId(2L);
return Arrays.asList(flower0, flower1, flower2);
}
}
| true
|
3d209d2c14331356b168f20deba8c98e02f3d246
|
Java
|
mohamedh5/Accommodation
|
/src/main/java/com/iter/accommodation/booking/dto/StrikethroughAmountPerNight__1.java
|
UTF-8
| 2,557
| 2.0625
| 2
|
[] |
no_license
|
package com.iter.accommodation.booking.dto;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"value",
"currency"
})
@Generated("jsonschema2pojo")
public class StrikethroughAmountPerNight__1 implements Serializable
{
@JsonProperty("value")
private Integer value;
@JsonProperty("currency")
private String currency;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = -4890590255845435132L;
@JsonProperty("value")
public Integer getValue() {
return value;
}
@JsonProperty("value")
public void setValue(Integer value) {
this.value = value;
}
@JsonProperty("currency")
public String getCurrency() {
return currency;
}
@JsonProperty("currency")
public void setCurrency(String currency) {
this.currency = currency;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(StrikethroughAmountPerNight__1 .class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("value");
sb.append('=');
sb.append(((this.value == null)?"<null>":this.value));
sb.append(',');
sb.append("currency");
sb.append('=');
sb.append(((this.currency == null)?"<null>":this.currency));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
}
| true
|
77c2a56e7a4701a20dbf93349481db08f63f5cf8
|
Java
|
dnychava/MISSystem
|
/MISSystem/src/main/java/com/ikaustubh/missystem/services/impl/ExpenditureServiceImpl.java
|
UTF-8
| 4,369
| 1.953125
| 2
|
[] |
no_license
|
package com.ikaustubh.missystem.services.impl;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.ikaustubh.missystem.dto.FMRReportFilterDTO;
import com.ikaustubh.missystem.entities.ActivityEntity;
import com.ikaustubh.missystem.entities.BudgetDistributeEntity;
import com.ikaustubh.missystem.entities.ExpenditureEntity;
import com.ikaustubh.missystem.repository.ExpenditureRepository;
import com.ikaustubh.missystem.services.ExpenditureService;
import com.ikaustubh.missystem.wrapper.ExpenditureWrapper;
@Service
public class ExpenditureServiceImpl implements ExpenditureService {
@Autowired
private ExpenditureRepository expenditueRepo;
@Override
public Set<ExpenditureEntity> findByUnitRidAndSubActivityRids(long unitRid, Set<Long> subActivityRids) {
return findByUnitRidAndSubActivityRids(unitRid, null, subActivityRids);
}
@Override
public Set<ExpenditureEntity> findByUnitRidAndSubActivityRids(long unitRid, String year,
Set<Long> subActivityRids) {
return findByUnitRidAndSubActivityRids(unitRid, year, null, subActivityRids);
}
@Transactional(isolation=Isolation.READ_COMMITTED, propagation=Propagation.REQUIRES_NEW, readOnly=true)
@Override
public Set<ExpenditureEntity> findByUnitRidAndSubActivityRids(long unitRid, String year,
LocalDateTime reportingMonth, Set<Long> subActivityRids) {
return expenditueRepo.findByUnitRidAndSubActivityRids( unitRid, year, reportingMonth, subActivityRids);
}
@Override
public Map<Long, ExpenditureWrapper> getPrograssiveAmtAndBudget(long unitRid, String year,
Set<Long> subActivityRids, boolean isFeatchBudgetData) {
return getPrograssiveAmtAndBudget(unitRid, year, subActivityRids, isFeatchBudgetData, -1);
}
@Transactional(isolation=Isolation.READ_COMMITTED, propagation=Propagation.REQUIRES_NEW, readOnly=true)
@Override
public Map<Long, ExpenditureWrapper> getPrograssiveAmtAndBudget(long unitRid, String year,
Set<Long> subActivityRids, boolean isFeatchBudgetData, int reportingMonth) {
return expenditueRepo.getPrograssiveAmtAndBudget(unitRid, year, subActivityRids, isFeatchBudgetData, reportingMonth);
}
@Transactional(isolation=Isolation.READ_COMMITTED, propagation=Propagation.REQUIRES_NEW, readOnly=true)
@Override
public ExpenditureEntity findByUnitRidAndSubActivityRids(long unitRid, String year, long subActivityRid) {
return expenditueRepo.findByUnitRidAndSubActivityRids(unitRid, year, subActivityRid);
}
@Transactional(isolation=Isolation.READ_COMMITTED, propagation=Propagation.REQUIRES_NEW, readOnly=true)
@Override
public List<BudgetDistributeEntity> findBudgetList(String unitName, String year) {
return expenditueRepo.findBudgetList(unitName, year);
}
@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=false)
public List<ExpenditureEntity> saveAll(List<ExpenditureEntity> entities){
return expenditueRepo.saveAll(entities);
}
@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=false)
@Override
public void saveOrUpdate(List<ExpenditureEntity> expenditureEntities) {
for (ExpenditureEntity expenditureEntity : expenditureEntities) {
}
}
@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true)
@Override
public List<ActivityEntity> getAllParentActivity(long mainHeadPrmRid, String financialYear) {
return expenditueRepo.getAllParentActivity(mainHeadPrmRid, financialYear);
}
@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true)
@Override
public List<ExpenditureEntity> getAllExpenditureUsingFilter(FMRReportFilterDTO fmrReportFilterDTO,
List<Long> activityRidList) {
return expenditueRepo.getAllExpenditureUsingFilter(fmrReportFilterDTO, activityRidList);
}
@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true)
@Override
public List<BudgetDistributeEntity> getAllBudgetSharedUsingFilter(FMRReportFilterDTO fmrReportFilterDTO,
List<Long> activityRidList) {
return expenditueRepo.getAllBudgetSharedUsingFilter(fmrReportFilterDTO, activityRidList);
}
}
| true
|
32a7b1b6a6d5a6d0b4a0dad5ed62fb9016653881
|
Java
|
mblackhall/Week4
|
/com/marcus/hello/exercises/exercise2/FizzBuzz.java
|
UTF-8
| 977
| 3.953125
| 4
|
[] |
no_license
|
package com.marcus.hello.exercises.exercise2;
/**
* @author marcus
* if int divisble by 3 only print 'Fizz'
* If int dicisible by 5 only print 'Buzz'
* if int divisible by 3 and 5 print FizzBuzz
* otherwise print int
*/
public final class FizzBuzz {
private static final String FIZZ = "Fizz";
private static final String BUZZ = "Buzz";
private static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
FizzBuzz fizzBuzz = new FizzBuzz();
for (int i = 1; i <= 100; i++) {
System.out.println(fizzBuzz.getFizzBuzz(i));
}
}
public String getFizzBuzz(int number) {
sb.setLength(0);
if (number % 3 == 0) {
sb.append(FIZZ);
}
if (number % 5 == 0) {
sb.append(BUZZ);
}
if (sb.length() == 0) {
sb.append(number);
}
return sb.toString();
}
}
| true
|
741bb9d28a7ee774c09d992c8473158982d34c24
|
Java
|
JiXiaoUIC/CS342-Project4
|
/src/battleShip/GameServer.java
|
UTF-8
| 4,817
| 2.96875
| 3
|
[] |
no_license
|
package battleShip;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GameServer extends JFrame implements ActionListener{
// GUI items
JButton ssButton;
JLabel machineInfo;
JLabel portInfo;
JTextArea history;
private boolean running;
static GameClient server = null;
// Network Items
boolean serverContinue;
ServerSocket serverSocket;
// set up GUI
public GameServer()
{
super( "Echo Server" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// create buttons
running = false;
ssButton = new JButton( "Start Listening" );
ssButton.addActionListener( this );
container.add( ssButton );
String machineAddress = null;
try
{
InetAddress addr = InetAddress.getLocalHost();
machineAddress = addr.getHostAddress();
}
catch (UnknownHostException e)
{
machineAddress = "127.0.0.1";
}
machineInfo = new JLabel (machineAddress);
container.add( machineInfo );
portInfo = new JLabel (" Not Listening ");
container.add( portInfo );
history = new JTextArea ( 10, 40 );
history.setEditable(false);
container.add( new JScrollPane(history) );
setSize( 500, 250 );
setVisible( true );
} // end CountDown constructor
public void actionPerformed( ActionEvent event )
{
if (running == false)
{
new ConnectionThread (this);
}
else
{
serverContinue = false;
ssButton.setText ("Start Listening");
portInfo.setText (" Not Listening ");
}
}
} // end class EchoServer3
class ConnectionThread extends Thread
{
GameServer gui;
public ConnectionThread (GameServer es3)
{
gui = es3;
start();
}
public void run()
{
gui.serverContinue = true;
try
{
gui.serverSocket = new ServerSocket(0);
gui.portInfo.setText("Listening on Port: " + gui.serverSocket.getLocalPort());
System.out.println ("Connection Socket Created");
try {
while (gui.serverContinue)
{
System.out.println ("Waiting for Connection");
gui.ssButton.setText("Stop Listening");
new CommunicationThread (gui.serverSocket.accept(), gui);
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally
{
try {
gui.serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
}
class CommunicationThread extends Thread
{
//private boolean serverContinue = true;
private Socket clientSocket;
private GameServer gui;
private int count = 0;
private Game2 game;
public CommunicationThread (Socket clientSoc, GameServer ec3)
{
clientSocket = clientSoc;
gui = ec3;
gui.history.insert ("Comminucating with Port" + clientSocket.getLocalPort()+"\n", 0);
game = new Game2(this);
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
int array[] = new int[2];
while ( ( array = (int[]) in.readObject()) != null ){
game.beHit(array[0],array[1]);
}
//
// String inputLine;
// while ((inputLine = in.readLine()) != null)
// {
// System.out.println ("Server: " + inputLine);
// gui.history.insert (inputLine+"\n", 0);
//
// if( inputLine == " ")
// out.println(inputLine);
//
//
// if (inputLine.equals("Bye."))
// break;
//
// if (inputLine.equals("End Server."))
// gui.serverContinue = false;
// }
out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
//System.exit(1);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
eaa44a77ce38511d7c3e6178571e203cc1e48896
|
Java
|
SankalpTaruFoundation/Organic-Green-App
|
/src/org/sankalptaru/kg/community/AboutusFragment.java
|
UTF-8
| 675
| 2.015625
| 2
|
[] |
no_license
|
package org.sankalptaru.kg.community;
import android.app.Fragment;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class AboutusFragment extends Fragment {
public AboutusFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_aboutus, container, false);
TextView foo = (TextView)rootView.findViewById(R.id.aboutusDesc);
foo.setText(Html.fromHtml(getString(R.string.aboutus)));
return rootView;
}
}
| true
|
b1a6f4488e118450a9b7eaac58ecad3c55920129
|
Java
|
IssacYoung2013/daily
|
/00-dialog-mq/src/main/java/com/dialog/mq/rocketmq/simple/Consumer.java
|
UTF-8
| 1,386
| 2.3125
| 2
|
[] |
no_license
|
package com.dialog.mq.rocketmq.simple;
import com.dialog.mq.rocketmq.constant.Const;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import java.util.List;
/**
*
*
* @author: ywy
* @date: 2019-09-29
* @desc:
*/
public class Consumer {
public static void main(String[] args) throws MQClientException {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_group_name");
consumer.setNamesrvAddr(Const.NAME_SERVER);
// subscribe
consumer.subscribe("test-topic","*");
consumer.registerMessageListener(new MessageListenerConcurrently() {
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
System.out.println("Receive New Message:" + Thread.currentThread().getName() + " " + msgs);
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
consumer.start();
System.out.println("Consumer Started...");
}
}
| true
|
5f17efcea05ef3945bdb21d079d6c7bb67bb7ffc
|
Java
|
sisyphus60/Design_pattern
|
/src/org/lawrence/pattern/composite/Client.java
|
UTF-8
| 858
| 2.5625
| 3
|
[] |
no_license
|
package org.lawrence.pattern.composite;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Company group = new ConcreteCompany("Alibaba");
Company etao = new ConcreteCompany("etao");
Company taobao = new ConcreteCompany("taobao");
Company bijia = new DepartmentCompany("bijia");
Company shouji = new DepartmentCompany("shouji");
Company wuxian = new DepartmentCompany("wuxian");
Company pc = new DepartmentCompany("pc");
etao.add(bijia);
etao.add(shouji);
taobao.add(wuxian);
taobao.add(pc);
group.add(etao);
group.add(taobao);
group.display();
}
}
| true
|
a4264413d210cb86de815fdcb9cbd28ef5a9bf93
|
Java
|
Sinahdalir/MiraCosta
|
/HW06/src/testers/PrintJobTest.java
|
UTF-8
| 1,102
| 2.671875
| 3
|
[] |
no_license
|
package testers;
import edu.miracosta.cs113.PrintJob;
import static org.junit.Assert.*;
import org.junit.Test;
public class PrintJobTest {
PrintJob object = new PrintJob(10, 10);
@Test
public void testPrintJob() {
PrintJob object1 = new PrintJob();
assertEquals(object1.getStartTime(), 0);
}
@Test
public void testPrintJobIntInt() {
PrintJob object1 = new PrintJob(5, 5);
assertEquals(object1.getStartTime(), 5);
assertEquals(object1.getNumberPapers(), 5);
}
@Test
public void testGetNumberPapers() {
assertEquals(object.getNumberPapers(), 10);
}
@Test
public void testSetNumberPapers() {
object.setNumberPapers(20);
assertEquals(object.getNumberPapers(), 20);
}
@Test
public void testGetStartTime() {
assertEquals(object.getStartTime(), 10);
}
@Test
public void testSetStartTime() {
object.setStartTime(20);
assertEquals(object.getStartTime(), 20);
}
@Test
public void testGetTimeToPrint() {
object.setNumberPapers(20);
assertEquals(object.getTimeToPrint(), 2 + object.getStartTime());
}
}
| true
|
4bb868cc290fcc9999e81b05abac4aa11f1c7163
|
Java
|
jefersonjl99/Java
|
/PI/src/pi/Montecarlo.java
|
UTF-8
| 1,054
| 3
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pi;
/**
*
* @author jefer
*/
public class Montecarlo extends Metodos {
double x, y;
@Override
double calcular_pi() {
int n = 50000000;
int contadorAdentro = 0;
for (int i = 0; i < n; i++) {
this.x = (Math.random() * 2);
this.y = (Math.random() * 2);
if (this.esta_dentro(1) == true) {
/*
g.setColor(Color.RED);
g.drawString(".", (int) ((punto.x * 100) / (radio)) + 149, (int) ((punto.y * 100) / (radio)) + 201);*/
contadorAdentro++;
}
}
double pi = (double) ((4 * (double) contadorAdentro) / ((double) n));
return pi;
}
boolean esta_dentro(double r) {
return (Math.sqrt(Math.pow(this.x - (r), 2) + Math.pow(this.y - (r), 2))) <= (r);
}
}
| true
|
5e5083c6c788c7bcfe13d9c570c10650976688d0
|
Java
|
ProyectoBootcamp3/customer-service
|
/src/main/java/com/everis/controller/CustomerControllerAdvice.java
|
UTF-8
| 786
| 2.109375
| 2
|
[] |
no_license
|
package com.everis.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import reactor.core.publisher.Mono;
/**
* Slf4j : Logback.
*/
@Slf4j
@RestControllerAdvice
public class CustomerControllerAdvice {
/** Manejo de excepciones. */
@ExceptionHandler(RuntimeException.class)
public Mono<ResponseEntity<String>> exceptionHandler(RuntimeException ex) {
log.info("Error : ", ex.getMessage());
return Mono.defer(() -> Mono
.just(ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage())));
}
}
| true
|
9759906723956a0473cd32ee93bf4fe827ee265b
|
Java
|
bingkuaix3/ylbaas
|
/src/com/justep/weixin/mp/ylwxServlet.java
|
UTF-8
| 1,912
| 2.21875
| 2
|
[] |
no_license
|
package com.justep.weixin.mp;
import java.io.File;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpCustomMessage;
public class ylwxServlet extends HttpServlet {
/**
*
*/
WxMpServiceInstance instance = WxMpServiceInstance.getInstance();
public void service(ServletRequest request, ServletResponse response) {
String action = request.getParameter("action");
if ("sendmessage".equals(action)) {
try {
sendmessage(request, response);
} catch (WxErrorException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} else if ("downloadmedia".equals(action)) {
try {
downloadmedia(request, response);
} catch (WxErrorException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
private void downloadmedia(ServletRequest request, ServletResponse response) throws WxErrorException {
JSONObject params = (JSONObject) JSONObject.parse(request.getParameter("params"));
String picture_media_id = params.getString("picture_media_id");
System.out.println(picture_media_id);
instance.downloadimg(picture_media_id);
}
private void sendmessage(ServletRequest request, ServletResponse response) throws WxErrorException {
// TODO 自动生成的方法存根
JSONObject params = (JSONObject) JSONObject.parse(request.getParameter("params"));
String userid = params.getString("userid");
String doctors_analysis = params.getString("doctors_analysis");
String doctors_recommend = params.getString("doctors_recommend");
String price = params.getString("price");
System.out.println(price);
instance.customMessageSend(doctors_recommend,price,doctors_analysis,userid);
}
}
| true
|
89f58012274976e7ff66595fdbd97f47938742fa
|
Java
|
memoryoverflow/shopMall
|
/admin/src/main/java/com/yj/shopmall/util/MyRedis.java
|
UTF-8
| 2,082
| 2.484375
| 2
|
[] |
no_license
|
package com.yj.shopmall.util;
import com.yj.shopmall.Utils.JsonUtils;
import com.yj.shopmall.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
import static com.yj.shopmall.constant.Constant.REDIS_SESSION_Prefix;
import static com.yj.shopmall.constant.Constant.USER_MSG;
@Component
public class MyRedis {
@Autowired
private StringRedisTemplate stringRedisTemplate;//直接@Autowired注入静态会报空指针 改用setter注入
//设置redis上的用户信息
public void setUserToRedis(String userId, User user) {
stringRedisTemplate.opsForValue().set(key(userId), JsonUtils.objectToJson(user), 30, TimeUnit.MINUTES);
System.out.println("设置用户信息到redis");
}
//更新redis的时间
public void updateTimeUserToRedis(String userId) {
stringRedisTemplate.expire(key(userId), 30, TimeUnit.MINUTES);
}
//获取redis上的用户信息
public User getUserFromRedis(String userId) {
String s = stringRedisTemplate.opsForValue().get(key(userId));
return JsonUtils.jsonToPojo(s, User.class);
}
//删除redis上的 用户信息
public void delUserFromRedis(String userId) {
stringRedisTemplate.delete(key(userId));
}
//判断是否存在key
public boolean isHaveUserFromRedis(String userId) {
Boolean aBoolean = stringRedisTemplate.hasKey(key(userId));
return aBoolean;
}
//判断 Session
public boolean isHaveSessionKey(String userId){
return stringRedisTemplate.hasKey(sessionKey(userId));
}
//删除Session
public void delSessionFromRedis(String userId){
stringRedisTemplate.delete(sessionKey(userId));
}
private static String key(String userId){
return (USER_MSG + "[" + userId + "]");
}
private static String sessionKey(String userId){
return (REDIS_SESSION_Prefix +userId);
}
}
| true
|
f973925a2725a2d442918531452d5f3d80e311ad
|
Java
|
Lebron-Liu/Basketballl
|
/vwill/xutil/src/main/java/com/xyy/utils/MediaUtil.java
|
UTF-8
| 13,386
| 2.546875
| 3
|
[] |
no_license
|
package com.xyy.utils;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.view.Surface;
import android.webkit.URLUtil;
import android.widget.SeekBar;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class MediaUtil {
private static final int MSG_PLAY_POS = 1; //播放进度更新
private static final int MSG_DOWNLOAD_POS = 2; //缓冲进度更新
//本地缓存的文件夹
private String localCachePath;
//媒体播放器
private MediaPlayer mediaPlayer;
//当前是否是停止
private boolean isStop = true;
//解码出错的位置
private int errorPos;
//进度显示的视图
private SeekBar seekBar;
private Surface surface;
private int playPos;
public void setPlayPos(int playPos) {
this.playPos = playPos;
}
public MediaUtil(Context context) {
localCachePath = context.getApplicationContext().getExternalCacheDir().toString();
}
/**
* 播放入口
*
* @param url
*/
public void play(String url) {
//初始化播放器
initMediaPlayer();
//是否是网址
if (URLUtil.isNetworkUrl(url)) {
// http://192.168.18.251:8080/musics/abc.mp3 -->abcmp3
//本地是否有缓存
String localCacheMedia = getLocalCachePath(url);
File f = new File(localCacheMedia);
if (f.exists()) {
//播放缓存中的媒体
setDataAndPrepare(localCacheMedia);
} else {
//启动下载
new DownloadThread(url, localCacheMedia, onDownloadListener).start();
}
} else {
//本地的内容直接播放
File f = new File(url);
if (f.exists()) {
setDataAndPrepare(url);
} else {
//非法路径
}
}
}
public boolean isMediaplayNull() {
return mediaPlayer == null;
}
public boolean isPlaying() {
return mediaPlayer != null && mediaPlayer.isPlaying();
}
public void start() {
if (null != mediaPlayer && !mediaPlayer.isPlaying()) {
mediaPlayer.start();
mHandler.sendEmptyMessageDelayed(MSG_PLAY_POS, 200);
}
}
public void pause() {
if (null != mediaPlayer && mediaPlayer.isPlaying()) {
mHandler.removeMessages(MSG_PLAY_POS);
mediaPlayer.pause();
}
}
public void seek(int pos){
if (null != mediaPlayer ) {
mediaPlayer.seekTo(pos);
}
}
public void stop() {
if (null != mediaPlayer) {
mHandler.removeMessages(MSG_PLAY_POS);
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
public int getCurrentPos() {
if (mediaPlayer != null) {
return mediaPlayer.getCurrentPosition();
}
return 0;
}
private OnDownloadListener onDownloadListener = new OnDownloadListener() {
@Override
public void loading(int currentSize, int totalSize, String savePath) {
//计算下载的百分比
int rate = 100 * currentSize / totalSize;
if (rate >= 2 && isStop) {
isStop = false;
setDataAndPrepare(savePath);
}
//更新缓存进度
if (null != onDownloadListener) {
mHandler.obtainMessage(MSG_DOWNLOAD_POS, rate).sendToTarget();
}
}
@Override
public void loadFail(int code, String extras) {
switch (code) {
case 0:
//缓存文件夹创建失败
break;
case 1:
//请求失败
break;
case 2:
//下载失败
File f = new File(extras);
if (f.exists()) {
f.delete();
}
break;
}
}
};
//初始化播放器
private void initMediaPlayer() {
if (null == mediaPlayer) {
//初始化播放器
mediaPlayer = new MediaPlayer();
//设置准备监听
mediaPlayer.setOnPreparedListener(onPreparedListener);
//设置错误监听
mediaPlayer.setOnErrorListener(onErrorListener);
//播放结束监听
mediaPlayer.setOnCompletionListener(onCompletionListener);
mediaPlayer.setOnVideoSizeChangedListener(onVideoSizeChangedListener);
} else {
mediaPlayer.reset();
}
//处于idle状态
//如果检测到有显示视频画面Surface,则设置显示载体
if (null != surface) {
mediaPlayer.setScreenOnWhilePlaying(true);
mediaPlayer.setSurface(surface);
}
}
//解码
private void setDataAndPrepare(String path) {
//设置播放的媒体源
try {
mediaPlayer.setDataSource(path);
//处于初始化完毕状态(initialized)
//准备
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
isStop = true;
mediaPlayer.reset();
}
}
//媒体播放的准备结果监听
private MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
//检测是否有错误位置
if (errorPos > 0) {
mp.seekTo(errorPos);
} else if (playPos > 0) {
mp.seekTo(playPos);
playPos = 0;
}
//准备完成---控制媒体的播放(播放、设置播放位置、获取媒体的总时间、暂停、停止)
mp.start();
if (null != onMediaListener) {
onMediaListener.onDuration(mp.getDuration());
}
//开始获取当前时间
mHandler.sendEmptyMessageDelayed(MSG_PLAY_POS, 200);
}
};
//解码错误监听
private MediaPlayer.OnErrorListener onErrorListener = new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
//记录出错的位置
errorPos = mp.getCurrentPosition();
//停止解码
mp.stop();
mp.reset();
isStop = true;
return true;
}
};
//播放结束监听
private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
}
};
class DownloadThread extends Thread {
private String url;
private String savePath; // /mnt/sdcard/Android/data/com.xykj.meida/caches/abcmp3
private OnDownloadListener onDownloadListener;
DownloadThread(String url, String savePath, OnDownloadListener onDownloadListener) {
this.url = url;
this.savePath = savePath;
this.onDownloadListener = onDownloadListener;
}
@Override
public void run() {
//检测缓存文件夹是否存在,不存在创建
File saveFile = new File(savePath);
if (checkFolderExists(saveFile.getParentFile())) {
//下载文件
try {
URL link = new URL(url);
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
if (conn.getResponseCode() == 200) {
// 获取服务器端返回内容的输入流
InputStream in = conn.getInputStream();
RandomAccessFile out = new RandomAccessFile(saveFile, "rw");
int totalLen = conn.getContentLength();
out.setLength(totalLen);
byte[] buf = new byte[2048];
int num;
int count = 0;
while ((num = in.read(buf)) != -1) {
out.write(buf, 0, num);
count += num;
//检测当前是否有解码器在解码,没有则开始解码
if (null != onDownloadListener) {
onDownloadListener.loading(count, totalLen, savePath);
}
}
out.close();
in.close();
} else {
if (null != onDownloadListener) {
onDownloadListener.loadFail(1, "请求失败");
}
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
if (null != onDownloadListener) {
onDownloadListener.loadFail(2, savePath);
}
}
} else {
//下载失败
if (null != onDownloadListener) {
onDownloadListener.loadFail(0, "文件夹创建失败");
}
}
}
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_PLAY_POS:
//计算播放进度的百分比 5 20 --> 25%
if (mediaPlayer != null) {
int currentPos = mediaPlayer.getCurrentPosition();
if (seekBar != null) {
int rate = 100 * currentPos / mediaPlayer.getDuration();
seekBar.setProgress(rate);
}
if (null != onMediaListener) {
onMediaListener.onCurrentPosition(currentPos);
}
sendEmptyMessageDelayed(MSG_PLAY_POS, 200);
}
break;
case MSG_DOWNLOAD_POS:
int pos = (Integer) msg.obj;
if (seekBar != null) {
seekBar.setSecondaryProgress(pos);
}
break;
}
}
};
interface OnDownloadListener {
void loading(int currentSize, int totalSize, String savePath);
void loadFail(int code, String extras);
}
public interface OnMediaListener {
//返回总时间
void onDuration(int duration);
//返回当前时间
void onCurrentPosition(int position);
}
private OnMediaListener onMediaListener;
public void setOnMediaListener(OnMediaListener onMediaListener) {
this.onMediaListener = onMediaListener;
}
private boolean checkFolderExists(File file) {
if (!file.exists()) {
return file.mkdirs();
}
return true;
}
private String getLocalCachePath(String path) {
//该地址是一个网址
int index = path.lastIndexOf("/");
if (index < 0) {
index = 0;
}
String name = path.substring(index).replaceAll("[^\\w]", "");
return localCachePath + File.separator + name;
}
public void setSeekBar(SeekBar seekBar) {
this.seekBar = seekBar;
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
if (null != mediaPlayer && mediaPlayer.isPlaying()) {
mHandler.removeMessages(MSG_PLAY_POS);
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (null != mediaPlayer) {
int pos = seekBar.getProgress();
//计算要设置播放的位置
int currentPos = mediaPlayer.getDuration() * pos / 100;
mediaPlayer.seekTo(currentPos);
if (mediaPlayer.isPlaying()) {
mHandler.sendEmptyMessageDelayed(MSG_PLAY_POS, 200);
}
}
}
});
}
public void setSurface(Surface surface) {
this.surface = surface;
}
private MediaPlayer.OnVideoSizeChangedListener onVideoSizeChangedListener;
public void setOnVideoSizeChangedListener(MediaPlayer.OnVideoSizeChangedListener onVideoSizeChangedListener) {
this.onVideoSizeChangedListener = onVideoSizeChangedListener;
}
}
| true
|
ccb2fa9ebbd84d6fb2f1f7ba40d1f52330e293d3
|
Java
|
saanaraw/expensetracker-backend
|
/src/main/java/com/example/saana/expense/model/Category.java
|
UTF-8
| 325
| 2.015625
| 2
|
[] |
no_license
|
package com.example.saana.expense.model;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import javax.persistence.*;
@Entity
@NoArgsConstructor
@Data
@Table(name="category")
public class Category {
@Id
private Long id;
@NonNull
//Travel, Grocery..
private String name;
}
| true
|
66fcb32fe3a98bd2189944e5a78dfbf11705e156
|
Java
|
AnmolAgarwal141/Android-studio-Projects
|
/Naaniz-master/app/src/main/java/com/example/naaniz/listofrecipes.java
|
UTF-8
| 6,596
| 2.09375
| 2
|
[] |
no_license
|
package com.example.naaniz;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.naaniz.adapters.RecipeAdapter;
import com.example.naaniz.views.ListOfRecipes;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class listofrecipes extends Fragment {
private ArrayList<ListOfRecipes> a= new ArrayList<>();
private String food;
public listofrecipes() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_listofrecipes, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle b = getArguments();
String phone = b.getString("phone");
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference pr = database.getReference("users").child(phone).getRef();
pr.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot p:dataSnapshot.getChildren())
{
if(p.getKey().equals("food_choice"))
{
food =p.getValue().toString();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
DatabaseReference parentRef = database.getReference("user_recipes");
parentRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot p : dataSnapshot.getChildren())
{
for(DataSnapshot o : p.getChildren())
{
String po=null,qo=null,status=null,phone=null,choice=null,ready=null;
for(DataSnapshot q : o.getChildren())
{
if(q.getKey().equals("title"))
{
po= q.getValue().toString();
}
if(q.getKey().equals("name"))
{
qo=q.getValue().toString();
}
if(q.getKey().equals("status"))
{
status=q.getValue().toString();
}
if(q.getKey().equals("phone"))
{
phone=q.getValue().toString();
}
if(q.getKey().equals("choice"))
{
choice=q.getValue().toString();
}
if(q.getKey().equals("readyInMinutes"))
{
ready=q.getValue().toString();
}
}
if(po!=null && status.equals("verified") && choice.equals(food))
{
Log.i("6546546546", food);
Log.i("6added24434",choice);
a.add(new ListOfRecipes(po,qo,phone,ready));
}
}
}
data(view);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public void data(View view)
{
RecyclerView recyclerView = view.findViewById(R.id.list_recipes_all_user);
RecipeAdapter adapter = new RecipeAdapter(a);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(),2));
recyclerView.setAdapter(adapter);
adapter.setOnclickListen(new RecipeAdapter.OnItemClickListen() {
@Override
public void onClickDisplay(int position) {
ListOfRecipes listOfRecipes = a.get(position);
String phone =listOfRecipes.getPhone();
String title =listOfRecipes.getRecipeTitle();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference parentRef = database.getReference("user_recipes");
DatabaseReference ref1 = parentRef.child(phone).getRef();
DatabaseReference ref = ref1.child(title).getRef();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot d :dataSnapshot.getChildren())
{
if(d.getKey().equals("views"))
{
int p = Integer.parseInt(d.getValue().toString());
p++;
ref.child("views").setValue(p);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Intent intent = new Intent(getActivity(), ShowRecipe.class);
intent.putExtra("dish",title);
intent.putExtra("parentRef","user_recipes");
intent.putExtra("phone",phone);
startActivity(intent);
}
});
}
}
| true
|
65ba969e2b4dd5aabddd17cdcaf8e31a6fc6f658
|
Java
|
zhangzhende/spring-boot-examples
|
/service-seetaface/src/main/java/com/seetaface2/model/SeetaImageData.java
|
UTF-8
| 1,051
| 2.765625
| 3
|
[] |
no_license
|
package com.seetaface2.model;
public class SeetaImageData {
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getChannels() {
return channels;
}
public void setChannels(int channels) {
this.channels = channels;
}
private SeetaImageData() {
}
public SeetaImageData(int width, int height, int channels) {
this.data = new byte[width * height * channels];
this.width = width;
this.height = height;
this.channels = channels;
}
public SeetaImageData(int width, int height) {
this(width, height, 3);
}
public byte[] data;
public int width;
public int height;
public int channels;
}
| true
|
13161a2890981c63059caea2f5adb43a8590839d
|
Java
|
AlperenYilmazyildiz/TraJour
|
/src/com/trajour/journey/Postable.java
|
UTF-8
| 172
| 1.898438
| 2
|
[] |
no_license
|
package com.trajour.journey;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public interface Postable {
Post post(String text, Image image);
}
| true
|
cf38eb83ee542dee2a2f7720891718f4d5b57a6b
|
Java
|
jmllubes/M6
|
/objectfile/src/objectfile/client.java
|
UTF-8
| 601
| 2.59375
| 3
|
[] |
no_license
|
package objectfile;
import java.io.Serializable;
public class client implements Serializable{
private String nombre;
private transient String passWord;
public client(String nombre, String passWord) {
this.nombre=nombre;
this.passWord= passWord;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
| true
|
5b47747cf7f0ff0e08424549c0b77c0ede991b72
|
Java
|
jmpereztorres/spotifire-back
|
/src/main/java/com/spotifire/core/service/IReportService.java
|
UTF-8
| 662
| 1.765625
| 2
|
[] |
no_license
|
package com.spotifire.core.service;
import java.io.IOException;
import com.spotifire.persistence.pojo.Report;
import com.spotifire.web.rest.dto.FireDTO;
import com.spotifire.web.rest.dto.NotificationDTO;
import com.spotifire.web.rest.dto.ReportRequestDTO;
public interface IReportService {
Report processReport(Report report);
Report saveReport(Report report);
void parseReportAndSave(ReportRequestDTO reportRequest) throws IOException;
FireDTO findFiresByLocation(ReportRequestDTO reportRequestDTO);
FireDTO findTypedFiresByLocation(ReportRequestDTO reportRequestDTO);
NotificationDTO createPushNotification(ReportRequestDTO reportRequestDTO);
}
| true
|
057d73bbfec1d75522f00ba1050eba3e7e3a9e85
|
Java
|
syabbahrul/FirstProjek
|
/app/src/main/java/com/example/firstprojek/MainActivity.java
|
UTF-8
| 2,083
| 2.09375
| 2
|
[] |
no_license
|
package com.example.firstprojek;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public int jumlah = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txthw = findViewById(R.id.tv_hw);
final TextView txtalamat = findViewById(R.id.tv_alamat);
final TextView txtuy = findViewById(R.id.tv_uy);
Button btnMove = findViewById(R.id.btn_pindah);
txthw.setText("Selamat Datang");
txtalamat.setText("Ujang");
txtuy.setText("Bandung");
txthw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Selamat Datang",
Toast.LENGTH_SHORT).show();
}
});
txtalamat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "anda menekan tulisan alamat",
Toast.LENGTH_SHORT).show();
}
});
txthw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
jumlah++;
Toast.makeText(MainActivity.this, "anda menekan sebanyak"+jumlah+"kali",
Toast.LENGTH_SHORT).show();
}
});
btnMove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Activity2.class);
intent.putExtra("nama",)
startActivity(intent);
// finish();
onDestroy();
}
});
}
}
| true
|
2af410fce502e93b228a17a31c58de3ff5b65456
|
Java
|
xshxsh/design_pattern
|
/src/main/java/com/example/designpattern/create/prototype/Application.java
|
UTF-8
| 575
| 2.953125
| 3
|
[] |
no_license
|
package com.example.designpattern.create.prototype;
import com.example.designpattern.create.prototype.concreate.Circle;
import com.example.designpattern.create.prototype.interfac.Shape;
import com.example.designpattern.create.prototype.manager.ProtoTypeManager;
public class Application {
public static void main(String[] args) {
ProtoTypeManager pm = new ProtoTypeManager();
Shape obj1 = (Circle) pm.getShape("Circle");
obj1.showSomething();
Shape obj2 = (Shape) pm.getShape("Circle");
System.out.println(obj1 == obj2);
}
}
| true
|
7d487556eb15be281e9eb07eff182a37edeed09f
|
Java
|
sngshivang/IITRPR_ACSE
|
/src/cosinesim/ToCheck.java
|
UTF-8
| 12,190
| 2.5625
| 3
|
[] |
no_license
|
/* The input code must be compiled and ensured that it is syntactically correct before this program
* can be used. DO NOT USE IT ON INCORRECT SYNTAX as this will lead to unpredictable and possibly
* erroneous output. This program does not have any tolerance to errors.
*/
package cosinesim;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;
public class ToCheck {
static Vector<String> txtdat;
String hash = "#c", phsh = "#p",univ;
String mhsh = "#m";
String vrhsh = "#v";
int cls=0;
int mcnt=0,vrcnt=0,pcnt=0;
static int nfree;
public static void main(String args[])
{
int len;txtdat = new Vector<String>();
nfree = 0;
String prog="";
try {
FileInputStream fl = new FileInputStream("/home/shivang/Desktop/example.java");
File out = new File("/home/shivang/Desktop/output.java");
BufferedInputStream bfs = new BufferedInputStream(fl);
byte bt[] = new byte[8192];
while ((len = bfs.read(bt))!=-1)
{
prog+=new String(bt);
}
bfs.close();
ToCheck cm = new ToCheck();
prog = cm.operations(prog);
System.out.print(prog);
}
catch(Exception e)
{
e.printStackTrace();
}
}
private String operations(String prog)
{
prog = this.textrepo(prog);
prog = this.rmcmt(prog);
prog = this.removenlines(prog);
prog = this.rmextrasp(prog);
prog = this.trimmer(prog);
prog = this.classnormal(prog);
prog = this.metnormal(prog);
prog = this.equalsuniv(prog);
//prog = this.renprimvar(prog);
return prog;
}
private String removenlines(String inp)
{
inp = inp.replaceAll("\n", "");
return inp;
}
private String rmcmt(String inp)
{
int ind,eind;
do {
ind = inp.indexOf("//");
if (ind!=-1) {
eind = inp.indexOf("\n",ind+2);
inp = inp.replace(inp.substring(ind, eind),"");
}
}while (ind!=-1);
do {
ind = inp.indexOf("/*");
if (ind!=-1)
{
eind = inp.indexOf("*/",ind+2);
inp = inp.replace(inp.substring(ind, eind+2), "");
}
}while (ind!=-1);
return inp;
}
private String textrepo(String inp)
{
int ind, eind, esc;
String deft = "$TEX$T",phr;
char apos = 34;
do {
ind = inp.indexOf(apos);
if (ind!=-1)
{
eind = inp.indexOf(apos,ind+1);
deft+=String.valueOf(nfree);
phr = inp.substring(ind,eind+1);
txtdat.add(phr);
nfree++;
inp = inp.replace(phr, deft);
//esc = inp.indexOf("\"",ind);
deft = "$TEX$T";
}
}while(ind!=-1);
return inp;
}
private int startid(String inp, int ind)
{
int len = inp.length();
while (ind<len&&inp.charAt(ind)==32)
ind++;
return ind;
}
private int endid(String inp, int ind)
{
int len = inp.length(),asc;
while (ind<len)
{
asc = inp.charAt(ind);
if (asc<len&&((asc>64&&asc<91)||(asc>96&&asc<123)||(asc>47&&asc<58)||asc==95||asc==36))
{
ind++;
}
else
break;
}
return ind;
}
private String classmod(String inp)
{
int len,i,ind, brcnt=0, end;
String org = inp;
while (true) {
len = org.length();
ind = org.indexOf("class");
if (ind!=-1) {
int strt = this.startid(org, ind+5);
end = this.endid(org, strt);
//System.out.println(org.charAt(strt));
String idfr = org.substring(strt, end);
//System.out.println(idfr);
String nnme = this.hash + String.valueOf(cls);
cls++;
for (i=0;i<end;i++)
{
if (org.charAt(i)=='{')
brcnt++;
else if (org.charAt(i)=='}')
brcnt--;
}
inp = AdvSubstring.replace(inp,idfr,nnme);
org = org.substring(end, len-end);
}
else
break;
}
return inp;
}
protected String classnormal(String inp)
{
String org=inp,part,out,keywrd;
boolean trip =false;
int len, ind,i,j;
do {
trip = false;
ind = org.indexOf('{');
len = org.length();j=ind;
if (ind!=-1)
{
//System.out.println(org.substring(0,ind));
ind--;
if (ind>-1&&org.charAt(ind)==32)
ind--;
part = "";keywrd="";
while (ind>-1&&Character.isJavaIdentifierPart(org.charAt(ind)))
{
part = Character.toString(org.charAt(ind))+part;
ind--;
if (org.charAt(ind)=='#')
trip = true;
}
ind--;
while (ind>-1&&this.isValidKeywordChar(org.charAt(ind)))
{
keywrd = org.charAt(ind)+keywrd;
ind--;
}
if (!trip&&(keywrd.equals("class")||keywrd.equals("interface")||keywrd.equals("enum")))
{
out = this.hash+String.valueOf(cls);
cls++;
inp = AdvSubstring.replace(inp, part, out);
}
org = org.substring(j+1, len-j-1);
}
}while (ind!=-1);
return inp;
}
protected String metnormal(String inp)
{
String org=inp,part,out;univ=inp;
boolean trip =false;
int len, ind,i,j;
do {
trip = false;
ind = org.indexOf('(');
len = org.length();j=ind;
if (ind!=-1)
{
ind--;
if (ind>-1&&org.charAt(ind)==32)
ind--;
part = "";
while (ind>-1&&Character.isJavaIdentifierPart(org.charAt(ind)))
{
part = Character.toString(org.charAt(ind))+part;
ind--;
if (org.charAt(ind)=='#')
trip = true;
}
if (org.charAt(ind)!=32)
trip=true;
if (!trip)
{
this.parnormal(org, j);
out = this.mhsh+String.valueOf(mcnt);
mcnt++;
univ = AdvSubstring.replace(univ, part, out);
}
org = org.substring(j+1, len-j-1);
}
}while (ind!=-1);
return univ;
}
protected void parnormal(String inp, int l)
{
int sze,r=0,i;
for (i=l+1;i<inp.length();i++)
if (inp.charAt(i)==')')
{
r = i;
break;
}
String itok,out, org = inp.substring(l+1,r);
StringTokenizer st = new StringTokenizer(org),st2;
Vector <String> vt = new Vector<>(),vt2 = new Vector<>();
while (st.hasMoreTokens())
vt.add(st.nextToken(","));
Iterator<String> it = vt.iterator();
while (it.hasNext())
{
itok = (String)it.next();
st2 = new StringTokenizer(itok);
while (st2.hasMoreTokens())
{
vt2.add(st2.nextToken());
}
sze = vt2.size();
//System.out.println(sze);
if (sze==2)
{
out = this.phsh+String.valueOf(pcnt);
pcnt++;
univ = AdvSubstring.replace(univ, vt2.get(1), out);
}
vt2.clear();
}
}
private String mtname(String inp, int pos)
{
int i;
boolean idfn2=true, trip = false;
int spval = 0;
String nme = "", typ="";
String types[] = {"void", "boolean", "int", "String", "float", "double", "Void", "Boolean", "Integer", "Long"
, "BigInteger", "short", "char", "boolean", "long"};
while (pos>-1&&this.stoppoints(inp.charAt(pos))!=true)
{
if (inp.charAt(pos)==32) {
if (spval == 1)
idfn2 = false;
else if (spval ==2)
break;
}
else if(idfn2) {
spval = 1;
if (this.isValidChar(inp.charAt(pos)))
nme = inp.charAt(pos)+nme;
}
else {
spval = 2;
typ = inp.charAt(pos)+typ;
}
pos--;
}
for (i=0;i<11;i++)
if (typ.equals(types[i]))
{
trip=true;
break;
}
if (trip)
return nme;
else
return "#INV";
}
private String methmod(String inp)
{
int len,i,ind, brcnt=0; String nnme,idf;
String org = inp;
while (true) {
len = org.length();
ind = org.indexOf('(');
if (ind!=-1) {
idf = this.mtname(org, --ind);
if (!idf.equals("#INV")) {
nnme = this.mhsh + String.valueOf(mcnt);
inp = AdvSubstring.replace(inp,idf, nnme);
mcnt++;
}
/*for (i=0;i<end;i++)
{
if (org.charAt(i)=='{')
brcnt++;
else if (org.charAt(i)=='}')
brcnt--;
}*/
org = org.substring(ind+2, len-(ind+2));
}
else
break;
}
return inp;
}
private String trimmer(String inp)
{
String kyd[]= {"package", "import"};
int len = inp.length(), ind, i, j;
String subs;
for (i=0;i<2;i++)
{
do {
ind = inp.indexOf(kyd[i]);
if (ind!=-1)
{
for (j=ind;j<len;j++)
if (inp.charAt(j)==';')
break;
subs = inp.substring(ind, j+1);
inp = inp.replace(subs, "");
}
}while (ind!=-1);
}
return inp;
}
private String rmextrasp(String inp)
{
int len = inp.length(),i;
if (inp.charAt(0)==9)
inp = this.rmchar(inp, 0);
for (i=1;i<len;)
{
if (inp.charAt(i)==32&&inp.charAt(i-1)==32)
{
inp = this.rmchar(inp, i);
len--;
}
else if (inp.charAt(i)==9)
{
inp = this.rmchar(inp, i);
len--;
}
else
i++;
}
return inp;
}
private String rmchar(String inp, int pos)
{
int len = inp.length();
String out = inp.substring(0, pos) + inp.substring(pos+1, len);
return out;
}
private String renprimvar(String inp)
{
String org=inp;
int len, ind,i,j;
String dattyp[]= {"int", "byte", "long", "double", "float", "short", "char", "boolean", "String"};
for (i=0;i<9;i++)
{
do {
ind = org.indexOf(dattyp[i]);
len = org.length();
if (ind!=-1)
{
ind+=dattyp[i].length();
if (org.charAt(ind+1)!='#') {
for (j=ind;j<len;j++)
if (org.charAt(j)==';')
break;
//System.out.println(org.substring(ind, j+1));
inp = this.renprimvarENG(inp, org.substring(ind,j+1));
}
else
j = ind;
org = org.substring(j+1, len-j-1);
}
}while (ind!=-1);
}
return inp;
}
private String renprimvarENG(String inp, String sstr)
{
boolean trip =false;
if (sstr.charAt(0)==32)
trip=true;
sstr = sstr.replace(" ", "");
String subs, out;
int i=0,coma,end = sstr.length();
if (sstr.charAt(0)=='[')
{i+=2;
trip = true;
}
coma = i;
if (trip) {
//System.out.println(sstr);
for (;i<end;i++)
{
if (sstr.charAt(i)=='['||sstr.charAt(i)==']')
{
subs = sstr.substring(coma, i);
out = this.vrhsh+String.valueOf(vrcnt);
vrcnt++;
//System.out.println(subs+" "+out);
inp = inp.replace(subs, out);
inp = AdvSubstring.replace(inp, subs, out);
coma=i+2;
i++;
}
else if (sstr.charAt(i)==',')
{
subs = sstr.substring(coma, i);
out = this.vrhsh+String.valueOf(vrcnt);
vrcnt++;
inp = AdvSubstring.replace(inp, subs, out);
coma=i+1;
}
else if (sstr.charAt(i)=='=')
{
if (coma<i) {
subs = sstr.substring(coma, i);
out = this.vrhsh+String.valueOf(vrcnt);
vrcnt++;
inp = AdvSubstring.replace(inp, subs, out);
}
if (sstr.charAt(i+1)=='{')
while (sstr.charAt(i)!='}')
i++;
while (i<end)
{
if (sstr.charAt(i)==','||sstr.charAt(i)==';')
{
coma = i+1;
break;
}
i++;
}
}
if (sstr.charAt(i)==';')
{
if (coma<i) {
subs = sstr.substring(coma, i);
out = this.vrhsh+String.valueOf(vrcnt);
vrcnt++;
inp = AdvSubstring.replace(inp, subs, out);
}
break;
}
}
}
return inp;
}
private String equalsuniv(String inp)
{
String org=inp,part,out;
boolean trip =false;
int len, ind,i,j;
do {
ind = org.indexOf('=');
len = org.length();j=ind;
if (ind!=-1)
{
ind--;
if (org.charAt(ind)==32)
ind--;
if (org.charAt(ind)==']')
{
if (org.charAt(ind-1)==32)
ind-=3;
else
ind-=2;
}
if (org.charAt(ind)==32)
ind--;
part = "";
while (Character.isJavaIdentifierPart(org.charAt(ind)))
{
part = Character.toString(org.charAt(ind))+part;
ind--;
if (org.charAt(ind)=='#')
trip = true;
}
if (!trip)
{
out = this.vrhsh+String.valueOf(vrcnt);
vrcnt++;
inp = AdvSubstring.replace(inp, part, out);
}
org = org.substring(j+1, len-j-1);
}
}while (ind!=-1);
return inp;
}
protected boolean isValidKeywordChar(char inp)
{
boolean trip = false;
if ((inp>64&&inp<91)||(inp>96&&inp<123))
trip=true;
return trip;
}
private boolean isValidChar(char inp)
{
boolean trip = false;
if ((inp>64&&inp<91)||(inp>96&&inp<123)||(inp>47&&inp<58)||inp=='$'||inp=='_')
trip=true;
return trip;
}
private boolean stoppoints(char inp)
{
boolean trip = false;
if (inp=='{'||inp=='}'||inp=='('||inp==')'||inp==';')
trip = true;
return trip;
}
}
| true
|
b29aefca6bc44d253fc07ccf55c197560686c6d4
|
Java
|
parthitechnotion/GoogleAndroidTV
|
/src/com/android/tv/dvr/recorder/DvrRecordingService.java
|
UTF-8
| 5,915
| 1.65625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.tv.dvr.recorder;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.HandlerThread;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.android.tv.ApplicationSingletons;
import com.android.tv.InputSessionManager;
import com.android.tv.InputSessionManager.OnRecordingSessionChangeListener;
import com.android.tv.R;
import com.android.tv.TvApplication;
import com.android.tv.common.SoftPreconditions;
import com.android.tv.common.feature.CommonFeatures;
import com.android.tv.dvr.WritableDvrDataManager;
import com.android.tv.util.Clock;
import com.android.tv.util.RecurringRunner;
/**
* DVR Scheduler service.
*
* <p> This service is responsible for:
* <ul>
* <li>Send record commands to TV inputs</li>
* <li>Wake up at proper timing for recording</li>
* <li>Deconflict schedule, handling overlapping times etc.</li>
* <li>
*
* </ul>
*
* <p>The service does not stop it self.
*/
public class DvrRecordingService extends Service {
private static final String TAG = "DvrRecordingService";
private static final boolean DEBUG = false;
public static final String HANDLER_THREAD_NAME = "DvrRecordingService-handler";
private static final int ONGOING_NOTIFICATION_ID = 1;
public static void startService(Context context) {
Intent dvrSchedulerIntent = new Intent(context, DvrRecordingService.class);
context.startService(dvrSchedulerIntent);
}
private final Clock mClock = Clock.SYSTEM;
private RecurringRunner mReaperRunner;
private Scheduler mScheduler;
private HandlerThread mHandlerThread;
private InputSessionManager mSessionManager;
private boolean mForeground;
private final OnRecordingSessionChangeListener mOnRecordingSessionChangeListener =
new OnRecordingSessionChangeListener() {
@Override
public void onRecordingSessionChange(final boolean create, final int count) {
if (create && !mForeground) {
Notification notification =
new Notification.Builder(getApplicationContext())
.setContentTitle(TAG)
.setSmallIcon(R.drawable.ic_dvr)
.build();
startForeground(ONGOING_NOTIFICATION_ID, notification);
mForeground = true;
} else if (!create && mForeground && count == 0) {
stopForeground(STOP_FOREGROUND_REMOVE);
mForeground = false;
}
}
};
@Override
public void onCreate() {
TvApplication.setCurrentRunningProcess(this, true);
if (DEBUG) Log.d(TAG, "onCreate");
super.onCreate();
SoftPreconditions.checkFeatureEnabled(this, CommonFeatures.DVR, TAG);
ApplicationSingletons singletons = TvApplication.getSingletons(this);
WritableDvrDataManager dataManager =
(WritableDvrDataManager) singletons.getDvrDataManager();
mSessionManager = singletons.getInputSessionManager();
mSessionManager.addOnRecordingSessionChangeListener(mOnRecordingSessionChangeListener);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// mScheduler may have been set for testing.
if (mScheduler == null) {
mHandlerThread = new HandlerThread(HANDLER_THREAD_NAME);
mHandlerThread.start();
mScheduler = new Scheduler(mHandlerThread.getLooper(), singletons.getDvrManager(),
singletons.getInputSessionManager(), dataManager,
singletons.getChannelDataManager(), singletons.getTvInputManagerHelper(), this,
mClock, alarmManager);
mScheduler.start();
}
mReaperRunner = new RecurringRunner(this, java.util.concurrent.TimeUnit.DAYS.toMillis(1),
new ScheduledProgramReaper(dataManager, mClock), null);
mReaperRunner.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (DEBUG) Log.d(TAG, "onStartCommand (" + intent + "," + flags + "," + startId + ")");
mScheduler.update();
return START_STICKY;
}
@Override
public void onDestroy() {
if (DEBUG) Log.d(TAG, "onDestroy");
mReaperRunner.stop();
mScheduler.stop();
mScheduler = null;
if (mHandlerThread != null) {
mHandlerThread.quitSafely();
mHandlerThread = null;
}
mSessionManager.removeRecordingSessionChangeListener(mOnRecordingSessionChangeListener);
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@VisibleForTesting
void setScheduler(Scheduler scheduler) {
Log.i(TAG, "Setting scheduler for tests to " + scheduler);
mScheduler = scheduler;
}
}
| true
|
4766b40740e9aa0db87375d2271bdca3c168e6b4
|
Java
|
fermadeiral/StyleErrors
|
/eclipse-vorto/2458092eb94690845d6e4c019216329cfc7d280a/292/SimpleSearchService.java
|
UTF-8
| 2,728
| 2.078125
| 2
|
[] |
no_license
|
/**
* Copyright (c) 2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional information regarding copyright
* ownership.
*
* This program and the accompanying materials are made available under the terms of the Eclipse
* Public License 2.0 which is available at https://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.vorto.repository.search.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.eclipse.vorto.model.ModelId;
import org.eclipse.vorto.repository.core.IModelRepository;
import org.eclipse.vorto.repository.core.IModelRepositoryFactory;
import org.eclipse.vorto.repository.core.ModelInfo;
import org.eclipse.vorto.repository.search.IIndexingService;
import org.eclipse.vorto.repository.search.ISearchService;
import org.eclipse.vorto.repository.search.IndexingResult;
import org.eclipse.vorto.repository.tenant.ITenantService;
/**
* Simple search which merely delegates the search to the model repository
*
*/
public class SimpleSearchService implements ISearchService, IIndexingService {
private ITenantService tenantService;
private IModelRepositoryFactory repositoryFactory;
public SimpleSearchService(ITenantService tenantService,
IModelRepositoryFactory repositoryFactory) {
this.tenantService = tenantService;
this.repositoryFactory = repositoryFactory;
}
@Override
public List<ModelInfo> search(Optional<Collection<String>> tenantIds, String expression) {
List<ModelInfo> result = new ArrayList<>();
if (tenantIds.isPresent() && !tenantIds.get().isEmpty()) {
tenantIds.get().stream().forEach(tenantId -> {
IModelRepository repository = this.repositoryFactory.getRepository(tenantId);
result.addAll(repository.search(expression));
});
} else {
tenantService.getTenants().forEach(tenant -> {
IModelRepository repository = this.repositoryFactory.getRepository(tenant.getTenantId());
result.addAll(repository.search(expression));
});
}
return result;
}
@Override
public List<ModelInfo> search(String expression) {
return search(Optional.empty(), expression);
}
@Override
public IndexingResult reindexAllModels() {
return new IndexingResult();
}
@Override
public void indexModel(ModelInfo modelInfo, String tenantId) {
// NOOP
}
@Override
public void updateIndex(ModelInfo modelInfo) {
// NOOP
}
@Override
public void deleteIndex(ModelId modelId) {
// NOOP
}
@Override
public void deleteIndexForTenant(String tenantId) {
// NOOP
}
}
| true
|
cb04adca45a4d6da5f0c49b89cca1523a96cccae
|
Java
|
jerrysbest/git
|
/sboerp/src/erp/ws/aop/permission/PermissionCheckAdvice.java
|
GB18030
| 1,432
| 2.421875
| 2
|
[] |
no_license
|
package erp.ws.aop.permission;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
import erp.ws.sbo.client.swing.app.appMain;
public class PermissionCheckAdvice implements MethodBeforeAdvice {
public void before(Method m, Object[] args, Object target) throws Throwable {
String privilege=(target.getClass().getName()+"." +m.getName()).toUpperCase();
System.out.println("ӡʼ=======================");
//User user=(User) args[0];
System.out.println(appMain.user);
System.out.println("ӡ=======================");
System.out.println("by " + this.getClass().getName()+"::"
+ "Target:"+target.getClass().getName()+"." +"Method:"+m.getName() +")");
if(!(privilege.equals("ERP.WS.SBO.CLIENT.SWING.DAO.IMPL.SNINDOC.ADD")||privilege.equals("ERP.WS.SBO.CLIENT.SWING.DAO.IMPL.OIGNDOC.ADD")))
{
System.out.println("AOPȨ");
}
else if (!appMain.user.isPermission(privilege)&&(privilege.equals("ERP.WS.SBO.CLIENT.SWING.DAO.IMPL.SNINDOC.ADD")||privilege.equals("ERP.WS.SBO.CLIENT.SWING.DAO.IMPL.OIGNDOC.ADD"))) {
throw new PermissionDeniedException(appMain.user, privilege);
}
else{
System.out.println("Ȩ");
}
}
}
| true
|
81c56900872837fa462eb66828c74acb2f1570c2
|
Java
|
nlp-lap/Version_Compatible_HL7_Parser
|
/hl7/pseudo/group/PATHWAY_PGL_PC7.java
|
UTF-8
| 334
| 1.726563
| 2
|
[] |
no_license
|
package hl7.pseudo.group;
import hl7.bean.Structure;
public class PATHWAY_PGL_PC7 extends hl7.model.V2_3.group.PATHWAY_PGL_PC7{
public PATHWAY_PGL_PC7(){
super();
}
public static PATHWAY_PGL_PC7 CLASS;
static{
CLASS = new PATHWAY_PGL_PC7();
}
public Structure[][] getComponents(){
return super.getComponents();
}
}
| true
|
314183f4c61659f3514fce89ba379717f9ba4bc7
|
Java
|
tlee2502/Flooring-Orders
|
/src/main/java/com/tom/flooringorder/dao/StateTaxDaoFileImpl.java
|
UTF-8
| 1,736
| 2.828125
| 3
|
[] |
no_license
|
package com.tom.flooringorder.dao;
import com.tom.flooringorder.dto.StateTax;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class StateTaxDaoFileImpl implements StateTaxDao {
private final String DELIMITER = ",";
private final String STATE_FILE;
Map<String, StateTax> stateTaxMap;
public StateTaxDaoFileImpl() {
this.STATE_FILE = "Data/Taxes.txt";
}
public StateTaxDaoFileImpl(String STATE_FILE) {
this.STATE_FILE = STATE_FILE;
}
@Override
public Map<String, StateTax> getStateTaxes() throws DataPersistenceException {
stateTaxMap = new TreeMap<>();
readStates();
return stateTaxMap;
}
private void readStates() throws DataPersistenceException {
Scanner sc;
try {
sc = new Scanner(new BufferedReader(new FileReader(STATE_FILE)));
String currentLine;
StateTax currentState;
sc.nextLine();
while (sc.hasNextLine()) {
currentLine = sc.nextLine();
currentState = unmarshallData(currentLine);
stateTaxMap.put(currentState.getStateInitial(), currentState);
}
sc.close();
} catch (FileNotFoundException e) {
throw new DataPersistenceException("Could not load state tax data into memory", e);
}
}
private StateTax unmarshallData(String stateTaxAsString) {
String[] parts = stateTaxAsString.split(DELIMITER);
return new StateTax(parts[0], parts[1], new BigDecimal(parts[2]));
}
}
| true
|
4fbbb6ccd8b572206295e1f1340d2ced728f9c19
|
Java
|
peligroso/streamline
|
/org.juxtapose.streamline/src/org/juxtapose/streamline/producer/executor/IExecutable.java
|
UTF-8
| 126
| 1.679688
| 2
|
[] |
no_license
|
package org.juxtapose.streamline.producer.executor;
public interface IExecutable extends Runnable{
public int getHash();
}
| true
|
91e36503c4015dc689f7a91d35125fca47727ad2
|
Java
|
browleless/Tellybuddy
|
/tellybuddy/tellybuddy-war/src/java/jsf/managedbean/TransactionManagementManagedBean.java
|
UTF-8
| 2,981
| 2.03125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jsf.managedbean;
import ejb.session.stateless.TransactionSessionBeanLocal;
import entity.Transaction;
import entity.TransactionLineItem;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import util.exception.TransactionAlreadyVoidedRefundedException;
import util.exception.TransactionNotFoundException;
import util.exception.TransactionUnableToBeRefundedException;
/**
*
* @author markt
*/
@Named(value = "transactionManagementManagedBean")
@ViewScoped
public class TransactionManagementManagedBean implements Serializable {
@EJB
private TransactionSessionBeanLocal transactionSessionBeanLocal;
private List<Transaction> transactions;
private List<TransactionLineItem> transactionToViewLineItems;
/**
* Creates a new instance of TransactionManagementManagedBean
*/
public TransactionManagementManagedBean() {
}
@PostConstruct
public void postConstruct() {
setTransactions(transactionSessionBeanLocal.retrieveAllTransactions());
}
public void approveRefundRequest(Long transactionId) {
try {
transactionSessionBeanLocal.refundTransaction(transactionId);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Transaction refunded successfully", null));
setTransactions(transactionSessionBeanLocal.retrieveAllTransactions());
} catch (TransactionNotFoundException | TransactionAlreadyVoidedRefundedException | TransactionUnableToBeRefundedException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "An error has occurred while refunding transaction: " + ex.getMessage(), null));
}
}
public TransactionSessionBeanLocal getTransactionSessionBeanLocal() {
return transactionSessionBeanLocal;
}
public void setTransactionSessionBeanLocal(TransactionSessionBeanLocal transactionSessionBeanLocal) {
this.transactionSessionBeanLocal = transactionSessionBeanLocal;
}
public List<Transaction> getTransactions() {
return transactions;
}
public void setTransactions(List<Transaction> transactions) {
this.transactions = transactions;
}
public List<TransactionLineItem> getTransactionToViewLineItems() {
return transactionToViewLineItems;
}
public void setTransactionToViewLineItems(List<TransactionLineItem> transactionToViewLineItems) {
this.transactionToViewLineItems = transactionToViewLineItems;
}
}
| true
|
83043634fb4d92f540c4162cd81103566d1c03cb
|
Java
|
ahmedatef00/digital-wallet
|
/src/main/java/com/example/digitalwallet/config/RedisConfig.java
|
UTF-8
| 1,822
| 2.265625
| 2
|
[] |
no_license
|
package com.example.digitalwallet.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.lettuce.core.*;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import java.lang.reflect.Method;
@EnableCaching
@Configuration
public class RedisConfig {
@Value("${spring.redis.pool.max-active}")
private int redisPoolMaxActive;
@Value("${spring.redis.pool.max-wait}")
private int redisPoolMaxWait;
@Value("${spring.redis.pool.max-idle}")
private int redisPoolMaxIdle;
@Value("${spring.redis.pool.min-idle}")
private int redisPoolMinIdle;
/**
* Configuration Key Generation
*
* @return
*/
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(o.getClass().getName())
.append(method.getName());
for (Object object : objects) {
stringBuilder.append(object.toString());
}
return stringBuilder.toString();
}
};
}
/**
* Create redis connection factory
*
* @param dbIndex
* @param host
* @param port
* @param password
* @param timeout
* @return
*/
// public RedisConnectionFactory createJedisConnectionFactory(int dbIndex, String host, int port, String password, int timeout) {
//
// }
}
| true
|
02cb6b1ca01f6782624e0026f21f74af11d8d3ec
|
Java
|
coderxiang1523/homework
|
/JavaCollectPackage/JavaCollectPackage/src/com/ui/test/TestJpcap.java
|
UTF-8
| 1,145
| 2.890625
| 3
|
[] |
no_license
|
package com.ui.test;
import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
public class TestJpcap {
public static void main(String[] args) {
//获得网卡设备的实例列表
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
//循环输出全部网卡设备对象相应的信息
for(int i = 0; i< devices.length; i++){
//设备号 ,网卡名,网卡描述
System.out.println(i+":"+devices[i].name + "("+devices[i].description+")");
//网卡所处数据链路层的名称与其描述
System.out.println(" 数据链路层名称和描述: "+devices[i].datalink_name+"("+devices[i].datalink_description+")");
//网卡MAC地址
System.out.print("MAC address:");
for(byte b : devices[i].mac_address)
System.out.print(Integer.toHexString(b&0xff) + ":");
System.out.println();
//输出网卡IP地址 IPV4 IPV6 子网地址 扩播地址
for (NetworkInterfaceAddress a : devices[i].addresses)
System.out.println(" address:"+a.address + " " + a.subnet + " "+ a.broadcast);
}
}
}
| true
|
63cacfc385f41c44ac45a79562312cd8d12bbcc3
|
Java
|
AlejandroNeira/Curso-Java
|
/alneira/Clase17oct/src/main/java/cl/bci/clase17oct/repository/VentasRepo.java
|
UTF-8
| 671
| 2.1875
| 2
|
[] |
no_license
|
package cl.bci.clase17oct.repository;
import cl.bci.clase17oct.valueobject.VentasAgrupadasVO;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
@Repository
public class VentasRepo {
@PersistenceContext
EntityManager em;
public List<VentasAgrupadasVO> ventasAgrupadas(){
Query consulta = em.createQuery("select new cl.bci.clase17oct.valueobject.VentasAgrupadasVO(v.vendedor.name, count (v)) from Ventas v group by v.vendedor.name", VentasAgrupadasVO.class);
return consulta.getResultList();
}
}
| true
|
010dc42531168454dbbc09601a4818cfe98d57b1
|
Java
|
erichsueh/erichsueh---Habit-Tracker
|
/app/src/main/java/com/example/ehsueh/erichsueh_habittracker/CompletedHabitListController.java
|
UTF-8
| 773
| 2.390625
| 2
|
[] |
no_license
|
package com.example.ehsueh.erichsueh_habittracker;
/**
* Created by Eric Shay on 2016-10-02.
*
* This code is modeled after Student Pick in android
* (your saga thing)
* This is the Completed Habit List Controller made so I can access the old completed habits from anywhere
*/
public class CompletedHabitListController {
private static CompletedHabitList comphabitList = null;
static public CompletedHabitList getcompHabitList(){
if(comphabitList ==null){
comphabitList = new CompletedHabitList();
}
return comphabitList;
}
public CompletedHabitList getComphabitlist(){
return getcompHabitList();
}
public void addHabit(CompletedHabits habit){ getcompHabitList().AddCompletedHabit(habit);
}
}
| true
|
6b440b34e96366de14a4ead1f6e4c0526db0faab
|
Java
|
dragoonvn/javacore
|
/src/activity35/Activity35.java
|
UTF-8
| 991
| 3.390625
| 3
|
[] |
no_license
|
package activity35;
import java.util.Scanner;
public class Activity35 {
public static void main(String[] args) {
int a, dem1 = 1, dem2 = 1;
char c = 'A';
Scanner scanner = new Scanner(System.in);
System.out.println("Nhập vào số dòng: ");
a = scanner.nextInt();
for (int i = 1; i < (a * 2); i++) {
for (int j = a - dem1; j > 0; j--) {
System.out.print(" ");
}
if (i < a) {
dem1++;
} else {
dem1--;
}
for (int n = 0; n < dem2; n++) {
System.out.print(c);
if (n < dem2 / 2) {
c++;
} else {
c--;
}
}
if (i < a) {
dem2 = dem2 + 2;
} else {
dem2 = dem2 - 2;
}
c = 'A';
System.out.println();
}
}
}
| true
|
0b56a5d0679c1c9b07b1b1495831a42cef78468a
|
Java
|
PoetVVV/hebau_training2020
|
/数据库/stmng/src/课上/dao/ScoreDao.java
|
UTF-8
| 666
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package 课上.dao;
import java.util.List;
import 课上.pojo.Score;
/**
* @ClassName: ScoreDao
* @Description: 分数数据信息操作类
* @author: Mr.T
* @date: 2020年6月28日 上午11:20:36
*/
public class ScoreDao extends BaseDao {
public List<Score> selectList() {
String sql = "select sc.id,sc.subject,sc.score,sc.st_id as stId,st.name as stName from score sc left join student st on sc.st_id = st.id";
return super.selectList(sql, Score.class);
}
public void insert(Score score) {
String sql = "insert into score value(0,?,?,?)";
super.update(sql, score.getSubject(),score.getScore(),score.getStId());
}
}
| true
|
99e54d0d70d08e094448c26db5f1a9e703b12452
|
Java
|
francton14/chat
|
/src/main/java/com/piczon/data/dto/UserShow.java
|
UTF-8
| 1,603
| 2.125
| 2
|
[] |
no_license
|
package com.piczon.data.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
/**
* Created by franc on 9/19/2016.
*/
public class UserShow {
private Long id;
private String username;
private String firstName;
private String lastName;
private String email;
private Date birthday;
private String aboutMe;
private String imageFilename;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getImageFilename() {
return imageFilename;
}
public void setImageFilename(String imageFilename) {
this.imageFilename = imageFilename;
}
public String getAboutMe() {
return aboutMe;
}
public void setAboutMe(String aboutMe) {
this.aboutMe = aboutMe;
}
}
| true
|
ec5203d7047645ab9c772d1f25038ae952c08080
|
Java
|
ViniAlex/PBD2019.2
|
/src/view/NovoPerfilCurricular.java
|
UTF-8
| 22,993
| 1.8125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import control.PerfilControler;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JTextField;
/**
*
* @author Vinícius
*/
public class NovoPerfilCurricular extends javax.swing.JInternalFrame {
/**
* Creates new form NovoPerfilCurricular
*/
public NovoPerfilCurricular() {
initComponents();
PerfilControler c = new PerfilControler(this);
btSalvar.addActionListener(c);
btVoltar.addActionListener(c);
btAtt.addActionListener(c);
txtNome.addActionListener(c);
}
public JCheckBox getCBefF() {
return CBefF;
}
public void setCBefF(JCheckBox CBefF) {
this.CBefF = CBefF;
}
public JCheckBox getCBefI() {
return CBefI;
}
public void setCBefI(JCheckBox CBefI) {
this.CBefI = CBefI;
}
public JCheckBox getCBem() {
return CBem;
}
public void setCBem(JCheckBox CBem) {
this.CBem = CBem;
}
public JButton getBtAtt() {
return btAtt;
}
public void setBtAtt(JButton btAtt) {
this.btAtt = btAtt;
}
public JButton getBtSalvar() {
return btSalvar;
}
public void setBtSalvar(JButton btSalvar) {
this.btSalvar = btSalvar;
}
public JButton getBtVoltar() {
return btVoltar;
}
public void setBtVoltar(JButton btVoltar) {
this.btVoltar = btVoltar;
}
public JComboBox<String> getCbSerieFF() {
return cbSerieFF;
}
public void setCbSerieFF(JComboBox<String> cbSerieFF) {
this.cbSerieFF = cbSerieFF;
}
public JComboBox<String> getCbSerieFI() {
return cbSerieFI;
}
public void setCbSerieFI(JComboBox<String> cbSerieFI) {
this.cbSerieFI = cbSerieFI;
}
public JComboBox<String> getCbSerieM() {
return cbSerieM;
}
public void setCbSerieM(JComboBox<String> cbSerieM) {
this.cbSerieM = cbSerieM;
}
public JComboBox<String> getCbTurmaFF() {
return cbTurmaFF;
}
public void setCbTurmaFF(JComboBox<String> cbTurmaFF) {
this.cbTurmaFF = cbTurmaFF;
}
public JComboBox<String> getCbTurmaFI() {
return cbTurmaFI;
}
public void setCbTurmaFI(JComboBox<String> cbTurmaFI) {
this.cbTurmaFI = cbTurmaFI;
}
public JComboBox<String> getCbTurmaM() {
return cbTurmaM;
}
public void setCbTurmaM(JComboBox<String> cbTurmaM) {
this.cbTurmaM = cbTurmaM;
}
public JTextField getTxtNome() {
return txtNome;
}
public void setTxtNome(JTextField txtNome) {
this.txtNome = txtNome;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel3 = new javax.swing.JPanel();
jPanel8 = new javax.swing.JPanel();
txtNome = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
CBefI = new javax.swing.JCheckBox();
CBem = new javax.swing.JCheckBox();
jLabel1 = new javax.swing.JLabel();
cbSerieFI = new javax.swing.JComboBox<>();
cbSerieM = new javax.swing.JComboBox<>();
jLabel2 = new javax.swing.JLabel();
cbTurmaFI = new javax.swing.JComboBox<>();
cbTurmaM = new javax.swing.JComboBox<>();
btAtt = new javax.swing.JButton();
CBefF = new javax.swing.JCheckBox();
cbTurmaFF = new javax.swing.JComboBox<>();
cbSerieFF = new javax.swing.JComboBox<>();
btSalvar = new javax.swing.JButton();
btVoltar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jPanel8.setBackground(new java.awt.Color(255, 255, 255));
jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Perfil Curricular"));
txtNome.setEditable(false);
txtNome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNomeActionPerformed(evt);
}
});
jLabel17.setText("Nome");
CBefI.setText("Ensino Fundamental Inicial");
CBefI.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CBefIActionPerformed(evt);
}
});
CBem.setText("Ensino Médio");
CBem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CBemActionPerformed(evt);
}
});
jLabel1.setText("Série");
cbSerieFI.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1°", "2°", "3°", "4°", " ", " " }));
cbSerieFI.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbSerieFIActionPerformed(evt);
}
});
cbSerieM.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1°", "2°", "3°", " " }));
cbSerieM.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbSerieMActionPerformed(evt);
}
});
jLabel2.setText("Turma");
cbTurmaFI.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "A", "B", "C", "D", "E" }));
cbTurmaFI.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbTurmaFIActionPerformed(evt);
}
});
cbTurmaM.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "A", "B", "C", "D", "E", " " }));
cbTurmaM.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbTurmaMActionPerformed(evt);
}
});
btAtt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/imagens/refresh-button.png"))); // NOI18N
btAtt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btAttActionPerformed(evt);
}
});
CBefF.setText("Ensino Fundamental Final");
CBefF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CBefFActionPerformed(evt);
}
});
cbTurmaFF.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "A", "B", "C", "D", "E" }));
cbTurmaFF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbTurmaFFActionPerformed(evt);
}
});
cbSerieFF.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "5°", "6°", "7°", "8°", " ", " " }));
cbSerieFF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbSerieFFActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addComponent(txtNome)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btAtt))
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel17)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(CBefI)
.addGap(98, 98, 98)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(cbSerieFI, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(cbTurmaFI, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CBefF)
.addComponent(CBem))
.addGap(104, 104, 104)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(cbSerieM, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cbTurmaM, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(cbSerieFF, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cbTurmaFF, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))))))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel17)
.addGap(18, 18, 18)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btAtt))
.addGap(44, 44, 44)
.addComponent(CBefI))
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cbSerieFI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cbTurmaFI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(0, 4, Short.MAX_VALUE)
.addComponent(CBefF)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cbTurmaM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cbSerieM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CBem)))
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cbSerieFF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cbTurmaFF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/imagens/save-icon-silhouette.png"))); // NOI18N
btSalvar.setText("Salvar");
btSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btSalvarActionPerformed(evt);
}
});
btVoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/imagens/back-arrow.png"))); // NOI18N
btVoltar.setText("Voltar");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(btVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btSalvar)
.addComponent(btVoltar))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNomeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNomeActionPerformed
private void cbSerieFIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSerieFIActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cbSerieFIActionPerformed
private void cbSerieMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSerieMActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cbSerieMActionPerformed
private void CBefIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CBefIActionPerformed
if (CBefI.isSelected()) {
txtNome.setText("");
CBefF.setEnabled(false);
cbSerieFF.setEnabled(false);
cbTurmaFF.setEnabled(false);
CBem.setEnabled(false);
cbSerieM.setEnabled(false);
cbTurmaM.setEnabled(false);
} else {
txtNome.setText("");
CBem.setEnabled(true);
cbSerieM.setEnabled(true);
cbTurmaM.setEnabled(true);
CBefI.setEnabled(true);
cbSerieFI.setEnabled(true);
cbTurmaFI.setEnabled(true);
CBefF.setEnabled(true);
cbSerieFF.setEnabled(true);
cbTurmaFF.setEnabled(true);
}
}//GEN-LAST:event_CBefIActionPerformed
private void CBemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CBemActionPerformed
if (CBem.isSelected()) {
txtNome.setText("");
CBefI.setEnabled(false);
cbSerieFI.setEnabled(false);
cbTurmaFI.setEnabled(false);
CBefF.setEnabled(false);
cbSerieFF.setEnabled(false);
cbTurmaFF.setEnabled(false);
} else {
txtNome.setText("");
CBem.setEnabled(true);
cbSerieM.setEnabled(true);
cbTurmaM.setEnabled(true);
CBefI.setEnabled(true);
cbSerieFI.setEnabled(true);
cbTurmaFI.setEnabled(true);
CBefF.setEnabled(true);
cbSerieFF.setEnabled(true);
cbTurmaFF.setEnabled(true);
}
}//GEN-LAST:event_CBemActionPerformed
private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
}//GEN-LAST:event_btSalvarActionPerformed
private void cbTurmaFIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbTurmaFIActionPerformed
}//GEN-LAST:event_cbTurmaFIActionPerformed
private void cbTurmaMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbTurmaMActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cbTurmaMActionPerformed
private void btAttActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAttActionPerformed
}//GEN-LAST:event_btAttActionPerformed
private void CBefFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CBefFActionPerformed
if (CBefF.isSelected()) {
txtNome.setText("");
CBefI.setEnabled(false);
cbSerieFI.setEnabled(false);
cbTurmaFI.setEnabled(false);
CBem.setEnabled(false);
cbSerieM.setEnabled(false);
cbTurmaM.setEnabled(false);
} else {
txtNome.setText("");
CBem.setEnabled(true);
cbSerieM.setEnabled(true);
cbTurmaM.setEnabled(true);
CBefI.setEnabled(true);
cbSerieFI.setEnabled(true);
cbTurmaFI.setEnabled(true);
CBefF.setEnabled(true);
cbSerieFF.setEnabled(true);
cbTurmaFF.setEnabled(true);
}
}//GEN-LAST:event_CBefFActionPerformed
private void cbTurmaFFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbTurmaFFActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cbTurmaFFActionPerformed
private void cbSerieFFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSerieFFActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cbSerieFFActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox CBefF;
private javax.swing.JCheckBox CBefI;
private javax.swing.JCheckBox CBem;
private javax.swing.JButton btAtt;
private javax.swing.JButton btSalvar;
private javax.swing.JButton btVoltar;
private javax.swing.JComboBox<String> cbSerieFF;
private javax.swing.JComboBox<String> cbSerieFI;
private javax.swing.JComboBox<String> cbSerieM;
private javax.swing.JComboBox<String> cbTurmaFF;
private javax.swing.JComboBox<String> cbTurmaFI;
private javax.swing.JComboBox<String> cbTurmaM;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel8;
private javax.swing.JTextField txtNome;
// End of variables declaration//GEN-END:variables
}
| true
|
654a811df2d781383d3f3e6d94ae05a3feb6167b
|
Java
|
pranavkamble3010/TripPlanner_partA
|
/app/src/main/java/com/example/tripplanner/ViewProfileFragment.java
|
UTF-8
| 11,234
| 1.9375
| 2
|
[] |
no_license
|
package com.example.tripplanner;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.WriteBatch;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link ViewProfileFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
*/
public class ViewProfileFragment extends Fragment implements TripsRecyclerAdapter.TripCardInteractionListener{
/**Private attributes**/
private OnFragmentInteractionListener mListener;
private TextView lbl_profile_header;
private ImageView iv_vp_dp;
private User user;
private Button btn_editProfile;
private Button btn_addTrip;
private Button btn_signout;
private TextView lbl_name;
private TextView lbl_gender;
private TextView lbl_username;
private RecyclerView rv_trips;
private TripsRecyclerAdapter tripsAdapter;
private List<Trip> trips;
/**Private attributes end**/
/**Private methods**/
private void init(){
lbl_profile_header = getActivity().findViewById(R.id.lbl_viewProfileHeader);
lbl_name = getActivity().findViewById(R.id.lbl_vp_name);
lbl_gender = getActivity().findViewById(R.id.lbl_vp_gender);
lbl_username = getActivity().findViewById(R.id.lbl_vp_username);
iv_vp_dp = getActivity().findViewById(R.id.iv_vp_dp);
btn_editProfile = getActivity().findViewById(R.id.btn_editProfile);
rv_trips = getActivity().findViewById(R.id.rv_vp_trips);
//init trips
trips = new ArrayList<>();
//Get logged in user's information from the authentication
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
//Set progress dialog
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading profile");
progressDialog.show();
//Get user details from database
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("profiles")
.document(currentUser.getEmail())
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot doc = task.getResult();
if(doc.exists()){
user = new User((HashMap<String, Object>) doc.getData());
//Load header
lbl_profile_header.setText("Welcome, "+ user.getFname()+"!");
//Load display pic
Picasso.get().load(user.getImageUrl()).into(iv_vp_dp);
lbl_name.setText(user.getFname()+" "+user.getLname());
lbl_gender.setText(user.getGender());
lbl_username.setText(user.getUsername());
//Dismiss progress dialog
progressDialog.dismiss();
//Populate trips data
populateRecyclerView();
}
}
}
});
btn_editProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mListener.editProfileClicked();
}
});
btn_addTrip = getActivity().findViewById(R.id.btn_add_trip);
btn_addTrip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mListener.addTripClicked();
}
});
btn_signout = getActivity().findViewById(R.id.btn_logout);
btn_signout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final AlertDialog.Builder confirmationDialog = new AlertDialog.Builder(getContext());
confirmationDialog.setTitle("Confirm Action");
confirmationDialog.setMessage("Are you sure to sign out of TripPlanner app?");
confirmationDialog.setPositiveButton("YES, Sign out!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
mAuth.signOut();
Toast.makeText(getContext(), "User signed out successfully!", Toast.LENGTH_SHORT).show();
mListener.signoutClicked();
}});
confirmationDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}});
confirmationDialog.show();
}
});
}
private void populateRecyclerView() {
tripsAdapter = new TripsRecyclerAdapter(trips,
this,
user.getUsername());
rv_trips.setLayoutManager(new LinearLayoutManager(getActivity()));
rv_trips.setAdapter(tripsAdapter);
populateTrips();
}
private void populateTrips() {
trips.removeAll(trips);
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("trips")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot doc: task.getResult()) {
trips.add(new Trip((HashMap<String, Object>) doc.getData()));
}
tripsAdapter.notifyDataSetChanged();
}
else {
Toast.makeText(getContext(), "Error loading trips!", Toast.LENGTH_SHORT).show();
Log.d("ViewProfileFrag", "onComplete: Error getting trips data");
}
}
});
}
/**Private methods end**/
/**Edit area**/
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().setTitle("Trip Planner");
init();
}
/**Edit area end**/
public ViewProfileFragment() {
// Required empty public constructor
//user = new User();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_view_profile, container, false);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onJoinButtonClick(String tripTitle) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
WriteBatch batch = db.batch();
//Add the trip in the user
DocumentReference userUpdateRef = db.collection("profiles").
document(user.getUsername());
batch.update(userUpdateRef, "tripsAddedTo", FieldValue.arrayUnion(tripTitle));
DocumentReference tripUpdateRef = db.collection("trips").
document(tripTitle);
batch.update(tripUpdateRef, "members", FieldValue.arrayUnion(user.getUsername()));
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getContext(), "Trip joined successfully!", Toast.LENGTH_SHORT).show();
populateTrips();
}
}
});
}
@Override
public void onTripCardClick(Trip trip) {
Log.d("viewProfileFrag", "onTripCardClick: "+trip.toString());
mListener.tripCardClicked(trip);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void editProfileClicked();
void addTripClicked();
void signoutClicked();
void tripCardClicked(Trip trip);
}
}
| true
|
ae087dc2d278389f647418283a3cf11981d811e4
|
Java
|
yangrui110/asunerp
|
/framework/entity/src/com/hanlin/fadp/entity/condition/EntityConditionParam.java
|
UTF-8
| 950
| 2.34375
| 2
|
[] |
no_license
|
package com.hanlin.fadp.entity.condition;
import java.io.Serializable;
import com.hanlin.fadp.entity.model.ModelField;
/**
* Represents a single parameter to be used in the preparedStatement
*
*/
@SuppressWarnings("serial")
public class EntityConditionParam implements Serializable {
protected ModelField modelField;
protected Object fieldValue;
protected EntityConditionParam() {}
public EntityConditionParam(ModelField modelField, Object fieldValue) {
if (modelField == null) {
throw new IllegalArgumentException("modelField cannot be null");
}
this.modelField = modelField;
this.fieldValue = fieldValue;
}
public ModelField getModelField() {
return modelField;
}
public Object getFieldValue() {
return fieldValue;
}
@Override
public String toString() {
return modelField.getColName() + "=" + fieldValue.toString();
}
}
| true
|
9502ce9ad817c5c42cd47e8c3dd92ac72f977a6f
|
Java
|
alinpopa/rapaio
|
/src/rapaio/core/stat/Sum.java
|
UTF-8
| 1,778
| 2.890625
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* Copyright 2013 Aurelian Tutuianu
*
* 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 rapaio.core.stat;
import rapaio.core.Printable;
import rapaio.data.Var;
import rapaio.printer.Printer;
import static rapaio.core.MathBase.validNumber;
/**
* Computes the sum of elements for a {@link rapaio.data.Var} of values.
* <p>
* Ignore invalid numeric values. See {@link rapaio.core.MathBase#validNumber(double)}.
* <p>
* User: <a href="mailto:padreati@yahoo.com">Aurelian Tutuianu</a>
*/
public class Sum implements Printable {
private final String varName;
private final double value;
public Sum(Var var) {
this.varName = var.name();
this.value = compute(var);
}
private double compute(Var var) {
double sum = 0;
for (int i = 0; i < var.rowCount(); i++) {
if (validNumber(var.value(i))) {
sum += var.value(i);
}
}
return sum;
}
public double value() {
return value;
}
@Override
public void buildSummary(StringBuilder sb) {
sb.append(String.format("> sum[%s]\n%sf\n", varName, Printer.formatDecLong.format(value)));
}
}
| true
|
74517b835a7134e94b6e8a3d605b0311f7002bba
|
Java
|
menucha-de/LLRP.Data
|
/src/main/java/havis/llrpservice/data/message/parameter/FixedFrequencyTable.java
|
UTF-8
| 1,319
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package havis.llrpservice.data.message.parameter;
import havis.llrpservice.data.message.parameter.ParameterTypes.ParameterType;
import java.util.List;
public class FixedFrequencyTable extends Parameter {
private static final long serialVersionUID = -5941560665499145522L;
private TLVParameterHeader parameterHeader;
private int numFrequencies;
private List<Long> frequency;
public FixedFrequencyTable() {
}
public FixedFrequencyTable(TLVParameterHeader header, List<Long> frequency) {
parameterHeader = header;
parameterHeader.setParameterType(ParameterType.FIXED_FREQUENCY_TABLE);
this.frequency = frequency;
}
public TLVParameterHeader getParameterHeader() {
return parameterHeader;
}
public void setParameterHeader(TLVParameterHeader parameterHeader) {
this.parameterHeader = parameterHeader;
}
public List<Long> getFrequency() {
return frequency;
}
public void setFrequency(List<Long> frequency) {
this.frequency = frequency;
}
public int getNumFrequencies() {
return numFrequencies;
}
public void setNumFrequencies(int numFrequencies) {
this.numFrequencies = numFrequencies;
}
@Override
public String toString() {
return "FixedFrequencyTable [parameterHeader=" + parameterHeader + ", numFrequencies=" + numFrequencies + ", frequency=" + frequency + "]";
}
}
| true
|
2b538410f0538d1aecd8c85fbbde7df06e375724
|
Java
|
zhangpengzhan/TallYou
|
/src/com/example/tallyou/utils/.svn/text-base/XmppTool.java.svn-base
|
GB18030
| 5,193
| 2.203125
| 2
|
[] |
no_license
|
package com.example.tallyou.utils;
import java.util.Collection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Registration;
import android.util.Log;
public class XmppTool {
private static XMPPConnection con = null;
private static void openConnection() {
try {
// url˿ڣҲӵķַ֣˿ڣû
ConnectionConfiguration connConfig = new ConnectionConfiguration(
FactoryUtil.getSavePrivateFolder(// ÷ַʼַΪ
FieldsUtil.WebAddress, FieldsUtil.mString), 5222);
System.out.println("webaddress===="
+ FactoryUtil.getSavePrivateFolder(// ÷ַʼַΪ
FieldsUtil.WebAddress, FieldsUtil.mString));
connConfig.setReconnectionAllowed(true);
connConfig
.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
connConfig.setSASLAuthenticationEnabled(true);
connConfig.setTruststorePath("/system/etc/security/cacerts.bks");
connConfig.setTruststorePassword("changeit");
connConfig.setTruststoreType("bks");
con = new XMPPConnection(connConfig);
con.connect();
} catch (XMPPException xe) {
xe.printStackTrace();
}
}
public static XMPPConnection getConnection() {
if (con == null) {
openConnection();
}
return con;
}
public static void closeConnection() {
if (con != null) {
if (con.isConnected())
con.disconnect();
con = null;
}
}
/**
* ȡûб
*
* @param mRoster
*/
public static void upDataRoster() {
Roster mRoster = getConnection().getRoster();
if (FactoryUtil.getmUserInfoArrayList() != null)
FactoryUtil.clearmUserInfoArrayList();
Collection<RosterEntry> mCollection = mRoster.getEntries();
for (RosterEntry mRosterEntry : mCollection) {
UserInfo mUserInfo = new UserInfo();
mUserInfo.setName(mRosterEntry.getUser().split("@")[0]);
mUserInfo.setUser(mRosterEntry.getUser());
mUserInfo.setGroup_Size(mRosterEntry.getGroups().size());
Presence mPresence = mRoster.getPresence(mRosterEntry.getUser());
mUserInfo.setStatus(mPresence.getStatus());
mUserInfo.setFrom(mPresence.getFrom());
if (!mRosterEntry.getUser().split("@")[0]
.equals(FactoryUtil.getSavePrivateFolder(FieldsUtil.UserID,
FieldsUtil.mString))) {
FactoryUtil.addmUserInfoToArrayList(mUserInfo);
System.out.println("==============");
}
}
}
/**
* ע
*
* @param account
* עʺ
* @param password
* ע
* @return 1עɹ 0ûзؽ2˺Ѿ3עʧ
*/
public static String regist(String account, String password) {
if (getConnection() == null)
return "0";
Registration reg = new Registration();
reg.setType(IQ.Type.SET);
reg.setTo(getConnection().getServiceName());
reg.setUsername(account);// עcreateAccountעʱusernamejidǡ@ǰIJ֡
reg.setPassword(password);
reg.addAttribute("android", "geolo_createUser_android");// addAttributeΪգ־androidֻİɣ
PacketFilter filter = new AndFilter(new PacketIDFilter(
reg.getPacketID()), new PacketTypeFilter(IQ.class));
PacketCollector collector = getConnection().createPacketCollector(
filter);
getConnection().sendPacket(reg);
IQ result = (IQ) collector.nextResult(SmackConfiguration
.getPacketReplyTimeout());
// Stop queuing results
collector.cancel();// ֹͣresultsǷɹĽ
if (result == null) {
Log.e("RegistActivity", "No response from server.");
return "0";
} else if (result.getType() == IQ.Type.RESULT) {
return "1";
} else { // if (result.getType() == IQ.Type.ERROR)
if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
Log.e("RegistActivity", "IQ.Type.ERROR: "
+ result.getError().toString());
return "2";
} else {
Log.e("RegistActivity", "IQ.Type.ERROR: "
+ result.getError().toString());
return "3";
}
}
}
/**
*
*
* @return
*/
public static boolean changePassword(String pwd) {
if (getConnection() == null)
return false;
try {
getConnection().getAccountManager().changePassword(pwd);
return true;
} catch (XMPPException e) {
return false;
}
}
}
| true
|
d61ad225a24bbe7213b714babacb2a8266cdae47
|
Java
|
fergeteges565612/MineResetLite
|
/src/com/koletar/jj/mineresetlite/SerializableBlock.java
|
UTF-8
| 953
| 2.796875
| 3
|
[] |
no_license
|
package com.koletar.jj.mineresetlite;
import org.bukkit.Material;
/**
* @author jjkoletar
*/
public class SerializableBlock {
private Material mat;
private String matName;
public SerializableBlock(Material material) throws NullPointerException {
mat = material;
if (material == null) {
throw new NullPointerException();
} else {
matName = mat.name();
}
}
public Material getMat() {
return mat;
}
public String toString() {
return mat.toString();
}
public String getMaterialName() {
return matName;
}
public boolean equals(Object o) {
if (o != null && o instanceof SerializableBlock) {
SerializableBlock other = (SerializableBlock)o;
if (mat != null && other != null) {
return matName.equalsIgnoreCase(other.matName);
}
}
return false;
}
}
| true
|
45e3476dca9fb62cfa9d1e2b43a1768501049193
|
Java
|
YuryAmirov/hotel-booking
|
/src/main/java/ua/com/foxminded/hotelbooking/model/entity/AdditionalOption.java
|
UTF-8
| 1,690
| 2.375
| 2
|
[] |
no_license
|
package ua.com.foxminded.hotelbooking.model.entity;
import com.google.common.base.MoreObjects;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import ua.com.foxminded.hotelbooking.model.entity.core.AdditionalOptionType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import static com.google.common.base.MoreObjects.toStringHelper;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(exclude = {"id"})
@Entity
@Table(name = "additional_options")
public class AdditionalOption {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne
@JoinColumn(name="room_id", nullable=false)
private Room room;
@NotNull
@Column
@Enumerated(value = EnumType.STRING)
private AdditionalOptionType type;
@NotNull
@Column(name = "price")
private int pricePerNight;
@Override
public String toString() {
return formToStringHelper().toString();
}
private MoreObjects.ToStringHelper formToStringHelper() {
return toStringHelper(this)
.add("id:", this.id)
.add("room:", this.room)
.add("type:", this.type)
.add("pricePerNight:", this.pricePerNight)
.omitNullValues();
}
}
| true
|
f1b7598ef6879e5fc02746ba490d0c6226128483
|
Java
|
unisysTechHub/Ecommerce
|
/app/src/main/java/com/exemplary/ecommerce/database/table/Colors.java
|
UTF-8
| 556
| 2.421875
| 2
|
[] |
no_license
|
package com.exemplary.ecommerce.database.table;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "colors")
public class Colors {
@ColumnInfo(name = "color_id")
@PrimaryKey
int Id;
@ColumnInfo(name = "color")
String color;
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
| true
|
7faaa4225ec5d0c4a71c7c3b0e37b49ea9c4fae8
|
Java
|
paulomcnally/place-uca-android
|
/app/src/main/java/uca/places/app/ui/activities/PlaceAddActivity.java
|
UTF-8
| 2,945
| 2.296875
| 2
|
[] |
no_license
|
package uca.places.app.ui.activities;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import uca.places.app.R;
import uca.places.app.api.Api;
import uca.places.app.models.LocationModel;
import uca.places.app.models.PlaceModel;
public class PlaceAddActivity extends AppCompatActivity {
private EditText name;
private Button save;
private Double latitude;
private Double longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_add);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle extras = getIntent().getExtras();
if (extras != null) {
latitude = extras.getDouble("latitude");
longitude = extras.getDouble("longitude");
// and get whatever type user account id is
}
initViews();
}
private void initViews() {
name = (EditText) findViewById(R.id.name);
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveAction();
}
});
}
private void saveAction() {
if(name.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), "Chele pone el texto", Toast.LENGTH_LONG).show();
} else {
PlaceModel placeModel = new PlaceModel();
placeModel.setName(name.getText().toString());
LocationModel locationModel = new LocationModel();
locationModel.setLat(latitude);
locationModel.setLng(longitude);
placeModel.setLocationModel(locationModel);
Call<PlaceModel> call = Api.instance().placeAdd(placeModel);
call.enqueue(new Callback<PlaceModel>() {
@Override
public void onResponse(Call<PlaceModel> call, Response<PlaceModel> response) {
if(response != null && response.body() != null) {
finish();
} else {
Log.i("PlaceAddActivity", "Negres, no funko");
}
}
@Override
public void onFailure(Call<PlaceModel> call, Throwable throwable) {
Log.i("PlaceAddActivity", throwable.getMessage());
}
});
}
}
}
| true
|
a2f83632d10859faead0a4f71420241c8543a7d6
|
Java
|
nhatnv7192/JavaProject
|
/WebSiteSecondNew/src/main/java/com/entities/OrderDetail.java
|
UTF-8
| 2,373
| 2.359375
| 2
|
[] |
no_license
|
package com.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="orderdetails")
public class OrderDetail {
@Id
@GeneratedValue(strategy =GenerationType.AUTO)
@Column(name="orderDetailsId")
private int orderDetailsId;
@Column(name="orderId",insertable = false,updatable = false)
private int orderId;
@Column(name="productId",insertable = false,updatable = false)
private int productId;
@Column(name="quantity")
private int quantity;
@Column(name="price")
private double price;
@Column(name="discount")
private double discount;
@Column(name="notes")
private String notes;
@ManyToOne(fetch = FetchType.LAZY , cascade = CascadeType.ALL)
@JoinColumn(name ="orderId")
private OrderProduct orderProduct;
@ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name="productId")
private Product product;
public int getOrderDetailsId() {
return orderDetailsId;
}
public void setOrderDetailsId(int orderDetailsId) {
this.orderDetailsId = orderDetailsId;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public OrderProduct getOrderProduct() {
return orderProduct;
}
public void setOrderProduct(OrderProduct orderProduct) {
this.orderProduct = orderProduct;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
| true
|
4b0a02df1a5518cc56e3c5aecedaae0529fc96bf
|
Java
|
astronaut183/data_structure
|
/src/main/java/zyh/data/main/SymmetricTree.java
|
UTF-8
| 639
| 2.984375
| 3
|
[] |
no_license
|
package zyh.data.main;
public class SymmetricTree {
public boolean IsSymmertric(BinaryTree.Node root) {
if (root == null) return true;
return IsSubSymmertric(root.getRightChind(),root.getLeftChind());
}
public boolean IsSubSymmertric(BinaryTree.Node rChild, BinaryTree.Node lChild) {
if (rChild == null && lChild == null) return true;
if (rChild == null || lChild == null) return false;
return (rChild.getData()==lChild.getData())&&IsSubSymmertric(rChild.getRightChind(),lChild.getLeftChind())&&
IsSubSymmertric(rChild.getLeftChind(),lChild.getRightChind());
}
}
| true
|
9cc68d92ba429da67ebb79758f954b2c21c7efdc
|
Java
|
huanghui6579/mytest
|
/src/net/ibaixin/chat/db/DatabaseHelper.java
|
UTF-8
| 6,230
| 2.171875
| 2
|
[] |
no_license
|
package net.ibaixin.chat.db;
import net.ibaixin.chat.provider.Provider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* 数据库创建
* @author huanghui1
* @version 1.0.0
* @update 2014年10月13日 上午11:26:25
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "ibaixin_chat.db";
private static final int DB_VERSION = 8;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建用户表
db.execSQL("CREATE TABLE " + Provider.UserColumns.TABLE_NAME + " ("
+ Provider.UserColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ Provider.UserColumns.USERNAME + " TEXT UNIQUE NOT NULL, "
+ Provider.UserColumns.NICKNAME + " TEXT, "
+ Provider.UserColumns.EMAIL + " TEXT, "
+ Provider.UserColumns.PHONE + " TEXT, "
+ Provider.UserColumns.RESOURCE + " TEXT, "
+ Provider.UserColumns.STATUS + " TEXT, "
+ Provider.UserColumns.MODE + " TEXT, "
+ Provider.UserColumns.FULLPINYIN + " TEXT, "
+ Provider.UserColumns.SHORTPINYIN + " TEXT, "
+ Provider.UserColumns.SORTLETTER + " TEXT);");
//创建用户名片表
db.execSQL("CREATE TABLE " + Provider.UserVcardColumns.TABLE_NAME + " ("
+ Provider.UserVcardColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Provider.UserVcardColumns.USERID + " INTEGER UNIQUE NOT NULL, "
+ Provider.UserVcardColumns.NICKNAME + " TEXT, "
+ Provider.UserVcardColumns.REALNAME + " TEXT, "
+ Provider.UserVcardColumns.MOBILE + " TEXT, "
+ Provider.UserVcardColumns.EMAIL + " TEXT, "
+ Provider.UserVcardColumns.PROVINCE + " TEXT, "
+ Provider.UserVcardColumns.STREET + " TEXT, "
+ Provider.UserVcardColumns.CITY + " TEXT, "
+ Provider.UserVcardColumns.ZIPCODE + " TEXT, "
+ Provider.UserVcardColumns.ICONPATH + " TEXT, "
+ Provider.UserVcardColumns.ICONHASH + " TEXT);");
//创建个人信息表
db.execSQL("CREATE TABLE " + Provider.PersonalColums.TABLE_NAME + " ("
+ Provider.PersonalColums._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Provider.PersonalColums.USERNAME + " TEXT UNIQUE NOT NULL, "
+ Provider.PersonalColums.PASSWORD + " TEXT NOT NULL, "
+ Provider.PersonalColums.NICKNAME + " TEXT, "
+ Provider.PersonalColums.REALNAME + " TEXT, "
+ Provider.PersonalColums.EMAIL + " TEXT, "
+ Provider.PersonalColums.PHONE + " TEXT, "
+ Provider.PersonalColums.RESOURCE + " TEXT, "
+ Provider.PersonalColums.STATUS + " TEXT, "
+ Provider.PersonalColums.MODE + " TEXT, "
+ Provider.PersonalColums.PROVINCE + " TEXT, "
+ Provider.PersonalColums.STREET + " TEXT, "
+ Provider.PersonalColums.CITY + " TEXT, "
+ Provider.PersonalColums.ZIPCODE + " TEXT, "
+ Provider.PersonalColums.ICONPATH + " TEXT, "
+ Provider.PersonalColums.ICONHASH + " TEXT);");
//创建聊天消息表
db.execSQL("CREATE TABLE " + Provider.MsgInfoColumns.TABLE_NAME + " ("
+ Provider.MsgInfoColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Provider.MsgInfoColumns.THREAD_ID + " INTEGER NOT NULL, "
+ Provider.MsgInfoColumns.FROM_USER + " TEXT NOT NULL, "
+ Provider.MsgInfoColumns.TO_USER + " TEXT NOT NULL, "
+ Provider.MsgInfoColumns.CONTENT + " TEXT, "
+ Provider.MsgInfoColumns.SUBJECT + " TEXT, "
+ Provider.MsgInfoColumns.CREATIO_NDATE + " LONG, "
+ Provider.MsgInfoColumns.IS_COMMING + " INTEGER, "
+ Provider.MsgInfoColumns.IS_READ + " INTEGER, "
+ Provider.MsgInfoColumns.MSG_TYPE + " INTEGER, "
+ Provider.MsgInfoColumns.SEND_STATE + " INTEGER);");
//创建聊天消息的附件表
db.execSQL("CREATE TABLE " + Provider.MsgPartColumns.TABLE_NAME + " ("
+ Provider.MsgPartColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Provider.MsgPartColumns.MSG_ID + " INTEGER NOT NULL, "
+ Provider.MsgPartColumns.FILE_NAME + " TEXT NOT NULL, "
+ Provider.MsgPartColumns.FILE_PATH + " TEXT NOT NULL, "
+ Provider.MsgPartColumns.SIZE + " LONG, "
+ Provider.MsgPartColumns.CREATION_DATE + " LONG, "
+ Provider.MsgPartColumns.MIME_TYE + " TEXT);");
//创建聊天会话表
db.execSQL("CREATE TABLE " + Provider.MsgThreadColumns.TABLE_NAME + " ("
+ Provider.MsgThreadColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Provider.MsgThreadColumns.MSG_THREAD_NAME + " TEXT, "
+ Provider.MsgThreadColumns.UNREAD_COUNT + " INTEGER, "
+ Provider.MsgThreadColumns.MODIFY_DATE + " LONG, "
+ Provider.MsgThreadColumns.SNIPPET_ID + " INTEGER, "
+ Provider.MsgThreadColumns.SNIPPET_CONTENT + " TEXT, "
+ Provider.MsgThreadColumns.MEMBER_IDS + " TEXT, "
+ Provider.MsgThreadColumns.IS_TOP + " INTEGER DEFAULT 0);");
//创建新的朋友列表
db.execSQL("CREATE TABLE " + Provider.NewFriendColumns.TABLE_NAME + " ("
+ Provider.NewFriendColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Provider.NewFriendColumns.USER_ID + " INTEGER UNIQUE NOT NULL, "
+ Provider.NewFriendColumns.FRIEND_STATUS + " INTEGER DEFAULT 0, "
+ Provider.NewFriendColumns.CONTENT + " TEXT, "
+ Provider.NewFriendColumns.FROM_USER + " TEXT UNIQUE NOT NULL, "
+ Provider.NewFriendColumns.TO_USER + " TEXT UNIQUE NOT NULL, "
+ Provider.NewFriendColumns.ICON_HASH + " TEXT, "
+ Provider.NewFriendColumns.ICON_PATH + " TEXT, "
+ Provider.NewFriendColumns.CREATION_DATE + " LONG);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Provider.UserColumns.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + Provider.UserVcardColumns.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + Provider.PersonalColums.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + Provider.MsgInfoColumns.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + Provider.MsgPartColumns.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + Provider.MsgThreadColumns.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + Provider.NewFriendColumns.TABLE_NAME);
onCreate(db);
}
}
| true
|
00a81799a8d09303517bd4f13f0b4da04ef7c5dd
|
Java
|
kaidezhanhao/sqltool
|
/src/com/entity/PreferencInfo.java
|
GB18030
| 574
| 2.328125
| 2
|
[] |
no_license
|
package com.entity;
/**
* ݿϢ
* @author Administrator
*
*/
public class PreferencInfo {
private String name ="";
private String view ="";
public PreferencInfo(String name, String view) {
this.name = name;
this.view = view;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
public String getView() {
return view;
}
public void setView(String view) {
this.view = view;
}
}
| true
|
9dd26a323788711524939729dac06d120b34666d
|
Java
|
juriel/ocelot-html
|
/src/main/java/net/comtor/ocelot/html/formatting/HtmlSamp.java
|
UTF-8
| 307
| 2.046875
| 2
|
[] |
no_license
|
package net.comtor.ocelot.html.formatting;
import net.comtor.ocelot.html.utils.HtmlTextContainer;
/**
*
* @author Guido A. Cafiel Vellojin
*/
public class HtmlSamp extends HtmlTextContainer {
public HtmlSamp() {
super("samp");
}
public HtmlSamp(String text) {
super("samp",text);
}
}
| true
|
bae1c0ab0e579224f70bfe7dc2833d2dd76b45be
|
Java
|
AndreaPCalvin/Plants-vs-Zombies-JAVA
|
/zombies/Deportista.java
|
UTF-8
| 885
| 2.875
| 3
|
[] |
no_license
|
package zombies;
import logic.Game;
public class Deportista extends Zombie {
public Deportista(int posX, int posY, Game game) {
super(posX, posY, game);
this.damage=1;
this.resist=2;
this.vidaMax=2;
this.ciclosMax=0;
this.frec=0;
this.nombre="Deportista";
this.letra="x";
this.ciclosRestantes=this.frec;
}
public Deportista() {
super();//es una planta que no existe, solo sirve para lectura
this.vidaMax=2;
this.ciclosMax=0;
this.damage=1;
this.resist=2;
this.frec=0;
this.ciclosRestantes=this.frec;
this.nombre="Deportista";
this.letra="x";
}
public Deportista(int x, int y, Game game, int lr, int t) {
super(x, y, game);
this.vidaMax=2;
this.ciclosMax=0;
this.damage=1;
this.resist=lr;
this.frec=0;
this.nombre="Deportista";
this.letra="x";
this.ciclosRestantes=t;
}
}
| true
|
c8471db55eee8761defa0e791d0de825e25bab12
|
Java
|
LDA111222/GraphScope
|
/interactive_engine/src/api/sdk-common/src/main/java/com/alibaba/maxgraph/compiler/api/schema/PropDataType.java
|
UTF-8
| 5,285
| 2.078125
| 2
|
[
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-elastic-license-2018",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
/**
* Copyright 2020 Alibaba Group Holding Limited.
*
* 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.alibaba.maxgraph.compiler.api.schema;
import com.alibaba.maxgraph.sdkcommon.meta.DataType;
import com.alibaba.maxgraph.sdkcommon.meta.InternalDataType;
import com.google.common.collect.Lists;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.ArrayList;
import java.util.Date;
public enum PropDataType {
BOOL,
CHAR,
SHORT,
INTEGER,
LONG,
FLOAT,
DOUBLE,
BINARY,
STRING,
DATE,
INTEGER_LIST,
LONG_LIST,
FLOAT_LIST,
DOUBLE_LIST,
STRING_LIST,
BYTES_LIST;
public static PropDataType parseFromDataType(DataType dataType) {
InternalDataType internalDataType = dataType.getType();
switch (internalDataType) {
case BOOL: {
return PropDataType.BOOL;
}
case CHAR: {
return PropDataType.CHAR;
}
case SHORT: {
return PropDataType.SHORT;
}
case INT: {
return PropDataType.INTEGER;
}
case LONG: {
return PropDataType.LONG;
}
case FLOAT: {
return PropDataType.FLOAT;
}
case DOUBLE: {
return PropDataType.DOUBLE;
}
case STRING: {
return PropDataType.STRING;
}
case BYTES: {
return PropDataType.BINARY;
}
case DATE: {
return PropDataType.STRING;
}
case LIST: {
switch (InternalDataType.valueOf(dataType.getExpression())) {
case INT: {
return PropDataType.INTEGER_LIST;
}
case LONG: {
return PropDataType.LONG_LIST;
}
case FLOAT: {
return PropDataType.FLOAT_LIST;
}
case DOUBLE: {
return PropDataType.DOUBLE_LIST;
}
case STRING: {
return PropDataType.STRING_LIST;
}
default: {
throw new IllegalArgumentException("Unsupport property data type " + dataType.toString());
}
}
}
default: {
throw new IllegalArgumentException("Unsupport property data type " + dataType.toString());
}
}
}
public Object getRandomValue() {
switch (this) {
case BOOL:
return RandomUtils.nextBoolean();
case CHAR:
return (char) Math.abs(RandomUtils.nextInt()) % 127;
case DATE:
return new Date().toString();
case SHORT:
return (short) RandomUtils.nextInt();
case INTEGER:
return RandomUtils.nextInt();
case LONG:
return RandomUtils.nextLong();
case FLOAT:
return RandomUtils.nextFloat();
case DOUBLE:
return RandomUtils.nextDouble();
case STRING:
return RandomStringUtils.randomAlphanumeric(64);
case BINARY:
return RandomStringUtils.random(64).getBytes();
case INTEGER_LIST:
return Lists.newArrayList(RandomUtils.nextInt(), RandomUtils.nextInt(), RandomUtils.nextInt());
case LONG_LIST:
return Lists.newArrayList(RandomUtils.nextLong(), RandomUtils.nextLong(), RandomUtils.nextLong());
case FLOAT_LIST:
return Lists.newArrayList(RandomUtils.nextFloat(), RandomUtils.nextFloat(), RandomUtils.nextFloat());
case DOUBLE_LIST:
return Lists.newArrayList(RandomUtils.nextDouble(), RandomUtils.nextDouble(), RandomUtils.nextDouble());
case STRING_LIST:
return Lists.newArrayList(RandomStringUtils.randomAlphanumeric(64),
RandomStringUtils.randomAlphanumeric(64),
RandomStringUtils.randomAlphanumeric(64));
case BYTES_LIST:
return Lists.newArrayList(RandomStringUtils.randomAlphanumeric(64).getBytes(),
RandomStringUtils.randomAlphanumeric(64).getBytes(),
RandomStringUtils.randomAlphanumeric(64).getBytes());
}
throw new IllegalArgumentException("Unknown prop data type " + this);
}
}
| true
|
6d2272301e2ae6b1256000bce1c9f4e0dfcf9a7a
|
Java
|
zhanght86/HSBC20171018
|
/LIS/sinosoft-parents/lis-business/src/main/java_other/com/sinosoft/ibrms/UpdateRuleResultThread.java
|
UTF-8
| 1,505
| 2.75
| 3
|
[] |
no_license
|
package com.sinosoft.ibrms;
import org.apache.log4j.Logger;
import java.util.LinkedList;
/**
* 专门用来写规则引擎执行结果的类,只有一个线程来进行执行
* 如果有任务来了,就执行,如果没有的话,就挂起直到有新的任务到来
*
* @author Administrator
*
*/
public class UpdateRuleResultThread extends Thread {
private static Logger logger = Logger.getLogger(UpdateRuleResultThread.class);
private UpdateRuleResultThread(){
this.start();
}
public static UpdateRuleResultThread getInstance(){
return thread;
}
private LinkedList tasks = new LinkedList();
public static UpdateRuleResultThread thread= new UpdateRuleResultThread();
protected void addTask(Task task){
synchronized(tasks)
{
this.tasks.add(task);
this.tasks.notify();
}
}
public void run() {
// TODO Auto-generated method stub
while (true) {
Task task = null;
synchronized(this.tasks){
while(tasks.isEmpty()){
try {
this.tasks.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
task = (Task) tasks.removeFirst();
}
try{
task.execute();
}catch (RuntimeException e) {
// You might want to log something here
e.printStackTrace();
logger.debug("runtime");
thread= new UpdateRuleResultThread();
//releaseThreadPool();
}
}
}
}
| true
|
130f01e54120369fc624b584ea3f3600e1c0c650
|
Java
|
ZhaoWanlia/Zproject
|
/config-client/src/main/java/com/zhibo/springcloud/config/server/DemoProviderApplication.java
|
UTF-8
| 622
| 2.09375
| 2
|
[] |
no_license
|
package com.zhibo.springcloud.config.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class DemoProviderApplication {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(DemoProviderApplication.class, args);
DemoConfig demoConfig = applicationContext.getBean(DemoConfig.class);
System.out.println(demoConfig.getName());
System.out.println(demoConfig.getAge());
}
}
| true
|
9003d7a0459708b73cff99e846fb4e155b81ca07
|
Java
|
ruwany/carbon-analytics
|
/components/analytics-core/org.wso2.carbon.analytics.dataservice.core/src/main/java/org/wso2/carbon/analytics/dataservice/core/Constants.java
|
UTF-8
| 5,376
| 1.609375
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2015, 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.wso2.carbon.analytics.dataservice.core;
import org.wso2.carbon.analytics.datasource.core.AnalyticsDataSourceConstants;
import java.io.File;
/**
* This class hold constants that required for data service
*/
public class Constants {
public static final String PERMISSION_LIST_TABLE = "/permission/admin/manage/analytics/table/list";
public static final String PERMISSION_CREATE_TABLE = "/permission/admin/manage/analytics/table/create";
public static final String PERMISSION_DROP_TABLE = "/permission/admin/manage/analytics/table/drop";
public static final String PERMISSION_LIST_RECORD = "/permission/admin/manage/analytics/records/get";
public static final String PERMISSION_PUT_RECORD = "/permission/admin/manage/analytics/records/put";
public static final String PERMISSION_GET_RECORD = "/permission/admin/manage/analytics/records/get";
public static final String PERMISSION_DELETE_RECORD = "/permission/admin/manage/analytics/records/delete";
public static final String PERMISSION_SEARCH_RECORD = "/permission/admin/manage/analytics/records/search";
public static final String DEFAULT_CHARSET = "UTF8";
public static final String ANALYTICS_SCHEMA_FILE_EXTENSION = "xml";
public static final String RETENTION_PERIOD = "retentionPeriod";
public static final String INCLUDE_TABLES = "includeTables";
public static final String INCLUDE_CLASS_SPLITTER = "###";
public static final String DISABLE_ANALYTICS_DATA_PURGING_JVM_OPTION = "disableDataPurging";
public static final int RECORDS_BATCH_SIZE = 1000;
public static final int DEFAULT_INDEX_REPLICATION_FACTOR = 1;
public static final String ANALYTICS_DATA_PURGING = "ANALYTICS_DATA_PURGING";
public static final String TABLE = "table";
public static final String TENANT_ID = "tenantId";
public static final String CRON_STRING = "cronString";
public static final int INDEX_WORKER_STOP_WAIT_TIME = 60000;
public static final int REINDEX_WORKER_STOP_WAIT_TIME = 60000;
public static final int TAXONOMY_WORKER_STOP_WAIT_TIME = 60000;
public static final int META_INFO_TENANT_ID = -1000;
public static final int GLOBAL_TENANT_TABLE_ACCESS_TENANT_ID = -2000;
public static final String GLOBAL_SHARD_ALLOCATION_CONFIG_TABLE = "__GLOBAL_SHARD_ALLOCATION_CONFIG__";
public static final String INDEX_STAGING_DATA_TABLE = "__INDEX_STAGING_DATA__";
public static final String INDEX_STAGING_DATA_COLUMN = "VALUE";
public static final long DEFAULT_SHARD_INDEX_RECORD_BATCH_SIZE = 20971520;
public static final long SHARD_INDEX_RECORD_BATCH_SIZE_MIN = 1000;
public static final int DEFAULT_SHARD_INDEX_WORKER_INTERVAL = 1500;
public static final int SHARD_INDEX_WORKER_INTERVAL_MIN = 10;
public static final int SHARD_INDEX_WORKER_INTERVAL_MAX = 60000;
public static final int DEFAULT_INDEX_WORKER_COUNT = 1;
public static final int DEFAULT_MAX_INDEXER_COMMUNICATOR_BUFFER_SIZE = 1024;
public static final int DEFAULT_INDEXING_QUEUE_CLEANUP_THRESHOLD = 209715200;
public static final String DEFAULT_TAXONOMY_WRITER_CACHE = "DEFAULT";
public static final String LRU_TAXONOMY_WRITER_CACHE = "LRU";
public static final String DEFAULT_LRU_CACHE_TYPE = "STRING";
public static final String HASHED_LRU_CACHE_TYPE = "HASHED";
public static final int DEFAULT_LRU_CACHE_SIZE = 4096;
public static final String DISABLE_INDEXING_ENV_PROP = "disableIndexing";
public static final String ANALYTICS_INDEXING_GROUP = "__ANALYTICS_INDEXING_GROUP__";
public static final String DISABLE_LOCAL_INDEX_QUEUE_OPTION = "disableLocalIndexQueue";
public static final String DEFAULT_INDEX_STORE_LOCATION = AnalyticsDataSourceConstants.CARBON_HOME_VAR + File.separator + "repository"
+ File.separator + "data" + File.separator + "index_data" + File.separator;
public static final String INDEX_STORE_DIR_PREFIX = "shard";
public static final String LOCAL_SHARD_ALLOCATION_CONFIG_LOCATION = AnalyticsDataSourceConstants.CARBON_HOME_VAR + File.separator + "repository"
+ File.separator + "conf" + File.separator + "analytics" + File.separator + "local-shard-allocation-config.conf";
public static final String MY_NODEID_LOCATION = AnalyticsDataSourceConstants.CARBON_HOME_VAR + File.separator + "repository"
+ File.separator + "conf" + File.separator + "analytics" + File.separator + "my-node-id.dat";
public static final String DEFAULT_LOCAL_INDEX_STAGING_LOCATION = AnalyticsDataSourceConstants.CARBON_HOME_VAR + File.separator + "repository"
+ File.separator + "data" + File.separator + "index_staging_queues" + File.separator;
}
| true
|
b0aec4fbfb822aada11c0edd2624452773e8b168
|
Java
|
riwa90/Mock-cash-register
|
/src/se/kth/iv1350/sem/model/SaleLogDTO.java
|
UTF-8
| 2,642
| 3.046875
| 3
|
[] |
no_license
|
package se.kth.iv1350.sem.model;
import java.util.ArrayList;
import java.util.Date;
/**
* Represents a log of a sale that have taken place.
* Contains data meant for a receipt and accounting systems.
*/
public class SaleLogDTO {
private int totalPrice;
private int totalVat;
private int payment;
private int change;
private ArrayList<ItemDTO> items;
private StoreDTO store;
private Date timeOfPurchase;
/**
* Creates an instance of <code>SaleLogDTO</code>
* @param saleToLog <code>Sale</code> object to log to a receipt and accounting systems.
* @param store Store that sale took place in.
* @param payment Payment received from the customer.
* @param change Amount of money to give back to customer.
*/
SaleLogDTO(Sale saleToLog, StoreDTO store, int payment, int change) {
this.store = store;
this.payment = payment;
this.change = change;
this.totalPrice = saleToLog.getTotalPrice();
this.totalVat = saleToLog.getTotalVAT();
this.items = saleToLog.getItems();
this.timeOfPurchase = new Date();
}
/**
* Gets the total price of the logged sale occasion.
* @return Sale price including VAT.
*/
public int getTotalPrice() {
return totalPrice;
}
/**
* Gets the total VAT price of the logged sale occasion.
* @return VAT amount.
*/
public int getTotalVat() {
return totalVat;
}
/**
* Gets the payment recieved from the customer of the logged sale occasion.
* @return Payment received from customer.
*/
public int getPayment() {
return payment;
}
/**
* Gets the change owed back to the customer of the logged sale occasion.
* @return Change owed back to the customer.
*/
public int getChange() {
return change;
}
/**
* Gets the items sold of the logged sale occasion.
* @return <code>ArrayList</code> of <code>ItemDTO</code> of sold items.
*/
public ArrayList<ItemDTO> getItems() {
ArrayList<ItemDTO> returnItems = new ArrayList<ItemDTO>();
for(ItemDTO item : items){
returnItems.add(item);
}
return returnItems;
}
/**
* Gets the store where the logged sale occasion occurred.
* @return Store info.
*/
public StoreDTO getStore() {
return store;
}
/**
* Gets the time and date of the logged sale occasion.
* @return <code>Date</code> object when the sale happened.
*/
public Date getTimeOfPurchase() {
return timeOfPurchase;
}
}
| true
|