hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
764f58a68a7390650752fd3f50ad6046734247a0
3,616
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rewindframework.agent; import com.rabbitmq.client.*; import org.rewindframework.messages.TestingAbort; import org.rewindframework.messages.TestingRequest; import org.apache.commons.lang3.SerializationUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.Map; public class RequestConsumer extends DefaultConsumer { private static final Logger LOGGER = LogManager.getLogger(RequestConsumer.class); private final Connection connection; private final File workerDirectory; private final Map<String, String> testProperties; RequestConsumer(Channel channel, Connection connection, File workerDirectory, Map<String, String> testProperties) { super(channel); this.connection = connection; this.workerDirectory = workerDirectory; this.testProperties = testProperties; } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { LOGGER.debug(String.format("Delivery received with consumer tag '%s' and a payload of %d bytes", consumerTag, body.length)); try { // 1) Deserialize the message TestingRequest request = SerializationUtils.deserialize(body); LOGGER.debug(String.format("Testing request deserialized: test JAR is %d bytes, id is '%s', repository count is %d, and dependency count is %d", request.payload.length, request.id, request.repositories.size(), request.dependencies.size())); // Responder Responder responder = new Responder(request.id, connection); // Connect the logger to this running test responder try { AgentLogAppender.responder = responder; LOGGER.info(String.format("Request '%s' received", request.id)); try { // Process request RequestFactory.newRequest(request.id, responder).useWorkerDirectory(new File(workerDirectory, "rewind-test")).useCacheDirectory(new File(workerDirectory, "cache")).withTestProperties(testProperties).execute(request.payload, request.dependencies, request.repositories).publishResults(); LOGGER.debug("Delivery processed successfully"); } catch (InterruptedException e) { LOGGER.error("Interrupt exception", e); } catch (URISyntaxException e) { LOGGER.error("URI syntax exception", e); } } catch (Throwable e) { responder.notify(new TestingAbort().withId(request.id)); throw e; } finally { AgentLogAppender.responder = null; } } catch (Throwable e) { LOGGER.error("Exception during setting appender", e); throw e; } } }
43.566265
305
0.678374
c014a7eef7cdb0108f649463e13007075366a2ef
8,266
package seedu.address.model.meeting; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.VALID_DATETIME_LECTURE; import static seedu.address.logic.commands.CommandTestUtil.VALID_DATETIME_TUTORIAL; import static seedu.address.logic.commands.CommandTestUtil.VALID_DURATION_TUTORIAL; import static seedu.address.logic.commands.CommandTestUtil.VALID_MODULE_TUTORIAL; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_TUTORIAL; import static seedu.address.logic.commands.CommandTestUtil.VALID_RECURRING_TUTORIAL; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_TUTORIAL; import static seedu.address.logic.commands.CommandTestUtil.VALID_URL_LECTURE; import static seedu.address.model.meeting.MeetingDateTime.INPUT_FORMAT; import static seedu.address.testutil.typical.TypicalMeetings.CS2103; import static seedu.address.testutil.typical.TypicalMeetings.CS2105; import java.time.LocalDateTime; import org.junit.jupiter.api.Test; import seedu.address.model.tag.Tag; import seedu.address.testutil.meeting.MeetingBuilder; public class MeetingTest { /* * Note: getNextRecurrence is only called for recurring meetings */ @Test public void getNextRecurrence_ongoingMeeting_returnCurrentRecurrence() { final LocalDateTime current = LocalDateTime.parse(MeetingBuilder.DEFAULT_DATETIME, INPUT_FORMAT); final LocalDateTime startDateTime = LocalDateTime.parse(MeetingBuilder.DEFAULT_DATETIME, INPUT_FORMAT) .minusHours(1); final Meeting meeting = new MeetingBuilder().withIsRecurring("Y") .withDuration("2").withDateTime(startDateTime).build(); assertEquals(meeting.getNextRecurrence(current), startDateTime); } @Test public void getNextRecurrence_newUpcomingMeeting_returnStartDateTime() { final LocalDateTime current = LocalDateTime.parse(MeetingBuilder.DEFAULT_DATETIME, INPUT_FORMAT); final LocalDateTime startDateTime = LocalDateTime.parse(MeetingBuilder.DEFAULT_DATETIME, INPUT_FORMAT).plusDays(2); final Meeting meeting = new MeetingBuilder().withIsRecurring("Y") .withDateTime(startDateTime).build(); assertEquals(meeting.getNextRecurrence(current), startDateTime); } @Test public void getNextRecurrence_elapsedMeeting_returnNextRecurrence() { final LocalDateTime current = LocalDateTime.parse(MeetingBuilder.DEFAULT_DATETIME, INPUT_FORMAT); final LocalDateTime startDateTime = LocalDateTime.parse(MeetingBuilder.DEFAULT_DATETIME, INPUT_FORMAT).minusDays(2); final LocalDateTime nextRecurrence = startDateTime.plusWeeks(1); final Meeting meeting = new MeetingBuilder().withIsRecurring("Y") .withDateTime(startDateTime).build(); assertEquals(meeting.getNextRecurrence(current), nextRecurrence); } @Test public void getNextRecurrence_justElapsedMeeting_returnNextRecurrence() { final LocalDateTime current = LocalDateTime.parse(MeetingBuilder.DEFAULT_DATETIME, INPUT_FORMAT); final LocalDateTime startDateTime = LocalDateTime.parse(MeetingBuilder.DEFAULT_DATETIME, INPUT_FORMAT) .minusHours(2).minusNanos(1); final LocalDateTime nextRecurrence = startDateTime.plusWeeks(1); final Meeting meeting = new MeetingBuilder().withIsRecurring("Y") .withDuration("2").withDateTime(startDateTime).build(); assertEquals(meeting.getNextRecurrence(current), nextRecurrence); } /* * Note: getStartDateTime and getEndDateTime both rely on getNextRecurrence */ @Test public void getStartDateTime_nonRecurringMeeting_returnStartDateTime() { final Meeting firstMeeting = new MeetingBuilder().withIsRecurring("N").build(); assertEquals(firstMeeting.getStartDateTime(), new MeetingDateTime(MeetingBuilder.DEFAULT_DATETIME)); final Meeting minMeeting = new MeetingBuilder().withIsRecurring("N").withDateTime(LocalDateTime.MIN).build(); final Meeting maxMeeting = new MeetingBuilder().withIsRecurring("N").withDateTime(LocalDateTime.MAX).build(); assertEquals(minMeeting.getStartDateTime(), new MeetingDateTime(LocalDateTime.MIN)); assertEquals(maxMeeting.getStartDateTime(), new MeetingDateTime(LocalDateTime.MAX)); } @Test public void getEndDateTime_nonRecurringMeeting_returnEndDateTimeFromStartDateTime() { final Meeting meeting = new MeetingBuilder().withIsRecurring("N").build(); final LocalDateTime startDateTime = LocalDateTime.parse(MeetingBuilder.DEFAULT_DATETIME, INPUT_FORMAT); final MeetingDuration duration = new MeetingDuration(MeetingBuilder.DEFAULT_DURATION); final LocalDateTime firstExpectedEnd = startDateTime.plusMinutes((int) duration.duration * 60); assertEquals(meeting.getEndDateTime(), new MeetingDateTime(firstExpectedEnd)); } @Test public void getTags_modifySet_throwsUnsupportedOperationException() { final Meeting meeting = new MeetingBuilder().build(); assertThrows(UnsupportedOperationException.class, () -> meeting.getTags().add(new Tag("tag"))); } @Test public void equals() { // same values -> returns true final Meeting cs2105Copy = new MeetingBuilder(CS2105).build(); assertTrue(CS2105.equals(cs2105Copy)); // same object -> returns true assertTrue(CS2105.equals(CS2105)); // null -> returns false assertFalse(CS2105.equals(null)); // different type -> returns false assertFalse(CS2105.equals(5)); // different meeting -> returns false assertFalse(CS2105.equals(CS2103)); // different name -> returns false Meeting editedCs2105 = new MeetingBuilder(CS2105).withName(VALID_NAME_TUTORIAL).build(); assertFalse(CS2105.equals(editedCs2105)); // different url -> returns false editedCs2105 = new MeetingBuilder(CS2105).withUrl(VALID_URL_LECTURE).build(); assertFalse(CS2105.equals(editedCs2105)); // different start datetime -> returns false editedCs2105 = new MeetingBuilder(CS2105).withDateTime(VALID_DATETIME_TUTORIAL).build(); assertFalse(CS2105.equals(editedCs2105)); // different duration -> returns false editedCs2105 = new MeetingBuilder(CS2105).withDuration(VALID_DURATION_TUTORIAL).build(); assertFalse(CS2105.equals(editedCs2105)); // different module -> returns false editedCs2105 = new MeetingBuilder(CS2105).withModule(VALID_MODULE_TUTORIAL).build(); assertFalse(CS2105.equals(editedCs2105)); // different recurrence -> returns false editedCs2105 = new MeetingBuilder(CS2105).withIsRecurring(VALID_RECURRING_TUTORIAL).build(); assertFalse(CS2105.equals(editedCs2105)); // different tags -> returns false editedCs2105 = new MeetingBuilder(CS2105).withTags(VALID_TAG_TUTORIAL).build(); assertFalse(CS2105.equals(editedCs2105)); } @Test public void compareTo_differentStartDateTime_earlierThenLater() { final Meeting earlierMeeting = new MeetingBuilder().withIsRecurring("N") .withDateTime(VALID_DATETIME_TUTORIAL).build(); final Meeting laterMeeting = new MeetingBuilder().withIsRecurring("N") .withDateTime(VALID_DATETIME_LECTURE).build(); assertTrue(earlierMeeting.compareTo(laterMeeting) < 0); } @Test public void compareTo_sameStartDifferentDuration_shorterThenLonger() { final Meeting shorterMeeting = new MeetingBuilder().withIsRecurring("N") .withDuration("1").build(); final Meeting longerMeeting = new MeetingBuilder().withIsRecurring("N") .withDuration("2").build(); assertTrue(shorterMeeting.compareTo(longerMeeting) < 0); } }
48.05814
117
0.726591
2d1116e881ff9529646598564759affa32d41af0
13,381
package tests; import global.*; import heap.Heapfile; import heap.Tuple; import iterator.*; import java.io.IOException; class SortFirstSkylineDriver extends TestDriver implements GlobalConst { private static String data1[] = { "raghu", "xbao", "cychan", "leela", "ketola", "soma", "ulloa", "dhanoa", "dsilva", "kurniawa", "dissoswa", "waic", "susanc", "kinc", "marc", "scottc", "yuc", "ireland", "rathgebe", "joyce", "daode", "yuvadee", "he", "huxtable", "muerle", "flechtne", "thiodore", "jhowe", "frankief", "yiching", "xiaoming", "jsong", "yung", "muthiah", "bloch", "binh", "dai", "hai", "handi", "shi", "sonthi", "evgueni", "chung-pi", "chui", "siddiqui", "mak", "tak", "sungk", "randal", "barthel", "newell", "schiesl", "neuman", "heitzman", "wan", "gunawan", "djensen", "juei-wen", "josephin", "harimin", "xin", "zmudzin", "feldmann", "joon", "wawrzon", "yi-chun", "wenchao", "seo", "karsono", "dwiyono", "ginther", "keeler", "peter", "lukas", "edwards", "mirwais", "schleis", "haris", "meyers", "azat", "shun-kit", "robert", "markert", "wlau", "honghu", "guangshu", "chingju", "bradw", "andyw", "gray", "vharvey", "awny", "savoy", "meltz"}; private static String data2[] = { "andyw", "awny", "azat", "barthel", "binh", "bloch", "bradw", "chingju", "chui", "chung-pi", "cychan", "dai", "daode", "dhanoa", "dissoswa", "djensen", "dsilva", "dwiyono", "edwards", "evgueni", "feldmann", "flechtne", "frankief", "ginther", "gray", "guangshu", "gunawan", "hai", "handi", "harimin", "haris", "he", "heitzman", "honghu", "huxtable", "ireland", "jhowe", "joon", "josephin", "joyce", "jsong", "juei-wen", "karsono", "keeler", "ketola", "kinc", "kurniawa", "leela", "lukas", "mak", "marc", "markert", "meltz", "meyers", "mirwais", "muerle", "muthiah", "neuman", "newell", "peter", "raghu", "randal", "rathgebe", "robert", "savoy", "schiesl", "schleis", "scottc", "seo", "shi", "shun-kit", "siddiqui", "soma", "sonthi", "sungk", "susanc", "tak", "thiodore", "ulloa", "vharvey", "waic", "wan", "wawrzon", "wenchao", "wlau", "xbao", "xiaoming", "xin", "yi-chun", "yiching", "yuc", "yung", "yuvadee", "zmudzin"}; private static int NUM_RECORDS = data2.length; private static int LARGE = 1000; private static short REC_LEN1 = 32; private static short REC_LEN2 = 160; private static int SORTPGNUM = 12; public SortFirstSkylineDriver() { super("skylinetest"); } public boolean runTests() { System.out.println("\n" + "Running " + testName() + " tests...." + "\n"); SystemDefs sysdef = new SystemDefs(dbpath, 10000, 10000, "Clock"); // Kill anything that might be hanging around String newdbpath; String newlogpath; String remove_logcmd; String remove_dbcmd; String remove_cmd = "/bin/rm -rf "; newdbpath = dbpath; newlogpath = logpath; remove_logcmd = remove_cmd + logpath; remove_dbcmd = remove_cmd + dbpath; // Commands here is very machine dependent. We assume // user are on UNIX system here try { Runtime.getRuntime().exec(remove_logcmd); Runtime.getRuntime().exec(remove_dbcmd); } catch (IOException e) { System.err.println("" + e); } remove_logcmd = remove_cmd + newlogpath; remove_dbcmd = remove_cmd + newdbpath; //This step seems redundant for me. But it's in the original //C++ code. So I am keeping it as of now, just in case I //I missed something try { Runtime.getRuntime().exec(remove_logcmd); Runtime.getRuntime().exec(remove_dbcmd); } catch (IOException e) { System.err.println("" + e); } //Run the tests. Return type different from C++ boolean _pass = runAllTests(); //Clean up again try { Runtime.getRuntime().exec(remove_logcmd); Runtime.getRuntime().exec(remove_dbcmd); } catch (IOException e) { System.err.println("" + e); } System.out.println("\n" + "..." + testName() + " tests "); System.out.println(_pass == OK ? "completely successfully" : "failed"); System.out.println(".\n\n"); return _pass; } protected boolean test1() { System.out.println("------------------------ TEST 1 --------------------------"); System.out.println("\n -- Testing SortFirstSky on correlated tuples -- "); boolean status = OK; AttrType[] attrType = new AttrType[2]; attrType[0] = new AttrType(AttrType.attrReal); attrType[1] = new AttrType(AttrType.attrReal); short[] attrSize = new short[0]; TupleOrder[] order = new TupleOrder[2]; order[0] = new TupleOrder(TupleOrder.Ascending); order[1] = new TupleOrder(TupleOrder.Descending); Tuple t = new Tuple(); try { t.setHdr((short) 2, attrType, attrSize); } catch (Exception e) { System.err.println("*** error in Tuple.setHdr() ***"); status = FAIL; e.printStackTrace(); } int size = t.size(); RID rid; Heapfile f = null; try { f = new Heapfile("test1.in"); } catch (Exception e) { status = FAIL; e.printStackTrace(); } t = new Tuple(size); try { t.setHdr((short) 2, attrType, attrSize); } catch (Exception e) { status = FAIL; e.printStackTrace(); } float inum1 =0; float inum2 =0; float fnum = 0.1567f; int count = 0; int j = 10; System.out.println("\n -- Generating correlated tuples -- "); int num_elements = 20; for (int i = 0; i < num_elements; i++) { // setting fields inum1 = i+1; inum2 = i+1; try { t.setFloFld(1, inum1); t.setFloFld(2, inum2); } catch (Exception e) { status = FAIL; e.printStackTrace(); } try { rid = f.insertRecord(t.returnTupleByteArray()); } catch (Exception e) { status = FAIL; e.printStackTrace(); } System.out.println("fld1 = " + inum1 + " fld2 = " + inum2); } // create an iterator by open a file scan FldSpec[] projlist = new FldSpec[2]; RelSpec rel = new RelSpec(RelSpec.outer); projlist[0] = new FldSpec(rel, 1); projlist[1] = new FldSpec(rel, 2); FileScan fscan = null; // Sort "test3.in" on the int attribute (field 3) -- Ascending System.out.println("\n -- Skyline candidates -- "); try { fscan = new FileScan("test1.in", attrType, attrSize, (short) 2, 2, projlist, null); } catch (Exception e) { status = FAIL; e.printStackTrace(); } int[] pref_list = new int[] {1,2}; SortFirstSky sort = null; try { sort = new SortFirstSky(attrType, (short) 2, attrSize, fscan, "test1.in", pref_list, 2, 5); } catch (Exception e) { status = FAIL; e.printStackTrace(); } count = 0; t = null; try { t = sort.get_next(); } catch (Exception e) { status = FAIL; e.printStackTrace(); } while (t != null) { try { System.out.println("fld1 = " + t.getFloFld(1) + " fld2 = " + t.getFloFld(2)); } catch (Exception e) { status = FAIL; e.printStackTrace(); } count++; try { t = sort.get_next(); } catch (Exception e) { status = FAIL; e.printStackTrace(); } } // clean up try { sort.close(); } catch (Exception e) { status = FAIL; e.printStackTrace(); } System.out.println("------------------- TEST 1 completed ---------------------\n"); return status; } protected boolean test2() { System.out.println("------------------------ TEST 2 --------------------------"); System.out.println("\n -- Testing SortFirstSky on anti-correlated tuples -- "); boolean status = OK; AttrType[] attrType = new AttrType[2]; attrType[0] = new AttrType(AttrType.attrReal); attrType[1] = new AttrType(AttrType.attrReal); short[] attrSize = new short[0]; TupleOrder[] order = new TupleOrder[2]; order[0] = new TupleOrder(TupleOrder.Ascending); order[1] = new TupleOrder(TupleOrder.Descending); Tuple t = new Tuple(); try { t.setHdr((short) 2, attrType, attrSize); } catch (Exception e) { System.err.println("*** error in Tuple.setHdr() ***"); status = FAIL; e.printStackTrace(); } int size = t.size(); RID rid; Heapfile f = null; try { f = new Heapfile("test2.in"); } catch (Exception e) { status = FAIL; e.printStackTrace(); } t = new Tuple(size); try { t.setHdr((short) 2, attrType, attrSize); } catch (Exception e) { status = FAIL; e.printStackTrace(); } float inum1 =0; float inum2 =0; float fnum = 0.1567f; int count = 0; int j = 10; System.out.println("\n -- Generating anti-correlated tuples -- "); int num_elements = 7000; for (int i = 0; i < num_elements; i++) { // setting fields inum1 = i+1; inum2 = num_elements-i; try { t.setFloFld(1, inum1); t.setFloFld(2, inum2); } catch (Exception e) { status = FAIL; e.printStackTrace(); } try { rid = f.insertRecord(t.returnTupleByteArray()); } catch (Exception e) { status = FAIL; e.printStackTrace(); } System.out.println("fld1 = " + inum1 + " fld2 = " + inum2); } // create an iterator by open a file scan FldSpec[] projlist = new FldSpec[2]; RelSpec rel = new RelSpec(RelSpec.outer); projlist[0] = new FldSpec(rel, 1); projlist[1] = new FldSpec(rel, 2); FileScan fscan = null; // Sort "test3.in" on the int attribute (field 3) -- Ascending System.out.println("\n -- Skyline candidates -- "); try { fscan = new FileScan("test2.in", attrType, attrSize, (short) 2, 2, projlist, null); } catch (Exception e) { status = FAIL; e.printStackTrace(); } int[] pref_list = new int[] {1,2}; SortFirstSky sort = null; try { sort = new SortFirstSky(attrType, (short) 2, attrSize, fscan, "test2.in", pref_list, 2, 5); } catch (Exception e) { status = FAIL; e.printStackTrace(); } count = 0; t = null; try { t = sort.get_next(); } catch (Exception e) { status = FAIL; e.printStackTrace(); } while (t != null) { try { System.out.println("fld1 = " + t.getFloFld(1) + " fld2 = " + t.getFloFld(2)); } catch (Exception e) { status = FAIL; e.printStackTrace(); } count++; try { t = sort.get_next(); } catch (Exception e) { status = FAIL; e.printStackTrace(); } } // clean up try { sort.close(); } catch (Exception e) { status = FAIL; e.printStackTrace(); } System.out.println("------------------- TEST 2 completed ---------------------\n"); return status; } protected boolean test3() { return true; } protected boolean test4() { return true; } protected boolean test5() { return true; } protected boolean test6() { return true; } protected String testName() { return "Skyline"; } } public class SortFirstSkylineTest { public static void main(String argv[]) { boolean sortstatus; SortFirstSkylineDriver sortt = new SortFirstSkylineDriver(); sortstatus = sortt.runTests(); if (sortstatus != true) { System.out.println("Error ocurred during sorting tests"); } else { System.out.println("Skyline tests completed successfully"); } } }
30.411364
103
0.491966
ce09a2a175dda24a6e0d64bb5be9ef2eada5f346
156
package com.example.android.newsfeed; /** * Created by acer on 10-03-2018. */ public interface OnItemClickListener { void OnItemClick(News news); }
15.6
38
0.717949
695c37ca72155fd7dd84bcc7e919b06e73b90c23
586
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.jmonitoring.standardPlots.timeSeries; import de.jmonitoring.standardPlots.common.ChartDescriber; import java.util.List; import de.jmonitoring.utils.intervals.DateInterval; /** * * @author togro */ public class TimeSeriesChartDescriber extends ChartDescriber<TimeSeriesLooks> { public TimeSeriesChartDescriber(String title, DateInterval dateInterval, List<TimeSeriesLooks> collection) { super(title, collection); setDateInterval(dateInterval); } }
25.478261
112
0.767918
51153b462e960f3333d9a759fed9d25d6e1f9566
145
package com.soo.ify.request; public interface RequestExceptionHanlder { boolean handleException(RequestException requestException); }
18.125
63
0.793103
6a39520198b96aff8c6c1491102854cf5c3ef0ae
6,659
import java.io.*; import org.apache.http.HttpEntity; //import org.apache.http.HttpStatus; import org.apache.http.HttpResponse; //import org.apache.http.client.ClientProtocolException; //import org.apache.http.impl.DefaultHttpRequestFactory; //import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.client.methods.HttpGet; //import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.HttpHost; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; //import sun.management.resources.agent; import static java.lang.System.*; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class HTMLPageParser { public static void main(String[] args) throws Exception{ // write your code here Connect connect=new Connect(url,origin,url,user_agent); HttpResponse response=connect.httpClient.execute(connect.get); HttpEntity entity=response.getEntity(); {InputStream in=entity.getContent(); //InputStream in=null; //保存到本地 SaveToLocal(in,filePath,"1.html");} String crsf=Get_crsf(in); if(!connect.SetBody(crsf,body)){ System.exit(-1); } else { //HttpResponse response=connect.httpClient.execute(connect.post); String result = EntityUtils.toString(response.getEntity(),"UTF-8"); while (response.getStatusLine().getStatusCode()==302) { response=connect.httpClient.execute(connect.post); result = EntityUtils.toString(response.getEntity(),"UTF-8"); } //print_res(response); { // InputStream in2=response.getEntity().getContent(); // SaveToLocal(in2,filePath,"2.html"); } response=connect.httpClient.execute(connect.httpHost,new HttpGet("https://www.docdroid.net/cUX0hjn/arianne.docx")); { InputStream in=response.getEntity().getContent(); SaveToLocal(in,filePath,"3.html"); } } } private static String filePath = "E:\\wyc\\Documents\\程序\\Java\\webpage_catcher\\"; private static String fileName="crawlPage.html"; private static String url = "https://www.docdroid.net/cUX0hjn/password"; private static String origin="https://www.docdroid.net"; private static String user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"; private static String body="{\"password\":\"Sunspear\",\"errors\":\"{errors:{}}\",\"busy\":\"true\",\"successful\":\"false\"}"; private static void SaveToLocal(InputStream ins, String filePath, String fileName) throws IOException { File file=new File(filePath); if (!file.exists()){ file.mkdirs(); } DataOutputStream out=new DataOutputStream(new FileOutputStream(new File(filePath+fileName))); int result; while ((result=ins.read())!=-1){ out.write(result); } ins.close(); out.flush(); out.close(); } private static void print_res(HttpResponse res) throws Exception{ System.out.println("状态码"+res.getStatusLine().getStatusCode()); HttpEntity entity=res.getEntity(); System.out.println(EntityUtils.toString(entity,"utf-8")); } private static String Get_crsf(InputStream in) { String str=(new Scanner(System.in)).nextLine(); return str; } public static class Connect{ public static HttpGet get; public static HttpPost post; public static CloseableHttpClient httpClient; public static HttpHost httpHost; public static void SetHttpClient(String u) throws Exception{ } public Connect(String u,String o,String r,String ua) { String url=u; try { URL _url= new URL(u); httpHost=new HttpHost(_url.getHost(), _url.getPort(),"https"); }catch (Exception e){ //do nothing!!! } httpClient= HttpClients.createDefault(); get = new HttpGet(url); post = new HttpPost(url); //设置请求头 if(!SetPost(o,r,ua)){ System.exit(-1); } } private boolean SetPost(String origin,String referer,String user_agent){ //post.setHeader("User-Agent",user_agent); return SetPost(origin,referer); } private boolean SetPost(String origin,String referer){ post.setHeader("Accept","*/*"); post.setHeader("Origin",origin); post.setHeader("Referer",referer); post.setHeader("Sec-Fetch-Mode","cors"); post.setHeader("Content-Type","application/json;charset=UTF-8"); post.setHeader("X-Requested-With","XMLHttpRequest"); post.setHeader("Host","www.docdroid.net"); // post.setHeader("x-csrf-token",csrf); // post.setEntity(new StringEntity(body,"utf-8")); if(post.getHeaders("Origin").length>0){ return true; } return false; } private boolean SetBody(String crsf,String body){ post.setHeader("X-CSRF-TOKEN",crsf); //post.setHeader("X-Requested-With","XMLHttpRequest"); StringEntity se=new StringEntity(body,"utf-8"); se.setContentType("text/json"); post.setEntity(se); // List<NameValuePair> nvps=new ArrayList<NameValuePair>(); // nvps.add(new BasicNameValuePair("password","Sunspear")); // nvps.add(new BasicNameValuePair("errors","{errors:{}}")); // nvps.add(new BasicNameValuePair("busy","true")); // nvps.add(new BasicNameValuePair("successful","false")); // try { // post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // }catch (UnsupportedEncodingException e){ // return false; // } if (post.getHeaders("X-CSRF-TOKEN").length>0) { return true; } return false; } } }
38.270115
156
0.614056
a53115a43b6c029d81c4f27de5fd4aabd32d8752
1,128
package com.biemo.cloud.bbs.modular.mapper; import java.util.List; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.biemo.cloud.bbs.modular.domain.BEmailCode; import org.apache.ibatis.annotations.CacheNamespace; /** * Mapper接口 * * @author makesoft * @date 2021-08-11 */ @CacheNamespace public interface BEmailCodeMapper extends BaseMapper<BEmailCode> { /** * 查询 * * @param id ID * @return */ BEmailCode selectBEmailCodeById(Long id); /** * 查询列表 * * @param bEmailCode * @return 集合 */ List<BEmailCode> selectBEmailCodeList(BEmailCode bEmailCode); /** * 新增 * * @param bEmailCode * @return 结果 */ int insertBEmailCode(BEmailCode bEmailCode); /** * 修改 * * @param bEmailCode * @return 结果 */ int updateBEmailCode(BEmailCode bEmailCode); /** * 删除 * * @param id ID * @return 结果 */ int deleteBEmailCodeById(Long id); /** * 批量删除 * * @param ids 需要删除的数据ID * @return 结果 */ int deleteBEmailCodeByIds(Long[] ids); }
17.090909
65
0.593085
f18d035847b1c8e392072a15db8112456649de40
1,577
package com.example.feedforfree.common; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.example.feedforfree.R; import com.example.feedforfree.User.Login; import com.example.feedforfree.User.UserDashboard; public class MainActivity extends AppCompatActivity { private static int Splash_timer =5000; //hooks ImageView backgroundImage; //animations Animation sideAnim,bottomAnim; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); //hooks backgroundImage=findViewById(R.id.imageView2); //animation sideAnim = AnimationUtils.loadAnimation(this,R.anim.side_anim); bottomAnim = AnimationUtils.loadAnimation(this,R.anim.bottom_anim); //set animation on aliment backgroundImage.setAnimation(sideAnim); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent= new Intent(MainActivity.this, Login.class); startActivity(intent); } },Splash_timer); } }
25.031746
116
0.710843
f0b6962860c8fc91b3e9b931c0a032db09da4881
3,646
package seedu.system.logic.parser; import static seedu.system.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.system.logic.commands.CommandTestUtil.DOB_DESC_BOB; import static seedu.system.logic.commands.CommandTestUtil.GENDER_DESC_BOB; import static seedu.system.logic.commands.CommandTestUtil.INVALID_DOB_DESC; import static seedu.system.logic.commands.CommandTestUtil.INVALID_NAME_DESC; import static seedu.system.logic.commands.CommandTestUtil.NAME_DESC_AMY; import static seedu.system.logic.commands.CommandTestUtil.NAME_DESC_BOB; import static seedu.system.logic.commands.CommandTestUtil.PREAMBLE_NON_EMPTY; import static seedu.system.logic.commands.CommandTestUtil.PREAMBLE_WHITESPACE; import static seedu.system.logic.commands.CommandTestUtil.VALID_DOB_BOB; import static seedu.system.logic.commands.CommandTestUtil.VALID_GENDER_BOB; import static seedu.system.logic.commands.CommandTestUtil.VALID_NAME_BOB; import static seedu.system.logic.parser.CommandParserTestUtil.assertParseFailure; import static seedu.system.logic.parser.CommandParserTestUtil.assertParseSuccess; import static seedu.system.testutil.TypicalPersons.BOB; import org.junit.jupiter.api.Test; import seedu.system.logic.commands.outofsession.AddPersonCommand; import seedu.system.logic.parser.outofsession.AddPersonCommandParser; import seedu.system.model.person.CustomDate; import seedu.system.model.person.Name; import seedu.system.model.person.Person; import seedu.system.testutil.PersonBuilder; public class AddPersonCommandParserTest { private AddPersonCommandParser parser = new AddPersonCommandParser(); @Test public void parse_allFieldsPresent_success() { Person expectedPerson = new PersonBuilder(BOB).build(); // whitespace only preamble assertParseSuccess(parser, PREAMBLE_WHITESPACE + NAME_DESC_BOB + DOB_DESC_BOB + GENDER_DESC_BOB, new AddPersonCommand(expectedPerson)); // multiple names - last name accepted assertParseSuccess(parser, NAME_DESC_AMY + NAME_DESC_BOB + DOB_DESC_BOB + GENDER_DESC_BOB, new AddPersonCommand(expectedPerson)); } @Test public void parse_compulsoryFieldMissing_failure() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddPersonCommand.MESSAGE_USAGE); // missing name prefix assertParseFailure(parser, VALID_NAME_BOB + DOB_DESC_BOB + GENDER_DESC_BOB, expectedMessage); // missing DOB prefix assertParseFailure(parser, NAME_DESC_BOB + VALID_DOB_BOB + GENDER_DESC_BOB, expectedMessage); // missing gender prefix assertParseFailure(parser, NAME_DESC_BOB + DOB_DESC_BOB + VALID_GENDER_BOB , expectedMessage); // all prefixes missing assertParseFailure(parser, VALID_NAME_BOB + VALID_DOB_BOB + VALID_GENDER_BOB, expectedMessage); } @Test public void parse_invalidValue_failure() { // invalid name assertParseFailure(parser, INVALID_NAME_DESC + DOB_DESC_BOB + GENDER_DESC_BOB, Name.MESSAGE_CONSTRAINTS); // invalid DOB assertParseFailure(parser, NAME_DESC_BOB + INVALID_DOB_DESC + GENDER_DESC_BOB, CustomDate.MESSAGE_CONSTRAINTS); // two invalid values, only first invalid value reported assertParseFailure(parser, INVALID_NAME_DESC + INVALID_DOB_DESC + GENDER_DESC_BOB, Name.MESSAGE_CONSTRAINTS); // non-empty preamble assertParseFailure(parser, PREAMBLE_NON_EMPTY + NAME_DESC_BOB + DOB_DESC_BOB + GENDER_DESC_BOB, String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddPersonCommand.MESSAGE_USAGE)); } }
45.575
119
0.786067
3de083286b921542d0681981fc44bc483ac38762
3,406
package castle.comp3021.assignment.gui.controllers; import castle.comp3021.assignment.protocol.exception.ResourceNotFoundException; import javafx.scene.image.Image; import org.jetbrains.annotations.NotNull; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; /** * Helper class for loading resources from the filesystem. */ public class ResourceLoader { /** * Path to the resources directory. */ @NotNull private static final Path RES_PATH; static { // TODO: Initialize RES_PATH-DONE // replace null to the actual path RES_PATH = Paths.get("C:\\Users\\pang\\IdeaProjects\\COMP3021-2020Fall-PA2-Student-Version\\src\\main\\resources").toAbsolutePath(); } /** * Retrieves a resource file from the resource directory. * * @param relativePath Path to the resource file, relative to the root of the resource directory. * @return Absolute path to the resource file. * @throws ResourceNotFoundException If the file cannot be found under the resource directory. */ @NotNull public static String getResource(@NotNull final String relativePath){ // TODO-DONE try { Paths.get(RES_PATH.resolve(relativePath).toString()); } catch (InvalidPathException e){ throw new ResourceNotFoundException("the file cannot be found under the resource directory"); } //System.out.println(RES_PATH.resolve(relativePath).toString()); return RES_PATH.resolve(relativePath).toFile().toURI().toString(); } /** * Return an image {@link Image} object * @param typeChar a character represents the type of image needed. * - 'K': white knight (whiteK.png) * - 'A': white archer (whiteA.png) * - 'k': black knight (blackK.png) * - 'a': black archer (blackA.png) * - 'c': central x (center.png) * - 'l': light board (lightBoard.png) * - 'd': dark board (darkBoard.png) * @return an image */ @NotNull public static Image getImage(char typeChar) { // TODO-DONE? Image image; String loc; switch (typeChar){ case 'K': loc = getResource("assets/images/whiteK.png"); image = new Image(loc); break; case 'A': loc = getResource("assets/images/whiteA.png"); image = new Image(loc); break; case 'k': loc = getResource("assets/images/blackK.png"); image = new Image(loc); break; case 'a': loc = getResource("assets/images/blackA.png"); image = new Image(loc); break; case 'c': loc = getResource("assets/images/center.png"); image = new Image(loc); break; case 'l': loc = getResource("assets/images/lightBoard.png"); image = new Image(loc); break; default: case 'd': loc = getResource("assets/images/darkBoard.png"); image = new Image(loc); break; } return image; } }
34.755102
140
0.556958
18b5fb82421a58685a212c4ba5f3fcdd688f2171
7,927
/* * Copyright 2017 Adobe Systems Incorporated * * 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.adobe.cq.testing.junit.rules; import com.adobe.cq.testing.client.CQClient; import org.apache.commons.io.IOUtils; import org.apache.http.HttpStatus; import org.apache.sling.testing.clients.ClientException; import org.apache.sling.testing.clients.SlingHttpResponse; import org.apache.sling.testing.clients.util.ResourceUtil; import org.apache.sling.testing.junit.rules.instance.Instance; import org.junit.rules.ExternalResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.UUID; import static org.apache.http.HttpStatus.SC_CREATED; /** * Create a new page. This rule can be sub-classed to specify the parent page and the template of the newly created * page. Subclasses can also specify which client to use or which server to target when a new page is created. */ public class Page extends ExternalResource { private Logger logger = LoggerFactory.getLogger(Page.class); // singleton value; true if the target test instances have been prepared once since the class was loaded // this is used to run prepare() once per classloader / "suite" execution private static boolean prepared = false; private static final String SITE_ROOT_PATH = "/content/test-site"; private static final String TEMPLATE_ROOT_PATH = "/conf/test-site"; private static final String TEMPLATE_PATH = "/conf/test-site/settings/wcm/templates/content-page"; private final Instance quickstartRule; private ThreadLocal<String> parentPath = new ThreadLocal<String>() { @Override protected String initialValue() { return initialParentPath(); } }; private ThreadLocal<String> name = new ThreadLocal<String>() { @Override protected String initialValue() { return initialName(); } }; private ThreadLocal<String> templatePath = new ThreadLocal<String>() { @Override protected String initialValue() { return initialTemplatePath(); } }; public Page(Instance quickstartRule) { super(); this.quickstartRule = quickstartRule; } @Override protected void before() throws ClientException { prepare(); SlingHttpResponse response = getClient().createPage(getName(), getTitle(), getParentPath(), getTemplatePath(), HttpStatus.SC_OK); logger.info("Created page at {}", response.getSlingLocation()); } @Override protected void after() { try { getClient().deletePage(new String[]{getPath()}, true, false); logger.info("Deleted page at {}", getPath()); } catch (Exception e) { logger.error("Unable to delete the page", e); } } /** * The initial parent path to be used when creating the page * This implementation returns {@value SITE_ROOT_PATH} * You can override this with dynamic names for each threads * @return the parent path used to create the page */ protected String initialParentPath() { return SITE_ROOT_PATH; } /** * The initial page name to be used when creating the page * This implementation returns "testpage_[randomUUID]" * You can override this with dynamic names for each thread * * @return the page name used to create the page */ protected String initialName() { return "testpage_" + UUID.randomUUID(); } /** * The initial template path to be used when creating the page * This implementation returns {@value TEMPLATE_PATH} * You can override this with dynamic names for each threads * * @return the template path used to create the page */ protected String initialTemplatePath() { return TEMPLATE_PATH; } /** * The client to use to create and delete this page. The default implementation creates a {@link CQClient}. * The default implementation also uses the default admin user. * * @return The client to use to create and delete this page. * @throws ClientException if the client cannot be retrieved */ protected CQClient getClient() throws ClientException { return quickstartRule.getAdminClient(CQClient.class); } /** * Method to be called before creating the page. * You can override this to perform custom operations before creating the page. * This implementation creates, if needed, the test template and site. * * @throws ClientException if the content cannot be created */ protected void prepare() throws ClientException { if (Page.prepared) return; if (!getClient().exists(TEMPLATE_ROOT_PATH)) { try { InputStream templateStream = ResourceUtil.getResourceAsStream("/com/adobe/cq/testing/junit/rules/template.json"); String template = IOUtils.toString(templateStream, StandardCharsets.UTF_8); getClient().importContent(TEMPLATE_ROOT_PATH, "json", template, SC_CREATED); logger.info("Created test template in {}", TEMPLATE_ROOT_PATH); } catch (IOException e) { throw new ClientException("Failed to create test template.", e); } } if (!getClient().exists(SITE_ROOT_PATH)) { try { InputStream siteStream = ResourceUtil.getResourceAsStream("/com/adobe/cq/testing/junit/rules/site.json"); String site = IOUtils.toString(siteStream, StandardCharsets.UTF_8); getClient().importContent(SITE_ROOT_PATH, "json", site, SC_CREATED); logger.info("Created test site {}", SITE_ROOT_PATH); } catch (IOException e) { throw new ClientException("Failed to create test site.", e); } } // set static prepared value Page.prepared = true; } /** * The title of this page. The default implementation returns the value {@code "Test Page"}. * * @return The title of this page. */ public String getTitle() { return "Test Page"; } /** * The node name of this page. The default implementation returns the value of {@link #initialName()}. * * @return The node name of this page. */ public String getName() { return name.get(); } /** * The path of the parent of this page. The default implementation returns the value {@link #initialParentPath()} * * @return The parent path of this page. The path must be absolute and must not end with a slash. */ public String getParentPath() { return parentPath.get(); } /** * The path of the template of this page. The default implementation returns the value {@link #initialTemplatePath()} * * @return The parent path of this page. The path must be a valid template path. */ public String getTemplatePath() { return templatePath.get(); } /** * The absolute path of this page. * * @return The absolute path of the page. */ public final String getPath() { return getParentPath() + "/" + getName(); } }
35.388393
137
0.65813
a43852b2947d529286b2142332d374ae65bf98ae
2,387
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.credit.isdastandardmodel.fastcalibration; import com.opengamma.analytics.financial.credit.isdastandardmodel.CDSCoupon; import com.opengamma.analytics.financial.credit.isdastandardmodel.ISDACompliantCreditCurve; import com.opengamma.analytics.financial.credit.isdastandardmodel.ISDACompliantYieldCurve; /** * */ public class CouponOnlyElement { private final double _riskLessValue; private final double _effEnd; private final int _creditCurveKnot; public CouponOnlyElement(final CDSCoupon coupon, final ISDACompliantYieldCurve yieldCurve, final int creditCurveKnot) { _riskLessValue = coupon.getYearFrac() * yieldCurve.getDiscountFactor(coupon.getPaymentTime()); _effEnd = coupon.getEffEnd(); _creditCurveKnot = creditCurveKnot; } public double pv(final ISDACompliantCreditCurve creditCurve) { return _riskLessValue * creditCurve.getDiscountFactor(_effEnd); } public double[] pvAndSense(final ISDACompliantCreditCurve creditCurve) { final double pv = _riskLessValue * creditCurve.getDiscountFactor(_effEnd); final double pvSense = -pv * creditCurve.getSingleNodeRTSensitivity(_effEnd, _creditCurveKnot); return new double[] {pv, pvSense }; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _creditCurveKnot; long temp; temp = Double.doubleToLongBits(_effEnd); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(_riskLessValue); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final CouponOnlyElement other = (CouponOnlyElement) obj; if (_creditCurveKnot != other._creditCurveKnot) { return false; } if (Double.doubleToLongBits(_effEnd) != Double.doubleToLongBits(other._effEnd)) { return false; } if (Double.doubleToLongBits(_riskLessValue) != Double.doubleToLongBits(other._riskLessValue)) { return false; } return true; } }
32.256757
121
0.718056
8a26a1ae21542c08afa81ee011297e54b0fa19db
1,328
package com.barmpas.upliftme.UserActionData; import android.net.Uri; import android.provider.BaseColumns; /** * The contract class for the local SQLite Database class where the user stores the action. * @author Konstantinos Barmpas. */ public final class UserContract { /** * The app's authority */ public static final String CONTENT_AUTHORITY = "com.barmpas.upliftme"; /** * The uri for the provider */ public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); /** * The title of the table in the SQL Database */ public static final String PATH_USER = "user"; /** * The constructor of the contract */ private UserContract() {} /** * Connects contract to the SQL Database columns */ public static final class UserEntry implements BaseColumns { public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_USER); public final static String TABLE_NAME = "users"; public final static String _ID = BaseColumns._ID; public final static String COLUMN_DATE = "date"; public final static String COLUMN_GOAL = "goal"; public final static String COLUMN_ACTIONS = "actions"; public final static String COLUMN_POINTS = "points"; } }
32.390244
96
0.677711
ebe82870f3cd03db81e95a4668de75f9f9d7186f
441
package com.squarespace.cldrengine.internal; import java.util.List; import com.squarespace.cldrengine.parsing.WrapperPattern; public interface AbstractValue<R> { int length(); void add(String type, String value); String get(int number); void append(R value); void insert(int i, String type, String value); R render(); void reset(); R join(List<R> elems); void wrap(WrapperPattern pattern, List<R> args); R empty(); }
22.05
57
0.721088
0f0ba36a12a7b76aaffff8dfdc9243fc1bed769b
8,239
package com.marklogic.envision.config; import com.marklogic.appdeployer.AppConfig; import com.marklogic.client.DatabaseClient; import com.marklogic.client.eval.EvalResultIterator; import com.marklogic.client.ext.DatabaseClientConfig; import com.marklogic.client.ext.SecurityContextType; import com.marklogic.envision.hub.HubClient; import com.marklogic.envision.hub.impl.HubClientImpl; import com.marklogic.envision.hub.impl.MultiTenantProjectImpl; import com.marklogic.hub.DatabaseKind; import com.marklogic.hub.HubProject; import com.marklogic.hub.impl.HubConfigImpl; import com.marklogic.hub.impl.HubProjectImpl; import com.marklogic.mgmt.ManageClient; import com.marklogic.mgmt.ManageConfig; import com.marklogic.mgmt.admin.AdminConfig; import com.marklogic.mgmt.admin.AdminManager; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import javax.annotation.PostConstruct; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; @Configuration @PropertySource({"classpath:application.properties"}) public class EnvisionConfig { @Value("${envision.autoInstall:true}") public boolean autoInstall; @Value("${marklogic.host:localhost}") public String markLogicHost; @Value("${marklogic.port:8002}") public Integer markLogicPort; @Value("${marklogic.managePort:8002}") public Integer markLogicManagePort; @Value("${marklogic.adminPort:8001}") public Integer markLogicAdminPort; @Value("${marklogic.username:admin}") public String marklogicUsername; @Value("${marklogic.password:admin}") public String marklogicPassword; @Value("${marklogic.database:}") public String marklogicDatabase; @Value("${dhfDir:.}") public File dhfDir; @Value("${dhfEnv:local}") public String dhfEnv; private boolean isMultiTenant; public boolean isMultiTenant() { return isMultiTenant; } @Value("${envision.multiTenant:false}") public void setMultiTenant(boolean multiTenant) { isMultiTenant = multiTenant; } private final Environment environment; private final HubConfigImpl hubConfig; private final HubProject hubProject; public HubConfigImpl getHubConfig() { return hubConfig; } @Autowired EnvisionConfig(Environment environment) { this.environment = environment; this.hubProject = new HubProjectImpl(); this.hubConfig = new HubConfigImpl(hubProject); } public HubClient newAdminHubClient() { return newHubClient(marklogicUsername, marklogicPassword); } public HubClient newHubClient(String username, String password) { HubConfigImpl hubConfig = newHubConfig(username, password); Map<DatabaseKind, String> databaseNames = new HashMap<>(); DatabaseKind[] kinds = new DatabaseKind[]{ DatabaseKind.STAGING, DatabaseKind.FINAL, DatabaseKind.JOB, DatabaseKind.MODULES, DatabaseKind.STAGING_TRIGGERS, DatabaseKind.STAGING_SCHEMAS, DatabaseKind.FINAL_TRIGGERS, DatabaseKind.FINAL_SCHEMAS }; for(DatabaseKind kind: kinds) { databaseNames.put(kind, hubConfig.getDbName(kind)); } return new HubClientImpl(hubConfig, databaseNames, this.isMultiTenant()); } private HubConfigImpl newHubConfig(String username, String password) { HubProject hp = hubProject; if (isMultiTenant) { hp = new MultiTenantProjectImpl(hubProject, username); } HubConfigImpl hubConfig = new HubConfigImpl(hp); setupHubConfig(hubConfig, username, password); return hubConfig; } public HubConfigImpl getAdminHubConfig() { return this.hubConfig; } public DatabaseClient newAdminFinalClient() { HubConfigImpl hubConfig = newHubConfig(marklogicUsername, marklogicPassword); AppConfig appConfig = hubConfig.getAppConfig(); DatabaseClientConfig config = new DatabaseClientConfig(appConfig.getHost(), hubConfig.getPort(DatabaseKind.FINAL), hubConfig.getMlUsername(), hubConfig.getMlPassword()); config.setSecurityContextType(SecurityContextType.valueOf(hubConfig.getAuthMethod(DatabaseKind.FINAL).toUpperCase())); config.setSslHostnameVerifier(hubConfig.getSslHostnameVerifier(DatabaseKind.FINAL)); config.setSslContext(hubConfig.getSslContext(DatabaseKind.FINAL)); config.setCertFile(hubConfig.getCertFile(DatabaseKind.FINAL)); config.setCertPassword(hubConfig.getCertPassword(DatabaseKind.FINAL)); config.setExternalName(hubConfig.getExternalName(DatabaseKind.FINAL)); config.setTrustManager(hubConfig.getTrustManager(DatabaseKind.FINAL)); if (hubConfig.getIsHostLoadBalancer()) { config.setConnectionType(DatabaseClient.ConnectionType.GATEWAY); } return appConfig.getConfiguredDatabaseClientFactory().newDatabaseClient(config); } @PostConstruct public void configureHub() { setupHubConfig(hubConfig, marklogicUsername, marklogicPassword); } private void setupHubConfig(HubConfigImpl hubConfig, String username, String password) { try { String projectDir = dhfDir.getCanonicalPath(); hubProject.createProject(projectDir); String envName = dhfEnv; if (envName == null || envName.isEmpty()) { envName = "local"; } hubConfig.withPropertiesFromEnvironment(envName); hubConfig.applyProperties(buildPropertySource(username, password)); hubConfig.setMlUsername(username); hubConfig.setMlPassword(password); if (isMultiTenant()) { String roleName = DigestUtils.md5Hex(username); hubConfig.setEntityModelPermissions(String.format("%s,read,%s,update", roleName, roleName)); } hubConfig.setHost(markLogicHost); } catch(Exception e) { throw new RuntimeException(e); } } /** * Construct a PropertySource based on the properties in the Spring Boot environment plus the given username and * password, which are supplied when a user authenticates. * * @param username * @param password * @return */ protected com.marklogic.mgmt.util.PropertySource buildPropertySource(String username, String password) { Properties primaryProperties = new Properties(); primaryProperties.setProperty("mlUsername", username); primaryProperties.setProperty("mlPassword", password); return propertyName -> { String value = primaryProperties.getProperty(propertyName); if (value != null) { return value; } return environment.getProperty(propertyName); }; } public DatabaseClient getClient() { DatabaseClientConfig config = new DatabaseClientConfig(markLogicHost, markLogicPort, marklogicUsername, marklogicPassword); config.setSecurityContextType(SecurityContextType.DIGEST); if (marklogicDatabase.length() > 0) { config.setDatabase(marklogicDatabase); } AppConfig appConfig = new AppConfig(); appConfig.setHost(markLogicHost); return appConfig.getConfiguredDatabaseClientFactory().newDatabaseClient(config); } public ManageClient getManageClient() { ManageConfig config = new ManageConfig(markLogicHost, markLogicManagePort, marklogicUsername, marklogicPassword); return new ManageClient(config); } public AdminManager getAdminManager() { AdminConfig config = new AdminConfig(markLogicHost, markLogicAdminPort, marklogicUsername, marklogicPassword); return new AdminManager(config); } public DatabaseClient getModulesClient() { return hubConfig.newModulesDbClient(); } public String getInstalledVersion() { try { EvalResultIterator result = hubConfig.newModulesDbClient().newServerEval().javascript("require('/envision/config.sjs').version").eval(); if (result.hasNext()) { return result.next().getString(); } } catch(Exception e) {} return null; } public String getVersion() { Properties properties = new Properties(); try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("version.properties")) { properties.load(inputStream); } catch (IOException e) { throw new RuntimeException(e); } String version = (String)properties.get("version"); // this lets debug builds work from an IDE if (version.equals("${project.version}")) { version = "1.0.4"; } return version; } }
33.628571
246
0.781041
80df9057fbe9e293c63fecf921a2c1ffb713ca57
1,790
package scouter.client.counter.actions; import org.eclipse.jface.action.Action; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import scouter.client.Images; import scouter.client.counter.views.CounterPTAllPairChart; import scouter.client.popup.CalendarDialog; import scouter.client.popup.CalendarDialog.ILoadCalendarDialog; import scouter.client.util.ConsoleProxy; import scouter.client.util.ImageUtil; import scouter.client.util.TimeUtil; import scouter.util.DateUtil; public class OpenPTPairAllAction extends Action implements ILoadCalendarDialog { IWorkbenchWindow window; int serverId; String objType; String counter; public OpenPTPairAllAction(IWorkbenchWindow window, String name, int serverId, String objType, String counter) { this.window = window; this.serverId = serverId; this.objType = objType; this.counter = counter; setImageDescriptor(ImageUtil.getImageDescriptor(Images.calendar)); setText(name); } public void run() { CalendarDialog dialog = new CalendarDialog(window.getShell().getDisplay(), this); dialog.showWithTime(-1, -1, TimeUtil.getCurrentTime(serverId) - DateUtil.MILLIS_PER_FIVE_MINUTE); } public void onPressedOk(long startTime, long endTime) { if (window != null) { try { CounterPTAllPairChart chart = (CounterPTAllPairChart) window.getActivePage().showView( CounterPTAllPairChart.ID, serverId + "&" + objType + "&" + counter , IWorkbenchPage.VIEW_ACTIVATE); if (chart != null) { chart.setInput(startTime, endTime); } } catch (PartInitException e) { ConsoleProxy.errorSafe("Error opening view:" + e.getMessage()); } } } public void onPressedOk(String date) { } public void onPressedCancel() { } }
29.344262
113
0.760335
830539d69ba37d5c6a471152b523ac0e3562ad6a
352
public class Esercizio1{ //stampare uno per riga tutti i divisori di n public static void div(int n, int i){ if(i<=n){ if(n%i == 0){ System.out.println(i); } div(n, i+1); } }//div public static void main(String[] args){ div(10,1); }//main }//class
20.705882
49
0.463068
44320047c4d7cb18d90a0f8e093b81f19373742a
1,764
/* * MSX SDK * MSX SDK client. * * The version of the OpenAPI document: 1.0.8 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.cisco.msx.platform.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.annotations.SerializedName; import java.io.IOException; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * Gets or Sets TemplateStatus */ @JsonAdapter(TemplateStatus.Adapter.class) public enum TemplateStatus { NEW("NEW"), PENDING("PENDING"), FAILED("FAILED"), SUCCESS("SUCCESS"), DELETE("DELETE"), ERROR("ERROR"); private String value; TemplateStatus(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static TemplateStatus fromValue(String value) { for (TemplateStatus b : TemplateStatus.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } public static class Adapter extends TypeAdapter<TemplateStatus> { @Override public void write(final JsonWriter jsonWriter, final TemplateStatus enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public TemplateStatus read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return TemplateStatus.fromValue(value); } } }
21.512195
105
0.697846
eccbb54fde000fb658168ecf153487d582bba1fd
4,558
package zener.zcomm.gui.zcomm_main; import io.github.cottonmc.cotton.gui.client.ScreenDrawing; import io.github.cottonmc.cotton.gui.widget.WWidget; import io.github.cottonmc.cotton.gui.widget.data.InputResult; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawableHelper; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.text.LiteralText; import net.minecraft.text.Text; import zener.zcomm.Main; import zener.zcomm.chat.ChatHistory; import zener.zcomm.util.nrCheck; public class ChatWidget extends WWidget { private final MinecraftClient client; private final int comm_nr; private int scroll = 0; private int text_padding = 2; private int padding_left = 4; private int padding_right = 2; public ChatWidget(int comm_nr) { client = MinecraftClient.getInstance(); this.comm_nr = comm_nr; } @Override public InputResult onMouseScroll(int x, int y, double amount) { scroll += amount; if (scroll < 0) scroll = 0; return InputResult.PROCESSED; } @Override public boolean canResize() { return true; } @Environment(EnvType.CLIENT) @Override public void paint(MatrixStack matrices, int x, int y, int mouseX, int mouseY) { ScreenDrawing.coloredRect(matrices, x-1, y-1, width+2, height+2, 0xFF_FFFFA0); ScreenDrawing.coloredRect(matrices, x, y, width, height, 0xFF000000); ChatHistory hist = ChatHistory.getInstance(); int max_text = height / (client.textRenderer.fontHeight+3); int offset = Integer.max(0, hist.getSize(comm_nr, hist.getLast_channel(comm_nr))-1-max_text); if (scroll > hist.getSize(comm_nr, hist.getLast_channel(comm_nr)) - 1 - max_text) scroll = Integer.max(0, hist.getSize(comm_nr, hist.getLast_channel(comm_nr))-1-max_text); int c = max_text; for (int i = hist.getSize(comm_nr, hist.getLast_channel(comm_nr)) - 1; i >= offset; i--) { Text text = hist.getMessages(comm_nr, hist.getLast_channel(comm_nr)).get(i-scroll); String message = hist.getMessage(text); String sender = hist.getSender(text); String recipient = hist.getReceiver(text); String as = hist.getAs(text); nrCheck sender_nr = new nrCheck(sender); nrCheck recipient_nr = new nrCheck(recipient); nrCheck as_nr = new nrCheck(as); if (sender_nr.getNr() != comm_nr && recipient_nr.getNr() != comm_nr) { if (sender_nr.getNr() != Main.GLOBAL_CHANNEL_NR && recipient_nr.getNr() != Main.GLOBAL_CHANNEL_NR) continue; } String sent_to = ""; if (hist.getLast_channel(comm_nr) == Main.GLOBAL_CHANNEL_NR) { if (recipient_nr.getNr() != Main.GLOBAL_CHANNEL_NR) { sent_to = "->"+recipient_nr.getNrStr(); } else { sent_to = "->G"; } } String new_message; if (as == null || !as_nr.isValid()) { new_message = String.format("[%s%s]: %s", sender_nr.getNrStr(), sent_to, message); } else { if (!sent_to.equals("")){ new_message = String.format("[%s%s](as %s): %s", sender_nr.getNrStr(), sent_to, as, message); } else { new_message = String.format("[%s->%s]: %s", sender_nr.getNrStr(), as, message); } } int length = new_message.length(); if (sender_nr.getNr() == comm_nr) { new_message = "§6" + new_message; } if (length > width - padding_left - padding_right) { DrawableHelper.drawTextWithShadow( matrices, client.textRenderer, new LiteralText("Too Long."), x+padding_left, y+(client.textRenderer.fontHeight+text_padding)*(c)+text_padding, 0xFFFFFFFF); c--; } else { DrawableHelper.drawTextWithShadow( matrices, client.textRenderer, new LiteralText(new_message), x+padding_left, y+(client.textRenderer.fontHeight+text_padding)*(c)+text_padding, 0xFFFFFFFF); c--; } if (c < 0) { break; } } } }
41.816514
176
0.588635
6c94e315d5020872ae7504f4ad4a9dc717cfa02f
95
package com.cw.productconsume; public interface ITaskDone { void onJobDone(String key); }
15.833333
31
0.757895
64a5f07a6d2910e229b898816ee5c80d675a3790
5,816
/* * The Jira Cloud platform REST API * Jira Cloud platform REST API documentation * * The version of the OpenAPI document: 1001.0.0-SNAPSHOT * Contact: ecosystem@atlassian.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.datengaertnerei.jira.rest.client.model; import java.util.Objects; import java.util.Arrays; import com.datengaertnerei.jira.rest.client.model.CustomFieldReplacement; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * DeleteAndReplaceVersionBean */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-05-17T17:45:56.601554Z[Etc/UTC]") public class DeleteAndReplaceVersionBean { public static final String SERIALIZED_NAME_MOVE_FIX_ISSUES_TO = "moveFixIssuesTo"; @SerializedName(SERIALIZED_NAME_MOVE_FIX_ISSUES_TO) private Long moveFixIssuesTo; public static final String SERIALIZED_NAME_MOVE_AFFECTED_ISSUES_TO = "moveAffectedIssuesTo"; @SerializedName(SERIALIZED_NAME_MOVE_AFFECTED_ISSUES_TO) private Long moveAffectedIssuesTo; public static final String SERIALIZED_NAME_CUSTOM_FIELD_REPLACEMENT_LIST = "customFieldReplacementList"; @SerializedName(SERIALIZED_NAME_CUSTOM_FIELD_REPLACEMENT_LIST) private List<CustomFieldReplacement> customFieldReplacementList = null; public DeleteAndReplaceVersionBean moveFixIssuesTo(Long moveFixIssuesTo) { this.moveFixIssuesTo = moveFixIssuesTo; return this; } /** * The ID of the version to update &#x60;fixVersion&#x60; to when the field contains the deleted version. * @return moveFixIssuesTo **/ @javax.annotation.Nullable @ApiModelProperty(value = "The ID of the version to update `fixVersion` to when the field contains the deleted version.") public Long getMoveFixIssuesTo() { return moveFixIssuesTo; } public void setMoveFixIssuesTo(Long moveFixIssuesTo) { this.moveFixIssuesTo = moveFixIssuesTo; } public DeleteAndReplaceVersionBean moveAffectedIssuesTo(Long moveAffectedIssuesTo) { this.moveAffectedIssuesTo = moveAffectedIssuesTo; return this; } /** * The ID of the version to update &#x60;affectedVersion&#x60; to when the field contains the deleted version. * @return moveAffectedIssuesTo **/ @javax.annotation.Nullable @ApiModelProperty(value = "The ID of the version to update `affectedVersion` to when the field contains the deleted version.") public Long getMoveAffectedIssuesTo() { return moveAffectedIssuesTo; } public void setMoveAffectedIssuesTo(Long moveAffectedIssuesTo) { this.moveAffectedIssuesTo = moveAffectedIssuesTo; } public DeleteAndReplaceVersionBean customFieldReplacementList(List<CustomFieldReplacement> customFieldReplacementList) { this.customFieldReplacementList = customFieldReplacementList; return this; } public DeleteAndReplaceVersionBean addCustomFieldReplacementListItem(CustomFieldReplacement customFieldReplacementListItem) { if (this.customFieldReplacementList == null) { this.customFieldReplacementList = new ArrayList<>(); } this.customFieldReplacementList.add(customFieldReplacementListItem); return this; } /** * An array of custom field IDs (&#x60;customFieldId&#x60;) and version IDs (&#x60;moveTo&#x60;) to update when the fields contain the deleted version. * @return customFieldReplacementList **/ @javax.annotation.Nullable @ApiModelProperty(value = "An array of custom field IDs (`customFieldId`) and version IDs (`moveTo`) to update when the fields contain the deleted version.") public List<CustomFieldReplacement> getCustomFieldReplacementList() { return customFieldReplacementList; } public void setCustomFieldReplacementList(List<CustomFieldReplacement> customFieldReplacementList) { this.customFieldReplacementList = customFieldReplacementList; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeleteAndReplaceVersionBean deleteAndReplaceVersionBean = (DeleteAndReplaceVersionBean) o; return Objects.equals(this.moveFixIssuesTo, deleteAndReplaceVersionBean.moveFixIssuesTo) && Objects.equals(this.moveAffectedIssuesTo, deleteAndReplaceVersionBean.moveAffectedIssuesTo) && Objects.equals(this.customFieldReplacementList, deleteAndReplaceVersionBean.customFieldReplacementList); } @Override public int hashCode() { return Objects.hash(moveFixIssuesTo, moveAffectedIssuesTo, customFieldReplacementList); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DeleteAndReplaceVersionBean {\n"); sb.append(" moveFixIssuesTo: ").append(toIndentedString(moveFixIssuesTo)).append("\n"); sb.append(" moveAffectedIssuesTo: ").append(toIndentedString(moveAffectedIssuesTo)).append("\n"); sb.append(" customFieldReplacementList: ").append(toIndentedString(customFieldReplacementList)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
34.619048
159
0.76238
5b0fc9512062be42fdac58d2c659eb4003c66a1a
11,329
package com.careydevelopment.ecosystem.user.service; import java.io.IOException; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.careydevelopment.ecosystem.user.exception.EmailCodeCreateFailedException; import com.careydevelopment.ecosystem.user.exception.InvalidRequestException; import com.careydevelopment.ecosystem.user.exception.ServiceException; import com.careydevelopment.ecosystem.user.exception.TextCodeCreateFailedException; import com.careydevelopment.ecosystem.user.exception.UserSaveFailedException; import com.careydevelopment.ecosystem.user.model.Registrant; import com.careydevelopment.ecosystem.user.model.RegistrantAuthentication; import com.careydevelopment.ecosystem.user.model.User; import com.careydevelopment.ecosystem.user.model.UserSearchCriteria; import com.careydevelopment.ecosystem.user.repository.RegistrantAuthenticationRepository; import com.careydevelopment.ecosystem.user.repository.UserRepository; import com.careydevelopment.ecosystem.user.util.TotpUtil; import com.careydevelopment.ecosystem.user.util.UserUtil; import us.careydevelopment.ecosystem.jwt.util.RecaptchaUtil; import us.careydevelopment.util.api.model.ValidationError; import us.careydevelopment.util.api.validation.ValidationUtil; import us.careydevelopment.util.date.DateConversionUtil; @Service public class RegistrantService { private static final Logger LOG = LoggerFactory.getLogger(RegistrantService.class); private static final int MAX_MINUTES_FOR_CODE = 5; private static final int MAX_FAILED_ATTEMPTS = 5; @Value("${recaptcha.active}") String recaptchaActive; @Autowired private UserService userService; @Autowired private UserRepository userRepository; @Autowired private RecaptchaUtil recaptchaUtil; @Autowired private TotpUtil totpUtil; @Autowired private RegistrantAuthenticationRepository registrantAuthenticationRepository; @Autowired private EmailService emailService; @Autowired private SmsService smsService; @Autowired private UserUtil userUtil; public void addAuthority(String username, String authority) { try { User user = userRepository.findByUsername(username); if (user != null) { user.getAuthorityNames().add(authority); userRepository.save(user); } } catch (Exception e) { LOG.error("Problem adding authority!", e); throw new ServiceException("Problem adding authority!"); } } public boolean validateTextCode(RegistrantAuthentication auth, String code) { boolean verified = false; LOG.debug("Failed attempts for " + auth.getUsername() + " is " + auth.getFailedAttempts()); try { if (auth.getFailedAttempts() < MAX_FAILED_ATTEMPTS) { String requestId = auth.getRequestId(); verified = smsService.checkValidationCode(requestId, code); if (!verified) { auth.setFailedAttempts(auth.getFailedAttempts() + 1); registrantAuthenticationRepository.save(auth); } } } catch (Exception e) { LOG.error("Problem validating text code!", e); throw new ServiceException("Problem validating text code!"); } return verified; } public boolean validateEmailCode(String username, String code) { try { int previousAttempts = getPreviousAttempts(username, RegistrantAuthentication.Type.EMAIL); if (previousAttempts < MAX_FAILED_ATTEMPTS) { List<RegistrantAuthentication> list = validateCode(username, code, RegistrantAuthentication.Type.EMAIL); if (list != null && list.size() > 0) { return true; } else { incrementFailedAttempts(username, RegistrantAuthentication.Type.EMAIL); return false; } } else { LOG.debug("User " + username + " exceeded max attempts to validate the email code"); return false; } } catch (Exception e) { LOG.error("Problem validating email code!", e); throw new ServiceException("Problem validating email code!"); } } private int getPreviousAttempts(String username, RegistrantAuthentication.Type type) { int previousAttempts = 0; LOG.debug("Checking previous attempts for " + username); List<RegistrantAuthentication> auths = registrantAuthenticationRepository .findByUsernameAndTypeOrderByTimeDesc(username, type.toString()); if (auths != null && auths.size() > 0) { RegistrantAuthentication auth = auths.get(0); previousAttempts = auth.getFailedAttempts(); } LOG.debug("Failed attempts is " + previousAttempts); return previousAttempts; } private void incrementFailedAttempts(String username, RegistrantAuthentication.Type type) { List<RegistrantAuthentication> auths = registrantAuthenticationRepository .findByUsernameAndTypeOrderByTimeDesc(username, type.toString()); if (auths != null && auths.size() > 0) { RegistrantAuthentication auth = auths.get(0); auth.setFailedAttempts(auth.getFailedAttempts() + 1); registrantAuthenticationRepository.save(auth); } } private List<RegistrantAuthentication> validateCode(String username, String code, RegistrantAuthentication.Type type) { long time = System.currentTimeMillis() - (DateConversionUtil.NUMBER_OF_MILLISECONDS_IN_MINUTE * MAX_MINUTES_FOR_CODE); List<RegistrantAuthentication> auths = registrantAuthenticationRepository.codeCheck(username, time, type.toString(), code); return auths; } public void createTextCode(String username) { User user = userRepository.findByUsername(username); LOG.debug("Found user is " + user); if (user != null) { try { String requestId = smsService.sendValidationCode(user.getPhoneNumber()); if (requestId != null) { RegistrantAuthentication auth = new RegistrantAuthentication(); auth.setUsername(username); auth.setTime(System.currentTimeMillis()); auth.setType(RegistrantAuthentication.Type.TEXT); auth.setRequestId(requestId); registrantAuthenticationRepository.save(auth); } else { LOG.error("Unable to create text code as user " + username + " doesn't exist"); throw new TextCodeCreateFailedException("User " + username + " doesn't exist"); } } catch (Exception e) { LOG.error("Problem creating text code!", e); throw new TextCodeCreateFailedException(e.getMessage()); } } } public void createEmailCode(Registrant registrant) { try { String code = createCode(registrant.getUsername(), RegistrantAuthentication.Type.EMAIL); String validationBody = "\n\nYour verification code for Carey Development, LLC and the CarEcosystem Network.\n\n" + "Use verification code: " + code; emailService.sendSimpleMessage(registrant.getEmailAddress(), "Your Verification Code", validationBody); } catch (Exception e) { LOG.error("Problem creating email code!", e); throw new EmailCodeCreateFailedException(e.getMessage()); } } private String createCode(String username, RegistrantAuthentication.Type type) { RegistrantAuthentication auth = new RegistrantAuthentication(); auth.setUsername(username); auth.setTime(System.currentTimeMillis()); auth.setType(type); String code = totpUtil.getTOTPCode(); auth.setCode(code); registrantAuthenticationRepository.save(auth); return code; } public User saveUser(Registrant registrant) { User savedUser = null; try { User user = userUtil.convertRegistrantToUser(registrant); savedUser = userRepository.save(user); } catch (Exception e) { LOG.error("Problem saving user!", e); throw new UserSaveFailedException(e.getMessage()); } return savedUser; } public void validateRegistrant(Registrant registrant, List<ValidationError> errors) { handleRemainingValidations(registrant, errors); LOG.debug("validation is " + errors); if (errors.size() > 0) { throw new InvalidRequestException("Invalid registrant", errors); } } private void handleRemainingValidations(Registrant registrant, List<ValidationError> errors) { try { validateUniqueName(errors, registrant); validateUniqueEmail(errors, registrant); validateRecaptcha(errors, registrant); } catch (Exception e) { LOG.error("Problem validating registrant!", e); throw new ServiceException("Problem validating registrant!"); } } private void validateRecaptcha(List<ValidationError> errors, Registrant registrant) throws IOException { if (!StringUtils.isBlank(recaptchaActive) && !recaptchaActive.equalsIgnoreCase("false")) { float score = recaptchaUtil.createAssessment(registrant.getRecaptchaResponse()); if (score < RecaptchaUtil.RECAPTCHA_MIN_SCORE) { // user-friendly error message not necessary if a bot is trying to get in ValidationUtil.addError(errors, "Google thinks you're a bot", null, null); } } } private void validateUniqueName(List<ValidationError> errors, Registrant registrant) { String username = registrant.getUsername(); if (!StringUtils.isBlank(username)) { UserSearchCriteria searchCriteria = new UserSearchCriteria(); searchCriteria.setUsername(username.trim()); List<User> users = userService.search(searchCriteria); if (users.size() > 0) { ValidationUtil.addError(errors, "Username is taken", "username", "usernameTaken"); } } } private void validateUniqueEmail(List<ValidationError> errors, Registrant registrant) { String email = registrant.getEmailAddress(); if (!StringUtils.isBlank(email)) { UserSearchCriteria searchCriteria = new UserSearchCriteria(); searchCriteria.setEmailAddress(email.trim()); List<User> users = userService.search(searchCriteria); if (users.size() > 0) { ValidationUtil.addError(errors, "Email address is taken", "emailAddress", "emailTaken"); } } } }
38.534014
125
0.658399
0999dec7e1a45ff540f13bf4bd1b4fd6ed277b59
2,593
package com.thecode.androidlocation.activities; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import com.thecode.androidlocation.R; public class SplashScreenActivity extends AppCompatActivity { private Context mContext; ImageView img; int SPLASH_TIME_OUT = 3000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); img = findViewById(R.id.ic_logo); mContext = SplashScreenActivity.this; setAnimation(); new Handler().postDelayed(() -> { Intent intent = new Intent(mContext, MapsActivity.class); // Animatoo.animateSlideLeft(mContext); startActivity(intent); finish(); }, SPLASH_TIME_OUT); } private void setAnimation() { View imageView = findViewById(R.id.ic_logo); ObjectAnimator scaleXAnimation = ObjectAnimator.ofFloat(imageView, "scaleX", 5.0F, 1.0F); scaleXAnimation.setInterpolator(new AccelerateDecelerateInterpolator()); scaleXAnimation.setDuration(900); ObjectAnimator scaleYAnimation = ObjectAnimator.ofFloat(imageView, "scaleY", 5.0F, 1.0F); scaleYAnimation.setInterpolator(new AccelerateDecelerateInterpolator()); scaleYAnimation.setDuration(900); ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(imageView, "alpha", 0.0F, 1.0F); alphaAnimation.setInterpolator(new AccelerateDecelerateInterpolator()); alphaAnimation.setDuration(900); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.play(scaleXAnimation).with(scaleYAnimation).with(alphaAnimation); animatorSet.setStartDelay(900); animatorSet.start(); imageView.setAlpha(1.0F); Animation anim1 = AnimationUtils.loadAnimation(this, R.anim.animate_fade); anim1.setDuration(2000); imageView.startAnimation(anim1); } @Override protected void onDestroy() { super.onDestroy(); } }
30.505882
97
0.715388
558b8ef8c5bf4d7f8f9a7f711890149db0851308
1,937
package pokecube.alternative.event; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import pokecube.adventures.items.ItemBadge; import pokecube.alternative.Config; import pokecube.alternative.container.card.CardPlayerData; import pokecube.core.utils.PokeType; import thut.core.common.handlers.PlayerDataHandler; import thut.lib.CompatWrapper; public class TrainerCardHandler { @SubscribeEvent public void PlayerUseItemEvent(PlayerInteractEvent.RightClickItem event) { if (Config.instance.isEnabled) return; ItemStack item = event.getItemStack(); EntityPlayer player = event.getEntityPlayer(); if (player.world.isRemote) return; if (Config.instance.trainerCard && ItemBadge.isBadge(item)) { CardPlayerData data = PlayerDataHandler.getInstance().getPlayerData(player).getData(CardPlayerData.class); int index = -1; PokeType type = PokeType.values()[item.getItemDamage()]; for (int i = 0; i < 8; i++) { if (Config.instance.badgeOrder[i].equalsIgnoreCase(type.name)) { index = i; break; } } if (index == -1 || CompatWrapper.isValid(data.inventory.getStackInSlot(index))) return; int slotIndex = event.getEntityPlayer().inventory.currentItem; data.inventory.setInventorySlotContents(index, item.copy()); player.inventory.setInventorySlotContents(slotIndex, ItemStack.EMPTY); PlayerDataHandler.getInstance().save(player.getCachedUniqueIdString(), data.getIdentifier()); event.setCanceled(true); return; } } }
42.108696
119
0.658751
7e153268b7235008d6468c6e2ea51023b43efc3e
1,817
package com.jmsoftware.maf.springcloudstarter.filter; import com.jmsoftware.maf.springcloudstarter.property.MafConfigurationProperties; import com.jmsoftware.maf.springcloudstarter.util.RequestUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * <h1>RequestFilter</h1> * <p>Request filter.</p> * * @author Johnny Miller (锺俊), email: johnnysviva@outlook.com * @date 2019-03-23 14:24 **/ @Slf4j @Component @RequiredArgsConstructor public class AccessLogFilter extends OncePerRequestFilter { private final MafConfigurationProperties mafConfigurationProperties; private final AntPathMatcher antPathMatcher = new AntPathMatcher(); @Override @SuppressWarnings("NullableProblems") protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { // Ignore URL for (String ignoredUrl : this.mafConfigurationProperties.flattenIgnoredUrls()) { if (this.antPathMatcher.match(ignoredUrl, request.getRequestURI())) { filterChain.doFilter(request, response); return; } } log.info("The requester({}) requested resource. Request URL: [{}] {}", RequestUtil.getRequestIpAndPort(request), request.getMethod(), request.getRequestURL()); filterChain.doFilter(request, response); } }
38.659574
120
0.742433
420e64df808914069cbaeb14a08100366716dbbe
2,320
package com.cpq.consulclient; import java.io.Serializable; import java.util.Date; /** * <p> * 日志表 * </p> * * @author chenpiqian * @since 2019-04-01 */ public class Log implements Serializable { private static final long serialVersionUID = 1L; private String id; /** * 用户id */ private Long userId; /** * 账号 */ private String loginName; /** * 操作功能项 */ private String operateItem; /** * 增删改查 */ private String operateType; /** * 操作时间 */ private Date operateTime; /** * 操作结果true成功,false失败 */ private Boolean result; /** * 请求url */ private String url; /** * 租户编码 */ private String tenantCode; /** * 详情 */ private String detail; public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getOperateItem() { return operateItem; } public void setOperateItem(String operateItem) { this.operateItem = operateItem; } public String getOperateType() { return operateType; } public void setOperateType(String operateType) { this.operateType = operateType; } public Date getOperateTime() { return operateTime; } public void setOperateTime(Date operateTime) { this.operateTime = operateTime; } public Boolean getResult() { return result; } public void setResult(Boolean result) { this.result = result; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTenantCode() { return tenantCode; } public void setTenantCode(String tenantCode) { this.tenantCode = tenantCode; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } }
15.890411
52
0.564655
b720cf02a4c61e0b83d253def1cf7c8f64a6a91f
2,830
/* * Copyright (c) 2020 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uber.rss.metrics; import com.uber.m3.tally.Buckets; import com.uber.m3.tally.Capabilities; import com.uber.m3.tally.Counter; import com.uber.m3.tally.Gauge; import com.uber.m3.tally.Histogram; import com.uber.m3.tally.Scope; import com.uber.m3.tally.Stopwatch; import com.uber.m3.tally.StopwatchRecorder; import com.uber.m3.tally.Timer; import com.uber.m3.util.Duration; import java.util.Map; public class M3DummyScope implements Scope { @Override public Counter counter(String s) { return new Counter() { @Override public void inc(long l) { } }; } @Override public Gauge gauge(String s) { return new Gauge() { @Override public void update(double v) { } }; } @Override public Timer timer(String s) { return new Timer() { @Override public void record(Duration duration) { } @Override public Stopwatch start() { StopwatchRecorder stopwatchRecorder = new StopwatchRecorder() { @Override public void recordStopwatch(long l) { } }; return new Stopwatch(System.nanoTime(), stopwatchRecorder); } }; } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public Histogram histogram(String s, Buckets buckets) { return new Histogram() { @Override public void recordValue(double v) { } @Override public void recordDuration(Duration duration) { } @Override public Stopwatch start() { StopwatchRecorder stopwatchRecorder = new StopwatchRecorder() { @Override public void recordStopwatch(long l) { } }; return new Stopwatch(System.nanoTime(), stopwatchRecorder); } }; } @Override public Scope tagged(Map<String, String> map) { return this; } @Override public Scope subScope(String s) { return this; } @Override public Capabilities capabilities() { return new Capabilities() { @Override public boolean reporting() { return false; } @Override public boolean tagging() { return false; } }; } @Override public void close() { } }
23.38843
75
0.648057
5b0c035fa3957ab7746438c7f64c1e72b407b39b
3,711
package urjcdaw11.relman.relations; import java.util.LinkedList; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import urjcdaw11.relman.units.Unit; @Service public class RelationService { @Autowired private RelationRepository relationRep; public Optional<Relation> findOne(long id) { return relationRep.findById(id); } public List<Page<Relation>> findContextByName(Unit unit, Pageable page){ List<Page<Relation>> list = new LinkedList<>(); list.add(this.findByTypeAndDestiny("inheritance", unit, page)); list.add(this.findByTypeAndOrigin("inheritance", unit, page)); list.add(this.findByTypeAndDestiny("composition", unit, page)); list.add(this.findByTypeAndOrigin("composition", unit, page)); list.add(this.findByTypeAndDestiny("use", unit, page)); list.add(this.findByTypeAndOrigin("use", unit, page)); list.add(this.findByTypeAndDestiny("association", unit, page)); list.add(this.findByTypeAndOrigin("association", unit, page)); return list; } public List<Relation> findAll() { return relationRep.findAll(); } public Page<Relation> findAll(Pageable page) { return relationRep.findAll(page); } public Relation save(Relation relation) { return relationRep.save(relation); } public void delete(long id) { relationRep.deleteById(id); } public void delete(Relation relation) { relationRep.delete(relation); } public List<Relation> findByTypeAndOrigin(String type, Unit origin) { return relationRep.findByTypeAndOrigin(type, origin); } public List<Relation> findByTypeAndDestiny(String type, Unit destiny) { return relationRep.findByTypeAndDestiny(type, destiny); } public Page<Relation> findByTypeAndOrigin(String type, Unit origin, Pageable page) { return relationRep.findByTypeAndOrigin(type, origin, page); } public Page<Relation> findByTypeAndDestiny(String type, Unit destiny, Pageable page) { return relationRep.findByTypeAndDestiny(type, destiny, page); } //@return the concrete part of a relation (Inheritance->Children||Parents) public Page<Relation> findByNameAndConcreteType(Unit unit, String type,Pageable page){ String relType=translateTypeRelation(type); String decide = this.decideOriginOrDestiny(type); if (decide.equals("destiny")) { return this.findByTypeAndDestiny (relType,unit, page); } else if (decide.equals("origin")) { return this.findByTypeAndOrigin (relType,unit, page); } else { return null; } } public String translateTypeRelation(String type) { String relType = ""; if (type.equals("parents") || type.equals("children")) { relType = "inheritance"; } if (type.equals("composites") || type.equals("parts")) { relType = "composition"; } if (type.equals("associatedBy") || type.equals("associatedTo")) { relType = "association"; } if (type.equals("uses") || type.equals("usedBy")) { relType = "use"; } return relType; } //Method to decide the search by origin or destiny public String decideOriginOrDestiny(String type) { if (type.equals("parents") || type.equals("composites") || type.equals("associatedBy") || type.equals("usedBy")) { return "destiny"; } else if (type.equals("uses") || type.equals("parts") || type.equals("children") || type.equals("associatedTo")) { return "origin"; } else { return null; } } public Relation findByTypeAndOriginAndDestiny(String type, Unit origin, Unit destiny){ return relationRep.findByTypeAndOriginAndDestiny(type, origin, destiny); } }
28.767442
88
0.729722
3fcf81030c24aefadc142a52fc9e7bdcab27061d
712
package caf.war.wm_opencaf_showcase.controls.caf_f; import java.net.MalformedURLException; import java.net.URL; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import com.webmethods.caf.faces.annotations.ExpireWithPageFlow; import com.webmethods.caf.faces.bean.BaseFacesBean; @ManagedBean(name="inputUrlBean") @SessionScoped @ExpireWithPageFlow public class InputURL extends BaseFacesBean { private URL value = null; public InputURL() { super(); try { value = new URL("http://www.softwareag.com"); } catch (MalformedURLException e) { error(e); } } public URL getValue() { return value; } public void setValue(URL value) { this.value = value; } }
19.243243
63
0.742978
e05f4800ca2f46ccb73391397872cf506803518d
4,919
package kaptainwutax.seedcracker.finder.structure; import kaptainwutax.featureutils.structure.RegionStructure; import kaptainwutax.seedcracker.Features; import kaptainwutax.seedcracker.SeedCracker; import kaptainwutax.seedcracker.cracker.DataAddedEvent; import kaptainwutax.seedcracker.finder.Finder; import kaptainwutax.seedcracker.render.Color; import kaptainwutax.seedcracker.render.Cube; import kaptainwutax.seedcracker.render.Cuboid; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.Direction; import net.minecraft.util.math.Vec3i; import net.minecraft.world.World; import net.minecraft.world.dimension.DimensionType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MonumentFinder extends Finder { protected static List<BlockPos> SEARCH_POSITIONS = buildSearchPositions(CHUNK_POSITIONS, pos -> { if(pos.getY() != 56)return true; return false; }); protected List<PieceFinder> finders = new ArrayList<>(); protected final Vec3i size = new Vec3i(8, 5, 8); public MonumentFinder(World world, ChunkPos chunkPos) { super(world, chunkPos); PieceFinder finder = new PieceFinder(world, chunkPos, Direction.NORTH, size); finder.searchPositions = SEARCH_POSITIONS; buildStructure(finder); this.finders.add(finder); } @Override public List<BlockPos> findInChunk() { Map<PieceFinder, List<BlockPos>> result = this.findInChunkPieces(); List<BlockPos> combinedResult = new ArrayList<>(); result.forEach((pieceFinder, positions) -> { positions.removeIf(pos -> { //Figure this out, it's not a trivial task. return false; }); combinedResult.addAll(positions); positions.forEach(pos -> { ChunkPos monumentStart = new ChunkPos(this.chunkPos.x + 1, this.chunkPos.z + 1); RegionStructure.Data<?> data = Features.MONUMENT.at(monumentStart.x, monumentStart.z); if(SeedCracker.get().getDataStorage().addBaseData(data, DataAddedEvent.POKE_STRUCTURES)) { this.renderers.add(new Cuboid(pos, pieceFinder.getLayout(), new Color(0, 0, 255))); this.renderers.add(new Cube(monumentStart.getStartPos().add(0, pos.getY(), 0), new Color(0, 0, 255))); } }); }); return combinedResult; } public Map<PieceFinder, List<BlockPos>> findInChunkPieces() { Map<PieceFinder, List<BlockPos>> result = new HashMap<>(); this.finders.forEach(pieceFinder -> { result.put(pieceFinder, pieceFinder.findInChunk()); }); return result; } @Override public boolean isValidDimension(DimensionType dimension) { return this.isOverworld(dimension); } public void buildStructure(PieceFinder finder) { BlockState prismarine = Blocks.PRISMARINE.getDefaultState(); BlockState prismarineBricks = Blocks.PRISMARINE_BRICKS.getDefaultState(); BlockState darkPrismarine = Blocks.DARK_PRISMARINE.getDefaultState(); BlockState seaLantern = Blocks.SEA_LANTERN.getDefaultState(); BlockState water = Blocks.WATER.getDefaultState(); //4 bottom pillars. for(int i = 0; i < 4; i++) { int x = i >= 2 ? 7 : 0; int z = i % 2 == 0 ? 0 : 7; for(int y = 0; y < 3; y++) { finder.addBlock(prismarineBricks, x, y, z); } } //First bend. for(int i = 0; i < 4; i++) { int x = i >= 2 ? 6 : 1; int z = i % 2 == 0 ? 1 : 6; finder.addBlock(prismarineBricks, x, 3, z); } //Prismarine ring. for(int x = 2; x <= 5; x++) { for(int z = 2; z <= 5; z++) { if(x == 2 || x == 5 || z == 2 || z == 5) { finder.addBlock(prismarine, x, 4, z); } } } //Second bend. for(int i = 0; i < 4; i++) { int x = i >= 2 ? 5 : 2; int z = i % 2 == 0 ? 2 : 5; finder.addBlock(prismarineBricks, x, 4, z); finder.addBlock(seaLantern, x, 3, z); } } public static List<Finder> create(World world, ChunkPos chunkPos) { List<Finder> finders = new ArrayList<>(); finders.add(new MonumentFinder(world, chunkPos)); finders.add(new MonumentFinder(world, new ChunkPos(chunkPos.x - 1, chunkPos.z))); finders.add(new MonumentFinder(world, new ChunkPos(chunkPos.x, chunkPos.z - 1))); finders.add(new MonumentFinder(world, new ChunkPos(chunkPos.x - 1, chunkPos.z - 1))); return finders; } }
35.135714
122
0.612929
2f17d58ba806d821af75f1ebd0fa6a10159ac2cf
849
package se.gory_moon.idp.common.jei; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent; import se.gory_moon.idp.client.ClientJEIManager; import se.gory_moon.idp.common.base.BaseData; import se.gory_moon.idp.common.base.BaseInfoMessage; import java.util.List; import java.util.function.Supplier; public class JEIInfoMessage extends BaseInfoMessage { public JEIInfoMessage(List<BaseData> tooltipDataList) { super(tooltipDataList); } public JEIInfoMessage(PacketBuffer buffer) { super(buffer, BaseData::new); } public void handle(Supplier<NetworkEvent.Context> ctx) { //noinspection CodeBlock2Expr ctx.get().enqueueWork(() -> { ClientJEIManager.INSTANCE.updateData(dataList); }); ctx.get().setPacketHandled(true); } }
28.3
60
0.725559
e762bb58802eee8bb30ceba5050b39733796343b
593
package com.revature.driver; import com.revature.beans.Dog; import com.revature.beans.HannahsPets; public class Driver { public static void main(String[] args) { HannahsPets a= new HannahsPets("Dog","Romeo",3,55); System.out.println(a); HannahsPets b= new HannahsPets ("Dog","Bailey",15,22); System.out.println(b); HannahsPets c= new HannahsPets ("Bird","Frodo",17,1); System.out.println(c); Dog Romeo= new Dog("brown/white","border collie","purinaOne"); System.out.println(Romeo); Dog Bailey= new Dog("tan","shitzu","purinaOne"); System.out.println(Bailey); } }
26.954545
64
0.699831
e072d27ccb81a76a4154a475fd2f79208fe9a8bf
370
import java.util.Optional; import java.util.OptionalInt; class WarnOptional { private Optional<String> go() { return <warning descr="Return of 'null'">null</warning>; } public OptionalInt nothing() { return <warning descr="Return of 'null'">null</warning>; } Object give() { return null; } private int[] giveMore() { return null; } }
17.619048
60
0.651351
1058bb749d0f501eb064c3ca8560aa406f180b06
2,455
package com.ajgaonkar.websockets.client; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketHttpHeaders; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.client.WebSocketClient; import org.springframework.web.socket.client.standard.StandardWebSocketClient; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.ExecutionException; public class MyHandlerClient implements WebSocketHandler { private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final java.net.URI uri; private final WebSocketClient client; private WebSocketSession session; public MyHandlerClient() throws URISyntaxException { client = new StandardWebSocketClient(); uri = new URI("ws://localhost:8080/myHandler"); } public void connect() throws ExecutionException, InterruptedException { session = client.doHandshake(this, new WebSocketHttpHeaders(), uri).get(); } public void sendMessage(String msg) throws IOException { if(!session.isOpen()){ return; } session.sendMessage(new TextMessage(msg)); } @Override public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception { LOGGER.info("MyHandlerClient - afterConnectionEstablished"); } @Override public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception { LOGGER.info("MyHandlerClient - handleTextMessage, session = {}, message = {}", webSocketSession, webSocketMessage.getPayload()); } @Override public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception { LOGGER.info("MyHandlerClient - handleTransportError, session = {}", webSocketSession, throwable); } @Override public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception { LOGGER.info("MyHandlerClient - afterConnectionClosed, session = {}, closeStatus = {}", webSocketSession, closeStatus); } @Override public boolean supportsPartialMessages() { return false; } }
34.097222
130
0.804888
e95d86fce3bb0d81b0e5009889095f93dad8efc3
1,520
package com.groo.bullethell; import android.app.Activity; import android.os.Bundle; import android.graphics.Point; import android.view.Display; import android.view.View; public class BulletHellActivity extends Activity { private BulletHellGame mBHGame; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getRealSize(size); mBHGame = new BulletHellGame(this, size.x, size.y); setContentView(mBHGame); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); View decorView = getWindow().getDecorView(); if (hasFocus) { decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN |View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } @Override protected void onResume() { super.onResume(); mBHGame.resume(); } @Override protected void onPause() { super.onPause(); mBHGame.pause(); } }
27.142857
78
0.618421
ce4558f29737f2fc4df0f26ad1277d5ea54b4e97
6,387
package uk.ac.cam.ch.wwmm.oscar.terms; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.cam.ch.wwmm.oscar.exceptions.OscarInitialisationException; import uk.ac.cam.ch.wwmm.oscar.tools.ResourceGetter; import uk.ac.cam.ch.wwmm.oscar.tools.StringTools; /** * A data class to hold several lists of words used in the name recogniser. * * @author ptc24 * @author sea36 * */ public final class TermSets { private static final Logger LOG = LoggerFactory.getLogger(TermSets.class); private static final ResourceGetter rg = new ResourceGetter(TermSets.class.getClassLoader(), "uk/ac/cam/ch/wwmm/oscar/terms/"); private static TermSets defaultInstance; private final Set<String> stopWords; private final Set<String> usrDictWords; private final Set<String> closedClass; private final Set<String> chemAses; private final Set<String> nonChemAses; private final Set<String> noSplitPrefixes; private final Set<String> splitSuffixes; private final Set<String> elements; private final Set<String> ligands; private final Set<String> reactWords; private final Set<String> abbreviations; private final Pattern endingInElementNamePattern; public static TermSets getDefaultInstance() { if (defaultInstance == null) { return loadTermSets(); } return defaultInstance; } private static synchronized TermSets loadTermSets() { if (defaultInstance == null) { defaultInstance = new TermSets(); } return defaultInstance; } /** * Gets the term set from stopwords.txt. * * @return The term set. */ public Set<String> getStopWords() { return stopWords; } /** * Gets the term set from usrDictWords.txt. * * @return The term set. */ public Set<String> getUsrDictWords() { return usrDictWords; } /** * Gets the term set from closedClass.txt. * * @return The term set. */ public Set<String> getClosedClass() { return closedClass; } /** * Gets the term set from noSplitPrefixes.txt. * * @return The term set. */ public Set<String> getNoSplitPrefixes() { return noSplitPrefixes; } public Set<String> getSplitSuffixes() { return splitSuffixes; } /** * Gets the term set from chemAses.txt. * * @return The term set. */ public Set<String> getChemAses() { return chemAses; } /** * Gets the term set from nonChemAses.txt. * * @return The term set. */ public Set<String> getNonChemAses() { return nonChemAses; } /** * Gets the term set from elements.txt. * * @return The term set. */ public Set<String> getElements() { return elements; } /** * Gets the term set from ligands.txt. * * @return The term set. */ public Set<String> getLigands() { return ligands; } /** * Gets the term set from reactWords.txt. * * @return The term set. */ public Set<String> getReactWords() { return reactWords; } /** * Gets the term set from abbreviations.txt * * @return The term set */ public Set<String> getAbbreviations() { return abbreviations; } /** * Gets a regular expression that detects whether a word is ending in * an element name. For example "trizinc" or "dialuminium". * * @return The compiled regular expression. */ public Pattern getEndingInElementNamePattern() { return endingInElementNamePattern; } private TermSets() { LOG.debug("Initialising term sets... "); try { stopWords = loadTerms("stopwords.txt"); usrDictWords = loadTerms("usrDictWords.txt", false); noSplitPrefixes = loadTerms("noSplitPrefixes.txt"); splitSuffixes = loadTerms("splitSuffixes.txt"); closedClass = loadTerms("closedClass.txt"); chemAses = loadTerms("chemAses.txt"); nonChemAses = loadTerms("nonChemAses.txt"); elements = loadTerms("elements.txt"); ligands = loadTerms("ligands.txt"); reactWords = loadTerms("reactWords.txt"); abbreviations = loadTerms("abbreviations.txt"); } catch (IOException e) { throw new OscarInitialisationException("failed to load TermSets", e); } endingInElementNamePattern = initEndingInElementNamePattern(); LOG.debug("term sets initialised"); } private Pattern initEndingInElementNamePattern() { // Pattern matches full (lowercase) names, but not element symbols Pattern namePattern = Pattern.compile("[a-z]+"); StringBuffer sb = new StringBuffer(); sb.append(".+("); for(Iterator<String> it = elements.iterator(); it.hasNext();) { String s = it.next(); if (namePattern.matcher(s).matches()) { sb.append(s); if (it.hasNext()) { sb.append('|'); } } } sb.append(')'); return Pattern.compile(sb.toString()); } private static Set<String> loadTerms(String filename) throws IOException { return loadTerms(filename, true); } private static Set<String> loadTerms(String filename, boolean normalise) throws IOException { HashSet<String> dict = new HashSet<String>(); InputStream is = rg.getStream(filename); try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (reader.ready()) { String line = StringTools.normaliseName(reader.readLine()); if (line.length() > 0 && line.charAt(0) != '#') { dict.add(line); } } } finally { IOUtils.closeQuietly(is); } return Collections.unmodifiableSet(dict); } }
27.063559
131
0.611085
05f30a21f6b406bf01bc2fcee73599481e218fdc
337
package quick.pager.pay.channel.dto; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import quick.pager.pay.dto.BaseDTO; /** * 支付渠道dto */ @EqualsAndHashCode(callSuper = true) @Data @Builder public class ChannelDTO extends BaseDTO { private static final long serialVersionUID = 8023643524327483948L; }
19.823529
70
0.783383
4bf5ac26b728b786724a4121355171fb3a080424
4,889
package hudson.plugins.ws_cleanup; import hudson.FilePath; import hudson.Launcher; import hudson.matrix.MatrixAggregator; import hudson.matrix.MatrixBuild; import hudson.model.BuildListener; import hudson.model.Node; import hudson.model.Result; import hudson.slaves.EnvironmentVariablesNodeProperty; import javax.annotation.CheckForNull; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class WsCleanupMatrixAggregator extends MatrixAggregator { private final List<Pattern> patterns; private final boolean deleteDirs; private final boolean notFailBuild; private final boolean cleanWhenSuccess; private final boolean cleanWhenUnstable; private final boolean cleanWhenFailure; private final boolean cleanWhenNotBuilt; private final boolean cleanWhenAborted; private final String externalDelete; public WsCleanupMatrixAggregator(MatrixBuild build, Launcher launcher, BuildListener listener, List<Pattern> patterns, boolean deleteDirs, boolean cleanWhenSuccess, boolean cleanWhenUnstable, boolean cleanWhenFailure, boolean cleanWhenNotBuilt, boolean cleanWhenAborted, boolean notFailBuild, String externalDelete) { super(build, launcher, listener); this.patterns = patterns; this.deleteDirs = deleteDirs; this.cleanWhenSuccess = cleanWhenSuccess; this.cleanWhenUnstable = cleanWhenUnstable; this.cleanWhenFailure = cleanWhenFailure; this.cleanWhenNotBuilt = cleanWhenNotBuilt; this.cleanWhenAborted = cleanWhenAborted; this.notFailBuild = notFailBuild; this.externalDelete = externalDelete; } @Override public boolean endBuild() throws InterruptedException, IOException { return doWorkspaceCleanup(); } private boolean shouldCleanBuildBasedOnState(@CheckForNull Result result) { if (result == null) { return true; } if(result.equals(Result.SUCCESS)) return this.cleanWhenSuccess; if(result.equals(Result.UNSTABLE)) return this.cleanWhenUnstable; if(result.equals(Result.FAILURE)) return this.cleanWhenFailure; if(result.equals(Result.NOT_BUILT)) return this.cleanWhenNotBuilt; if(result.equals(Result.ABORTED)) return this.cleanWhenAborted; return true; } private boolean doWorkspaceCleanup() throws IOException, InterruptedException { listener.getLogger().println("Deleting matrix project workspace..."); //TODO do we want to keep keep child workpsaces if run on the same machine? Make it optional? /* VirtualChannel vch = build.getWorkspace().getChannel(); String parentPath = build.getWorkspace().absolutize().toString(); Set<String> filter = new HashSet<String>(); for(MatrixRun run : build.getRuns()) { if(vch != run.getWorkspace().getChannel()) continue; String childPath = run.getWorkspace().absolutize().toString(); if(childPath.indexOf(parentPath) == 0) { if(!parentPath.endsWith(File.separator)) parentPath = parentPath + File.separator; String relativePath = childPath.substring(parentPath.length()); int firstDirIndex = relativePath.indexOf(File.separator); String childDir = relativePath.substring(0,firstDirIndex); //TODO add ./childDir ? filter.add(childDir); } } if(patterns == null) { patterns = new LinkedList<Pattern>(); } for(String excludeDir : filter) patterns.add(new Pattern(excludeDir, PatternType.EXCLUDE)); */ FilePath workspace = build.getWorkspace(); try { if (workspace == null || !workspace.exists()) return true; if(!shouldCleanBuildBasedOnState(build.getResult())) { listener.getLogger().println("Skipped based on build state " + build.getResult() + "\n"); return true; } if (patterns == null || patterns.isEmpty()) { workspace.deleteRecursive(); } else { Node node = build.getBuiltOn(); if (node != null) { workspace.act(new Cleanup(patterns,deleteDirs, node.getNodeProperties().get( EnvironmentVariablesNodeProperty.class), externalDelete, listener)); } } listener.getLogger().append("done\n\n"); } catch (Exception ex) { Logger.getLogger(WsCleanupMatrixAggregator.class.getName()).log(Level.SEVERE, null, ex); if(notFailBuild) { listener.getLogger().println("Cannot delete workspace: " + ex.getCause()); listener.getLogger().println("Option not to fail the build is turned on, so let's continue"); return true; } return false; } return true; } }
37.899225
120
0.677439
3227ba89217c1d5b386a7b60d0b839ba72bd2101
3,099
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Person { static int count = 1; private int id; private int age; private String name; public Person() { this.id = -1; this.name = ""; this.age = 0; } public Person(String name, int age) { this.id = count++; this.name = name; this.age = age; } public void setName(String name) { this.name = name; } public void setId(int id) { this.id = id; } public String getName() { return this.name; } public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } public int getId() { return this.id; } @Override public String toString() { String str = "ID:" + this.id+" Name:" + this.name + " Age:" + this.age; return str; } public Person[] initPersons() { //21 Person[] p = new Person[21]; p[0] = new Person("Gosho", 22); p[1] = new Person("Ivan", 23); p[2] = new Person("Gosho1", 24); p[3] = new Person("Ivan1", 43); p[4] = new Person("Petkan", 33); p[5] = new Person("Shestkan", 26); p[6] = new Person("Sedemkan", 27); p[7] = new Person("Ivan Ivanov", 31); p[8] = new Person("Gosho Petkov", 28); p[9] = new Person("Pesho Ivanov", 19); p[10] = new Person("Pesho Georgiev", 38); p[11] = new Person("Shesti Shestov", 46); p[12] = new Person("Sedemk Os", 27); p[13] = new Person("Gosho", 22); p[14] = new Person("Ivan", 23); p[15] = new Person("Gosho1", 24); p[16] = new Person("Ivan1", 43); p[17] = new Person("Gosho Petkov", 28); p[18] = new Person("Pesho Ivanov", 19); p[19] = new Person("Sedemkan", 27); p[20] = new Person("Ivan Ivanov21", 31); return p; } public String writeInFile(Person[] arr) { String toWrite = ""; for(Person p : arr) { toWrite += p.getId()+"*"+p.getName()+"*"+p.getAge()+"*"; } try { File file = new File("Persons.txt"); FileWriter fs = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fs); if(file.exists()) { bw.write(toWrite); bw.flush(); bw.close(); System.out.println("File rdy"); }else { System.out.println("Cant create file"); } return toWrite; }catch(IOException e) { System.out.println("Error with file!"); e.printStackTrace(); return "EMPTY"; } } public Person[] readFromFile(){ try { File file = new File("Persons.txt"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String in = br.readLine(); String[] strArr = in.split("\\*"); Person[] personArr = new Person[strArr.length/3]; int j = 0; for(int i=0;i<strArr.length;i+=3,j++) { personArr[j] = new Person(strArr[i+1],Integer.valueOf(strArr[i+2])); personArr[j].setId(Integer.valueOf(strArr[i])); } System.out.println("File read : Completed!"); br.close(); return personArr; }catch(IOException e) { System.out.println("Error with file opening!"); e.printStackTrace(); return null; } } }
18.668675
74
0.60342
4c331ca5b8664a129b4d3fd905c3bb05b823d28e
4,401
package com.seals.shubham.myapplication; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class LoginActivity extends AppCompatActivity { dbController db = new dbController(this); EditText regId,pass; Button logIn,exit; TextView forget,reg; CheckBox cb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); regId = (EditText)findViewById(R.id.LogRegId); pass = (EditText)findViewById(R.id.LogPass); forget = (TextView)findViewById(R.id.frgtPass); exit = (Button)findViewById(R.id.btnExit); reg = (TextView)findViewById(R.id.CreAcc); cb = (CheckBox)findViewById(R.id.showPass); logIn = (Button)findViewById(R.id.btnLog); /*To Show Password in Normal Manner when CheckBox is ticked*/ cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if(b){ pass.setInputType(InputType.TYPE_NUMBER_VARIATION_NORMAL); } else{ pass.setInputType(129); } } }); /*Clicking on Create Account Takes the user to Registration Activity*/ reg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(getApplicationContext(),RegisterActivity.class);//Intent to Registration Activity startActivity(i); //Start the Intent } }); /*For resetting the Password*/ forget.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(getApplicationContext(),ForgetPassword.class); //Intent to Forget Password Activity startActivity(i); } }); /*this takes user to his Profile*/ logIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String userName = regId.getText().toString(); String password = pass.getText().toString(); regId.setText(""); pass.setText(""); if(db.checkData(userName,password)==1){ Intent i = new Intent(getApplicationContext(),CommonActivity.class); startActivity(i); } else{ Toast.makeText(getApplicationContext(),"Invalid User",Toast.LENGTH_LONG).show(); } } }); /*Exit Takes it Out of the Application*/ exit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder ab = new AlertDialog.Builder(LoginActivity.this); ab.setMessage("Hey Fella!Really wanna Check Out?");//Message to be Shown to the User when he Click on Exit ab.setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { /*If this Option is selected then user resides in the Application****Dialog is dismissed*/ dialogInterface.dismiss(); } }); ab.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { /*If this Option is Selected then Application is Closed...*/ finishAffinity(); } }); ab.show(); } }); } }
42.317308
122
0.592138
e1369720eeead82d56e9a5f0c975535609b8b446
2,586
package com.mehmetakiftutuncu.muezzin.activities; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.mehmetakiftutuncu.muezzin.R; import net.yslibrary.licenseadapter.LicenseAdapter; import net.yslibrary.licenseadapter.LicenseEntry; import net.yslibrary.licenseadapter.Licenses; import java.util.ArrayList; public class LicencesActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_licences); ArrayList<LicenseEntry> licences = new ArrayList<>(); // Libraries that are not hosted on GitHub licences.add(Licenses.noContent("Android SDK", "Google Inc.", "https://developer.android.com/sdk/terms.html")); licences.add(Licenses.noContent("Android Support Libraries", "Google Inc.", "https://developer.android.com/sdk/terms.html")); licences.add(Licenses.noContent("Mosque Vector Icon", "Freepik", "https://www.flaticon.com")); // Libraries that are hosted on GitHub, but do not provide license text licences.add(Licenses.fromGitHub("Kennyc1012/MultiStateView", Licenses.LICENSE_APACHE_V2)); // Libraries that are hosted on GitHub, and "LICENSE.md" is provided licences.add(Licenses.fromGitHub("makiftutuncu/Toolbelt", Licenses.FILE_MD)); // Libraries that are hosted on GitHub, and "LICENSE.txt" is provided licences.add(Licenses.fromGitHub("arimorty/floatingsearchview")); licences.add(Licenses.fromGitHub("stephentuso/welcome-android")); licences.add(Licenses.fromGitHub("square/okhttp")); licences.add(Licenses.fromGitHub("JodaOrg/joda-time")); // Libraries that are hosted on GitHub, and license file is provided as "LICENSE" licences.add(Licenses.fromGitHub("Maddoc42/Android-Material-Icon-Generator", Licenses.FILE_NO_EXTENSION)); licences.add(Licenses.fromGitHub("yshrsmz/LicenseAdapter", Licenses.FILE_NO_EXTENSION)); LicenseAdapter adapter = new LicenseAdapter(licences); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView_licences); if (recyclerView != null) { recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(adapter); Licenses.load(licences); } } }
46.178571
133
0.737432
26ee6b2da4bc4bff9a70206d9027599d3ed8588f
552
package org.pnop.waf.sample.lv.sb; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { private SampleService service; public SampleController(SampleService service) { this.service = service; } @GetMapping("/test/{code}") public String test1(@PathVariable("code") int code ) { return service.test1(code); } }
26.285714
63
0.713768
a273c2c2a1e9946a6ec23b57af3f891757fdd919
2,309
package io.costax.formulas; import io.costax.relationships.formulas.BankAccount; import io.github.jlmc.jpa.test.annotation.JpaContext; import io.github.jlmc.jpa.test.annotation.JpaTest; import io.github.jlmc.jpa.test.junit.JpaProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayNameGeneration; import org.junit.jupiter.api.DisplayNameGenerator; import org.junit.jupiter.api.Test; import java.math.BigDecimal; @JpaTest(persistenceUnit = "it") @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) public class JoinFormulaTest { private static final Integer ROGER_ID = 1; private static final Integer SERENA_ID = 2; @JpaContext public JpaProvider provider; @Test public void should_generate_some_bank_accounts() { provider.doInTx(em -> { final BankAccount roger = BankAccount.of(ROGER_ID, "Roger"); em.persist(roger); final BankAccount serena = BankAccount.of(SERENA_ID, "Serena"); em.persist(serena); }); // Add money to roger provider.doInTx(em -> { final BankAccount bankAccount = em.find(BankAccount.class, ROGER_ID); bankAccount.push(new BigDecimal("10000.91")); bankAccount.push(new BigDecimal("9999.09")); }); // Remove money to roger provider.doInTx(em -> { final BankAccount bankAccount = em.find(BankAccount.class, ROGER_ID); bankAccount.pull(new BigDecimal("500.00")); }); // add money to serena provider.doInTx(em -> { final BankAccount bankAccount = em.find(BankAccount.class, SERENA_ID); bankAccount.push(new BigDecimal("100.90")); bankAccount.push(new BigDecimal("50.00")); }); // What the value of the account? And what is the last Movement? provider.doIt(em -> { final BankAccount bankAccount = em.find(BankAccount.class, ROGER_ID); Assertions.assertEquals(0, new BigDecimal("19500.00").compareTo(bankAccount.getBalance())); Assertions.assertNotNull(bankAccount.getLastMovement()); Assertions.assertEquals(0, new BigDecimal("-500").compareTo(bankAccount.getLastMovement().getValue())); }); } }
33.463768
115
0.666522
a082cd89194685d059ad38e6b94553f788c448c7
3,726
package org.quincy.rock.sso; import java.util.Arrays; import java.util.Collection; import org.quincy.rock.core.vo.BaseEntity; import org.quincy.rock.core.vo.Vo; /** * <b>操作信息类。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * <p><b>修改列表:</b></p> * <table width="100%" cellSpacing=1 cellPadding=3 border=1> * <tr bgcolor="#CCCCFF"><td>序号</td><td>作者</td><td>修改日期</td><td>修改内容</td></tr> * <!-- 在此添加修改列表,参考第一行内容 --> * <tr><td>1</td><td>wks</td><td>2008-10-18 下午07:25:39</td><td>建立类型</td></tr> * * </table> * @version 1.0 * @author wks * @since 1.0 */ public class OpInfo extends BaseEntity<String> { /** * serialVersionUID。 */ private static final long serialVersionUID = 2412711330260257955L; /** * 操作标识。 */ private String opCode; /** * 操作名称 */ private String opName; /** * 操作时间。 */ private long opTime = System.currentTimeMillis(); /** * 操作说明。 */ private String opDescr; /** * 客户机地址。 */ private String hostAddr; /** * id。 * @see org.quincy.rock.core.vo.Vo#id() */ @Override public String id() { return opCode; } /** * <b>id。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @param id * @return */ @Override public Vo<String> id(String id) { this.opCode = id; return this; } /** * <b>获得操作标识。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @return 操作标识 */ public String getOpCode() { return opCode; } /** * <b>设置操作标识。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @param opCode 操作标识 */ public void setOpCode(String opCode) { this.opCode = opCode; } /** * <b>获得操作名称。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @return 操作名称 */ public String getOpName() { return opName; } /** * <b>设置操作名称。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @param opName 操作名称 */ public void setOpName(String opName) { this.opName = opName; } /** * <b>获得操作时间。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @return 操作时间 */ public long getOpTime() { return opTime; } /** * <b>设置操作时间。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @param opTime 操作时间 */ public void setOpTime(long opTime) { this.opTime = opTime; } /** * <b>获得操作说明。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @return 操作说明 */ public String getOpDescr() { return opDescr; } /** * <b>设置操作说明。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @param opDescr 操作说明 */ public void setOpDescr(String opDescr) { this.opDescr = opDescr; } /** * <b>获得客户机地址。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @return 客户机地址 */ public String getHostAddr() { return hostAddr; } /** * <b>设置客户机地址。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @param hostAddr 客户机地址 */ public void setHostAddr(String hostAddr) { this.hostAddr = hostAddr; } /** * propertyNames4ToString。 * @see org.quincy.rock.core.sso.ClientInfo#propertyNames4ToString() */ @Override protected Collection<String> propertyNames4ToString() { Collection<String> cs = super.propertyNames4ToString(); cs.addAll(Arrays.asList("opCode", "opName")); return cs; } /** * <b>创建操作信息。</b> * <p><b>详细说明:</b></p> * <!-- 在此添加详细说明 --> * 无。 * @param opCode 操作代码 * @param opName 操作名称 * @param opTime 操作时间 * @param opDescr 操作说明 * @param hostAddr 客户机地址 * @return OpInfo */ public static OpInfo of(String opCode, String opName, long opTime, String opDescr, String hostAddr) { OpInfo opInfo = new OpInfo(); opInfo.setOpCode(opCode); opInfo.setOpName(opName); opInfo.setOpTime(opTime); opInfo.setOpDescr(opDescr); opInfo.setHostAddr(hostAddr); return opInfo; } }
17.170507
102
0.562802
0d3621401420a1e5e3e8d4084b0eca02b78dd136
1,439
/** * */ package de.kjEngine.demos; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author konst * */ public class Autismus { private static class IntPtr { int value; } /** * @param args */ public static void main(String[] args) { File root = new File("../"); Map<String, IntPtr> lines = new HashMap<>(); scanFiles(root, lines); for (String extension : lines.keySet()) { System.out.println(extension + ": " + lines.get(extension).value + " lines"); } } private static void scanFiles(File root, Map<String, IntPtr> target) { for (File file : root.listFiles()) { if (file.isDirectory()) { scanFiles(file, target); } else { String name = file.getName(); String extension = null; if (name.contains(".")) { String[] pts = name.split("\\."); extension = pts[pts.length - 1]; } if (extension != null && (extension.equals("java") || extension.equals("shader"))) { IntPtr lines = target.get(extension); if (lines == null) { lines = new IntPtr(); target.put(extension, lines); } try { BufferedReader in = new BufferedReader(new FileReader(file)); while (in.readLine() != null) { lines.value++; } in.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
21.80303
88
0.596942
33981017cdc9892e6cf3fbb1fec372cc6c0f9d7e
2,043
package a.a.k.a.a; import java.util.*; public class b extends a { private Map<String, String> bbh; public b() { super(); this.bbh = new HashMap<String, String>() { public final /* synthetic */ b bbg; public b$a() { this.bbg = bbg; super(); } { this.put("the", "te"); this.put("check", "czech"); this.put("your", "ur"); this.put("who ", "hoo"); this.put("me", " i"); this.put("i", " me"); this.put("ok", "k"); this.put("inter", "intre"); this.put("family", "fam"); this.put("crystal", "cyrtal"); this.put("i'm", "me is"); this.put("im", "me is"); this.put("racist", "rasist"); this.put("to", "2"); this.put("have", "av"); this.put("32k", "32kay"); this.put("32ks", "32kays"); this.put("hause", "horse"); this.put("house", "horse"); this.put("hausemaster", "horsemaster"); this.put("housemaster", "horsemaster"); this.put("jesus", "jebus"); this.put("spawn", "spwan"); this.put("cookiedragon", "cookiewagon"); this.put("cookiedragon234", "cookiewagon234"); this.put("tigermouthbear", "tigressmouthbear"); this.put("carbolemons", "carbonlenons"); this.put("give", "gib"); } }; } @Override public String b() { return "Chav"; } @Override public String b(final String s) { final StringBuilder sb = new StringBuilder(); for (final String s2 : s.split(" ")) { sb.append(this.bbh.getOrDefault(s2.toLowerCase(), s2)).append(" "); } return sb.toString(); } }
30.954545
79
0.418992
2351fb3428db8053d4c2508d09c0932de15731db
11,004
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.lens.driver.jdbc; import static org.apache.hadoop.hive.ql.parse.HiveParser.*; import java.util.ArrayList; import java.util.TreeSet; import org.apache.lens.cube.parse.CubeSemanticAnalyzer; import org.apache.lens.cube.parse.HQLParser; import org.apache.lens.server.api.error.LensException; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.parse.ASTNode; import org.apache.hadoop.hive.ql.parse.HiveParser; import org.apache.hadoop.hive.ql.parse.QB; import org.apache.hadoop.hive.ql.parse.SemanticException; import lombok.Getter; import lombok.extern.slf4j.Slf4j; @Slf4j public class DruidSQLRewriter extends ColumnarSQLRewriter { /** * Is Having supported. */ @Getter protected boolean isHavingSupported; /** * Is OrderBy supported. */ @Getter protected boolean isOrderBySupported; /** * Whether to resolve native tables or not. In case the query has sub query, the outer query may not * require native table resolution */ private boolean resolveNativeTables; /** * Analyze internal. * * @throws SemanticException the semantic exception */ public void analyzeInternal(Configuration conf, HiveConf hconf) throws SemanticException { CubeSemanticAnalyzer c1 = new CubeSemanticAnalyzer(conf, hconf); QB qb = new QB(null, null, false); if (!c1.doPhase1(ast, qb, c1.initPhase1Ctx(), null)) { return; } if (!qb.getSubqAliases().isEmpty()) { log.warn("Subqueries in from clause is not supported by {} Query : {}", this, this.query); throw new SemanticException("Subqueries in from clause is not supported by " + this + " Query : " + this.query); } // Get clause name TreeSet<String> ks = new TreeSet<String>(qb.getParseInfo().getClauseNames()); /* The clause name. */ String clauseName = ks.first(); if (qb.getParseInfo().getJoinExpr() != null) { log.warn("Join queries not supported by {} Query : {}", this, this.query); throw new SemanticException("Join queries not supported by " + this + " Query : " + this.query); } // Split query into trees if (qb.getParseInfo().getWhrForClause(clauseName) != null) { this.whereAST = qb.getParseInfo().getWhrForClause(clauseName); } if (qb.getParseInfo().getGroupByForClause(clauseName) != null) { this.groupByAST = qb.getParseInfo().getGroupByForClause(clauseName); } if (qb.getParseInfo().getSelForClause(clauseName) != null) { this.selectAST = qb.getParseInfo().getSelForClause(clauseName); } if (qb.getParseInfo().getHavingForClause(clauseName) != null) { this.havingAST = qb.getParseInfo().getHavingForClause(clauseName); } if (qb.getParseInfo().getOrderByForClause(clauseName) != null) { this.orderByAST = qb.getParseInfo().getOrderByForClause(clauseName); } this.fromAST = HQLParser.findNodeByPath(ast, TOK_FROM); } /** * Builds the query. * * @throws SemanticException */ public void buildDruidQuery(Configuration conf, HiveConf hconf) throws SemanticException, LensException { analyzeInternal(conf, hconf); if (resolveNativeTables) { replaceWithUnderlyingStorage(hconf); } // Get the limit clause String limit = getLimitClause(ast); ArrayList<String> filters = new ArrayList<>(); getWhereString(whereAST, filters); String havingTree = null; String orderbyTree = null; if (isHavingSupported) { havingTree = HQLParser.getString(havingAST, HQLParser.AppendMode.DEFAULT); } if (isOrderBySupported) { orderbyTree = HQLParser.getString(orderByAST, HQLParser.AppendMode.DEFAULT); } // construct query with fact sub query constructQuery(HQLParser.getString(selectAST, HQLParser.AppendMode.DEFAULT), filters, HQLParser.getString(groupByAST, HQLParser.AppendMode.DEFAULT), havingTree, orderbyTree, limit); } private ArrayList<String> getWhereString(ASTNode node, ArrayList<String> filters) throws LensException { if (node == null) { return null; } if (node.getToken().getType() == HiveParser.KW_AND) { // left child is "and" and right child is subquery if (node.getChild(0).getType() == HiveParser.KW_AND) { filters.add(getfilterSubquery(node, 1)); } else if (node.getChildCount() > 1) { for (int i = 0; i < node.getChildCount(); i++) { filters.add(getfilterSubquery(node, i)); } } } else if (node.getParent().getType() == HiveParser.TOK_WHERE && node.getToken().getType() != HiveParser.KW_AND) { filters.add(HQLParser.getString(node, HQLParser.AppendMode.DEFAULT)); } for (int i = 0; i < node.getChildCount(); i++) { ASTNode child = (ASTNode) node.getChild(i); return getWhereString(child, filters); } return filters; } private String getfilterSubquery(ASTNode node, int index) throws LensException { String filter; if (node.getChild(index).getType() == HiveParser.TOK_SUBQUERY_EXPR) { log.warn("Subqueries in where clause not supported by {} Query : {}", this, this.query); throw new LensException("Subqueries in where clause not supported by " + this + " Query : " + this.query); } else { filter = HQLParser.getString((ASTNode) node.getChild(index), HQLParser.AppendMode.DEFAULT); } return filter; } /** * Construct final query using all trees * * @param selectTree the selecttree * @param whereFilters the wheretree * @param groupbyTree the groupbytree * @param havingTree the havingtree * @param orderbyTree the orderbytree * @param limit the limit */ private void constructQuery( String selectTree, ArrayList<String> whereFilters, String groupbyTree, String havingTree, String orderbyTree, String limit) { log.info("In construct query .."); rewrittenQuery.append("select ").append(selectTree.replaceAll("`", "\"")).append(" from "); String factNameAndAlias = getFactNameAlias(fromAST); rewrittenQuery.append(factNameAndAlias); if (!whereFilters.isEmpty()) { rewrittenQuery.append(" where ").append(StringUtils.join(whereFilters, " and ")); } if (StringUtils.isNotBlank(groupbyTree)) { rewrittenQuery.append(" group by ").append(groupbyTree); } if (StringUtils.isNotBlank(havingTree)) { rewrittenQuery.append(" having ").append(havingTree); } if (StringUtils.isNotBlank(orderbyTree)) { rewrittenQuery.append(" order by ").append(orderbyTree); } if (StringUtils.isNotBlank(limit)) { rewrittenQuery.append(" limit ").append(limit); } } /* * (non-Javadoc) * * @see org.apache.lens.server.api.query.QueryRewriter#rewrite(java.lang.String, org.apache.hadoop.conf.Configuration) */ @Override public String rewrite(String query, Configuration conf, HiveConf metastoreConf) throws LensException { this.query = query; String reWritten = rewrite(HQLParser.parseHQL(query, metastoreConf), conf, metastoreConf, true); log.info("Rewritten : {}", reWritten); String queryReplacedUdf = replaceUDFForDB(reWritten); log.info("Input Query : {}", query); log.info("Rewritten Query : {}", queryReplacedUdf); return queryReplacedUdf; } public String rewrite(ASTNode currNode, Configuration conf, HiveConf metastoreConf, boolean resolveNativeTables) throws LensException { this.resolveNativeTables = resolveNativeTables; rewrittenQuery.setLength(0); reset(); this.ast = currNode; isHavingSupported = conf.getBoolean(JDBCDriverConfConstants.JDBC_IS_HAVING_SUPPORTED, JDBCDriverConfConstants.DEFAULT_JDBC_IS_HAVING_SUPPORTED); isOrderBySupported = conf.getBoolean(JDBCDriverConfConstants.JDBC_IS_ORDERBY_SUPPORTED, JDBCDriverConfConstants.DEFAULT_JDBC_IS_ORDERBY_SUPPORTED); ASTNode fromNode = HQLParser.findNodeByPath(currNode, TOK_FROM); if (fromNode != null) { if (fromNode.getChild(0).getType() == TOK_SUBQUERY) { log.warn("Subqueries in from clause not supported by {} Query : {}", this, this.query); throw new LensException("Subqueries in from clause not supported by " + this + " Query : " + this.query); } else if (isOfTypeJoin(fromNode.getChild(0).getType())) { log.warn("Join in from clause not supported by {} Query : {}", this, this.query); throw new LensException("Join in from clause not supported by " + this + " Query : " + this.query); } } if (currNode.getToken().getType() == TOK_UNIONALL) { log.warn("Union queries are not supported by {} Query : {}", this, this.query); throw new LensException("Union queries are not supported by " + this + " Query : " + this.query); } if (!isHavingSupported && HQLParser.findNodeByPath(currNode, HiveParser.TOK_INSERT, HiveParser.TOK_HAVING) != null) { log.warn("Having queries are not supported by {} Query : {}", this, this.query); throw new LensException("Having queries are not supported by " + this + " Query : " + this.query); } if (!isOrderBySupported && HQLParser.findNodeByPath(currNode, HiveParser.TOK_INSERT, HiveParser.TOK_ORDERBY) != null) { log.warn("Order by queries are not supported by {} Query : {}", this, this.query); throw new LensException("Order by queries are not supported by " + this + " Query : " + this.query); } String rewritternQueryText = rewrittenQuery.toString(); if (currNode.getToken().getType() == TOK_QUERY) { try { buildDruidQuery(conf, metastoreConf); rewritternQueryText = rewrittenQuery.toString(); log.info("Rewritten query from build : " + rewritternQueryText); } catch (SemanticException e) { throw new LensException(e); } } return rewritternQueryText; } private boolean isOfTypeJoin(int type) { return (type == TOK_JOIN || type == TOK_LEFTOUTERJOIN || type == TOK_RIGHTOUTERJOIN || type == TOK_FULLOUTERJOIN || type == TOK_LEFTSEMIJOIN || type == TOK_UNIQUEJOIN); } }
36.926174
120
0.691658
3818e7df0edea7ca150eb63a74d4d89574bb12f5
2,699
package net.sf.classifier4J.vector; import junit.framework.TestCase; public class VectorUtilsTest extends TestCase { public void testScalarProduct() { try { double result = VectorUtils.scalarProduct(new int[] { 1, 2, 3 }, null); fail("Null argument allowed"); } catch (IllegalArgumentException e) { // expected } try { double result = VectorUtils.scalarProduct(null, new int[] { 1, 2, 3 }); fail("Null argument allowed"); } catch (IllegalArgumentException e) { // expected } try { double result = VectorUtils.scalarProduct(new int[] {1}, new int[] { 1, 2, 3 }); fail("Arguments of different size allowed"); } catch (IllegalArgumentException e) { // expected } assertEquals(3, VectorUtils.scalarProduct(new int[] {1,1,1}, new int[] { 1,1,1})); assertEquals(6, VectorUtils.scalarProduct(new int[] {1,1,1}, new int[] { 1,2,3})); assertEquals(14, VectorUtils.scalarProduct(new int[] {1,2,3}, new int[] { 1,2,3 })); assertEquals(0, VectorUtils.scalarProduct(new int[] {0,0,0}, new int[] { 1,2,3 })); } public void testVectorLength() { try { double result = VectorUtils.vectorLength(null); fail("Null argument allowed"); } catch (IllegalArgumentException e) { // expected } assertEquals(Math.sqrt(2), VectorUtils.vectorLength(new int[]{1,1}),0.001d); assertEquals(Math.sqrt(3), VectorUtils.vectorLength(new int[]{1,1,1}),0.001d); assertEquals(Math.sqrt(12), VectorUtils.vectorLength(new int[]{2,2,2}),0.001d); } public void testCosineOfVectors() { try { double result = VectorUtils.cosineOfVectors(new int[] { 1, 2, 3 }, null); fail("Null argument allowed"); } catch (IllegalArgumentException e) { // expected } try { double result = VectorUtils.cosineOfVectors(null, new int[] { 1, 2, 3 }); fail("Null argument allowed"); } catch (IllegalArgumentException e) { // expected } try { double result = VectorUtils.cosineOfVectors(new int[] {1}, new int[] { 1, 2, 3 }); fail("Arguments of different size allowed"); } catch (IllegalArgumentException e) { // expected } int[] one = new int[]{1,1,1}; int[] two = new int[]{1,1,1}; assertEquals(1d, VectorUtils.cosineOfVectors(one, two), 0.001); } }
35.051948
94
0.545758
43253527d6f6621bf5693161b8a6b31f6a69c3b4
142
package com.kristina.creational_patterns.AbstractFactory; public interface Factory { Tire makeTire(); Headlight makeHeadlight(); }
20.285714
57
0.760563
769b7b2a84050d4110c11c95d8bc6fee37c01889
18,712
package com.example.WorkoutBuddy.workoutbuddy.Activities; // TODO decouple even more try to keep database and business login as serpereate as possible,elimnate any mgic numbers /* -keep local sql database -redo photos/store in an actual location and in database just store the file path(for local images) -gonna need php */ import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.*; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.design.widget.NavigationView; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.*; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ScrollView; import android.widget.TextView; import com.example.WorkoutBuddy.workoutbuddy.DataBase.Data.Exercise; import com.example.WorkoutBuddy.workoutbuddy.DataBase.Data.ProgressPhoto; import com.example.WorkoutBuddy.workoutbuddy.DataBase.DatabaseManagment.DataBaseContract; import com.example.WorkoutBuddy.workoutbuddy.DataBase.TableManagers.*; import com.example.WorkoutBuddy.workoutbuddy.Fragments.FragmentPopupWindows.ExercisePopupWindows.CustomExercisePopup; import com.example.WorkoutBuddy.workoutbuddy.Fragments.Managers.FragmentStackManager; import com.example.WorkoutBuddy.workoutbuddy.Fragments.MainFragments.*; import com.example.WorkoutBuddy.workoutbuddy.Fragments.SubFragments.BlankExerciseFragment; import com.example.WorkoutBuddy.workoutbuddy.R; import com.example.WorkoutBuddy.workoutbuddy.RemoteDatabase.RequestHandlers.ExerciseRequestHandler; import com.example.WorkoutBuddy.workoutbuddy.RemoteDatabase.RequestHandlers.ProgressPhotoRequestHandler; import java.io.File; import java.util.List; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private Menu menu; private boolean activityHidden = false; private ExerciseFragment exercise_frag; public static final int RESULT_LOAD_IMAGE = 1; private CustomExercisePopup customExercisePopup; public static final int REQUEST_IMAGE_CAPTURE = 2; private ProgressPhotosFragment progressPhoto_frag; private FragmentStackManager fragmentStackManager; @Override protected void onCreate(Bundle savedInstanceState) {//pictures ARE downlowading error in exercise table becuase of the way it is stored super.onCreate(savedInstanceState); setBaseContent(); getPermissions(); loadRecentStats(); fragmentStackManager = new FragmentStackManager(getSupportFragmentManager()); setTileOnCLickListeners(); } private void setBaseContent() { setContentView(R.layout.activity_main); setDrawer(setToolbar()); setNavigationView(); } private Toolbar setToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); return toolbar; } private void setDrawer(Toolbar toolbar) { DrawerLayout mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); mDrawer.setDrawerListener(toggle); toggle.syncState(); } private void setNavigationView() { NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Bitmap customImageBitmap = getGalleryImage(requestCode, resultCode, data); if(customImageBitmap != null) {//this is null for some reason customExercisePopup.setExerciseImageBitmap(customImageBitmap); customExercisePopup.setImageViewWithGalleryImage(); } else { progressPhoto_frag.saveImage();//error being thrown here when //not clicking on a custom exercise image from the gallery to save } } private Bitmap getGalleryImage(int requestCode,int resultCode,Intent data) { if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); return BitmapFactory.decodeFile(picturePath); } return null; } @Override public void onBackPressed() { FragmentStackManager.PopFragmentStack(); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if(getSupportFragmentManager().getBackStackEntryCount()==1 && activityHidden) { activityHidden = false; showMainActivityContent(); } if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); this.menu = menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.body_stats: showBodyStatsFragment(); break; case R.id.lifting_stats: showWorkoutStatsFragment(); break; case R.id.workout_menu: showWorkoutFragment(); break; case R.id.exercise_menu: showExerciseFragment(); break; case R.id.progress_photos: showProgressPhotoFragment(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } private void getPermissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) { } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},1); } } } private void getCameraPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},REQUEST_IMAGE_CAPTURE); } } } private void setTileOnCLickListeners() { exerciseTileCLicked(); workoutTileClicked(); progressPhotosTileCLicked(); workoutStatsTileClicked(); bodyStatsTileClicked(); } private void exerciseTileCLicked() { CardView cardView = (CardView) findViewById(R.id.exerciseTile); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showExerciseFragment(); } }); } private void workoutTileClicked() { CardView cardView = (CardView) findViewById(R.id.workoutTile); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showWorkoutFragment(); } }); } private void progressPhotosTileCLicked() { CardView cardView = (CardView) findViewById(R.id.progressPhotoTile); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showProgressPhotoFragment(); } }); } private void workoutStatsTileClicked() { CardView cardView = (CardView) findViewById(R.id.workoutStatsTile); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showWorkoutStatsFragment(); } }); } private void bodyStatsTileClicked() { CardView cardView = (CardView) findViewById(R.id.bodyStatsTile); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showBodyStatsFragment(); } }); } private void showWorkoutStatsFragment() { WorkoutStatsFragment workoutStatsFragment = new WorkoutStatsFragment(); workoutStatsFragment.setMenu(menu); workoutStatsFragment.setFragmentStackManager(fragmentStackManager); fragmentStackManager.addFragmentToStack(workoutStatsFragment,R.id.workoutStats_fragment); hideMainActivity(); } private void showBodyStatsFragment() { BodyStatsFragment bodyStats_fragment = new BodyStatsFragment(); fragmentStackManager.addFragmentToStack(bodyStats_fragment,R.id.bodyStats_fragment); hideMainActivity(); } private void showExerciseFragment() { exercise_frag = new ExerciseFragment(); exercise_frag.setMenu(menu); exercise_frag.setFragmentStackManager(fragmentStackManager); exercise_frag.setMainActivity(this); fragmentStackManager.addFragmentToStack(exercise_frag,R.id.exercise_fragment); hideMainActivity(); } public void showBlankExerciseFragment() { BlankExerciseFragment blankExercise_frag = new BlankExerciseFragment(); fragmentStackManager.addFragmentToStack(blankExercise_frag,R.id.blankExercise_fragment); } private void showWorkoutFragment() { MainWorkoutFragment mainWorkout_frag = new MainWorkoutFragment(); mainWorkout_frag.setMenu(menu); mainWorkout_frag.setMainActivity(this); mainWorkout_frag.setFragmentStackManager(fragmentStackManager); fragmentStackManager.addFragmentToStack(mainWorkout_frag,R.id.mainWorkout_fragment); hideMainActivity(); } private void showProgressPhotoFragment() { getCameraPermission(); progressPhoto_frag = new ProgressPhotosFragment(); progressPhoto_frag.setMainActivity(this); fragmentStackManager.addFragmentToStack(progressPhoto_frag, R.id.progressPhotos_fragment); hideMainActivity(); } public void showAddExercisePopupWindow() { customExercisePopup = new CustomExercisePopup(getCurrentFocus(),getBaseContext()); customExercisePopup.setExerciseFragment(exercise_frag); customExercisePopup.setMainActivity(this); customExercisePopup.showPopupWindow(); } private void showMainActivityContent() { ScrollView scrollView = (ScrollView) findViewById(R.id.activityScrollView); scrollView.setVisibility(View.VISIBLE); loadRecentStats(); } private void hideMainActivity() { if (!activityHidden) { hideMainActivityContent(); activityHidden = true; } } private void hideMainActivityContent() { ScrollView scrollView = (ScrollView) findViewById(R.id.activityScrollView); scrollView.setVisibility(View.INVISIBLE); } private void loadRecentStats() { try { loadRecentBodyStats(); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } try { loadRecentWorkoutStats(); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } } private void loadRecentWorkoutStats() throws IndexOutOfBoundsException { int INDEX = 0; WorkoutStatsTable table = new WorkoutStatsTable(getBaseContext()); loadRecentWorkoutStatsPt1(table,INDEX); loadRecentWorkoutStatsPt2(table,INDEX); } private void loadRecentBodyStats() throws IndexOutOfBoundsException{ int INDEX = 0; BodyTable table = new BodyTable(getBaseContext()); loadRecentBodyStatsPt1(table, INDEX); loadRecentBodyStatsPt2(table, INDEX); loadRecentBodyStatsPt3(table, INDEX); } private void loadRecentBodyStatsPt1(BodyTable table,int INDEX) throws IndexOutOfBoundsException { String date = table.getColumn(DataBaseContract.BodyData.COLUMN_DATE,INDEX+1, DataBaseContract.BodyData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); String weight = table.getColumn(DataBaseContract.BodyData.COLUMN_WEIGHT,INDEX+1, DataBaseContract.BodyData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); String chest = table.getColumn(DataBaseContract.BodyData.COLUMN_CHEST_SIZE,INDEX+1, DataBaseContract.BodyData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); TextView textView = (TextView) findViewById(R.id.recentDateView); textView.setText(date); textView = (TextView) findViewById(R.id.recentWeightView); textView.setText(weight); textView = (TextView) findViewById(R.id.recentChestView); textView.setText(chest); } private void loadRecentBodyStatsPt2(BodyTable table,int INDEX) throws IndexOutOfBoundsException { String back = table.getColumn(DataBaseContract.BodyData.COLUMN_BACK_SIZE,INDEX+1, DataBaseContract.BodyData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); String arm = table.getColumn(DataBaseContract.BodyData.COLUMN_ARM_SIZE,INDEX+1, DataBaseContract.BodyData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); String forearm = table.getColumn(DataBaseContract.BodyData.COLUMN_FOREARM_SIZE,INDEX+1, DataBaseContract.BodyData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); TextView textView = (TextView) findViewById(R.id.recentBackView); textView.setText(back); textView = (TextView) findViewById(R.id.recentArmsView); textView.setText(arm); textView = (TextView) findViewById(R.id.recentForearmsView); textView.setText(forearm); } private void loadRecentBodyStatsPt3(BodyTable table,int INDEX) throws IndexOutOfBoundsException { String waist = table.getColumn(DataBaseContract.BodyData.COLUMN_WAIST_SIZE,INDEX+1, DataBaseContract.BodyData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); String quad = table.getColumn(DataBaseContract.BodyData.COLUMN_QUAD_SIZE,INDEX+1, DataBaseContract.BodyData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); String calves = table.getColumn(DataBaseContract.BodyData.COLUMN_CALF_SIZE,INDEX+1, DataBaseContract.BodyData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); TextView textView = (TextView) findViewById(R.id.recentWaistView); textView.setText(waist); textView = (TextView) findViewById(R.id.recentQuadsView); textView.setText(quad); textView = (TextView) findViewById(R.id.recentCalvesView); textView.setText(calves); } private void loadRecentWorkoutStatsPt1(WorkoutStatsTable table,int INDEX) throws IndexOutOfBoundsException { String date = table.getColumn(DataBaseContract.WorkoutData.COLUMN_DATE,INDEX+1, DataBaseContract.WorkoutData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); String mainWorkout = table.getColumn(DataBaseContract.WorkoutData.COLUMN_MAINWORKOUT,INDEX+1, DataBaseContract.WorkoutData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); String subWorkout = table.getColumn(DataBaseContract.WorkoutData.COLUMN_SUBWORKOUT,INDEX+1, DataBaseContract.WorkoutData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); TextView textView = (TextView) findViewById(R.id.recentWorkoutDateView); textView.setText(getString(R.string.datePointer)+" "+TableManager.getParsedDate(date)); textView = (TextView) findViewById(R.id.recentMainWorkoutView); textView.setText(getString(R.string.mainWorkoutPointer)+" "+mainWorkout); textView = (TextView) findViewById(R.id.recentSubWorkoutView); textView.setText(getString(R.string.subWorkoutPointer)+" "+subWorkout); } private void loadRecentWorkoutStatsPt2(WorkoutStatsTable table,int INDEX) throws IndexOutOfBoundsException { String sets = table.getColumn(DataBaseContract.WorkoutData.COLUMN_TOTAL_SETS,INDEX+1, DataBaseContract.WorkoutData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); String reps = table.getColumn(DataBaseContract.WorkoutData.COLUMN_TOTAL_REPS,INDEX+1, DataBaseContract.WorkoutData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); String weight = table.getColumn(DataBaseContract.WorkoutData.COLUMN_TOTAL_WEIGHT,INDEX+1, DataBaseContract.WorkoutData.COLUMN_DATE+" DESC LIMIT 1").get(INDEX); TextView textView = (TextView) findViewById(R.id.recentTotalSetsView); textView.setText(getString(R.string.totalReps)+" "+sets); textView = (TextView) findViewById(R.id.recentTotalRepsView); textView.setText(getString(R.string.totalReps)+" "+reps); textView = (TextView) findViewById(R.id.recentTotalWeightView); textView.setText(getString(R.string.totalWeight)+" "+weight); } }
41.035088
139
0.688489
b6e99f1572fe0b741e13970f42e5d48e4c264f83
801
package com.owen.framework.mvvm.presenter; import androidx.annotation.NonNull; import com.owen.framework.mvvm.view.IView; /** * IPresenter 实现类 * Presenter 基础类,业务 P 继承此类实现逻辑 * * @author ZhengYuanle */ public class MVVMPresenter<V extends IView> implements IPresenter<V> { //View(传递时对象为Activity/Fragment必须要销毁) protected V mView; @Override public void attachView(@NonNull V view) { mView = view; } @Override public void detachView() { mView = null; } /** * 获取View * 备注: getView() 在组件销毁后可能为 null 使用前通过 isAttached() 判断 * * @return */ public V getView() { return mView; } /** * View是否已经绑定 * * @return */ public boolean isAttached() { return mView != null; } }
16.6875
70
0.593009
bb22b975ab88d12826d282af7aab79dee8e1b30f
4,751
package com.canton.model.ontology; import java.io.Serializable; /** * 本体的三元组对象。 * * @author Rosahen * @version 1.0 */ public class Statement implements Serializable{ /** * */ private static final long serialVersionUID = -6570094052594038686L; /** * 三元组的主语。 */ private String subject; /** * 三元组主语所属的类名。 */ private String subjectClassName; /** * 三元组的谓语。 */ private String predicate; /** * 三元组谓语所属的类名。 */ private String predicateClassName; /** * 三元组的宾语。 */ private String object; /** * 三元组宾语所属的类名。 */ private String objectClassName = "null"; /** * 三元组所属的Graph名称。 */ private String namedGraph; public Statement() { super(); // TODO Auto-generated constructor stub } /** * 三元组的构造方法。 * * @param subject 三元组的主语。 * @param predicate 三元组的谓语。 * @param object 三元组的宾语。 * @param namedGraph 三元组所属的Graph。 */ public Statement(String subject, String predicate, String object, String namedGraph) { super(); this.subject = subject; this.predicate = predicate; this.object = object; this.namedGraph = namedGraph; } /** * 三元组的构造方法。 * * @param subject 三元组的主语。 * @param predicate 三元组的谓语。 * @param object 三元组的宾语。 */ public Statement(String subject, String predicate, String object) { super(); this.subject = subject; this.predicate = predicate; this.object = object; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getPredicate() { return predicate; } public void setPredicate(String predicate) { this.predicate = predicate; } public String getObject() { return object; } public void setObject(String object) { this.object = object; } public String getNamedGraph() { return namedGraph; } public void setNamedGraph(String namedGraph) { this.namedGraph = namedGraph; } public String getSubjectClassName() { return subjectClassName; } public void setSubjectClassName(String subjectClassName) { this.subjectClassName = subjectClassName; } public String getPredicateClassName() { return predicateClassName; } public void setPredicateClassName(String predicateClassName) { this.predicateClassName = predicateClassName; } public String getObjectClassName() { return objectClassName; } public void setObjectClassName(String objectClassName) { this.objectClassName = objectClassName; } @Override public String toString() { return "Statement [subject=" + subject + ", subjectClassName=" + subjectClassName + ", predicate=" + predicate + ", predicateClassName=" + predicateClassName + ", object=" + object + ", objectClassName=" + objectClassName + ", namedGraph=" + namedGraph + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((namedGraph == null) ? 0 : namedGraph.hashCode()); result = prime * result + ((object == null) ? 0 : object.hashCode()); result = prime * result + ((objectClassName == null) ? 0 : objectClassName.hashCode()); result = prime * result + ((predicate == null) ? 0 : predicate.hashCode()); result = prime * result + ((predicateClassName == null) ? 0 : predicateClassName.hashCode()); result = prime * result + ((subject == null) ? 0 : subject.hashCode()); result = prime * result + ((subjectClassName == null) ? 0 : subjectClassName.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; Statement other = (Statement) obj; if (namedGraph == null) { if (other.namedGraph != null) return false; } else if (!namedGraph.equals(other.namedGraph)) return false; if (object == null) { if (other.object != null) return false; } else if (!object.equals(other.object)) return false; if (objectClassName == null) { if (other.objectClassName != null) return false; } else if (!objectClassName.equals(other.objectClassName)) return false; if (predicate == null) { if (other.predicate != null) return false; } else if (!predicate.equals(other.predicate)) return false; if (predicateClassName == null) { if (other.predicateClassName != null) return false; } else if (!predicateClassName.equals(other.predicateClassName)) return false; if (subject == null) { if (other.subject != null) return false; } else if (!subject.equals(other.subject)) return false; if (subjectClassName == null) { if (other.subjectClassName != null) return false; } else if (!subjectClassName.equals(other.subjectClassName)) return false; return true; } }
21.99537
112
0.671017
7f061ccd87730c40006ba3fd31d28814ac359d83
9,390
package serializer; import main.Main; import views.FDView; import views.ParserView; import views.RootLayoutView; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; /** * @Author Dmitry Volovod * created on 14.10.2015 */ public class Serializer { //saving & loading states of flags and other private static final String PROPERTIES_STORE = "gaze-reckon.properties"; ParserView parserView; FDView fdView; RootLayoutView rootLayoutView; private Properties properties; public Serializer(Main mainApp) { properties = new Properties(); parserView = mainApp.getParserView(); fdView = mainApp.getFdView(); rootLayoutView = mainApp.getRootLayoutView(); } public boolean load() { File file = new File(PROPERTIES_STORE); if (file.exists()) { try { FileInputStream in = new FileInputStream(file); properties.loadFromXML(in); in.close(); } catch (IOException e) { e.printStackTrace(); return false; } try { //text fields parserView.setTrackerFileAddress((String) properties.get("TrackerFileAddress")); parserView.setTestFileAddress((String) properties.get("TestFileAddress")); parserView.setOutputFileName((String) properties.get("OutputFileName")); //flags parserView.setNumber(properties.get("Number").equals("True")); parserView.setTime(properties.get("Time").equals("True")); parserView.setStimulusPosition(properties.get("StimulusPosition").equals("True")); parserView.setFix(properties.get("Fix").equals("True")); parserView.setAvg(properties.get("Avg").equals("True")); parserView.setRaw(properties.get("Raw").equals("True")); parserView.setDAvg(properties.get("dAvg").equals("True")); parserView.setDeltaRaw(properties.get("dRaw").equals("True")); parserView.setLeftEyeAvg(properties.get("lEyeAvg").equals("True")); parserView.setLeftEyeRaw(properties.get("lEyeRaw").equals("True")); parserView.setLeftEyeDAvg(properties.get("lEyeDAvg").equals("True")); parserView.setLeftEyeDRaw(properties.get("lEyeDRaw").equals("True")); parserView.setLeftEyePCenter(properties.get("lEyePCenter").equals("True")); parserView.setLeftEyePSize(properties.get("lEyePSize").equals("True")); parserView.setRightEyeAvg(properties.get("rEyeAvg").equals("True")); parserView.setRightEyeRaw(properties.get("rEyeRaw").equals("True")); parserView.setRightEyeDAvg(properties.get("rEyeDAvg").equals("True")); parserView.setRightEyeDRaw(properties.get("rEyeDRaw").equals("True")); parserView.setRightEyePCenter(properties.get("rEyePCenter").equals("True")); parserView.setRightEyePSize(properties.get("rEyePSize").equals("True")); parserView.setTimeStamp(properties.get("TimeStamp").equals("True")); parserView.setCategory(properties.get("Category").equals("True")); parserView.setRequest(properties.get("Request").equals("True")); parserView.setState(properties.get("State").equals("True")); parserView.setStatuscode(properties.get("Statuscode").equals("True")); //fd elements states fdView.getIdt().setSelected(properties.get("IDT").equals("True")); fdView.setIdtLatency((String) properties.get("IDT_latency")); fdView.setIdtThreshold((String) properties.get("IDT_threshold")); fdView.getHyperbola().setSelected(properties.get("Hyperbola").equals("True")); fdView.getLogarithm().setSelected(properties.get("Logarithm").equals("True")); //RootLayout (Menu) elements states rootLayoutView.setLinearInterpolationFlag(properties.get("LinearSmoothingFilter").equals("True")); rootLayoutView.setListwiseDeletionFlag(properties.get("ListwiseDeletion").equals("True")); rootLayoutView.setSimpleRecoveryFlag(properties.get("SimpleRecovery").equals("True")); rootLayoutView.setCommaFlag(properties.get("CommaSeparator").equals("True")); rootLayoutView.setSemicolonFlag(properties.get("SemicolonSeparator").equals("True")); rootLayoutView.setUseConfigFlag(true); return true; } catch (NullPointerException ex) { file.delete(); return false; } } else { return false; } } public void store() { if (rootLayoutView.getUseConfigFlag()) { //parser elements states //text fields properties.put("TrackerFileAddress", parserView.getTrackerFileAddress()); properties.put("TestFileAddress", parserView.getTestFileAddress()); properties.put("OutputFileName", parserView.getOutputFileName()); //check boxes properties.put("Number", parserView.getNumber() ? "True" : "False"); properties.put("Time", parserView.getTime() ? "True" : "False"); properties.put("StimulusPosition", parserView.getStimulusPosition() ? "True" : "False"); properties.put("Fix", parserView.getFix() ? "True" : "False"); properties.put("Avg", parserView.getAvg() ? "True" : "False"); properties.put("Raw", parserView.getRaw() ? "True" : "False"); properties.put("dAvg", parserView.getDeltaAvg() ? "True" : "False"); properties.put("dRaw", parserView.getDeltaRaw() ? "True" : "False"); properties.put("lEyeAvg", parserView.getLeftEyeAvg() ? "True" : "False"); properties.put("lEyeRaw", parserView.getLeftEyeRaw() ? "True" : "False"); properties.put("lEyeDAvg", parserView.getLeftEyeDAvg() ? "True" : "False"); properties.put("lEyeDRaw", parserView.getLeftEyeDRaw() ? "True" : "False"); properties.put("lEyePCenter", parserView.getLeftEyePCenter() ? "True" : "False"); properties.put("lEyePSize", parserView.getLeftEyePSize() ? "True" : "False"); properties.put("rEyeAvg", parserView.getRightEyeAvg() ? "True" : "False"); properties.put("rEyeRaw", parserView.getRightEyeRaw() ? "True" : "False"); properties.put("rEyeDAvg", parserView.getRightEyeDAvg() ? "True" : "False"); properties.put("rEyeDRaw", parserView.getRightEyeDRaw() ? "True" : "False"); properties.put("rEyePCenter", parserView.getRightEyePCenter() ? "True" : "False"); properties.put("rEyePSize", parserView.getRightEyePSize() ? "True" : "False"); properties.put("TimeStamp", parserView.getTimeStamp() ? "True" : "False"); properties.put("Category", parserView.getCategory() ? "True" : "False"); properties.put("Request", parserView.getRequest() ? "True" : "False"); properties.put("State", parserView.getState() ? "True" : "False"); properties.put("Statuscode", parserView.getStatuscode() ? "True" : "False"); //fd elements states properties.put("IDT", fdView.getIdt().isSelected() ? "True" : "False"); properties.put("IDT_latency", fdView.getIdtLatency()); properties.put("IDT_threshold", fdView.getIdtThreshold()); properties.put("Hyperbola", fdView.getHyperbola().isSelected() ? "True" : "False"); properties.put("Logarithm", fdView.getLogarithm().isSelected() ? "True" : "False"); //RootLayout (Menu) elements states properties.put("LinearSmoothingFilter", rootLayoutView.getLinearInterpolationFlag() ? "True" : "False"); properties.put("ListwiseDeletion", rootLayoutView.getListwiseDeletionFlag() ? "True" : "False"); properties.put("SimpleRecovery", rootLayoutView.getSimpleRecoveryFlag() ? "True" : "False"); properties.put("CommaSeparator", rootLayoutView.getCommaFlag() ? "True" : "False"); properties.put("SemicolonSeparator", rootLayoutView.getSemicolonFlag() ? "True" : "False"); //saving to file try { File file = new File(PROPERTIES_STORE); if (!file.exists()) { file.createNewFile(); } file.setWritable(true); FileOutputStream out = new FileOutputStream(file); properties.storeToXML(out, "File contains properties of Gaze Reckon application. " + "Authors does not responsible for the correct operation of the program with changed configuration file." + "Make changes at your own risk."); out.close(); file.setReadOnly(); } catch (IOException e) { e.printStackTrace(); } } else { File file = new File(PROPERTIES_STORE); if (file.exists()) file.delete(); } } }
56.909091
130
0.608094
650cf68581df5948cef1897cbbf6194dd5dca051
683
package net.evendanan.testgrouping; import org.junit.runner.Description; /** * A simple implementation of {@link HashingStrategy} which allows you to just implement a * simple, normally-distributed, hashing function for the given {@link Description}. */ public abstract class SimpleHashingStrategyBase implements HashingStrategy { @Override public int calculateHashFromDescription(final Description description, final int groupsCount) { return Math.abs(calculateHashFromDescription(description)) % groupsCount; } /** * calculates a hashing value for the given description. */ protected abstract int calculateHashFromDescription(Description description); }
32.52381
97
0.787701
4ffa55e74b36c16439db76ebbe4536afd37d7e19
1,870
package cascade.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class MixingAlphabet extends Alphabet { public String [] reverseLookup; public int capacity; public MixingAlphabet(){ } public MixingAlphabet(int capacity) { this(capacity,true); } public MixingAlphabet(int capacity, boolean keepReverseMap) { this.capacity = capacity; if (keepReverseMap) reverseLookup = new String[capacity]; } /** No such thing as not being present. */ public int lookupIndex(String entry) { int res = entry.hashCode()%capacity; if (res < 0) res+=capacity; if (reverseLookup!=null) reverseLookup[res] = entry; return res; } public Object[] toArray() { return reverseLookup; } public boolean contains(String entry) { // FIXME: what is this used for? return true; } public int size() { return capacity; } public void stopGrowth() { } public void allowGrowth() { } public boolean growthStopped() { return true; } // Serialization private static final long serialVersionUID = 2L; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(CURRENT_SERIAL_VERSION); out.writeInt(capacity); out.writeObject(reverseLookup); } @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { @SuppressWarnings("unused") int version = in.readInt(); capacity = in.readInt(); reverseLookup = (String[]) in.readObject(); } @Override public String toString() { return "Mixing Alphabet [capacity = "+capacity+"]"; } public String [] getKeysInOrder() { return reverseLookup; } public String reverseLookup(int idx) { if(reverseLookup != null) return reverseLookup[idx]; return null; } }
20.107527
70
0.719251
b5ee9a67c07360f5899aabb9acdf2001d838851c
1,095
package hr.fer.zemris.dipl.lukasuman.fpga.gui.local; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * This class represents a {@linkplain LocalizationProvider} which is used to automatically * disconnect the specified frame from the specified {@linkplain LocalizationProvider} when the * window is closed. * @author Luka Suman * @version 1.0 */ public class FormLocalizationProvider extends LocalizationProviderBridge { /** * Creates a new {@link FormLocalizationProvider} with the specified parameters. The specified * provider and frame are "connected" when the frame is opened and automatically closed when * the frame is closed. * @param provider The localization provider. * @param frame The frame. */ public FormLocalizationProvider(LocalizationProvider provider, Frame frame) { super(provider); frame.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { connect(); } @Override public void windowClosed(WindowEvent e) { disconnect(); } }); } }
28.076923
95
0.746119
c929057a4cb3feba5cf729546ae79d7f6d119c9d
1,463
package com.leodsc.blog.security; import java.util.Collection; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.leodsc.blog.model.Usuario; public class UserDetailsImpl implements UserDetails { /** * */ private static final long serialVersionUID = 1L; private final String password; private final String username; private final List<GrantedAuthority> authorities = null; public UserDetailsImpl(Usuario usuario) { this.password = usuario.getPassword(); this.username = usuario.getUsername(); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { // TODO Auto-generated method stub return authorities; } @Override public String getPassword() { // TODO Auto-generated method stub return password; } @Override public String getUsername() { // TODO Auto-generated method stub return username; } @Override public boolean isAccountNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isAccountNonLocked() { // TODO Auto-generated method stub return true; } @Override public boolean isCredentialsNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isEnabled() { // TODO Auto-generated method stub return true; } }
21.202899
66
0.712235
744a3feea437e18beec0fcfbbe2ef35d7a254f66
8,315
package com.pi.pano.helper; import android.view.ViewGroup; import androidx.annotation.NonNull; import com.pi.pano.ChangeResolutionListener; import com.pi.pano.PanoSDKListener; import com.pi.pano.PilotSDK; import com.pi.pano.annotation.PiPhotoResolution; import com.pi.pano.annotation.PiPreviewMode; import com.pi.pano.annotation.PiProEv; import com.pi.pano.annotation.PiProIsoInAutoEx; import com.pi.pano.annotation.PiProWb; import com.pi.pano.annotation.PiPushResolution; import com.pi.pano.annotation.PiStitchingDistance; import com.pi.pano.annotation.PiVideoResolution; public class PreviewHelper { /** * initialization pano view. */ public static PilotSDK initPanoView(ViewGroup parent, PanoSDKListener listener) { return new PilotSDK(parent, listener); } /** * Set preview mode. * * @param mode preview mode. * @param playAnimation Whether to play animation when switching preview mode. */ public static void setPreviewMode(@PiPreviewMode int mode, boolean playAnimation) { PilotSDK.setPreviewMode(mode, 0, playAnimation); } /** * Whether to lock yaw when turning on the rotation lock. * * @param lock Whether to lock yaw. */ public static void lockYaw(boolean lock) { PilotSDK.lockYaw(lock); } /** * Whether to use a gyroscope, turn on the gyroscope during playback, you can refer to it and behold, * it can be used for PilotSteady when recording */ public static void useGyroscope(boolean able) { PilotSDK.useGyroscope(able); } /** * Set the inverted state, if the anti-shake is turned on, the inverted effect is invalid. * * @param able Is it inverted. */ public static void upsideDown(boolean able) { useGyroscope(false); // Turning off image stabilization. PilotSDK.setUpsideDown(able); } /** * Set the exposure compensation value. */ public static void setEV(@PiProEv int ev) { PilotSDK.setExposureCompensation(ev); } /** * ISO used when setting auto exposure time. */ public static void setISO(@PiProIsoInAutoEx int iso) { PilotSDK.setISO(iso); } /** * Set white balance. */ public static void setWB(@PiProWb String wb) { PilotSDK.setWhiteBalance(wb); } /** * Set stitching distance. * When taking photos and real-time video files, * calculating the stitching distance again has nothing to do with this setting. * * @param distance stitching distance. * @param max maximum stitching distance. */ public static void setStitchDistance(@PiStitchingDistance float distance, float max) { if (distance == PiStitchingDistance.auto) { onceParamReCali(); } else { PilotSDK.setStitchingDistance(distance, max); } } /** * Measure the stitching distance once, that is, automatically measure the splicing distance. */ public static void onceParamReCali() { PilotSDK.setParamReCaliEnable(new OnceParamReCaliListener()); } public static void changeCameraResolutionForVideo(String resolution, boolean retain) { changeCameraResolutionForVideo(resolution, retain, new ChangeResolutionListener() { @Override protected void onChangeResolution(int width, int height) { } }); } public static void changeCameraResolutionForVideo(@PiVideoResolution String resolution, boolean retain, ChangeResolutionListener listener) { int[] params = obtainCameraParamsForVideo(resolution, retain); PilotSDK.changeCameraResolution(params, listener); } /** * @param resolution resolution * @param nrt not real time video(postpone stitching) */ @NonNull private static int[] obtainCameraParamsForVideo(@PiVideoResolution String resolution, boolean nrt) { switch (resolution) { case PiVideoResolution._8K: if (nrt) { return PilotSDK.CAMERA_PREVIEW_400_250_24; } else { return PilotSDK.CAMERA_PREVIEW_4048_2530_7; } case PiVideoResolution._7K: if (nrt) { return PilotSDK.CAMERA_PREVIEW_288_180_24; } else { throw new RuntimeException("VideoResolution don't support:" + resolution + ",nrt:" + nrt); } case PiVideoResolution._6K: if (nrt) { return PilotSDK.CAMERA_PREVIEW_512_320_30; } else { return PilotSDK.CAMERA_PREVIEW_2880_1800_15; } case PiVideoResolution._4K_FPS: if (nrt) { return PilotSDK.CAMERA_PREVIEW_480_300_30; } else { return PilotSDK.CAMERA_PREVIEW_2192_1370_30; } case PiVideoResolution._4K_QUALITY: if (nrt) { throw new RuntimeException("VideoResolution don't support:" + resolution + ",nrt:" + nrt); } else { //return PilotSDK.CAMERA_PREVIEW_3520_2200_24; return PilotSDK.CAMERA_PREVIEW_2880_1800_24; } case PiVideoResolution._2K: if (nrt) { throw new RuntimeException("VideoResolution don't support:" + resolution + ",nrt:" + nrt); } else { return PilotSDK.CAMERA_PREVIEW_1920_1200_30; } default: throw new RuntimeException("VideoResolution don't support:" + resolution); } } public static void changeCameraResolutionForPhoto() { changeCameraResolutionForPhoto(new ChangeResolutionListener() { @Override protected void onChangeResolution(int width, int height) { } }); } public static void changeCameraResolutionForPhoto(ChangeResolutionListener listener) { changeCameraResolutionForPhoto(PiPhotoResolution._8K, listener); } public static void changeCameraResolutionForPhoto(@PiPhotoResolution String resolution, ChangeResolutionListener listener) { int[] params = obtainCameraParamsForPhoto(resolution); PilotSDK.changeCameraResolution(params, listener); } @NonNull private static int[] obtainCameraParamsForPhoto(@PiPhotoResolution String resolution) { switch (resolution) { case PiPhotoResolution._8K: case PiPhotoResolution._3K: case PiPhotoResolution._6K: case PiPhotoResolution._4K: case PiPhotoResolution._2K: break; default: throw new RuntimeException("VideoResolution don't support:" + resolution); } return PilotSDK.CAMERA_PREVIEW_4048_2530_15; } public static void changeCameraResolutionForLive(@PiPushResolution String resolution) { changeCameraResolutionForLive(resolution, new ChangeResolutionListener() { @Override protected void onChangeResolution(int width, int height) { } }); } public static void changeCameraResolutionForLive(@PiPushResolution String resolution, ChangeResolutionListener listener) { int[] params = obtainCameraParamsForLive(resolution); PilotSDK.changeCameraResolution(params, listener); } @NonNull private static int[] obtainCameraParamsForLive(@PiPushResolution String resolution) { switch (resolution) { case PiPushResolution._8K: return PilotSDK.CAMERA_PREVIEW_400_250_24; case PiPushResolution._8K_7FPS: return PilotSDK.CAMERA_PREVIEW_4048_2530_7; case PiPushResolution._4K_FPS: return PilotSDK.CAMERA_PREVIEW_2192_1370_30; case PiPushResolution._4K_QUALITY: //return PilotSDK.CAMERA_PREVIEW_3520_2200_24; return PilotSDK.CAMERA_PREVIEW_2880_1800_24; default: throw new RuntimeException("PushResolution don't support:" + resolution); } } }
35.686695
144
0.635117
3529688d5794f16e7a1b94e74c2f0ae3565cdaf5
694
package org.weirdloop.exp4j.ext; import net.objecthunter.exp4j.Expression; import net.objecthunter.exp4j.ExpressionBuilder; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; public class ByteShiftMaskTest { private ByteShiftMask bsm; @Before public void setup() { bsm = ByteShiftMask.create("bsm"); } @Test public void high_byte_shift() { double result = expr() .setVariable("x100680_0_2", 5670) .evaluate(); assertThat(result, is(38.0)); } private Expression expr() { return new ExpressionBuilder("bsm(x100680_0_2, 0)") .variable("x100680_0_2") .function(bsm) .build(); } }
20.411765
53
0.721902
2e7ef7f0fad5d72607b027e8f3ac137ccae0e1c2
386
package peacefulotter.engine.rendering.resourceManagement; import static org.lwjgl.opengl.GL11.glGenTextures; public class TextureResource { private final int id; public TextureResource() { this.id = glGenTextures(); // Used to free memory and thus avoid memory leak Resources.addBuffer( this.id ); } public int getId() { return id; } }
21.444444
58
0.681347
4f66b8194dfebc51f6941ab4732468fc537d2744
19,114
package com.eightsines.espromo; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.webkit.HttpAuthHandler; import android.webkit.JavascriptInterface; import android.webkit.WebChromeClient; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.InputStream; import java.util.Locale; import zame.game.BuildConfig; public class PromoView extends FrameLayout { interface Listener { void onActivePromoLoaded(); void onActivePromoDismissed(); } private static final String PROMO_URL = "https://eightsines.com/promo/?package="; private static final long RELOAD_INTERVAL = 10L * 1000L; private static final long ROTATE_INTERVAL = 15L * 1000L; private static final int STATE_INITIALIZED = 0; private static final int STATE_LOADING = 1; private static final int STATE_LOADED = 2; private static final int STATE_DISMISSED = 3; private final Handler handler = new Handler(); private Context context; private WebView prevWebView; private WebView currentWebView; private int state; private boolean activePromoLoaded; private Listener listener; private String debugLogTag; private final Runnable loadPromoRunnable = new Runnable() { @Override public void run() { debugLog("loadPromoRunnable.run"); loadPromo(); } }; private final Runnable reloadPromoRunnable = new Runnable() { @Override public void run() { debugLog("reloadPromoRunnable.run"); reloadPromo(); } }; private final Runnable rotatePromoRunnable = new Runnable() { @Override public void run() { debugLog("rotatePromoRunnable.run"); rotatePromo(); } }; private final Runnable promoLoadedRunnable = new Runnable() { @Override public void run() { debugLog("promoLoadedRunnable.run"); promoLoaded(); } }; private final Runnable promoDismissedRunnable = new Runnable() { @Override public void run() { promoDismissed(); } }; public PromoView(@NonNull Context context) { super(context); initialize(context); } public PromoView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); initialize(context); } public PromoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initialize(context); } public PromoView(@NonNull Context context, @Nullable Listener listener, @Nullable String debugLogTag) { super(context); this.listener = listener; synchronized (this) { this.debugLogTag = debugLogTag; } initialize(context); } @SuppressWarnings({ "unused", "RedundantSuppression" }) public boolean isActivePromoLoaded() { return activePromoLoaded; } @SuppressWarnings({ "unused", "RedundantSuppression" }) @Nullable public Listener getListener() { return listener; } @SuppressWarnings({ "unused", "RedundantSuppression" }) public void setListener(@Nullable Listener listener) { this.listener = listener; } @SuppressWarnings({ "unused", "RedundantSuppression" }) @Nullable public String getDebugLogTag() { synchronized (this) { return debugLogTag; } } @SuppressWarnings({ "unused", "RedundantSuppression" }) public void setDebugLogTag(@Nullable String debugLogTag) { synchronized (this) { this.debugLogTag = debugLogTag; } } private void debugLog(String message) { String debugLogTagLocal; synchronized (this) { debugLogTagLocal = debugLogTag; } if (debugLogTagLocal != null) { Log.w(debugLogTagLocal, "[PromoView] " + message); } } private void initialize(@NonNull Context context) { this.context = context; prevWebView = createWebView(); currentWebView = createWebView(); loadPromo(); } @SuppressLint({ "AddJavascriptInterface", "ObsoleteSdkInt", "SetJavaScriptEnabled" }) @NonNull private WebView createWebView() { WebView webView = new WebView(context); webView.addJavascriptInterface(new JsApi(), "promoApi"); webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); webView.setScrollbarFadingEnabled(true); webView.setWebViewClient(new PromoWebViewClient()); webView.setWebChromeClient(new PromoWebChromeClient()); webView.setVisibility(View.INVISIBLE); webView.setBackgroundColor(0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); } webView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { return true; } }); WebSettings webSettings = webView.getSettings(); webSettings.setBuiltInZoomControls(false); webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); webSettings.setJavaScriptEnabled(true); webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); webSettings.setSupportZoom(false); webSettings.setUseWideViewPort(true); webSettings.setSupportMultipleWindows(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { webSettings.setDisplayZoomControls(false); } webView.setLayoutParams(new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); addView(webView); return webView; } private void loadPromo() { debugLog("loadPromo: state = " + state); handler.removeCallbacks(loadPromoRunnable); handler.removeCallbacks(reloadPromoRunnable); handler.removeCallbacks(rotatePromoRunnable); if (state != STATE_INITIALIZED) { return; } if (isNetworkConnected()) { state = STATE_LOADING; String url = PROMO_URL + context.getPackageName() + "&lang=" + Locale.getDefault() .getLanguage() .toLowerCase(Locale.US); if (BuildConfig.DEBUG) { url += "&mode=debug"; } debugLog("loadPromo: isNetworkConnected() = true, state = " + state + ", url = \"" + url + "\""); currentWebView.loadUrl(url); } else { debugLog("loadPromo: isNetworkConnected() = false"); handler.postDelayed(loadPromoRunnable, RELOAD_INTERVAL); } } private void reloadPromo() { debugLog("reloadPromo"); currentWebView.setVisibility(View.INVISIBLE); currentWebView.stopLoading(); currentWebView.loadData("", "text/html", null); state = STATE_INITIALIZED; loadPromo(); } private void rotatePromo() { debugLog("rotatePromo"); WebView tmpWebView = prevWebView; prevWebView = currentWebView; currentWebView = tmpWebView; reloadPromo(); } private void promoLoaded() { debugLog("promoLoaded: state = " + state); if (state != STATE_LOADING) { return; } currentWebView.setVisibility(View.VISIBLE); prevWebView.setVisibility(View.INVISIBLE); try { prevWebView.stopLoading(); prevWebView.loadData("", "text/html", null); } catch (Throwable e) { debugLog("promoLoaded: exception in prevWebView, e = " + e); // Something bad happened inside WebView. Just re-create it. prevWebView = createWebView(); prevWebView.loadData("", "text/html", null); } state = STATE_LOADED; handler.postDelayed(rotatePromoRunnable, ROTATE_INTERVAL); activePromoLoaded = true; debugLog("promoLoaded: activePromoLoaded = true"); if (listener != null) { debugLog("promoLoaded: calling listener.onActivePromoLoaded()"); listener.onActivePromoLoaded(); } } private void promoDismissed() { debugLog("promoDismissed: state = " + state); if (state != STATE_LOADING && state != STATE_LOADED) { return; } prevWebView.setVisibility(View.INVISIBLE); currentWebView.setVisibility(View.INVISIBLE); try { prevWebView.stopLoading(); prevWebView.loadData("", "text/html", null); } catch (Throwable e) { debugLog("promoDismissed: exception in prevWebView, e = " + e); // Something bad happened inside WebView. Just re-create it. prevWebView = createWebView(); prevWebView.loadData("", "text/html", null); } try { currentWebView.stopLoading(); currentWebView.loadData("", "text/html", null); } catch (Throwable e) { debugLog("promoDismissed: exception in currentWebView, e = " + e); // Something bad happened inside WebView. Just re-create it. currentWebView = createWebView(); currentWebView.loadData("", "text/html", null); } state = STATE_DISMISSED; handler.post(rotatePromoRunnable); // rotate immediately activePromoLoaded = false; debugLog("promoDismissed: activePromoLoaded = false"); if (listener != null) { debugLog("promoDismissed: calling listener.onActivePromoDismissed()"); listener.onActivePromoDismissed(); } } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); debugLog("onWindowFocusChanged: state = " + state + ", hasWindowFocus = " + hasWindowFocus); if (state != STATE_INITIALIZED) { return; } if (hasWindowFocus) { loadPromo(); } else { handler.removeCallbacks(loadPromoRunnable); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); debugLog("onAttachedToWindow: state = " + state); if (state == STATE_INITIALIZED) { loadPromo(); } } @Override protected void onDetachedFromWindow() { debugLog("onDetachedFromWindow"); handler.removeCallbacks(loadPromoRunnable); handler.removeCallbacks(reloadPromoRunnable); handler.removeCallbacks(rotatePromoRunnable); state = STATE_INITIALIZED; super.onDetachedFromWindow(); } private boolean isNetworkConnected() { ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager == null) { return false; } NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected()); } private void openExternalBrowser(@NonNull final String uri) { handler.post(new Runnable() { @Override public void run() { try { context.startActivity((new Intent( Intent.ACTION_VIEW, Uri.parse(uri))).addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)); } catch (Exception ex) { try { Toast.makeText(context, "Could not launch the browser application.", Toast.LENGTH_LONG).show(); } catch (Exception inner) { // ignored } } } }); } private void openExternalIntent(@NonNull final Intent intent) { handler.post(new Runnable() { @Override public void run() { try { context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)); } catch (Exception ex) { try { Toast.makeText(context, "Could not startBatch external intent.", Toast.LENGTH_LONG).show(); } catch (Exception inner) { // ignored } } } }); } @SuppressWarnings({ "unused", "RedundantSuppression" }) private class JsApi { @JavascriptInterface public void loaded() { //noinspection MagicNumber handler.postDelayed(promoLoadedRunnable, 100L); } @JavascriptInterface public void dismiss() { handler.post(promoDismissedRunnable); } } private class PromoWebViewClient extends WebViewClient { @SuppressLint("ObsoleteSdkInt") @Override public void onPageFinished(@NonNull WebView view, @NonNull String url) { try { view.setBackgroundColor(0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); } } catch (Throwable e) { debugLog("PromoWebViewClient.onPageFinished failed: " + e); } } @Override public boolean shouldOverrideUrlLoading(@NonNull WebView view, String url) { final String MAILTO_PREFIX = "mailto:"; try { if (url == null || !url.startsWith(MAILTO_PREFIX)) { return false; } Intent intent = new Intent( Intent.ACTION_SENDTO, Uri.fromParts("mailto", url.replaceFirst(MAILTO_PREFIX, ""), null)); openExternalIntent(intent); return true; } catch (Throwable e) { debugLog("PromoWebViewClient.shouldOverrideUrlLoading failed: " + e); } return false; } @SuppressLint("NewApi") @Nullable @Override public WebResourceResponse shouldInterceptRequest(@NonNull WebView view, @NonNull String url) { final String ANDROID_ASSET = "file:///android_asset/"; try { if (!url.startsWith(ANDROID_ASSET)) { return null; } Uri uri = Uri.parse(url.replaceFirst(ANDROID_ASSET, "")); String path = uri.getPath(); if (path != null) { InputStream stream = view.getContext().getAssets().open(path); return new WebResourceResponse("text/html", "UTF-8", stream); } } catch (Throwable e) { debugLog("PromoWebViewClient.shouldInterceptRequest failed: " + e); } return null; } @Override public void onReceivedError( @NonNull WebView view, int errorCode, String description, String failingUrl) { //noinspection UnnecessaryCallToStringValueOf debugLog("PromoWebViewClient.onReceivedError: errorCode = " + errorCode + ", description = \"" + String.valueOf(description) + "\", failingUrl = \"" + String.valueOf(failingUrl) + "\""); try { view.stopLoading(); view.loadData("", "text/html", null); } catch (Throwable e) { debugLog("PromoWebViewClient.onReceivedError failed: " + e); } handler.post(reloadPromoRunnable); } @Override public void onReceivedHttpAuthRequest( @NonNull WebView view, @NonNull HttpAuthHandler httpAuthHandler, @NonNull String host, @NonNull String realm) { try { view.stopLoading(); view.loadData("", "text/html", null); } catch (Throwable e) { debugLog("PromoWebViewClient.onReceivedHttpAuthRequest failed: " + e); } handler.post(reloadPromoRunnable); } } private class PromoWebChromeClient extends WebChromeClient { private WebView childWebView; @Override public boolean onCreateWindow( @NonNull WebView view, boolean dialog, boolean userGesture, @NonNull Message resultMsg) { try { if (childWebView != null) { childWebView.stopLoading(); childWebView.destroy(); } createChildWebView(view.getContext()); ((WebView.WebViewTransport)resultMsg.obj).setWebView(childWebView); resultMsg.sendToTarget(); return true; } catch (Throwable e) { debugLog("PromoWebChromeClient.onCreateWindow failed: " + e); return false; } } private void createChildWebView(Context context) { childWebView = new WebView(context); childWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(@NonNull WebView view, String url) { try { if (url != null) { url = url.trim(); if (!TextUtils.isEmpty(url)) { openExternalBrowser(url); } } childWebView.stopLoading(); childWebView.destroy(); childWebView = null; } catch (Throwable e) { debugLog("Child WebViewClient.shouldOverrideUrlLoading failed: " + e); } return true; } }); } } }
31.334426
119
0.577587
b89a3d26f1cfacdb68c23bdfd7c2c22bf7543c21
143
package com.thegongoliers.output.interfaces; public interface Displayable { /** * Display onto the SmartDashboard. */ void display(); }
15.888889
44
0.727273
9e0f2100bce82156e863a306819092d24fd1e7ae
5,618
package com.sech.framework.business.admin.aop; import com.fasterxml.jackson.databind.ObjectMapper; import com.sech.framework.business.admin.service.PermissionService; import com.sech.framework.business.commons.utils.WebUtils; import com.sech.framework.business.commons.web.aop.PrePermissions; import com.sech.framework.business.commons.web.config.PermissionConfiguration; import com.sech.framework.core.commons.jwt.JwtUtil; import com.sech.framework.core.configuration.JwtConfiguration; import com.sech.framework.core.utils.R; import com.sech.framework.exception.CheckedException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.List; import java.util.Set; /** * 功能权限切面验证 * * @author sech.io */ @Slf4j @Component public class AuthorizationInterceptor extends HandlerInterceptorAdapter { @Autowired private PermissionService permissionService; @Autowired private PermissionConfiguration permissionConfiguration; @Autowired private ObjectMapper objectMapper; @Autowired private JwtConfiguration jwtConfiguration; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { if (!permissionConfiguration.isEnabled()) return true; if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) return true; final HandlerMethod handlerMethod = (HandlerMethod) handler; final Method method = handlerMethod.getMethod(); final Class<?> clazz = method.getDeclaringClass(); String requestURI = request.getRequestURI(); String modulePermission; // 为了规范,如果class上面没有设置@PrePermissions则不通过 if (!clazz.isAnnotationPresent(PrePermissions.class)) { log.error("请求[" + requestURI + "]模块上未设置权限,请设置注解@PrePermissions权限!"); R<Boolean> responseWithR = new R<Boolean>().failure( "请求[" + requestURI + "]模块上未设置权限,请设置注解@PrePermissions权限!").data(false); this.handleWithResponse(response, responseWithR); return false; } PrePermissions clazzPermissions = clazz.getAnnotation(PrePermissions.class); if (!clazzPermissions.required()) return true; modulePermission = clazzPermissions.value()[0]; // 为了规范:方法上没设置权限的请求则不通过 if (!method.isAnnotationPresent(PrePermissions.class)) { log.error("请求[" + requestURI + "]方法上未设置权限,请设置注解@PrePermissions权限!"); R<Boolean> responseWithR = new R<Boolean>().failure( "请求[" + requestURI + "]方法上未设置权限,请设置注解@PrePermissions权限!").data(false); this.handleWithResponse(response, responseWithR); return false; } PrePermissions prePermissions = method.getAnnotation(PrePermissions.class); String[] permissions = prePermissions.value(); if (permissions.length == 0) { log.error("请求[" + requestURI + "]方法上未正确设置权限,请设置注解@PrePermissions权限!"); R<Boolean> responseWithR = new R<Boolean>().failure( "请求[" + requestURI + "]方法上未正确设置权限,请设置注解@PrePermissions权限!").data(false); this.handleWithResponse(response, responseWithR); return false; } // 验证是否有功能权限 List<String> roleList = JwtUtil.getRole(request, jwtConfiguration.getJwtkey()); if (null == roleList || roleList.size() == 0) { R<Boolean> responseWithR = new R<Boolean>().failure("请求[" + requestURI + "]权限验证失败!") .data(false); this.handleWithResponse(response, responseWithR); return false; } // 所以角色权限集合 Set<String> menuPermissions = new HashSet<String>(); for (String roleCode : roleList) { menuPermissions.addAll(this.permissionService.findMenuPermissions(roleCode)); } if (menuPermissions.size() == 0) { R<Boolean> responseWithR = new R<Boolean>().failure("请求[" + requestURI + "]权限未配置!") .data(false); this.handleWithResponse(response, responseWithR); return false; } for (String permission : permissions) { String valiatePermission = modulePermission + permission; log.info("请求[" + requestURI + "],permission:[" + valiatePermission + "]"); // 验证permission是否有功能权限 if (!menuPermissions.contains(valiatePermission)) { log.info("请求[" + requestURI + "]权限[" + valiatePermission + "]未配置!"); R<Boolean> responseWithR = new R<Boolean>().failure( "请求[" + requestURI + "]权限[" + valiatePermission + "]未配置!").data(false); this.handleWithResponse(response, responseWithR); return false; } } return true; } public void handleWithResponse(HttpServletResponse response, R<Boolean> responseWithR) { try { WebUtils.handleWithResponse(response, this.objectMapper .writeValueAsString(responseWithR)); } catch (IOException e) { e.printStackTrace(); throw new CheckedException("Failed to response"); } } }
39.843972
96
0.659487
719d50a17bab826e6813e7951acb9d9717b1c7df
3,277
package game; import game.input.TargetInputEvent; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.input.KeyEvent; import javafx.stage.Stage; import javafx.util.Duration; public class Main extends Application { private static final double TARGET_FPS = 60; private static final double TARGET_UPDATE_RATE = 30; private Timeline renderLoop, updateLoop; private long frameTime; private long updateTime; private GraphicsContext gc; private GameCore game; private float fps, ups; private Stage primaryStage; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { this.primaryStage = primaryStage; primaryStage.setTitle("Avoid the Purple 4"); primaryStage.setResizable(false); Group root = new Group(); Scene scene = new Scene(root); primaryStage.setScene(scene); Canvas canvas = new Canvas(1280, 720); assert canvas.getWidth() > 0 : "Actual: " + canvas.getWidth(); assert canvas.getHeight() > 0 : "Actual: " + canvas.getHeight(); root.getChildren().add(canvas); game = new GameCore(); gc = canvas.getGraphicsContext2D(); initializeLoop(); frameTime = System.currentTimeMillis(); updateTime = frameTime; renderLoop.play(); updateLoop.play(); // key listener scene.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent ke) { game.inMgner.inputs.add(new TargetInputEvent(0, ke.getCode())); } }); scene.setOnKeyReleased(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent ke) { game.inMgner.releases.add(new TargetInputEvent(0, ke.getCode())); } }); primaryStage.show(); } /** * Setup the render and update loops */ private void initializeLoop() { renderLoop = new Timeline(); renderLoop.setCycleCount(Timeline.INDEFINITE); // keyframe render loop KeyFrame kfRender = new KeyFrame(Duration.seconds(1.0 / TARGET_FPS), new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { float delta = (System.currentTimeMillis() - frameTime) / 1000.0f; fps = 1f / delta; gc.clearRect(0, 0, primaryStage.getWidth(), primaryStage.getHeight()); game.render(gc, delta); frameTime = System.currentTimeMillis(); } }); renderLoop.getKeyFrames().add(kfRender); updateLoop = new Timeline(); updateLoop.setCycleCount(Timeline.INDEFINITE); // keyframe render loop KeyFrame kfUpdate = new KeyFrame(Duration.seconds(1.0 / TARGET_UPDATE_RATE), new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { float delta = (System.currentTimeMillis() - updateTime) / 1000.0f; ups = 1f / delta; game.update(delta); updateTime = System.currentTimeMillis(); primaryStage.setTitle(String.format("Avoid the Purple 4 (fps: %.0f ups: %.0f)", fps, ups)); } }); updateLoop.getKeyFrames().add(kfUpdate); } }
25.207692
97
0.701251
ac78ecdc01e6030d1d96e861624e67298bd0d330
5,807
package com.web2design.souqclone.app.controller; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import com.web2design.souqclone.app.R; import com.web2design.souqclone.app.utils.Utils; import com.web2design.souqclone.app.model.MenuCategory; import com.web2design.souqclone.app.model.MenuSubCategory; import java.util.HashMap; import java.util.List; /** * Created by Inzimam on 29-Oct-17. */ public class ExpandableListAdapterCategory extends BaseExpandableListAdapter { private List<MenuCategory> dataListHeader; private HashMap<MenuCategory, List<MenuSubCategory>> listHashMap; private boolean isFilter; private Utils utils; private Context mContext; public ExpandableListAdapterCategory(List<MenuCategory> dataListHeader, HashMap<MenuCategory, List<MenuSubCategory>> listHashMap, boolean isFilter) { this.dataListHeader = dataListHeader; this.listHashMap = listHashMap; this.isFilter = isFilter; } @Override public int getGroupCount() { return dataListHeader.size(); } @Override public int getChildrenCount(int groupPosition) { return listHashMap.get(dataListHeader.get(groupPosition)).size(); } @Override public Object getGroup(int groupPosition) { return dataListHeader.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return listHashMap.get(dataListHeader.get(groupPosition)).get(childPosition); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return false; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { mContext = parent.getContext(); utils = new Utils(mContext); MenuCategory menuCategory = (MenuCategory) getGroup(groupPosition); View groupView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_group, parent, false); TextView lblListHeader = groupView.findViewById(R.id.lblListHeader); lblListHeader.setText(menuCategory.getMenuCategoryName()); // lblListHeader.setTypeface(null, Typeface.BOLD); ImageView imageView = groupView.findViewById(R.id.imageView); ImageView expandCollapseIV = groupView.findViewById(R.id.expand_collapse_image); String imgPath = menuCategory.getMenuCategoryImage(); utils.printLog("Product Image = " + imgPath); if (imgPath != null && !imgPath.isEmpty()) { int width = (int) mContext.getResources().getDimension(R.dimen.image_width); imageView.getLayoutParams().height = width; imageView.getLayoutParams().width = width; Picasso.with(parent.getContext()).load(menuCategory.getMenuCategoryImage()) .into(imageView); } else imageView.setVisibility(View.GONE); if (getChildrenCount(groupPosition) > 0) { expandCollapseIV.setImageResource(isExpanded ? R.drawable.ic_expand_less_black : R.drawable.ic_expand_more_black); } if (isFilter) { groupView.setClickable(false); } return groupView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) { final MenuSubCategory child = (MenuSubCategory) getChild(groupPosition, childPosition); View itemView; if (!isFilter) { itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item, parent, false); TextView lblListChild = itemView.findViewById(R.id.lblListItem); lblListChild.setText(child.getMenuSubCategoryName()); Log.e("ChildText", child.getMenuSubCategoryName()); } else { itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_chechbox, parent, false); itemView.setClickable(false); CheckBox checkBox = itemView.findViewById(R.id.item_option); checkBox.setText(child.getMenuSubCategoryName()); // checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // @Override // public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // utils.printLog("IsChecked=" + isChecked); // if (isChecked) { // utils.printLog("CheckedId=" + child.getMenuSubCategoryId()); // selectedFilters.add(child.getMenuSubCategoryId()); // } else { // utils.printLog("Un-CheckedId=" + child.getMenuSubCategoryId()); // } // } // }); } return itemView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }
35.845679
126
0.631996
27f4c333e9fc2771f04cf8d497e82021366f6b73
509
package net.kikkirej.pdfview.rcp; interface PDFScrollable { /** * This method is used to scroll the currently opened PDF to a specified * page * * @param page * - the page# to scroll to */ public void scrollToPage(int page); /** * This method is used to scroll the currently opened PDF to a specified * named destination * * @param destination * - a string representing the name of the destination */ public void scrollToDestination(String destination); }
24.238095
73
0.67387
11f1043292b91bd0a793b654d2990ba964a9ba25
1,224
package mekanism.api.inventory; import javax.annotation.Nonnull; import mcp.MethodsReturnNonnullByDefault; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @MethodsReturnNonnullByDefault public final class IgnoredIInventory implements IInventory { public static IgnoredIInventory INSTANCE = new IgnoredIInventory(); private IgnoredIInventory() { } @Override public int getSizeInventory() { return 0; } @Override public boolean isEmpty() { return true; } @Override public ItemStack getStackInSlot(int index) { return ItemStack.EMPTY; } @Override public ItemStack decrStackSize(int index, int count) { return ItemStack.EMPTY; } @Override public ItemStack removeStackFromSlot(int index) { return ItemStack.EMPTY; } @Override public void setInventorySlotContents(int index, @Nonnull ItemStack stack) { } @Override public void markDirty() { } @Override public boolean isUsableByPlayer(@Nonnull PlayerEntity player) { return false; } @Override public void clear() { } }
21.103448
79
0.690359
807c5863309f8e3d7f52310662132255e5f25162
685
package com.bugjc.ea.opensdk.mock.data.parser.converter.impl; import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.StrUtil; import com.bugjc.ea.opensdk.mock.data.parser.converter.NewFieldValueConverter; /** * 字符 类型 * * @author aoki * @date 2020/9/1 **/ public class CharacterNewFieldValueConverter implements NewFieldValueConverter<Character> { public final static CharacterNewFieldValueConverter INSTANCE = new CharacterNewFieldValueConverter(); @Override public Character transform(String value) { if (StrUtil.isNotBlank(value)) { //TODO 自定义生成策略 return null; } return RandomUtil.randomChar(); } }
26.346154
105
0.716788
881dc23623b2c4340be2a3d8498bdcda29d91ac3
9,691
package org.coreasm.eclipse.editors.errors; import java.util.LinkedList; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.SortedSet; import java.util.TreeSet; import org.codehaus.jparsec.error.ParseErrorDetails; import org.codehaus.jparsec.error.ParserException; import org.coreasm.eclipse.editors.ASMDocument; import org.coreasm.eclipse.editors.ASMEditor; import org.coreasm.eclipse.editors.ASMParser.ParsingResult; import org.coreasm.eclipse.editors.warnings.AbstractWarning; import org.coreasm.eclipse.editors.warnings.CoreASMWarningRecognizer; import org.coreasm.eclipse.editors.warnings.DanglingElseWarningRecognizer; import org.coreasm.eclipse.editors.warnings.IWarningRecognizer; import org.coreasm.eclipse.editors.warnings.NumberOfArgumentsWarningRecognizer; import org.coreasm.eclipse.editors.warnings.UndefinedIdentifierWarningRecognizer; import org.eclipse.core.resources.IMarker; import org.eclipse.jface.text.BadLocationException; /** * An ErrorManager checks a CoreASM specification for errors beyond * syntax errors. Each instance of ASMEditor creates an ErrorManager * and binds it to its ASMParser as an Observer. So the ErrorManager * gets notified each time the parser was run. * * An ErrorManager manages a list of objects implementing the IErrorRecognizer * interface. These objects are doing the actual error checking, each error * recognizer searches for a certain kind of errors. The ErrorManager executes * these ErrorRegognizers after each run of the parser. * * @author Markus Müller */ public class ErrorManager implements Observer { private ASMEditor asmEditor; // the editor this instance belongs to private List<ITextErrorRecognizer> listTextParsers; private List<ITreeErrorRecognizer> listTreeParsers; private List<IWarningRecognizer> warningRecognizers; /** * Generates a new ErrorManager and adds all available ErrorRecognizers to itself. * @param asmEditor The ASMEditor instance the generated ErrorManager belongs to. */ public ErrorManager(ASMEditor asmEditor) { this.asmEditor = asmEditor; this.listTextParsers = new LinkedList<ITextErrorRecognizer>(); this.listTreeParsers = new LinkedList<ITreeErrorRecognizer>(); this.warningRecognizers = new LinkedList<IWarningRecognizer>(); // Creating and adding all available ErrorRecognizers. addErrorRecognizer(new InitErrorRecognizer()); addErrorRecognizer(new RuleErrorRecognizer(asmEditor)); addErrorRecognizer(new PluginErrorRecognizer(asmEditor.getParser())); addErrorRecognizer(new ModularityErrorRecognizer(asmEditor)); addErrorRecognizer(new CoreASMErrorRecognizer(asmEditor)); addWarningRecognizer(new UndefinedIdentifierWarningRecognizer(asmEditor)); addWarningRecognizer(new NumberOfArgumentsWarningRecognizer(asmEditor)); addWarningRecognizer(new CoreASMWarningRecognizer(asmEditor)); addWarningRecognizer(new DanglingElseWarningRecognizer()); } /** * Adds an ErrorRegognizer to this ErrorManager, so the ErrorRecognizer will * be run after each run of the parser. */ public void addErrorRecognizer(IErrorRecognizer errorRecognizer) { if (errorRecognizer instanceof ITextErrorRecognizer) listTextParsers.add((ITextErrorRecognizer) errorRecognizer); if (errorRecognizer instanceof ITreeErrorRecognizer) listTreeParsers.add((ITreeErrorRecognizer) errorRecognizer); } /** * Adds a WarningRecognizer to this ErrorManager. * @param warningRecognizer */ public void addWarningRecognizer(IWarningRecognizer warningRecognizer) { warningRecognizers.add(warningRecognizer); } /** * Executes all ErrorRecognizers implementing the ITextErrorRecognizer interface and * collects the errors which were found in a list. * @param document The document which is to be checked. * @return A list with all errors which have been found. * @see org.coreasm.eclipse.editors.errors.ITextErrorRecognizer */ public List<AbstractError> checkAllTextErrorRecognizers(ASMDocument document) { List<AbstractError> errors = new LinkedList<AbstractError>(); for (ITextErrorRecognizer errorParser: listTextParsers) errorParser.checkForErrors(document, errors); return errors; } /** * Executes all ErrorRecognizers implementing the ITreeErrorRecognizer interface and * collects the errors which were found in a list. * @param document The document which is to be checked. * @return A list with all errors which have been found. * @see org.coreasm.eclipse.editors.errors.ITreeErrorRecognizer */ public List<AbstractError> checkAllTreeErrorRecognizers(ASMDocument document) { List<AbstractError> errors = new LinkedList<AbstractError>(); for (ITreeErrorRecognizer errorParser: listTreeParsers) errorParser.checkForErrors(document, errors); return errors; } /** * Executes all ErrorRecognizers (both TextErrorRecognizers and TreeErrorRecognizers) * interface and collects the errors which were found in a list. * @param document The document which is to be checked. * @return A list with all errors which have been found. * @see org.coreasm.eclipse.editors.errors.ITextErrorRecognizer * @see org.coreasm.eclipse.editors.errors.ITreeErrorRecognizer */ public List<AbstractError> checkAllErrorRecognizer(ASMDocument document) { List<AbstractError> errors = new LinkedList<AbstractError>(); errors.addAll(checkAllTextErrorRecognizers(document)); errors.addAll(checkAllTreeErrorRecognizers(document)); return errors; } /** * Execute all WarningRecognizers. * @param document document to be checked * @return list of warnings that have been found */ public List<AbstractWarning> checkAllWarnings(ASMDocument document) { List<AbstractWarning> warnings = new LinkedList<AbstractWarning>(); for (IWarningRecognizer warningRecognizer : warningRecognizers) warnings.addAll(warningRecognizer.checkForWarnings(document)); return warnings; } /** * This is the method of the Observer interface which is called after each * run of the parser. It executes the ErrorRecognizers depending if the parsing * was successful and creates an error marker for each error. It also creates * a marker if the parser delivered a syntax error or an unknown error. * @param o The observable which has called this method. This must be * the parser instance which is bound to the same instance of * ASMEditor than this ErrorManager. * @param arg The data the Observable delivered. This must be an instance * of ParsingResult. */ @Override public void update(Observable o, Object arg) { // check if correctly called by the right parser if (o != asmEditor.getParser() || ! (arg instanceof ParsingResult)) return; ParsingResult result = (ParsingResult) arg; List<AbstractError> errors = new LinkedList<AbstractError>(); // clear old markers asmEditor.removeMarkers(IMarker.PROBLEM); // always run TextErrorRecognizers errors.addAll(checkAllTextErrorRecognizers(result.document)); // run TreeErrorRecognizers only if there was no syntax error if (result.wasSuccessful == true) errors.addAll(checkAllTreeErrorRecognizers(result.document)); // create markers for all errors for (AbstractError error: errors) { if (error instanceof SimpleError) asmEditor.createSimpleMark((SimpleError) error, IMarker.SEVERITY_ERROR); else asmEditor.createErrorMark(error); } if (result.wasSuccessful) { for (AbstractWarning warning : checkAllWarnings(result.document)) asmEditor.createWarningMark(warning); } // if there was a syntax error: create error object if (result.exception != null) { ParserException pe = result.exception; ParseErrorDetails perr = pe.getErrorDetails(); if (perr != null) { // SYNTAX ERROR int line = asmEditor.getSpec().getLine(pe.getLocation().line).line; int col = pe.getLocation().column; int index = 0; try { if (line > 0) index = result.document.getLineOffset(line-1) + col-1; } catch (BadLocationException e1) { e1.printStackTrace(); } String message = pe.getMessage(); int beginIndex = message.indexOf(':'); if (beginIndex > 0) message = "Syntax Error: " + message.substring(beginIndex + 1).trim(); String encountered = perr.getEncountered().trim(); int length = getErrorLength(encountered, result.document.get(), index); // build expected string List<String> lstExpected = perr.getExpected(); deleteDuplicatesAndSortList(lstExpected); // create error object SyntaxError serror = new SyntaxError(message, line, col, index, length, lstExpected, encountered); asmEditor.createSyntaxMark(serror, IMarker.SEVERITY_ERROR); } else { // OTHER ERROR String message = pe.getMessage(); int line = pe.getLocation().line; int col = pe.getLocation().column; // create error object UndefinedError error = new UndefinedError(message, line, col); asmEditor.createUndefinedMark(error, IMarker.SEVERITY_ERROR); } } } // ============================== // Helper methods for update(...) // ============================== private int getErrorLength(String token, String strDoc, int index) { if (token.equals("EOF")) return 0; if (strDoc.charAt(index)=='"' && strDoc.startsWith(token, index+1)) return token.length()+2; return token.length(); } private void deleteDuplicatesAndSortList(List<String> list) { SortedSet<String> setEntries = new TreeSet<String>(); for (String entry: list) if ( ! setEntries.contains(entry) ) setEntries.add(entry); list.clear(); list.addAll(setEntries); } }
37.416988
102
0.75534
eabcbf5bd5727ef762dc04150352fd6b9ae0f8d9
285
package org.seqcode.ml.classification; import weka.classifiers.AbstractClassifier; import weka.classifiers.bayes.*; public class WekaNaiveBayes { public static void main(String[] args){ NaiveBayes nb = new NaiveBayes(); AbstractClassifier.runClassifier(nb, args); } }
17.8125
45
0.754386
cb1b006ce37506191b7af1e11c7aacb4481b5693
1,637
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE * file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.alibaba.nacossync.util; import org.apache.commons.lang3.StringUtils; import java.io.File; /** * @author paderlol * @date: 2018-12-25 21:34 */ public final class DubboConstants { public static final String DUBBO_PATH_FORMAT = StringUtils.join(new String[] {"/dubbo", "%s", "providers"}, File.separator); public static final String DUBBO_URL_FORMAT ="%s://%s:%s?%s"; public static final String VERSION_KEY = "version"; public static final String GROUP_KEY = "group"; public static final String INTERFACE_KEY = "interface"; public static final String INSTANCE_IP_KEY = "ip"; public static final String INSTANCE_PORT_KEY = "port"; public static final String PROTOCOL_KEY = "protocol"; public static final String WEIGHT_KEY = "weight"; public static final String CATALOG_KEY = "providers"; }
45.472222
120
0.744044
2907db2e897d552a404de7c8635764b3db6d45e5
539
package com.wings.model; import java.io.Serializable; /** * * * * * @author : skywarker * @Date : 2012. 3. 12. * */ public class CodeModel implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String code; private String codeName; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getCodeName() { return codeName; } public void setCodeName(String codeName) { this.codeName = codeName; } }
12.534884
49
0.649351
07dc41328d88ec47617a95f074a7f5f68fb3f458
3,164
/* Copyright (c) 2014, Effektif GmbH. * * 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.effektif.workflow.api.model; import com.effektif.workflow.api.types.DataType; import java.util.HashMap; import java.util.Map; /** * @author Tom Baeyens */ public class DataContainer { protected Map<String,TypedValue> data; // transientData is not serialized (and DataContainer is not persisted) protected Map<String,Object> transientData; public Object getData(String key) { TypedValue value = data!=null ? data.get(key) : null; return value!=null ? value.getValue() : null; } public void setData(String key, Object value) { setTypedValue(key, new TypedValue(value)); } public void setData(String key, Object value, DataType dataType) { setTypedValue(key, new TypedValue(value, dataType)); } public void setTypedValue(String key, TypedValue value) { if (data==null) { data = new HashMap<>(); } data.put(key, value); } public DataContainer data(String key, Object value) { setData(key, value); return this; } public DataContainer data(String key, Object value, DataType dataType) { setData(key, value, dataType); return this; } public DataContainer typedValue(String key, TypedValue value) { setTypedValue(key, value); return this; } public DataContainer data(Map<String,Object> data) { if (data!=null) { for (String key: data.keySet()) { Object value = data.get(key); if (value instanceof TypedValue) { setTypedValue(key, (TypedValue) value); } else { setData(key, value); } } } return this; } public void removeData(String key) { if (data != null && key != null) { data.remove(key); } } public Map<String, TypedValue> getData() { return data; } public Map<String,Object> getTransientData() { return this.transientData; } public void setTransientData(Map<String,Object> transientData) { this.transientData = transientData; } public Object getTransientData(String key) { return transientData !=null ? transientData.get(key) : null; } public DataContainer transientData(String key,Object value) { if (transientData ==null) { transientData = new HashMap<>(); } this.transientData.put(key, value); return this; } public DataContainer transientDataOpt(String key,Object value) { if (value!=null) { transientData(key, value); } return this; } public Object removeTransientData(String key) { return transientData !=null ? transientData.remove(key) : null; } }
27.042735
75
0.677307
5b4db85d65d024adfbb6eafca61a33c2a82bd0fb
392
package ch.peters.daniel.adventuregame.items; /** * Key as Item. Uses id for unique identification. * * @author Daniel Peters * @version 1.0 */ public class Key extends Item { /** * Specify for which object the key is used for. */ private String keyId; public Key(String name, String description, String keyId) { super(name, description); this.keyId = keyId; } }
19.6
61
0.673469
4e8be058ecf0d176020343c41f5c82655ea82f63
7,232
package cn.edu.gdut.douyintoutiao.view.show.video; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import androidx.viewpager2.widget.ViewPager2; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import cn.edu.gdut.douyintoutiao.R; import cn.edu.gdut.douyintoutiao.entity.MyNews; import es.dmoral.toasty.Toasty; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * @author hayring * @date 2020.11.9 15:00 */ public class VerticalVideoPlayActivity extends VideoPlayActivity { private String status; private String key; public static final String DEFAULT = "default"; public static final String SEARCH = "search"; public static final String FLASHING_NO_SUPPORT = "flashingNoSupport"; private int errorCode = 0; private VideoStateAdapter adapter; List<Fragment> fragments = new ArrayList<>(); List<MyNews> newses = new ArrayList<>(); VerticalVideoViewModel verticalVideoPlayViewModel; @Override protected void onCreate(Bundle savedInstanceState) { //super 中已经设置了 setContentView super.onCreate(savedInstanceState); verticalVideoPlayViewModel = new ViewModelProvider(this,videoViewModelFactory).get(VerticalVideoViewModel.class); adapter = new VideoStateAdapter(this, fragments, newses); viewBinding.videoViewPager.setOrientation(ViewPager2.ORIENTATION_VERTICAL); viewBinding.videoViewPager.setAdapter(adapter); viewBinding.videoViewPager.registerOnPageChangeCallback(onPageChangeCallback); //数据 Live data verticalVideoPlayViewModel.getNewsesFromServer().observe(this, newsListObserver); verticalVideoPlayViewModel.getErrCode().observe(this, errorCodeObserver); } @Override public void removeVideo() { int position = viewBinding.videoViewPager.getCurrentItem(); fragments.remove(position); newses.remove(position); adapter.notifyDataSetChanged(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); Intent intent = getIntent(); String type = intent.getStringExtra("type"); if (!"search".equals(type)) { status = FLASHING_NO_SUPPORT.equals(type) ? FLASHING_NO_SUPPORT : DEFAULT; //获取附加的数据 List<MyNews> data; if ((data = (List<MyNews>) intent.getSerializableExtra("data")) != null) { adapter.addAllAndNotify(data); int currentIndex = getIntent().getIntExtra("index",-1); viewBinding.videoViewPager.setCurrentItem(currentIndex, false); } else { //视频列表有多少个视频了 int preCount = intent.getIntExtra("count",-1); if (preCount != -1) { verticalVideoPlayViewModel.getFollowVideoNewsByCount(preCount + 2); } else { verticalVideoPlayViewModel.getFollowVideoNewsByCount(); } } } else { status = SEARCH; key = intent.getStringExtra("key"); verticalVideoPlayViewModel.searchVideoNews(key); } } ViewModelProvider.Factory videoViewModelFactory = new ViewModelProvider.Factory() { @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { try { Constructor constructor = modelClass.getConstructor(Activity.class); return (T) constructor.newInstance(VerticalVideoPlayActivity.this); } catch (Exception e) { IllegalArgumentException ile = new IllegalArgumentException("" + modelClass + "is not" + VideoViewModel.class); ile.initCause(e); throw ile; } } }; private final ViewPager2.OnPageChangeCallback onPageChangeCallback = new ViewPager2.OnPageChangeCallback() { @Override public void onPageScrollStateChanged(int state) { if (FLASHING_NO_SUPPORT.equals(status)) return; if (state == 1) { if (adapter.getItemCount() == viewBinding.videoViewPager.getCurrentItem() + 1) { if (errorCode == 0) { Toasty.info(VerticalVideoPlayActivity.this, R.string.video_play_requesting, Toasty.LENGTH_SHORT, true).show(); } else { Toasty.error(VerticalVideoPlayActivity.this, getString(R.string.video_play_request_fail) + errorCode, Toasty.LENGTH_SHORT, true).show(); errorCode = 0; } } } else if (state == 0) { if (adapter.getItemCount() == viewBinding.videoViewPager.getCurrentItem() + 2) { if (DEFAULT.equals(status)) { verticalVideoPlayViewModel.getMoreFollowVideoNews(newses.size()); } else if (SEARCH.equals(status)) { verticalVideoPlayViewModel.searchMoreVideoNews(key, newses.size()); } } } } @Override public void onPageSelected(int position) { super.onPageSelected(position); MyNews news = getNewses().get(position); //调用父类方法 setCurrentNews(news); } }; private final Observer<List<MyNews>> newsListObserver = new Observer<List<MyNews>>() { @Override public void onChanged(List<MyNews> myNews) { adapter.addAllAndNotify(myNews); if (adapter.getItemCount() == myNews.size() && -1 != getIntent().getIntExtra("index",-1)) { int currentIndex = getIntent().getIntExtra("index",-1); viewBinding.videoViewPager.setCurrentItem(currentIndex, false); } } }; private final Observer<Integer> errorCodeObserver = new Observer<Integer>() { @Override public void onChanged(Integer errorCode) { VerticalVideoPlayActivity.this.errorCode = errorCode; } }; //getter setter 区 public VideoStateAdapter getAdapter() { return adapter; } public List<MyNews> getNewses() { return newses; } public String getStatus() { return status; } public String getKey() { return key; } // /** // * 给 VideoList返回更新的数据 // */ // @Override // public void finish() { // Intent innerIntent = getIntent(); // if (innerIntent.getSerializableExtra("data") != null) { // Intent intent = new Intent(); // intent.putExtra("data", (Serializable) newses); // setResult(RESULT_OK, intent); // } // super.finish(); // } }
31.719298
134
0.615874
475a46f07e03da8493f7298832e1aa9fe9949f24
1,568
package com.nulldreams.beone.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.nulldreams.beone.Finals; import com.nulldreams.beone.R; import com.nulldreams.beone.manager.OneManager; import com.nulldreams.beone.module.Content; import com.nulldreams.beone.module.TextDetail; import com.nulldreams.beone.retrofit.Result; import com.tencent.smtt.sdk.WebView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class TextDetailActivity extends AppCompatActivity { private static final String TAG = TextDetailActivity.class.getSimpleName(); private Content mContent; private WebView mWv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_text_detail); mWv = (WebView)findViewById(R.id.text_wv); mContent = (Content)getIntent().getSerializableExtra(Finals.KEY_CONTENT); OneManager.getInstance(this).getTextDetail(mContent.item_id, new Callback<Result<TextDetail>>() { @Override public void onResponse(Call<Result<TextDetail>> call, Response<Result<TextDetail>> response) { Log.v(TAG, "onResponse"); mWv.loadUrl(response.body().data.web_url); } @Override public void onFailure(Call<Result<TextDetail>> call, Throwable t) { Log.v(TAG, "onFailure " + t.getLocalizedMessage()); } }); } }
31.36
106
0.705357
72934a5b750e538a9e50a9426e9f65c839496390
7,902
/* SortKey.java -- Copyright (C) 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.xml.transform; import javax.xml.namespace.QName; import javax.xml.transform.TransformerException; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Node; import gnu.xml.xpath.Expr; /** * <p> * An XSL sort key, as specified by section 10 of the XSL * Transformations specification. This takes the form: * </p> * <pre> * &lt;xsl:sort * select = string-expression * lang = { nmtoken } * data-type = { "text" | "number" | qname-but-not-ncname } * order = { "ascending" | "descending" } * case-order = { "upper-first" | "lower-first" } /&rt; * </pre> * <p> * Note that all but the selection expression are optional, * and so may be {@code null}. * </p> * * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> */ final class SortKey { static final int DEFAULT = 0; static final int UPPER_FIRST = 1; static final int LOWER_FIRST = 2; final Expr select; final TemplateNode langTemplate; final TemplateNode dataTypeTemplate; final TemplateNode orderTemplate; final TemplateNode caseOrderTemplate; transient String lang; transient String dataType; transient boolean descending; transient int caseOrder; /** * Constructs a new {@link SortKey} to represent an &lt;xsl:sort&rt; * tag. * * @param select the XPath expression which selects the nodes to be sorted. * @param lang the language of the sort keys or {@code null} if unspecified. * @param dataType the data type of the strings. May be "string", "number", * a QName or {@code null} if unspecified. * @param order the ordering of the nodes, which may be "ascending", "descending" * or {@code null} if unspecified. * @param caseOrder the treatment of case when the data type is a string. This * may be "upper-first", "lower-first" or {@code null} if * unspecified. */ SortKey(Expr select, TemplateNode lang, TemplateNode dataType, TemplateNode order, TemplateNode caseOrder) { this.select = select; this.langTemplate = lang; this.dataTypeTemplate = dataType; this.orderTemplate = order; this.caseOrderTemplate = caseOrder; } String key(Node node) { Object ret = select.evaluate(node, 1, 1); if (ret instanceof String) { return (String) ret; } else { return Expr._string(node, ret); } } /** * Prepare for a sort. * This sets all transient variables from their AVTs. */ void init(Stylesheet stylesheet, QName mode, Node context, int pos, int len, Node parent, Node nextSibling) throws TransformerException { Document doc = (context instanceof Document) ? (Document) context : context.getOwnerDocument(); if (langTemplate == null) { lang = null; } else { DocumentFragment fragment = doc.createDocumentFragment(); langTemplate.apply(stylesheet, mode, context, pos, len, fragment, null); lang = Expr.stringValue(fragment); } if (dataTypeTemplate == null) { dataType = "text"; } else { DocumentFragment fragment = doc.createDocumentFragment(); dataTypeTemplate.apply(stylesheet, mode, context, pos, len, fragment, null); dataType = Expr.stringValue(fragment); } if (orderTemplate == null) { descending = false; } else { DocumentFragment fragment = doc.createDocumentFragment(); orderTemplate.apply(stylesheet, mode, context, pos, len, fragment, null); String order = Expr.stringValue(fragment); descending = "descending".equals(order); } if (caseOrderTemplate == null) { caseOrder = DEFAULT; } else { DocumentFragment fragment = doc.createDocumentFragment(); caseOrderTemplate.apply(stylesheet, mode, context, pos, len, fragment, null); String co = Expr.stringValue(fragment); caseOrder = "upper-first".equals(co) ? UPPER_FIRST : "lower-first".equals(co) ? LOWER_FIRST : DEFAULT; } } boolean references(QName var) { if (select != null && select.references(var)) { return true; } if (langTemplate != null && langTemplate.references(var)) { return true; } if (dataTypeTemplate != null && dataTypeTemplate.references(var)) { return true; } if (orderTemplate != null && orderTemplate.references(var)) { return true; } if (caseOrderTemplate != null && caseOrderTemplate.references(var)) { return true; } return false; } /** * Provides a clone of this {@link SortKey}, using the given * stylesheet as a context. * * @param stylesheet the stylesheet which provides context for the cloning. * @return a clone of this instance. */ SortKey clone(Stylesheet stylesheet) { return new SortKey(select.clone(stylesheet), langTemplate == null ? null : cloneAttributeValueTemplate(langTemplate, stylesheet), dataTypeTemplate == null ? null : cloneAttributeValueTemplate(dataTypeTemplate, stylesheet), orderTemplate == null ? null : cloneAttributeValueTemplate(orderTemplate, stylesheet), caseOrderTemplate == null ? null : cloneAttributeValueTemplate(caseOrderTemplate, stylesheet)); } /** * Clones an attribute value template as created by * {@link Stylesheet#parseAttributeValueTemplate(String, Node)}. * The node may either by a literal node or an xsl:value-of expression. * * @param node the node to clone. * @param stylesheet the stylesheet which provides context for the cloning. * @return the cloned node. */ private TemplateNode cloneAttributeValueTemplate(TemplateNode node, Stylesheet stylesheet) { if (node instanceof ValueOfNode) return ((ValueOfNode) node).clone(stylesheet); return ((LiteralNode) node).clone(stylesheet); } }
32.925
104
0.667932
46e0e6885384034c9b2cb6c5f74a3ec2c4f20943
878
package hevs.gdx2d.lib.interfaces; /** * An interface for Android actions that should be triggered from libgdx side * * @author Pierre-Andre Mudry (mui) * @author Christopher Metrailler (mei) * @version 1.1 */ public interface AndroidResolver { int LENGTH_LONG = 0x01; // Toast.LENGTH_LONG int LENGTH_SHORT = 0x00; // Toast.LENGTH_SHORT /** * Display an about dialog Activity. */ void showAboutBox(); /** * Force to dismiss the about dialog. Must be called when the screen * orientation change. */ void dismissAboutBox(); /** * Show an Android Toast on the screen with default position on the screen * (bottom center). * * @param text The text of the Toast * @param duration How long to display the message. Either {@link LENGTH_SHORT} * or {@link LENGTH_LONG} */ void showToast(CharSequence text, int duration); }
24.388889
80
0.687927
da5b8af09cb9130d0139f0c78e81785503bda1e2
31,036
package cn.tenmg.sqltool; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import cn.tenmg.sqltool.data.Page; public abstract class TestUtils { /** * * 当不指定批处理大小时,默认的批处理大小 * * The default batch size when no batch size is specified */ private static int defaultBatchSize = 500; private static String position = "Software Engineer"; private static DecimalFormat df = new DecimalFormat("0000000000"); public static void testDao(Dao dao) { // 测试插入数据 insert(dao); // 测试批量插入数据 insertBatch(dao); // 测试更新数据 update(dao); // 测试批量更新数据 updateBatch(dao); // 测试软保存数据 save(dao); // 测试批量软保存数据 saveBatch(dao); // 测试硬保存数据 hardSave(dao); // 测试批量硬保存数据 hardSaveBatch(dao); // 测试删除数据 delete(dao); // 测试删除数据 deleteBatch(dao); // 测试单条记录查询 get(dao); // 测试多条记录查询 select(dao); // 测试分页查询 page(dao); // 测试执行语句 execute(dao); // 测试执行更新语句 executeUpdate(dao); } private static void insert(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 String staffName = "June"; StaffInfo staffInfo = new StaffInfo("000001"); staffInfo.setStaffName(staffName); /** * * 插入单条记录 * * Insert entity object/objects */ dao.insert(staffInfo); staffInfo.setStaffName(null); dao.save(staffInfo); /** * 使用DSQL编号查询。同时,你还可以使用Map对象来更自由地组织查询参数 * * Query with DSQL's id. You can also use map object to organize query * parameters at the same time */ Map<String, String> paramaters = new HashMap<String, String>(); paramaters.put("staffId", "000001"); StaffInfo june = dao.get(StaffInfo.class, "get_staff_info_by_staff_id", paramaters); Assert.assertEquals(staffName, june.getStaffName()); Assert.assertEquals(staffName, dao.get(staffInfo).getStaffName()); /** * 插入多条记录 */ // 条目数小于批容量 dao.execute("DELETE FROM STAFF_INFO"); // 清空表 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); DecimalFormat df = new DecimalFormat("0000000000"); for (int i = 1; i < defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfos.add(staffInfo); } dao.insert(staffInfos); Assert.assertEquals(defaultBatchSize - 1, dao.get(Long.class, "get_total_staff_count").intValue()); // 条目数等于批容量 dao.execute("DELETE FROM STAFF_INFO"); // 清空表 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize)); staffInfo.setStaffName("" + defaultBatchSize); staffInfos.add(staffInfo); dao.insert(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_total_staff_count").intValue()); // 条目数大于批容量 dao.execute("DELETE FROM STAFF_INFO"); // 清空表 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize + 1)); staffInfo.setStaffName("" + (defaultBatchSize + 1)); staffInfos.add(staffInfo); dao.insert(staffInfos); Assert.assertEquals(defaultBatchSize + 1, dao.get(Long.class, "get_total_staff_count").intValue()); } private static void insertBatch(Dao dao) { /** * 批量插入多条记录 */ // 条目数小于批容量 dao.execute("DELETE FROM STAFF_INFO"); // 清空表 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); StaffInfo staffInfo; for (int i = 1; i < defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfo.setPosition(position); staffInfos.add(staffInfo); } dao.insertBatch(staffInfos); Assert.assertEquals(defaultBatchSize - 1, dao.get(Long.class, "get_total_staff_count").intValue()); // 条目数等于批容量 dao.execute("DELETE FROM STAFF_INFO"); // 清空表 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize)); staffInfo.setStaffName("" + defaultBatchSize); staffInfo.setPosition(position); staffInfos.add(staffInfo); dao.insertBatch(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_total_staff_count").intValue()); // 条目数大于批容量 dao.execute("DELETE FROM STAFF_INFO"); // 清空表 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize + 1)); staffInfo.setStaffName("" + (defaultBatchSize + 1)); staffInfo.setPosition(position); staffInfos.add(staffInfo); dao.insertBatch(staffInfos); Assert.assertEquals(defaultBatchSize + 1, dao.get(Long.class, "get_total_staff_count").intValue()); } private static void update(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 // 初始化数据 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); StaffInfo staffInfo; for (int i = 0; i < defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfo.setPosition(position); staffInfos.add(staffInfo); } dao.insertBatch(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_total_staff_count").intValue()); // 更新单条数据 String staffId = df.format(0), staffName = "June"; StaffInfo june = new StaffInfo(staffId), original = dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId); june.setStaffName(staffName); june.setPosition(position); Assert.assertEquals(1, dao.update(june)); StaffInfo newStaffInfo = dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId); Assert.assertEquals(staffName, newStaffInfo.getStaffName()); Assert.assertEquals(original.getPosition(), newStaffInfo.getPosition()); june.setStaffName(null); dao.update(june); // 软更新,不更新null属性 Assert.assertEquals(staffName, dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId).getStaffName()); // 部分硬更新,属性即使是null也更新 Assert.assertEquals(1, dao.update(june, "staffName")); Assert.assertEquals(null, dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId).getStaffName()); // 更新多条数据 for (int i = 0; i < defaultBatchSize; i++) { staffInfo = staffInfos.get(i); staffInfo.setStaffName(staffName); } dao.update(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_staff_count_the_same_name", "staffName", staffName).intValue()); // 软更新,不更新null属性 long count = dao.get(Long.class, "get_staff_count_the_same_name", "staffName", staffName); for (int i = 0; i < defaultBatchSize; i++) { staffInfo = staffInfos.get(i); staffInfo.setStaffName(null); } dao.update(staffInfos); Assert.assertEquals(count, dao.get(Long.class, "get_staff_count_the_same_name", "staffName", staffName).longValue()); // 部分硬更新,属性即使是null也更新 dao.update(staffInfos, "staffName"); Assert.assertEquals(0, dao.get(Long.class, "get_staff_count_the_same_name", "staffName", staffName).longValue()); // 尝试更新不存在的数据 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize + 1)); staffInfo.setStaffName("" + (defaultBatchSize + 1)); staffInfo.setPosition(position); Assert.assertEquals(0, dao.update(staffInfo)); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_total_staff_count").intValue()); staffInfos.add(staffInfo); dao.update(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_total_staff_count").intValue()); } private static void updateBatch(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 // 初始化数据 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); StaffInfo staffInfo; for (int i = 0; i < defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfo.setPosition(position); staffInfos.add(staffInfo); } dao.insertBatch(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_total_staff_count").intValue()); // 批量更新多条数据 String staffName = "June"; for (int i = 0; i < defaultBatchSize; i++) { staffInfo = staffInfos.get(i); staffInfo.setStaffName(staffName); } dao.updateBatch(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_staff_count_the_same_name", "staffName", staffName).intValue()); // 软更新,不更新null属性 for (int i = 0; i < defaultBatchSize; i++) { staffInfo = staffInfos.get(i); staffInfo.setStaffName(null); } dao.updateBatch(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_staff_count_the_same_name", "staffName", staffName).intValue()); // 硬更新,null属性也更新 dao.updateBatch(staffInfos, "staffName"); Assert.assertEquals(0, dao.get(Long.class, "get_staff_count_the_same_name", "staffName", staffName).intValue()); // 尝试更新不存在的数据 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize + 1)); staffInfo.setStaffName("" + (defaultBatchSize + 1)); staffInfo.setPosition(position); staffInfos.add(staffInfo); dao.updateBatch(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_total_staff_count").intValue()); } private static void save(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 /** * * 保存(插入或更新)实体对象 * * Save(insert or update) entity object/objects */ String staffId = "000001"; StaffInfo june = new StaffInfo(staffId); june.setStaffName("June"); dao.save(june); StaffInfo staffInfo = dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId); Assert.assertEquals(june.getStaffName(), staffInfo.getStaffName()); june.setStaffName("Happy June"); june.setPosition(position); dao.save(june); staffInfo = dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId); Assert.assertEquals(june.getStaffName(), staffInfo.getStaffName()); Assert.assertEquals(position, staffInfo.getPosition()); june.setPosition(null); dao.save(june, "position"); Assert.assertEquals(null, dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId).getPosition()); dao.execute("DELETE FROM STAFF_INFO"); // 清空表 /** * 软保存多条记录 */ // 条目数小于批容量 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); for (int i = 1; i < defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfos.add(staffInfo); } dao.save(staffInfos, "position"); Assert.assertEquals(0, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数等于批容量 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize)); staffInfo.setStaffName("" + defaultBatchSize); staffInfo.setPosition(position); staffInfos.add(staffInfo); dao.save(staffInfos, "position"); Assert.assertEquals(1, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数大于批容量 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize + 1)); staffInfo.setStaffName("" + (defaultBatchSize + 1)); staffInfo.setPosition(position); staffInfos.add(staffInfo); dao.save(staffInfos, "position"); Assert.assertEquals(2, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); } private static void saveBatch(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 /** * 批量软保存多条记录 */ // 初始化数据 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); StaffInfo staffInfo; for (int i = 1; i <= defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfo.setPosition(position); staffInfos.add(staffInfo); } dao.saveBatch(staffInfos, "position"); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数小于批容量 staffInfos = new ArrayList<StaffInfo>(); for (int i = 1; i < defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfos.add(staffInfo); } dao.saveBatch(staffInfos, "position"); Assert.assertEquals(1, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数等于批容量 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize)); staffInfo.setStaffName("" + defaultBatchSize); staffInfos.add(staffInfo); dao.saveBatch(staffInfos, "position"); Assert.assertEquals(0, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数大于批容量 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize + 1)); staffInfo.setStaffName("" + (defaultBatchSize + 1)); staffInfos.add(staffInfo); dao.saveBatch(staffInfos, "position"); Assert.assertEquals(0, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); Assert.assertEquals(defaultBatchSize + 1, dao.get(Long.class, "get_staff_count_of_specific_position", "position", null).intValue()); } private static void hardSave(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 /** * 硬保存数据 */ String staffId = "000001"; StaffInfo staffInfo = new StaffInfo(staffId); staffInfo.setStaffName("June"); staffInfo.setPosition(position); dao.hardSave(staffInfo); Assert.assertEquals(position, dao .get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffInfo.getStaffId()).getPosition()); staffInfo.setPosition(null); dao.hardSave(staffInfo); Assert.assertEquals(null, dao .get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffInfo.getStaffId()).getPosition()); dao.execute("DELETE FROM STAFF_INFO"); // 清空表 /** * 硬保存多条记录 */ // 初始化数据 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); for (int i = 1; i <= defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfo.setPosition(position); staffInfos.add(staffInfo); } dao.hardSave(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数小于批容量 staffInfos = new ArrayList<StaffInfo>(); for (int i = 1; i < defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfos.add(staffInfo); } dao.hardSave(staffInfos); Assert.assertEquals(1, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数等于批容量 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize)); staffInfo.setStaffName("" + defaultBatchSize); staffInfos.add(staffInfo); dao.hardSave(staffInfos); Assert.assertEquals(0, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数大于批容量 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize + 1)); staffInfo.setStaffName("" + (defaultBatchSize + 1)); staffInfos.add(staffInfo); dao.hardSave(staffInfos); Assert.assertEquals(0, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); Assert.assertEquals(defaultBatchSize + 1, dao.get(Long.class, "get_staff_count_of_specific_position", "position", null).intValue()); } private static void hardSaveBatch(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 /** * 批量硬保存多条记录 */ // 初始化数据 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); StaffInfo staffInfo; for (int i = 1; i <= defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfo.setPosition(position); staffInfos.add(staffInfo); } dao.hardSaveBatch(staffInfos); Assert.assertEquals(defaultBatchSize, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数小于批容量 staffInfos = new ArrayList<StaffInfo>(); for (int i = 1; i < defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfos.add(staffInfo); } dao.hardSaveBatch(staffInfos); Assert.assertEquals(1, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数等于批容量 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize)); staffInfo.setStaffName("" + defaultBatchSize); staffInfos.add(staffInfo); dao.hardSaveBatch(staffInfos); Assert.assertEquals(0, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 条目数大于批容量 staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize + 1)); staffInfo.setStaffName("" + (defaultBatchSize + 1)); staffInfos.add(staffInfo); dao.hardSaveBatch(staffInfos); Assert.assertEquals(0, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); Assert.assertEquals(defaultBatchSize + 1, dao.get(Long.class, "get_staff_count_of_specific_position", "position", null).intValue()); } private static void delete(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 // 初始化数据 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); StaffInfo staffInfo; int total = defaultBatchSize * 3 + 1; for (int i = 1; i <= total; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfo.setPosition(position); staffInfos.add(staffInfo); } dao.hardSaveBatch(staffInfos); Assert.assertEquals(total, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 删除单条记录 StaffInfo first = new StaffInfo(df.format(1)); Assert.assertEquals(1, dao.delete(first)); Assert.assertEquals(null, dao.get(first)); // 删除多条记录 // 小于批容量 List<StaffInfo> staffInfosForDelete = new ArrayList<StaffInfo>(); for (int i = 2; i <= defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfosForDelete.add(staffInfo); } Assert.assertEquals(defaultBatchSize - 1, dao.delete(staffInfosForDelete)); Assert.assertEquals(total - defaultBatchSize, dao.get(Long.class, "get_total_staff_count").intValue()); // 等于批容量 staffInfosForDelete = new ArrayList<StaffInfo>(); for (int i = 1; i <= defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize + i)); staffInfosForDelete.add(staffInfo); } Assert.assertEquals(defaultBatchSize, dao.delete(staffInfosForDelete)); Assert.assertEquals(total - 2 * defaultBatchSize, dao.get(Long.class, "get_total_staff_count").intValue()); // 大于批容量 staffInfosForDelete = new ArrayList<StaffInfo>(); for (int i = 0; i <= defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(2 * defaultBatchSize + i + 1)); staffInfosForDelete.add(staffInfo); } Assert.assertEquals(defaultBatchSize + 1, dao.delete(staffInfosForDelete)); Assert.assertEquals(0, dao.get(Long.class, "get_total_staff_count").intValue()); } private static void deleteBatch(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 // 初始化数据 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); StaffInfo staffInfo; int total = defaultBatchSize * 3; for (int i = 1; i <= total; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfo.setStaffName("" + i); staffInfo.setPosition(position); staffInfos.add(staffInfo); } dao.hardSaveBatch(staffInfos); Assert.assertEquals(total, dao.get(Long.class, "get_staff_count_of_specific_position", "position", position).intValue()); // 删除多条记录 // 小于批容量 List<StaffInfo> staffInfosForDelete = new ArrayList<StaffInfo>(); for (int i = 1; i < defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(i)); staffInfosForDelete.add(staffInfo); } Assert.assertEquals(defaultBatchSize - 1, dao.delete(staffInfosForDelete)); Assert.assertEquals(total - defaultBatchSize + 1, dao.get(Long.class, "get_total_staff_count").intValue()); // 等于批容量 staffInfosForDelete = new ArrayList<StaffInfo>(); for (int i = 0; i < defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(defaultBatchSize + i)); staffInfosForDelete.add(staffInfo); } Assert.assertEquals(defaultBatchSize, dao.delete(staffInfosForDelete)); Assert.assertEquals(total - 2 * defaultBatchSize + 1, dao.get(Long.class, "get_total_staff_count").intValue()); // 大于批容量 staffInfosForDelete = new ArrayList<StaffInfo>(); for (int i = 0; i <= defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffInfo.setStaffId(df.format(2 * defaultBatchSize + i)); staffInfosForDelete.add(staffInfo); } Assert.assertEquals(defaultBatchSize + 1, dao.delete(staffInfosForDelete)); Assert.assertEquals(0, dao.get(Long.class, "get_total_staff_count").intValue()); } private static void get(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 // 初始化数据 String staffId = "000001", staffName = "June"; StaffInfo june = new StaffInfo(staffId); june.setStaffName(staffName); dao.save(june); /** * 使用员工编号获取员工信息 * * Load staff information with staffId */ StaffInfo staffInfo = dao.get(new StaffInfo(staffId)); Assert.assertEquals(staffName, staffInfo.getStaffName()); /** * 使用DSQL编号查询 * * Query with id of DSQL's id */ staffInfo = dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId); Assert.assertEquals(staffName, staffInfo.getStaffName()); Map<String, Object> params = new HashMap<String, Object>(); params.put("staffId", staffId); staffInfo = dao.get(StaffInfo.class, "get_staff_info_by_staff_id", params); Assert.assertEquals(staffName, staffInfo.getStaffName()); } private static void select(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 // 初始化数据 StaffInfo sharry = new StaffInfo("000001"), june = new StaffInfo("000002"); String staffName = "Sharry"; sharry.setStaffName(staffName); june.setStaffName("June"); dao.save(Arrays.asList(sharry, june)); /** * 使用员工编号查询员工信息 * * Load staff information with staffId */ List<StaffInfo> staffInfos = dao.select(new StaffInfo("000001")); Assert.assertNotNull(staffInfos); Assert.assertEquals(1, staffInfos.size()); Assert.assertEquals(staffName, staffInfos.get(0).getStaffName()); StaffInfo staffInfo = new StaffInfo(); staffInfo.setStaffName(staffName); staffInfos = dao.select(staffInfo); Assert.assertNotNull(staffInfos); Assert.assertEquals(1, staffInfos.size()); Assert.assertEquals(staffName, staffInfos.get(0).getStaffName()); /** * 使用员工编号查询员工信息 */ String[] staffIdArray = new String[] { "000001", "000002" }; staffInfos = dao.select(StaffInfo.class, "find_staff_info_by_staff_ids", "staffIds", staffIdArray); Assert.assertNotNull(staffInfos); Assert.assertEquals(2, staffInfos.size()); Assert.assertEquals("Sharry", staffInfos.get(0).getStaffName()); Assert.assertEquals("June", staffInfos.get(1).getStaffName()); List<String> staffIds = new ArrayList<String>(); staffIds.add("000001"); staffIds.add("000002"); staffInfos = dao.select(StaffInfo.class, "find_staff_info_by_staff_ids", "staffIds", staffIds); Assert.assertNotNull(staffInfos); Assert.assertEquals(2, staffInfos.size()); Assert.assertEquals("Sharry", staffInfos.get(0).getStaffName()); Assert.assertEquals("June", staffInfos.get(1).getStaffName()); Map<String, Object> params = new HashMap<String, Object>(); params.put("staffIds", staffIdArray); staffInfos = dao.select(StaffInfo.class, "find_staff_info_by_staff_ids", params); Assert.assertNotNull(staffInfos); Assert.assertEquals(2, staffInfos.size()); Assert.assertEquals("Sharry", staffInfos.get(0).getStaffName()); Assert.assertEquals("June", staffInfos.get(1).getStaffName()); params.put("staffIds", staffIds); staffInfos = dao.select(StaffInfo.class, "find_staff_info_by_staff_ids", params); Assert.assertNotNull(staffInfos); Assert.assertEquals(2, staffInfos.size()); Assert.assertEquals("Sharry", staffInfos.get(0).getStaffName()); Assert.assertEquals("June", staffInfos.get(1).getStaffName()); } private static void page(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 // 初始化数据 List<StaffInfo> staffInfos = new ArrayList<StaffInfo>(); StaffInfo staffInfo; int staffNameLikeCount = 0; String staffNameLike = "1", staffId; for (int i = 1; i <= defaultBatchSize; i++) { staffInfo = new StaffInfo(); staffId = df.format(i); if (staffId.contains(staffNameLike)) { staffNameLikeCount++; } staffInfo.setStaffId(staffId); staffInfo.setStaffName("" + i); staffInfo.setPosition(position); staffInfos.add(staffInfo); } dao.save(staffInfos); long currentPage = 1; int pageSize = defaultBatchSize / 10; Page<StaffInfo> page = dao.page(StaffInfo.class, "select * from staff_info", currentPage, pageSize); Assert.assertEquals(currentPage, page.getCurrentPage()); Assert.assertEquals(pageSize, page.getPageSize()); Assert.assertEquals(defaultBatchSize, page.getTotal().intValue()); Assert.assertEquals(pageSize, page.getRows().size()); long totalPage = page.getTotalPage(); page = dao.page(StaffInfo.class, "select * from staff_info order by staff_id", totalPage, pageSize); Assert.assertEquals(totalPage, page.getCurrentPage()); Assert.assertEquals(pageSize, page.getPageSize()); Assert.assertEquals(defaultBatchSize, page.getTotal().intValue()); List<StaffInfo> rows = page.getRows(); Assert.assertEquals(df.format(defaultBatchSize), rows.get(rows.size() - 1).getStaffId()); page = dao.page(StaffInfo.class, "select * from staff_info order by staff_id desc", currentPage, pageSize); Assert.assertEquals(currentPage, page.getCurrentPage()); Assert.assertEquals(pageSize, page.getPageSize()); Assert.assertEquals(defaultBatchSize, page.getTotal().intValue()); Assert.assertEquals(df.format(defaultBatchSize), page.getRows().get(0).getStaffId()); Map<String, Object> params = new HashMap<String, Object>(); params.put("staffName", "1"); page = dao.page(StaffInfo.class, "find_staff_info_staff_name_like", currentPage, pageSize, params); Assert.assertEquals(currentPage, page.getCurrentPage()); Assert.assertEquals(pageSize, page.getPageSize()); Assert.assertEquals(staffNameLikeCount, page.getTotal().intValue()); page = dao.page(StaffInfo.class, "find_staff_info_staff_name_like_with", currentPage, pageSize, "staffName", "1"); Assert.assertEquals(currentPage, page.getCurrentPage()); Assert.assertEquals(pageSize, page.getPageSize()); Assert.assertEquals(staffNameLikeCount, page.getTotal().intValue()); params.put("defualtPosition", "Salesperson"); page = dao.page(StaffInfo.class, "find_staff_info_staff_name_like_order_by_has_param", currentPage, pageSize, params); Assert.assertEquals(currentPage, page.getCurrentPage()); Assert.assertEquals(pageSize, page.getPageSize()); Assert.assertEquals(staffNameLikeCount, page.getTotal().intValue()); Assert.assertEquals(df.format(1), page.getRows().get(0).getStaffId()); page = dao.page(StaffInfo.class, "find_staff_info_staff_name_like_order_by_staff_name", "find_staff_info_staff_name_like", currentPage, pageSize, params); Assert.assertEquals(currentPage, page.getCurrentPage()); Assert.assertEquals(pageSize, page.getPageSize()); Assert.assertEquals(staffNameLikeCount, page.getTotal().intValue()); Assert.assertEquals(df.format(1), page.getRows().get(0).getStaffId()); page = dao.page(StaffInfo.class, "find_staff_info_staff_name_like_order_by_staff_name", "find_staff_info_staff_name_like", currentPage, pageSize, "staffName", "1"); Assert.assertEquals(currentPage, page.getCurrentPage()); Assert.assertEquals(pageSize, page.getPageSize()); Assert.assertEquals(staffNameLikeCount, page.getTotal().intValue()); Assert.assertEquals(df.format(1), page.getRows().get(0).getStaffId()); page = dao.page(StaffInfo.class, "find_staff_info_staff_name_like_order_by_staff_name", "find_staff_info_staff_name_like", currentPage, pageSize, params); Assert.assertEquals(currentPage, page.getCurrentPage()); Assert.assertEquals(pageSize, page.getPageSize()); Assert.assertEquals(staffNameLikeCount, page.getTotal().intValue()); Assert.assertEquals(df.format(1), page.getRows().get(0).getStaffId()); } private static void execute(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 /** * 插入语句 */ String staffId = "000001", staffName = "June"; dao.execute("INSERT INTO STAFF_INFO(STAFF_ID, STAFF_NAME) VALUES (:staffId, :staffName)", "staffId", staffId, "staffName", staffName); StaffInfo staffInfo = dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId); Assert.assertEquals(staffName, staffInfo.getStaffName()); /** * 更新语句 */ String newStaffName = "Sharry"; dao.execute("UPDATE STAFF_INFO SET STAFF_NAME = :staffName WHERE STAFF_ID = :staffId", "staffId", staffId, "staffName", newStaffName); Assert.assertEquals(newStaffName, dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId).getStaffName()); /** * 删除语句 */ Map<String, String> params = new HashMap<String, String>(); params.put("staffId", staffId); dao.execute("DELETE FROM STAFF_INFO WHERE STAFF_ID = :staffId", params); Assert.assertNull(dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId)); } private static void executeUpdate(Dao dao) { dao.execute("DELETE FROM STAFF_INFO"); // 清空表 /** * 插入语句 */ String staffId = "000001", staffName = "June"; int count = dao.executeUpdate("INSERT INTO STAFF_INFO(STAFF_ID, STAFF_NAME) VALUES (:staffId, :staffName)", "staffId", staffId, "staffName", staffName); Assert.assertEquals(1, count); Assert.assertEquals(staffName, dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId).getStaffName()); /** * 更新语句 */ String newStaffName = "Sharry"; count = dao.executeUpdate("UPDATE STAFF_INFO SET STAFF_NAME = :staffName WHERE STAFF_ID = :staffId", "staffId", staffId, "staffName", newStaffName); Assert.assertEquals(1, count); Assert.assertEquals(newStaffName, dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId).getStaffName()); /** * 删除语句 */ Map<String, String> params = new HashMap<String, String>(); params.put("staffId", staffId); count = dao.executeUpdate("DELETE FROM STAFF_INFO WHERE STAFF_ID = :staffId", params); Assert.assertEquals(1, count); Assert.assertNull(dao.get(StaffInfo.class, "get_staff_info_by_staff_id", "staffId", staffId)); } }
35.838337
120
0.720421
04ecd761deaa1db685859fae10edf372a65e9001
1,141
package com.smartgwt.mobile.client.widgets.form.fields; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Style; import com.smartgwt.mobile.client.theme.FormCssResource; import com.smartgwt.mobile.client.widgets.form.DynamicForm; public class SpacerItem extends FormItem { private static final FormCssResource CSS = DynamicForm._CSS; private static final int DEFAULT_HEIGHT = 15; private static int nextNum = 1; private Integer height; public SpacerItem() { super("$36z-" + Integer.toString(nextNum++), Document.get().createDivElement()); getElement().addClassName(CSS.spacerItemClass()); internalSetHeight(DEFAULT_HEIGHT); } public final Integer getHeight() { return height; } private void internalSetHeight(int height) { final int newHeight = Math.min(0, height); this.height = newHeight; getElement().getStyle().setHeight(newHeight, Style.Unit.PX); } public void setHeight(int height) { internalSetHeight(height); } @Override public boolean validate() { return true; } }
27.829268
88
0.691499
42b6dd0063a207f52dd1e6d7128eb11ea15e9067
4,489
package com.abin.lee.algorithm.special.basic.maze; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Stack; /** * Created by abin on 2018/5/29 16:51. * algorithm-svr * com.abin.lee.algorithm.special.basic.maze * 基于深度优先遍历的随机迷宫算法 * https://blog.csdn.net/y378076136/article/details/19832659 */ public class Maze { int len = 11; //迷宫长度 int wid = 11; //迷宫宽度 char wall = '■'; //代表墙 char blank = '○'; //代表空地 char[][] maze; //迷宫 boolean[][] visit; //用来标记某一格是否被访问过 Node start = new Node(0, 0); //开始节点 Node exit = new Node(len - 1, wid - 1); //出口,其实现在也没什么用,因为没有交互只是生成了一个迷宫而已 Node cur; //当前格 Node next; //下一格 Stack<Node> path = new Stack<Node>(); //表示路径的栈 int[][] adj = { {0, 2}, {0, -2}, {2, 0}, {-2, 0} }; //用来计算邻接格 /** * 迷宫的格子类 * * @author Yan */ class Node { int x, y; public Node() { } public Node(int x, int y) { this.x = x; this.y = y; } public String toString() { return "Node [x=" + x + ", y=" + y + "]"; } } /** * 初始化,初始化迷宫参数 */ void init() { maze = new char[len][wid]; visit = new boolean[len][wid]; for (int i = 0; i < len; i++) { for (int j = 0; j < wid; j++) { maze[i][j] = wall; visit[i][j] = false; } } visit[start.x][start.y] = true; maze[start.x][start.y] = blank; cur = start; //将当前格标记为开始格 } /** * 打印结果 */ void printMaze() { for (int i = 0; i < len; i++) { for (int j = 0; j < wid; j++) { System.out.print(maze[i][j] + " "); // // if(maze[i][j] == '○') // { // System.err.print(maze[i][j] + " "); // } // else // { // System.out.print(maze[i][j] + " "); // } // try { // Thread.sleep(100); // } catch (InterruptedException e) { // e.printStackTrace(); // } } System.out.println(); } System.out.println("=========================================="); } /** * 开始制作迷宫 */ void makeMaze() { path.push(cur); //将当前格压入栈 while (!path.empty()) { Node[] adjs = notVisitedAdj(cur);//寻找未被访问的邻接格 if (adjs.length == 0) { cur = path.pop();//如果该格子没有可访问的邻接格,则跳回上一个格子 continue; } next = adjs[new Random().nextInt(adjs.length)]; //随机选取一个邻接格 int x = next.x; int y = next.y; //如果该节点被访问过,则回到上一步继续寻找 if (visit[x][y]) { cur = path.pop(); } else//否则将当前格压入栈,标记当前格为已访问,并且在迷宫地图上移除障碍物 { path.push(next); visit[x][y] = true; maze[x][y] = blank; maze[(cur.x + x) / 2][(cur.y + y) / 2] = blank; //移除当前格与下一个之间的墙壁 cur = next;//当前格等于下一格 } } } /** * 判断节点是否都被访问 * * @param ns * @return */ boolean allVisited(Node[] ns) { for (Node n : ns) { if (!visit[n.x][n.y]) return false; } return true; } /** * 寻找可访问的邻接格,这里可以优化,不用list * {0, 2}, {0, -2}, {2, 0}, {-2, 0} * @param node * @return */ Node[] notVisitedAdj(Node node) { List<Node> list = new ArrayList<Node>(); for (int i = 0; i < adj.length; i++) { int x = node.x + adj[i][0]; int y = node.y + adj[i][1]; if (x >= 0 && x < len && y >= 0 && y < wid) { if (!visit[x][y]) list.add(new Node(x, y)); } } Node[] a = new Node[list.size()]; for (int i = 0; i < list.size(); i++) { a[i] = list.get(i); } return a; } /** * 入口方法 * * @param args */ public static void main(String[] args) { Maze m = new Maze(); m.init(); System.out.println("--------------------初始化迷宫----------------------------"); m.printMaze(); System.out.println("--------------------初始化迷宫----------------------------"); m.makeMaze(); m.printMaze(); } }
23.380208
84
0.398084
3c72b40294fcad1908a1f204d8cb7b39defdd36a
1,374
package info.mornlight.gw2s.android.model.event; public class Event { private int worldId; private int mapId; private String eventId; private EventState state; private transient String eventName; private transient String mapName; public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } public String getMapName() { return mapName; } public void setMapName(String mapName) { this.mapName = mapName; } public Event() { } public Event(int worldId, int mapId, String eventId, EventState state) { this.worldId = worldId; this.mapId = mapId; this.eventId = eventId; this.state = state; } public int getWorldId() { return worldId; } public void setWorldId(int worldId) { this.worldId = worldId; } public int getMapId() { return mapId; } public void setMapId(int mapId) { this.mapId = mapId; } public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public EventState getState() { return state; } public void setState(EventState state) { this.state = state; } }
18.821918
76
0.598981
e39cb27ae22dfb2472f8d4fb38d31cd2042653f6
1,291
// layer: frameworksanddrivers package server; import java.net.MalformedURLException; import java.net.URL; /** A set of environment variables related to the functioning of this program */ public class Env { private static final String SENSO_API_BASE_URL = System.getenv("SENSO_API_BASE_URL"); private static final String SENSO_API_KEY = System.getenv("SENSO_API_KEY"); public static final URL SENSO_SCORE_URL = createScoreURL(); public static final URL SENSO_RATE_URL = createRateURL(); public static final int PORT = System.getenv("PORT") != null ? Integer.parseInt(System.getenv("PORT")) : 8080; public static final String POSTGRES_PASSWORD = System.getenv("POSTGRES_PASSWORD"); private static URL createScoreURL() throws ExceptionInInitializerError { try { return new URL(SENSO_API_BASE_URL + "/score?key=" + SENSO_API_KEY); } catch (MalformedURLException e) { throw new ExceptionInInitializerError(e); } } private static URL createRateURL() throws ExceptionInInitializerError { try { return new URL(SENSO_API_BASE_URL + "/rate?key=" + SENSO_API_KEY); } catch (MalformedURLException e) { throw new ExceptionInInitializerError(e); } } }
39.121212
91
0.697134
0c4ae2123fff4dec1ed0377c657605ad86071caa
15,906
package uk.ac.aber.dcs.cs124.clg11.diag; import java.awt.Graphics; import uk.ac.aber.dcs.cs124.clg11.data.ClassDiagData; import uk.ac.aber.dcs.cs124.clg11.data.RelationshipDiagData; /** * GUI layer used to output/draw relationship diagram * to the {@link uk.ac.aber.dcs.cs124.clg11.panel.CanvasPanel}. * * Retrieves data about classes and relationship from {@link uk.ac.aber.dcs.cs124.clg11.data.ClassDiagData} & * {@link uk.ac.aber.dcs.cs124.clg11.data.RelationshipDiagData} objects. * * Stored of type 'RelationshipDiag' in VectorOfDrawables * * @author Connor Goddard (clg11), Sam Jackson (slj11), Craig Heptinstall (crh13) * */ public class RelationshipDiag extends Drawable { private int diamondX, diamondY; private String arrowDir; /** * RelationshipDiagData object used to store data relating to the relationship diagram */ private RelationshipDiagData reld = new RelationshipDiagData(); public RelationshipDiag() { } /** * Determines and sets the two classes to have the relationship drawn between including the relationship type and multiplicities * * @param a - First 'ClassDiag' object to draw relationship from * @param b - Second 'ClassDiag' object to draw relationship to * @param assocVar - Associated variable for relationship used in classes * @param classAMulti - Multiplicity value for first class * @param classBMulti - Multiplicity value for second class * @param relType - Relationship type (e.g. Inheritance, Aggregation etc..) */ public RelationshipDiag(ClassDiag a,ClassDiag b, String assocVar, String classAMulti, String classBMulti, String relType) { reld.setClassA(a); reld.setClassB(b); ClassDiagData d = (ClassDiagData) reld.getClassA().getData(); d.addAssocInstanceVar(assocVar); reld.setAssocVar(assocVar); reld.setRelType(relType); reld.setClassAMulti(classAMulti); reld.setClassBMulti(classBMulti); } /** * Determines whether the {@link uk.ac.aber.dcs.cs124.clg11.data.RelationshipDiagData} object contains a reference to the selected classes * @param d * @return contains - Boolean */ public boolean contains(Drawable d) { if (getReld().getClassA().equals(d) || getReld().getClassB().equals(d)) { return true; } return false; } /** * Determines what relationship type has been selected, and draws the relationship diagram between the two classes, using data * retrieved from {@link uk.ac.aber.dcs.cs124.clg11.data.RelationshipDiagData}) * * Includes automatic line drawing algorithm that allows relationship diagram to be automatically redrawn * depending on the positions of the two related classes at any given time. * * @see uk.ac.aber.dcs.cs124.clg11.diag.Drawable#paint(java.awt.Graphics) */ @Override public void paint(Graphics g) { /** * x1 - X position coordinate of first class * x2 - X position coordinate of second class * y1 - Y position coordinate of first class * y2 - Y position coordinate of second class * w1 - Width of first class * w2 - Width of second class * h1 - Height of first class * h2 - Height of second class * acx - Centre 'X' position of first class * bcx - Centre 'X' position of second class * acy - Centre 'Y' position of first class * bcy - Centre 'Y' position of second class */ int x1 = getReld().getClassA().getX(), y1 = getReld().getClassA().getY(), x2 = getReld().getClassB().getX(), y2 = getReld().getClassB().getY(); int w1 = getReld().getClassA().getWidth(), h1 = getReld().getClassA().getHeight(), w2 = getReld().getClassB().getWidth(), h2 = getReld().getClassB().getHeight(); //change 180 to getWidth int acx = x1+w1/2, acy = y1+h1/2, bcx = x2+w2/2, bcy = y2+h2/2; /* This algorithm is used to determine where the two classes that are linked by the particular relationship diagram * are positioned in relation to each other, using the X/Y and centre X/Y coordinates of both classes. It then draws lines between * them, in the shortest distance possible but ENSURES that NO LINES OVERLAP EITHER OF THE CLASSES and will * automatically re-draw the lines as the user moves the two classes around the CanvasPanel. */ if (Math.abs(acx-bcx) > Math.abs(acy-bcy)) { // Check if first class is above second class if (bcy < y1) { g.drawLine(acx, y1, acx, bcy); //Draw line from first class if(x2 > x1) { //Side 1 System.out.println("Side 1"); this.setDiamondX(x2 - 20); //Set the diamond X value to position any diamonds that will need to be drawn this.setDiamondY(bcy - 10); //Set the diamond Y value to position any diamonds that will need to be drawn setArrowDir("EAST"); //Set the arrow direction for inheritance if (getReld().getRelType().equals("ASSOCIATION")) { //Check the relationship type g.drawLine(acx, bcy, x2, bcy); /*If it is INHERITANCE, draw the line right up to the edge of the second class */ } else { g.drawLine(acx, bcy, x2 - 20, bcy); //Otherwise draw the line 20 pixels back to make room for the diamond, filled arrow } g.drawString(getReld().getClassBMulti(), x2 - 40, bcy + 15); //Draw second class multiplicity g.drawString(getReld().getClassAMulti(), acx + 10, y1 - 15); //Draw first class multiplicity g.drawString(getReld().getAssocVar(), acx + 10, y1 - 50); //Draw associated variable //This algorithm is repeated for ALL potential positions of the two classes... } else { //Side 2 this.setDiamondX(x2 + w2); this.setDiamondY(bcy - 10); setArrowDir("WEST"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(acx, bcy, x2 + w2, bcy); } else { g.drawLine(acx, bcy, x2 + w2 + 20, bcy); } g.drawString(getReld().getClassBMulti(), x2 + getReld().getClassB().getWidth() + 20, bcy + 20); g.drawString(getReld().getClassAMulti(), acx + 10, y1 - 15); g.drawString(getReld().getAssocVar(), acx + 10, y1 - 55); } } else if (bcy > y1 && bcy < y1 + h1) { if(x2 > x1) { //Side 3 this.setDiamondX(x2 - 20); //2nd class left this.setDiamondY(bcy - 10); setArrowDir("EAST"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(x1 + w1, bcy, x2, bcy); } else { g.drawLine(x1 + w1, bcy, x2 - 20, bcy); } g.drawString(getReld().getClassBMulti(), x2 - 40, bcy + 15); g.drawString(getReld().getClassAMulti(), x1 + getReld().getClassA().getWidth() + 10, bcy + 15); g.drawString(getReld().getAssocVar(), x1 + getReld().getClassA().getWidth() + 10, bcy + 35); } else { //Side 4 this.setDiamondX(x2 + w2); this.setDiamondY(bcy - 10); setArrowDir("WEST"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(x1, bcy, x2 + w2, bcy); } else { g.drawLine(x1, bcy, x2 + w2 + 20, bcy); } g.drawString(getReld().getClassBMulti(), x2 + getReld().getClassB().getWidth() + 30, bcy + 20); g.drawString(getReld().getClassAMulti(), x1 - 30, bcy + 20); g.drawString(getReld().getAssocVar(), x1 - 200, bcy - 20); } } else if (bcy > y1 + h1) { g.drawLine(acx, y1 + h1, acx, bcy); if(x2 > x1) { //Side 5 this.setDiamondX(x2 - 20); this.setDiamondY(bcy - 10); setArrowDir("EAST"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(acx, bcy, x2, bcy); } else { g.drawLine(acx, bcy, x2 - 20, bcy); } g.drawString(getReld().getClassBMulti(), x2 - 40, bcy + 15); g.drawString(getReld().getClassAMulti(), acx + 10, y1 + getReld().getClassA().getHeight() + 20); g.drawString(getReld().getAssocVar(), acx + 10, y1 + getReld().getClassA().getHeight() + 60); } else { //Side 6 this.setDiamondX(x2 + w2); this.setDiamondY(bcy - 10); setArrowDir("WEST"); System.out.println("Side 6"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(acx, bcy, x2 + w2, bcy); } else { g.drawLine(acx, bcy, x2 + w2 + 20, bcy); } g.drawString(getReld().getClassBMulti(), x2 + getReld().getClassB().getWidth() + 30, bcy + 20); g.drawString(getReld().getClassAMulti(), acx + 10 ,y1 + getReld().getClassA().getHeight() + 20); g.drawString(getReld().getAssocVar(), acx + 10, y1 + getReld().getClassA().getHeight() + 60); } } } else { if (bcx < x1) { g.drawLine(x1, acy, bcx, acy); if(y2 > y1) { //Side 7 this.setDiamondX(bcx - 10); this.setDiamondY(y2 - 20); setArrowDir("SOUTH"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(bcx, acy, bcx, y2); } else { g.drawLine(bcx, acy, bcx, y2 - 20); } g.drawString(getReld().getClassBMulti(), bcx + 10, y2 - 30); g.drawString(getReld().getClassAMulti(), x1 - 20, acy + 20); g.drawString(getReld().getAssocVar(), x1 - 30 , y1 + getReld().getClassA().getHeight() + 20); } else { //Side 8 this.setDiamondX(bcx - 10); this.setDiamondY(y2 + h2); setArrowDir("NORTH"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(bcx, acy, bcx, y2 + h2); } else { g.drawLine(bcx, acy, bcx, y2 + h2 + 20); } g.drawString(getReld().getClassBMulti(), bcx + 10, y2 + getReld().getClassB().getHeight() + 30); g.drawString(getReld().getClassAMulti(), x1 - 30, acy - 10); g.drawString(getReld().getAssocVar(), bcx + 10, y2 + getReld().getClassB().getHeight() + 80); } } else if (bcx > x1 && bcx < x1 + w1) { if(y2 > y1) { //Side 9 this.setDiamondX(bcx - 10); this.setDiamondY(y2 - 20); setArrowDir("SOUTH"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(bcx, y1 + h1, bcx, y2); } else { g.drawLine(bcx, y1 + h1, bcx, y2 - 20); } g.drawString(getReld().getClassBMulti(), bcx + 10, y2 - 20); g.drawString(getReld().getClassAMulti(), bcx + 10, y1 + getReld().getClassA().getHeight() + 20); g.drawString(getReld().getAssocVar(), bcx + 10, y1 + getReld().getClassA().getHeight() + 60); } else { //Side 10 this.setDiamondX(bcx - 10); this.setDiamondY(y2 + h2); setArrowDir("NORTH"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(bcx, y1, bcx, y2 + h2); } else { g.drawLine(bcx, y1, bcx, y2 + h2 + 20); } g.drawString(getReld().getClassBMulti(), bcx + 10, y2 + getReld().getClassB().getHeight() + 30); g.drawString(getReld().getClassAMulti(), acx + 10, y1 - 10); g.drawString(getReld().getAssocVar(), bcx + 10, y2 + getReld().getClassB().getHeight() + 80); } } else if (bcx > x1 + w1) { g.drawLine(x1+ w1, acy, bcx, acy); if(y2 > y1) { //Side 11 this.setDiamondX(bcx - 10); this.setDiamondY(y2 - 20); setArrowDir("SOUTH"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(bcx, acy, bcx, y2); } else { g.drawLine(bcx, acy, bcx, y2 - 20); } g.drawString(getReld().getClassBMulti(), bcx + 10, y2 - 25); g.drawString(getReld().getClassAMulti(), x1 + getReld().getClassA().getWidth() + 10, acy - 10); g.drawString(getReld().getAssocVar(), x1 + getReld().getClassA().getWidth() + 30, y1 + 140); } else { //Side 12 this.setDiamondX(bcx - 10); this.setDiamondY(y2 + h2); setArrowDir("NORTH"); if (getReld().getRelType().equals("ASSOCIATION")) { g.drawLine(bcx, acy, bcx, y2 + h2); } else { g.drawLine(bcx, acy, bcx, y2 + h2 + 20); } g.drawString(getReld().getClassBMulti(), bcx + 10, y2 + getReld().getClassB().getHeight() + 30); g.drawString(getReld().getClassAMulti(), x1 + getReld().getClassA().getWidth() + 10, acy - 10); g.drawString(getReld().getAssocVar(), x1 + getReld().getClassA().getWidth() + 50, y1 + 20); } } } /** * x1 -'X' position of the left side of the diamond */ x1 = this.getDiamondX(); /** * x2 -'X' position of the right side of the diamond */ x2 = this.getDiamondX() + 20; /** * y1 -'Y' position of the top side of the diamond */ y1 = this.getDiamondY(); /** * y2 -'Y' position of the bottom side of the diamond */ y2 = this.getDiamondY() + 20; /** * startx - Start centre position of diamond on X axis */ int startx = (x1+x2)/2; /** * starty - Start centre position of diamond on Y axis */ int starty = (y1+y2)/2; if (getReld().getRelType().equals("AGGREGATION")) { //Determine relationship type //Draw un-filled diamond at end of line (edge of class 2) g.drawLine(x1, starty , startx , y1); g.drawLine(startx , y1, x2, starty ); g.drawLine(x2, starty , startx , y2); g.drawLine(startx , y2, x1, starty ); } else if (getReld().getRelType().equals("ASSOCIATION")) { if (getArrowDir().equals("NORTH")) { //Draw arrow point facing required direction g.drawLine(startx , y1, x2, starty ); g.drawLine(x1, starty , startx , y1); } else if (getArrowDir().equals("SOUTH")) { g.drawLine(x2, starty , startx , y2); g.drawLine(startx , y2, x1, starty ); } else if (getArrowDir().equals("EAST")) { g.drawLine(startx , y1, x2, starty ); g.drawLine(x2, starty , startx , y2); } else if (getArrowDir().equals("WEST")) { g.drawLine(x1, starty , startx , y1); g.drawLine(startx , y2, x1, starty ); } } else if (getReld().getRelType().equals("COMPOSITION")) { //Draw filled diamond at end of line (edge of class 2) int [] xpoints = { x1, startx, x2, startx, x1 }; int [] ypoints = { starty, y1, starty, y2, starty }; g.fillPolygon(xpoints, ypoints, xpoints.length); } else if (getReld().getRelType().equals("INHERITANCE")) { if (getArrowDir().equals("NORTH")) { //Draw closed arrow point facing required direction g.drawLine(startx , y1, x2, starty ); g.drawLine(x1, starty , startx , y1); g.drawLine(x1,starty, x2, starty); g.drawLine(startx,starty, startx, y2); } else if (getArrowDir().equals("SOUTH")) { g.drawLine(x2, starty , startx , y2); g.drawLine(startx , y2, x1, starty ); g.drawLine(x1,starty, x2, starty); g.drawLine(startx,starty, startx, y1); } else if (getArrowDir().equals("EAST")) { g.drawLine(startx , y1, x2, starty ); g.drawLine(x2, starty , startx , y2); g.drawLine(startx,y1, startx, y2); g.drawLine(startx,starty, x1, starty); } else if (getArrowDir().equals("WEST")) { g.drawLine(x1, starty , startx , y1); g.drawLine(startx , y2, x1, starty ); g.drawLine(startx,y1, startx, y2); g.drawLine(startx,starty, x2, starty); } } } /** * @return diamondX - 'X' position of the left side of the diamond */ public int getDiamondX() { return diamondX; } /** * @param diamondX - 'X' position of the left side of the diamond to be set */ public void setDiamondX(int diamondX) { this.diamondX = diamondX; } /** * @return diamondY - 'Y' position of the top side of the diamond */ public int getDiamondY() { return diamondY; } /** * @param diamondY - 'Y' position of the top side of the diamond to be set */ public void setDiamondY(int diamondY) { this.diamondY = diamondY; } /** * @return arrowDir - The direction that the arrow (for Inheritance) is facing */ public String getArrowDir() { return arrowDir; } /** * @param arrowDir - The direction that the arrow (for Inheritance) is facing to be set */ public void setArrowDir(String arrowDir) { this.arrowDir = arrowDir; } /** * @return the reld */ public RelationshipDiagData getReld() { return reld; } /** * @param reld the reld to set */ public void setReld(RelationshipDiagData reld) { this.reld = reld; } }
29.620112
188
0.624733
5797f15a48fb2174508a0c2c349342bade9e786e
1,629
package com.zhihuianxin.xyaxf.app.unionqr_pay.contract; import modellib.thrift.fee.PaymentRecord; import modellib.thrift.payment.PaymentOrder; import modellib.thrift.unqr.PaymentConfig; import modellib.thrift.unqr.RealName; import modellib.thrift.unqr.UPBankCard; import com.xyaxf.axpay.modle.PayRequest; import com.zhihuianxin.xyaxf.app.BaseView; import io.realm.RealmList; /** * Created by Vincent on 2017/12/4. */ public interface IunionSweptContract { interface IunionSweptView extends BaseView<IunionSweptPresenter>{ void getBankCardResult(RealmList<UPBankCard> bankCards); void JudgePayPwdResult(PaymentConfig config); void getC2BCodeResult(String qr_code); void swepPayPwdResult(); void verifyPayPwdResult(boolean is_match, int left_retry_count); void payOrderResult(PaymentOrder order); void setPayList(RealmList<PaymentRecord> payList); void getRealNameResult(RealName realName); void c2bQrVerifyPpaymentPasswordResult(boolean is_match, int left_retry_count); } interface IunionSweptPresenter{ void getBankCard(); void JudgePayPwd(); void getC2BCode(String bank_card_id); void swepPayPwd(String qr_code, String amount, String payment_password); void verifyPayPwd(String pay_password);// 验证支付密码 void payOrder(PayRequest payRequest);// 下单 void loadPayList(String start_date, String end_date, String page_index, String page_size); void getRealName();// 获取实名认证状态 void c2bQrVerifyPpaymentPassword(String qr_code, String amount, String payment_password); } }
38.785714
98
0.750767
6191a312992f7ac52304cc7a3fb782b00583d6bd
4,892
/* * $RCSfile: PackageUtil.java,v $ * * * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for * use in the design, construction, operation or maintenance of any * nuclear facility. * * $Revision: 1.3 $ * $Date: 2006-03-31 19:43:38 $ * $State: Exp $ */ package com.sun.media.imageioimpl.common; import java.security.AccessController; import java.security.PrivilegedAction; import com.sun.medialib.codec.jiio.Util; public class PackageUtil { /** * Flag indicating whether codecLib is available. */ private static boolean isCodecLibAvailable = false; /** * Implementation version derived from Manifest. */ private static String version = "1.0"; /** * Implementation vendor derived from Manifest. */ private static String vendor = "Sun Microsystems, Inc."; /** * Specification Title derived from Manifest. */ private static String specTitle = "Java Advanced Imaging Image I/O Tools"; /** * Set static flags. */ static { // Set codecLib flag. try { // Check for codecLib availability. isCodecLibAvailable = Util.isCodecLibAvailable(); } catch(Throwable e) { // A Throwable is equivalent to unavailable. Throwable is used // in case an Error rather than an Exception is thrown. isCodecLibAvailable = false; } Package thisPackage = com.sun.media.imageioimpl.common.PackageUtil.class.getPackage(); version = thisPackage.getImplementationVersion(); vendor = thisPackage.getImplementationVendor(); specTitle = thisPackage.getSpecificationTitle(); } /** * Returns a <code>boolean</code> indicating whether codecLib is available. */ public static final boolean isCodecLibAvailable() { // Retrieve value of system property here to allow this to be // modified dynamically. Boolean result = (Boolean) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { String property = null; try { property = System.getProperty("com.sun.media.imageio.disableCodecLib"); } catch(SecurityException se) { // Do nothing: leave 'property' null. } return (property != null && property.equalsIgnoreCase("true")) ? Boolean.TRUE : Boolean.FALSE; } }); boolean isCodecLibDisabled = result.booleanValue(); return isCodecLibAvailable && !isCodecLibDisabled; } /** * Return a version string for the package. */ public static final String getVersion() { return version; } /** * Return a vendor string for the package. */ public static final String getVendor() { return vendor; } /** * Return the Specification Title string for the package. */ public static final String getSpecificationTitle() { return specTitle; } }
35.194245
94
0.642069
b51271b7d7cf57e12e3dc9aa4601175fd7c28be6
4,009
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.cdi.tck.tests.full.extensions.interceptionFactory; import static org.jboss.cdi.tck.TestGroups.CDI_FULL; import static org.jboss.cdi.tck.cdi.Sections.BINDING_INTERCEPTOR_TO_BEAN; import static org.jboss.cdi.tck.cdi.Sections.INTERCEPTION_FACTORY; import java.util.stream.Collectors; import java.util.stream.Stream; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.inject.Any; import jakarta.enterprise.inject.Default; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.InterceptionFactory; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.cdi.tck.AbstractTest; import org.jboss.cdi.tck.shrinkwrap.WebArchiveBuilder; import org.jboss.cdi.tck.util.ActionSequence; import org.jboss.shrinkwrap.api.BeanDiscoveryMode; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.BeansXml; import org.jboss.test.audit.annotations.SpecAssertion; import org.jboss.test.audit.annotations.SpecAssertions; import org.jboss.test.audit.annotations.SpecVersion; import org.testng.Assert; import org.testng.annotations.Test; /** * @author Tomas Remes */ @SpecVersion(spec = "cdi", version = "2.0") @Test(groups = CDI_FULL) public class InterceptionFactoryTest extends AbstractTest { @Deployment public static WebArchive createTestArchive() { return new WebArchiveBuilder() .withTestClassPackage(InterceptionFactoryTest.class) .withBeansXml(new BeansXml(BeanDiscoveryMode.ALL)) .build(); } @Inject @Custom FinalProduct finalProduct; @Inject Product product; @Test @SpecAssertions({ @SpecAssertion(section = BINDING_INTERCEPTOR_TO_BEAN, id = "c"), @SpecAssertion(section = INTERCEPTION_FACTORY, id = "b"), @SpecAssertion(section = INTERCEPTION_FACTORY, id = "ca") }) public void producedInstanceIsIntercepted() { ActionSequence.reset(); Assert.assertEquals(product.ping(), 4); ActionSequence.assertSequenceDataEquals(ProductInterceptor1.class, ProductInterceptor2.class, ProductInterceptor3.class); } @Test @SpecAssertion(section = INTERCEPTION_FACTORY, id = "g") public void interceptionFactoryBeanIsAvailable() { Bean<?> interceptionFactoryBean = getCurrentManager().resolve(getCurrentManager().getBeans(InterceptionFactory.class)); Assert.assertEquals(Dependent.class, interceptionFactoryBean.getScope()); Assert.assertEquals(Stream.of(Default.Literal.INSTANCE, Any.Literal.INSTANCE).collect(Collectors.toSet()), interceptionFactoryBean.getQualifiers()); } @Test @SpecAssertions({ @SpecAssertion(section = BINDING_INTERCEPTOR_TO_BEAN, id = "c"), @SpecAssertion(section = INTERCEPTION_FACTORY, id = "a"), @SpecAssertion(section = INTERCEPTION_FACTORY, id = "b"), @SpecAssertion(section = INTERCEPTION_FACTORY, id = "ca") }) public void producedWithFinalMethodIsIntercepted() { ActionSequence.reset(); Assert.assertEquals(finalProduct.ping(), 3); ActionSequence.assertSequenceDataEquals(ProductInterceptor1.class, ProductInterceptor2.class); } }
41.760417
156
0.753056
28302ef4d1ac00ad548249be220ddde5a51620e3
2,338
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.CliSyntax.PREFIX_PHONE; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import java.util.Set; import java.util.stream.Stream; import seedu.address.logic.commands.AddBuyerCommand; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.buyer.Buyer; import seedu.address.model.client.Appointment; import seedu.address.model.client.Name; import seedu.address.model.client.Phone; import seedu.address.model.property.NullPropertyToBuy; import seedu.address.model.property.PropertyToBuy; import seedu.address.model.tag.Tag; public class AddBuyerCommandParser implements Parser<AddBuyerCommand> { /** * Parses the arguments of the command into the various attributes of a buyer. * * @param args The arguments to be parsed. * @return An AddBuyerCommand of the new Buyer to add. * @throws ParseException If there are problems with argument passed in. */ public AddBuyerCommand parse(String args) throws ParseException { ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_NAME, PREFIX_PHONE, PREFIX_TAG); if (!arePrefixesPresent(argMultimap, PREFIX_NAME, PREFIX_PHONE) || !argMultimap.getPreamble().isEmpty()) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddBuyerCommand.MESSAGE_USAGE)); } Name name = ParserUtil.parseName(argMultimap.getValue(PREFIX_NAME).get()); Phone phone = ParserUtil.parsePhone(argMultimap.getValue(PREFIX_PHONE).get()); Set<Tag> tagList = ParserUtil.parseTags(argMultimap.getAllValues(PREFIX_TAG)); Appointment appointment = new Appointment(""); PropertyToBuy desiredProperty = NullPropertyToBuy.getNullPropertyToBuy(); Buyer buyer = new Buyer(name, phone, appointment, tagList, desiredProperty); return new AddBuyerCommand(buyer); } private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent()); } }
44.961538
115
0.763045
996096d9307e75bd2ff995a39c5de9a6c72a6eb2
292
package com.example.queue; /** * Create in 2018/4/10 22:36. * * @author lhh. * <p>优先级</p> */ public enum Priority { /** * 优先级最低 */ A, /** * 默认优先级 */ B, /** * 优先级最高 */ C, /** * 一般情况下不用;特殊情况下,请求假如到到队列后立即执行 */ D }
9.733333
34
0.400685
15e16ac8b733546185fd91be56c3e3544ca9535e
1,700
/* * Copyright Siemens AG, 2014-2015. Part of the SW360 Portal Project. * * SPDX-License-Identifier: EPL-1.0 * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.sw360.datahandler.couchdb; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import static org.eclipse.sw360.datahandler.common.SW360Constants.KEY_ID; import static org.eclipse.sw360.datahandler.common.SW360Constants.KEY_REV; /** * Mixin class for Jackson serialization into CouchDB. Allows to use objects generated by Thrift directly into CouchDB * via Ektorp. * * @author cedric.bodet@tngtech.com */ @JsonPropertyOrder({KEY_ID, KEY_REV}) // Always put _id and _rev upfront. Not required, but serialized objects then look nicer. @JsonIgnoreProperties({"optionals", "_attachments"}) @SuppressWarnings("unused") public class DatabaseMixIn { @JsonProperty("issetBitfield") private byte __isset_bitfield = 0; /* * Definitions of the standard CouchDB fields */ @JsonProperty(KEY_ID) public String getId() { return null; } @JsonProperty(KEY_ID) public void setId(String id) { // No implementation necessary } @JsonProperty(KEY_REV) public String getRevision() { return null; } @JsonProperty(KEY_REV) public void setRevision(String revision) { // No implementation necessary } }
28.333333
118
0.733529
6531bddad05c5d811325c50252147eb5a7029b4a
441
package br.com.basis.madre.prescricao.repository.search; import br.com.basis.madre.prescricao.domain.ItemPrescricaoProcedimento; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Spring Data Elasticsearch repository for the {@link ItemPrescricaoProcedimento} entity. */ public interface ItemPrescricaoProcedimentoSearchRepository extends ElasticsearchRepository<ItemPrescricaoProcedimento, Long> { }
44.1
127
0.854875
1b7e1acac941907c01162c43792d21dec13863ad
2,727
package com.tw.go.task.dockerpipeline; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.plugin.api.task.JobConsoleLogger; import com.tw.go.plugin.common.AbstractCommand; import com.tw.go.plugin.common.ConfigVars; import com.tw.go.plugin.common.ListUtil; import java.util.ArrayList; public class DockerCreateCommand extends DockerCommand { private final Logger logger = Logger.getLoggerFor(DockerCreateCommand.class); protected String _containerName = null; public DockerCreateCommand(JobConsoleLogger console, ConfigVars configVars) throws Exception { super(console, configVars); add("docker"); add("create"); add("--name"); this._containerName = createRandomContainerName(); add(this._containerName); /* String id = getContainerID(console, configVars); String workingDir = getAbsoluteWorkingDir(); if (id != null) { logger.info(String.format("Running inside container '%s'. Using '--volume-from' with working directory set to '%s'", id, workingDir)); // todo: check, if the container provides access to the actual pipeline directory // e.g. "/var/lib/go-agent" .. add("--volumes-from"); add(id); } else { logger.info(String.format("(Most likely) NOT running in container. Using '--volume' with working directory set to '%s'", workingDir)); add("--volume"); add(workingDir + ":" + workingDir); } add("--workdir"); add(workingDir); */ addRunEnvVars(configVars.getValue(DockerTask.RUN_ENV_VARS)); add(configVars.getValue(DockerTask.RUN_IMAGE)); for (String arg : splitArgs(configVars.getValue(DockerTask.RUN_ARGS))) { add(arg); } } protected String createRandomContainerName() { String randomId = Long.toHexString(Double.doubleToLongBits(Math.random())); return String.format("tmp_%s", randomId); } protected String getContainerName() { return this._containerName; } protected void addRunEnvVars(String envVars) { for (String envVar : ListUtil.splitByFirstOrDefault(envVars, ';')) { if (!envVar.isEmpty()) { command.add("-e"); command.add(envVar); } } } protected String getContainerID(JobConsoleLogger console, ConfigVars configVars) throws Exception { AbstractCommand cmd = new DockerContainerIdCommand(console, configVars) .disableConsoleOutput(); cmd.run(); return DockerContainerIdCommand.extractId(cmd.getProcessOutput()); } }
36.36
146
0.642098
10befdb078c82addbdf213b2389f77b009c97c6f
1,453
package net.runelite.mixins; import net.runelite.api.FriendsChatMember; import net.runelite.api.FriendsChatRank; import net.runelite.api.events.FriendsChatMemberJoined; import net.runelite.api.events.FriendsChatMemberLeft; import net.runelite.api.mixins.Inject; import net.runelite.api.mixins.Mixin; import net.runelite.api.mixins.Shadow; import net.runelite.rs.api.RSFriendsChat; import net.runelite.rs.api.RSClient; import net.runelite.rs.api.RSUser; import net.runelite.rs.api.RSUsername; @Mixin(RSFriendsChat.class) public abstract class RSFriendsChatMixin implements RSFriendsChat { @Shadow("client") private static RSClient client; @Inject @Override public void rl$add(RSUsername name, RSUsername prevName) { FriendsChatMember member = findByName(name); if (member == null) { return; } FriendsChatMemberJoined event = new FriendsChatMemberJoined(member); client.getCallbacks().postDeferred(event); } @Inject @Override public void rl$remove(RSUser nameable) { FriendsChatMember member = findByName(nameable.getRsName()); if (member == null) { return; } FriendsChatMemberLeft event = new FriendsChatMemberLeft(member); client.getCallbacks().postDeferred(event); } @Inject @Override public FriendsChatRank getMyRank() { return FriendsChatRank.valueOf(this.getRank()); } @Inject @Override public FriendsChatRank getKickRank() { return FriendsChatRank.valueOf(this.getMinKickRank()); } }
23.063492
70
0.77426
1b2d13f1e7a9c718f7dbbe002894fbe49f641950
463
class Solution { public int XXX(String s) { //字符取值范围是-128-127 int [] num = new int[256]; char [] str = s.toCharArray(); int res = 0; //双指针 for(int i = 0 , j = 0 ;i < str.length; i++){ num[str[i]+128]++; while(num[str[i]+128]>1){ num[str[j]+128]--; j++; } res = Integer.max(res, i-j+1); } return res; } }
24.368421
52
0.37797
0365f8ad0e9d411e854993d7401a74826f528dec
31,408
/** * Copyright (c) 2018 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uber.rxcentralble.core; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.content.Context; import android.os.Build; import com.uber.rxcentralble.ConnectionError; import com.uber.rxcentralble.PeripheralError; import com.uber.rxcentralble.Peripheral; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.util.ReflectionHelpers; import java.util.UUID; import io.reactivex.observers.TestObserver; import static android.bluetooth.BluetoothGattCharacteristic.PROPERTY_NOTIFY; import static android.bluetooth.BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE; import static com.uber.rxcentralble.ConnectionError.Code.CONNECT_FAILED; import static com.uber.rxcentralble.ConnectionError.Code.DISCONNECTION; import static com.uber.rxcentralble.PeripheralError.Code.CHARACTERISTIC_SET_VALUE_FAILED; import static com.uber.rxcentralble.PeripheralError.Code.DISCONNECTED; import static com.uber.rxcentralble.PeripheralError.Code.MISSING_CHARACTERISTIC; import static com.uber.rxcentralble.PeripheralError.Code.OPERATION_IN_PROGRESS; import static com.uber.rxcentralble.PeripheralError.Code.READ_CHARACTERISTIC_FAILED; import static com.uber.rxcentralble.PeripheralError.Code.READ_RSSI_FAILED; import static com.uber.rxcentralble.PeripheralError.Code.REGISTER_NOTIFICATION_FAILED; import static com.uber.rxcentralble.PeripheralError.Code.SERVICE_DISCOVERY_FAILED; import static com.uber.rxcentralble.PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_CCCD_MISSING; import static com.uber.rxcentralble.PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_MISSING_PROPERTY; import static com.uber.rxcentralble.PeripheralError.Code.REQUEST_MTU_FAILED; import static com.uber.rxcentralble.PeripheralError.Code.UNREGISTER_NOTIFICATION_FAILED; import static com.uber.rxcentralble.PeripheralError.Code.WRITE_CHARACTERISTIC_FAILED; import static com.uber.rxcentralble.PeripheralError.Code.WRITE_DESCRIPTOR_FAILED; import static com.uber.rxcentralble.PeripheralError.ERROR_STATUS_CALL_FAILED; import static com.uber.rxcentralble.Peripheral.ConnectableState.CONNECTED; import static com.uber.rxcentralble.Peripheral.ConnectableState.CONNECTING; import static com.uber.rxcentralble.Peripheral.MTU_OVERHEAD; import static com.uber.rxcentralble.core.CorePeripheral.CCCD_UUID; import static com.uber.rxcentralble.core.CorePeripheral.DEFAULT_MTU; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @RunWith(RobolectricTestRunner.class) public class CorePeripheralTest { @Mock BluetoothDevice bluetoothDevice; @Mock Context context; @Mock BluetoothGatt bluetoothGatt; @Mock BluetoothGattService bluetoothGattService; @Mock BluetoothGattCharacteristic bluetoothGattCharacteristic; @Mock BluetoothGattDescriptor bluetoothGattDescriptor; private final UUID svcUuid = UUID.randomUUID(); private final UUID chrUuid = UUID.randomUUID(); private CorePeripheral corePeripheral; private BluetoothGattCallback bluetoothGattCallback; private TestObserver<Peripheral.ConnectableState> connectTestObserver; private TestObserver<byte[]> readTestObserver; private TestObserver<Void> writeTestObserver; private TestObserver<Void> registerNotificationTestObserver; private TestObserver<byte[]> notificationTestObserver; private TestObserver<Integer> setMtuTestObserver; private TestObserver<Integer> readRssiTestObserver; @Before public void setup() { MockitoAnnotations.initMocks(this); ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 21); corePeripheral = new CorePeripheral(bluetoothDevice, context); } @Test public void connect_connectGattFailed() { when(bluetoothDevice.connectGatt(any(), anyBoolean(), any())).thenReturn(null); connectTestObserver = corePeripheral.connect().test(); connectTestObserver.assertError( throwable -> { ConnectionError error = (ConnectionError) throwable; if (error != null && error.getCode() == CONNECT_FAILED && error.getCause() != null && error.getCause() instanceof PeripheralError) { PeripheralError peripheralError = (PeripheralError) error.getCause(); return peripheralError.getErrorStatus() == ERROR_STATUS_CALL_FAILED; } return false; }); } @Test public void connect_gattCallback_nonZeroStatus() { prepareConnect(false); bluetoothGattCallback.onConnectionStateChange(bluetoothGatt, 99, BluetoothGatt.STATE_CONNECTED); connectTestObserver.assertError( throwable -> { ConnectionError error = (ConnectionError) throwable; if (error != null && error.getCode() == CONNECT_FAILED && error.getCause() != null && error.getCause() instanceof PeripheralError) { PeripheralError peripheralError = (PeripheralError) error.getCause(); return peripheralError.getErrorStatus() == 99; } return false; }); verify(bluetoothGatt).disconnect(); } @Test public void connect_serviceDiscoveryGattFailed() { prepareConnect(false); bluetoothGattCallback.onConnectionStateChange(bluetoothGatt, 0, BluetoothGatt.STATE_CONNECTED); connectTestObserver.assertError( throwable -> { ConnectionError error = (ConnectionError) throwable; if (error != null && error.getCode() == CONNECT_FAILED && error.getCause() != null && error.getCause() instanceof PeripheralError) { PeripheralError peripheralError = (PeripheralError) error.getCause(); return peripheralError.getCode() == SERVICE_DISCOVERY_FAILED && peripheralError.getErrorStatus() == ERROR_STATUS_CALL_FAILED; } return false; }); verify(bluetoothGatt).disconnect(); } @Test public void connect_serviceDiscovery_gattCallback_nonZeroStatus() { prepareConnect(true); bluetoothGattCallback.onConnectionStateChange(bluetoothGatt, 0, BluetoothGatt.STATE_CONNECTED); verify(bluetoothGatt).discoverServices(); bluetoothGattCallback.onServicesDiscovered(bluetoothGatt, 99); connectTestObserver.assertError( throwable -> { ConnectionError error = (ConnectionError) throwable; if (error != null && error.getCode() == CONNECT_FAILED && error.getCause() != null && error.getCause() instanceof PeripheralError) { PeripheralError peripheralError = (PeripheralError) error.getCause(); return peripheralError.getCode() == SERVICE_DISCOVERY_FAILED && peripheralError.getErrorStatus() == 99; } return false; }); verify(bluetoothGatt).disconnect(); } @Test public void connect_success() { connect(); connectTestObserver.assertValues(CONNECTING, CONNECTED); } @Test public void connect_verifyMulticasted() { connect(); corePeripheral.connect().test(); verifyNoMoreInteractions(bluetoothGatt); } @Test public void read_disconnected() { readTestObserver = corePeripheral.read(svcUuid, chrUuid).test(); readTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == DISCONNECTED; }); } @Test public void read_characteristicMissing() { connect(); readTestObserver = corePeripheral.read(svcUuid, chrUuid).test(); readTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == MISSING_CHARACTERISTIC; }); } @Test public void read_gattReadFailed() { connect(); prepareRead(false); readTestObserver = corePeripheral.read(svcUuid, chrUuid).test(); readTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == READ_CHARACTERISTIC_FAILED && error.getErrorStatus() == ERROR_STATUS_CALL_FAILED; }); } @Test public void read_gattCallback_nonZeroStatus() { connect(); prepareRead(true); readTestObserver = corePeripheral.read(svcUuid, chrUuid).test(); bluetoothGattCallback.onCharacteristicRead(bluetoothGatt, bluetoothGattCharacteristic, 99); readTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == READ_CHARACTERISTIC_FAILED && error.getErrorStatus() == 99; }); } @Test public void read_success() { connect(); prepareRead(true); byte[] readBytes = new byte[] {0x00}; when(bluetoothGattCharacteristic.getValue()).thenReturn(readBytes); readTestObserver = corePeripheral.read(svcUuid, chrUuid).test(); bluetoothGattCallback.onCharacteristicRead(bluetoothGatt, bluetoothGattCharacteristic, 0); readTestObserver.assertValue(readBytes); } @Test public void read_operationInProgress() { connect(); prepareRead(true); corePeripheral.read(svcUuid, chrUuid).test(); readTestObserver = corePeripheral.read(svcUuid, chrUuid).test(); readTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == OPERATION_IN_PROGRESS; }); } @Test public void write_disconnected() { byte[] writeBytes = new byte[] {0x00}; writeTestObserver = corePeripheral.write(svcUuid, chrUuid, writeBytes).test(); writeTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == DISCONNECTED; }); } @Test public void write_characteristicMissing() { connect(); byte[] writeBytes = new byte[] {0x00}; writeTestObserver = corePeripheral.write(svcUuid, chrUuid, writeBytes).test(); writeTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == MISSING_CHARACTERISTIC; }); } @Test public void write_setValueFailed() { connect(); prepareWrite(false, false); byte[] writeBytes = new byte[] {0x00}; writeTestObserver = corePeripheral.write(svcUuid, chrUuid, writeBytes).test(); writeTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == CHARACTERISTIC_SET_VALUE_FAILED; }); } @Test public void write_gattWriteFailed() { connect(); prepareWrite(true, false); byte[] writeBytes = new byte[] {0x00}; writeTestObserver = corePeripheral.write(svcUuid, chrUuid, writeBytes).test(); writeTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == WRITE_CHARACTERISTIC_FAILED && error.getErrorStatus() == ERROR_STATUS_CALL_FAILED; }); } @Test public void write_gattCallback_nonZeroStatus() { connect(); prepareWrite(true, true); byte[] writeBytes = new byte[] {0x00}; writeTestObserver = corePeripheral.write(svcUuid, chrUuid, writeBytes).test(); bluetoothGattCallback.onCharacteristicWrite(bluetoothGatt, bluetoothGattCharacteristic, 99); writeTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == WRITE_CHARACTERISTIC_FAILED && error.getErrorStatus() == 99; }); } @Test public void write_success() { connect(); prepareWrite(true, true); byte[] writeBytes = new byte[] {0x00}; writeTestObserver = corePeripheral.write(svcUuid, chrUuid, writeBytes).test(); bluetoothGattCallback.onCharacteristicWrite(bluetoothGatt, bluetoothGattCharacteristic, 0); writeTestObserver.assertComplete(); } @Test public void write_operationInProgress() { connect(); prepareWrite(true, true); byte[] writeBytes = new byte[] {0x00}; corePeripheral.write(svcUuid, chrUuid, writeBytes).test(); writeTestObserver = corePeripheral.write(svcUuid, chrUuid, writeBytes).test(); writeTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == OPERATION_IN_PROGRESS; }); } @Test public void registerNotification_disconnected() { registerNotificationTestObserver = corePeripheral.registerNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == DISCONNECTED; }); } @Test public void registerNotification_operationInProgress() { connect(); prepareNotifications(true, true, true, true, true); corePeripheral.registerNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver = corePeripheral.registerNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == OPERATION_IN_PROGRESS; }); } @Test public void registerNotification_characteristicMissing() { connect(); registerNotificationTestObserver = corePeripheral.registerNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == MISSING_CHARACTERISTIC; }); } @Test public void registerNotification_characteristic_missingNotificationProperty() { connect(); prepareNotifications(false, true, false, true, false); registerNotificationTestObserver = corePeripheral.registerNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; if (error != null && error.getCode() == REGISTER_NOTIFICATION_FAILED && error.getCause() != null && error.getCause() instanceof PeripheralError) { PeripheralError peripheralError = (PeripheralError) error.getCause(); return peripheralError.getCode() == SET_CHARACTERISTIC_NOTIFICATION_MISSING_PROPERTY; } return false; }); } @Test public void registerNotification_descriptor_missing() { connect(); prepareNotifications(true, false, false, false, false); registerNotificationTestObserver = corePeripheral.registerNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; if (error != null && error.getCode() == REGISTER_NOTIFICATION_FAILED && error.getCause() != null && error.getCause() instanceof PeripheralError) { PeripheralError peripheralError = (PeripheralError) error.getCause(); return peripheralError.getCode() == SET_CHARACTERISTIC_NOTIFICATION_CCCD_MISSING; } return false; }); } @Test public void registerNotification_setValueFailed() { connect(); prepareNotifications(true, true, false, true, false); registerNotificationTestObserver = corePeripheral.registerNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; if (error != null && error.getCode() == REGISTER_NOTIFICATION_FAILED && error.getCause() != null && error.getCause() instanceof PeripheralError) { PeripheralError peripheralError = (PeripheralError) error.getCause(); return peripheralError.getCode() == CHARACTERISTIC_SET_VALUE_FAILED; } return false; }); } @Test public void registerNotification_descriptor_writeFailed() { connect(); prepareNotifications(true, true, true, true, false); registerNotificationTestObserver = corePeripheral.registerNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; if (error != null && error.getCode() == REGISTER_NOTIFICATION_FAILED && error.getCause() != null && error.getCause() instanceof PeripheralError) { PeripheralError peripheralError = (PeripheralError) error.getCause(); return peripheralError.getCode() == WRITE_DESCRIPTOR_FAILED; } return false; }); } @Test public void registerNotification_gattCallback_nonZeroStatus() { connect(); prepareNotifications(true, true, true, true, true); registerNotificationTestObserver = corePeripheral.registerNotification(svcUuid, chrUuid).test(); bluetoothGattCallback.onDescriptorWrite(bluetoothGatt, bluetoothGattDescriptor, 99); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == WRITE_DESCRIPTOR_FAILED && error.getErrorStatus() == 99; }); } @Test public void registerNotification_success() { connect(); prepareNotifications(true, true, true, true, true); registerNotificationTestObserver = corePeripheral.registerNotification(svcUuid, chrUuid).test(); bluetoothGattCallback.onDescriptorWrite(bluetoothGatt, bluetoothGattDescriptor, 0); registerNotificationTestObserver.assertComplete(); } @Test public void unregisterNotification_disconnected() { registerNotificationTestObserver = corePeripheral.unregisterNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == DISCONNECTED; }); } @Test public void unregisterNotification_operationInProgress() { connect(); prepareNotifications(true, true, true, true, true); corePeripheral.registerNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver = corePeripheral.unregisterNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == OPERATION_IN_PROGRESS; }); } @Test public void unregisterNotification_characteristicMissing() { connect(); registerNotificationTestObserver = corePeripheral.unregisterNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == MISSING_CHARACTERISTIC; }); } @Test public void unregisterNotification_descriptor_missing() { connect(); prepareNotifications(true, false, false, false, false); registerNotificationTestObserver = corePeripheral.unregisterNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; if (error != null && error.getCode() == UNREGISTER_NOTIFICATION_FAILED && error.getCause() != null && error.getCause() instanceof PeripheralError) { PeripheralError peripheralError = (PeripheralError) error.getCause(); return peripheralError.getCode() == SET_CHARACTERISTIC_NOTIFICATION_CCCD_MISSING; } return false; }); } @Test public void unregisterNotification_descriptor_writeFailed() { connect(); prepareNotifications(true, true, true, true, false); registerNotificationTestObserver = corePeripheral.unregisterNotification(svcUuid, chrUuid).test(); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; if (error != null && error.getCode() == UNREGISTER_NOTIFICATION_FAILED && error.getCause() != null && error.getCause() instanceof PeripheralError) { PeripheralError peripheralError = (PeripheralError) error.getCause(); return peripheralError.getCode() == WRITE_DESCRIPTOR_FAILED; } return false; }); } @Test public void unregisterNotification_gattCallback_nonZeroStatus() { connect(); prepareNotifications(true, true, true, true, true); registerNotificationTestObserver = corePeripheral.unregisterNotification(svcUuid, chrUuid).test(); bluetoothGattCallback.onDescriptorWrite(bluetoothGatt, bluetoothGattDescriptor, 99); registerNotificationTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == WRITE_DESCRIPTOR_FAILED && error.getErrorStatus() == 99; }); } @Test public void unregisterNotification_success() { connect(); prepareNotifications(true, true, true, true, true); registerNotificationTestObserver = corePeripheral.unregisterNotification(svcUuid, chrUuid).test(); bluetoothGattCallback.onDescriptorWrite(bluetoothGatt, bluetoothGattDescriptor, 0); registerNotificationTestObserver.assertComplete(); } @Test public void notifications() { connect(); prepareGatt(); byte[] notification = new byte[] {0x00}; when(bluetoothGattCharacteristic.getValue()).thenReturn(notification); notificationTestObserver = corePeripheral.notification(chrUuid).test(); bluetoothGattCallback.onCharacteristicChanged(bluetoothGatt, bluetoothGattCharacteristic); notificationTestObserver.assertValue(notification); } @Test public void setMtu_disconnected() { setMtuTestObserver = corePeripheral.requestMtu(100).test(); setMtuTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == DISCONNECTED; }); } @Test public void setMtu_operationInProgress() { connect(); when(bluetoothGatt.requestMtu(anyInt())).thenReturn(true); corePeripheral.requestMtu(100).test(); setMtuTestObserver = corePeripheral.requestMtu(100).test(); setMtuTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == OPERATION_IN_PROGRESS; }); } @Test public void setMtu_gattFailed() { connect(); when(bluetoothGatt.requestMtu(anyInt())).thenReturn(false); setMtuTestObserver = corePeripheral.requestMtu(100).test(); setMtuTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == REQUEST_MTU_FAILED && error.getErrorStatus() == ERROR_STATUS_CALL_FAILED; }); } @Test public void setMtu_gattCallback_nonZeroStatus() { connect(); when(bluetoothGatt.requestMtu(anyInt())).thenReturn(true); setMtuTestObserver = corePeripheral.requestMtu(100).test(); bluetoothGattCallback.onMtuChanged(bluetoothGatt, -1, 99); setMtuTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == REQUEST_MTU_FAILED && error.getErrorStatus() == 99; }); assertEquals(corePeripheral.getMaxWriteLength(), DEFAULT_MTU - MTU_OVERHEAD); } @Test public void setMtu_success() { connect(); when(bluetoothGatt.requestMtu(anyInt())).thenReturn(true); setMtuTestObserver = corePeripheral.requestMtu(100).test(); bluetoothGattCallback.onMtuChanged(bluetoothGatt, 100, 0); setMtuTestObserver.assertValue(100); assertEquals(corePeripheral.getMaxWriteLength(), 100 - MTU_OVERHEAD); } @Test public void readRssi_disconnected() { readRssiTestObserver = corePeripheral.readRssi().test(); readRssiTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == DISCONNECTED; }); } @Test public void readRssi_operationInProgress() { connect(); when(bluetoothGatt.readRemoteRssi()).thenReturn(true); corePeripheral.readRssi().test(); readRssiTestObserver = corePeripheral.readRssi().test(); readRssiTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == OPERATION_IN_PROGRESS; }); } @Test public void readRssi_gattFailed() { connect(); when(bluetoothGatt.readRemoteRssi()).thenReturn(false); readRssiTestObserver = corePeripheral.readRssi().test(); readRssiTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == READ_RSSI_FAILED && error.getErrorStatus() == ERROR_STATUS_CALL_FAILED; }); } @Test public void readRssi_gattCallback_nonZeroStatus() { connect(); when(bluetoothGatt.readRemoteRssi()).thenReturn(true); readRssiTestObserver = corePeripheral.readRssi().test(); bluetoothGattCallback.onReadRemoteRssi(bluetoothGatt, 0, 99); readRssiTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == READ_RSSI_FAILED && error.getErrorStatus() == 99; }); } @Test public void readRssi_success() { connect(); when(bluetoothGatt.readRemoteRssi()).thenReturn(true); readRssiTestObserver = corePeripheral.readRssi().test(); bluetoothGattCallback.onReadRemoteRssi(bluetoothGatt, 100, 0); readRssiTestObserver.assertValue(100); } @Test public void disconnect() { connect(); corePeripheral.disconnect(); connectTestObserver.assertError( throwable -> { ConnectionError error = (ConnectionError) throwable; return error != null && error.getCode() == DISCONNECTION; }); } private void prepareConnect(boolean discoverServiceSuccess) { when(bluetoothDevice.connectGatt(any(), anyBoolean(), any())).thenReturn(bluetoothGatt); when(bluetoothGatt.discoverServices()).thenReturn(discoverServiceSuccess); connectTestObserver = corePeripheral.connect().test(); ArgumentCaptor<BluetoothGattCallback> gattCaptor = ArgumentCaptor.forClass(BluetoothGattCallback.class); verify(bluetoothDevice).connectGatt(any(), anyBoolean(), gattCaptor.capture()); bluetoothGattCallback = gattCaptor.getValue(); } private void connect() { prepareConnect(true); bluetoothGattCallback.onConnectionStateChange(bluetoothGatt, 0, BluetoothGatt.STATE_CONNECTED); verify(bluetoothGatt).discoverServices(); bluetoothGattCallback.onServicesDiscovered(bluetoothGatt, 0); } private void prepareGatt() { when(bluetoothGattCharacteristic.getUuid()).thenReturn(chrUuid); when(bluetoothGatt.getService(any())).thenReturn(bluetoothGattService); when(bluetoothGattService.getCharacteristic(any())).thenReturn(bluetoothGattCharacteristic); } private void prepareRead(boolean gattReadSuccess) { prepareGatt(); when(bluetoothGatt.readCharacteristic(any())).thenReturn(gattReadSuccess); } private void prepareWrite(boolean setValueSuccess, boolean gattWriteSuccess) { prepareGatt(); when(bluetoothGattCharacteristic.getProperties()).thenReturn(PROPERTY_WRITE_NO_RESPONSE); when(bluetoothGattCharacteristic.setValue(any(byte[].class))).thenReturn(setValueSuccess); when(bluetoothGatt.writeCharacteristic(any())).thenReturn(gattWriteSuccess); } private void prepareNotifications( boolean descriptorNotificationsEnabled, boolean cccdPresent, boolean setValueSuccess, boolean setCharacteristicSuccess, boolean gattWriteDescriptorSuccess) { prepareGatt(); when(bluetoothGattDescriptor.setValue(any())).thenReturn(setValueSuccess); when(bluetoothGattDescriptor.getUuid()).thenReturn(CCCD_UUID); when(bluetoothGattDescriptor.getCharacteristic()).thenReturn(bluetoothGattCharacteristic); if (descriptorNotificationsEnabled) { when(bluetoothGattCharacteristic.getProperties()).thenReturn(PROPERTY_NOTIFY); } else { when(bluetoothGattCharacteristic.getProperties()).thenReturn(0x00); } if (cccdPresent) { when(bluetoothGattCharacteristic.getDescriptor(any())).thenReturn(bluetoothGattDescriptor); } when(bluetoothGatt.setCharacteristicNotification(any(), anyBoolean())) .thenReturn(setCharacteristicSuccess); when(bluetoothGatt.writeDescriptor(any())).thenReturn(gattWriteDescriptorSuccess); } }
33.200846
106
0.703611
f8996a3dc5ed9909f549bc0a5add8da0c63ea3d6
2,849
/* * Copyright (c) 2010, Soar Technology, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Soar Technology, Inc. nor the names of its contributors * may be used to endorse or promote products derived from this software * without the specific prior written permission of Soar Technology, Inc. * * THIS SOFTWARE IS PROVIDED BY SOAR TECHNOLOGY, INC. AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SOAR TECHNOLOGY, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Created on May 29, 2007 */ package com.soartech.simjr.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @author ray */ public class ProcessStreamConsumer extends Thread { private InputStream stream; private OutputStream redirect; public ProcessStreamConsumer(Process process, InputStream stream, OutputStream redirect) { super("Stream consumer thread for process " + process.toString()); this.stream = stream; this.redirect = redirect; start(); } public ProcessStreamConsumer(Process process, InputStream stream) { this(process, stream, null); } @Override public void run() { byte[] buffer = new byte[1024]; while(true) { try { int r = stream.read(buffer); if(r < 0) { return; } if(redirect != null) { redirect.write(buffer, 0, r); } } catch (IOException e) { return; } } } }
32.375
92
0.646894
4d8092ebcda577fa328b61da0ef187fea6719476
2,137
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.statistics.examples.distribution; import java.io.File; import picocli.CommandLine.Option; /** * Standard options for distribution commands. */ class DistributionOptions { /** The distribution function. */ protected DistributionFunction distributionFunction; /** The field delimiter. */ @Option(names = { "--delim" }, description = {"Output field delimiter (default: \\t)."}) protected String delim = "\t"; /** The output file. */ @Option(names = { "--out" }, paramLabel = "file", description = {"Output file (default: stdout)."}) protected File outputFile; /** The output file. */ @Option(names = { "--in" }, paramLabel = "file", description = {"Input file containing points to evaluate.", "Overrides configured ranges."}) protected File inputFile; /** Flag indicating if an exception should be suppressed during function evaluation. * Exceptions are thrown by the ICDF function when the input probability is not in * the interval {@code [0, 1]}. */ @Option(names = { "--no-ex", "--no-exception" }, description = {"Suppress function evaluation exceptions (returns NaN or integer min value)."}) protected boolean suppressException; }
38.854545
106
0.678053
3684b0f4333ba34fe57adb3977e936e1e01492a1
2,660
package com.umg.ventas.core.controller; import com.umg.ventas.core.bs.dao.DireccionClienteRepository; import com.umg.ventas.core.ies.bo.DireccionCliente; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value = "/api/v1/direccion-cliente",produces = MediaType.APPLICATION_JSON_VALUE) public class DireccionClienteController { @Autowired private DireccionClienteRepository direccionClienteRepository; @RequestMapping(method = RequestMethod.GET) public Iterable<DireccionCliente> getAll(){ return direccionClienteRepository.findAll(); } @RequestMapping(value = "/{id}") public ResponseEntity<DireccionCliente> getDireccionCliente(@PathVariable("id") Long id){ return new ResponseEntity<DireccionCliente>(direccionClienteRepository.findOne(id),HttpStatus.OK); } @RequestMapping(method = RequestMethod.POST) public Object agregar(@RequestBody(required = true) DireccionCliente direccionCliente){ return direccionClienteRepository.save(direccionCliente); } @RequestMapping(value = "/{id}",method = RequestMethod.PATCH) public ResponseEntity<DireccionCliente> update(@PathVariable("id") Long id, @RequestBody DireccionCliente registro){ if(id == null || id <= 0){ return new ResponseEntity("{ \"message\" : \"id is required\"}",HttpStatus.CONFLICT); } if(direccionClienteRepository.findOne(id) == null){ return new ResponseEntity(HttpStatus.NO_CONTENT); } DireccionCliente direccionCliente = direccionClienteRepository.findOne(id); direccionCliente.setDireccion(registro.getDireccion()); direccionCliente.setDescripcion(registro.getDescripcion()); direccionCliente.setCliente(registro.getCliente()); direccionClienteRepository.save(direccionCliente); return new ResponseEntity<DireccionCliente>(direccionCliente,HttpStatus.OK); } @RequestMapping(value = "/{id}",method = RequestMethod.DELETE) public ResponseEntity<?> delete(@PathVariable("id") Long id){ if(id == null || id <= 0){ return new ResponseEntity("{ \"message\" : \"id is required\"}",HttpStatus.CONFLICT); } if(direccionClienteRepository.findOne(id) == null){ return new ResponseEntity(HttpStatus.NO_CONTENT); } DireccionCliente direccionCliente = direccionClienteRepository.findOne(id); direccionClienteRepository.delete(direccionCliente); return new ResponseEntity("{ \"message\" : \"delete online-course\"}",HttpStatus.OK); } }
46.666667
118
0.766541
479b7622097aa6ea190c059609e80b442f4201b7
615
package com.example.now; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created with IntelliJ IDEA. * @author Alex Bostan (alex.bostan@hostelworld.com) * @version $Id$ * @since 1.0 */ @RestController @EnableAutoConfiguration public class NowController { @RequestMapping("/") public String test() { return DateTimeFormatter.ISO_DATE.format(LocalDate.now()); } }
26.73913
70
0.769106