blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
eb7da0b668878e1129d922b66fcdffa7dae1fd4e
14c2f24f4b76550da5b74817df71674b6301b5e1
/src/main/java/com/server/shopserver/model/BookRepository.java
dcb49bd10e376fc85d9628d6824fa3937af3a6fa
[]
no_license
ViktorijaJ/spring-java-swagger.openAPI-gradle-docker
ac771bf7242222ffe0c349aa2bb24046c4df2e32
ad3fa1ba720e70dc8bcd3287861f2d722ce3eec1
refs/heads/master
2020-12-08T17:36:34.536400
2020-01-17T14:51:41
2020-01-17T14:51:41
233,049,408
0
0
null
null
null
null
UTF-8
Java
false
false
294
java
package com.server.shopserver.model; import org.springframework.data.repository.CrudRepository; // This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository // CRUD refers Create, Read, Update, Delete public interface BookRepository extends CrudRepository<Book, Integer> { }
[ "viktorija@riawolf.com" ]
viktorija@riawolf.com
178c1eeae4edc56cb8a2e67fe7f456fefab31285
a1d00fd7792806a7f75810813e5b0c7f6f0dfda1
/eclipse/src/org/ripple/power/ui/table/AddressTable.java
cff0988a23ea8b387d052e33e0e45a4bd3fc95e7
[ "Apache-2.0" ]
permissive
hjkio19086/RipplePower
0790863058547bbd6227d1bc100e11481f7b4855
af087e473cbacb17f4de11559493afd85ff8d171
refs/heads/master
2021-01-22T21:37:09.136987
2014-11-06T06:06:10
2014-11-06T06:06:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,241
java
package org.ripple.power.ui.table; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; public final class AddressTable extends ColorTable { /** * */ private static final long serialVersionUID = 1L; public static final int DATE = 1; public static final int NAME = 2; public static final int TYPE = 3; public static final int AMOUNT = 4; public static final int STATUS = 5; public static final int ADDRESS = 6; public static final int CUR = 7; public AddressTable(TableModel tableModel, int[] columnTypes) { super(tableModel); JTableHeader header = getTableHeader(); header.setBackground(new Color(70, 70, 70)); header.setForeground(Color.WHITE); Component component; TableCellRenderer renderer; TableColumn column; TableColumnModel columnModel = getColumnModel(); TableCellRenderer headRenderer = getTableHeader().getDefaultRenderer(); if (headRenderer instanceof DefaultTableCellRenderer) { DefaultTableCellRenderer defaultRenderer = (DefaultTableCellRenderer) headRenderer; defaultRenderer.setHorizontalAlignment(JLabel.CENTER); } int columnCount = tableModel.getColumnCount(); if (columnCount > columnTypes.length) { throw new IllegalArgumentException( "columnCount > columnTypes.length ! More columns than column types."); } for (int i = 0; i < columnCount; i++) { Object value = null; column = columnModel.getColumn(i); switch (columnTypes[i]) { case DATE: // 日期 column.setCellRenderer(new DateRenderer()); value = "1970-01-01"; break; case NAME: // 别名(max length 20) value = "mmmmmmmmmmmmmmmmmmmm"; break; case TYPE:// 状态(max length 10) column.setCellRenderer(new StringRenderer(JLabel.CENTER)); value = "mmmmmmmmmm"; break; case AMOUNT:// 钱数 column.setCellRenderer(new AmountRenderer()); value = "0.000000"; break; case STATUS: // 状态 column.setCellRenderer(new StringRenderer(JLabel.CENTER)); value = "none"; break; case ADDRESS: // 地址长度(max length 34) value = "0123456789AbCdEfGhIjKlMnOpQrStUvWx"; break; case CUR: // 地址长度(max length 34) column.setCellRenderer(new StringRenderer(JLabel.CENTER)); value = "XRP"; break; default: throw new IllegalArgumentException("Unsupported column type " + columnTypes[i]); } component = headRenderer.getTableCellRendererComponent(this, tableModel.getColumnName(i), false, false, 0, i); int headWidth = component.getPreferredSize().width; renderer = column.getCellRenderer(); if (renderer == null) { renderer = getDefaultRenderer(tableModel.getColumnClass(i)); } component = renderer.getTableCellRendererComponent(this, value, false, false, 0, i); int cellWidth = component.getPreferredSize().width; column.setPreferredWidth(Math.max(headWidth + 5, cellWidth + 5)); } setAutoResizeMode(AUTO_RESIZE_ALL_COLUMNS); } }
[ "longwind2012@hotmail.com" ]
longwind2012@hotmail.com
7d1c0eeb8b1557d2cd7a3335f38fdff7079b46cb
c89a7d47f41ab950259d0170f06305071a5fcc96
/otpserver/src/main/java/org/sisdirect/otpserver/server/api/OtpEventListener.java
c242ac51fb9896e50b83893adcf57561c94ba03b
[]
no_license
ollie314/simpleotpserver
cd0267808f566e3e0114c326a2de3054e8c6dc26
3974d6774e3dd818649043f2166a592ec2b01da9
refs/heads/master
2016-09-06T09:50:02.276356
2014-04-08T15:05:23
2014-04-08T15:05:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
84
java
package org.sisdirect.otpserver.server.api; public interface OtpEventListener { }
[ "mehdi.lefebvre@gmail.com" ]
mehdi.lefebvre@gmail.com
9e0724937c296c613b13a90a6bcf4fe8ba496e89
6e6a69bdf10266274bfd59f1b911ffa8b8107435
/src/java/cn/edu/tsinghua/sthu/action/ShowLoginPageAction.java
e70720c47c5e5d74af289790f28327e3f9c9d833
[]
no_license
cfan8/sthu
87f46cbe81a9ed67e61103b7717bfe04a8f9bdc6
dc014ba08cef15baed2ad916b1582c7c9dc08391
refs/heads/master
2016-09-10T10:50:34.655548
2014-02-22T14:46:01
2014-02-22T14:46:01
32,304,208
0
0
null
null
null
null
UTF-8
Java
false
false
1,842
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cn.edu.tsinghua.sthu.action; import cn.edu.tsinghua.sthu.Util; import cn.edu.tsinghua.sthu.message.ShowLoginPageMessage; /** * * @author linangran */ public class ShowLoginPageAction extends BaseAction { private String redirectURL; private ShowLoginPageMessage showLoginPageMessage; private String url; public static final String REDIRECT = "redirect"; @Override public String onExecute() { if (isLogin()) { url = Util.decodeURL(redirectURL); return REDIRECT; } else { showLoginPageMessage.setRedirectURL(redirectURL); showLoginPageMessage.setPublicKey(Util.publicString); showLoginPageMessage.setModulus(Util.modulusString); showLoginPageMessage.setTimestamp(System.currentTimeMillis()); return SUCCESS; } } @Override public boolean valid() { if (getRedirectURL() == null) { setRedirectURL(getReferer()); if (isValid(redirectURL)) { redirectURL = Util.encodeURL(redirectURL); } else { redirectURL = Util.encodeURL("/index.do"); } } return true; } public String getRedirectURL() { return redirectURL; } public void setRedirectURL(String redirectURL) { this.redirectURL = redirectURL; } public ShowLoginPageMessage getShowLoginPageMessage() { return showLoginPageMessage; } public void setShowLoginPageMessage(ShowLoginPageMessage showLoginPageMessage) { this.showLoginPageMessage = showLoginPageMessage; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public boolean needLogin() { return false; } }
[ "linangran@gmail.com@939c7460-21cd-d779-1633-3a3d42984b78" ]
linangran@gmail.com@939c7460-21cd-d779-1633-3a3d42984b78
1f89fed6451ad897ade5a22547bc2b6101b4098b
1a84d45caa3d587154ad8a09c03d1c59c3560b7c
/steemj-core/src/test/java/eu/bittrade/libs/steemj/base/models/operations/virtual/InterestOperationIT.java
ebef4497e8ca3749d922934e179306672021bedf
[ "MIT" ]
permissive
BoomApps-LLC/SteemApp-Android
694484c2c58ec835330272b0a87c6ba8fcb0c32c
f8ff7b430b221dc12ebb1e411b881d23f6db1c75
refs/heads/master
2020-03-20T15:46:23.258448
2018-08-30T20:32:17
2018-08-30T20:32:17
137,521,625
3
4
MIT
2018-09-01T08:52:05
2018-06-15T18:49:08
Java
UTF-8
Java
false
false
2,471
java
package eu.bittrade.libs.steemj.base.models.operations.virtual; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import eu.bittrade.libs.steemj.BaseITForOperationParsing; import eu.bittrade.libs.steemj.base.models.AppliedOperation; import eu.bittrade.libs.steemj.base.models.operations.Operation; import eu.bittrade.libs.steemj.enums.AssetSymbolType; import eu.bittrade.libs.steemj.exceptions.SteemCommunicationException; import eu.bittrade.libs.steemj.exceptions.SteemResponseException; /** * Test that the {@link CurationRewardOperation} can be parsed. * * @author <a href="http://steemit.com/@dez1337">dez1337</a> */ public class InterestOperationIT extends BaseITForOperationParsing { private static final int BLOCK_NUMBER_CONTAINING_OPERATION = 16022103; private static final int OPERATION_INDEX = 0; private static final String EXPECTED_OWNER = "eric818"; private static final AssetSymbolType EXPECTED_INTEREST_SYMBOL = AssetSymbolType.SBD; private static final double EXPECTED_INTEREST_VALUE_REAL = 0.003; private static final long EXPECTED_INTEREST_VALUE = 3L; /** * Prepare the environment for this specific test. * * @throws Exception * If something went wrong. */ @BeforeClass() public static void prepareTestClass() throws Exception { setupIntegrationTestEnvironment(); } @Override @Test public void testOperationParsing() throws SteemCommunicationException, SteemResponseException { List<AppliedOperation> operationsInBlock = steemJ.getOpsInBlock(BLOCK_NUMBER_CONTAINING_OPERATION, true); Operation interestOperation = operationsInBlock.get(OPERATION_INDEX).getOp(); assertThat(interestOperation, instanceOf(InterestOperation.class)); assertThat(((InterestOperation) interestOperation).getOwner().getName(), equalTo(EXPECTED_OWNER)); assertThat(((InterestOperation) interestOperation).getInterest().getSymbol(), equalTo(EXPECTED_INTEREST_SYMBOL)); assertThat(((InterestOperation) interestOperation).getInterest().toReal(), equalTo(EXPECTED_INTEREST_VALUE_REAL)); assertThat(((InterestOperation) interestOperation).getInterest().getAmount(), equalTo(EXPECTED_INTEREST_VALUE)); } }
[ "Vitaliy.Grechikha@artezio.com" ]
Vitaliy.Grechikha@artezio.com
32490653f68e161cafa1cce28c20ea6704b31bd8
b94db279557c85068cbf4871068dea2e2852cc28
/leetcode/editor/en/[98]Validate Binary Search Tree.java
82c05c976acb02fbc0ca88ab7043fc61147d5602
[]
no_license
yesluck/Leetcode
9bd5b1cb88f6a2d5b81c74db023e19e71428de6a
70b0aea9da52db79821a1ac5cc925b915dbabf0a
refs/heads/master
2023-05-27T16:02:18.998830
2021-06-06T12:18:08
2021-06-06T12:18:08
261,068,395
0
0
null
null
null
null
UTF-8
Java
false
false
3,048
java
//Given a binary tree, determine if it is a valid binary search tree (BST). // // Assume a BST is defined as follows: // // // The left subtree of a node contains only nodes with keys less than the node's key. // The right subtree of a node contains only nodes with keys greater than the node's key. // Both the left and right subtrees must also be binary search trees. // // // // // Example 1: // // // 2 // / \ // 1 3 // //Input: [2,1,3] //Output: true // // // Example 2: // // // 5 // / \ // 1 4 //  / \ //  3 6 // //Input: [5,1,4,null,null,3,6] //Output: false //Explanation: The root node's value is 5 but its right child's value is 4. // // /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ // inorder traversal class Solution { public boolean isValidBST(TreeNode root) { TreeNode curr = root; Stack<TreeNode> stack = new Stack<>(); double prevNum = -Double.MAX_VALUE; // otherwise can't pass -2147483648 case while (curr != null || !stack.isEmpty()) { if (curr != null) { stack.push(curr); curr = curr.left; } else { curr = stack.pop(); if (curr.val <= prevNum) return false; prevNum = curr.val; curr = curr.right; } } return true; } } // recursion class Solution { public boolean isValidBST(TreeNode root) { return helper(root, null, null); } public boolean helper(TreeNode node, Integer lower, Integer upper) { if (node == null) return true; int val = node.val; if (lower != null && val <= lower) return false; if (upper != null && val >= upper) return false; if (!helper(node.right, val, upper)) return false; if (!helper(node.left, lower, val)) return false; return true; } } // iterative class Solution { Stack<TreeNode> stack = new Stack<>(); Stack<Integer> lowers = new Stack<>(), uppers = new Stack<>(); public boolean isValidBST(TreeNode root) { Integer lower = null, upper = null, val; update(root, lower, upper); while (!stack.isEmpty()) { root = stack.pop(); lower = lowers.pop(); upper = uppers.pop(); if (root == null) continue; val = root.val; if (lower != null && val <= lower) return false; if (upper != null && val >= upper) return false; update(root.right, val, upper); update(root.left, lower, val); } return true; } public void update (TreeNode root, Integer lower, Integer upper) { stack.push(root); lowers.push(lower); uppers.push(upper); } }
[ "yesluck@126.com" ]
yesluck@126.com
fc947183b1c221c70619f69e951d2fee82165240
8588fcda6065a48d153f56ae13b7a4519266ca2a
/Chapter01/ch01-jaxrs/src/main/java/com/eldermoraes/ch01/jaxrs/ClientConsumer.java
5939a69c67017a4b198f6a5b228cd40f2f4938fc
[ "MIT" ]
permissive
PacktPublishing/Java-EE-8-Cookbook
4bfa701685c15aa5001c3285d60a3e31ff2f7ce3
18a1fbc9e9d8e4efcd2a1b7521cb148baefdb4c2
refs/heads/master
2023-02-06T03:32:06.489220
2023-01-30T10:22:12
2023-01-30T10:22:12
128,202,843
16
14
null
null
null
null
UTF-8
Java
false
false
1,386
java
package com.eldermoraes.ch01.jaxrs; import static com.eldermoraes.ch01.jaxrs.ServerMock.BASE_PATH; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.sse.SseEventSource; public class ClientConsumer { public static final Client CLIENT = ClientBuilder.newClient(); public static final WebTarget WEB_TARGET = CLIENT.target(ServerMock.CONTEXT + BASE_PATH); public static void main(String[] args) { consume(); } private static void consume() { try (final SseEventSource sseSource = SseEventSource .target(WEB_TARGET) .build()) { sseSource.register(System.out::println); sseSource.open(); for (int counter=0; counter < 5; counter++) { System.out.println(" "); for (int innerCounter=0; innerCounter < 5; innerCounter++) { WEB_TARGET.request().post(Entity.json("event " + innerCounter)); } Thread.sleep(1000); } CLIENT.close(); System.out.println("\nAll messages consumed"); } catch (InterruptedException e) { System.out.println(e.getMessage()); } } }
[ "prajaktam@packtpub.com" ]
prajaktam@packtpub.com
ef8570b202711c5cdb7f77dd9fcef2f4d748f53c
9857fcde58e9e09caab9063090a3c1b5787ca1bf
/src/main/java/uk/co/todddavies/website/cron/tasks/data/RecurringTask.java
31ef5eb4b3de89e1db6a3aeb85c2ee8134516aa0
[ "Apache-2.0" ]
permissive
DavidLeeEvans/appengine-website
6ac9b42dd90ccf08b36c587471fddde9f633deb3
c776588916dec315d1bb1153c2b6bba9a210cfbd
refs/heads/master
2021-09-02T09:39:24.792883
2018-01-01T14:39:26
2018-01-01T14:39:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,606
java
package uk.co.todddavies.website.cron.tasks.data; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.appengine.api.datastore.Entity; import com.google.common.annotations.VisibleForTesting; import java.io.Serializable; @JsonSerialize(using = RecurringTaskSerializer.class) public final class RecurringTask implements Serializable { private static final long serialVersionUID = -844261516437759395L; final String name; final String notes; final long key; //TODO(td): Use autovalue here RecurringTask( String name, String notes, long key) { this.name = name; this.notes = notes; this.key = key; } static RecurringTask createFromEntity(Entity entity) { return new RecurringTask( (String) entity.getProperty("name"), (String) entity.getProperty("notes"), entity.getKey().getId()); } @VisibleForTesting public static RecurringTask createForTest( String name, String notes, long key) { return new RecurringTask(name, notes, key); } @Override public String toString() { return new StringBuilder() .append("RecurringTask(") .append(name).append(",") .append(notes).append(",") .append(key).append(")") .toString(); } @Override public boolean equals(Object other) { return other instanceof RecurringTask ? this.key == ((RecurringTask) other).key : false; } public String getName() { return name; } public String getNotes() { return notes; } public long getKey() { return key; } }
[ "todd434@gmail.com" ]
todd434@gmail.com
b59e7e10cc3d75bff0a6df046c8c2ca90f8f2084
eb3d671e1c78ab3e4665c199ef8c072b287ea116
/bank-application/Manager.java
86277ee1ef194f3f85a09f8fcb2c1305f24c1e31
[]
no_license
sfasihh/soft-dev
3ce05ed11c33e0050960dd3fb033d618d8ab8044
61a6efb471ae483c3d02f84b2d2f5f5d4a6275f3
refs/heads/main
2023-04-16T05:00:09.537815
2019-01-22T09:41:46
2019-01-22T09:41:46
360,467,223
0
0
null
null
null
null
UTF-8
Java
false
false
1,346
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package coe528; /** * * @author Samiya Fasihuddin */ import java.util.*; import java.io.*; import java.nio.file.Files; public class Manager extends Account { // Overview: Manager is mutable, bounded // Customer files that operate under // the Manager's control // // The abstraction function is: // a)Write the abstraction function here // AF(s) = the stack of files A // A.add = adds a file filled with information // A.sum = shows the total number of customers // The rep invariant is: // b)Write the rep invariant here // A.name != null // A.name[i] != "admin" //the rep private List<Customer> customerList; public Manager() { super("admin", "admin", "Manager"); customerList = new ArrayList<Customer>(); } public void addCustomer(String username, String password) throws IOException { Customer customer; customer = new Customer(username, password, 100.0); } public void deleteCustomer(String username) { File file = new File(username); file.delete(); } }
[ "samiya.fasih@gmail.com" ]
samiya.fasih@gmail.com
403417e7940e3c8c649bf25d234124604bafccc9
649f347cbb633c91515fccce7571b547cc3628d2
/src/com/movilesseguros/ui/fragment/GoogleMapFragment.java
52ef42fbab1832f6bd3fc8f8f1729192d9429760
[]
no_license
jorgealvz/Moviles-Seguros
21bcc3343c9f4acc6c038d68e5fd35ae49800a51
192daa2c01251ce8e44dc6ba69da9a505969bcf2
refs/heads/master
2016-09-06T19:09:39.226592
2014-04-26T05:31:43
2014-04-26T05:31:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,642
java
package com.movilesseguros.ui.fragment; import java.util.List; import android.app.Activity; import android.database.Cursor; import android.location.Location; import android.os.Bundle; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.helper.FormatHelper; import com.android.helper.HelpPopup; import com.android.helper.HelpPopup.ShowListener; import com.android.helper.google.map.Route; import com.android.helper.gps.GpsHelper; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.movilesseguros.R; import com.movilesseguros.dal.PlaceProvider; import com.movilesseguros.helper.Constantes; import com.movilesseguros.negocio.ControlConfiguracion; public class GoogleMapFragment extends SupportMapFragment implements OnInfoWindowClickListener, LoaderCallbacks<Cursor> { private static final int DEFAULT_ZOOM = 15; private static final LatLng DEFAULT_LAT_LNG = new LatLng(-17.7797768, -63.1699816); private static final int SEARCH_CURSOR_LOADER_ID = 0; private static final int DETAILS_CURSOR_LOADER_ID = 1; private Marker marker; private GoogleMap mGoogleMap; private GoogleMapListener mGoogleMapListener; private ControlConfiguracion mControlConfiguracion; private HelpPopup mHelpPopup; @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mGoogleMapListener = (GoogleMapListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement GoogleMapListener."); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); initMap(); return view; } private void initMap() { mGoogleMap = getMap(); mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); mGoogleMap.setMyLocationEnabled(true); Location location = GpsHelper.getInstancia().getLocation(); mGoogleMap .moveCamera(CameraUpdateFactory.newLatLngZoom( location == null ? DEFAULT_LAT_LNG : new LatLng(location.getLatitude(), location .getLongitude()), DEFAULT_ZOOM)); UiSettings settings = getMap().getUiSettings(); settings.setMyLocationButtonEnabled(true); settings.setCompassEnabled(true); settings.setAllGesturesEnabled(true); mGoogleMap.setOnMapLongClickListener(new OnMapLongClickListener() { @Override public void onMapLongClick(LatLng point) { mGoogleMap.clear(); marker = mGoogleMap.addMarker(new MarkerOptions() .position(point) .title("") .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_RED))); } }); mGoogleMap.setOnInfoWindowClickListener(this); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mControlConfiguracion = new ControlConfiguracion(getActivity()); if (!mControlConfiguracion.isShowHelpMapa() && getView() != null) { mHelpPopup = new HelpPopup(getActivity(), getString(R.string.mapa_message_help_punto_destino), R.layout.yellow_popup_layout); mHelpPopup.setShowListener(new ShowListener() { @Override public void onShow() { mControlConfiguracion.setShowHelpMapa(); } @Override public void onPreShow() { } @Override public void onDismiss() { } }); mHelpPopup.show(getView()); } } @Override public void onDestroy() { super.onDestroy(); if (mHelpPopup != null) { mHelpPopup.dismiss(); } } public Marker getMarker() { return marker; } public void drawRoute(Route route) { mGoogleMap.clear(); marker = null; List<LatLng> listPoints = route.getPoints(); if (!listPoints.isEmpty()) { PolylineOptions polylineOptions = new PolylineOptions(); polylineOptions.color(0x7F0000FF); for (LatLng point : listPoints) { polylineOptions.add(point); } // ## Calculamos la tarifa double tarifa = calcularTarifa(route.getLength()); // ## Adicionamos el punto inicial addMarker(mGoogleMap, route.getStartAddress(), null, R.drawable.ic_maps_indicator_startpoint_route, listPoints.get(0)); // ## Adicionamos el punto final Marker markerDestino = addMarker( mGoogleMap, route.getEndAddress(), getString(R.string.mapa_tarifa_aproximada_label, FormatHelper.toDecimalFormat(tarifa, "Bs.")), R.drawable.ic_maps_indicator_endpoint_route, listPoints.get(listPoints.size() - 1)); mGoogleMap.addPolyline(polylineOptions); showMarkerInfo(markerDestino); } } private Marker addMarker(GoogleMap map, String title, String snippet, int drawableId, LatLng position) { return map.addMarker(new MarkerOptions().title(title).snippet(snippet) .icon(BitmapDescriptorFactory.fromResource(drawableId)) .position(position).anchor(0.5f, 1.0f)); } private void showMarkerInfo(Marker marker) { marker.showInfoWindow(); if (mGoogleMap.getCameraPosition().zoom < DEFAULT_ZOOM) { mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom( marker.getPosition(), DEFAULT_ZOOM)); } else { mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(marker .getPosition())); } } private double calcularTarifa(int routeLength) { double kilometers = routeLength / 1000; double tarifa = 0; if (kilometers <= Constantes.KILOMETROS_MINIMOS) { tarifa = Constantes.TARIFA_BASICA; } else { tarifa = Constantes.TARIFA_BASICA + ((kilometers - Constantes.KILOMETROS_MINIMOS) * Constantes.TARIFA_X_KILOMETRO); } return tarifa; } @Override public void onInfoWindowClick(Marker marker) { mGoogleMapListener.onInfoWindowClick(); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { case SEARCH_CURSOR_LOADER_ID: return new CursorLoader(getActivity(), PlaceProvider.SEARCH_URI, null, getString(R.string.mapa_google_api_browser_key), new String[] { args.getString("query") }, null); case DETAILS_CURSOR_LOADER_ID: return new CursorLoader(getActivity(), PlaceProvider.DETAILS_URI, null, getString(R.string.mapa_google_api_browser_key), new String[] { args.getString("query") }, null); default: return null; } } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { showLocations(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { // do nothing } private void showLocations(Cursor cursor) { LatLng position = null; mGoogleMap.clear(); while (cursor.moveToNext()) { MarkerOptions markerOptions = new MarkerOptions(); position = new LatLng(Double.parseDouble(cursor.getString(1)), Double.parseDouble(cursor.getString(2))); markerOptions.position(position); mGoogleMap.addMarker(markerOptions); } if (position != null) { CameraUpdate cameraPosition = CameraUpdateFactory .newLatLng(position); mGoogleMap.animateCamera(cameraPosition); } } public void doSearch(String query) { Bundle data = new Bundle(); data.putString("query", query); getLoaderManager().restartLoader(SEARCH_CURSOR_LOADER_ID, data, this); } public void getPlace(String query) { Bundle data = new Bundle(); data.putString("query", query); getLoaderManager().restartLoader(DETAILS_CURSOR_LOADER_ID, data, this); } public void addMarker(LatLng position) { marker = mGoogleMap.addMarker(new MarkerOptions() .position(position) .title("") .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_RED))); if (position != null) { CameraUpdate cameraPosition = CameraUpdateFactory .newLatLng(position); mGoogleMap.animateCamera(cameraPosition); } } public interface GoogleMapListener { public void onInfoWindowClick(); } }
[ "alvz.jorge@gmail.com" ]
alvz.jorge@gmail.com
fb91b7fe1d71ee5ba18379ccaa4d00031012981b
6ad55aac083e8418dcce803800f9c0694907e3ef
/src/main/java/com/nickcaplan/oddschecker/repository/OddsRepository.java
e51bf7566226ffbc04c3f00a511c1c4b9198a42c
[]
no_license
nickcaplan/springboot-example
297a22fdf91b664d6fd8172df9b7893c84fea38e
8f67ed27de2bc8ffe52d6ea965c0d20e5f57ea3e
refs/heads/master
2022-11-13T14:15:30.799837
2020-07-14T14:59:16
2020-07-14T14:59:16
279,615,708
0
0
null
null
null
null
UTF-8
Java
false
false
338
java
package com.nickcaplan.oddschecker.repository; import com.nickcaplan.oddschecker.model.Odds; import org.springframework.data.repository.CrudRepository; /** * Provides access to the {@link Odds} table. */ public interface OddsRepository extends CrudRepository<Odds, Long> { Odds findByBetIdAndUserId(Long betId, String userId); }
[ "nicholas.caplan@moogsoft.com" ]
nicholas.caplan@moogsoft.com
69fc7f3ac8f42b65ce97bc7444a75d970e143202
efb25b187d19064858ecd45f0616674db807ec91
/day5/Java/pattern_4.java
086f126765f8d64150b40f9e5b0f15578bc227e4
[ "MIT" ]
permissive
CodeToExpress/dailycodebase
c03956b0a6ce70e125b05e1c1515286736f01f8c
aa99d5a78a44bfe5fb5555af530a25209f120956
refs/heads/master
2022-08-28T05:04:10.781286
2022-04-14T00:52:31
2022-04-14T00:52:31
162,131,062
262
214
MIT
2023-01-18T01:02:58
2018-12-17T12:59:49
Java
UTF-8
Java
false
false
923
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package patterns; /** * * @author SPREEHA DUTTA */ public class pattern4 { public static void print(int s,int p) { int i,j;int t; if(p<=5) { for(i=1;i<=s;i++) System.out.print(' '); t=p; for(j=1;j<=p;j++) { System.out.print(t); t++; } t-=2; for(j=1;j<p;j++) { System.out.print(t); t--; } System.out.println(); s--; p++; print(s,p); } else return; } public static void main(String []args) { print(4,1); } }
[ "madhavbahl10@gmail.com" ]
madhavbahl10@gmail.com
822583b2eb8af49a47c2b8a887e4b194a9d137ef
aca5a5b0322328ef479b7d375ab6bb990e9f7574
/jdk1.8.0_66_src/src/org/omg/PortableServer/POAPackage/AdapterAlreadyExists.java
5a2a5dde53c4b9a40f3c52caecceff6c89235e36
[ "Apache-2.0" ]
permissive
codecly259/read-source
8970b37614294622b9d09b78f0b1fba3bfef97c1
84f31d4b1f86e8fee3c2a161251e7ccecd4ac223
refs/heads/master
2021-01-21T12:52:52.762373
2016-04-08T14:47:54
2016-04-08T14:47:54
53,556,248
1
0
null
null
null
null
UTF-8
Java
false
false
679
java
package org.omg.PortableServer.POAPackage; /** * org/omg/PortableServer/POAPackage/AdapterAlreadyExists.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u66/5298/corba/src/share/classes/org/omg/PortableServer/poa.idl * Monday, November 9, 2015 10:52:07 AM PST */ public final class AdapterAlreadyExists extends org.omg.CORBA.UserException { public AdapterAlreadyExists () { super(AdapterAlreadyExistsHelper.id()); } // ctor public AdapterAlreadyExists (String $reason) { super(AdapterAlreadyExistsHelper.id() + " " + $reason); } // ctor } // class AdapterAlreadyExists
[ "maxinchun0215@qq.com" ]
maxinchun0215@qq.com
98d0470ac50556d29447157b9ce3217314a1bc9b
1dbe29422cd08ad7becfea756741fd0dc5bce841
/app/src/main/java/me/chaoyang805/doubanmovie/data/MovieResults.java
45907910c6bb5a4ae36bb326e05cb6bc59051179
[]
no_license
chaoyang805/DoubanMovie-Android
fadca8745e05b22ef632a0623ef8259b9b59aa54
96cbd982fb0f3caf50dba2da65253bb3ebd81a96
refs/heads/master
2021-01-11T02:16:02.474098
2016-10-16T16:21:55
2016-10-16T16:21:55
70,987,177
0
0
null
null
null
null
UTF-8
Java
false
false
850
java
package me.chaoyang805.doubanmovie.data; import java.util.List; /** * Created by chaoyang805 on 16/10/17. */ public class MovieResults { private String title; private int count; private int total; private int start; private List<DoubanMovie> subjects; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public List<DoubanMovie> getSubjects() { return subjects; } public void setSubjects(List<DoubanMovie> subjects) { this.subjects = subjects; } }
[ "zhangchaoyang805@gmail.com" ]
zhangchaoyang805@gmail.com
39712ef82103e9abcf8ae2bdabad8c65973045b3
a86baa293fb020f69f6cb42bc0ddc7668662e382
/app/src/main/java/ar/shadow/org/exhibition/render/BackgroundRenderer.java
b4870bb87f5d6ad1696b2f111c1a55324afd0a3e
[]
no_license
Shadowru/Exhibition
4f033dded8cc588cbc6a8ef2f217677daf07798b
afc48eaf3fa9a5af67e672f0ddc80f2ce8c3646f
refs/heads/master
2021-05-11T16:03:07.081866
2018-01-16T22:37:17
2018-01-16T22:37:17
117,751,225
0
0
null
null
null
null
UTF-8
Java
false
false
6,560
java
package ar.shadow.org.exhibition.render; import android.content.Context; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import com.google.ar.core.Frame; import com.google.ar.core.Session; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import ar.shadow.org.exhibition.R; /** * Created by Shadow on 16.01.2018. */ public class BackgroundRenderer { private static final String TAG = BackgroundRenderer.class.getSimpleName(); private static final int COORDS_PER_VERTEX = 3; private static final int TEXCOORDS_PER_VERTEX = 2; private static final int FLOAT_SIZE = 4; private FloatBuffer mQuadVertices; private FloatBuffer mQuadTexCoord; private FloatBuffer mQuadTexCoordTransformed; private int mQuadProgram; private int mQuadPositionParam; private int mQuadTexCoordParam; private int mTextureId = -1; public BackgroundRenderer() { } public int getTextureId() { return mTextureId; } /** * Allocates and initializes OpenGL resources needed by the background renderer. Must be * called on the OpenGL thread, typically in * {@link GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)}. * * @param context Needed to access shader source. */ public void createOnGlThread(Context context) { // Generate the background texture. int[] textures = new int[1]; GLES20.glGenTextures(1, textures, 0); mTextureId = textures[0]; int textureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES; GLES20.glBindTexture(textureTarget, mTextureId); GLES20.glTexParameteri(textureTarget, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(textureTarget, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(textureTarget, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameteri(textureTarget, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST); int numVertices = 4; if (numVertices != QUAD_COORDS.length / COORDS_PER_VERTEX) { throw new RuntimeException("Unexpected number of vertices in BackgroundRenderer."); } ByteBuffer bbVertices = ByteBuffer.allocateDirect(QUAD_COORDS.length * FLOAT_SIZE); bbVertices.order(ByteOrder.nativeOrder()); mQuadVertices = bbVertices.asFloatBuffer(); mQuadVertices.put(QUAD_COORDS); mQuadVertices.position(0); ByteBuffer bbTexCoords = ByteBuffer.allocateDirect( numVertices * TEXCOORDS_PER_VERTEX * FLOAT_SIZE); bbTexCoords.order(ByteOrder.nativeOrder()); mQuadTexCoord = bbTexCoords.asFloatBuffer(); mQuadTexCoord.put(QUAD_TEXCOORDS); mQuadTexCoord.position(0); ByteBuffer bbTexCoordsTransformed = ByteBuffer.allocateDirect( numVertices * TEXCOORDS_PER_VERTEX * FLOAT_SIZE); bbTexCoordsTransformed.order(ByteOrder.nativeOrder()); mQuadTexCoordTransformed = bbTexCoordsTransformed.asFloatBuffer(); int vertexShader = ShaderUtil.loadGLShader(TAG, context, GLES20.GL_VERTEX_SHADER, R.raw.screenquad_vertex); int fragmentShader = ShaderUtil.loadGLShader(TAG, context, GLES20.GL_FRAGMENT_SHADER, R.raw.screenquad_fragment_oes); mQuadProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(mQuadProgram, vertexShader); GLES20.glAttachShader(mQuadProgram, fragmentShader); GLES20.glLinkProgram(mQuadProgram); GLES20.glUseProgram(mQuadProgram); ShaderUtil.checkGLError(TAG, "Program creation"); mQuadPositionParam = GLES20.glGetAttribLocation(mQuadProgram, "a_Position"); mQuadTexCoordParam = GLES20.glGetAttribLocation(mQuadProgram, "a_TexCoord"); ShaderUtil.checkGLError(TAG, "Program parameters"); } /** * Draws the AR background image. The image will be drawn such that virtual content rendered * with the matrices provided by {@link com.google.ar.core.Camera#getViewMatrix(float[], int)} * and {@link com.google.ar.core.Camera#getProjectionMatrix(float[], int, float, float)} will * accurately follow static physical objects. * This must be called <b>before</b> drawing virtual content. * * @param frame The last {@code Frame} returned by {@link Session#update()}. */ public void draw(Frame frame) { // If display rotation changed (also includes view size change), we need to re-query the uv // coordinates for the screen rect, as they may have changed as well. if (frame.hasDisplayGeometryChanged()) { frame.transformDisplayUvCoords(mQuadTexCoord, mQuadTexCoordTransformed); } // No need to test or write depth, the screen quad has arbitrary depth, and is expected // to be drawn first. GLES20.glDisable(GLES20.GL_DEPTH_TEST); GLES20.glDepthMask(false); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId); GLES20.glUseProgram(mQuadProgram); // Set the vertex positions. GLES20.glVertexAttribPointer( mQuadPositionParam, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, 0, mQuadVertices); // Set the texture coordinates. GLES20.glVertexAttribPointer(mQuadTexCoordParam, TEXCOORDS_PER_VERTEX, GLES20.GL_FLOAT, false, 0, mQuadTexCoordTransformed); // Enable vertex arrays GLES20.glEnableVertexAttribArray(mQuadPositionParam); GLES20.glEnableVertexAttribArray(mQuadTexCoordParam); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); // Disable vertex arrays GLES20.glDisableVertexAttribArray(mQuadPositionParam); GLES20.glDisableVertexAttribArray(mQuadTexCoordParam); // Restore the depth state for further drawing. GLES20.glDepthMask(true); GLES20.glEnable(GLES20.GL_DEPTH_TEST); ShaderUtil.checkGLError(TAG, "Draw"); } private static final float[] QUAD_COORDS = new float[]{ -1.0f, -1.0f, 0.0f, -1.0f, +1.0f, 0.0f, +1.0f, -1.0f, 0.0f, +1.0f, +1.0f, 0.0f, }; private static final float[] QUAD_TEXCOORDS = new float[]{ 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, }; }
[ "proteyrus@gmail.com" ]
proteyrus@gmail.com
cd6fbd371fff624e301994726c4925d094c96fd5
9c38365a4980ee0ed6be4202902fda67e5bac5fc
/src/com/memory/db/Proxy.java
12d0be8cb0af6ab2f1d9bcb9df33cdec0017ab76
[]
no_license
280247489/demo
dcdbf191c6e315511586698efaedc95fa5f9085e
5d04bd68782d3a2829cd2b1210dcf7e3a4f32e33
refs/heads/master
2020-04-12T03:01:32.752933
2018-12-28T08:24:32
2018-12-28T08:24:32
162,261,280
0
0
null
null
null
null
UTF-8
Java
false
false
1,841
java
package com.memory.db; /** * @Auther: cui.Memory * @Date: 2018/12/19 0019 13:28 * @Description: */ public class Proxy { private String id; private String name; private Double money; private Double moneySum; private String parent; private String parentName; private Integer count; private Double moneyLs; private Double moneySumLs; @Override public String toString() { if(count>0){ return name + "("+count+")"; }else{ return name; } } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } public Double getMoneySum() { return moneySum; } public void setMoneySum(Double moneySum) { this.moneySum = moneySum; } public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public Double getMoneyLs() { return moneyLs; } public void setMoneyLs(Double moneyLs) { this.moneyLs = moneyLs; } public Double getMoneySumLs() { return moneySumLs; } public void setMoneySumLs(Double moneySumLs) { this.moneySumLs = moneySumLs; } }
[ "280247489@qq.com" ]
280247489@qq.com
222636931194e075f8e3852f1da2dd0715169c08
980c2fa0720a27060cbaa8137142b26e6e264189
/back/java/src/main/java/com/svlada/security/auth/ajax/AjaxLoginProcessingFilter.java
6577c175dda348cb054aec5f00fd5ade20b5bc92
[ "MIT" ]
permissive
lfdajr/campusbase
f0d1c1ef607f35746b68bf6e516773fcb69eaf8c
32aac95282bf847b4eca52eb8a7efa7bba8d35b4
refs/heads/master
2020-03-27T11:27:54.262832
2018-08-28T18:50:33
2018-08-28T18:50:33
139,278,727
0
0
null
null
null
null
UTF-8
Java
false
false
3,591
java
package com.svlada.security.auth.ajax; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import com.fasterxml.jackson.databind.ObjectMapper; import com.svlada.common.WebUtil; import com.svlada.security.exceptions.AuthMethodNotSupportedException; public class AjaxLoginProcessingFilter extends AbstractAuthenticationProcessingFilter { private static Logger logger = LoggerFactory.getLogger(AjaxLoginProcessingFilter.class); private final AuthenticationSuccessHandler successHandler; private final AuthenticationFailureHandler failureHandler; private final ObjectMapper objectMapper; public AjaxLoginProcessingFilter(String defaultProcessUrl, AuthenticationSuccessHandler successHandler, AuthenticationFailureHandler failureHandler, ObjectMapper mapper) { super(defaultProcessUrl); this.successHandler = successHandler; this.failureHandler = failureHandler; this.objectMapper = mapper; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!HttpMethod.POST.name().equals(request.getMethod())) { if (logger.isDebugEnabled()) { logger.debug("Authentication method not supported. Request method: " + request.getMethod()); } throw new AuthMethodNotSupportedException("Authentication method not supported"); } LoginRequest loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class); if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) { throw new AuthenticationServiceException("Username or Password not provided"); } UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()); return this.getAuthenticationManager().authenticate(token); } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { successHandler.onAuthenticationSuccess(request, response, authResult); } @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { SecurityContextHolder.clearContext(); failureHandler.onAuthenticationFailure(request, response, failed); } }
[ "lourival.almeida@gmail.com" ]
lourival.almeida@gmail.com
1b0081a9bfc21f71ef1fbb8c5a960b81ad3a2a18
e60685847d77895a4019426b9c291b986855d9ec
/archunit/src/main/java/com/tngtech/archunit/library/dependencies/Slice.java
2dfad29f2508f42d29f1197807dbedc14cb57202
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
kosani/ArchUnit
ba818058b4f9d2262b0e1c54780ee7b9a4898c84
fefe1d372200781ada710db8ba88e4fed5fb2f2b
refs/heads/master
2020-04-16T13:58:14.245764
2019-01-13T21:33:44
2019-01-13T21:33:44
165,649,629
5
0
null
null
null
null
UTF-8
Java
false
false
5,075
java
/* * Copyright 2019 TNG Technology Consulting 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.tngtech.archunit.library.dependencies; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.common.base.Joiner; import com.google.common.collect.ForwardingSet; import com.google.common.collect.ImmutableSet; import com.tngtech.archunit.PublicAPI; import com.tngtech.archunit.base.HasDescription; import com.tngtech.archunit.core.domain.Dependency; import com.tngtech.archunit.core.domain.JavaClass; import com.tngtech.archunit.core.domain.properties.CanOverrideDescription; import static com.google.common.base.Preconditions.checkArgument; import static com.tngtech.archunit.PublicAPI.Usage.ACCESS; public final class Slice extends ForwardingSet<JavaClass> implements HasDescription, CanOverrideDescription<Slice> { private final List<String> matchingGroups; private Description description; private final Set<JavaClass> classes; private Slice(List<String> matchingGroups, Set<JavaClass> classes) { this.matchingGroups = matchingGroups; this.description = new Description("Slice " + Joiner.on(" - ").join(ascendingCaptures(matchingGroups))); this.classes = ImmutableSet.copyOf(classes); } private List<String> ascendingCaptures(List<String> matchingGroups) { List<String> result = new ArrayList<>(); for (int i = 1; i <= matchingGroups.size(); i++) { result.add("$" + i); } return result; } @Override protected Set<JavaClass> delegate() { return classes; } @Override public String getDescription() { return description.format(matchingGroups); } /** * The pattern can be a description with references to the matching groups by '$' and position. * E.g. slices are created by 'some.svc.(*).sub.(*)', and the pattern is "the module $2 of service $1", * and we match 'some.svc.foo.module.bar', then the resulting description will be * "the module bar of service foo". * * @param pattern The description pattern with numbered references of the form $i * @return Same slice with different description */ @Override public Slice as(String pattern) { description = new Description(pattern); return this; } @PublicAPI(usage = ACCESS) public Set<Dependency> getDependencies() { Set<Dependency> result = new HashSet<>(); for (JavaClass javaClass : this) { for (Dependency dependency : javaClass.getDirectDependenciesFromSelf()) { if (!contains(dependency.getTargetClass())) { result.add(dependency); } } } return result; } @Override public String toString() { return getDescription(); } /** * Returns a matching part of this slice. E.g. if the slice was created by matching '..(*).controller.(*)..', * against 'some.other.controller.here.more', then name part '1' would be 'other' and name part '2' would * be 'here'. * * @param index The index of the matched group * @return The part of the matched package name. */ @PublicAPI(usage = ACCESS) public String getNamePart(int index) { checkArgument(index > 0 && index <= matchingGroups.size(), "Found no name part with index %d", index); return matchingGroups.get(index - 1); } private static class Description { private final String pattern; private Description(String pattern) { this.pattern = pattern; } String format(List<String> matchingGroups) { String result = pattern; for (int i = 1; i <= matchingGroups.size(); i++) { result = result.replace("$" + i, matchingGroups.get(i - 1)); } return result; } } static class Builder { private final List<String> matchingGroups; private final Set<JavaClass> classes = new HashSet<>(); private Builder(List<String> matchingGroups) { this.matchingGroups = matchingGroups; } static Builder from(List<String> matchingGroups) { return new Builder(matchingGroups); } Builder addClass(JavaClass clazz) { classes.add(clazz); return this; } Slice build() { return new Slice(matchingGroups, classes); } } }
[ "peter.gafert@tngtech.com" ]
peter.gafert@tngtech.com
0b03a1f17bb25b31b7b7608fd6d0ea9c58bb64b8
aea499d8ae43dc18f93da82f5ae70c840659bbad
/org.ektorp/src/main/java/org/ektorp/support/OpenCouchDbDocument.java
f8c899b7402f7939251f6552ddafffc926597b1d
[ "Apache-2.0" ]
permissive
mschoch/Ektorp
f7272a6f3df95640d9248a4d2a80a74d72a750ff
e4e4fdf501b40ec900830bb43173589680597ac9
refs/heads/master
2023-06-09T18:58:49.631846
2011-11-10T22:08:43
2011-11-10T22:08:43
2,257,881
1
1
null
null
null
null
UTF-8
Java
false
false
1,216
java
package org.ektorp.support; import java.util.*; import org.codehaus.jackson.annotate.*; /** * Provides convenience field and methods for holding unmapped fields in JSON serialization / deserialization. * * Subclasses of this class can be read and written to and from JSON documents without loosing unmapped fields in the process. * i.e. the class will be tolerant for changes in the underlying JSON data, * @author henriklundgren * */ public class OpenCouchDbDocument extends CouchDbDocument { private static final long serialVersionUID = 4252717502666745598L; private Map<String, Object> anonymous; /** * @return a Map containing fields that did not map to any other field in the class during object deserializarion from a JSON document. */ @JsonAnyGetter public Map<String, Object> getAnonymous() { return anonymous(); } /** * * @param key * @param value */ @JsonAnySetter public void setAnonymous(String key, Object value) { anonymous().put(key, value); } /** * Provides lay init for the anonymous Map * @return */ private Map<String, Object> anonymous() { if (anonymous == null) { anonymous = new HashMap<String, Object>(); } return anonymous; } }
[ "carl.henrik.lundgren@gmail.com" ]
carl.henrik.lundgren@gmail.com
0d5e2656756e536937a32b51c30fc644f993b616
f842b5faa55e72b3d7a72eb054d59b09aca7383b
/Hallo/src/Wurfeln/Wurfeln.java
ab6a6bc70e6069b7f7870234649bbf15ce23c66c
[]
no_license
dangtbh1623/Eclipse
707233f6df6f820c986252d2890a245642df952e
66fd5423e0a2b696f3fc45dec5c4c2b986ebecc7
refs/heads/master
2020-08-05T04:07:25.442011
2019-11-12T09:26:28
2019-11-12T09:26:28
212,388,034
0
0
null
2019-10-21T11:56:35
2019-10-02T16:24:18
Java
UTF-8
Java
false
false
228
java
package Wurfeln; public class Wurfeln { private int wurf; public Wurfeln() { wurfeln(); } public void wurfeln() { this.wurf = (int)(Math.random()*6 + 1); } public int getWurf() { return wurf; } }
[ "dang.tbh1623@gmail.com" ]
dang.tbh1623@gmail.com
f45947b997fab36038e36a820eb104bbfc6bc090
b56b17fb6db96b7d9ef1cf095132b038717b0b4c
/app/src/main/java/com/food/sofra/data/model/restaurant/notifications/restaurantNotificationRegisterToken/RestaurantNotificationRegisterToken.java
a2b244331f7f69f497bcb476c73cdb28d8d25f60
[]
no_license
vetaprog85samir/Sofra
378fabc6516b9056fc32b78e0de841434d09e17c
7d91942978189f4771b66458bc8b158ce7b6e2e6
refs/heads/master
2022-07-29T04:29:26.573731
2020-05-23T23:02:41
2020-05-23T23:02:41
266,341,866
0
0
null
null
null
null
UTF-8
Java
false
false
844
java
package com.food.sofra.data.model.restaurant.notifications.restaurantNotificationRegisterToken; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class RestaurantNotificationRegisterToken { @SerializedName("status") @Expose private Integer status; @SerializedName("msg") @Expose private String msg; @SerializedName("data") @Expose private Object data; public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
[ "37863223+vetaprog85samir@users.noreply.github.com" ]
37863223+vetaprog85samir@users.noreply.github.com
9dfd3dd2d6819f4e74f4273427fd0d3143b74748
21a59430da2c8eeb7244d0ccc782b999cb4361e3
/SilverSaver/app/src/test/java/com/weebly/silvertm/silversaver/ExampleUnitTest.java
f479682666095c0ceeff35dd818337104ead7453
[]
no_license
guilanfredi/SilverSaverApp
1ab646488213e3772d462bbd955102cebbe603a9
4128ccbe650e5d2d6573fa1085bb2a7f9b20045d
refs/heads/master
2021-01-24T09:01:27.697714
2016-10-17T12:19:59
2016-10-17T12:19:59
70,080,245
0
0
null
null
null
null
UTF-8
Java
false
false
409
java
package com.weebly.silvertm.silversaver; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "gui.lanfredi@gmail.com" ]
gui.lanfredi@gmail.com
30cdd751be0fee1e1c480337253eae70e2fa4035
c86992b04c99cd54ccc31cb7402483d4326b3ea6
/Media.io/app/src/androidTest/java/com/example/mediaio/mediaio/ExampleInstrumentedTest.java
1c3ce9d811e9c858a7863abc726f6999a35ec16c
[]
no_license
MusicIO-Grupo2/androidUserApplication
05ed677a6f8574d55bba99e77acc7702a84e8771
ba485f90adaa0f1e08288d63922cf6c02fd34f94
refs/heads/master
2021-01-23T02:23:30.272521
2017-05-27T18:31:19
2017-05-27T18:31:19
85,989,670
0
0
null
null
null
null
UTF-8
Java
false
false
758
java
package com.example.mediaio.mediaio; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.mediaio.mediaio", appContext.getPackageName()); } }
[ "marcospernica@gmail.com" ]
marcospernica@gmail.com
a6770e8292756574e7de283dd3a152885c3684b1
180e78725121de49801e34de358c32cf7148b0a2
/dataset/protocol1/java-design-patterns/testing/56/App.java
54bf10e5c04c670c1742ab133d960143f40d80c3
[]
no_license
ASSERT-KTH/synthetic-checkstyle-error-dataset
40e8d1e0a7ebe7f7711def96a390891a6922f7bd
40c057e1669584bfc6fecf789b5b2854660222f3
refs/heads/master
2023-03-18T12:50:55.410343
2019-01-25T09:54:39
2019-01-25T09:54:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,031
java
/** * The MIT License * Copyright (c) 2014-2016 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.pageobject ; import java.awt.Desktop; import java.io.File; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Page Object pattern wraps an UI component with an application specific API allowing you to * manipulate the UI elements without having to dig around with the underlying UI technology used. This is * especially useful for testing as it means your tests will be less brittle. Your tests can concentrate on * the actual test cases where as the manipulation of the UI can be left to the internals of the page object * itself. * * <p> * Due to this reason, it has become very popular within the test automation community. * In particular, it is very common in that the page object is used to represent the html pages of a * web application that is under test. This web application is referred to as AUT (Application Under Test). * A web browser automation tool/framework like Selenium for instance, is then used to drive the automating * of the browser navigation and user actions journeys through this web application. Your test class would * therefore only be responsible for particular test cases and page object would be used by the test class * for UI manipulation required for the tests. * * <p> * In this implementation rather than using Selenium, the HtmlUnit library is used as a replacement to * represent the specific html elements and to drive the browser. The purpose of this example is just to * provide a simple version that showcase the intentions of this pattern and how this pattern is used * in order to understand it. */ public final class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); private App() { } /** * Application entry point * * <p> * The application under development is a web application. Normally you would probably have a * backend that is probably implemented in an object-oriented language (e.g. Java) that serves * the frontend which comprises of a series of HTML, CSS, JS etc... * * <p> * For illustrations purposes only, a very simple static html app is used here. This main method * just fires up this simple web app in a default browser. * * @param args arguments */ public static void main(String[] args) { try { File applicationFile = new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath()); // should work for unix like OS (mac, unix etc...) if (Desktop.isDesktopSupported()) { Desktop.getDesktop().open(applicationFile); } else { // java Desktop not supported - above unlikely to work for Windows so try following instead... Runtime.getRuntime().exec("cmd.exe start " + applicationFile); } } catch (IOException ex) { LOGGER.error("An error occured.", ex); } } }
[ "bloriot97@gmail.com" ]
bloriot97@gmail.com
426b2d1fa7539e504bec65b827757ba3dc8d31b3
a448756f33d32fc6633459da21e11c40c7e824fb
/src/main/java/com/iqy/im/exception/UnAuthenticatedException.java
25ffe650855bdef8627f6548855d8ffb4779dd96
[]
no_license
icecream-code/im-netty
000458f4b1c8e9b09046957eda5120d629000ca8
90daf5ac36815d54db3f770ed74db9c7145ca404
refs/heads/master
2023-06-24T11:31:43.500984
2021-07-30T13:26:51
2021-07-30T13:26:51
391,072,659
2
0
null
null
null
null
UTF-8
Java
false
false
207
java
package com.iqy.im.exception; public class UnAuthenticatedException extends HttpException { public UnAuthenticatedException (int code) { this.code = code; this.httpStatus = 401; } }
[ "1784229301@qq.com" ]
1784229301@qq.com
915bbc4c6a8aeaebccf1caa066815e9c285ae4b4
31ffb347d971038f19cc4de6f9023b9f9d997cf6
/lightframework.data/src/main/java/lightframework/data/biz/AbstractBaseBiz.java
bfd692908363a0eb660b1352a8c74d7d29829174
[]
no_license
shaxianwei/LightFramework
1e3db400e2f879d3cc31fe8cc94ceeafbca78778
be66ecb87d34a4b3f79f5bd67663a5c72ee6aac7
refs/heads/master
2021-01-16T21:50:55.505038
2013-07-26T10:18:03
2013-07-26T10:18:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
509
java
package lightframework.data.biz; import java.util.List; import lightframework.data.Select; /** * * @param <TDAO> * @param <TEntity> * @author Tom Deng */ public abstract class AbstractBaseBiz<TDAO extends Select<TEntity>, TEntity> { private TDAO dao; protected AbstractBaseBiz(TDAO dao) { this.dao = dao; } public TDAO getDAO() { return this.dao; } public List<TEntity> getAll(String... columnNames) { return this.dao.select(columnNames); } }
[ "14068728@qq.com" ]
14068728@qq.com
e937fd461dd888930084b825b3a00db6570ed0cf
2c47066781f0398cfc78c247b3817ef7385a78fa
/compiler/frontend/src/org/jetbrains/jet/config/CompilerConfiguration.java
339eb8e1864b45e580827a97c541612697d06988
[]
no_license
hhariri/kotlin
9e60383961d5ba9e6216b8344f3fb54165262e49
d150bfbce0e2e47d687f39e2fd233ea55b2ccd26
refs/heads/master
2021-01-21T02:11:33.068540
2014-06-20T14:52:30
2014-06-21T08:26:34
21,116,939
1
0
null
null
null
null
UTF-8
Java
false
false
3,996
java
/* * Copyright 2010-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jet.config; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; @SuppressWarnings("unchecked") public class CompilerConfiguration { private final Map<Key, Object> map = new HashMap<Key, Object>(); private boolean readOnly = false; @Nullable public <T> T get(@NotNull CompilerConfigurationKey<T> key) { T data = (T) map.get(key.ideaKey); return data == null ? null : unmodifiable(data); } @NotNull public <T> T get(@NotNull CompilerConfigurationKey<T> key, @NotNull T defaultValue) { T data = (T) map.get(key.ideaKey); return data == null ? defaultValue : unmodifiable(data); } @NotNull public <T> List<T> getList(@NotNull CompilerConfigurationKey<List<T>> key) { List<T> data = (List<T>) map.get(key.ideaKey); if (data == null) { return Collections.emptyList(); } else { return Collections.unmodifiableList(data); } } public <T> void put(@NotNull CompilerConfigurationKey<T> key, @Nullable T value) { checkReadOnly(); map.put(key.ideaKey, value); } public <T> void add(@NotNull CompilerConfigurationKey<List<T>> key, @NotNull T value) { checkReadOnly(); Key<List<T>> ideaKey = key.ideaKey; if (map.get(ideaKey) == null) { map.put(ideaKey, new ArrayList<T>()); } List<T> list = (List<T>) map.get(ideaKey); list.add(value); } public <T> void addAll(@NotNull CompilerConfigurationKey<List<T>> key, @NotNull Collection<T> values) { checkReadOnly(); checkForNullElements(values); Key<List<T>> ideaKey = key.ideaKey; if (map.get(ideaKey) == null) { map.put(ideaKey, new ArrayList<T>()); } List<T> list = (List<T>) map.get(ideaKey); list.addAll(values); } public CompilerConfiguration copy() { CompilerConfiguration copy = new CompilerConfiguration(); copy.map.putAll(map); return copy; } private void checkReadOnly() { if (readOnly) { throw new IllegalStateException("CompilerConfiguration is read-only"); } } public void setReadOnly(boolean readOnly) { if (readOnly != this.readOnly) { checkReadOnly(); this.readOnly = readOnly; } } @NotNull private static <T> T unmodifiable(@NotNull T object) { if (object instanceof List) { return (T) Collections.unmodifiableList((List) object); } else if (object instanceof Map) { return (T) Collections.unmodifiableMap((Map) object); } else if (object instanceof Collection) { return (T) Collections.unmodifiableCollection((Collection) object); } else { return object; } } private static <T> void checkForNullElements(Collection<T> values) { int index = 0; for (T value : values) { if (value == null) { throw new IllegalArgumentException("Element " + index + " is null, while null values in compiler configuration are not allowed"); } index++; } } }
[ "Evgeny.Gerashchenko@jetbrains.com" ]
Evgeny.Gerashchenko@jetbrains.com
50a8e2304ce155406558cca27e64a27a45d184a3
e693a7b318b63323eee669e8b443e076f415ee73
/src/main/java/br/com/consultamedica/utils/JPAUtils.java
880b213b5a4bc366f4603fdba75b84b37d22744c
[]
no_license
davidalmeida14/consultamed
781effe705aee0dfdb224b50a114c5fd1bca6197
8708f7b003f2b0a988568baae94301b228e2e751
refs/heads/master
2023-08-10T12:40:03.953217
2019-07-28T14:29:28
2019-07-28T14:29:28
193,015,393
0
0
null
2023-07-22T08:54:44
2019-06-21T02:18:53
Java
UTF-8
Java
false
false
545
java
package br.com.consultamedica.utils; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class JPAUtils { private static EntityManagerFactory factory; public static EntityManagerFactory getEntityManagerFactory(){ if(factory == null) { factory = Persistence.createEntityManagerFactory(Constantes.PERSISTENCE_UNIT_NAME); return factory; } else { return factory; } } public static void shutDown() { if(factory != null) { factory.close(); } } }
[ "david_almeida_1@hotmail.com" ]
david_almeida_1@hotmail.com
2446c81c30d3ba7bc65e8bdd8c9fb5de9d8a9805
1bf0454e84a36b8929fe400ec801ce2d74039946
/src/riskyspace/model/BuildAble.java
7cc2b335ae1d9bd34b3c5984c8e57edaf3c9d38e
[]
no_license
Z3B0/RiskySpace
b3984296bf27d3da09e795d941ebdf6b6dfa0690
f6ce41bcc3efc06c74c35059572b4fc66b824f43
refs/heads/master
2021-01-18T06:46:56.232000
2012-05-08T16:13:19
2012-05-08T16:13:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
177
java
package riskyspace.model; public interface BuildAble { public int getSupplyCost(); public int getMetalCost(); public int getGasCost(); public int getBuildTime(); }
[ "daniel.augurell@gmail.com" ]
daniel.augurell@gmail.com
5bfba75b14caf850bc90584b36c882244a3a748d
729e5f9084d5bae1d5cb681c7d23dd9eac492fb5
/src/com/generation/Main.java
8da3fd679a745d8103f87393a1df16424b0286aa
[]
no_license
AbbyRT/java-colecciones
f7c9d5fa2669c8d3108eb3613afdfea350f4ae1d
c1bf0315bbc2a5a48473b301714a225224b6bbb7
refs/heads/master
2023-08-12T21:08:28.909386
2021-10-15T02:23:04
2021-10-15T02:23:04
417,343,693
0
0
null
null
null
null
UTF-8
Java
false
false
7,848
java
package com.generation; import java.util.*; public class Main { public static void main(String[] args) { // arreglos: hya que definir el tipo de dato que contendra el arreglo, solo se peude de un tipo //el tamaño del arreglo es estatico, no se puede modificar // String universidades[]; // universidades = new String[5]; //para declararlo en una sola línea: // String universidades[] = new String[5]; //otra forma de inicializar valores: String universidades[]= new String[]{"ITVH", "ULA","UAM","UADM","UNAM"}; // universidades[0] ="ITVH"; // universidades[1]="ULA"; // universidades[2]="UAM"; // universidades[3]="UADM"; // universidades[4]="UNAM"; // universidades[5]="UPN"; // universidades[6]="IPN"; // universidades[7]="TESCO"; //el vector uiversodades sera recorrido con la ayuda de la variable universidad //es similae al foreach de javascript System.out.println("arreglos"); for(String universidad : universidades){ System.out.println(universidad); } System.out.println("--------------------------------"); //colecciones: conjunto de objetos, hay diferentes maneras de almacenarlas, //principalmente 3 formas: array, set y map //set: no puede contener elementos duplicados //Si hay valores repetidos no los toma en cuenta, pero no marca error //conunto de metodoos de set: //hashset: tabla con mejor rendimiento,es la mas rapdia //el orden de los elementos puede variar //se puede inicializar con un tamaño,pero este solo sera el tamaño MINIMO, //por lo que se pueden añadir mas elementos //es el mas rapido //para almacenar numeros:<Integer> Set<String> frutas = new HashSet(4); frutas.add("Manngo"); frutas.add("Fresa"); frutas.add("Pera"); frutas.add("Uva"); frutas.add("Melon"); frutas.add("Lima"); frutas.add("Lima"); //no lo toma en cuenta System.out.println("Set: hashset"); for (String fruta : frutas){ System.out.println(fruta); } System.out.println("--------------------------------"); // // //treeset // //es el mas lento // //ordena los elementos alfabeticamente // //no se le puede establecer un cambio inicial // // Set<String> frutas2 = new TreeSet<>(); frutas2.add("Manngo"); frutas2.add("Fresa"); frutas2.add("Pera"); frutas2.add("Uva"); frutas2.add("Melon"); frutas2.add("Lima"); System.out.println("Set: treeset"); for (String fruta : frutas2){ System.out.println(fruta); } System.out.println("--------------------------------"); // //LinkedHashSet // //almacena los valores en prden de insercion // //si se le puede darun tamaño inicial // Set<String> frutas3 = new LinkedHashSet<>(4); frutas3.add("Manngo"); frutas3.add("Fresa"); frutas3.add("Pera"); frutas3.add("Uva"); frutas3.add("Melon"); frutas3.add("Lima"); System.out.println("Set: LinkedHasSet"); for (String fruta : frutas3){ System.out.println(fruta); } System.out.println("--------------------------------"); // List //acepta elementos duplciados //aparecen los elementos en orden //get: devuelve elemento especficio de la collection, realiza busqueda //es mas lento //tiene mas metodos, puede eliminar lugareso asignar nuevos valors //list es de las mas utilizadas List<String> frutas4 = new ArrayList<>(); frutas4.add("Manngo"); frutas4.add("Fresa"); frutas4.add("Pera"); frutas4.add("Uva"); frutas4.add("Melon"); frutas4.add("Lima"); frutas4.add("Manngo"); System.out.println("List"); for (String fruta : frutas4){ System.out.println(fruta); } System.out.println("--------------------------------"); System.out.println(frutas4.get(3)); //SI no conozco el indice int indice = frutas4.indexOf("Melon"); //busca el indice del elemento, solo del primer elementomque encuentre System.out.println(frutas4.get(indice)); System.out.println("--------------------------------"); //Linkedlist //tiene los mismos metodos que list //tiene una estructura onterna diferente, es una lista doblemente enlazada //esto significa que el elemento sabe que va antes y despues //por ejemplo el elemento fresa sabe que antes va mango y despues peroa //tambien acepta elementos repetidos List<String> frutas5 = new LinkedList<>(); frutas5.add("Manngo"); frutas5.add("Fresa"); frutas5.add("Pera"); frutas5.add("Uva"); frutas5.add("Melon"); frutas5.add("Lima"); frutas5.add("Manngo"); System.out.println("List: linked list"); for (String fruta : frutas5){ System.out.println(fruta); } System.out.println("--------------------------------"); //map - hashmap //trabaja con clave y valor, las asocia //podemos almacenar pares de infromacion //no puede tener claves repetidas //solo puede tener un valor asociado a la vlave //a este tipo de colleccionaes les pueden decir diccionarios //put nos permite colocar claves y valores //las claves tambien pueden ser textto, por ejemplo las palcas de un auto //LAS CLAVES NO SE PUEDEN REPETIR //no garantiza un orden //se recomienda darle un tamaño especifico inicial Map<Integer, String> universidades2 = new HashMap<Integer, String>(); //aqui crea la coleccion vacia universidades2.put(1, "IPN"); universidades2.put(2, "UNAM"); universidades2.put(3, "UAEM"); universidades2.put(4, "UAM"); universidades2.put(5, "TESCO"); System.out.println(universidades2.get(3)); System.out.println("Map: HasMap"); //para recorrer la coleccion: for (Map.Entry<Integer, String> universidad : universidades2.entrySet()) { System.out.println("clave=" + universidad.getKey() + ", valor=" + universidad.getValue()); } System.out.println("--------------------------------"); //tree Map //ordena los daots en funcion de sus valores de la CLAVE //es mas lento que HashMap //interfaz comparable ._. Map<String, String> autos = new TreeMap<String, String>(); autos.put("PLE9945", "FORD"); autos.put("PMK7764", "RENAULT"); autos.put("PMA1359", "VW"); autos.put("GGN3426", "NISSAN"); autos.put("LTU5408", "CHEVROLET"); System.out.println("Map: tree Map"); for (Map.Entry<String, String> auto : autos.entrySet()) { System.out.println("clave=" + auto.getKey() + ", valor=" + auto.getValue()); } System.out.println("--------------------------------"); //LinkedHashMap //almacena las claves en funcion del orden de insercion //se tarda mas que hashmap Map<String, String> autos2 = new LinkedHashMap<String, String>(); autos2.put("PLE9945", "FORD"); autos2.put("PMK7764", "RENAULT"); autos2.put("PMA1359", "VW"); autos2.put("GGN3426", "NISSAN"); autos2.put("LTU5408", "CHEVROLET"); System.out.println("Map: LinkedMap"); for (Map.Entry<String, String> auto : autos2.entrySet()) { System.out.println("clave=" + auto.getKey() + ", valor=" + auto.getValue()); } } }
[ "romerot.abigail@gmail.com" ]
romerot.abigail@gmail.com
c1cc4a28e6b5c3543f6a8178474c9517d80a68b4
69fe13445c4e1c592b94f4d80f3c78cb4e17e1b5
/src/main/java/com/frog/serviceImpl/SysMessageServiceImpl.java
08ef79103a1aaad003a7ef3c023cb6eb8c9a4997
[]
no_license
chenarui/frog-provider
6aacfb23e5d0513a47307f48d89abcda16b86e8d
c7854cfa502bf9fe92fb4b43377df1d9d933907c
refs/heads/master
2020-04-07T22:25:56.931772
2018-11-23T02:43:43
2018-11-23T02:43:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,761
java
package com.frog.serviceImpl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import com.frog.dao.SysMessageMapper; import com.frog.model.SysMessage; import com.frog.service.SysMessageService; public class SysMessageServiceImpl implements SysMessageService{ @Autowired private SysMessageMapper sysMessageMapper; @Override public List<SysMessage> list(Integer page, Integer pageSize, Map<String, Object> params) { // TODO Auto-generated method stub return null; } @Override public long count(Map<String, Object> params) { // TODO Auto-generated method stub return 0; } @Override public SysMessage viewById(int id) { // TODO Auto-generated method stub return null; } @Override public boolean delete(int id) { // TODO Auto-generated method stub return false; } @Override public SysMessage save(SysMessage t) { // TODO Auto-generated method stub return null; } @Override public boolean update(SysMessage t) { // TODO Auto-generated method stub return false; } @Override public String getFilePath(Integer fileid) { // TODO Auto-generated method stub return null; } @Override public List<SysMessage> selectSysMessage() { return sysMessageMapper.selectSysMessage(); } @Override public int insertMessage(SysMessage sysMessage) { return sysMessageMapper.insertMessage(sysMessage); } @Override public List<SysMessage> selectSysMessageByUser(Integer user_id) { return sysMessageMapper.selectSysMessageByUser(user_id); } @Override public int updateAddressType(SysMessage sysMessage) { return sysMessageMapper.updateAddressType(sysMessage); } }
[ "Gracie@windows10.microdone.cn" ]
Gracie@windows10.microdone.cn
e0c2a1fea86f5acbac2d994acc296e06427f9901
a321e24b568db293b4fc7c51312549ce1f05600e
/src/main/java/com/crm/validators/DateValidator.java
077599f19001fff3188b29139ef9f0b10c367d7b
[]
no_license
WissemMliki/Wissem-MLIKI_Module-CRM-Back-End
002bf99fb9d360887d6284b3224d779e83a47af8
b4c5cab9617c2cb853838ba99b3c60bfc85078a4
refs/heads/master
2020-07-13T20:00:13.324950
2019-08-29T11:09:21
2019-08-29T11:09:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
600
java
package com.crm.validators; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import com.crm.clientservice.ClientService; public class DateValidator implements ConstraintValidator<ValidDates, ClientService>{ @Override public void initialize(ValidDates constraintAnnotation) { // TODO Auto-generated method stub } @Override public boolean isValid(ClientService clientService, ConstraintValidatorContext context) { if(clientService.getDateDebut().before(clientService.getDateFin())) { return true; } else return false; } }
[ "wissem.mliki@gmail.com" ]
wissem.mliki@gmail.com
fed0671df8d2459698a0c7a9c7af933c6364ca66
7ea3fee0aabf06186fa5f68c61d0c7d4492db1cf
/app/src/main/java/com/adgvit/iosfusion2017/ForumRecyclerAdapter.java
fd6a392c7fa3d8dd522931c34c1ade93053c8a22
[]
no_license
shashankgutgutia/IOS-FUSION2017
a7b1837bc5bc26d8d766ce940b480fe073af095b
5072e4363cf98913cb00cce36582bef49196f47a
refs/heads/master
2021-01-21T04:25:01.389905
2017-09-09T07:11:00
2017-09-09T07:11:00
101,910,406
0
1
null
2017-09-08T13:36:23
2017-08-30T17:34:57
Java
UTF-8
Java
false
false
1,395
java
package com.adgvit.iosfusion2017; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class ForumRecyclerAdapter extends RecyclerView.Adapter<ForumRecyclerAdapter.MyViewHolder>{ LayoutInflater inflater; List<ForumItem> data = new ArrayList<>(); public ForumRecyclerAdapter(Context context, List<ForumItem> data) { inflater = LayoutInflater.from(context); this.data = data; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.forum_row_layout, parent, false); MyViewHolder holder = new MyViewHolder(view); return holder; } @Override public void onBindViewHolder(MyViewHolder holder, int position) { ForumItem forumItem=data.get(position); holder.doubt.setText(forumItem.question); } @Override public int getItemCount() { return data.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView doubt; public MyViewHolder(View itemView) { super(itemView); doubt = (TextView) itemView.findViewById(R.id.ques); } } }
[ "shashankgutgutia@gmail.com" ]
shashankgutgutia@gmail.com
cf73e0600062b85c60cb01e762b26570e76ad468
d0e38a56306c4182980485e3483931cd9ece8587
/foodie_shop_pojo/src/main/java/net/seehope/foodie_shop/vo/CommentLevelDto.java
d50fb03162107253ac1ba39daf3b54fbb77c043f
[]
no_license
Nathan-Chen-cwj/foodie-shop
a9ca11e21a86f24bd1e6f845e914d033a4e738d2
a1a3342ca8b43d17829cfefe3bdd5c485ab27479
refs/heads/master
2023-04-22T18:52:30.905040
2021-05-04T16:19:25
2021-05-04T16:19:25
341,104,643
0
0
null
null
null
null
UTF-8
Java
false
false
233
java
package net.seehope.foodie_shop.vo; import lombok.Data; /** * @Version 1.0 * @Author NathanChen * @Date 2021/1/31 21:50 */ @Data public class CommentLevelDto { private Integer countsNum; private Integer commentLevel; }
[ "1121369106@qq.com" ]
1121369106@qq.com
31659488d22bbea77bca593a79c9fb487b70d88a
036dbf356ffa6bba65b79565fce6cd9ef8412705
/app/src/main/java/com/example/android/celebrateawesomeness/MainActivity.java
9b06910162926a39e30da8f0745cc115c85d73d0
[]
no_license
codercarly/CelebrateAwesomeness
ace154293ece06529e2d247cb170af2e33cc97e0
a0075e0953327dfe50337da31004923e6ea8150c
refs/heads/master
2021-04-12T07:57:23.311024
2018-08-05T17:50:51
2018-08-05T17:50:51
126,061,980
0
0
null
null
null
null
UTF-8
Java
false
false
353
java
package com.example.android.celebrateawesomeness; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
[ "carlyc@Carlys-MacBook.local" ]
carlyc@Carlys-MacBook.local
6ca4b4551a4d7d8e9824c6a889da0766bf5863d8
8f80ddab3e0988ca3e603a61e256833043c6b9dd
/src/MemberCard.java
411c0fa2ae7eb437197be09d75d95a1ba7fe4cbd
[]
no_license
Zearss/LAP3_assignment2_211_6110450391
3e75c7b45eff99a901a9b9dfa9cac1c95bc5ba43
e34ede376c83d0d519c4b34a3a73cc508e57fb46
refs/heads/main
2023-06-23T11:46:03.333206
2021-07-21T15:09:26
2021-07-21T15:09:26
388,161,723
0
0
null
null
null
null
UTF-8
Java
false
false
1,749
java
public class MemberCard { private String name; private String numberPhone; private double totalMoneyPurchase; private int totalStamp; public MemberCard(String name, String numberPhone) { this.name = name; this.numberPhone = numberPhone; } public MemberCard(String name, String numberPhone, int totalStamp) { this(name, numberPhone); this.totalStamp = totalStamp; } public double addPurchase(double purchase){ totalMoneyPurchase = totalMoneyPurchase+purchase; if (purchase>=50){ double stamp = purchase/50; totalStamp = (int) (totalStamp + Math.floor(stamp)); return totalStamp; } return totalMoneyPurchase; } public boolean userStamp(int stamp){ if (stamp>=totalStamp){ totalStamp = totalStamp - stamp; return true; } return false; } public String getName() { return name; } public String getNumberPhone() { return numberPhone; } public double getTotalMoneyPurchase() { return totalMoneyPurchase; } public int getTotalStamp() { return totalStamp; } public void setTotalMoneyPurchase(double totalMoneyPurchase) { this.totalMoneyPurchase = totalMoneyPurchase; } public void setTotalStamp(int totalStamp) { this.totalStamp = totalStamp; } @Override public String toString() { return "MemberCard{" + "name='" + name + '\'' + ", numberPhone='" + numberPhone + '\'' + ", totalMoneyPurchase=" + totalMoneyPurchase + ", totalStamp=" + totalStamp + '}'; } }
[ "suppasiri@ku.th" ]
suppasiri@ku.th
e5455103ab2aae380db81a7d1639acd49f39208d
30600c69d1e22d9e6fa637b978505381dbf33e6c
/src/simulation/occupant/entiy/Vehicle.java
a09d076a96fc402e29dd9986b2ab3bf08c852c57
[]
no_license
amunkharel/siesta-garden-controller
9d8c343961b209aab7e6c0cfd9a0dcf5c3f7496f
f26b72e91262fb3446e0b0f99d494d94694ed0a1
refs/heads/master
2023-04-28T04:28:42.826110
2021-05-12T17:39:35
2021-05-12T17:39:35
366,510,750
0
0
null
null
null
null
UTF-8
Java
false
false
6,654
java
package simulation.occupant.entiy; import common.Coordinate; import common.Location; import common.device.proxy.VehicleProxy; import common.device.state.VehicleCondition; import simulation.Simulation; import simulation.occupant.base.Occupant; import simulation.occupant.base.OccupantType; import simulation.world.Node; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class Vehicle extends Occupant implements VehicleProxy { private int capacity = Simulation.getInstance().getVehicleCapacity(); private VehicleCondition condition = VehicleCondition.OKAY; private ConcurrentHashMap<Integer,Guest> passengers = new ConcurrentHashMap<>(); private LinkedList<Guest> temp; private AtomicInteger reserved = new AtomicInteger(); private int id = 1; private String name; private FutureTask<Void> currentOperationTask = null; private boolean abortDrive; private boolean isLoading; public Vehicle(String name) { super(null, OccupantType.VEHICLE); reserved.set(0); this.name = name; } @Override public synchronized void enterNode(Occupant occupant) { switch (occupant.getOccupantType()){ case GUEST: Guest guest = (Guest)occupant; passengers.put(guest.getTokenID(),guest); ((Guest)occupant).setVehicle(this); break; default: //do nothing } } int i = 0; public synchronized boolean isFull(){ return reserved.incrementAndGet() > capacity; } public synchronized LinkedList<Integer> getPassengers() { LinkedList<Integer> tokenIDS = new LinkedList<>(); passengers.values().forEach((p) -> tokenIDS.add(p.getTokenID())); return tokenIDS; } public Guest getPassengerRaw(int id) { return passengers.get(id); } public void removeGuests() { passengers.clear(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); passengers.values().forEach((passenger)-> sb.append(passenger.getTokenID()).append("\n")); return "Vehicle" + "\n,coordinate=" +coordinate+ "\npassengers:\n" + sb.toString(); } public VehicleCondition getCondition() { return condition; } public String getName() { return name; } @Override public void drive(Coordinate target,Coordinate previousLocation, boolean isEmergency) { initializeDrive(); startDrive(target,previousLocation,isEmergency); } public void drive(Coordinate target) { initializeDrive(); startDrive(target, null,false); } private void startDrive(Coordinate target,Coordinate previous,boolean isEmergency) { Occupant occupant = this; currentOperationTask = new FutureTask<>(() -> { LinkedList<Coordinate> route = determineRoute(target,previous,isEmergency); abortDrive = false; route.forEach((coordinate)->{ List<Node> path = findPath(this.coordinate, coordinate); for(Node n:path) { if(!this.coordinate.equals(n.getCoordinate())){ world.get(n.getCoordinate()).enterNode(occupant); } occupant.exitNode(); try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if (abortDrive) break; } }); setLoading(true); return null; }); Thread t = new Thread(currentOperationTask); t.setDaemon(true); t.start(); } private LinkedList<Coordinate> determineRoute(Coordinate target,Coordinate previous,boolean isEmergency) { if(this.coordinate.equals(previous)) return new LinkedList<>(); if(previous == null){ LinkedList<Coordinate> route = new LinkedList<>(); route.add(target); return route; } if(Location.getLocation(previous) == Location.EASTSIDE_LOADING_ZONE && isEmergency){ LinkedList<Coordinate> temp = new LinkedList<>(Simulation.getInstance().getPathToWest()); LinkedList<Coordinate> route = new LinkedList<>(); Collections.reverse(temp); boolean add = false; for(Coordinate c:temp){ if(c.equals(Simulation.getInstance().getWestPoint())|| add){ add = true; route.addLast(c); }; } route.addLast(Location.EASTSIDE_LOADING_ZONE.getCoordinate()); return route; } switch (Objects.requireNonNull(Location.getLocation(target))){ case EASTSIDE_LOADING_ZONE: return Simulation.getInstance().getPathToEast(); case WESTSIDE_LOADING_ZONE: return Simulation.getInstance().getPathToWest(); default: LinkedList<Coordinate> route = new LinkedList<>(); route.add(target); return route; } } private void initializeDrive() { abortDrive = true; if(currentOperationTask != null){ try { currentOperationTask.get(); } catch (Exception e) { e.printStackTrace(); } } } public void setLoading(boolean loading) { isLoading = loading; } @Override public Coordinate getCurrentLocation() { return this.coordinate; } @Override public VehicleCondition getCurrentVehicleCondition() { return VehicleCondition.OKAY; } @Override public void lockDoors() { } @Override public void unlockDoors() { } @Override public ConcurrentHashMap<Integer, Integer> readRFIDScanner() { ConcurrentHashMap<Integer,Integer> temp = new ConcurrentHashMap<>(); passengers.forEach((k,v)->temp.put(k,k)); return temp; } public boolean isLoading() { return isLoading; } public ConcurrentHashMap<Integer,Guest> getPassengerMap(){ return passengers; } public void resetReserved() { reserved.set(0); } }
[ "akharel@cs.unm.edu" ]
akharel@cs.unm.edu
8e75a3cde438c9eaf03ca2738a45e9a66a84134c
a2e0d1604ac6b8d33297f4e948d5d73d74c29753
/src/org/yccheok/jstock/engine/currency/CurrencyPair.java
a5979c6a21d269d7f5e3aea05056cbd5c8ee4786
[]
no_license
bearrundr/jstock
eefe7d3c969a3f41378c7751320de78bd1630143
c88dac1ae6eb9460818e0315db895c05883dedcc
refs/heads/master
2020-04-05T23:42:24.906988
2014-12-21T17:14:53
2014-12-21T17:14:53
28,450,719
0
1
null
null
null
null
UTF-8
Java
false
false
1,234
java
/* * JStock - Free Stock Market Software * Copyright (C) 2015 Yan Cheng Cheok <yccheok@yahoo.com> * * This program 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 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.yccheok.jstock.engine.currency; import java.util.Currency; /** * * @author yccheok */ public class CurrencyPair extends org.yccheok.jstock.engine.Pair<Currency, Currency> { public CurrencyPair(Currency from, Currency to) { super(from, to); } public Currency from() { return this.first; } public Currency to() { return this.first; } }
[ "yccheok@yahoo.com" ]
yccheok@yahoo.com
bab9009665c9797af0b0ef5c6b59c95d4f06d1f3
91ef9ed0d581d4383d06a65d927b0536a10e7799
/cs555/FileSystem/node/Controller.java
06486d5e4c7dee3a528de687a63a5b4b784af42d
[]
no_license
skmishra5/Building-A-Distributed-Replicated-And-Fault-Tolerant-File-System
bb76c42e81282c85597419979ab196f3add9a1fa
b8859068b6569e91650dcc5a56e6dbcb0deea7ed
refs/heads/master
2021-08-30T12:49:06.541424
2017-12-18T02:00:04
2017-12-18T02:00:04
114,499,439
0
0
null
null
null
null
UTF-8
Java
false
false
16,071
java
package cs555.FileSystem.node; import java.io.IOException; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Random; import cs555.FileSystem.transport.CommandThread; import cs555.FileSystem.transport.TCPSender; import cs555.FileSystem.transport.TCPServerThread; import cs555.FileSystem.util.DetectionOfFailure; import cs555.FileSystem.wireformats.ErrorCorrFromChunkServerRequest; import cs555.FileSystem.wireformats.ErrorCorrFromChunkServerResponse; import cs555.FileSystem.wireformats.Event; import cs555.FileSystem.wireformats.EventFactory; import cs555.FileSystem.wireformats.FailureDetectionRequest; import cs555.FileSystem.wireformats.NewReplicationMessage; import cs555.FileSystem.wireformats.Protocol; import cs555.FileSystem.wireformats.ReadControllerResponse; import cs555.FileSystem.wireformats.ReadFailedControllerResponse; import cs555.FileSystem.wireformats.RequestMajorHeartbeat; import cs555.FileSystem.wireformats.StoreFileControllerRequest; import cs555.FileSystem.wireformats.StoreFileControllerResponse; public class Controller implements Node{ private int portNumber = -1; private EventFactory eventFactory; private static TCPServerThread server = null; public static ArrayList<String> chunkServers = new ArrayList<String>(); private static HashMap<String, String> fileChunkServerInfo = new HashMap<String, String>(); private static HashMap<String, String> fileMetaDataInfo = new HashMap<String, String>(); private static HashMap<String, Integer> fileChunkCount = new HashMap<String, Integer>(); public static HashMap<String, String> NodeFileList = new HashMap<String, String>(); public static HashMap<String, Long> failureTimeStamp = new HashMap<String, Long>(); public static HashMap<String, Integer> heartBeatCount = new HashMap<String, Integer>(); Random randomNode = new Random(); private CommandThread commandInput; private DetectionOfFailure detectFailure; // Initializing the Controller Node public void Initialize(String[] args) { if(args.length != 1) { System.out.println("Enter Port Number"); return; } portNumber = Integer.parseInt(args[0]); // Initializing Event Factory Singleton Instance eventFactory = EventFactory.getInstance(); eventFactory.setNodeInstance(this); // Initializing the server thread server = new TCPServerThread(portNumber, Controller.class.getSimpleName(), eventFactory); Thread serverThread = new Thread(server); serverThread.start(); commandInput = new CommandThread(1); Thread commandThread = new Thread(commandInput); commandThread.start(); detectFailure = new DetectionOfFailure(this); Thread failureDetectionThread = new Thread(detectFailure); failureDetectionThread.start(); } private void sendChunkServerInformation(String clientIP, int clientPort) { Socket msgSocket = null; int index1 = randomNode.nextInt(chunkServers.size()); int index2 = randomNode.nextInt(chunkServers.size()); while(index2 == index1) { index2 = randomNode.nextInt(chunkServers.size()); } int index3 = randomNode.nextInt(chunkServers.size()); while((index3 == index2)) { index3 = randomNode.nextInt(chunkServers.size()); } while((index3 == index1)) { index3 = randomNode.nextInt(chunkServers.size()); } String info = chunkServers.get(index1) + "#" + chunkServers.get(index2) + "#" + chunkServers.get(index3); // sending response message try { msgSocket = new Socket(clientIP, clientPort); } catch (IOException e) { e.printStackTrace(); }; //sending lookup message try { TCPSender sender = new TCPSender(msgSocket); StoreFileControllerResponse stFlContRes= new StoreFileControllerResponse(); byte[] dataToSend = stFlContRes.storeFileControllerResponse(info); sender.sendData(dataToSend); } catch (IOException e) { e.printStackTrace(); } try { msgSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void sendChunkServerInfoToClient(String clientIP, int clientPort, String fileName, int numSplits) { Socket msgSocket = null; try { msgSocket = new Socket(clientIP, clientPort); } catch (IOException e) { e.printStackTrace(); }; //int numOfChunks = fileChunkCount.get(fileName); for(int i = 1; i <= numSplits; i++) { String chunkFileName = fileName + ".00" + i; String info = chunkFileName + "#" + fileChunkServerInfo.get(chunkFileName).split(",")[0]; try { TCPSender sender = new TCPSender(msgSocket); ReadControllerResponse readContRes= new ReadControllerResponse(); byte[] dataToSend = readContRes.readFileControllerResponse(info); sender.sendData(dataToSend); } catch (IOException e) { e.printStackTrace(); } } try { msgSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void readFailedChunkServerInfoToClient(String clientIP, int clientPort, String information) { String reqFile = information.split("#")[0]; String prevFailedNodeInfo = information.split("#")[1].trim(); String info = ""; int i = 0; // while(i < 3) // { // if(!fileChunkServerInfo.get(reqFile).split(",")[i].equals(prevFailedNodeInfo)) // { // info = reqFile + "#" + fileChunkServerInfo.get(reqFile).split(",")[i]; // break; // } // i++; // } System.out.println("File: " + reqFile); info = reqFile + "#" + fileChunkServerInfo.get(reqFile).split(",")[1]; System.out.println("Inside readFailedChunkServerInfoToClient: " + info); Socket msgSocket = null; try { msgSocket = new Socket(clientIP, clientPort); } catch (IOException e) { e.printStackTrace(); }; try { TCPSender sender = new TCPSender(msgSocket); ReadFailedControllerResponse readFailedContRes= new ReadFailedControllerResponse(); byte[] dataToSend = readFailedContRes.readFailedControllerResponse(info); sender.sendData(dataToSend); } catch (IOException e) { e.printStackTrace(); } try { msgSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void sendOtherReplicaInfoForErrCorr(String chunkServerIP, int chunkServerPort, String fileName) { boolean flag = false; if(fileChunkServerInfo.containsKey(fileName)) { String[] temp = fileChunkServerInfo.get(fileName).split(","); for(String s: temp) { if(!s.equals(chunkServerIP + ":" + chunkServerPort)) { if(!flag){ Socket msgSocket = null; try { msgSocket = new Socket(chunkServerIP, chunkServerPort); } catch (IOException e) { e.printStackTrace(); }; try { TCPSender sender = new TCPSender(msgSocket); ErrorCorrFromChunkServerResponse errCorrFrmChnkServRes= new ErrorCorrFromChunkServerResponse(); byte[] dataToSend = errCorrFrmChnkServRes.errorCorrFromChunkServerResponse(fileName + "#" + s); sender.sendData(dataToSend); flag = true; } catch (IOException e) { e.printStackTrace(); } try { msgSocket.close(); msgSocket = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }} } } } } @Override public void onEvent(Event e) { int messageType = e.getMessageType(); if(messageType == Protocol.STORE_FILE_CONTROLLER_REQUEST) { //Sending 3 chunk server information to client fileChunkCount.put(e.getInfo(), e.getForwardFlag()); sendChunkServerInformation(e.getIPAddress(), e.getListenPortNumber()); } else if(messageType == Protocol.MINOR_HEARTBEAT_MESSAGE) { synchronized(this) { String IPPortCombination = e.getIPAddress() + ":" + e.getListenPortNumber(); System.out.println("Info: " + e.getInfo()); if(heartBeatCount.containsKey(IPPortCombination)) { int value = heartBeatCount.get(IPPortCombination); heartBeatCount.put(IPPortCombination, value+1); } else { heartBeatCount.put(IPPortCombination, 1); // Request a major heart beat Socket msgSocket = null; try { msgSocket = new Socket(InetAddress.getByName(e.getIPAddress()), e.getListenPortNumber()); } catch (IOException e1) { e1.printStackTrace(); }; try { TCPSender sender = new TCPSender(msgSocket); RequestMajorHeartbeat reqMajorHrtBeat= new RequestMajorHeartbeat(); byte[] dataToSend = reqMajorHrtBeat.requestMajorHeartbeat(); sender.sendData(dataToSend); } catch (IOException e2) { e2.printStackTrace(); } try { msgSocket.close(); msgSocket = null; } catch (IOException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } } if(!chunkServers.contains(IPPortCombination)) { chunkServers.add(IPPortCombination); } if((!e.getInfo().trim().equals("NONE")) && (!e.getInfo().trim().equals(""))) { String[] token = e.getInfo().split(","); for(int i = 0; i < token.length; i++) { System.out.println("token0= " + token[i].split("#")[0] + " token1= " + token[i].split("#")[1] + " IPPort= " + IPPortCombination); String info1 = ""; String info2 = ""; if(fileChunkServerInfo.containsKey(token[i].split("#")[0])) { String temp = fileChunkServerInfo.get(token[i].split("#")[0]); if(!temp.contains(IPPortCombination)) { info1 = fileChunkServerInfo.get(token[i].split("#")[0]) + "," + IPPortCombination; fileChunkServerInfo.put(token[i].split("#")[0], info1); } } else { fileChunkServerInfo.put(token[i].split("#")[0], IPPortCombination); } if(fileMetaDataInfo.containsKey(token[i].split("#")[0])) { String temp = fileMetaDataInfo.get(token[i].split("#")[0]); if(!temp.contains(token[i].split("#")[1])) { info2 = fileMetaDataInfo.get(token[i].split("#")[0]) + "," + token[i].split("#")[1]; fileMetaDataInfo.put(token[i].split("#")[0], info2); } } else { fileMetaDataInfo.put(token[i].split("#")[0], token[i].split("#")[1]); } } } } } else if(messageType == Protocol.MAJOR_HEARTBEAT_MESSAGE) { synchronized(this) { String IPPortCombination = e.getIPAddress() + ":" + e.getListenPortNumber(); System.out.println(e.getInfo()); if(!chunkServers.contains(IPPortCombination)) { chunkServers.add(IPPortCombination); } if((!e.getInfo().trim().equals("NONE")) && (!e.getInfo().trim().equals(""))) { String[] token = e.getInfo().split(","); for(int i = 0; i < token.length; i++) { System.out.println("token0= " + token[i].split("#")[0] + " token1= " + token[i].split("#")[1] + " IPPort= " + IPPortCombination); String info1 = ""; String info2 = ""; if(fileChunkServerInfo.containsKey(token[i].split("#")[0])) { String temp = fileChunkServerInfo.get(token[i].split("#")[0]); if(!temp.contains(IPPortCombination)) { info1 = fileChunkServerInfo.get(token[i].split("#")[0]) + "," + IPPortCombination; fileChunkServerInfo.put(token[i].split("#")[0], info1); } } else { fileChunkServerInfo.put(token[i].split("#")[0], IPPortCombination); } if(fileMetaDataInfo.containsKey(token[i].split("#")[0])) { String temp = fileMetaDataInfo.get(token[i].split("#")[0]); if(!temp.contains(token[i].split("#")[1])) { info2 = fileMetaDataInfo.get(token[i].split("#")[0]) + "," + token[i].split("#")[1]; fileMetaDataInfo.put(token[i].split("#")[0], info2); } } else { fileMetaDataInfo.put(token[i].split("#")[0], token[i].split("#")[1]); } } } } } else if(messageType == Protocol.READ_FILE_CONTROLLER_REQUEST) { sendChunkServerInfoToClient(e.getIPAddress(), e.getListenPortNumber(), e.getInfo(), e.getForwardFlag()); } else if(messageType == Protocol.ERROR_CORRECTION_FROM_CHUNKSERVER_REQUEST) { sendOtherReplicaInfoForErrCorr(e.getIPAddress(), e.getListenPortNumber(), e.getInfo()); } else if(messageType == Protocol.READ_FAILED_CONTROLLER_REQUEST) { readFailedChunkServerInfoToClient(e.getIPAddress(), e.getListenPortNumber(), e.getInfo()); } else if(messageType == Protocol.FAILURE_DETECTION_RESPONSE) { Date dte=new Date(); long timestamp = dte.getTime(); failureTimeStamp.put(e.getIPAddress() + ":" + e.getListenPortNumber(), timestamp); NodeFileList.put(e.getIPAddress() + ":" + e.getListenPortNumber(), e.getInfo()); // for(Map.Entry<String, String> entry : NodeFileList.entrySet()) // { // System.out.println(entry.getKey() + "-> " + entry.getValue()); // } } } public void printChunkServers() { for(int i = 0; i < chunkServers.size(); i++) { System.out.println("ChunkServer " + i + "-> " + chunkServers.get(i)); } } public void printFileChunkServerInfo() { for(Map.Entry<String, String> entry : fileChunkServerInfo.entrySet()) { System.out.println(entry.getKey() + "-> " + entry.getValue()); } } public void printFileMetaDataInfo() { for(Map.Entry<String, String> entry : fileMetaDataInfo.entrySet()) { System.out.println(entry.getKey() + "-> " + entry.getValue()); } } public void replicateToANewNodeOnFailure(String IPPortInfo) { String[] failedNodeFileList = NodeFileList.get(IPPortInfo).split(","); for(int i = 0; i < failedNodeFileList.length; i++) { String newReplicaNode = ""; String[] replNodes = fileChunkServerInfo.get(failedNodeFileList[i]).split(","); for(int j = 0; j < chunkServers.size(); j++) { int k = 0; int count = 0; while(k < replNodes.length) { if(!chunkServers.get(j).equals(replNodes[k])) { count++; } k++; } if(count == 3) { newReplicaNode = chunkServers.get(j); break; } } System.out.println("New replica Node: " + i + "->" + newReplicaNode); // Send a message to this new node to store the replica int l = 0; String fromReplicationInfo = ""; while(l < replNodes.length) { if(!IPPortInfo.equals(replNodes[l])) { fromReplicationInfo = replNodes[l]; break; } l++; } Socket msgSocket = null; try { msgSocket = new Socket(InetAddress.getByName(newReplicaNode.split(":")[0]), Integer.parseInt(newReplicaNode.split(":")[1])); } catch (IOException e) { e.printStackTrace(); }; try { TCPSender sender = new TCPSender(msgSocket); NewReplicationMessage newReplMsg= new NewReplicationMessage(); byte[] dataToSend = newReplMsg.newReplicationMessage(failedNodeFileList[i] + "#" + fromReplicationInfo); sender.sendData(dataToSend); } catch (IOException e) { e.printStackTrace(); } try { msgSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Updating the data structures chunkServers.remove(IPPortInfo); String[] failedNodeFileList1 = NodeFileList.get(IPPortInfo).split(","); for(int i = 0; i < failedNodeFileList1.length; i++) { String newList = ""; String[] replNodes = fileChunkServerInfo.get(failedNodeFileList[i]).split(","); int j = 0; while(j < replNodes.length) { if(!replNodes[j].equals(IPPortInfo)) { newList += replNodes[j]; if(j+1 != replNodes.length) newList += ","; } j++; } System.out.println("NewList: " + newList); fileChunkServerInfo.put(failedNodeFileList[i], newList); } NodeFileList.remove(IPPortInfo); } public static void main(String[] args) { Controller controller = new Controller(); // Initialize the Discovery node controller.Initialize(args); } }
[ "sitakanta.mishra@gmail.com" ]
sitakanta.mishra@gmail.com
d6d968239759cb4965553d6a5621ee482050996e
1f29f7842e30d6265fb9dbb302fe9414755e7403
/src/main/java/com/eurodyn/okstra/KonfliktLBPPropertyType.java
a3467d60e7952d63dadedd1d45e93e4696c624d8
[]
no_license
dpapageo/okstra-2018-classes
b4165aea3c84ffafaa434a3a1f8cf0fff58de599
fb908eabc183725be01c9f93d39268bb8e630f59
refs/heads/master
2021-03-26T00:22:28.205974
2020-03-16T09:16:31
2020-03-16T09:16:31
247,657,881
2
0
null
null
null
null
UTF-8
Java
false
false
8,751
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.03.09 at 04:49:50 PM EET // package com.eurodyn.okstra; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Konflikt_LBPPropertyType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Konflikt_LBPPropertyType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence minOccurs="0"&gt; * &lt;element ref="{http://www.okstra.de/okstra/2.018.2}Konflikt_LBP"/&gt; * &lt;/sequence&gt; * &lt;attGroup ref="{http://www.opengis.net/gml/3.2}OwnershipAttributeGroup"/&gt; * &lt;attGroup ref="{http://www.opengis.net/gml/3.2}AssociationAttributeGroup"/&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Konflikt_LBPPropertyType", propOrder = { "konfliktLBP" }) public class KonfliktLBPPropertyType { @XmlElement(name = "Konflikt_LBP") protected KonfliktLBPType konfliktLBP; @XmlAttribute(name = "owns") protected Boolean owns; @XmlAttribute(name = "nilReason") protected List<String> nilReason; @XmlAttribute(name = "remoteSchema", namespace = "http://www.opengis.net/gml/3.2") @XmlSchemaType(name = "anyURI") protected String remoteSchema; @XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink") protected TypeType type; @XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink") protected String href; @XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink") protected String role; @XmlAttribute(name = "arcrole", namespace = "http://www.w3.org/1999/xlink") protected String arcrole; @XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink") protected String attibuteTitle; @XmlAttribute(name = "show", namespace = "http://www.w3.org/1999/xlink") protected ShowType show; @XmlAttribute(name = "actuate", namespace = "http://www.w3.org/1999/xlink") protected ActuateType actuate; /** * Gets the value of the konfliktLBP property. * * @return * possible object is * {@link KonfliktLBPType } * */ public KonfliktLBPType getKonfliktLBP() { return konfliktLBP; } /** * Sets the value of the konfliktLBP property. * * @param value * allowed object is * {@link KonfliktLBPType } * */ public void setKonfliktLBP(KonfliktLBPType value) { this.konfliktLBP = value; } /** * Gets the value of the owns property. * * @return * possible object is * {@link Boolean } * */ public boolean isOwns() { if (owns == null) { return false; } else { return owns; } } /** * Sets the value of the owns property. * * @param value * allowed object is * {@link Boolean } * */ public void setOwns(Boolean value) { this.owns = value; } /** * Gets the value of the nilReason property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nilReason property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNilReason().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNilReason() { if (nilReason == null) { nilReason = new ArrayList<String>(); } return this.nilReason; } /** * Gets the value of the remoteSchema property. * * @return * possible object is * {@link String } * */ public String getRemoteSchema() { return remoteSchema; } /** * Sets the value of the remoteSchema property. * * @param value * allowed object is * {@link String } * */ public void setRemoteSchema(String value) { this.remoteSchema = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link TypeType } * */ public TypeType getType() { if (type == null) { return TypeType.SIMPLE; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link TypeType } * */ public void setType(TypeType value) { this.type = value; } /** * Gets the value of the href property. * * @return * possible object is * {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is * {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the role property. * * @return * possible object is * {@link String } * */ public String getRole() { return role; } /** * Sets the value of the role property. * * @param value * allowed object is * {@link String } * */ public void setRole(String value) { this.role = value; } /** * Gets the value of the arcrole property. * * @return * possible object is * {@link String } * */ public String getArcrole() { return arcrole; } /** * Sets the value of the arcrole property. * * @param value * allowed object is * {@link String } * */ public void setArcrole(String value) { this.arcrole = value; } /** * Gets the value of the attibuteTitle property. * * @return * possible object is * {@link String } * */ public String getAttibuteTitle() { return attibuteTitle; } /** * Sets the value of the attibuteTitle property. * * @param value * allowed object is * {@link String } * */ public void setAttibuteTitle(String value) { this.attibuteTitle = value; } /** * Gets the value of the show property. * * @return * possible object is * {@link ShowType } * */ public ShowType getShow() { return show; } /** * Sets the value of the show property. * * @param value * allowed object is * {@link ShowType } * */ public void setShow(ShowType value) { this.show = value; } /** * Gets the value of the actuate property. * * @return * possible object is * {@link ActuateType } * */ public ActuateType getActuate() { return actuate; } /** * Sets the value of the actuate property. * * @param value * allowed object is * {@link ActuateType } * */ public void setActuate(ActuateType value) { this.actuate = value; } }
[ "Dimitrios.Papageorgiou@eurodyn.com" ]
Dimitrios.Papageorgiou@eurodyn.com
25accbd7eb9cb500b05581baa71ac768d45de1af
05570e35508f2b8f8b41e39b49f3e7a02b922d30
/src/main/omr/check/Result.java
f9a202fa3df995f91c8e0b9ef4d048acab3d36e6
[]
no_license
brennn-rpi/SightReaderPro
98b214a481c9cf893e8341f7335eb9e69812de11
ec235c3f14c90850983e1dcaf687033bc113d221
refs/heads/master
2021-01-15T22:19:33.959618
2016-02-11T22:31:01
2016-02-11T22:31:01
51,522,243
0
0
null
2016-02-11T15:04:36
2016-02-11T15:04:35
null
UTF-8
Java
false
false
1,849
java
//----------------------------------------------------------------------------// // // // R e s u l t // // // //----------------------------------------------------------------------------// // <editor-fold defaultstate="collapsed" desc="hdr"> // // Copyright © Hervé Bitteur and others 2000-2013. All rights reserved. // // This software is released under the GNU General Public License. // // Goto http://kenai.com/projects/audiveris to report bugs or suggestions. // //----------------------------------------------------------------------------// // </editor-fold> package omr.check; /** * Class {@code Result} is the root of all result information stored while * processing processing checks. * * @author Hervé Bitteur */ public abstract class Result { //~ Instance fields -------------------------------------------------------- /** * A readable comment about the result. */ public final String comment; //~ Constructors ----------------------------------------------------------- //--------// // Result // //--------// /** * Creates a new Result object. * * @param comment A description of this result */ public Result (String comment) { this.comment = comment; } //~ Methods ---------------------------------------------------------------- //----------// // toString // //----------// /** * Report a description of this result * * @return A descriptive string */ @Override public String toString () { return comment; } }
[ "brennn@rpi.edu" ]
brennn@rpi.edu
d3ab28c90f15ecb5dec2a5e3dd8161944ead9967
eb035e1341e7fdf983a95526b4eb389658221ea6
/app/src/test/java/net/toracode/moviebuzz/ExampleUnitTest.java
f5fb45235dcd1c62ad0a9da79276c3fb0d49a444
[]
no_license
sayemkcn/md12101046android
795036dab163f6e2bb2751e9e2a8392031ccbffa
0b8ce7251c4d78b43cbb6ae3d63de34fddb3c373
refs/heads/master
2021-07-13T22:53:27.174776
2017-10-19T08:01:22
2017-10-19T08:01:22
107,515,885
0
0
null
2017-10-19T08:01:23
2017-10-19T07:58:51
Java
UTF-8
Java
false
false
315
java
package net.toracode.moviebuzz; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "sayemkcn@gmail.com" ]
sayemkcn@gmail.com
6c0b192f794a1c89e92891a9e38e3d3555840109
05402fc0ffd11a84bb9619152d2a28f1b2e10047
/fase3/ine5409/programasEmJava/metodosDeQuebra/modelo/MetodoDaFalsaPosicao.java
0ce4dfaaa12f5e2c2e8ceae539331ca239285879
[]
no_license
grazipauluka/cienciasDaComputacaoUfsc
61c14d724e6852529e5d8b0a576be819a1a1547d
13357b174f9d520874514194efd446747e11be5b
refs/heads/master
2023-07-24T12:45:42.635201
2015-12-09T20:42:27
2015-12-09T20:42:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,023
java
package modelo; public class MetodoDaFalsaPosicao { private static final double ZERO = 0.0; public static double calcular(double a, double b, double e) { double fa = f(a); double fb = f(b); double xx = (a-fa*(b-a)/(fb-fa))*10; if (verificarSeTemMesmoSinal(fa, fb)) { return Double.NaN; } double erro = Math.abs(a-b); while (erro >= e) { double xx0 = xx; xx = a-fa*(b-a)/(fb-fa); double fxx = f(xx); if (fxx == ZERO) { return xx; } System.out.printf("%.10f %.10f %.10f %.10f %.10f %.10f %.11f\n", a, xx, b, fa, fxx, fb, erro); if (verificarSeTemMesmoSinal(fa, fxx)) { a = xx; fa = fxx; } else { b = xx; fb = fxx; } erro = Math.abs(xx-xx0); } return xx; } private static double f(double x) { double ln = Math.log(x); double elevadoLn = Math.pow(ln, x); return x-elevadoLn; } private static boolean verificarSeTemMesmoSinal(double a, double b) { return (a > ZERO && b > ZERO) || (a < ZERO && b < ZERO); } }
[ "lucas@dominiol.com.br" ]
lucas@dominiol.com.br
1fed8ff6ff42f9ac0fde838781bab7d2492d9e7a
4303c062f90dfd5381dfbd5272edbb88c7bf7d28
/app/src/main/java/nl/vanrsmln/wilkin/hci2020/models/orders/FoodItem.java
4566aa15310529e834c57f109d205e72dcc3f333
[]
no_license
Siarl/hci-project-2020-VU
b5cadac42c6a3bfeb9465330075299b69b0e6efa
dd526856224b0fc2317e21e7a31e8be109b7b29b
refs/heads/master
2022-10-26T18:27:12.692395
2020-06-16T21:47:17
2020-06-16T21:47:17
271,506,757
1
0
null
null
null
null
UTF-8
Java
false
false
578
java
package nl.vanrsmln.wilkin.hci2020.models.orders; import java.io.Serializable; public class FoodItem implements Serializable { private String name; private String description; private int price; // in cents public FoodItem(String name, String description, int price) { this.name = name; this.description = description; this.price = price; } public String getName() { return name; } public String getDescription() { return description; } public int getPrice() { return price; } }
[ "w.s.roosmalen@gmail.com" ]
w.s.roosmalen@gmail.com
c27de3eef8806a117d4660617446fd078f887d32
8e5bbc35328ef18589254c5113d83339f6e37fae
/src/test/java/de/pdbm/janki/core/LoggerTest.java
a0c897faa0a3be03d0f6d7528473948a430f0aeb
[ "MIT" ]
permissive
BerndMuller/JAnki
da92f7c314fb80cd69a38432cb530113b4b1b2ab
d440d00b8e2b138ffa150f52a63af545dd6e9b43
refs/heads/master
2023-02-17T23:09:25.268126
2021-01-13T20:12:21
2021-01-13T20:12:21
115,536,860
7
0
null
null
null
null
UTF-8
Java
false
false
884
java
package de.pdbm.janki.core; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; import org.junit.Test; import de.pdbm.janki.core.LogType; import de.pdbm.janki.core.Logger; public class LoggerTest { @Test public void test() throws IOException { Logger.switchLogTypeOn(LogType.DEVICE_INITIALIZATION); Path path = Paths.get(Logger.LOG_FILE_NAME); long numberOfLines1= Files.lines(path).count(); Logger.log(LogType.DEVICE_DISCOVERY, "write some text"); long numberOfLines2= Files.lines(path).count(); Assert.assertSame("must be same number of lines", numberOfLines1, numberOfLines2); Logger.log(LogType.DEVICE_INITIALIZATION, "write some text"); long numberOfLines3= Files.lines(path).count(); Assert.assertSame("must be one more line", numberOfLines2 + 1, numberOfLines3); } }
[ "bernd.mueller@ostfalia.de" ]
bernd.mueller@ostfalia.de
241c674bc68ef576b20ed476af3189d90c48e362
327aacba9454b6f8e7f2475cca5e50e715087d35
/src/vn/its/Java8_05_DefaultMethods.java
2949ea08270fbba85d04599377f0e3f165f9d22b
[]
no_license
tuannt39-study/study-java8
4727d6ec10ee9d1aa34e79a17333da7abdf1527a
95a258289e675e37aa4b4409bb028ceb6b127444
refs/heads/master
2020-03-22T23:10:28.268062
2018-07-13T07:55:34
2018-07-13T07:55:34
140,694,199
0
0
null
null
null
null
UTF-8
Java
false
false
686
java
package vn.its; public class Java8_05_DefaultMethods { public static void main(String[] args) { Vehicle vehicle = new Car(); vehicle.print(); } } interface Vehicle { default void print() { System.out.println("I am a vehicle!"); } static void blowHorn() { System.out.println("Blowing horn!!!"); } } interface FourWheeler { default void print() { System.out.println("I am a four wheeler!"); } } class Car implements Vehicle, FourWheeler { public void print() { Vehicle.super.print(); FourWheeler.super.print(); Vehicle.blowHorn(); System.out.println("I am a car!"); } }
[ "tuannt39@gmail.com" ]
tuannt39@gmail.com
14dac95b80e661b474c3c1a1e114699b9299fe5b
92ebd000c24b0cffbe562920f45cfd8ffad449de
/JAwesomeBase/src/math/ComplexMath.java
93ec126fed97de47fc1860d1a2aebbe531d7cef3
[ "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mokacao/JAwesomeEngine
9977e73dd3f49fcd0b921a6addc2e29434f2ede2
f2f6343f797a4d0998c68afcc0d6ba2b05c352b6
refs/heads/master
2020-12-27T15:37:54.557705
2015-11-25T16:59:31
2015-11-25T16:59:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,180
java
package math; import quaternion.Complex; import quaternion.Complexd; import quaternion.Complexf; import vector.Vector2; import vector.Vector2d; import vector.Vector2f; /** * Applies mathematical operations on complex numbers. * * @author Oliver Schall * */ public class ComplexMath { private static final float thresholdValue = 0.99f; public static Complexd addition(Complex c1, Complex c2) { return new Complexd(c1.getReal() + c2.getReal(), c1.getImaginary() + c2.getImaginary()); } public static Complexf addition(Complexf c1, Complexf c2) { return new Complexf(c1.getRealf() + c2.getRealf(), c1.getImaginaryf() + c2.getImaginaryf()); } public static Complexd conjugate(Complex c) { return new Complexd(c.getReal(), -c.getImaginary()); } public static Complexf conjugate(Complexf c) { return new Complexf(c.getRealf(), -c.getImaginaryf()); } public static double dotproduct(Complex v1, Complex v2) { return v1.getReal() * v2.getReal() + v1.getImaginary() * v2.getImaginary(); } public static float dotproduct(Complexf v1, Complexf v2) { return v1.getRealf() * v2.getRealf() + v1.getImaginaryf() * v2.getImaginaryf(); } public static Complexd negate(Complex c) { return new Complexd(-c.getReal(), -c.getImaginary()); } public static Complexf negate(Complexf c) { return new Complexf(-c.getRealf(), -c.getImaginaryf()); } public static Complexd invert(Complex c) { Complexd conj = conjugate(c); double mag = conj.magnitudeSquared(); if (mag != 0) conj.scale(1 / mag); return conj; } public static Complexf invert(Complexf c) { Complexf conj = conjugate(c); float mag = (float) conj.magnitudeSquared(); if (mag != 0) conj.scale(1 / mag); return conj; } public static Complexd multiplication(Complex c1, Complex c2) { return new Complexd(c1.getReal() * c2.getReal() - c1.getImaginary() * c2.getImaginary(), c1.getReal() * c2.getImaginary() + c1.getImaginary() * c2.getReal()); } public static Complexf multiplication(Complexf c1, Complexf c2) { return new Complexf(c1.getRealf() * c2.getRealf() - c1.getImaginaryf() * c2.getImaginaryf(), c1.getRealf() * c2.getImaginaryf() + c1.getImaginaryf() * c2.getRealf()); } public static Complexd normalize(Complex c) { double length = c.magnitude(); return new Complexd(c.getReal() / length, c.getImaginary() / length); } public static Complexf normalize(Complexf c) { float length = (float) c.magnitude(); return new Complexf(c.getRealf() / length, c.getImaginaryf() / length); } public static Complexd scale(Complex c, double scale) { return new Complexd(c.getReal() * scale, c.getImaginary() * scale); } public static Complexf scale(Complexf c, float scale) { return new Complexf(c.getRealf() * scale, c.getImaginaryf() * scale); } public static Complexd substraction(Complex c1, Complex c2) { return new Complexd(c1.getReal() - c2.getReal(), c1.getImaginary() - c2.getImaginary()); } public static Complexf substraction(Complexf c1, Complexf c2) { return new Complexf(c1.getRealf() - c2.getRealf(), c1.getImaginaryf() - c2.getImaginaryf()); } public static Complexd lerp(Complex q1, Complex q2, double t) { double oneMt = 1 - t; Complexd result = new Complexd(q1.getReal() * oneMt + q2.getReal() * t, q1.getImaginary() * oneMt + q2.getImaginary() * t); result.normalize(); return result; } public static Complexf lerp(Complexf q1, Complexf q2, float t) { float oneMt = 1 - t; Complexf result = new Complexf(q1.getReal() * oneMt + q2.getReal() * t, q1.getImaginary() * oneMt + q2.getImaginary() * t); result.normalize(); return result; } // public static Complexd slerp(Complex q1, Complex q2, double t) { // DIFFERENT FROM QUATERNIONS // } // // public static Complexf slerp(Complexf q1, Complexf q2, float t) { // // } public static Complexd slerpNoInvert(Complex q1, Complex q2, double t) { double dot = dotproduct(q1, q2); if (dot > -thresholdValue && dot < thresholdValue) { double angle = Math.acos(dot); double sina = Math.sin(angle); double sinat = Math.sin(angle * t); double sinaomt = Math.sin(angle * (1 - t)); return new Complexd((q1.getReal() * sinaomt + q2.getReal() * sinat) / sina, (q1.getImaginary() * sinaomt + q2.getImaginary() * sinat) / sina); } return lerp(q1, q2, t); } public static Complexf slerpNoInvert(Complexf q1, Complexf q2, float t) { float dot = dotproduct(q1, q2); if (dot > -thresholdValue && dot < thresholdValue) { float angle = (float) Math.acos(dot); float sina = (float) Math.sin(angle); float sinat = (float) Math.sin(angle * t); float sinaomt = (float) Math.sin(angle * (1 - t)); return new Complexf((q1.getReal() * sinaomt + q2.getReal() * sinat) / sina, (q1.getImaginary() * sinaomt + q2.getImaginary() * sinat) / sina); } return lerp(q1, q2, t); } public static Complexd squad(Complex q1, Complex q2, Complex q3, Complex q4, double t) { Complex a = slerpNoInvert(q1, q2, t); Complex b = slerpNoInvert(q3, q4, t); return slerpNoInvert(a, b, 2 * t * (1 - t)); } public static Complexf squad(Complexf q1, Complexf q2, Complexf q3, Complexf q4, float t) { Complexf a = slerpNoInvert(q1, q2, t); Complexf b = slerpNoInvert(q3, q4, t); return slerpNoInvert(a, b, 2 * t * (1 - t)); } public static Vector2 transform(Complex c, Vector2 v) { return new Vector2d(v.getX() * c.getReal() + v.getY() * c.getImaginary(), v.getX() * -c.getImaginary() + v.getY() * c.getReal()); } public static Vector2f transform(Complexf c, Vector2f v) { return new Vector2f(v.getXf() * c.getRealf() + v.getYf() * c.getImaginaryf(), v.getXf() * -c.getImaginaryf() + v.getYf() * c.getRealf()); // return new Vector2f( // (1 - 2 * c.getImaginaryf() * c.getImaginaryf()) * v.getXf() // + (-2 * c.getImaginaryf() * c.getRealf()) * v.getYf(), // (2 * c.getImaginaryf() * c.getRealf()) * v.getXf() // + (1 - 2 * c.getImaginaryf() * c.getImaginaryf()) * v.getYf()); } }
[ "oliverschall22@googlemail.com" ]
oliverschall22@googlemail.com
e513b9cf013ef820dea87ed6a3f84cf5f8e6cce1
48c6e9cf78f781d66e4d470844d4f222b8bce6d5
/library/src/main/java/com/shizhefei/view/multitype/ItemViewProviderSet.java
81140530c77aff4389df8ed327ae6bdfb631487f
[ "Apache-2.0" ]
permissive
zhufengi/MultiTypeView
7f98984b8b46ea7569a3e7b6c1a559fe9c7a5e1f
dbfdb90dd8008cb184391249c43e4b8f7c4eeb39
refs/heads/master
2021-01-22T22:07:45.658435
2016-08-12T15:54:10
2016-08-12T15:54:10
65,565,925
1
0
null
2016-08-12T16:06:05
2016-08-12T16:06:04
null
UTF-8
Java
false
false
2,017
java
package com.shizhefei.view.multitype; import java.util.Arrays; import java.util.List; /** * DATA数据类型的imteView提供者集合 * Created by LuckyJayce on 2016/8/7. */ public abstract class ItemViewProviderSet<DATA> { protected List<ItemViewProvider<DATA>> itemProviders; private int providerType; public ItemViewProviderSet(ItemViewProvider<DATA> provider1) { this(Arrays.asList(provider1)); } public ItemViewProviderSet(ItemViewProvider<DATA> provider1, ItemViewProvider<DATA> provider2) { this(Arrays.asList(provider1, provider2)); } public ItemViewProviderSet(ItemViewProvider<DATA> provider1, ItemViewProvider<DATA> provider2, ItemViewProvider<DATA> provider3) { this(Arrays.asList(provider1, provider2, provider3)); } public ItemViewProviderSet(ItemViewProvider<DATA> provider1, ItemViewProvider<DATA> provider2, ItemViewProvider<DATA> provider3, ItemViewProvider<DATA> provider4) { this(Arrays.asList(provider1, provider2, provider3, provider4)); } public ItemViewProviderSet(ItemViewProvider<DATA>[] providers) { this(Arrays.asList(providers)); } public ItemViewProviderSet(List<ItemViewProvider<DATA>> itemProviders) { this.itemProviders = itemProviders; } public void setProviderType(int providerType) { this.providerType = providerType; } public int getProviderType(int index) { return providerType + index; } public ItemViewProvider<DATA> getItemProvider(int index) { return itemProviders.get(index); } public int size() { return itemProviders.size(); } protected abstract int selectIndex(DATA data); public final int select(DATA data) { int index = selectIndex(data); if (index < 0 || index > itemProviders.size() - 1) { throw new RuntimeException("selectIndex 的方法越界 selectIndex:" + index + " size:" + itemProviders.size()); } return index; } }
[ "794629068@qq.com" ]
794629068@qq.com
95fec5e43e11dababdfee1191a9593fe039a4d19
9b01ffa3db998c4bca312fd28aa977f370c212e4
/app/src/streamD/java/com/loki/singlemoduleapp/stub/SampleClass6863.java
91e449b94badeeec0d19fed28e6422d49c3a368f
[]
no_license
SergiiGrechukha/SingleModuleApp
932488a197cb0936785caf0e73f592ceaa842f46
b7fefea9f83fd55dbbb96b506c931cc530a4818a
refs/heads/master
2022-05-13T17:15:21.445747
2017-07-30T09:55:36
2017-07-30T09:56:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
281
java
package com.loki.singlemoduleapp.stub; public class SampleClass6863 { private SampleClass6864 sampleClass; public SampleClass6863(){ sampleClass = new SampleClass6864(); } public String getClassName() { return sampleClass.getClassName(); } }
[ "sergey.grechukha@gmail.com" ]
sergey.grechukha@gmail.com
23f20ba249e1db7fbcffce512004b4eef60e261d
d93ce3950a3c805cd2a5b32e09ed8341a0ff9bbd
/md-sal/model/model-flow-base/src/main/yang-gen-sal/org/opendaylight/yang/gen/v1/urn/opendaylight/model/match/types/rev131026/match/layer/_3/match/TunnelIpv4Match.java
661a69bf6e0c79b14804aa897decda4f2ef68326
[]
no_license
ycymio/opendaylight-adsal-controller
6247d6d4b2a11718932528f4873dc90844f6145d
c3d5164e990e5f95faf02594646c164c66759a23
refs/heads/master
2021-01-11T09:05:36.364505
2016-12-26T02:40:46
2016-12-26T02:40:46
77,222,077
0
0
null
null
null
null
UTF-8
Java
false
false
1,403
java
package org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Layer3Match; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.TunnelIpv4MatchFields; import org.opendaylight.yangtools.yang.binding.Augmentable; /** * <p>This class represents the following YANG schema fragment defined in module <b>opendaylight-match-types</b> * <br />(Source path: <i>META-INF\yang\opendaylight-match-types.yang</i>): * <pre> * case tunnel-ipv4-match { * leaf tunnel-ipv4-source { * type ipv4-prefix; * } * leaf tunnel-ipv4-destination { * type ipv4-prefix; * } * } * </pre> * The schema path to identify an instance is * <i>opendaylight-match-types/match/layer-3-match/tunnel-ipv4-match</i> */ public interface TunnelIpv4Match extends DataObject, Augmentable<org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.TunnelIpv4Match>, TunnelIpv4MatchFields, Layer3Match { public static final QName QNAME = org.opendaylight.yangtools.yang.common.QName.create("urn:opendaylight:model:match:types","2013-10-26","tunnel-ipv4-match");; }
[ "ycymio@gmail.com" ]
ycymio@gmail.com
4861e5ffa5140fa86dca4b3a2a9db50453b46985
6d07091a43429595973b7875196f56c659903687
/CrossApp/proj.android/src/org/CrossApp/lib/CrossAppTextField.java
cbbed41f1ced623f5941ace1cfb20ae0b0bb9e28
[]
no_license
ceowufan/nano-CrossApp
63edca6cad2f75f3b0c2eaa008d2bf633f12f764
087dcae9625c5e89bfee7447c057cde35ae9c87a
refs/heads/master
2020-12-24T08:10:20.148476
2016-11-04T09:07:19
2016-11-04T09:07:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
24,483
java
package org.CrossApp.lib; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import android.R.bool; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Rect; import android.os.Handler; import android.os.Looper; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewTreeObserver; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView.OnEditorActionListener; @SuppressLint("UseSparseArrays") public class CrossAppTextField { private EditText textField = null; private static FrameLayout layout = null; private static CrossAppActivity context = null; private static Handler handler = null; private static HashMap<Integer, CrossAppTextField> dict = null; private int mykey = -1; private ByteBuffer imageData = null; private Bitmap bmp = null; private Button clearButton = null; private int keyboardheight = 0; private int keyboardheightTemp = 0; private int leftMargin = 10; private int rightMargin = 10; private int inputType = InputType.TYPE_CLASS_TEXT; private int fontSize = 20; private String placeHolder = ""; private int placeHolderColor = Color.GRAY; private String textFieldText = ""; private int textFieldTextColor = Color.BLACK; private int contentSizeW = 800; private int contentSizeH = 200; private boolean secureTextEntry = false; private boolean showClearButton = false; private int keyBoardReturnType = EditorInfo.IME_ACTION_DONE; private int gravity = (Gravity.LEFT | Gravity.CENTER_VERTICAL); private TextWatcher textWatcher = null; private OnEditorActionListener onEditorActionListener = null; private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = null; private boolean isSetText = false; private String beforeTextString = ""; private int selection = 0; private boolean isFocus = false; private boolean isFocusAction = false; public static void initWithHandler() { if (handler == null) { handler = new Handler(Looper.myLooper()); } if (dict == null) { dict = new HashMap<Integer, CrossAppTextField>(); } if (context == null) { context = (CrossAppActivity)CrossAppActivity.getContext(); } if (layout == null) { layout = CrossAppActivity.getFrameLayout(); } } public static void reload() { handler = new Handler(Looper.myLooper()); context = (CrossAppActivity)CrossAppActivity.getContext(); layout = CrossAppActivity.getFrameLayout(); Set<Integer> keys = (Set<Integer>) dict.keySet() ; Iterator<Integer> iterator = keys.iterator() ; while (iterator.hasNext()) { Integer key = iterator.next(); CrossAppTextField textField = dict.get(key); textField.initWithTextField(key); } } public static boolean isShowKeyboard() { boolean showKeyboard = false; Iterator<Entry<Integer, CrossAppTextField>> iter = dict.entrySet().iterator(); while (iter.hasNext()) { HashMap.Entry entry = (HashMap.Entry) iter.next(); CrossAppTextField val = (CrossAppTextField)entry.getValue(); if (val.textField.isFocused()) { showKeyboard = true; break; } } return showKeyboard; } //keyBoard return call back private static native void keyBoardReturnCallBack(int key); private static native boolean textChange(int key,String before,String change,int arg0,int arg1); private static native void didTextChanged(int key); private static native void text(int key, byte[] text, int lenght); public void init(int key) { mykey = key; context.runOnUiThread(new Runnable() { @Override public void run() { initWithTextField(mykey); } }); } //keyboard height private static native void keyBoardHeightReturn(int key,int height); private static native void resignFirstResponder(int key); public int getKeyBoardHeight() { onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // TODO Auto-generated method stub Rect r = new Rect(); layout.getWindowVisibleDisplayFrame(r); int screenHeight = layout.getRootView().getHeight(); keyboardheightTemp = screenHeight- r.bottom; if (keyboardheightTemp!=keyboardheight) { context.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if (keyboardheightTemp < 1 && isFocus == true) { //hide isFocus = false; context.runOnGLThread(new Runnable() { @Override public void run() { resignFirstResponder(mykey); } }); } // if (keyboardheight<1) { // //show // Log.d("android", "show board"); // } // Log.d("android", "call c++"); //keyBoardReturn if (isFocusAction) { context.runOnGLThread(new Runnable() { @Override public void run() { keyBoardHeightReturn(mykey, keyboardheightTemp); } }); isFocusAction = false; } } }); } keyboardheight = keyboardheightTemp; } }; layout.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener); return keyboardheight; } public void setFontSize(final int size) { context.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub fontSize = size; textField.setTextSize(size); } }); } //placeholder text public void setTextFieldPlacHolder(final String text) { context.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub placeHolder = text; textField.setHint(text); } }); } public void setTextFieldText(final String text) { context.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub isSetText = true; textFieldText = text; textField.setText(text); isSetText = false; } }); } //placeholder color public void setTextFieldPlacHolderColor(final int color) { context.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub placeHolderColor = color; textField.setHintTextColor(color); } }); } //textfield color public void setTextFieldTextColor(final int color) { context.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub textFieldTextColor = color; textField.setTextColor(color); } }); } //keyboard type public void setKeyBoardType(final int type) { context.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub switch (type) { case 0: //default inputType = InputType.TYPE_CLASS_TEXT; break; case 1: //NumbersAndPunctuation inputType = InputType.TYPE_NUMBER_VARIATION_NORMAL; break; case 2: //URL inputType = InputType.TYPE_TEXT_VARIATION_URI; break; case 3: //NumberPad inputType = InputType.TYPE_CLASS_NUMBER; break; case 4: //PhonePad inputType = InputType.TYPE_CLASS_PHONE; break; case 5: //NamePhonePad inputType = InputType.TYPE_TEXT_VARIATION_PERSON_NAME; break; case 6: //EmailAddress inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS; break; default: break; } textField.setInputType(inputType); } }); } //textField Algin public void setTextFieldAlgin(final int var) { context.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub switch (var) { case 0: //center gravity = (Gravity.LEFT | Gravity.CENTER_VERTICAL); break; case 1: //left gravity = (Gravity.CENTER | Gravity.CENTER_VERTICAL); break; case 2: //right gravity = (Gravity.RIGHT | Gravity.CENTER_VERTICAL); break; default: break; } textField.setGravity(gravity); } }); } //text field return type public void setKeyBoardReturnType(final int type) { context.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub String string = type + ""; Log.d("android", string); switch (type) { case 0: keyBoardReturnType = EditorInfo.IME_ACTION_DONE; break; case 1: keyBoardReturnType = EditorInfo.IME_ACTION_GO; break; case 2: keyBoardReturnType = EditorInfo.IME_ACTION_NEXT; break; case 3: keyBoardReturnType = EditorInfo.IME_ACTION_SEARCH; break; case 4: keyBoardReturnType = EditorInfo.IME_ACTION_SEND; break; default: keyBoardReturnType = EditorInfo.IME_ACTION_DONE; break; } textField.setImeOptions(keyBoardReturnType); } }); } //margins right length public void setMarginsDis(final int left,final int right,final int top,final int bottom) { leftMargin = left; rightMargin = right; context.runOnUiThread(new Runnable() { @Override public void run() { textField.setPadding(left, 0, right, 0); } }); } //margins left image public void setMarginLeftImage(final String filePath) { context.runOnUiThread(new Runnable() { @Override public void run() { } }); } //margins right image public void setMarginRightImage(final String filePath) { context.runOnUiThread(new Runnable() { @Override public void run() { } }); } //clearButton public void showClearButton() { context.runOnUiThread(new Runnable() { @Override public void run() { showClearButton = true; clearButton = new Button(context); clearButton.setBackgroundColor(0); // clearButton.setHighlightColor(Color.YELLOW); FrameLayout.LayoutParams btnParams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); btnParams.width = 20; btnParams.height = 20; btnParams.rightMargin = -1000; btnParams.topMargin = -1000; layout.addView(clearButton, btnParams) ; clearButton.setVisibility(View.GONE); clearButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { textField.setText(""); } }); } }); } public void setTextFieldPoint(final int x, final int y) { context.runOnUiThread(new Runnable() { @Override public void run() { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)textField.getLayoutParams(); params.leftMargin = x; params.topMargin = y; textField.setLayoutParams(params); if (clearButton != null) { FrameLayout.LayoutParams btnParams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); btnParams.width = params.height; btnParams.height = params.height; btnParams.leftMargin = params.leftMargin + params.width - btnParams.width; btnParams.topMargin = params.topMargin; clearButton.setLayoutParams(btnParams); } } }); } public void setTextFieldSize(final int width, final int height) { contentSizeW = width; contentSizeH = height; context.runOnUiThread(new Runnable() { @Override public void run() { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)textField.getLayoutParams(); params.width = contentSizeW; params.height = contentSizeH; textField.setLayoutParams(params); TimerTask task = new TimerTask() { public void run() { getImage(); } }; Timer timer = new Timer(); timer.schedule(task, (long) 100); } }); } public void setSecureTextEntry(int var) { if (var == 0) { secureTextEntry = false; context.runOnUiThread(new Runnable() { @Override public void run() { textField.setInputType(inputType); } }); } else { secureTextEntry = true; context.runOnUiThread(new Runnable() { @Override public void run() { if (inputType == InputType.TYPE_CLASS_NUMBER) { textField.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD); } else { textField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } }); } } private static native void onByte(int key, byte[] buf, int wdith, int height); public void getImage() { context.runOnUiThread(new Runnable() { @Override public void run() { bmp = textField.getDrawingCache(); if (bmp != null && imageData == null) { imageData = ByteBuffer.allocate(bmp.getRowBytes() * bmp.getHeight()); bmp.copyPixelsToBuffer(imageData); context.runOnGLThread(new Runnable() { @Override public void run() { onByte(mykey, imageData.array(), bmp.getWidth(), bmp.getHeight()); imageData = null; } }); } } }); } private static native void hideImageView(int key); public void becomeFirstResponder() { CrossAppActivity.setSingleTextField(this); context.runOnUiThread(new Runnable() { @Override public void run() { isFocus = true; isFocusAction = true; //show textField.requestFocus(); Editable etext = textField.getText(); textField.setSelection(etext.length()); TimerTask task = new TimerTask() { public void run() { if (CrossAppTextField.isShowKeyboard() || CrossAppTextView.isShowKeyboard()) { InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(textField, 0); } } }; Timer timer = new Timer(); timer.schedule(task, (long) 20); if (clearButton != null) { clearButton.setVisibility(View.VISIBLE); textField.setPadding(leftMargin, 0, rightMargin, 0); } context.runOnGLThread(new Runnable() { @Override public void run() { hideImageView(mykey); } }); } }); } public void resignFirstResponder() { CrossAppActivity.setSingleTextField(null); context.runOnUiThread(new Runnable() { @Override public void run() { isFocus = false; isFocusAction = true; //show if (clearButton != null) { clearButton.setVisibility(View.GONE); textField.setPadding(leftMargin, 0, 10, 0); } textField.clearFocus(); TimerTask task = new TimerTask() { public void run() { if (!CrossAppTextField.isShowKeyboard() && !CrossAppTextView.isShowKeyboard()) { InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(textField.getWindowToken(), 0); } } }; Timer timer = new Timer(); timer.schedule(task, (long) 20); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)textField.getLayoutParams(); params.leftMargin = -10000; params.topMargin = 0; textField.setLayoutParams(params); bmp = textField.getDrawingCache(); if (bmp != null && imageData == null) { imageData = ByteBuffer.allocate(bmp.getRowBytes() * bmp.getHeight()); bmp.copyPixelsToBuffer(imageData); context.runOnGLThread(new Runnable() { @Override public void run() { onByte(mykey, imageData.array(), bmp.getWidth(), bmp.getHeight()); imageData = null; } }); } } }); } public void setMaxLenght(final int var) { context.runOnUiThread(new Runnable() { @Override public void run() { textField.setFilters(new InputFilter[]{new InputFilter.LengthFilter(var)}); } }); } public void removeThis() { textField.removeTextChangedListener(textWatcher); layout.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener); layout.removeView(textField); } static public CrossAppTextField getTextField(final int key) { CrossAppTextField var = dict.get(key); if (var != null) return var; return null; } static public void createTextField(final int key) { CrossAppTextField text = new CrossAppTextField(); dict.put(key, text); text.init(key); } static public void removeTextField(final int key) { final CrossAppTextField var = dict.get(key); dict.remove(key); if (var != null) { context.runOnUiThread(new Runnable() { @Override public void run() { var.removeThis(); } }); } } public void initWithTextField(int key) { if (textField != null) { layout.removeView(textField); textField = null; } textField = new EditText(context) ; textField.setMaxLines(1); textField.setSingleLine(true); textField.setGravity(gravity); textField.setBackgroundColor(0); textField.setFocusable(true); textField.setDrawingCacheEnabled(true); textField.setTextSize(fontSize); textField.setInputType(inputType); textField.setHint(placeHolder); textField.setHintTextColor(placeHolderColor); textField.setText(textFieldText); textField.setTextColor(textFieldTextColor); textField.setImeOptions(keyBoardReturnType); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) ; params.leftMargin = -10000; params.topMargin = 0; params.width = contentSizeW; params.height = contentSizeH; layout.addView(textField, params) ; textField.setPadding(leftMargin, 0, rightMargin, 0) ; if (secureTextEntry == true) { setSecureTextEntry(1); } if (showClearButton == true) { showClearButton(); } textWatcher = new TextWatcher() { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub String string = arg0.toString(); String changedText = ""; if (arg3 > 0) { changedText = string.substring(arg1, arg1 + arg3); } else { changedText = ""; } if (!textChange(mykey, beforeTextString, changedText, arg1, arg2)) { if (isSetText == false) { isSetText = true; textField.setText(beforeTextString); textField.setSelection(selection); isSetText = false; } } else { if (isSetText == false) { isSetText = true; textField.setText(string); textField.setSelection(selection - arg2 + arg3); } ByteBuffer textBuffer = ByteBuffer.wrap(textField.getText().toString().getBytes()); text(mykey, textBuffer.array(), textBuffer.array().length); didTextChanged(mykey); isSetText = false; } } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { if (isSetText) { return; } // TODO Auto-generated method stub beforeTextString = arg0.toString(); selection = textField.getSelectionStart(); } @Override public void afterTextChanged(Editable arg0) { if (isSetText) { return; } // TODO Auto-generated method stub } }; textField.addTextChangedListener(textWatcher); onEditorActionListener = new OnEditorActionListener() { @Override public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) { // TODO Auto-generated method stub context.runOnGLThread(new Runnable() { @Override public void run() { keyBoardReturnCallBack(mykey); } }); return true; } }; textField.setOnEditorActionListener(onEditorActionListener); getKeyBoardHeight(); } public void resume() { TimerTask task = new TimerTask() { public void run() { context.runOnGLThread(new Runnable() { @Override public void run() { resignFirstResponder(mykey); } }); } }; Timer timer = new Timer(); timer.schedule(task, (long) 100); } }
[ "278688386@qq.com" ]
278688386@qq.com
2b4c140d769f21564b5d951db156b43f6440d74d
838274700405ea678189eb08c0007ac81844f3d1
/storage/sis-xmlstore/src/main/java/org/apache/sis/internal/storage/gpx/Reader.java
4a0b0c7c2007073a8444a025832a920a4520786f
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
dinush/sis
d2d99c1b16e8b2f11ca45245b4c2314771f2095b
eee2c18120537441a0a4ba35b0cf9284c5dd5818
refs/heads/trunk
2021-01-20T12:56:28.731446
2017-05-06T13:00:50
2017-05-06T13:00:50
90,428,282
0
0
null
2017-05-06T01:08:22
2017-05-06T01:08:22
null
UTF-8
Java
false
false
30,076
java
/* * 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.sis.internal.storage.gpx; import java.util.List; import java.util.ArrayList; import java.util.Objects; import java.io.IOException; import java.io.EOFException; import java.net.URISyntaxException; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.bind.JAXBException; import com.esri.core.geometry.Point; import org.apache.sis.storage.gps.Fix; import org.apache.sis.storage.DataStoreException; import org.apache.sis.storage.DataStoreContentException; import org.apache.sis.internal.storage.xml.stream.StaxStreamReader; import org.apache.sis.util.collection.BackingStoreException; import org.apache.sis.util.resources.Errors; import org.apache.sis.util.Version; // Branch-dependent imports import org.apache.sis.internal.jdk8.Consumer; import org.apache.sis.internal.jdk8.Predicate; import java.text.ParseException; import org.apache.sis.feature.AbstractFeature; /** * Reader for GPX 1.0 and 1.1 files. * This reader is itself a spliterator over all features found in the XML file. * Usage: * * {@preformat java * Consumer<Feature> consumer = ...; * try (Reader reader = new Reader(dataStore)) { * final Version version = reader.initialize(true); * final Metadata metadata = reader.getMetadata(); * reader.forEachRemaining(consumer); * } * } * * @author Johann Sorel (Geomatys) * @author Martin Desruisseaux (Geomatys) * @version 0.8 * @since 0.8 * @module */ final class Reader extends StaxStreamReader { /** * The namespace, which should be either {@link Tags#NAMESPACE_V10} or {@link Tags#NAMESPACE_V11}. * We store this information for identifying the closing {@code <gpx>} tag. */ private String namespace; /** * The metadata (ISO 19115 compatible), or {@code null} if none. */ private Metadata metadata; /** * Identifier of the last "way point" feature instance created. * We use sequential numbers starting from 1. */ private int wayPointId; /** * Identifier of the last "route" feature instance created. * We use sequential numbers starting from 1. */ private int routeId; /** * Identifier of the last "track" feature instance created. * We use sequential numbers starting from 1. */ private int trackId; /** * Creates a new GPX reader for the given data store. * The {@link #initialize(boolean)} method must be invoked after this constructor. * * @param owner the data store for which this reader is created. * @throws DataStoreException if the input type is not recognized. * @throws XMLStreamException if an error occurred while opening the XML file. * @throws IOException if an error occurred while preparing the input stream. * @throws Exception if another kind of error occurred while closing a previous stream. */ public Reader(final Store owner) throws Exception { super(owner); } /** * Returns {@code true} if the given namespace is a GPX namespace or is null. */ private static boolean isGPX(final String ns) { return (ns == null) || ns.startsWith(Tags.NAMESPACE); } /** * Returns {@code true} if the current element can be considered as in the GPX namespace. * Strictly speaking we should require the namespace URI to be exactly {@link #namespace}, * but this method is a little bit more lenient. */ private boolean isGPX() { final String ns = reader.getNamespaceURI(); return Objects.equals(namespace, ns) || isGPX(ns); } /** * Returns {@code true} if the current position of the given reader is the closing {@code </gpx>} tag. * The reader event should be {@link #END_ELEMENT} before to invoke this method. */ private boolean isEndGPX() { assert reader.isEndElement(); return Tags.GPX.equals(reader.getLocalName()) && Objects.equals(namespace, reader.getNamespaceURI()); } /** * Reads the metadata. This method should be invoked exactly once after construction. * This work is performed outside the constructor for allowing {@link #close()} method * invocation no matter if this {@code initialize(boolean)} method fails. * * @param readMetadata if {@code false}, skip the reading of metadata elements. * @return the GPX file version, or {@code null} if no version information was found. * @throws DataStoreException if the root element is not the expected one. * @throws XMLStreamException if an error occurred while reading the XML file. * @throws JAXBException if an error occurred while parsing GPX 1.1 metadata. * @throws ClassCastException if an object unmarshalled by JAXB was not of the expected type. * @throws URISyntaxException if an error occurred while parsing URI in GPX 1.0 metadata. * @throws ParseException if a text can not be parsed as a date. * @throws EOFException if the file seems to be truncated. */ public Version initialize(final boolean readMetadata) throws DataStoreException, XMLStreamException, JAXBException, URISyntaxException, ParseException, EOFException { /* * Skip comments, characters, entity declarations, etc. until we find the root element. * If that root is anything other than <gpx>, we consider that this is not a GPX file. */ moveToRootElement(new Predicate<String>() { @Override public boolean test(String value) { return isGPX(value); } }, Tags.GPX); /* * If a version attribute is found on the <gpx> element, use that value for detecting the GPX version. * If a version is specified, we require major.minor version 1.0 or 1.1 but accept any bug-fix versions * (e.g. 1.1.x). If no version attribute was found, try to infer the version from the namespace URL. */ namespace = reader.getNamespaceURI(); String ver = reader.getAttributeValue(null, Attributes.VERSION); Version version = null; if (ver != null) { version = new Version(ver); if (version.compareTo(StoreProvider.V1_0, 2) < 0 || version.compareTo(StoreProvider.V1_1, 2) > 0) { throw new DataStoreContentException(errors().getString( Errors.Keys.UnsupportedFormatVersion_2, owner.getFormatName(), version)); } } else if (namespace != null) { switch (namespace) { case Tags.NAMESPACE_V10: version = StoreProvider.V1_0; break; case Tags.NAMESPACE_V11: version = StoreProvider.V1_1; break; } } /* * Read metadata immediately, from current position until the beginning of way points, tracks or routes. * The metadata can appear in two forms: * * - In GPX 1.0, they are declared directly in the <gpx> body. * Those elements are parsed in the switch statement below. * * - In GPX 1.1, they are declared in a <metadata> sub-element and their structure is a little bit * more elaborated than what it was in the previous version. We will use JAXB for parsing them. */ parse: while (reader.hasNext()) { switch (next()) { case START_ELEMENT: { /* * GPX 1.0 and 1.1 metadata should not be mixed. However the following code will work even * if GPX 1.0 metadata like <name> or <author> appear after the GPX 1.1 <metadata> element. * If both kind of metadata are specified, the latest value overwrites the values before it. */ if (isGPX()) { final String name = reader.getLocalName(); if (readMetadata) { switch (name) { // GPX 1.1 metadata case Tags.METADATA: metadata = unmarshal(Metadata.class); break; // GPX 1.0 metadata case Tags.NAME: metadata().name = getElementText(); break; case Tags.DESCRIPTION: metadata().description = getElementText(); break; case Tags.AUTHOR: author() .name = getElementText(); break; case Tags.EMAIL: author() .email = getElementText(); break; case Tags.URL: link() .uri = getElementAsURI(); break; case Tags.URL_NAME: link() .text = getElementText(); break; case Tags.TIME: metadata().time = getElementAsDate(); break; case Tags.KEYWORDS: metadata().keywords = getElementAsList(); break; case Tags.BOUNDS: metadata().bounds = unmarshal(Bounds.class); break; case Tags.WAY_POINT: // stop metadata parsing. case Tags.TRACKS: case Tags.ROUTES: break parse; case Tags.GPX: throw new DataStoreContentException(nestedElement(Tags.GPX)); } } else { /* * If the caller asked to skip metadata, just look for the end of metadata elements. */ switch (name) { case Tags.METADATA: skipUntilEnd(reader.getName()); break; case Tags.WAY_POINT: case Tags.TRACKS: case Tags.ROUTES: break parse; case Tags.GPX: throw new DataStoreContentException(nestedElement(Tags.GPX)); } } } break; } case END_ELEMENT: { /* * Reminder: calling next() after getElementText(), getElementAsFoo() and unmarshal(…) methods * moves the reader after the END_ELEMENT event. Consequently there is only the enclosing <gpx> * tag to check here. */ if (isEndGPX()) { break parse; } break; } } } if (readMetadata) { metadata().store = (Store) owner; } return version; } /** * Returns the {@link #metadata} field, creating it if needed. * This is a convenience method for GPX 1.0 metadata parsing. * This is not for returning the metadata result after parsing. * * @see #getMetadata() */ private Metadata metadata() { if (metadata == null) { metadata = new Metadata(); } return metadata; } /** * Returns the {@link Metadata#author} field, creating all necessary objects if needed. * This is a convenience method for GPX 1.0 metadata parsing. */ private Person author() { final Metadata metadata = metadata(); if (metadata.author == null) { metadata.author = new Person(); } return metadata.author; } /** * Returns the first element of the {@link Metadata#links} field, creating all necessary objects if needed. * This is a convenience method for GPX 1.0 metadata parsing. */ private Link link() { final Metadata metadata = metadata(); List<Link> links = metadata.links; if (links == null) { metadata.links = links = new ArrayList<>(); } final Link first; if (links.isEmpty()) { first = new Link(); links.add(first); } else { first = links.get(0); } return first; } /** * Returns the metadata (ISO 19115 compatible), or {@code null} if none. * This method can return a non-null value only if {@code initialize(true)} * has been invoked before this method. * * @return the metadata, or {@code null} if none. * * @see #initialize(boolean) */ public Metadata getMetadata() { return metadata; } /** * Performs the given action on the next feature instance, or returns {@code null} if there is no more * feature to parse. * * @param action the action to perform on the next feature instances. * @return {@code true} if a feature has been found, or {@code false} if we reached the end of GPX file. * @throws BackingStoreException if an error occurred while parsing the next feature instance. * The cause may be {@link DataStoreException}, {@link IOException}, {@link URISyntaxException} * or various {@link RuntimeException}. */ @Override public boolean tryAdvance(final Consumer<? super AbstractFeature> action) throws BackingStoreException { try { return parse(action, false); } catch (Exception e) { // Many possible exceptions including unchecked ones. throw new BackingStoreException(canNotParseFile(), e); } } /** * Performs the given action for each remaining element until all elements have been processed. * * @param action the action to perform on the remaining feature instances. * @throws BackingStoreException if an error occurred while parsing the next feature instance. * The cause may be {@link DataStoreException}, {@link IOException}, {@link URISyntaxException} * or various {@link RuntimeException}. */ @Override public void forEachRemaining(final Consumer<? super AbstractFeature> action) throws BackingStoreException { try { parse(action, true); } catch (Exception e) { // Many possible exceptions including unchecked ones. throw new BackingStoreException(canNotParseFile(), e); } } /** * Implementation of {@link #tryAdvance(Consumer)} and {@link #forEachRemaining(Consumer)}. * * @param action the action to perform on the remaining feature instances. * @param all whether to perform the action on all remaining instances or only the next one. * @return {@code false} if this method as detected the end of {@code <gpx>} element or the end of document. * @throws DataStoreException if the file contains invalid elements. * @throws XMLStreamException if an error occurred while reading the XML file. * @throws URISyntaxException if an error occurred while parsing GPX 1.0 URI. * @throws JAXBException if an error occurred while parsing GPX 1.1 link. * @throws ClassCastException if an object unmarshalled by JAXB was not of the expected type. * @throws NumberFormatException if a text can not be parsed as an integer or a floating point number. * @throws ParseException if a text can not be parsed as a date. * @throws EOFException if the file seems to be truncated. */ @SuppressWarnings("fallthrough") private boolean parse(final Consumer<? super AbstractFeature> action, final boolean all) throws Exception { for (int type = reader.getEventType(); ; type = reader.next()) { /* * We do not need to check 'reader.hasNext()' in above loop * since this check is done by the END_DOCUMENT case below. */ switch (type) { case START_ELEMENT: { final AbstractFeature f; switch (isGPX() ? reader.getLocalName() : "") { case Tags.WAY_POINT: f = parseWayPoint(++wayPointId); break; case Tags.ROUTES: f = parseRoute (++routeId); break; case Tags.TRACKS: f = parseTrack (++trackId); break; case Tags.GPX: throw new DataStoreContentException(nestedElement(Tags.GPX)); default: skipUntilEnd(reader.getName()); continue; } action.accept(f); if (all) continue; reader.next(); // Skip the END_ELEMENT return true; } case END_ELEMENT: if (!isEndGPX()) continue; // else fallthrough case END_DOCUMENT: return false; } } } /** * Parses a {@code <wpt>}, {@code <rtept>} or {@code <trkpt>} element. * The STAX reader {@linkplain XMLStreamReader#getEventType() current event} must be a {@link #START_ELEMENT}. * After this method invocation, the reader will be on {@link #END_ELEMENT}. * * @throws Exception see the list of exceptions documented in {@link #parse(Consumer, boolean)}. */ private AbstractFeature parseWayPoint(final int index) throws Exception { assert reader.isStartElement(); /* * Way points might be located in different elements: <wpt>, <rtept> and <trkpt>. * We have to keep the current tag name in order to know when we reach the end. * We are lenient about namespace since we do not allow nested way points. */ final String tagName = reader.getLocalName(); final String lat = reader.getAttributeValue(null, Attributes.LATITUDE); final String lon = reader.getAttributeValue(null, Attributes.LONGITUDE); if (lat == null || lon == null) { throw new DataStoreContentException(errors().getString(Errors.Keys.MandatoryAttribute_2, (lat == null) ? Attributes.LATITUDE : Attributes.LONGITUDE, tagName)); } final AbstractFeature feature = ((Store) owner).types.wayPoint.newInstance(); feature.setPropertyValue("sis:identifier", index); feature.setPropertyValue("sis:geometry", new Point(parseDouble(lon), parseDouble(lat))); List<Link> links = null; while (true) { /* * We do not need to check 'reader.hasNext()' in above loop * since this check is done by the END_DOCUMENT case below. */ switch (next()) { case START_ELEMENT: { final Object value; final String name = reader.getLocalName(); switch (isGPX() ? name : "") { case Tags.NAME: // Fallthrough to getElementText() case Tags.COMMENT: // ︙ case Tags.DESCRIPTION: // ︙ case Tags.SOURCE: // ︙ case Tags.SYMBOL: // ︙ case Tags.TYPE: value = getElementText(); break; case Tags.TIME: value = getElementAsTemporal(); break; case Tags.MAGNETIC_VAR: // Fallthrough to getElementAsDouble() case Tags.GEOID_HEIGHT: // ︙ case Tags.AGE_OF_GPS_DATA: // ︙ case Tags.HDOP: // ︙ case Tags.PDOP: // ︙ case Tags.VDOP: // ︙ case Tags.ELEVATION: value = getElementAsDouble(); break; case Tags.SATELITTES: // Fallthrough to getElementAsInteger() case Tags.DGPS_ID: value = getElementAsInteger(); break; case Tags.FIX: value = Fix.fromGPX(getElementText()); break; case Tags.LINK: links = Metadata.addIfNonNull(links, unmarshal(Link.class)); continue; case Tags.URL: links = Metadata.addIfNonNull(links, Link.valueOf(getElementAsURI())); continue; default: { if (name.equals(tagName)) { throw new DataStoreContentException(nestedElement(name)); } continue; } } feature.setPropertyValue(name, value); break; } case END_ELEMENT: { if (tagName.equals(reader.getLocalName()) && isGPX()) { if (links != null) feature.setPropertyValue(Tags.LINK, links); return feature; } break; } case END_DOCUMENT: { throw new EOFException(endOfFile()); } } } } /** * Parses a {@code <rte>} element. The STAX reader {@linkplain XMLStreamReader#getEventType() current event} * must be a {@link #START_ELEMENT} and the name of that start element must be {@link Tags#ROUTES}. * * @throws Exception see the list of exceptions documented in {@link #parse(Consumer, boolean)}. */ private AbstractFeature parseRoute(final int index) throws Exception { assert reader.isStartElement() && Tags.ROUTES.equals(reader.getLocalName()); final AbstractFeature feature = ((Store) owner).types.route.newInstance(); feature.setPropertyValue("sis:identifier", index); List<AbstractFeature> wayPoints = null; List<Link> links = null; while (true) { /* * We do not need to check 'reader.hasNext()' in above loop * since this check is done by the END_DOCUMENT case below. */ switch (next()) { case START_ELEMENT: { final Object value; final String name = reader.getLocalName(); switch (isGPX() ? name : "") { default: continue; case Tags.NAME: // Fallthrough to getElementText() case Tags.COMMENT: // ︙ case Tags.DESCRIPTION: // ︙ case Tags.SOURCE: // ︙ case Tags.TYPE: value = getElementText(); break; case Tags.NUMBER: value = getElementAsInteger(); break; case Tags.LINK: links = Metadata.addIfNonNull(links, unmarshal(Link.class)); continue; case Tags.URL: links = Metadata.addIfNonNull(links, Link.valueOf(getElementAsURI())); continue; case Tags.ROUTES: throw new DataStoreContentException(nestedElement(name)); case Tags.ROUTE_POINTS: { if (wayPoints == null) wayPoints = new ArrayList<>(8); wayPoints.add(parseWayPoint(wayPoints.size() + 1)); continue; } } feature.setPropertyValue(name, value); break; } case END_ELEMENT: { if (Tags.ROUTES.equals(reader.getLocalName()) && isGPX()) { if (wayPoints != null) feature.setPropertyValue(Tags.ROUTE_POINTS, wayPoints); if (links != null) feature.setPropertyValue(Tags.LINK, links); return feature; } break; } case END_DOCUMENT: { throw new EOFException(endOfFile()); } } } } /** * Parses a {@code <trkseg>} element. The STAX reader {@linkplain XMLStreamReader#getEventType() current event} * must be a {@link #START_ELEMENT} and the name of that start element must be {@link Tags#TRACK_SEGMENTS}. * * @throws Exception see the list of exceptions documented in {@link #parse(Consumer, boolean)}. */ private AbstractFeature parseTrackSegment(final int index) throws Exception { assert reader.isStartElement() && Tags.TRACK_SEGMENTS.equals(reader.getLocalName()); final AbstractFeature feature = ((Store) owner).types.trackSegment.newInstance(); feature.setPropertyValue("sis:identifier", index); List<AbstractFeature> wayPoints = null; while (true) { /* * We do not need to check 'reader.hasNext()' in above loop * since this check is done by the END_DOCUMENT case below. */ switch (reader.next()) { case START_ELEMENT: { final String name = reader.getLocalName(); switch (isGPX() ? name : "") { default: continue; case Tags.TRACK_POINTS: { if (wayPoints == null) wayPoints = new ArrayList<>(8); wayPoints.add(parseWayPoint(wayPoints.size() + 1)); continue; } case Tags.TRACK_SEGMENTS: throw new DataStoreContentException(nestedElement(name)); } } case END_ELEMENT: { if (Tags.TRACK_SEGMENTS.equals(reader.getLocalName()) && isGPX()) { if (wayPoints != null) feature.setPropertyValue(Tags.TRACK_POINTS, wayPoints); return feature; } break; } case END_DOCUMENT: { throw new EOFException(endOfFile()); } } } } /** * Parses a {@code <trk>} element. The STAX reader {@linkplain XMLStreamReader#getEventType() current event} * must be a {@link #START_ELEMENT} and the name of that start element must be {@link Tags#TRACKS}. * * @throws Exception see the list of exceptions documented in {@link #parse(Consumer, boolean)}. */ private AbstractFeature parseTrack(final int index) throws Exception { assert reader.isStartElement() && Tags.TRACKS.equals(reader.getLocalName()); final AbstractFeature feature = ((Store) owner).types.track.newInstance(); feature.setPropertyValue("sis:identifier", index); List<AbstractFeature> segments = null; List<Link> links = null; while (true) { /* * We do not need to check 'reader.hasNext()' in above loop * since this check is done by the END_DOCUMENT case below. */ switch (next()) { case START_ELEMENT: { final Object value; final String name = reader.getLocalName(); switch (isGPX() ? name : "") { default: continue; case Tags.NAME: // Fallthrough to getElementText() case Tags.COMMENT: // ︙ case Tags.DESCRIPTION: // ︙ case Tags.SOURCE: // ︙ case Tags.TYPE: value = getElementText(); break; case Tags.NUMBER: value = getElementAsInteger(); break; case Tags.LINK: links = Metadata.addIfNonNull(links, unmarshal(Link.class)); continue; case Tags.URL: links = Metadata.addIfNonNull(links, Link.valueOf(getElementAsURI())); continue; case Tags.TRACKS: throw new DataStoreContentException(nestedElement(name)); case Tags.TRACK_SEGMENTS: { if (segments == null) segments = new ArrayList<>(8); segments.add(parseTrackSegment(segments.size() + 1)); continue; } } feature.setPropertyValue(name, value); break; } case END_ELEMENT: { if (Tags.TRACKS.equals(reader.getLocalName()) && isGPX()) { if (segments != null) feature.setPropertyValue(Tags.TRACK_SEGMENTS, segments); if (links != null) feature.setPropertyValue(Tags.LINK, links); return feature; } break; } case END_DOCUMENT: { throw new EOFException(endOfFile()); } } } } }
[ "desruisseaux@apache.org" ]
desruisseaux@apache.org
a210e0a5f143fc22e1ad9575fba7856b6a556582
4a5afa09ceb7df5dfbd9720279afe9ff3e9df61c
/serverside/java/src/main/java/com/justonetech/biz/utils/jbpm/extattr/instance/ObjectFactory.java
7fdbebe7d878b5707668003d11457b9fb36c5b07
[]
no_license
chrgu000/juyee
00ad3af9446a1df68d5a7c286f6243700e371c5c
0de221b728e1eed7fe8eb06c267d62a0edc99793
refs/heads/master
2020-05-25T01:21:01.504384
2016-11-28T09:26:10
2016-11-28T09:26:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,462
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2009.03.26 at 03:35:54 下午 CST // package com.justonetech.biz.utils.jbpm.extattr.instance; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.justonetech.ipromis.core.extattr.instance package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _Value_QNAME = new QName("", "Value"); private final static QName _Expression_QNAME = new QName("", "Expression"); private final static QName _None_QNAME = new QName("", "None"); private final static QName _All_QNAME = new QName("", "All"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.justonetech.ipromis.core.extattr.instance * */ public ObjectFactory() { } /** * Create an instance of {@link Values } * */ public Values createValues() { return new Values(); } /** * Create an instance of {@link Attributes } * */ public Attributes createAttributes() { return new Attributes(); } /** * Create an instance of {@link Attribute } * */ public Attribute createAttribute() { return new Attribute(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Long }{@code >}} * */ @XmlElementDecl(namespace = "", name = "Value") public JAXBElement<Long> createValue(Long value) { return new JAXBElement<Long>(_Value_QNAME, Long.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "", name = "Expression") public JAXBElement<String> createExpression(String value) { return new JAXBElement<String>(_Expression_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Object }{@code >}} * */ @XmlElementDecl(namespace = "", name = "None") public JAXBElement<Object> createNone(Object value) { return new JAXBElement<Object>(_None_QNAME, Object.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Object }{@code >}} * */ @XmlElementDecl(namespace = "", name = "All") public JAXBElement<Object> createAll(Object value) { return new JAXBElement<Object>(_All_QNAME, Object.class, null, value); } }
[ "chenjunping@18d54d2b-35bc-4a19-92ed-a673819ede82" ]
chenjunping@18d54d2b-35bc-4a19-92ed-a673819ede82
6cde76b57d0058c13397b03aeb39be5ca51c971f
6b010107b2ba1baa618453ea5cda690ea1fe26d1
/src/com/xingpk/xiazhuji/intr/ACS.java
12462c20c2620adfe790b94a26b5cfc0f6b9fab3
[]
no_license
SoLonGxing/moreEffect
1345f746e3b9c886cd075f3c240e1edec3aba4c4
b5fdd192b0b6de4599c64b8d763666d02563576b
refs/heads/master
2021-06-22T11:46:30.822418
2020-12-29T06:57:45
2020-12-29T06:57:45
131,278,476
0
0
null
null
null
null
UTF-8
Java
false
false
314
java
package com.xingpk.xiazhuji.intr; public interface ACS extends Pbrb2ServiceClass { //返回ACS类的内容 String printAcsClass(); // //生成Acs的reponse那一行 // String makeResponseString(); // // //生成调用Bos的那一行 // String makeCallString(String calledBosServiceName); }
[ "xpeikang@gmail.com" ]
xpeikang@gmail.com
49bff6900dc3ced000690efc95865fe2a49df79a
7ecea0f90b572fbb2ba2f31c4d30a5a1538d4561
/Aufgabe2/Bubblesort.java
22ef09d682c2820864dce7d2be67dc86680f76a7
[]
no_license
hyerex/SysProg
cb7ff3f3d68d77f16786093cb3656c7b0dfe1ab4
5d3a4a7d969745e9847a488da335da35210d3729
refs/heads/master
2020-04-07T20:44:48.235746
2019-01-12T16:34:05
2019-01-12T16:34:05
158,701,311
0
0
null
null
null
null
UTF-8
Java
false
false
1,972
java
// Bubblesort.java import java.util.Scanner; import java.util.Random; /** * Bubblesort liest ganze Zahlen ein und sortiert sie aufsteigend. * @author H.Drachenfels * @version 6.3.2013 */ public final class Bubblesort { private Bubblesort() { } /** * main ist der Startpunkt des Programms. * @param args wird nicht verwendet. */ public static void main(final String[] args) { final Scanner stdin = new Scanner(System.in); final Random random = new Random(); //----------------------------------------------- Feldgroesse einlesen if (args.length != 1) { System.err.println("Aufruf: java Bubblesort Anzahl"); System.err.println(args.length); return; } System.err.println(args.length); final int n = Integer.parseInt(args[0]); //---------------------------------------------------- Zahlen einlesen final int[] a = new int[n]; System.out.printf("Bitte %d ganze Zahlen eingeben: ", n); for (int i = 0; i < a.length; ++i) { if (stdin.hasNextInt()) { a[i] = stdin.nextInt(); } else { a[i] = random.nextInt(); System.out.println(a[i]); } } //--------------------------------------------------- Zahlen sortieren for (int i = a.length; i > 1; i--) { // groessten Wert nach hinten schieben for (int j = 0; j < i - 1; ++j) { if (a[j] > a[j + 1]) { // Werte tauschen int tmp = a[j + 1]; a[j + 1] = a[j]; a[j] = tmp; } } } //---------------------------------------------------- Zahlen ausgeben System.out.println("Sortierte Zahlenfolge: "); for (int i = 0; i < a.length; ++i) { System.out.println(a[i]); } } }
[ "andreas.ly96@gmai.com" ]
andreas.ly96@gmai.com
3269b13a65b2ebdff3ebf57097f4bb04c1acd74c
f8e8b214f99bf99e5fb5f346b56a4065133ef1a5
/src/slogo/commands/idcommands/ID.java
9e7ec5bb1d41c7cadde46f59f3286494785f0ade
[ "MIT" ]
permissive
wenyue-gu/Slogo
9c16b9e1ba843cff97e38c13a1992b501416fb2e
64c6504e2870c332d8137cd8d8c8beb275b63828
refs/heads/master
2022-04-19T21:59:08.071984
2020-03-07T08:14:40
2020-03-07T08:14:40
254,761,652
0
0
null
null
null
null
UTF-8
Java
false
false
1,200
java
package slogo.commands.idcommands; import slogo.backendexternal.TurtleManifest; import slogo.backendexternal.TurtleStatus; import slogo.commands.IdCommand; import java.util.LinkedList; import java.util.List; import java.util.function.Supplier; /** * Class that implements IdCommand, used to query the active turtle. * * @author Tyler Jang */ public class ID implements IdCommand { public static final int NUM_ARGS = 0; private double activeID; /** * Constructor for ID. Takes 0 command arguments. */ public ID() { } /** * Executes the ID instance, retrieving the active turtle. * * @param manifest a TurtleManifest containing information about all the turtles * @return a List of TurtleStatus instances, containing only the parameter ts. */ @Override public List<TurtleStatus> execute(TurtleManifest manifest) { activeID = manifest.getActiveTurtle(); return new LinkedList<>(); } /** * Retrieves the value returned by ID's execution, the active turtle ID. * * @return the active turtle's ID. */ @Override public double returnValue() { return activeID; } }
[ "taj26@duke.edu" ]
taj26@duke.edu
f8eddb215423e1484cdd27feccbc98c1e554ffd7
a36508ced89dc3c995708f7f330ddb89a2b209f5
/app/src/main/java/com/example/k1/api/ApiService.java
27acec14ea12e10b1f1132dc0455eb01edab2eac
[]
no_license
sanshinan/K1
151f711b0570c642476bc497a002d10b9967ecba
a1103b118c6ea7a2a7af7086398311c08af9eb2d
refs/heads/master
2023-01-29T21:37:34.832919
2020-12-17T11:47:36
2020-12-17T11:47:36
322,257,739
0
0
null
null
null
null
UTF-8
Java
false
false
567
java
package com.example.k1.api; import java.util.HashMap; import io.reactivex.Observable; import okhttp3.ResponseBody; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Url; public interface ApiService { @GET Observable<ResponseBody> get(@Url String url); @FormUrlEncoded @POST Observable<ResponseBody> post(@Url String url); @FormUrlEncoded @POST Observable<ResponseBody> post(@Url String url, @FieldMap HashMap<String,String> map); }
[ "2274682830@qq.com" ]
2274682830@qq.com
1c43f99a978a5feb7a89e83466051302af16ff4a
50068116a77e2beffd20770a07772e47d6f97bc8
/src/com/halim/genericclasslar/YazdirmaSinifi.java
ad440fe435ada3f84644adb70af5a1adfc848bdf
[]
no_license
HalimBezek/Use_GenericClasses
18a3fdced815d69be8582c84146bdb0683108e75
e73f397da5d520d506dce29734bbae18956d2be6
refs/heads/master
2020-03-22T21:55:06.258839
2018-07-12T14:07:28
2018-07-12T14:07:28
null
0
0
null
null
null
null
ISO-8859-9
Java
false
false
419
java
package com.halim.genericclasslar; //buradaki E aslında gönderilen faklı türden verileri E nerede varsa o türde kullan demek oluyor diyebliliriz. public class YazdirmaSinifi<E> { public void yazdir(E[] dizi) { for(E e: dizi) //for-each dongüsü { System.out.println(e); //not : ogrenci sınıfı içindeki toString metodu obje yazdırılmak istendiğinde aktifleşip yazdırılmış oldu. } } }
[ "halimbezek@gmail.com" ]
halimbezek@gmail.com
a788b0e95841908e3531d1879edb00903db45a20
dfa13e6241bff153a8cc3bfd9b6713a22bfcc9c2
/kodilla-intro/src/main/java/AdvCalculator.java
42e4c0e08e2a27b0e6ba6259bf694312d14676b2
[]
no_license
blrp/Bartosz_-Switalski-kodilla_tester
fe566afa7f6e0c424b69a61b0b3ee933cb0089be
f30f53946cdd922a11298dd8ed4af6298a3acd32
refs/heads/master
2023-04-14T05:17:34.174357
2021-04-27T16:58:13
2021-04-27T16:58:13
324,841,214
0
0
null
null
null
null
UTF-8
Java
false
false
727
java
public class AdvCalculator { public double calculate() { String userSelected = UserDialogs.getUserSelection(); int a = UserDialogs.getValue(); int b = UserDialogs.getValue(); double result = 0; switch (userSelected) { case "ADD": result = a + b; break; // [1] case "SUB": result = a - b; break; // [2] case "DIV": result = a / b; break; // [3] case "MUL": result = a * b; break; // [4] } return result; } }
[ "bartosz.switalski@o2.pl" ]
bartosz.switalski@o2.pl
0ce6d99d6751ab38cbff4c0dbc0da4b3a418b6da
af148317bd600186f91ee2430bac87eccd32a0b8
/src/test/java/util/HexTest.java
eaefc8a12ed213273d460eafc79fd5abc8c8ed4b
[]
no_license
Lahne/factom-sdk
b7628e60f47f2fceb81947ca211e03899e192d9b
b8f14a238b1740738c768cac41463cf9d027d4b4
refs/heads/master
2020-03-15T23:52:59.867332
2018-05-07T03:39:14
2018-05-07T03:39:14
132,402,671
2
0
null
null
null
null
UTF-8
Java
false
false
419
java
package util; import org.junit.Assert; import org.junit.Test; import io.wancloud.factom.sdk.TestBase; import io.wancloud.factom.sdk.util.Hex; public class HexTest extends TestBase{ @Test public void testHex(){ String src = "abcd12中国,中國"; String dest = Hex.encode(src); System.out.println(dest); String back = Hex.decode(dest); System.out.println(back); Assert.assertEquals(src, back); } }
[ "804929779@qq.com" ]
804929779@qq.com
c3b45a9f30f8e1a9865008d50732455e63de69ad
d93ce3950a3c805cd2a5b32e09ed8341a0ff9bbd
/md-sal/model/model-flow-base/src/main/yang-gen-sal/org/opendaylight/yang/gen/v1/urn/opendaylight/action/types/rev131112/action/action/flood/action/_case/FloodActionBuilder.java
985afa63a9c56c9962fb2a2181cf0139fef6fce2
[]
no_license
ycymio/opendaylight-adsal-controller
6247d6d4b2a11718932528f4873dc90844f6145d
c3d5164e990e5f95faf02594646c164c66759a23
refs/heads/master
2021-01-11T09:05:36.364505
2016-12-26T02:40:46
2016-12-26T02:40:46
77,222,077
0
0
null
null
null
null
UTF-8
Java
false
false
7,414
java
package org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case; import java.util.Collections; import java.util.Map; import org.opendaylight.yangtools.yang.binding.DataObject; import java.util.HashMap; import org.opendaylight.yangtools.yang.binding.Augmentation; /** * Class that builds {@link org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction} instances. * * @see org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction */ public class FloodActionBuilder { Map<java.lang.Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>> augmentation = new HashMap<>(); public FloodActionBuilder() { } public FloodActionBuilder(FloodAction base) { if (base instanceof FloodActionImpl) { FloodActionImpl _impl = (FloodActionImpl) base; this.augmentation = new HashMap<>(_impl.augmentation); } } @SuppressWarnings("unchecked") public <E extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>> E getAugmentation(java.lang.Class<E> augmentationType) { if (augmentationType == null) { throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!"); } return (E) augmentation.get(augmentationType); } public FloodActionBuilder addAugmentation(java.lang.Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>> augmentationType, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction> augmentation) { this.augmentation.put(augmentationType, augmentation); return this; } public FloodAction build() { return new FloodActionImpl(this); } private static final class FloodActionImpl implements FloodAction { public java.lang.Class<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction> getImplementedInterface() { return org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction.class; } private Map<java.lang.Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>> augmentation = new HashMap<>(); private FloodActionImpl(FloodActionBuilder base) { switch (base.augmentation.size()) { case 0: this.augmentation = Collections.emptyMap(); break; case 1: final Map.Entry<java.lang.Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>> e = base.augmentation.entrySet().iterator().next(); this.augmentation = Collections.<java.lang.Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>>singletonMap(e.getKey(), e.getValue()); break; default : this.augmentation = new HashMap<>(base.augmentation); } } @SuppressWarnings("unchecked") @Override public <E extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>> E getAugmentation(java.lang.Class<E> augmentationType) { if (augmentationType == null) { throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!"); } return (E) augmentation.get(augmentationType); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((augmentation == null) ? 0 : augmentation.hashCode()); return result; } @Override public boolean equals(java.lang.Object obj) { if (this == obj) { return true; } if (!(obj instanceof DataObject)) { return false; } if (!org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction.class.equals(((DataObject)obj).getImplementedInterface())) { return false; } org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction other = (org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction)obj; if (getClass() == obj.getClass()) { // Simple case: we are comparing against self FloodActionImpl otherImpl = (FloodActionImpl) obj; if (augmentation == null) { if (otherImpl.augmentation != null) { return false; } } else if(!augmentation.equals(otherImpl.augmentation)) { return false; } } else { // Hard case: compare our augments with presence there... for (Map.Entry<java.lang.Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.flood.action._case.FloodAction>> e : augmentation.entrySet()) { if (!e.getValue().equals(other.getAugmentation(e.getKey()))) { return false; } } // .. and give the other one the chance to do the same if (!obj.equals(this)) { return false; } } return true; } @Override public java.lang.String toString() { java.lang.StringBuilder builder = new java.lang.StringBuilder ("FloodAction ["); boolean first = true; if (first) { first = false; } else { builder.append(", "); } builder.append("augmentation="); builder.append(augmentation.values()); return builder.append(']').toString(); } } }
[ "ycymio@gmail.com" ]
ycymio@gmail.com
5ef497b0873a87e58046f9bf1c12515a07cd7ed4
26e3686596206df96a9c0ae29953124c2059f318
/src/ccb/android/fetchgraduateinfo/MainActivity.java
681c45a182b15ae4f294e3c780f823cfe10a849b
[]
no_license
Trible-ccb/FetchGraduateInfo
00753a0ad30ab414a5c8d317bf0e998fc9dd2fc3
8c9f5e682848a66fe1b52873d7bde9f0d4aff683
refs/heads/master
2021-01-16T18:20:18.810937
2015-01-04T15:49:02
2015-01-04T15:49:02
28,778,254
0
0
null
null
null
null
UTF-8
Java
false
false
3,045
java
package ccb.android.fetchgraduateinfo; import java.io.IOException; import java.util.List; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import ccb.android.commons.utils.Bog; import ccb.android.fetchgraduateinfo.biz.FetchGraduateInfoImpl; import ccb.android.fetchgraduateinfo.biz.IFetchStudentInfo; import ccb.android.fetchgraduateinfo.biz.IFetchStudentInfo.FetchCallback; import ccb.android.fetchgraduateinfo.biz.ParseStudentInfoFromXLS; import ccb.android.fetchgraduateinfo.pojos.StudentInfo; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.avos.avoscloud.AVException; import com.avos.avoscloud.SaveCallback; public class MainActivity extends CustomFragmentActivity implements OnClickListener{ Button mStartFetchBtn,mViewInfosBtn; boolean isFetching; IFetchStudentInfo mFetchControl; volatile int mFetchnum; RequestQueue mReqQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mReqQueue = Volley.newRequestQueue(this); mFetchControl = new FetchGraduateInfoImpl(mReqQueue); initView(); } void initView(){ mStartFetchBtn = (Button) findViewById(R.id.start_fetch); mViewInfosBtn = (Button) findViewById(R.id.view_infos); mStartFetchBtn.setOnClickListener(this); mViewInfosBtn.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } void doFetch() throws IOException{ String name = "黄金凤"; String number = "201421030317"; // 清水河 String file1 = "qshStdInfo.XLS"; // 沙河 String file2 = "shStdInfo.XLS"; List<String[]> info1 = ParseStudentInfoFromXLS.parse(getAssets().open(file1)); List<String[]> info2 = ParseStudentInfoFromXLS.parse(getAssets().open(file2)); info1.addAll(info2); mFetchnum = 0; for ( String[] s : info1 ){ name = s[2]; number = s[1]; if ( !number.startsWith("2") ){ continue; } mStartFetchBtn.setEnabled(false); mFetchControl.fetch(name, number,new FetchCallback() { @Override public void onFetch(StudentInfo info, Exception e) { mStartFetchBtn.setEnabled(true); if ( e != null || info == null ){ Bog.toast("exc"+e+"info = "+info); return; } info.saveInBackground(new SaveCallback() { @Override public void done(AVException arg0) { if ( arg0 == null ){ mFetchnum++; setTitle(""+mFetchnum,R.color.blue_qq); } else { Bog.toast(arg0.getMessage()); } } }); } }); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.start_fetch: try { doFetch(); } catch (IOException e) { e.printStackTrace(); } break; case R.id.view_infos: simpleDisplayActivity(ViewStudentInfoActivity.class); break; default: break; } } }
[ "chenchuibo@qq.com" ]
chenchuibo@qq.com
6c72af423835cc8b1737a5782cd5574f7b316b99
4126576063649742c7a7ed048011cca313cd16d9
/ios-controllers/src/com/badlogic/gdx/controllers/IosControllerManager.java
055e518e2a4c8fb1cc870320152540cf21b10645
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
vminc/gdx-controllerutils
6173fe145050af7e055380907c6df4fba54a02c3
d83a84430fb32c8e444ca08446013fd1d5e53b6b
refs/heads/master
2020-12-02T21:30:58.836122
2019-12-31T16:59:49
2019-12-31T16:59:49
231,122,020
0
0
Apache-2.0
2019-12-31T16:58:58
2019-12-31T16:58:57
null
UTF-8
Java
false
false
6,069
java
package com.badlogic.gdx.controllers; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.LifecycleListener; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; import org.robovm.apple.foundation.Foundation; import org.robovm.apple.foundation.NSArray; import org.robovm.apple.gamecontroller.GCController; import org.robovm.apple.uikit.UIKeyCommand; import org.robovm.apple.uikit.UIKeyModifierFlags; import org.robovm.apple.uikit.UIViewController; import org.robovm.objc.Selector; import org.robovm.objc.block.VoidBlock1; public class IosControllerManager implements ControllerManager { private final Array<Controller> controllers = new Array<>(); private final Array<ControllerListener> listeners = new Array<>(); private boolean initialized = false; private ICadeController iCadeController; public IosControllerManager() { } /** * you need to call this method to register IosControllerManager with libGDX before your first call to * Controllers.getControllers(). */ public static void initializeIosControllers() { ObjectMap<Application, ControllerManager> managers = Controllers.managers; // this is a copy from Controllers class. A hack to get IosControllerManager to work with libGDX if (Foundation.getMajorSystemVersion() < 7) { Gdx.app.log("Controllers", "IosControllerManager not added, needs iOS 7+."); } else if (!managers.containsKey(Gdx.app)) { IosControllerManager manager = new IosControllerManager(); managers.put(Gdx.app, manager); final Application app = Gdx.app; Gdx.app.addLifecycleListener(new LifecycleListener() { public void resume() { } public void pause() { } public void dispose() { Controllers.managers.remove(app); Gdx.app.log("Controllers", "removed manager for application, " + Controllers.managers.size + " managers active"); } }); Gdx.app.log("Controllers", "added manager for application, " + managers.size + " managers active"); } else { Gdx.app.log("Controllers", "IosControllerManager not added, manager already active. "); } } public static void enableICade(UIViewController controller, Selector action) { for (int i = 0; i < ICadeController.KEYS_TO_HANDLE.length(); i++) { controller.addKeyCommand(new UIKeyCommand(Character.toString(ICadeController.KEYS_TO_HANDLE.charAt(i)), UIKeyModifierFlags.None, action)); } controller.becomeFirstResponder(); Gdx.app.log("Controllers", "iCade support activated"); } public static void keyPress(UIKeyCommand sender) { //a key for ICadeController was pressed // instantiate it, if not already available IosControllerManager controllerManager = (IosControllerManager) Controllers.managers.get(Gdx.app); if (controllerManager != null) controllerManager.handleKeyPressed(sender); } private void handleKeyPressed(UIKeyCommand sender) { if (iCadeController == null) { Gdx.app.log("Controllers", "iCade key was pressed, adding iCade controller."); iCadeController = new ICadeController(); controllers.add(iCadeController); synchronized (listeners) { for (ControllerListener listener : listeners) listener.connected(iCadeController); } } iCadeController.handleKeyPressed(sender.getInput()); } protected boolean isSupportedController(GCController controller) { return controller.getExtendedGamepad() != null || controller.getGamepad() != null; } @Override public Array<Controller> getControllers() { initializeControllerArray(); return controllers; } private void initializeControllerArray() { if (!initialized) { initialized = true; NSArray<GCController> controllers = GCController.getControllers(); for (GCController controller : controllers) { if (isSupportedController(controller)) this.controllers.add(new IosController(controller)); } GCController.Notifications.observeDidConnect(new VoidBlock1<GCController>() { @Override public void invoke(GCController gcController) { onControllerConnect(gcController); } }); GCController.Notifications.observeDidDisconnect(new VoidBlock1<GCController>() { @Override public void invoke(GCController gcController) { onControllerDisconnect(gcController); } }); } } protected void onControllerConnect(GCController gcController) { if (!isSupportedController(gcController)) return; boolean alreadyInList = false; for (Controller controller : controllers) { if (controller instanceof IosController && ((IosController) controller).getController() == gcController) { alreadyInList = true; break; } } if (!alreadyInList) { IosController iosController = new IosController(gcController); controllers.add(iosController); synchronized (listeners) { for (ControllerListener listener : listeners) listener.connected(iosController); } } } protected void onControllerDisconnect(GCController gcController) { IosController oldReference = null; for (Controller controller : controllers) { if (controller instanceof IosController && ((IosController) controller).getController() == gcController) { oldReference = (IosController) controller; } } if (oldReference != null) { controllers.removeValue(oldReference, true); synchronized (listeners) { for (ControllerListener listener : listeners) listener.disconnected(oldReference); } oldReference.dispose(); } } @Override public void addListener(ControllerListener controllerListener) { initializeControllerArray(); synchronized (listeners) { if (!listeners.contains(controllerListener, true)) listeners.add(controllerListener); } } @Override public void removeListener(ControllerListener controllerListener) { synchronized (listeners) { listeners.removeValue(controllerListener, true); } } @Override public Array<ControllerListener> getListeners() { return listeners; } @Override public void clearListeners() { synchronized (listeners) { listeners.clear(); } } }
[ "bs@golfgl.de" ]
bs@golfgl.de
c8e2c0ba53272eef28d4a2cc567e459a9a4d025b
cf0b2e2fcd3838e470cb4c205dda8cc05ac11628
/hotils-core/src/main/java/org/hotilsframework/lang/FatalInstanceException.java
292532cba00a14c9c72af39cf11695330ae246c9
[]
no_license
hireny/hotils
b216b2991c7f3ad6447dbcc8433a9a771e8be1e3
0b59a3853d5e636a4a499cca8e7799d540ece62b
refs/heads/master
2021-09-10T02:05:54.275527
2021-08-26T14:44:08
2021-08-26T14:44:08
225,169,822
0
0
null
2020-10-13T20:59:23
2019-12-01T13:54:30
Java
UTF-8
Java
false
false
868
java
package org.hotilsframework.lang; /** * 这个异常主要针对:对类进行实例化失败。 * @author hireny * @className CannotInstanceException * @create 2020-02-21 21:25 */ public class FatalInstanceException extends NestedRuntimeException { private static final long serialVersionUID = 4251359161254269742L; public FatalInstanceException() { super(); } public FatalInstanceException(String message) { super(message); } public FatalInstanceException(String message, Throwable cause) { super(message, cause); } public FatalInstanceException(Throwable cause) { super(cause); } protected FatalInstanceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
[ "910502500@qq.com" ]
910502500@qq.com
c544457890d3e369723a2977a94f2acb8a89ea8f
b9d1c473a18b4834da5e16feaf773554bcdfd807
/ap1/UserCompare.java
7bbb8559d17a25ddfcd3ff34f5f43fa7c7943154
[]
no_license
lzhan107/CodingBat
cd04c8a1aa1fcda1bd13478ccc5d60f164e5dde4
4adeae881ad0a26f41c1b55d740a5575af594531
refs/heads/master
2021-01-13T16:10:22.692737
2014-08-04T21:12:05
2014-08-04T21:12:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
479
java
package ap1; public class UserCompare { public static int userCompare(String aName, int aId, String bName, int bId) { int nameOrder = aName.compareToIgnoreCase(bName); if (nameOrder == 0) { if (aId < bId) { return -1; } else if (aId > bId) { return 1; } else { return 0; } } else if (nameOrder < 0) { return -1; } else { return 1; } } public static void main(String[] args) { System.out.println(userCompare("bb", 1, "zz", 2)); } }
[ "Lzhan107@gmail.com" ]
Lzhan107@gmail.com
7a71d5222e13d5460865469189fc43ce9beab93f
ea48509d44177fa42f7b172a335d0bea0b454c96
/gradletrans/gson/trans/gson/src/test/java/com/google/gson/functional/ThrowableFunctionalTest.java
6c7bf88219fc81ed657f17c414167eb0888aac0d
[ "Apache-2.0" ]
permissive
touchlab-lab/DoppelPoc
b2850a7a057b0f2e5955303badf92dcaf4d671ba
0d13d71a20b64c6c371c1bf6fc43bd6a69e9ea53
refs/heads/master
2021-06-09T14:57:56.642071
2016-11-30T15:50:36
2016-11-30T15:50:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,497
java
// Copyright (C) 2014 Trymph Inc. package com.google.gson.functional; import java.io.IOException; import junit.framework.TestCase; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import co.touchlab.doppel.testing.DoppelTest; @SuppressWarnings("serial") @DoppelTest public final class ThrowableFunctionalTest extends TestCase { private final Gson gson = new Gson(); public void testExceptionWithoutCause() { RuntimeException e = new RuntimeException("hello"); String json = gson.toJson(e); assertTrue(json.contains("hello")); e = gson.fromJson("{'detailMessage':'hello'}", RuntimeException.class); assertEquals("hello", e.getMessage()); } /*public void testExceptionWithCause() { Exception e = new Exception("top level", new IOException("io error")); String json = gson.toJson(e); assertTrue(json.contains("{\"detailMessage\":\"top level\",\"cause\":{\"detailMessage\":\"io error\"")); e = gson.fromJson("{'detailMessage':'top level','cause':{'detailMessage':'io error'}}", Exception.class); assertEquals("top level", e.getMessage()); assertTrue(e.getCause() instanceof Throwable); // cause is not parameterized so type info is lost assertEquals("io error", e.getCause().getMessage()); }*/ public void testSerializedNameOnExceptionFields() { MyException e = new MyException(); String json = gson.toJson(e); assertTrue(json.contains("{\"my_custom_name\":\"myCustomMessageValue\"")); } public void testErrorWithoutCause() { OutOfMemoryError e = new OutOfMemoryError("hello"); String json = gson.toJson(e); assertTrue(json.contains("hello")); e = gson.fromJson("{'detailMessage':'hello'}", OutOfMemoryError.class); assertEquals("hello", e.getMessage()); } /*public void testErrornWithCause() { Error e = new Error("top level", new IOException("io error")); String json = gson.toJson(e); assertTrue(json.contains("top level")); assertTrue(json.contains("io error")); e = gson.fromJson("{'detailMessage':'top level','cause':{'detailMessage':'io error'}}", Error.class); assertEquals("top level", e.getMessage()); assertTrue(e.getCause() instanceof Throwable); // cause is not parameterized so type info is lost assertEquals("io error", e.getCause().getMessage()); }*/ private static final class MyException extends Throwable { @SerializedName("my_custom_name") String myCustomMessage = "myCustomMessageValue"; } }
[ "kgalligan@gmail.com" ]
kgalligan@gmail.com
1eca1442d0fcaff4952ab55e8e0ca615bf54837e
46acc5f6b0b86533549cdd2315cb851779e75b0b
/app/src/main/java/com/example/tictactoe_petar_angelov/gameComponents/Bot.java
a99b40af3677a526ff0e198e213b6646201f9337
[]
no_license
Petretooo/TicTacToe_AI
eba9cd9f752b514f89eaa9ef9d8e08074970a754
5a435fb7d1e7f6122e26a742d5b69e51d4928259
refs/heads/main
2023-03-12T16:44:25.789307
2021-02-26T08:18:29
2021-02-26T08:18:29
315,783,558
0
0
null
null
null
null
UTF-8
Java
false
false
2,077
java
package com.example.tictactoe_petar_angelov.gameComponents; import com.example.tictactoe_petar_angelov.PlayActivity; import java.util.List; public class Bot { public int position = 0; private int score; public Bot() { } private Bot(int score){ this.score = score; } private Bot(int score, int position){ this.score = score; this.position=position; } private Bot score(Board game){ int score ; switch (game.getGameResult()){ case 0:score=0; break; case 1:score=1; break; case 2:score=-1; break; default: score =999; break; } return new Bot(score); } public Bot findingPerfectPosition(Board game){ game.getGameResult(); if (game.gameOverCHECK){ PlayActivity.counter++; return score(game); }else { int currentScore = 0; int bestScoreForMove = 0; int bestMove=0; Board gameCopy; if (game.getCurrentPlayer().equals("You")){ bestScoreForMove=-666; }else if(game.getCurrentPlayer().equals("AI")){ bestScoreForMove=666; } List<Integer> moves = game.availablePositions(); for (int i=0;i<moves.size();i++){ gameCopy=game.copyGameBoard(); gameCopy.setOnPosition(moves.get(i)); currentScore= findingPerfectPosition(gameCopy).score; if (game.getCurrentPlayer().equals("You")){ if (currentScore > bestScoreForMove){ bestScoreForMove=currentScore; bestMove=moves.get(i); } }else { if (currentScore < bestScoreForMove){ bestScoreForMove=currentScore; bestMove=moves.get(i); } } } return new Bot(bestScoreForMove,bestMove); } } }
[ "P37arAn93l0bv!" ]
P37arAn93l0bv!
660e2ad5948f820f64eb6ba8b4885ef55e8d8db6
b9bc9f9070c1774388f268d58a9c528c613582e9
/src/main/java/com/liang/controller/UserController.java
307ca8da883e5f06f3d7104a6fa53bd7d9627495
[]
no_license
liangbeng/myssm3
8687f6bed785469866663227c21b38ff0738de5d
e39b3bfadf99e6b0d565adc6f298a5f9565b315e
refs/heads/main
2023-04-09T09:51:17.211203
2021-03-03T10:38:22
2021-03-03T10:38:22
344,047,588
0
0
null
2021-03-03T10:38:22
2021-03-03T08:01:13
Java
UTF-8
Java
false
false
727
java
package com.liang.controller; import com.alibaba.fastjson.JSON; import com.liang.pojo.User; import com.liang.service.UserService; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @RestController @RequestMapping("/user") public class UserController { @Resource private UserService userService; @RequestMapping(value = "/add",method = RequestMethod.POST) public void addUser(@RequestBody User user){ userService.insertUser(user); } @RequestMapping(value = "/findById",method = RequestMethod.GET) public String findById(@RequestParam("id") int id){ User userById = userService.findUserById(id); return JSON.toJSONString(userById); } }
[ "qxdz6dbx" ]
qxdz6dbx
a1f5cb85db8233e1478b4852692b5226c5baeec7
3374b442432c922128d346d9bc21f560fc1d0ee3
/customer-service/src/main/java/pl/piomin/microservices/customer/Application.java
9637743024374a87b26011ae236c19a46eefd899
[]
no_license
yashdevops27/microservices
2ef4d905976a32f31e6e03c403460085cc7a7bd2
4ba648a62ea9fb037ec5a6b1bdcea312a5b576a5
refs/heads/master
2020-07-11T20:33:35.070480
2020-06-15T17:17:38
2020-06-15T17:17:38
204,639,173
0
2
null
null
null
null
UTF-8
Java
false
false
496
java
package pl.piomin.microservices.customer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
[ "varsha.patil@yash.com" ]
varsha.patil@yash.com
2e78b8edd2e7f1a9260b898d518338c47f2d4b22
684e018ce44456ad860b9bbd01ca0fcf40be296d
/src/main/java/com/leetcode/algorithm/No23/Solution.java
412cf56bf3758148cf1dfb80fa644f1f29a9b6f2
[]
no_license
Nagisa12321/LeetCode
ebcfc5d9508e9e5feb1a9d44932f28f19d1ac3e2
14d0bd9e95fe1eef57678e3dbf3fb6751ee196d1
refs/heads/master
2023-07-15T21:32:51.265786
2021-08-29T03:37:14
2021-08-29T03:37:14
316,138,604
1
0
null
null
null
null
UTF-8
Java
false
false
771
java
package com.leetcode.algorithm.No23; import com.leetcode.struct.ListNode; import java.util.Comparator; import java.util.PriorityQueue; /** * @author jtchen * @version 1.0 * @date 2021/7/30 9:54 */ public class Solution { public ListNode mergeKLists(ListNode[] lists) { PriorityQueue<ListNode> queue = new PriorityQueue<>(Comparator.comparingInt(node -> node.val)); for (ListNode list : lists) { ListNode cur = list; while (cur != null) { queue.offer(cur); cur = cur.next; } } if (queue.isEmpty()) return null; ListNode head = new ListNode(queue.poll().val); ListNode cur = head; while (!queue.isEmpty()) { cur.next = new ListNode(queue.poll().val); cur = cur.next; } return head; } }
[ "1216414009@qq.com" ]
1216414009@qq.com
9ed4517bac8ff595e31206d9cfc13daba14dbd2e
7b457ebd94832a94d0df3b241e573a7e827891f8
/laufometer.webapp/src/main/java/de/tp82/laufometer/web/controllers/TickController.java
978c2e3dc71755bee9c674f93d6d1baf0ab144d1
[]
no_license
ThorstenPlatz/laufometer-webapp
a716b4e3a8a46f5e2a4774c4d53bfa52fd3a3c74
df26b20afb519a5b9a50ecacb0d234e794aff5bd
refs/heads/master
2020-05-17T19:37:04.857427
2013-05-09T09:44:12
2013-05-09T09:44:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,801
java
package de.tp82.laufometer.web.controllers; import com.google.common.collect.Lists; import com.google.common.net.MediaType; import de.tp82.laufometer.core.RunRepository; import de.tp82.laufometer.core.TickImportHelper; import de.tp82.laufometer.core.importer.RunImporter; import de.tp82.laufometer.model.run.RunInterval; import de.tp82.laufometer.util.ExceptionHandling; import org.gmr.web.multipart.GMultipartFile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Thorsten Platz */ @Controller @RequestMapping(value = "/tick") public class TickController { private static final Logger LOG = Logger.getLogger(TickController.class.getName()); @Autowired RunRepository runRepository; @Autowired RunImporter runImporter; @RequestMapping(value="/upload", method = RequestMethod.POST) public String uploadTicksAction(ModelMap model, @RequestParam(value="ticksFile", required = false) GMultipartFile ticksFile, @RequestParam(value="ticksText", required = false) String ticksText, @RequestParam(value="skipKnownTicks", required = false, defaultValue = "true") boolean skipKnownTicks, HttpServletRequest request) { ActionResult result; try { List<Date> ticks = Lists.newArrayList(); if(ticksFile != null) { ticks.addAll(TickImportHelper.extractTicks(ticksFile.getInputStream(), MediaType.parse(ticksFile.getContentType()))); } if(ticksText != null) ticks.addAll(TickImportHelper.extractTicks(ticksText)); List<RunInterval> importedRuns = runImporter.importTicksAsRuns(ticks, skipKnownTicks); result = ActionResult .success("Imported " + importedRuns.size() + " runs.") .next("../") .previous(ActionResult.NAVIGATION_NONE) .build(); } catch (Exception exc) { if(LOG.isLoggable(Level.WARNING)) { String stacktrace = ExceptionHandling.getStacktrace(exc); LOG.warning("Error during import: " + exc + ". Stacktrace follows:\n" + stacktrace); } result = ActionResult .error("Error during import: " + exc) .build(); } model.put("result", result); return "generic/actionResult"; } @RequestMapping(value="/upload", method = RequestMethod.GET) public String uploadTicksForm() { return "tick/uploadTicks"; } }
[ "thorsten.platz@capgemini.com" ]
thorsten.platz@capgemini.com
185fa2f0a3d1a8b31a73009a48d5c9ad25a575c6
99dfacbdb2dbe59e8822a8a422feebcf9b4f84e1
/spaceship-sdk/src/main/java/com/spaceship/client/model/InlineResponse2004.java
b80055dfb3cf67fa09ce4839c8f63fd205ed08ab
[]
no_license
simon-atta/spaceship
e389f0c7e7dabee4f002f71ba541eb756bf6e31b
ddf729fc857bede8438f56ff302eb2e20e46a174
refs/heads/master
2021-09-26T21:29:06.214609
2021-09-15T16:48:08
2021-09-15T16:48:08
168,671,226
0
0
null
null
null
null
UTF-8
Java
false
false
2,247
java
/* * Spaceship API * Spaceship API help for commincate between spaceships * * OpenAPI spec version: 1.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.spaceship.client.model; import java.util.ArrayList; import java.util.List; import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModelProperty; /** * InlineResponse2004 */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-05-18T19:52:26.338Z") public class InlineResponse2004 { @SerializedName("board") private List<List<String>> board = new ArrayList<List<String>>(); public InlineResponse2004 board(List<List<String>> board) { this.board = board; return this; } public InlineResponse2004 addBoardItem(List<String> boardItem) { this.board.add(boardItem); return this; } /** * Get board * * @return board **/ @ApiModelProperty(example = "null", value = "") public List<List<String>> getBoard() { return board; } public void setBoard(List<List<String>> board) { this.board = board; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InlineResponse2004 inlineResponse2004 = (InlineResponse2004) o; return Objects.equals(this.board, inlineResponse2004.board); } @Override public int hashCode() { return Objects.hash(board); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse2004 {\n"); sb.append(" board: ").append(toIndentedString(board)).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(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
[ "simon.ghobreil1@ikea.com" ]
simon.ghobreil1@ikea.com
c94de45c9563ff5e4fd6656e137712cd33308577
e1e432d66fb8a8bc5908e14e8f83132e3cf60e3e
/labs/lab08/src/lab08Test.java
9a867a68a2a7e13d1c904f3d4414c5f433a31bff
[]
no_license
aranga1/CS180
1695a54eb9a3029c28d1e7b618d51638c0bea08b
a2230c8255b93b3b75b94ec8c32a866966571671
refs/heads/master
2016-08-12T04:14:22.220076
2015-10-25T02:47:53
2015-10-25T02:47:53
44,722,616
4
0
null
null
null
null
UTF-8
Java
false
false
4,969
java
import static org.junit.Assert.*; import org.junit.Test; public class lab08Test { private Car c; private CarLot x; @Test(timeout = 100) public void testgetMake() { c = new Car("red" , "ford"); String actual = c.getMake(); String expected = "ford"; String message = "getMake() check if method is working properly"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void testgetMakeWhenNull() { c = new Car("red" , null); String actual = c.getMake(); String expected = ""; String message = "getMake() check if method is working properly when input String is null"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void testgetColor() { c = new Car("red" , "ford"); String actual = c.getColor(); String expected = "red"; String message = "getColor() check if method is working properly"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void testgetColorWhenNull() { c = new Car(null, "ford"); String actual = c.getColor(); String expected = ""; String message = "getColor() check if method is working properly when input String is null"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void testCapacity() { x = new CarLot(10); int actual = x.capacity(); int expected = 10; String message = "capacity() check if method is working properly"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void numVehicles() { x = new CarLot(10); int actual = x.numVehicles(); int expected = 0; String message = "numVehicles() check if method is working properly"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void numVehiclesWhenCarPresent() { x = new CarLot(10); x.cars[3] = new Car("red", "chevy"); int actual = x.numVehicles(); int expected = 1; String message = "numVehicles() check if method is working properly"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void addCar() { x = new CarLot(1); boolean actual = x.add(new Car("Black" , "Mustang")); boolean expected = true; String message = "add() check if method is working properly"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void addCarWhenNoSpace() { x = new CarLot(1); x.cars[0] = new Car("red", "chevy"); boolean actual = x.add(new Car("Black" , "Mustang")); boolean expected = false; String message = "add() check if method is working properly when no space is present"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void getCar() { x = new CarLot(1); x.cars[0] = new Car("red", "chevy"); Car actual = x.get(0); Car expected = x.cars[0]; String message = "get() check if method is working properly when car is present"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void getCarWhenNoCar() { x = new CarLot(1); Car actual = x.get(0); Car expected = null; String message = "get() check if method is working properly when no car is present"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void removeCar() { x = new CarLot(1); x.cars[0] = new Car("red", "chevy"); Car actual = x.remove(0); Car expected = x.cars[0]; String message = "remove() check if method is working properly when a car is present"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void removeCarWhenNoCar() { x = new CarLot(1); Car actual = x.remove(0); Car expected = null; String message = "remove() check if method is working properly when no car is present"; assertEquals(message, expected, actual); } @Test(timeout = 100) public void searchByMake() { x = new CarLot(1); x.cars[0] = new Car("red", "chevy"); boolean[] actual = x.searchByMake("chevy"); boolean[] expected = {true}; String message = "searchByMake() check if method is working properly when no space is present"; assertEquals(message, expected[0], actual[0]); } @Test(timeout = 100) public void searchByMakeWhenMoreThanOneCarPresent() { x = new CarLot(2); x.cars[0] = new Car("red", "chevy"); x.cars[1] = new Car("red", "chevy"); boolean[] actual = x.searchByMake("chevy"); boolean[] expected = {true, true}; String message = "searchByMake() check if method is working properly when no space is present"; assertEquals(message, expected[0], actual[0]); assertEquals(message, expected[1], actual[1]); } @Test(timeout = 100) public void searchByMakeWhenNoCars() { x = new CarLot(2); x.cars[0] = new Car("red", "chevy"); x.cars[1] = new Car("red", "chevy"); boolean[] actual = x.searchByMake("ford"); boolean[] expected = {false, false}; String message = "searchByMake() check if method is working properly when no current make is present"; assertEquals(message, expected[0], actual[0]); assertEquals(message, expected[1], actual[1]); } }
[ "aranga@purdue.du" ]
aranga@purdue.du
ee219e9fdb956cb26d46cd1dafd4bf2062cd7002
1dd399e322fd936a02e1700c2b3beea05ff0993b
/src/main/java/br/edu/ifsp/app/MyResource.java
c605245a8a57d52cdcc1d8352e9b03a74bbff9c1
[]
no_license
giovanidisperati/ADI
ff483cb3e7e2ef56ee61505f07ef46ea1eb9f95b
061a735029562537f83e990951438d649ca2692e
refs/heads/master
2022-08-08T07:09:46.420080
2019-09-17T22:36:29
2019-09-17T22:36:29
203,045,562
0
1
null
2022-06-21T01:53:17
2019-08-18T19:07:01
Java
UTF-8
Java
false
false
567
java
package br.edu.ifsp.app; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * Root resource (exposed at "myresource" path) */ @Path("myresource") public class MyResource { /** * Method handling HTTP GET requests. The returned object will be sent * to the client as "text/plain" media type. * * @return String that will be returned as a text/plain response. */ @GET @Produces(MediaType.TEXT_PLAIN) public String getIt() { return "Got it!"; } }
[ "giovani@ifsp.edu.br" ]
giovani@ifsp.edu.br
d5fd14ea8210389ea0812bca8a59f455c29b3bf2
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/java/neo4j/2019/8/AdversarialFileChannel.java
a51a51945b5606c1a3f411cf9d497afd127e92ef
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
Java
false
false
6,720
java
/* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.adversaries.fs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileLock; import org.neo4j.adversaries.Adversary; import org.neo4j.io.fs.StoreChannel; import org.neo4j.io.fs.StoreFileChannel; @SuppressWarnings( "unchecked" ) public class AdversarialFileChannel extends StoreFileChannel { private final StoreChannel delegate; private final Adversary adversary; public static StoreFileChannel wrap( StoreFileChannel channel, Adversary adversary ) { return new AdversarialFileChannel( channel, adversary ); } private AdversarialFileChannel( StoreFileChannel channel, Adversary adversary ) { super( channel ); this.delegate = channel; this.adversary = adversary; } @Override public long write( ByteBuffer[] srcs ) throws IOException { if ( adversary.injectFailureOrMischief( IOException.class ) ) { ByteBuffer mischievousBuffer = srcs[srcs.length - 1]; int oldLimit = mischiefLimit( mischievousBuffer ); long written = delegate.write( srcs ); mischievousBuffer.limit( oldLimit ); return written; } return delegate.write( srcs ); } @Override public void writeAll( ByteBuffer src, long position ) throws IOException { adversary.injectFailure( IOException.class ); delegate.writeAll( src, position ); } @Override public void writeAll( ByteBuffer src ) throws IOException { adversary.injectFailure( IOException.class ); delegate.writeAll( src ); } @Override public long write( ByteBuffer[] srcs, int offset, int length ) throws IOException { if ( adversary.injectFailureOrMischief( IOException.class ) ) { length = length == 1 ? 1 : length / 2; ByteBuffer mischievousBuffer = srcs[offset + length - 1]; int oldLimit = mischiefLimit( mischievousBuffer ); long written = delegate.write( srcs, offset, length ); mischievousBuffer.limit( oldLimit ); return written; } return delegate.write( srcs, offset, length ); } @Override public StoreFileChannel truncate( long size ) throws IOException { adversary.injectFailure( IOException.class ); return (StoreFileChannel) delegate.truncate( size ); } @Override public StoreFileChannel position( long newPosition ) throws IOException { adversary.injectFailure( IOException.class ); return (StoreFileChannel) delegate.position( newPosition ); } @Override public int read( ByteBuffer dst, long position ) throws IOException { if ( adversary.injectFailureOrMischief( IOException.class ) ) { int oldLimit = mischiefLimit( dst ); int read = delegate.read( dst, position ); dst.limit( oldLimit ); return read; } return delegate.read( dst, position ); } private int mischiefLimit( ByteBuffer buf ) { int oldLimit = buf.limit(); int newLimit = oldLimit - buf.remaining() / 2; buf.limit( newLimit ); return oldLimit; } @Override public void force( boolean metaData ) throws IOException { adversary.injectFailure( IOException.class ); delegate.force( metaData ); } @Override public int read( ByteBuffer dst ) throws IOException { if ( adversary.injectFailureOrMischief( IOException.class ) ) { int oldLimit = mischiefLimit( dst ); int read = delegate.read( dst ); dst.limit( oldLimit ); return read; } return delegate.read( dst ); } @Override public long read( ByteBuffer[] dsts, int offset, int length ) throws IOException { if ( adversary.injectFailureOrMischief( IOException.class ) ) { ByteBuffer lastBuf = dsts[dsts.length - 1]; int oldLimit = mischiefLimit( lastBuf ); long read = delegate.read( dsts, offset, length ); lastBuf.limit( oldLimit ); return read; } return delegate.read( dsts, offset, length ); } @Override public long position() throws IOException { adversary.injectFailure( IOException.class ); return delegate.position(); } @Override public FileLock tryLock() throws IOException { adversary.injectFailure( IOException.class ); return delegate.tryLock(); } @Override public boolean isOpen() { adversary.injectFailure(); return delegate.isOpen(); } @Override public long read( ByteBuffer[] dsts ) throws IOException { if ( adversary.injectFailureOrMischief( IOException.class ) ) { ByteBuffer lastBuf = dsts[dsts.length - 1]; int oldLimit = mischiefLimit( lastBuf ); long read = delegate.read( dsts ); lastBuf.limit( oldLimit ); return read; } return delegate.read( dsts ); } @Override public int write( ByteBuffer src ) throws IOException { if ( adversary.injectFailureOrMischief( IOException.class ) ) { int oldLimit = mischiefLimit( src ); int written = delegate.write( src ); src.limit( oldLimit ); return written; } return delegate.write( src ); } @Override public void close() throws IOException { adversary.injectFailure( IOException.class ); delegate.close(); } @Override public long size() throws IOException { adversary.injectFailure( IOException.class ); return delegate.size(); } @Override public void flush() throws IOException { force( false ); } }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
21304d6f6ab16aa4f01795189121ef841c2fb9e7
80469e6bc041910a5fdeb7b932286e67529bcb5c
/src/com/java/loops/LoopExercise.java
4f41f87f1c3944e3e9892a5673fb8aa26332930f
[]
no_license
alokbarman/Java-Exercise
c3c577c14d63df11b9adf533ea21bb02cbe1557e
dcd066d63d149c12f90e3b7e63478e64222c9fe2
refs/heads/master
2020-04-02T20:04:41.935531
2018-10-26T01:01:12
2018-10-26T01:01:12
154,757,254
0
0
null
null
null
null
UTF-8
Java
false
false
262
java
package com.java.loops; //(Ques.1.Write a for loop that prints 50 through 1 separeted by spaces in the same line.) public class LoopExercise { public static void main(String[] args) { for(int i=50;i>=1;i=i-1) { System.out.print(i+","); } } }
[ "alokgr88@gmail.com" ]
alokgr88@gmail.com
10c2f76f1e36db36d4b7a52ef4c99a8245bbd53f
8d1142c34f7ef5cb63c5e3115f4b58e19c036b51
/dump-code/panelpower/a.b.a.h.c.java
f0c3b6571a11e31a63dead8c73284550cc7e6fe1
[]
no_license
kingking888/android-auto-hack
b19c979f2c39a3584ba5841c7b13b253cfc798c8
e91cb827c7ebf53ad253f965df55bfcaa9e82c32
refs/heads/master
2021-01-26T11:09:51.958052
2020-02-27T02:59:49
2020-02-27T02:59:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,401
java
package a.b.a.h; import a.b.a.c.a; import a.b.a.f; import a.b.a.g; import android.app.AlarmManager; import android.app.AlarmManager.AlarmClockInfo; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build.VERSION; import androidx.core.app.NotificationCompat; import com.embrain.panelpower.IConstValue.SavedMoney; import com.loplat.placeengine.EventReceiver; import com.loplat.placeengine.PlaceEngineBase; /* compiled from: PlaceEngineTimer */ public class c { /* renamed from: a reason: collision with root package name */ public static int f45a = 180901; public static void a(Context context, int i) { try { AlarmManager alarmManager = (AlarmManager) context.getSystemService(NotificationCompat.CATEGORY_ALARM); if (alarmManager != null) { PendingIntent broadcast = PendingIntent.getBroadcast(context, f45a, b(context), 268435456); long j = (long) i; long currentTimeMillis = System.currentTimeMillis() + j; if (VERSION.SDK_INT >= 23) { if (VERSION.SDK_INT >= 26) { if (a.a(context, (String) "lhtibaq5ot47p0xrinly", (String) SavedMoney.GIVE_TP_GIFT_CARD_ONLINE, false)) { alarmManager.setAlarmClock(new AlarmClockInfo(currentTimeMillis, null), broadcast); } } alarmManager.setExactAndAllowWhileIdle(0, currentTimeMillis, broadcast); } else { alarmManager.setRepeating(0, currentTimeMillis, j, broadcast); } StringBuilder sb = new StringBuilder(); sb.append("setScanTimer: "); sb.append(i); sb.append(", sdk: "); sb.append(VERSION.SDK_INT); sb.toString(); } } catch (Exception unused) { } } public static Intent b(Context context) { Intent intent = new Intent(PlaceEngineBase.ENGINE_EVENT_SCAN_WIFI); intent.setPackage(context.getPackageName()); if (VERSION.SDK_INT >= 26 && a.b.a.g.a.m(context) >= 26) { intent.setClass(context, EventReceiver.class); } return intent; } public static void c(Context context) { int i; a(context); int h = a.b.a.g.a.h(context); if (h == 0) { if (f.f(context) == 2) { i = a.b.a.g.a.j(context); } else { i = a.b.a.g.a.i(context); } } else if (h != 1) { i = a.b.a.g.a.i(context); } else if (g.j(context) == 1) { i = a.b.a.g.a.l(context); } else { i = a.b.a.g.a.k(context); } a(context, i); } public static void a(Context context) { try { AlarmManager alarmManager = (AlarmManager) context.getSystemService(NotificationCompat.CATEGORY_ALARM); if (alarmManager != null) { PendingIntent broadcast = PendingIntent.getBroadcast(context, f45a, b(context), 536870912); if (broadcast != null) { alarmManager.cancel(broadcast); broadcast.cancel(); } } } catch (Exception unused) { } } }
[ "rjsdid7325@naver.com" ]
rjsdid7325@naver.com
0d49aeadb917d1820edd7b5fe742caace9aa9c90
d3cec8d89422b43c636e74f82c0453c232fc980e
/app/src/main/java/com/example/hermes/bitcointwallet/ViewHolder.java
c9aa2a1ed4a72c5a63b7e79b647efdfcaec1e828
[]
no_license
LorandP/BitcoinWallet
658034abf35291b7f40e94c1396ceec3eaa7316c
9bd603d327d9da36a37bfa456f2c02c31d3d82a7
refs/heads/master
2020-03-23T19:27:39.383788
2018-07-23T07:54:18
2018-07-23T07:54:18
141,979,189
0
0
null
null
null
null
UTF-8
Java
false
false
477
java
package com.example.hermes.bitcointwallet; import android.widget.ImageView; import android.widget.TextView; /** * Created by Hermes on 26/05/2017. * * This class is used to hold the view types that we are going to use to populate the list. */ public class ViewHolder { TextView mTime; TextView mHashString; TextView mNote; TextView mBTCValue; ImageView mVerticalLine; TextView mBTCValueRed; TextView mDots; TextView mDotsGreen; }
[ "palfalvi.lorand@gmail.com" ]
palfalvi.lorand@gmail.com
21bbccb3609e54b27e230bc15962a40d2a2d72dc
a8d2807e15c6fc23f0297ab6231f0ead2338216f
/Iterations/src/iterations/myClass.java
6aeeb6186facaebaeb4ce64e78a918b39e195ed8
[]
no_license
lungeloShabangu/My-Project
bed76acce19466ddf8f0fd7d1bc1e19124414f5e
4588e73748b59110d1110ceeb46aff35457fe08a
refs/heads/master
2020-03-30T16:26:21.420768
2018-10-04T08:42:28
2018-10-04T08:42:28
151,408,827
0
1
null
null
null
null
UTF-8
Java
false
false
8,229
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package iterations; /** * * @author User */ public class myClass { //1 finding the highest value in an array public int findLargentnumber(int[] myArr){ int highest=0; for(int i=0; i<=myArr.length-1;i++){ if(myArr[i]>highest) highest=myArr[i]; } return highest; } //2 finding the second largest value in an array public int findSecondLargest(int arrNum[]){ int LargestNum = 0; int largestPos = 0; int SecondLargestNum = 0; for (int i = 0; i < arrNum.length; i++) { if (arrNum[i] > LargestNum) { LargestNum = arrNum[i]; largestPos = i; } } for (int j = 0; j < arrNum.length; j++) { if (arrNum[j] > SecondLargestNum) { if (j != largestPos) { SecondLargestNum = arrNum[j]; } } } return SecondLargestNum; } //3 Finding checking if a value is in an array public String contains(int[] myArr, int number){ for (final int i : myArr) { if (i == number) { return " exists in the array"; } } return " doesn't exist in an array"; } //4 finds the value with maximum occurences public int occurence(int myArr[],int number){ int res = 0; for (int i=0; i<myArr.length; i++) if (number == myArr[i]) res++; return res; } //5 finds the maximum occurence of a number public int maxRepeating(int arr[]) { // find the max frequency using linear // traversal int max_count = 1, res = arr[0]; int curr_count = 1; for (int i = 1; arr.length-1 >= i; i++) { if (arr[i] == arr[i - 1]) curr_count++; else { if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } curr_count = 1; } } // If last element is most frequent if (curr_count > max_count) { max_count = curr_count; res = arr[arr.length - 1]; } return res; } //6 method to count spaces in a string public int countSpaces(String Name){ int count =0; for(int i=0;i<Name.length()-1;i++){ if(Character.isWhitespace(Name.charAt(i))) count+=1; } return count; } //7 Method for counting number of words in a sentence public int countWords(String sentence){ if(sentence == null || sentence.isEmpty()){ return 0; } String[] numWords= sentence.split("\\s+"); return numWords.length; } //8 Method to replace all spaces with underscore public void replaceSpaces(String myString) { // Replace letter with underscore. String result = myString.replace(' ', '_'); System.out.println(result); } //9 Sorting an array in ascending order public int[] sortArray(int[] nonSortedArray) { int[] sortedArray = new int[nonSortedArray.length]; int temp; for (int i = 0; i < nonSortedArray.length - 1; i++) { if (nonSortedArray[i] > nonSortedArray[i + 1]) { temp = nonSortedArray[i]; nonSortedArray[i] = nonSortedArray[i + 1]; nonSortedArray[i + 1] = temp; sortedArray = nonSortedArray; } } return sortedArray; } //10 Finding all even numbers in array public int findEven(int[] myArr){ int evenNum=0; for(int x =0; x<myArr.length;x++){ if(myArr[x]%2==0) evenNum+=myArr[x]; System.out.println(evenNum); } return evenNum; } //11 Generating a fibonacci series from 1 to N //every number after the first two is the sum of the two preceding ones public void generateFibonacci(int n){ int t1 = 0, t2 = 1; int sum=0; while (t1 <= n) { sum = t1 + t2; t1 = t2; t2 = sum; System.out.println(sum); } } //12 Reversing a string public void reverseString(String strOriginal) { char[] temparray = strOriginal.toCharArray(); int left, right=0; right = temparray.length-1; for (left=0; left < right ; left++ ,right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right]=temp; } for (char c : temparray) System.out.print(c); System.out.println(); } //13 Converting numeric value "1234" to 1234 public int convertString(String myInput){ int number= Integer.parseInt(myInput); return number; } //14 Find the sum of odd numbers from one to n public int findSumOfOddNumbersInArray(int num){ int sumOdd=0; for(int i =1; i <=num;i++){ if(i % 2 != 0) sumOdd+=i; } return sumOdd; } //15 Finding number of number public int findNumberOfDigits(int num){ int count = 0; while(num != 0) { // num = num/10 num /= 10; ++count; } return count; } //16 Claculating the sum of digits in a number public int sumOfDigits(int num){ int sum=0; while (num > 0) { sum = sum + num % 10; num = num / 10; } return sum; } //17 Reversing number public void reverseNumber(int num){ reverseString(Integer.toString(num)); } //18 Swapping first and last digit public void swapFirstAndLast(int number){ int result = 0; int place = 1; while (number > 9) { result += place * 10 * (number % 10); number /= 10; result += place * (number % 10); number /= 10; place *= 100; } System.out.println(result); } //19 Check if alphabe is vowl or consonent public String VowelCheck(char alphabet) { switch (alphabet) { case 'A': case 'a': case 'E': case 'e': case 'I': case 'i': case 'O': case 'o': case 'U': case 'u': { return "Vowel"; } default: { return "Consonent"; } } } //20 Find the maximum difference between two consecutive items in an array of numbers public int findMaxDifferenceBtwnTwoConsequtives(int[] myArr){ int difference = 0; int maxiDifference = 0; for (int i = 0; i < myArr.length-1; i++) { difference = myArr[i + 1] - myArr[i]; if (difference > maxiDifference) { maxiDifference = difference; } } return maxiDifference; } }
[ "lungelo.shabangu101gmail.com" ]
lungelo.shabangu101gmail.com
9f2449bf1ea882981f00162668515a3d3a6ec984
09608caeb319ce95ce11fa950b54485a20a6a45f
/weevent-governance/src/main/java/com/webank/weevent/governance/entity/base/RuleDatabaseBase.java
26b51e8a785d8305a1ea8e55c164c7b6a051f34c
[ "Apache-2.0" ]
permissive
jamexialove/WeEvent
15266d639c5bf44e3e3906afec5280699ce6fe47
d39ef2303a8d683ff6260c605f49f01b46fb0a8d
refs/heads/master
2020-09-20T22:58:57.339439
2019-11-25T09:46:47
2019-11-25T09:46:47
224,611,990
1
0
Apache-2.0
2019-11-28T09:02:53
2019-11-28T09:02:53
null
UTF-8
Java
false
false
505
java
package com.webank.weevent.governance.entity.base; import lombok.Data; import lombok.EqualsAndHashCode; /** * CirculationDatabaseBase class * * @since 2019/10/15 */ @Data @EqualsAndHashCode(callSuper = false) public class RuleDatabaseBase extends BaseEntity { private Integer userId; private Integer brokerId; private String databaseUrl; private String databaseName; private String tableName; /** * 1 visible ,2 invisible */ private String isVisible; }
[ "saintping@gmail.com" ]
saintping@gmail.com
a62b2950718a71403c993b8e63c3e736adad13a8
ee5be1c49c2c78ed3f74886e30a63be389f8e4fe
/app/src/main/java/lnq/com/lnq/utils/FontUtils.java
bcce6e50c2ee7bfe589757b5a58ca8e59604ed69
[]
no_license
Imran7331/lnq_training
6c26e1dfaebb06ba9eb37d7cb94b68aabf048af0
f343f588730b8d1f5ba727b4f160d572eb9c95aa
refs/heads/master
2023-08-02T05:43:09.582603
2021-09-20T13:37:27
2021-09-20T13:37:27
408,457,699
0
0
null
null
null
null
UTF-8
Java
false
false
3,586
java
package lnq.com.lnq.utils; import android.content.Context; import android.graphics.Typeface; import android.text.Spannable; import android.text.SpannableString; import android.text.style.TypefaceSpan; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; import androidx.appcompat.app.ActionBar; public class FontUtils { private static Typeface typefaceBold, typefaceRegular, typefaceSemiBold, typefaceMedium; private static FontUtils fontUtils; private FontUtils() { } public static FontUtils getFontUtils(Context context) { if (fontUtils == null) { fontUtils = new FontUtils(); typefaceBold = Typeface.createFromAsset(context.getAssets(), "fonts/sf_pro_display_bold.otf"); typefaceRegular = Typeface.createFromAsset(context.getAssets(), "fonts/sf_pro_display_regular.otf"); typefaceSemiBold = Typeface.createFromAsset(context.getAssets(), "fonts/sf_pro_display_semibold.otf"); typefaceMedium = Typeface.createFromAsset(context.getAssets(), "fonts/sf_pro_display_medium.otf"); } return fontUtils; } public void setTextViewRegularFont(TextView textView) { textView.setTypeface(typefaceRegular); } public void setTextViewBoldFont(TextView textView) { textView.setTypeface(typefaceBold); } public void setTextViewSemiBold(TextView textView) { textView.setTypeface(typefaceSemiBold); } public void setTextViewMedium(TextView textView) { textView.setTypeface(typefaceMedium); } public void setButtonRegularFont(Button button) { button.setTypeface(typefaceRegular); } public void setButtonBoldFont(Button button) { button.setTypeface(typefaceBold); } public void setButtonSemiBold(Button button) { button.setTypeface(typefaceSemiBold); } public void setButtonMedium(Button button) { button.setTypeface(typefaceMedium); } public void setEditTextRegularFont(EditText editText) { editText.setTypeface(typefaceRegular); } public void setEditTextBoldFont(EditText editText) { editText.setTypeface(typefaceBold); } public void setEditTextSemiBold(EditText editText) { editText.setTypeface(typefaceSemiBold); } public void setEditTextMedium(EditText editText) { editText.setTypeface(typefaceMedium); } public Typeface getTypefaceRegular() { return typefaceRegular; } public Typeface getTypefaceBold() { return typefaceBold; } public static Typeface getTypefaceSemiBold() { return typefaceSemiBold; } public static Typeface getTypefaceMedium() { return typefaceMedium; } public void setRadioButtonRegularFont(RadioButton radioButton) { radioButton.setTypeface(typefaceRegular); } public static void setFont(ViewGroup group) { int count = group.getChildCount(); View v; for (int i = 0; i < count; i++) { v = group.getChildAt(i); if (v instanceof TextView) { ((TextView) v).setTypeface(typefaceSemiBold); } else if (v instanceof ViewGroup) setFont((ViewGroup) v); } } /** * Sets the font on TextView */ public static void setFont(View v) { if (v instanceof TextView) { ((TextView) v).setTypeface(typefaceSemiBold); } } }
[ "awaissarwar847@gmail.com" ]
awaissarwar847@gmail.com
206f2e7ef4a51a382d4716891e8991eaa6f49cc0
73b934718e7e606095eb341320f865ba6c526e6a
/src/main/java/com/bluestar/teach/entity/School.java
227f45044438e833cedb6056220973d7eef2aec9
[]
no_license
EchoFromProgram/BlueStar_TSMS
c1fee1906d6a010e8db3d0e656c639ff8bdfa67a
c64f096c601febed50071eee3ae110fd1c7e3b12
refs/heads/master
2020-03-10T17:28:26.193815
2018-07-24T05:48:21
2018-07-24T05:48:21
129,501,117
0
0
null
null
null
null
UTF-8
Java
false
false
750
java
package com.bluestar.teach.entity; /** * 学校类,对应school表 * @author happyChicken * */ public class School { //学校id private Integer schoolId; //城市id private Integer cityId; //学校名 private String school; public Integer getSchoolId() { return schoolId; } public void setSchoolId(Integer schoolId) { this.schoolId = schoolId; } public Integer getCityId() { return cityId; } public void setCityId(Integer cityId) { this.cityId = cityId; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } @Override public String toString() { return "School [schoolId=" + schoolId + ", cityId=" + cityId + ", school=" + school + "]"; } }
[ "1149062639@qq.com" ]
1149062639@qq.com
2c44bfdc1a75b5be17e3fc069c30b2a6836fff1c
a213edcb973f341078f239164e9baa7b4e0fc7c0
/src/高频面试题/栈和队列/IsValid.java
e6bc785ec76c78d3c74a2e88688c807be2db43b0
[]
no_license
gitlhp/JavaOffer2
8e327beeaee74672075651fda450f90c79ff578c
9f850a9d10888ba47ef72987d2a20ed571002b02
refs/heads/master
2022-09-26T06:45:38.297787
2020-05-25T07:09:53
2020-05-25T07:09:53
266,709,006
0
0
null
null
null
null
UTF-8
Java
false
false
752
java
package 高频面试题.栈和队列; import java.util.Stack; /** * @ClassName: IsValid * @Description:有效的括号 * @Author: lhp * @Date: 2020/5/5 15:18 * @Version: V1.0 **/ public class IsValid { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (char c : s.toCharArray()) { if (stack.isEmpty()) { stack.push(c); } else if (isSym(c, stack.peek())) { stack.pop(); } else { stack.push(c); } } return stack.size() == 0; } private boolean isSym(char c1, char c2) { return (c1 == '(' && c2 == ')') || (c1 == '[' && c2 == ']') || (c1 == '{' && c2 == '}'); } }
[ "770284670@qq.com" ]
770284670@qq.com
09e6c6e76774ff11dc34bbafcb20e1e721fceeb4
186c4be66e518c796ec4785eb8b2ae6bfab4d63a
/src/main/java/com/sample/assignment/batch/reader/Reader.java
0ae4258dc08e3ff392f26859a4ac70c97b0c8c10
[]
no_license
BKundu/dnb-assignment
4a09ca2f9d36d1c58d638b09147df21647322142
82bfa9fd3f128d6d640036ff796f3e009d2980f2
refs/heads/master
2023-02-22T02:12:42.693832
2021-01-29T04:57:55
2021-01-29T04:57:55
334,031,626
0
0
null
null
null
null
UTF-8
Java
false
false
267
java
package com.sample.assignment.batch.reader; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; public abstract class Reader { public SparkSession session; public abstract Dataset<Row> getDF(); }
[ "biswajit.kundu@Biswajits-MacBook-Pro.local" ]
biswajit.kundu@Biswajits-MacBook-Pro.local
15408227e79a7796e6561d5f3e4738a98e9552d0
964541d36d9c176b7c489077aa71b905cb15695f
/src/main/java/org/lab/basic/Coordinate4D.java
fa83870b153c56e4893b52b191014aa006433305
[]
no_license
volodink/qweqweweq
661675b73d591713a18499573be77b378487c530
11262f5e45516b36c350c4b3cab666d02e1a7d72
refs/heads/master
2023-09-02T22:34:49.485649
2021-11-07T15:07:44
2021-11-07T15:07:44
425,535,645
0
0
null
null
null
null
UTF-8
Java
false
false
308
java
package org.lab.basic; public class Coordinate4D<T extends Number> extends Coordinate3D{ private T t; public Coordinate4D(T x, T y, T z, T t) { super(x, y, z); this.t = t; } public T getT() { return t; } public void setT(T t) { this.t = t; } }
[ "volodin.konstantin@gmail.com" ]
volodin.konstantin@gmail.com
d70525b3a9602bb7f15fb1bd1f5b424c3fd3ed68
de08da59dac5a8a047e39f6850a2ee02e084edb3
/dop-framework-core/src/main/java/com/sunvalley/framework/core/utils/Lazy.java
bceca98b929682715d67b35822171078392ab98f
[]
no_license
hanzujun/sjroom-boot
0c94b0fcd7235fac03ddc7b466a18e84df6211aa
6d42336c8330ff0a588be2dd406b96fb68d63adf
refs/heads/master
2022-03-21T12:48:52.647632
2019-12-18T03:37:03
2019-12-18T03:37:03
270,490,799
1
0
null
2020-06-08T01:50:40
2020-06-08T01:50:39
null
UTF-8
Java
false
false
1,202
java
package com.sunvalley.framework.core.utils; import org.springframework.lang.Nullable; import java.io.Serializable; import java.util.function.Supplier; /** * Holder of a value that is computed lazy. * * @author L.cm */ public class Lazy<T> implements Supplier<T>, Serializable { @Nullable private transient volatile Supplier<? extends T> supplier; @Nullable private T value; /** * Creates new instance of Lazy. * * @param supplier Supplier * @param <T> 泛型标记 * @return Lazy */ public static <T> Lazy<T> of(final Supplier<T> supplier) { return new Lazy<>(supplier); } private Lazy(final Supplier<T> supplier) { this.supplier = supplier; } /** * Returns the value. Value will be computed on first call. * * @return lazy value */ @Nullable @Override public T get() { return (supplier == null) ? value : computeValue(); } @Nullable private synchronized T computeValue() { final Supplier<? extends T> s = supplier; if (s != null) { value = s.get(); supplier = null; } return value; } }
[ "manson.zhou@sunvalley.com.cn" ]
manson.zhou@sunvalley.com.cn
fdfec16dc059f4e533490b12b3c4e0657030f279
ec0aa4cc75b6d8cc4dd48c03189d418fc1331853
/Eshwara/src/com/new12/Calculator.java
61d56d8762d1617ed8b71f3cce7d79f20ca46919
[]
no_license
Nirmithaaa/dummy
fde41f7f1ef9dcd29a0c1b07fd671766d432b3cb
78fc152ede4985fe62e140a42bed2dd1a445f474
refs/heads/master
2023-06-17T02:22:33.702256
2021-07-12T08:35:45
2021-07-12T08:35:45
385,177,597
0
0
null
null
null
null
UTF-8
Java
false
false
440
java
package com.new12; public class Calculator { public static void main(String[] args) { A a = new A(); int sum= a.add(10, 20); System.out.println(sum); int sub=a.sub(50, 100); System.out.println(sub); } } class A { public int add(int num1,int num2) { int result=num1+num2; return result; } public int sub(int num1,int num2) { int res=num1-num2; return res; } }
[ "NIRMITHA.C.B@DESKTOP-OAV7NRU" ]
NIRMITHA.C.B@DESKTOP-OAV7NRU
fd41d437e4c52323a7a00fe751028b4134588485
2ce7ba355b4eaacbf740f8e78d2736dce631d801
/app/src/main/java/com/yourannet/android/bean/TestBean.java
931d7e85c6deaefb260451cbf7eba9e72631ba0c
[ "Apache-2.0" ]
permissive
nonfuxinyang/android-study
770d27e34ce47892d8510f8cb67e8656dbe1750d
309b8f971fc26edbcbd0c9b3fde69923766e68c0
refs/heads/master
2021-07-23T20:09:46.899002
2017-11-03T00:20:09
2017-11-03T00:20:09
100,320,855
0
0
null
null
null
null
UTF-8
Java
false
false
1,115
java
package com.yourannet.android.bean; import java.io.Serializable; /** * Created by Administrator on 2017/9/5. */ @SuppressWarnings("serial") public class TestBean implements Serializable { private String username;//昵称 private String headphoto;//头像 private String content;//发布内容 private String time;//发布时间 private String images;//图片 public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getHeadphoto() { return headphoto; } public void setHeadphoto(String headphoto) { this.headphoto = headphoto; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getImages() { return images; } public void setImages(String images) { this.images = images; } }
[ "nonfuxinyang@gmail.com" ]
nonfuxinyang@gmail.com
a922d7c89ce99baa30bfebcbd21d2dab148fd11e
15e8b762b6d303a66f32724b9f66b7a3ff4a3c48
/len-web/src/main/java/test/SmsTest.java
a7b09e90e743eb384a16aee9b7321c0bcbaa416a
[ "Apache-2.0" ]
permissive
dongjinlong123/schoolitem
ee70a4b2eb43f79ba44a79b005fd388f24fedf3f
b434a2abcf2ac39808b9670cfee8bd6014694483
refs/heads/master
2022-10-19T06:43:39.097403
2019-10-28T15:26:50
2019-10-28T15:26:50
217,572,628
0
0
Apache-2.0
2022-10-12T20:33:10
2019-10-25T16:21:48
JavaScript
UTF-8
Java
false
false
4,586
java
package test; import com.len.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.MessagingException; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) @WebAppConfiguration public class SmsTest { @Autowired private JavaMailSender mailSender; @Test public void test(){ MimeMessage message = mailSender.createMimeMessage();// 新建邮件 MimeMessageHelper messageHelper = new MimeMessageHelper(message);// 编辑发送内容 try { messageHelper.setFrom("904118787@qq.com"); messageHelper.setTo("316799047@qq.com"); messageHelper.setSubject("主题"); messageHelper.setText("内容"); } catch (MessagingException e) { e.printStackTrace(); } System.out.println("发送成功"); mailSender.send(message);// 发送 } @Test public void test2() { MimeMessage message = mailSender.createMimeMessage();// 新建邮件 MimeMessageHelper messageHelper = new MimeMessageHelper(message);// 编辑发送内容 try { messageHelper.setFrom("904118787@qq.com"); messageHelper.setTo("316799047@qq.com"); messageHelper.setSubject("主题"); // 创建图片"节点" MimeBodyPart image = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("F:\\微信图片_20181009180226.jpg")); // 将图片数据添加到"节点" image.setDataHandler(dh); // 为"节点"设置一个唯一编号(在文本"节点"将引用该ID) image.setContentID("mailImgId"); // 6. 创建文本"节点" MimeBodyPart text = new MimeBodyPart(); text.setContent("这是一张图片<br/><a href='http://www.baidu.com'><img src='cid:mailImgId'/></a>", "text/html;charset=UTF-8"); // 7. (文本+图片)设置 文本 和 图片"节点"的关系(将 文本 和 图片"节点"合成一个混合"节点") MimeMultipart mm_text_image = new MimeMultipart(); mm_text_image.addBodyPart(text); mm_text_image.addBodyPart(image); mm_text_image.setSubType("related"); // 关联关系 // 8. 将 文本+图片 的混合"节点"封装成一个普通"节点" // 最终添加到邮件的 Content 是由多个 BodyPart 组成的 Multipart, 所以我们需要的是 BodyPart, // 上面的 mailImgId 并非 BodyPart, 所有要把 mm_text_image 封装成一个 BodyPart MimeBodyPart text_image = new MimeBodyPart(); text_image.setContent(mm_text_image); // 9. 创建附件"节点" MimeBodyPart attachment = new MimeBodyPart(); // 读取本地文件 DataHandler dh2 = new DataHandler(new FileDataSource("F:\\微信图片_20181009180226.jpg")); // 将附件数据添加到"节点" attachment.setDataHandler(dh2); // 设置附件的文件名(需要编码) attachment.setFileName(MimeUtility.encodeText(dh2.getName())); // 10. 设置(文本+图片)和 附件 的关系(合成一个大的混合"节点" / Multipart ) MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text_image); mm.addBodyPart(attachment); // 如果有多个附件,可以创建多个多次添加 mm.setSubType("mixed"); // 混合关系 // 11. 设置整个邮件的关系(将最终的混合"节点"作为邮件的内容添加到邮件对象) message.setContent(mm); } catch (MessagingException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } System.out.println("发送成功"); mailSender.send(message);// 发送 } }
[ "904118787@qq.com" ]
904118787@qq.com
2acf6e74cff115d6d7554169be30e7f4e4149a12
d662c9e9254935ef71843cd81df5624a7fdc8bcd
/src/test/java/com/example/auction/AuctionApplicationTests.java
9e934d35c8dc84f3a32ebbc1ac6604e9fc985129
[ "MIT" ]
permissive
jonathancodev/auction
9a1eb1582f65f3def0577c37ec1375928c93e3b4
f6e91ea17ef95978bbd6b883225c1116ea211b7c
refs/heads/main
2023-03-15T02:08:03.139414
2021-03-22T20:59:36
2021-03-22T20:59:36
350,367,410
0
0
null
null
null
null
UTF-8
Java
false
false
8,165
java
package com.example.auction; import com.example.auction.dto.BidDTO; import com.example.auction.dto.WinnerDTO; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc class AuctionApplicationTests { @Autowired private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; @Test void contextLoads() { } @Test void nullValues() throws Exception{ mockMvc.perform(post("/api/auction/find-winner") .contentType("application/json") .content("")) .andExpect(status().isBadRequest()); } @Test void emptyValues() throws Exception{ List<BidDTO> bids = new ArrayList<>(); MvcResult mvcResult = mockMvc.perform(post("/api/auction/find-winner") .contentType("application/json") .content(objectMapper.writeValueAsString(bids))) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(400, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Bids is required"); } @Test void emptyName() throws Exception{ List<BidDTO> bids = new ArrayList<>(); BidDTO bid = new BidDTO(); bids.add(bid); MvcResult mvcResult = mockMvc.perform(post("/api/auction/find-winner") .contentType("application/json") .content(objectMapper.writeValueAsString(bids))) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(400, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Name is required"); } @Test void emptyValue() throws Exception{ List<BidDTO> bids = new ArrayList<>(); BidDTO bid = new BidDTO(); bid.setName("Test"); bids.add(bid); MvcResult mvcResult = mockMvc.perform(post("/api/auction/find-winner") .contentType("application/json") .content(objectMapper.writeValueAsString(bids))) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(400, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Value is required"); } @Test void emptyValueZero() throws Exception{ List<BidDTO> bids = new ArrayList<>(); BidDTO bid = new BidDTO(); bid.setName("Test"); bid.setValue(0.0); bids.add(bid); MvcResult mvcResult = mockMvc.perform(post("/api/auction/find-winner") .contentType("application/json") .content(objectMapper.writeValueAsString(bids))) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(400, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Value is required"); } @Test void negativeValue() throws Exception{ List<BidDTO> bids = new ArrayList<>(); BidDTO bid = new BidDTO(); bid.setName("Test"); bid.setValue(-1.0); bids.add(bid); MvcResult mvcResult = mockMvc.perform(post("/api/auction/find-winner") .contentType("application/json") .content(objectMapper.writeValueAsString(bids))) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(400, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Value must be positive"); } @Test void moreThanTwoDecimalPlacesValue() throws Exception{ List<BidDTO> bids = new ArrayList<>(); BidDTO bid = new BidDTO(); bid.setName("Test"); bid.setValue(1.001); bids.add(bid); MvcResult mvcResult = mockMvc.perform(post("/api/auction/find-winner") .contentType("application/json") .content(objectMapper.writeValueAsString(bids))) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(400, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Value cannot have more than two decimal places"); } @Test void noWinner() throws Exception{ List<BidDTO> bids = new ArrayList<>(); BidDTO bid = new BidDTO(); bid.setName("Test"); bid.setValue(1.01); bids.add(bid); BidDTO bid2 = new BidDTO(); bid2.setName("Test 2"); bid2.setValue(1.01); bids.add(bid2); double total = 2*0.98; MvcResult mvcResult = mockMvc.perform(post("/api/auction/find-winner") .contentType("application/json") .content(objectMapper.writeValueAsString(bids))) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); WinnerDTO winnerDTO = objectMapper.readValue(content, WinnerDTO.class); assertEquals(winnerDTO.getMsg(), "No winner. All bids has the same value. Total: "+total); } @Test void max999Bids() throws Exception{ List<BidDTO> bids = new ArrayList<>(); double total = 999*0.98; BidDTO bid = new BidDTO(); bid.setName("Test"); bid.setValue(0.1); bids.add(bid); for(int i=0; i<1000; i++){ BidDTO bid2 = new BidDTO(); bid2.setName("Test"+i); bid2.setValue(0.2); bids.add(bid2); } MvcResult mvcResult = mockMvc.perform(post("/api/auction/find-winner") .contentType("application/json") .content(objectMapper.writeValueAsString(bids))) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); WinnerDTO winnerDTO = objectMapper.readValue(content, WinnerDTO.class); assertEquals(winnerDTO.getMsg(), "Winner: Test with the bid 0.1 and total: "+total); } @Test void rightWinner() throws Exception{ List<BidDTO> bids = new ArrayList<>(); double total = 4*0.98; BidDTO bid = new BidDTO(); bid.setName("João"); bid.setValue(0.01); bids.add(bid); bid = new BidDTO(); bid.setName("Maria"); bid.setValue(0.3); bids.add(bid); bid = new BidDTO(); bid.setName("Renata"); bid.setValue(0.01); bids.add(bid); bid = new BidDTO(); bid.setName("Pedro"); bid.setValue(12.34); bids.add(bid); MvcResult mvcResult = mockMvc.perform(post("/api/auction/find-winner") .contentType("application/json") .content(objectMapper.writeValueAsString(bids))) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); WinnerDTO winnerDTO = objectMapper.readValue(content, WinnerDTO.class); assertEquals(winnerDTO.getMsg(), "Winner: Maria with the bid 0.3 and total: "+total); } }
[ "jonathan.moreira@infosolo.com.br" ]
jonathan.moreira@infosolo.com.br
3d524a8f4ff7b349705bd5a62d268e4ace9d2d28
e5ccbab5dbd523c4073f14b023a5e928a313c96a
/app/src/main/java/com/movies/app/movies/adapters/TrailersAdapter.java
10ee72384568f05718e67fe5087d4f0c0aabf8b3
[]
no_license
snowhite185/moviesold
a20b475a2b0a2fa9f118865bdcf9a14acb34718c
73a47ec4a0d9cd0b70c422193cdb523a0ad63e04
refs/heads/master
2021-07-11T05:37:55.531626
2017-10-14T06:35:21
2017-10-14T06:35:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,260
java
package com.movies.app.movies.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.movies.app.movies.R; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by Anusha on 10/13/2017. * * Adapter class for trailer list recycler view */ public class TrailersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final String IMAGE_BASE_URL = "https://img.youtube.com/vi/%s/default.jpg"; private List<String> trailerKeys; private List<String> trailerNames; private Context context; public TrailersAdapter(Context context,List<String> trailerKeys, List<String> trailerNames) { this.trailerKeys = trailerKeys; this.trailerNames = trailerNames; this.context = context; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_trailer_list_item, parent, false); return new TrailerListVH(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { TrailerListVH trailerListVH = (TrailerListVH) holder; String key = trailerKeys.get(position); String name = trailerNames.get(position); String imageUrl = String.format(IMAGE_BASE_URL, key); trailerListVH.txtTrailerTitle.setText(name); Picasso.with(context).load(imageUrl).placeholder(R .drawable.poster_placeholder).into(trailerListVH.imgTrailer); } @Override public int getItemCount() { return trailerKeys == null ? 0 : trailerKeys.size(); } static class TrailerListVH extends RecyclerView.ViewHolder { private ImageView imgTrailer; private TextView txtTrailerTitle; TrailerListVH(View itemView) { super(itemView); imgTrailer = itemView.findViewById(R.id.imgTrailer); txtTrailerTitle = itemView.findViewById(R.id.txtTrailerTitle); } } }
[ "snowhite185@gmail.com" ]
snowhite185@gmail.com
4804c69d7f1e349295937830193a4f43bb78b0d3
0ff24eb09fcb405200da72302b8bf7497b720f5f
/app/src/androidTest/java/com/example/pcoscar/menu_v2/ExampleInstrumentedTest.java
17d54b96e8a9281ce5d14f25d1fcdb35eaa101d7
[]
no_license
oscarmendezzavaleta/menu_v2_may2018
b1ed050df262a4b87a6d8c139933a0501509afee
47191901f39697243bdbe0d4c1fa947b7b23fbfb
refs/heads/master
2020-03-17T07:53:05.338022
2018-05-20T15:30:16
2018-05-20T15:30:16
133,416,500
0
0
null
null
null
null
UTF-8
Java
false
false
738
java
package com.example.pcoscar.menu_v2; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.pcoscar.menu_v2", appContext.getPackageName()); } }
[ "oscar.mendez.zavaleta@gmail.com" ]
oscar.mendez.zavaleta@gmail.com
abee4fcec045b6b9772e08e3e1f75d21111a9fd9
29e2f682385bc22b618569cf581134f1284aa6ed
/code/Fuego/src/cn/tinder/fuego/webservice/struts/bo/receive/ReceivePlanInfoBo.java
6cf1954393985129c68354de9f85dc1b038276af
[]
no_license
TinderTeam/Fuego
2140e00b33cd10925351701aada0f2eb19f3d111
30472f24bceb7767bc36e9dcd305ef1203f42708
refs/heads/master
2020-05-28T05:30:10.544230
2014-06-11T16:00:41
2014-06-11T16:00:41
13,932,448
2
3
null
2013-11-23T16:33:04
2013-10-28T17:04:04
Java
UTF-8
Java
false
false
697
java
/** * @Title: ReceivePlanInfoBo.java * @Package cn.tinder.fuego.webservice.struts.bo.receive * @Description: TODO * @author Tang Jun * @date 2013-10-22 上午12:14:19 * @version V1.0 */ package cn.tinder.fuego.webservice.struts.bo.receive; import cn.tinder.fuego.webservice.struts.bo.assets.AssetsPageBo; /** * @ClassName: ReceivePlanInfoBo * @Description: TODO * @author Tang Jun * @date 2013-10-22 上午12:14:19 * */ public class ReceivePlanInfoBo { private AssetsPageBo assetsPage = new AssetsPageBo(); public AssetsPageBo getAssetsPage() { return assetsPage; } public void setAssetsPage(AssetsPageBo assetsPage) { this.assetsPage = assetsPage; } }
[ "mxl805@163.com" ]
mxl805@163.com
a14253c2bd6903b69f471ed2a7bb9ecb6d138f79
84a910fc5bec37503b13eca423f5872376f3af32
/src/test/java/ru/hse/dictionary/DictionaryApplicationTests.java
0c6c89afa7fb14b9d7249731e35f66345da84282
[]
no_license
VincentHawks/Dictionary
c232e822cedb64b88bfbbfaa6d3b4ea9ad42b2bd
309b6c99c25d2220df0c70c0b5ba95f954dfd05a
refs/heads/master
2021-02-08T11:33:50.361802
2020-03-03T12:32:44
2020-03-03T12:32:44
244,146,973
0
0
null
null
null
null
UTF-8
Java
false
false
222
java
package ru.hse.dictionary; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DictionaryApplicationTests { @Test void contextLoads() { } }
[ "qwertar3@gmail.com" ]
qwertar3@gmail.com
dc3181c4e741138e06761c0feb68128ff4dbd857
94c633c661d14ff4135a16578a0a9b38aa7244b8
/src/main/java/com/back/lxw/mapper/ArticleCommentaryMapper.java
9ae893706dae6682e2ea290543a3d6cc55cf385d
[]
no_license
ZzhangSamA/back_platform
16b69ae653ac35a0848bb668dc0af6a1ad75ad7f
121cb22e2562391ac164ec5c462d29cfd2b15a79
refs/heads/master
2022-12-21T13:54:33.016885
2019-07-08T03:05:24
2019-07-08T03:05:24
180,752,661
0
0
null
2022-12-16T11:06:50
2019-04-11T08:52:28
JavaScript
UTF-8
Java
false
false
1,474
java
package com.back.lxw.mapper; import com.back.lxw.pojo.ArticleCommentary; public interface ArticleCommentaryMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table article_commentary * * @mbggenerated */ int deleteByPrimaryKey(Integer commentaryId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table article_commentary * * @mbggenerated */ int insert(ArticleCommentary record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table article_commentary * * @mbggenerated */ int insertSelective(ArticleCommentary record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table article_commentary * * @mbggenerated */ ArticleCommentary selectByPrimaryKey(Integer commentaryId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table article_commentary * * @mbggenerated */ int updateByPrimaryKeySelective(ArticleCommentary record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table article_commentary * * @mbggenerated */ int updateByPrimaryKey(ArticleCommentary record); }
[ "544233188@qq.com" ]
544233188@qq.com
3dad21d18b19917586cb31f8952b71952fb0fc89
92d862cc7ac14f2304abc66edc3a5112a41c5eb5
/branches/main-release/src/ca/qc/bdeb/guillaumepoiriermorency/tp1/graphical/Interface.java
1921bf5cf512014e5401f5ceb62afeeb73de393a
[]
no_license
arteymix/tp2-guillaume-poirier-nafie-harmani
a2ac5c7811c9fd66400f8777b35f058cf2d2879b
1e3783fd7f91a5d1cb8204d5a64ca4c7da3c8feb
refs/heads/master
2021-01-10T13:55:57.538523
2011-12-13T08:05:47
2011-12-13T08:05:47
46,582,019
0
0
null
null
null
null
UTF-8
Java
false
false
28,147
java
/* This file is part of "Sauver l'univers du tentacule mauve en jouant * au Boggle!". * * "Sauver l'univers du tentacule mauve en jouant au Boggle!" is free * software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. * * "Sauver l'univers du tentacule mauve en jouant au Boggle!" 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 "Sauver l'univers du tentacule mauve en jouant au Boggle!". * If not, see <http://www.gnu.org/licenses/>. */ package ca.qc.bdeb.guillaumepoiriermorency.tp1.graphical; import ca.qc.bdeb.guillaumepoiriermorency.tp1.core.Dictionary; import ca.qc.bdeb.guillaumepoiriermorency.tp1.core.SaveFile; import ca.qc.bdeb.guillaumepoiriermorency.tp1.core.Highscores; import ca.qc.bdeb.guillaumepoiriermorency.tp1.core.Root; import ca.qc.bdeb.guillaumepoiriermorency.tp1.core.TimerMethods; import ca.qc.bdeb.guillaumepoiriermorency.tp1.translation.Translateable; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Map.Entry; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.Timer; import javax.swing.UIManager; /** * Ceci est le fichier principal du programme de jeu de Boogle : l'éternel * combat contre le tentacule mauve. Le programme est codé en anglais, mais tous * les commentaires et l'interface est construit en bon français! * @author Guillaume Poirier-Morency */ public final class Interface extends JFrame implements Translateable { /** * @param args contient les arguments en ligne de commande. * Il peut prendre les valeurs suivantes : * --highscores affiche les meilleurs scores à ce jour ; * --rules affiche les règlements de Boggle ; * --license affiche les informations sur la license de ce logiciel. */ public static void main(String[] args) { if (args.length == 0) { } else if (args[0].equals("--highscores")) { // Ne montrer que les meilleurs scores et quitter Highscores hs = Highscores.unSerialize(); String messageToRender = ""; for (Entry e : Highscores.unSerialize().entrySet()) { messageToRender += e.getKey() + " : " + e.getValue() + "\n"; } JOptionPane.showMessageDialog(null, (messageToRender.equals("") ? "Aucuns scores trouvés!" : ""), messageToRender, (messageToRender.equals("") ? JOptionPane.WARNING_MESSAGE : JOptionPane.INFORMATION_MESSAGE)); System.exit(0); } else if (args[0].equals("--license")) { JOptionPane.showMessageDialog(null, "Sauver [...] est un logiciel libre" + "\n\nCe logiciel distribué sous license GPLv3" + "\nVous trouverez plus amples informations" + "\nsur <http://www.gnu.org/licenses/> ainsi" + "\nqu'une copie numérique de la GPLv3dans " + "\nles sources de ce logiciel." + "\n\nCréé par Guillaume Poirier-Morency." + "\nRemis le : ", "À propos", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } else if (args[0].equals("--rules")) { JOptionPane.showMessageDialog(null, "Les règles du jeu sont simples :" + "\n\n Formez des mots de 3 lettres ou plus à l'aide" + "\n des cubes du jeu. Les lettres doivent être " + "\n adjacente et utilisées une seule fois. Un mot ne" + "\n peut pas être formé plus d'une fois et plus long ils" + "\n seront, plus de points vous ammasserez." + "\n\n 3 ou 4 lettres : 1 point" + "\n 5 lettres : 2 points" + "\n 6 lettres : 3 points" + "\n 7 lettres : 5 points" + "\n 8 lettres et plus : 11 points", "Règles du jeu", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } else { JOptionPane.showMessageDialog(null, "Please check your argument spelling :" + "\n--highscores shows highscores then quit ;" + "\n--license shows license details then quit ;" + "\n--rules shows rules then quit.", "À propos", JOptionPane.ERROR_MESSAGE); System.exit(0); } try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); if (JOptionPane.showOptionDialog(null, "Il existe des problèmes avec l'implémentation" + "\nde GTK dans java, voulez-vous utiliser un autre look?", "Problème de compatibilité de l'interface", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null) == 0) { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } } catch (Exception e) { e.printStackTrace(); try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e1) { e1.printStackTrace(); System.out.println("Le look dégeulasse de Swing sera utilisé."); } } new Interface(4, 4); } //<editor-fold defaultstate="collapsed" desc="Variables"> /** * Couleur de l'interface. */ public Color colorInterface; /** * Dimension en y de la grille de Boggle. */ /** * Dimension en x de la grille de Boggle */ public final int HEIGH, LENGTH; // TODO Jeu de test sur ces variables /** * Bouton de vérification. */ private JButton btnVerify = new JButton("Vérifier"); /** * Timer ppur le temps restant. */ private Timer timerRemainingTime; /** * Référence de la table de Boggle en utilisation. */ public BoggleGrid pnlBoggleGrid; private JScrollPane jspFoundWords = new JScrollPane(); private DefaultListModel dlmFoundWords = new DefaultListModel(); /** * Liste des mots trouvés. */ public JList listFoundWords = new JList(dlmFoundWords); /** * Panel EAST contenant la liste de mots trouvé, le buffer de réponse et le temps restant. */ /** * Panel contenant le pointage. */ /** * Panel contenant les boutons de vérification et d'annulation. */ private JPanel pnlEastBorder = new JPanel(new BorderLayout()), pnlStatusBar = new JPanel(), pnlNorthBorder = new JPanel(); /** * Position du dernier cube cliqué. */ public int lastClickedCubeNumber = -1; // TODO Jeu de test sur cette variable /** * Minuteur pour le temps restant. */ /** * Label pour afficher les points. */ public JLabel lblTimer = new JLabel("3 minutes 0 secondes"), // TODO Jeu de test sur ces variables lblPoints = new JLabel("0"); /** * Buffer pour les réponses. */ private JLabel lblAnswerBuffer = new JLabel(""); // TODO Jeu de test sur cette variable private JMenuBar menuBarMainMenu = new JMenuBar(); private JMenu menuFile = new JMenu("Fichier"), menuHelp = new JMenu("Aide"); /** * Composantes des menus */ private JMenuItem menuItemSave = new JMenuItem("Sauvegarder"), menuItemQuit = new JMenuItem("Quitter"), menuItemNewGame = new JMenuItem("Nouvelle partie..."), menuItemRules = new JMenuItem("Règlements..."), menuItemAbout = new JMenuItem("À propos de..."), menuItemLoad = new JMenuItem("Charger la derniere partie..."), menuItemHighscores = new JMenuItem("Meilleurs scores..."), menuItemParameters = new JMenuItem("Paramètres..."), menuItemPause = new JMenuItem("Pause..."); /** * Bouton pour annuler la sélection. */ private JButton btnCancel; /** * Variable contenant la version du jeu. */ private final double VERSION = 1.0; /** * JFrame de paramètres pour changer la couleur et la langue. */ private Parameters parameters = new Parameters(this); /** * Dictionnaire de mots. */ private Dictionary dictionnary = new Dictionary(); /** * Highscores, pour les meilleurs! */ private Highscores highscores = Highscores.unSerialize(); //</editor-fold> /** * Permet de transférer l'interface en référence pour les ActionListener. * @return l'interface actuel. */ private Interface getInterface() { return this; } /** * Instancie un interface de Boggle. * @param heigh est la hauteur de la grille. * @param length est la longeur de la grille. */ private Interface(int heigh, int length) { super(); HEIGH = heigh; LENGTH = length; pnlBoggleGrid = new BoggleGrid(HEIGH, LENGTH, lblAnswerBuffer, this); generalInterfaceCalls(); } /** * Génère une partie à partir d'un fichier de configuration. * @param sf est le fichier de configuration en question. */ private Interface(SaveFile sf) { super(); HEIGH = sf.HEIGH; LENGTH = sf.LENGTH; lblTimer = new JLabel(sf.REMAINING_TIME); listFoundWords = sf.FOUND_WORD_LIST; lblPoints.setText(sf.POINTS); pnlBoggleGrid = sf.GRID; lastClickedCubeNumber = sf.LAST_CLICKED_CUBE_NUMBER; generalInterfaceCalls(); // On rajoute la référence du JFrame dans les composantes for (Component c : sf.GRID.getComponents()) { ((Cube) c).setAnswerBuffer(this, lblAnswerBuffer); } setGameColor(sf.COLOR); } /** * Détruit tout forme de sélection dans la grille. */ private void cleanGrid() { lblAnswerBuffer.setText(""); lastClickedCubeNumber = -1; for (int i = 0; i < pnlBoggleGrid.HEIGH * pnlBoggleGrid.LENGTH; i++) { pnlBoggleGrid.getComponent(i).setEnabled(true); } } /** * Regroupe les appels généraux pour créer l'interface. */ private void generalInterfaceCalls() { //<editor-fold defaultstate="collapsed" desc="Le AnswerBuffer est défini ici."> lblAnswerBuffer.setHorizontalAlignment(JLabel.CENTER); lblAnswerBuffer.setPreferredSize(new Dimension(200, 25)); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Le panel EAST du JFrame est défini ici."> jspFoundWords.add(listFoundWords); pnlEastBorder.add(jspFoundWords, BorderLayout.NORTH); pnlEastBorder.add(lblTimer, BorderLayout.CENTER); pnlEastBorder.add(lblAnswerBuffer, BorderLayout.SOUTH); //</editor-fold> /* On rajoute la table de Boggle à l'interface. Pour simplifier son * accès, on lui définit une référence locale. */ //<editor-fold defaultstate="collapsed" desc="Les composants du JFrame sont ajoutés ici"> add(pnlBoggleGrid, BorderLayout.CENTER); // La liste de mots trouvés est générée ici lblTimer.setHorizontalAlignment(JLabel.CENTER); add(pnlEastBorder, BorderLayout.EAST); pnlNorthBorder.add(btnVerify); btnCancel = new JButton("Annuler la sélection"); pnlNorthBorder.add(btnCancel); // Le bouton de vérification est ajouté ici add(pnlNorthBorder, BorderLayout.NORTH); pack(); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="L'Action Listener du bouton de vérification est défini ici"> btnVerify.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { /* On envoit à la classe spécialisée en vérification de réponse * la réponse de l'utilisateur et cette dernière devrait être * en mesure de la vérifier à partir d'un dictionnaire. */ int i; if ((i = Root.checkAnAnswer(dictionnary, lblAnswerBuffer.getText(), dlmFoundWords)) > 0) { dlmFoundWords.add(listFoundWords.getModel().getSize(), lblAnswerBuffer.getText() + " " + i + " points"); lblPoints.setText("" + (Integer.parseInt(lblPoints.getText()) + i)); } cleanGrid(); } }); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Le bouton Annuler est defini ici"> btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { cleanGrid(); } }); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="La barre de status est définie ici"> pnlStatusBar.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); pnlStatusBar.add(new JLabel("Points")); pnlStatusBar.add(lblPoints); add(pnlStatusBar, BorderLayout.SOUTH); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="La barre de menus est définie ici"> menuItemSave.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { SaveFile i = new SaveFile(getInterface()); // On mets le Timer en pause pendant la sauvegarde... timerRemainingTime.stop(); Thread threadMessageWhileSaving = new Thread() { @Override public void run() { setVisible(false); JOptionPane.showMessageDialog(null, "Sauvegarde en cours...", "Sauvegarde", JOptionPane.INFORMATION_MESSAGE); setVisible(true); timerRemainingTime.start(); } }; threadMessageWhileSaving.start(); i.serialize("save.serial"); } }); menuItemPause.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { timerRemainingTime.stop(); setVisible(false); JOptionPane.showMessageDialog(null, "Le jeu est en pause...", "Pause", JOptionPane.INFORMATION_MESSAGE); setVisible(true); timerRemainingTime.start(); } }); menuItemRules.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { setVisible(false); timerRemainingTime.stop(); JOptionPane.showMessageDialog(null, "Les règles du jeu sont simples :" + "\n\n Formez des mots de 3 lettres ou plus à l'aide" + "\n des cubes du jeu. Les lettres doivent être " + "\n adjacente et utilisées une seule fois. Un mot ne" + "\n peut pas être formé plus d'une fois et plus long ils" + "\n seront, plus de points vous ammasserez." + "\n\n 3 ou 4 lettres : 1 point" + "\n 5 lettres : 2 points" + "\n 6 lettres : 3 points" + "\n 7 lettres : 5 points" + "\n 8 lettres et plus : 11 points", "Règles du jeu", JOptionPane.INFORMATION_MESSAGE); setVisible(true); timerRemainingTime.start(); } }); menuItemLoad.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { generalCallsWhenNewGameIsAsked(4, 4, SaveFile.unSerialize("save.serial")); timerRemainingTime.stop(); } catch (Exception e) { timerRemainingTime.stop(); setVisible(false); JOptionPane.showMessageDialog(null, "La dernière partie sauvegardé n'a pas pu être trouvée!", "Problème de sauvegarde", JOptionPane.ERROR_MESSAGE); setVisible(true); timerRemainingTime.start(); } } }); menuItemQuit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { gameEnded(); } }); menuItemNewGame.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { /* TODO Rendre invisible les fenetres inactives peut nuire a la * gestion de la memoire. On devrait detruire les ancienne * fenetres. En reinstanciant une nouvelle fenetre, on lui * accorde les privileges de EXIT_ON_CLOSE tandis que la fenetre * courrante sera reduite a HIDE_ON_CLOSE. */ timerRemainingTime.stop(); if (JOptionPane.showOptionDialog(null, "Voulez-vous vraiment recommencer une nouvelle partie?", "Sauvegarder la partie", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null) == 1) { // On fait pas grand chose mais la structure est présente au besoin. timerRemainingTime.start(); } else { // Le timer reste stoppé!! generalCallsWhenNewGameIsAsked(4, 4, null); } } }); menuItemHighscores.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { setVisible(false); timerRemainingTime.stop(); String messageToRender = ""; for (Entry e : Highscores.unSerialize().entrySet()) { messageToRender += e.getKey() + " : " + e.getValue() + "\n"; } JOptionPane.showMessageDialog(null, (messageToRender == "" ? "Aucuns scores trouvés!" : messageToRender),"Meilleurs scores" , (messageToRender.equals("") ? JOptionPane.WARNING_MESSAGE : JOptionPane.INFORMATION_MESSAGE)); setVisible(true); timerRemainingTime.start(); } }); menuItemAbout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { setVisible(false); timerRemainingTime.stop(); JOptionPane.showMessageDialog(null, "Sauver [...] est un logiciel libre" + "\n\nCe logiciel distribué sous license GPLv3" + "\nVous trouverez plus amples informations" + "\nsur <http://www.gnu.org/licenses/> ainsi" + "\nqu'une copie numérique de la GPLv3dans " + "\nles sources de ce logiciel." + "\n\nCréé par Guillaume Poirier-Morency." + "\nRemis le : ", "À propos", JOptionPane.INFORMATION_MESSAGE); setVisible(true); timerRemainingTime.start(); } }); menuItemParameters.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { // TODO Jeu indisonible quand l'utilisateur chance ses pref parameters.setVisible(true); } }); menuFile.add(menuItemNewGame); menuFile.add(menuItemSave); menuFile.add(menuItemLoad); menuFile.addSeparator(); menuFile.add(menuItemPause); menuFile.add(menuItemHighscores); menuFile.add(menuItemParameters); menuFile.addSeparator(); menuFile.add(menuItemQuit); menuHelp.add(menuItemRules); menuHelp.add(menuItemAbout); menuBarMainMenu.add(menuFile); menuBarMainMenu.add(menuHelp); setJMenuBar(menuBarMainMenu); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Les dimensions sont définies ici avec un .pack()"> setPreferredSize(new Dimension(710, 600)); listFoundWords.setSize(new Dimension(200, 425)); jspFoundWords.setPreferredSize(new Dimension(200, 425)); pnlEastBorder.setPreferredSize(new Dimension(200, 500)); lblTimer.setPreferredSize(new Dimension(200, 25)); pack(); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Les propriétés du JFrame sont définies ici"> setResizable(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Sauver l'univers du tentacule mauve en jouant au Boggle! " + VERSION); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Ce code à été pris sur le site : http://www.java-forums.org/awt-swing/3491-jframe-center-screen.html"> // Get the size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Determine the new location of the window int w = getSize().width; int h = getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; // Move the window setLocation(x, y); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Le timer est défini ici"> timerRemainingTime = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { int toFormat = TimerMethods.convertTimeToInteger(lblTimer.getText()); if (toFormat > 0) { lblTimer.setText(TimerMethods.convertIntegerToTime(toFormat - 1)); } else { gameEnded(); } } }); timerRemainingTime.start(); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Le window manager est défini ici."> this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { gameEnded(); } }); //</editor-fold> this.setResizable(false); this.setVisible(true); } /** * Méthode appelée lorsque le jeu doit être éteint. */ private void gameEnded() { timerRemainingTime.stop(); String name = null; if (Integer.parseInt(this.lblPoints.getText()) > 0) { name = JOptionPane.showInputDialog(null, "La partie est finie! Vous avez fait " + this.lblPoints.getText() + " points!" + "\nVeuillez entrer votre nom :", "Partie terminée", JOptionPane.INFORMATION_MESSAGE); } if (name != null) { highscores.addScore(name, Integer.parseInt(this.lblPoints.getText())); highscores.serialize(); } if (dictionnary.isNewWords() && JOptionPane.showOptionDialog(null, "Voulez-vous sauvegarder le dictionnaire?", "Sauvegarder le dictionnaire", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null) == 0) { // De nouveaux mots ont été ajouté, on propose une sauvegarde... dictionnary.save(); } if (Integer.parseInt(this.lblPoints.getText()) > 0) { Highscores hs = Highscores.unSerialize(); hs.addScore(name, Integer.parseInt(this.lblPoints.getText())); hs.serialize(); } if (JOptionPane.showOptionDialog(null, "Voulez-vous rejouer?", "Rejouer", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null) == 0) { generalCallsWhenNewGameIsAsked(4, 4, null); } else { System.exit(0); } } /** * Change la couleur de l'interface. * @param color est la couleur voulue. */ void setGameColor(Color color) { colorInterface = color; pnlEastBorder.setBackground(color); pnlStatusBar.setBackground(color); pnlNorthBorder.setBackground(color); pnlBoggleGrid.setBackground(color); btnVerify.setBackground(color); btnCancel.setBackground(color); } /** * Appels de méthodes lorsqu'une nouvelle partie doit être générée. * @param length est la longeur de la nouvelle grille. * @param heigh est la hauteur de la nouvell grille. * @param s est le fichier de sauvegarde au besoin, mettre null si aucuns. */ private void generalCallsWhenNewGameIsAsked(int length, int heigh, SaveFile s) { setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); this.setVisible(false); // On nettoye les objets en mémoire... colorInterface = null; btnVerify = null; timerRemainingTime = null; pnlBoggleGrid = null; dlmFoundWords = null; listFoundWords = null; pnlEastBorder = null; pnlStatusBar = null; pnlNorthBorder = null; lblTimer = null; lblPoints = null; lblAnswerBuffer = null; menuBarMainMenu = null; menuFile = null; menuHelp = null; menuItemSave = null; menuItemQuit = null; menuItemNewGame = null; menuItemRules = null; menuItemAbout = null; menuItemLoad = null; menuItemHighscores = null; menuItemParameters = null; menuItemPause = null; btnCancel = null; parameters = null; dictionnary = null; highscores = null; // On appelle le garebage collector, anyway c'est en train de loader! // TODO Fixer les exceptions de NullPointer.. ou on s'en fout, l'objet est inutile... new Thread() { @Override public void run() { System.gc(); } }.start(); if (s == null) { new Interface(length, heigh); } else { new Interface(s); } } @Override public String[] getLocalStringToTranslate() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Translateable[] getTranslateableObjects() { Translateable[] t = {pnlBoggleGrid, parameters}; throw new UnsupportedOperationException("Not supported yet."); } @Override public void translate(String[] s) { throw new UnsupportedOperationException("Not supported yet."); } }
[ "guillaumepoiriermorency@gmail.com" ]
guillaumepoiriermorency@gmail.com
7aefc9d2418b8b2f4770e971ecff9394f838db00
28c14798300acc596b8b12f4d04167f2107a67ad
/app/src/main/java/com/news/news/ui/aljajeera/GalleryViewModel.java
7f585e511f260c18ce47b12d649398ace11d035f
[]
no_license
guptaankit18598/NewsApp-using-Navigation-Drawer
f3cb885ec869c20fbbbbbdcb2cc1cf45b7e5713e
545d001d4d346de34eae7137aee04ed4448821d7
refs/heads/master
2023-04-20T05:29:37.519448
2021-05-16T12:53:51
2021-05-16T12:53:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
453
java
package com.news.news.ui.aljajeera; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class GalleryViewModel extends ViewModel { private MutableLiveData<String> mText; public GalleryViewModel() { mText = new MutableLiveData<>(); mText.setValue("This is Al Jajeera fragment"); } public LiveData<String> getText() { return mText; } }
[ "guptankit18598@gmail.com" ]
guptankit18598@gmail.com
d9722c2621064a02b555f1148fc848fe9f77db9a
bf3e8f3b1f2054aac46807bc23bfa775e46e48af
/代码众筹spring—cloud/atcrowdfunding-boot-act-service/src/main/java/com/atguigu/crowdfunding/listener/RefuseListener.java
c097b90a0dba759bae065ce7652b56e3f7d8f480
[]
no_license
jianghuxiaoxiaoyu/MyCode
371ed6b898a8f244ac941742b54f78bfdc28471c
24d736f9de1060d1e265a20667163495e052bf7f
refs/heads/master
2021-01-25T13:28:29.668775
2018-03-02T16:39:13
2018-03-02T16:39:13
123,573,759
0
0
null
null
null
null
UTF-8
Java
false
false
347
java
package com.atguigu.crowdfunding.listener; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.ExecutionListener; public class RefuseListener implements ExecutionListener { @Override public void notify(DelegateExecution execution) throws Exception { System.out.println("RefuseListener..."); } }
[ "1130497883@qq.com" ]
1130497883@qq.com
4092154dcca15aef79fcba7d010709a2c4a60eb1
c7ff844a2ac95501e38a65d2a5b1c674d20f650c
/ashigel-compiler/src/main/java/com/asakusafw/compiler/flow/epilogue/parallel/ResolvedSlot.java
45315848781e204e8b954c22a36d3c4a907e5412
[ "Apache-2.0" ]
permissive
tottokomakotaro/asakusafw
3a16cf125302169fecb9aec5df2c8a387663415c
fd237fc270165eeda831d33f984451b684d5356f
refs/heads/master
2021-01-18T05:34:48.764909
2011-07-28T05:48:55
2011-07-28T05:49:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,848
java
/** * Copyright 2011 Asakusa Framework Team. * * 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.asakusafw.compiler.flow.epilogue.parallel; import java.util.List; import com.asakusafw.compiler.common.Precondition; import com.asakusafw.compiler.flow.DataClass; import com.asakusafw.compiler.flow.DataClass.Property; /** * 型に関連する情報を解決したスロット。 */ public class ResolvedSlot { private Slot source; private int slotNumber; private DataClass valueClass; private List<Property> sortProperties; /** * インスタンスを生成する。 * @param source コンパイルしたソース * @param slotNumber このスロットのスロット番号 * @param valueClass スロットの値を表すクラス * @param sortProperties スロットのソート順序に関連するプロパティ一覧 * @throws IllegalArgumentException 引数に{@code null}が指定された場合 */ public ResolvedSlot(Slot source, int slotNumber, DataClass valueClass, List<Property> sortProperties) { Precondition.checkMustNotBeNull(source, "source"); //$NON-NLS-1$ Precondition.checkMustNotBeNull(valueClass, "valueClass"); //$NON-NLS-1$ Precondition.checkMustNotBeNull(sortProperties, "sortProperties"); //$NON-NLS-1$ this.source = source; this.slotNumber = slotNumber; this.valueClass = valueClass; this.sortProperties = sortProperties; } /** * コンパイルしたソースを返す。 * @return コンパイルしたソース */ public Slot getSource() { return source; } /** * このスロットのスロット番号を返す。 * @return このスロットのスロット番号 */ public int getSlotNumber() { return slotNumber; } /** * スロットの値を表すクラスを返す。 * @return スロットの値を表すクラス */ public DataClass getValueClass() { return valueClass; } /** * スロットのソート順序に関連するプロパティ一覧を返す。 * @return スロットのソート順序に関連するプロパティ一覧 */ public List<DataClass.Property> getSortProperties() { return sortProperties; } }
[ "akirakw@gmail.com" ]
akirakw@gmail.com
10316d19255f45cd8d17cba3a7c7d576e52988a8
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/15/15_5ac5447456035bc650951f760cc95684076fbbd7/ClaferOptimizer/15_5ac5447456035bc650951f760cc95684076fbbd7_ClaferOptimizer_t.java
cfab5cb95cb0d8e92ed3398b9d1d7b80868aed90
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
5,614
java
package org.clafer.compiler; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.clafer.collection.Either; import org.clafer.collection.Pair; import org.clafer.common.Check; import org.clafer.instance.InstanceModel; import solver.ResolutionPolicy; import solver.Solver; import solver.constraints.ICF; import solver.exception.ContradictionException; import solver.objective.IntObjectiveManager; import solver.propagation.NoPropagationEngine; import solver.propagation.hardcoded.SevenQueuesPropagatorEngine; import solver.search.loop.monitors.IMonitorSolution; import solver.search.solution.Solution; import solver.variables.IntVar; import solver.variables.SetVar; import solver.variables.Variable; /** * * @author jimmy */ public class ClaferOptimizer implements ClaferSearch<Pair<Integer, InstanceModel>> { public final Solver solver; private final ClaferSolutionMap solutionMap; private final boolean maximize; private final Either<Integer, IntVar> score; private boolean first = true; private boolean more = true; private boolean second = true; private final Solution firstSolution = new Solution(); ClaferOptimizer(Solver solver, ClaferSolutionMap solutionMap, boolean maximize, Either<Integer, IntVar> score) { this.solver = Check.notNull(solver); this.solutionMap = Check.notNull(solutionMap); this.maximize = maximize; this.score = Check.notNull(score); } public ClaferSolutionMap getSolutionMap() { return solutionMap; } public boolean isMaximize() { return maximize; } public boolean isMinimize() { return !maximize; } @Override public boolean find() { if (!more) { return false; } if (first) { more &= solveFirst(); first = false; return more; } more &= solveNext(); return more; } /* * Implementation of multiple optimal search based on discussion here: * https://github.com/chocoteam/choco3/issues/121. */ private boolean solveFirst() { if (score.isLeft()) { return solver.findSolution(); } IntVar scoreVar = score.getRight(); solver.getSearchLoop().setObjectivemanager(new IntObjectiveManager( scoreVar, maximize ? ResolutionPolicy.MAXIMIZE : ResolutionPolicy.MINIMIZE, solver)); solver.getSearchLoop().plugSearchMonitor(new IMonitorSolution() { private static final long serialVersionUID = 1L; @Override public void onSolution() { if (first) { firstSolution.record(solver); } } }); if (solver.getEngine() == NoPropagationEngine.SINGLETON) { solver.set(new SevenQueuesPropagatorEngine(solver)); } solver.getSearchLoop().getMeasures().setReadingTimeCount(System.nanoTime()); solver.getSearchLoop().launch(false); if (!firstSolution.hasBeenFound()) { return false; } try { firstSolution.restore(); } catch (ContradictionException e) { // Should never happen because the solution should not be contradictory. throw new IllegalStateException(e); } return true; } private boolean solveNext() { if (score.isLeft() || !second) { return solver.nextSolution(); } second = false; IntVar scoreVar = score.getRight(); int best = scoreVar.getValue(); // TODO: forbid the current solution from happening again. solver.getEngine().flush(); solver.getSearchLoop().reset(); solver.post(ICF.arithm(scoreVar, "=", best)); boolean next = solver.findSolution(); return next && duplicateSolution() ? solver.nextSolution() : next; } private boolean duplicateSolution() { for (IntVar var : solutionMap.getIrSolution().getIntVars()) { if ((var.getTypeAndKind() & Variable.CSTE) == 0) { if (var.getValue() != firstSolution.getIntVal(var)) { return false; } } } for (SetVar var : solutionMap.getIrSolution().getSetVars()) { if ((var.getTypeAndKind() & Variable.CSTE) == 0) { if (!Arrays.equals(var.getValue(), firstSolution.getSetVal(var))) { return false; } } } return true; } /** * @return the optimal value and the optimal instance */ @Override public Pair<Integer, InstanceModel> instance() { return new Pair<>( score.isLeft() ? score.getLeft() : score.getRight().getValue(), solutionMap.getInstance()); } @Override public Pair<Integer, InstanceModel>[] allInstances() { List<Pair<Integer, InstanceModel>> instances = new ArrayList<>(); while (find()) { instances.add(instance()); } @SuppressWarnings("unchecked") Pair<Integer, InstanceModel>[] pairs = new Pair[instances.size()]; return instances.toArray(pairs); } @Override public Solver getInternalSolver() { return solver; } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com